diff --git a/docs/reports/2026-11-16-phase3-report.md b/docs/reports/2026-11-16-phase3-report.md new file mode 100644 index 0000000..36d1124 --- /dev/null +++ b/docs/reports/2026-11-16-phase3-report.md @@ -0,0 +1,159 @@ +# Pure-Java AST: phase 3 report + +## Summary + +Phase 3 ported FitsChan writing and the FITS encodings other than FITS-WCS on 15 and 16 November 2026, following the plan [`2026-11-15-pure-java-ast-phase3-fitschan-write.md`](../superpowers/plans/2026-11-15-pure-java-ast-phase3-fitschan-write.md). +`FitsChan.write()` now writes FrameSets of this library's classes as FITS-WCS (with SIP distortion), NATIVE, FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and DSS cards, and refuses FITS-CLASS as C does; `FitsChan.read()` now reads FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and DSS. +Of the 194 rows of C's FITS conversion regression table (`ast_tester/fixtures/wcsconv/cases.txt`), 118 now give C's cards, in C's order with C's comments and numbers within 4 units in the last place; at the start of the phase none did, since every row writes cards. +Every one of the other 76 needs a class outside this library: SpecFrame (63), the FITS-CLASS read (6), DSBSpecFrame (4), MathMap (2) or SplineMap (1). +19 more headers of the transform oracle now read and transform as C's do, and six C-probe oracle suites of the Rust port were converted and pass. +Porting found about 20 places where C reads or writes memory it does not own, dereferences a null pointer or recurses without end; they are recorded in [`docs/rust-c-differences.md`](../rust-c-differences.md), and listed below. +The work added 8,441 lines of main code and 8,838 lines of tests; `mvn verify` passes with 2,829 tests on JDK 21, and the tests pass on the JDK 27 runtime. + +## What was ported + +| Task | What | Main lines | Test lines | +| --- | --- | ---: | ---: | +| 1 | The write entry (`FitsChan.write`, C's `Write` with `FixNew`) and the NATIVE encoding (`FitsNativeWriter`) | 477 | 698 | +| 2 | Intermediate world coordinates and linear axes (`FitsMakeIntWorld`, `FitsIsMapLinear`, `FitsWorldAxes`, `FitsInvertable`, `FitsOrth`, `FitsWcsDecompose`) | 1,329 | 693 | +| 5 | The SIP building blocks (`FitsSipIntWorld`, `AnalysePoly`, `ScalePolyInputs`, PolyMap's `MergeShift`) | 1,086 | 611 | +| 3 | Celestial axes (`FitsCelestialAxes`, `FitsSkySys`, `FitsSkyPole`, `FitsFiducial.getFiducialWcs`, `FitsMapTab`) | 1,546 | 1,255 | +| 4 | FrameSet to store (`FitsFsetToStore`, `FitsPlaneStores`, `FitsOtherAxes`) | 898 | 883 | +| 6 | Writing FITS-WCS (`FitsWcsWrite`, `FitsFromStore`, C's `FindWcs` templates and `SetValue` comment rules) and the C-probe oracle suites | 710 | 1,593 | +| 7 | FITS-PC and FITS-IRAF (`FitsEncPc`, `FitsEncIraf`, their `SpecTrans` translations) | 728 | 711 | +| 8 | FITS-AIPS and FITS-AIPS++ (`FitsEncAips`) | 739 | 622 | +| 9 | DSS (`FitsEncDss`) and the FITS-CLASS refusal (`FitsEncClass`) | 825 | 760 | +| 10 | The remaining Rust write tests; no main code changed | 0 | 786 | +| 11 | Sweep of the deferred lists: nothing left to change | 0 | 0 | +| 12 | This report | | | + +Main lines are lines added to `src/main`; 203 lines were removed over the phase. +Task 5 ran before Task 3: MakeIntWorld calls SIPIntWorld whenever SipOK is set, which is its default, so every celestial test of Tasks 3 and 4 needed it. +Each of Tasks 1 to 10 was done by one implementer subagent and verified in the controlling session before it was recorded (the full test suite, the deferred lists changing only by removal or by a more specific class reason, and the C source for each finding); Tasks 3 and 8 needed one fix round each. +From Task 4 on, expected values that no fixture held were taken from probes run against the pinned C library, built without floating-point contraction; the probe sources were kept with the execution record. +The tasks were committed between 22:34 on 15 November and 02:49 on 16 November. + +## Departures from the plan + +The [rulings](2026-11-16-phase3-rulings.md) give each with its reason and cost; these change what later work builds on. + +- **C's signatures.** + Where the plan guessed a signature (`makeIntWorld` returning a MatrixMap, `fsetToStore` returning a boolean, `celestialAxes` returning a boolean), the port takes C's arguments and results: `makeIntWorld` needs C's FitsTol and an encoding-dependent SipOK, `fsetToStore` returns the store, and `celestialAxes` returns the Mapping from world to intermediate world coordinates. +- **The store indexed by version letter.** + C writes alternate descriptions in letter order and merges two descriptions given one letter, so the store is a `FitsPlaneStores` of one `FitsStore` per letter (the plan's design item 7). +- **No SIP orders in the store.** + C stores SIP coefficients only, and `WcsFromStore` finds each order as it writes the cards; Java does the same. +- **Where the cards go.** + The plan's Review Focus item 4 put new cards before the card current when the write began; C puts them after the last card that describes WCS (`FindWcs`), or at the end when there is none, and the test asserts C's placement. +- **The `-TAB` decision.** + C decides whether an axis can be a table with classes this library has (separability and a known dimension) before it needs a FitsTable; that decision is ported (`FitsMapTab`), and only a write C would describe with `-TAB` throws `needs FitsTable`. +- **A write that throws has its new cards removed.** + C leaves the cards a write added when the write fails with an error, because its clean-up does nothing once the error status is set; Java removes them, as the Rust port does. + As in C, a card that the write replaced before failing is not brought back. + +## Gates + +| Gate | Before | After | +| --- | --- | --- | +| `wcsconv/cases.txt` rows giving C's cards | 0 of 194 | 118 of 194 | +| `wcsconv` rows by encoding (matching / total) | | NATIVE 66/107, FITS-WCS 17/26, FITS-AIPS 11/17, FITS-AIPS++ 12/18, FITS-IRAF 6/9, FITS-PC 4/5, DSS 1/1, AST 1/2, FITS-CLASS 0/9 | +| `wcsconv` rows deferred as `out-of-scope method FitsChan.write` | 134 | 0 | +| `wcsconv` rows deferred for an encoding | 28 | 6 (all reading FITS-CLASS) | +| `headers.txt` entries (transform oracle) | 70 | 51: SpecFrame 45, FITS-CLASS 4, MathMap 2 | +| `rust-tests.txt` entries | 399 | 376, after adding 13 entries for two Rust test files the list had missed | +| `FitsChanCursorOracleTest` cases run | 147 | 247 | +| `TranGridOracleTest` grids run | 14 | 19 | +| Tests | 2,467 | 2,829 | + +New C-probe oracle suites, converted from the Rust port's `cases.rs` with `CasesToJson`: `FitsChanEncodingsOracleTest` (every encoding column), `FitsChanSipokOracleTest`, `FitsChanSplitmapOracleTest`, `FitsChanAltNaxesOracleTest` and `FitsChanAltEpochOracleTest`, and the write cases of `SkyPoleOracleTest`; cases needing an absent class are listed in each and checked both ways. +`FitsChanWriteTest` holds the Review Focus tests: a failed or Strict write leaves the cards, their order and the current card as they were, except that a card the write replaced before failing is lost, as in C; cards go where C puts them; every in-scope header of the transform oracle, read and written in each encoding that accepts it, reads back to transform as C's own round trip does (where C's round trip fails or differs, the test expects that); four threads writing copies of one FrameSet give identical cards. + +The native dumps that phase 2 reported as differing from C in the last bits without a known cause (`skyref`, `skyref-alt`, `tidy-pole`, `azel`) now give C's cards within 4 units in the last place. + +## Tolerances and excuses + +Removed: the `tan` grids of `TranGridOracleTest`, unrun since phase 1 (now run, see below). +Added; each runtime-Math entry was traced, with a debugger on C and replays in C and Java, to an elementary function returning a different last bit for identical argument bits, with every other intermediate value identical: + +| Where | What | Measured size and cause | +| --- | --- | --- | +| C-probe oracle suites | Cards compared within 4 ULP, as the `wcsconv` gate, rather than byte for byte; `FitsChanSipokOracleTest` stays exact | Java's `Math` against macOS libm | +| `FitsChanSplitmapOracleTest` `linear`, `linear_3d` | CDELT2 within 1e-13 relative | 5 ULP: `Math.cos(2π − 0.2)` 1 ULP from libm, amplified by `FitLine`'s least squares | +| `FitsChanEncodingsOracleTest` offset-SkyRef cases | PC elements within 1e-13 relative | about 1e-16: identical MatrixMaps, `atan2` 1 ULP apart | +| `FitsChanEncodingsOracleTest` DSS cases (7) | PLTRAS and PLTDECS within the effect of 4 ULP of CRVAL | CRVAL 1 to 2 ULP from C through `atan2` (forward SphMap, and `eraC2s` in `eraFk5hz` with Epoch set); the keywords hold 3600 times CRVAL's fractional part | +| `TranGridOracleTest` `tan` grids (5) | Sampled positions within `ulp(π/2)`; the bit-for-bit hash not checked for them | at most 2.2e-16 rad: `atan2`, `sin` and `cos` 1 ULP apart in 472 of 682 pixels, at identical arguments | +| `FitsChanCursorOracleTest` `alt_axes_offset{,_none}` | CDELT2 and CDELT2A within 1e-14 relative | 1 ULP, runtime Math | +| `FitsChanCursorOracleTest` `sky_offset_system_rw` | CDELT1 and CDELT2 within 1e-14 relative, PC1_2 and PC2_1 within 1e-14 absolute (the PC diagonal is 1) | CDELT1 8 ULP, PC2_1 2.0e-15: identical fitted Mappings, whose SphMap and TAN WcsMap transforms differ first at equal inputs (traced with a debugger and per-component comparisons, not replayed), the slopes of the differences being the differences of the fitted gradients | +| `FitsLogMapTest` | Logarithms and exponentials within 1 ULP of C's MathMap | `Math.exp(1)` is 1 ULP from libm | +| `FitsChanWcsWriteTest` AZEL, Galactic and Supergalactic writes | CDELTn and PCi_j within 1e-14 absolute plus 1e-13 relative; other cards within 4 ULP | identical fitted Mappings; IWC computed from native latitudes near 90° amplify 1-ULP differences; the Galactic PC1_2 differs by 2.8e-15 against a limit of 1.3e-14 | +| `FitsFsetToStoreTest` offset-sky description | Within 1e-14 rather than 4 ULP | the FrameSet read from the header already differs by 15 to 20 ULP, from the same runtime functions | +| `FitsSipIntWorldTest` SIP_2D | CD within 1e-12 relative; CRPIX, the 32 coefficients and the samples exact | 1 to 3 ULP: the Rust oracle's copy of `SIPIntWorld` fits over an older box than current C; current C is checked end to end by the `sip` rows of `wcsconv` | +| `FitsSkyPoleTest`, `FitsCelestialAxesTest` | Stored LONPOLE and LATPOLE within 1e-12 of C's cards | the values come from C's cards, written with 15 and 17 significant digits, and are at most 180 | + +## Defects found in the C library + +All are in the pinned library (`3d3f255f`), in `fitschan.c` unless named; "probe" means a probe against the pinned library showed it, "reading" that it follows from the code. +Each is recorded in [`docs/rust-c-differences.md`](../rust-c-differences.md) with what Java does. +Java gives a defined result in every case: it treats an index past an array as absent, declines or throws `AstException` with `AST__INTER` where C's behaviour is undefined, and stores nothing C leaves uninitialised. + +| Where | Defect | Confirmed | +| --- | --- | --- | +| `MakeFitsFrameSet`, `AddEncodingFrame` | A world Frame holding two SkyFrames makes no FrameSet, and the null FrameSet is then dereferenced | Probe (crash in `astGetFrame_`) | +| `SplitMap2` | A CmpMap with Ident set is decomposed into itself, and the search recurses without end | Reading | +| `IsMapTab1D`, `CelestialAxes`, `OtherAxes` | A WCS axis fed by several grid axes returns a Mapping with no table columns, after which a FitsTable that was never made is used (a null dereference in `OtherAxes`) | Reading | +| `AnalysePoly` | Writes an output index past the end of its coefficient array for each unused coefficient after the last used one | Reading (the Java port's first run hit the bound) | +| `MakeInvertable` | Reads a dimension past the end of its caller's array for degenerate axes | Reading | +| `WorldAxes` | For a Mapping with only a forward transformation, reads `perm[j]` past the array when there are more inputs than outputs | Reading | +| `SIPIntWorld` | Reads grid axes past the array `astMapSplit` returns when the split of the other outputs has fewer inputs | Reading | +| `FsetToStore` | Its second letter pass reads past its table of Frames once the 26 letters are used | Reading | +| `PCFromStore` | Compares an alternate PC matrix with the primary as flat arrays, past the primary for an alternate with more axes; compares RADECSYS with an absent primary value | Reading | +| `MakeIntWorld` | A failed fit stores CDELT values `SplitMat` never set (they never reach a card, since a version without CRPIX is not written) | Probe | +| `CLASSFromStore` | With one-pixel celestial axes, `astTranN` is given three coordinates whatever the FrameSet, so four pixel axes fail with `AST__NCPIN` | Probe | +| `WcsFromStore` (date helper) | An MJD `palDjcl` rejects leaves the date fields uninitialised and formats them | Reading | +| `SkySys` | The offset CTYPE comment reads past an empty Symbol, and a long SkyRef overflows its 80-character buffer | Reading | +| `Similar` | Reads past both strings when both are blank, and ignores the last non-blank character, so `ABCD` and `ABCX` are alike (kept) | Probe | +| `polymap.c` `MergeShift` | Reads the number of outputs with `astGetNin` (latent: its one caller passes a 2-by-2 PolyMap) | Reading | +| `Write`, `FixNew` | A write that fails with an error leaves the cards it added and the current card where it failed | Reading | +| `SetValue`, `FixNew` | A write that replaces a card with the keyword it stores and then fails loses that card (kept) | Probe | + +Kept as C has them, since they are defined: DATE-OBS written `T24:00:00.000` when the time of day rounds up, and years before 1900 as negative two-digit years; SIP `*_ORDER` and IMAGFREQ written without a version letter; `QV` used for every axis once one is TPN; FITS-AIPS++ `PROJPm` not read back; the `CardComm` comment and the `CmXXX` letter counting of the PC and IRAF translations; the method and class names exchanged in FsetToStore's warnings; the offset SkyFrame's FrameSet remapped twice by `AddVersion`. + +## Final review + +A fresh reviewer read the whole branch and ran a differential fuzz against the pinned C library: 1,800 random FrameSets of this library's classes written in all seven encodings (12,600 writes), some into FitsChans already holding cards with a random current card and attributes, and 4,440 mutated FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and DSS headers read. +No exception other than `AstException` and `UnsupportedOperationException` escaped; wherever both libraries wrote, the cards, their order, their placement and the current card matched C's, and wherever both refused, both FitsChans were unchanged; Review Focus items 4 and 5 were confirmed against C. +It found no Critical problem and no phase 3 port error. +The fix pass dealt with: + +- **Writes refused that C completes.** + `LogAxis` threw `needs MathMap` for every non-linear axis with a non-zero CRVAL, where C uses the MathMap only to test whether the axis's logarithm is linear and, when it is not, goes on to describe the axis linearly within FitsTol; the fuzz found 231 writes C completed that Java refused. + The test is now ported with a package-private Mapping computing what C's MathMap computes, and `needs MathMap` is thrown only where the test passes; of the 735 fuzzed writes that threw there, 700 now give C's outcome and cards, 28 reach `-TAB` and throw `needs FitsTable`, and 7 (one FrameSet) still throw where C builds the `-LOG` Mapping and then writes nothing. + This reverses the Task 4 ruling, and it made the `lsst`, `offset-sky` and `offset-sky-pole` FITS-WCS rows match C. +- **Documentation.** + The Javadoc of `write` now says where each encoding puts its cards, and that a failed write loses a card it had already replaced (C does the same; recorded as a C quirk, and pinned by a test); a test name that said the opposite of what it asserts was corrected. + +A scoped re-review found all four findings addressed and no new problem. +The minor findings were then fixed. +The `FitsSkyPoleTest` tolerance is 1e-12 (it was 1e-9), and the libm licence of the cursor-oracle cases is 1e-14 relative (it was 1e-13), five times the largest difference. +Two read differences from earlier phases that the fuzz exposed now follow C, each pinned by a test whose expected values come from a C probe: +the read's keyword translations are kept apart from the header's cards and read after them, as C reads its FitsChan of translations, so a translation outranks every card with its keyword (a zero CDELT followed by another CDELT, several CDELTs before a CD matrix) and a repeated translation keeps its comment by `SetFits`'s rules; +and a NAXISn of a described axis that is not a number fails the read with `AST__FTCNV`, as C's `DistortMaps` reads it with `astGetFitsF`. +A CTYPE card without a comment no longer clears the comment an earlier card gave, which with several "other" axes becomes the axis Label. +Rust shares all three; they are in `docs/rust-c-differences.md`. + +## Gaps and risks + +- **Logarithmic axes need MathMap.** + `LogAxis` tests an axis for the `-LOG` algorithm as C does, with an internal Mapping computing what C's MathMap computes, and `write` throws `needs MathMap` only where C would then describe the axis with `-LOG`, a description whose Mapping holds a MathMap. + C sometimes builds that description and then drops it, when `MakeIntWorld` cannot fit it: the absolute description of an offset SkyFrame in the cursor-oracle case `alt_axes_alt_offset`, and one FrameSet of the review's write fuzz, which C writes in no encoding and Java refuses in all seven. + With the test ported, offset sky coordinates (`offset-sky`, `offset-sky-pole`, `offset-sref`, `skyref`, `skyref-alt`), `lsst`, and non-celestial axes that are linear only within FitsTol are written as C writes them: the `offset-sky`, `offset-sky-pole` and `lsst` rows of `wcsconv` match. + Of the 735 fuzzed writes that threw at `LogAxis` before, 700 now give C's outcome and cards, 28 reach a `-TAB` description with TabOK set and throw `needs FitsTable`, and 7 are the FrameSet above. +- **Everything spectral needs SpecFrame**, which accounts for 63 of the 76 deferred `wcsconv` rows and 45 of the 51 deferred headers; reading FITS-CLASS needs SpecFrame and DSBSpecFrame. +- **Runtime-Math margins.** + The Galactic PC1_2 comparison has a margin of about 4.6 times; another JDK or libm could use more of it. + Only every 97th position of the `tan` grids is compared, because C's oracle holds only those samples and a hash. +- **ReadCrval** reads the FitsChan before a write, so a write into a FitsChan holding a header this library cannot read (spectral, FITS-CLASS) throws `UnsupportedOperationException` naming the class. + +## Rulings + +Every decision made while executing the plan where it was wrong, unclear or silent is in [`2026-11-16-phase3-rulings.md`](2026-11-16-phase3-rulings.md), with its reason and its cost if wrong. diff --git a/docs/reports/2026-11-16-phase3-rulings.md b/docs/reports/2026-11-16-phase3-rulings.md new file mode 100644 index 0000000..b191b55 --- /dev/null +++ b/docs/reports/2026-11-16-phase3-rulings.md @@ -0,0 +1,124 @@ +# Phase 3: rulings + +These are the decisions made while executing the phase 3 plan ([`2026-11-15-pure-java-ast-phase3-fitschan-write.md`](../superpowers/plans/2026-11-15-pure-java-ast-phase3-fitschan-write.md)) where the plan was wrong, unclear or silent. +They are copied from the execution ledger, in the order they were made within each task. +Each gives what was decided, why, and what it costs if wrong. +A later ruling can reverse an earlier one; the final review section records the reversals made in the fix pass. +The phase report is [`2026-11-16-phase3-report.md`](2026-11-16-phase3-report.md). + +## Task order + +- Ruling: Task 5 (SIP building blocks) runs before Task 3 — SIPIntWorld needs only Task 2, AnalysePoly, ScalePolyInputs and existing Mapping methods, and with SipOK defaulting to 1 every celestial FITS-WCS test in Tasks 3/4 would otherwise hit the interim throw — cost if wrong: none. + +## Task 1 + +- Ruling: a write that throws is undone (Rust), where C leaves partial cards because FixNew/astSetCard do nothing once status is set; recorded in docs/rust-c-differences.md — cost if wrong: after a failed write, Java's cards differ from C's partial state (C's state is an error leftover). +- Ruling: C's nested Write marking cards not-new is not reproduced; matters only when a write fails — cost if wrong: none observable since a failed write removes all new cards. +- Ruling: a comment leaving no room for a string value throws AST__INTER where C's behaviour is undefined — cost if wrong: an exception on an input C mishandles. +- Ruling: FitsChanCursorOracleTest write ops (W, WF, WFT, WC, WCF; 18 cases) pulled forward from Task 10, as the only C source of exact NATIVE cards; native_full_1 excluded (C writes object/pointer counts Java does not keep), the rest of it compared by a separate test; RW/RCIW/RSW stay for Task 10 — cost if wrong: none. + +## Task 2 + +- Ruling: makeIntWorld follows C's signature — boolean makeIntWorld(cmap, fr, wperm, s, store, dim, fitstol, sipok, method, cls) — not the plan's MatrixMap(..., fc); sipok = encoding==FITS-WCS && SipOK — cost if wrong: mechanical call-site change. + Carried to Tasks 3-5. +- Ruling: SIP branch (C: sipok && lonax != -1) throws "needs FitsSipIntWorld" until Task 5 — cost if wrong: none once Task 5 lands. +- Ruling: on failure makeIntWorld stores nothing where C leaves CDELT from uninitialised SplitMat memory (C quirk, recorded) — cost if wrong: a failed alternate's C cards (if C writes them) cannot be reproduced; Task 4/6 to check whether C writes a failed version at all. +- Ruling: C reads past arrays in MakeInvertable and WorldAxes (forward-only); Java treats the out-of-range index as absent (recorded as C quirks) — cost if wrong: only for heap contents C happened to read. +- Ruling: findBasisVectors largest-dimension, fitOK strict <, IsASkyFrame Domain check, worldAxes simplify + bad root, orthVector divide, orthVectorSet empty → unit basis, nearestPix any nout, C round: all follow C over Rust (recorded) — cost if wrong: none observed. +- Ruling: Rust tests orth.rs::wrong_row_length_returns_none (Rust-only check) not translated; make_int_world.rs::sip_chain_routes_through_sip_int_world left to Task 5 (interim test asserts the needs-FitsSipIntWorld throw) — cost if wrong: none. +- Ruling: Invert restored in finally in isMapLinear/nearestPix (differs from C only on error paths) — cost if wrong: none. + +## Task 3 + +- Ruling: celestialAxes returns C's WCS→IWC Mapping and takes (fc, fs, dim, wperm, s, store, boolean[] axisDone, isoff, method, cls); isSkyOff returns int with a 1-based Frame index — cost if wrong: mechanical. +- Ruling: TDBConv reuses FitsEpoch.tdbConv (TimeFrame, H8) — cost if wrong: none. +- Ruling: SkySys stores nothing for a non-SKY Domain SkyFrame (C IsASkyFrame); J2000 written as unknown system UNLN/UNLT without RADESYS (C), where Rust writes ICRS — cost if wrong: checked by Task 6's wcsconv gate. +- Ruling: SkySys stores MJD-OBS only — CARRY TO TASK 6: DATE-OBS formatted from store.mjdobs as C — cost if wrong: missing DATE-OBS. +- Ruling: SplitMap2 treats an Ident CmpMap as holding no WcsMap where C recurses without end (C quirk, recorded); other C-undefined paths (empty Symbol, 80-char comment overflow, NULL annul in TAN constant branch) handled without C's UB — cost if wrong: none in practice. +- Ruling: C quirk kept: IsMapTab1D returns the split Mapping with no table columns when the inverse split gives several grid axes (recorded) — cost if wrong: none. +- Ruling: skyPoleMatchesTheCLibrary compares stored LONPOLE/LATPOLE with C's 15-digit card values to 1e-9; splitmap oracle LONPOLE/PV1_3 to 1e-12 (C card text is not the shortest repr); CRVAL exact — cost if wrong: sub-tolerance differences surface only at Task 6's card gate. +- Ruling: some test expectations worked from C's code by hand (non_zenithal_with_unit_map3, tan2axisWritesCelestialKeywords, the -TAB cases) where no oracle covers the input — cost if wrong: a test encodes a misreading of C. +- Ruling: Rust tests fiducial.rs::invalid_axes_return_none (C reads past array) not translated; sky_pole wcs_nat_pole_fiducial_at_north_pole already translated — cost if wrong: none. + +## Task 4 + +- Ruling: fsetToStore returns FitsPlaneStores (null for C NULL), indexed by version letter (common item 7; C writes letters in order and merges colliding letters) — cost if wrong: mechanical. +- Ruling: per-version FitsStore capacity max(pixel, world axes); C's store->naxis is FitsPlaneStores.naxis — CARRY TO TASKS 6-9: use FitsPlaneStores.naxis where C uses store->naxis; skip versions without CRPIX1/CRVAL1 as C — cost if wrong: wrong axis count in DSS/CLASS. +- Ruling: writeForeign calls fsetToStore and still returns false (so the Task 4 tests can call write) — cost if wrong: none once Task 6 lands. +- Ruling: C quirk 1527 kept (method/class swapped in Warn text) — cost if wrong: one message text. +- Ruling: C quirks kept: offset-sky absolute description letter not checked against Ident letters (merged into one store); AddVersion clears/restores SkyRefIs on the caller's FrameSet — cost if wrong: last-bit differences. +- Ruling: C undefined behaviour not kept: two SkyFrames (C NULL deref) give no description; letters past Z (C reads past frms) give none; OtherAxes table-less IsMapTab1D result (C NULL FitsTable deref) throws needs FitsTable — cost if wrong: none observable. +- Ruling: LogAxis throws needs MathMap for any non-zero CRVAL (C builds the MathMap before testing log-linearity; probe confirms C reaches it, even with TabOK) — cost if wrong: an axis C would refuse throws instead (convention for a reached class). +- Ruling: a failed alternate keeps partial values but no CRPIX; C's FITS-WCS/PC writers skip versions without CRPIX, so C's uninitialised CDELT never reaches a card (resolves Task 2's open point) — cost if wrong: none. +- Ruling: readCrval propagates UnsupportedOperationException from reading the FitsChan copy (C reads it) and maps AstException to null (C clears status) — cost if wrong: write into a FitsChan holding a header Java cannot yet read throws (FITS-PC/IRAF/AIPS until Tasks 7-8; spectral stays). +- Ruling: SkyRefIs restored in finally (C skips restore on error) — cost if wrong: none. +- Ruling: FitsFsetToStoreTest offset-sky primary description compared to 1e-14 not 4 ULP — the FrameSet read from the TAN header already differs from C by 15-20 ULP before FsetToStore (read-side, phase 1) — cost if wrong: hides an FsetToStore error below 1e-14; Task 6's wcsconv offset rows may hit it. + +## Task 5 + +- Ruling: sipIntWorld follows C: Mapping sipIntWorld(map, tol, lonax, latax, s, store, dim, int[] inaxes, double[] crpix, double[] cd, method, cls), null for C's NULL; analysePoly(PolyMap, Mapping[3]) boolean — cost if wrong: mechanical. +- Ruling: store keeps SIP coefficients in sipA/sipB/sipAp/sipBp via FitsStore.setItem (C SetItem); order fields left empty as C stores no orders — CARRY TO TASK 6: WcsFromStore computes A_ORDER etc. from the tables as C does — cost if wrong: Task 6 writes no orders if it reads the fields. +- Ruling: PolyMap.mergeShift ported from C astMergeShift/MergeShifts/ExpandTerm, not Rust's binomial expansion — C term/sum order; WITH_CONSTANT fixture bit-exact — cost if wrong: none. +- Ruling: C quirks avoided (recorded): MergeShift reads astGetNin for nout; AnalysePoly writes an index past its array; SIPIntWorld reads past an array when the non-celestial split is short (Java throws AST__INTER); CTYPE shorter than 8 left unchanged as C — cost if wrong: only on inputs where C is undefined. +- Ruling: ScalePolyInputs zero/bad scale and AnalysePoly non-2x2 throw AST__INTER as C's astError, where Rust returns None — cost if wrong: exception where Rust declines. +- Ruling: SIP_2D oracle CD values compared to 1e-12 relative, not exactly — the oracle's copy of SIPIntWorld fits over an older box (-ubnd..ubnd with tol); current C uses the transformed-corner box with utol; Java differs by 1-3 ULP; all box-independent values (CRPIX, 32 coefficients, samples) exact. + Task 6's wcsconv sip rows check current C end to end — cost if wrong: a real 1-3 ULP CD difference from current C would surface only in Task 6's gate. +- Ruling: Rust tests binomial_basics and wrong_length_returns_none not translated (Rust-only helpers/checks); sip3dKeepsTheOtherAxis expectations read from C's code — cost if wrong: none. + +## Task 6 + +- Ruling: wcsFromStore(FitsChan, FitsPlaneStores, method, cls) returns boolean (C int) — cost if wrong: mechanical. +- Ruling: fitsFromStore returns false for PC/IRAF/AIPS/AIPS++/CLASS/DSS until Tasks 7-9 (FsetToStore still runs and warns) — cost if wrong: none. +- Ruling: writers use new FitsCardList.setValueAsWriter (C SetValue/SetFits/CnvValue comment rules); read-side FitsSpecTrans keeps putOrAppend — cost if wrong: a translated card's comment may differ from C on read (deferred minor). +- Ruling: FindWcs check replaced by C's 57 templates via FitsMatch (old check missed CD1_1A and misordered multi-wcs-dup) — cost if wrong: none. +- Ruling: C quirks kept: Similar ignores the last non-blank character; SIP *_ORDER without version letter; IMAGFREQ without letter; QV prefix for every axis once one is TPN; DATE-OBS T24:00:00.000 and negative two-digit years — cost if wrong: cards differ from a fixed C. +- Ruling: mjdToDateStr throws AST__INTER when palDjcl fails (C formats uninitialised fields); no MJD-AVG written (only reads set it); an alternate's AstException dropped as C clears status, UnsupportedOperationException propagates — cost if wrong: none observed. +- Ruling: oracle cards compared within 4 ULP (cardsMatchC, as wcsconv) except Sipok exact; runtime-Math licences rtol 1e-13 on named keywords only (splitmap linear/linear_3d CDELT2 5 ULP from Math.cos vs libm amplified by FitLine; offset-SkyRef PC ~1e-16 from atan2), traced with lldb and probes — cost if wrong: hides a port error below 1e-13 in those keywords. +- Ruling: Review Focus 4 corrected to C: new cards go after the last FindWcs card (or at the end when none), not before the current card; cardsAreWrittenBeforeTheCurrentCard asserts C's placement (probe p1) — cost if wrong: none; plan text was wrong. +- Ruling: everyInScopeHeaderRoundTrips lists 12 headers with C's own round-trip outcome (probe p3: write 0 for CHIPASS_Equ/car6/tsc; transforms differ car1/car2; needs MathMap offset-sky*, offset-sref, skyref*) — cost if wrong: none. +- Ruling: Task 4's offset-sky ULP concern is runtime Math (identical MatrixMaps, 1-ULP transforms), not a read-side error; it does not reach wcsconv (those rows need MathMap) — cost if wrong: an undetected ~1e-16 read-side error. +- Ruling: FitsWcsWriteTest written after the implementation from probe values (never seen failing); Task 1's foreignFrameSetWriteFailsForNow replaced by C's result — cost if wrong: test-first evidence missing for that class; the oracle tests did fail first. + +## Task 7 + +- Ruling: pcFromStore/irafFromStore(FitsChan, FitsPlaneStores, method, cls) → boolean — cost if wrong: mechanical. +- Ruling: SpecTrans PC/IRAF translations replace header values as C does (RADECSYS beats RADESYS; probed); Rust tests keeps_radesys_when_both_present and rename_keyword_no_op_when_destination_already_present translated to C's result — cost if wrong: none. +- Ruling: C quirks kept: translated cards take CardComm(this) (first unconsumed card's comment at read entry); CmXXX letter is A at the lowest m present — cost if wrong: differs from a fixed C. +- Ruling: C undefined behaviour in PCFromStore alternates (element past primary matrix, RADECSYS against none, unset projection parameters) resolved as differs / AST__BAD — cost if wrong: only for such FrameSets. +- Ruling: FitsStore.lonLatSpecAxes takes FitsPlaneStores.naxis (C store->naxis); empty-version stores passed as empty FitsStore — cost if wrong: none. +- Ruling: enc_pc/enc_iraf read_from_cards tests not translated (dead code per plan); translate_projp_retains_source_cards translated now — cost if wrong: none. +- Ruling: everyInScopeHeaderRoundTrips: 8 WRITE_FAILS and scp DIFFERS added to NOT_ROUND_TRIPPED, each C's outcome (probe rt) — cost if wrong: none. + +## Task 8 + +- Ruling: aipsFromStore/aipsppFromStore(FitsChan, FitsPlaneStores, method, cls) → boolean — cost if wrong: mechanical. +- Ruling: C's write flow kept: after a missing CRPIX/CRVAL/CTYPE or -TAB the remaining cards are still written and the result is false (FixNew removes them) — cost if wrong: none. +- Ruling: AIPS spectral string checks ported in full (no SpecFrame needed; CTYPE FREQ reaches the store from a plain Frame) — cost if wrong: none. +- Ruling: C quirks kept: AIPS SIN check resets ok; AIPS++ PROJPm not read back (recorded) — cost if wrong: differs from a fixed C. +- Ruling: Rust write_aipspp_with_lonpole_latpole translated to C's result (LONPOLE 180 written; probe p2) — cost if wrong: none. +- Ruling: read_aips_spectral_felo_geo not translated (SpecFrame); FitsChanErrorsTest write_enc checks implemented (mutation-checked); sky_systems_through_five_encodings left for Task 10 — cost if wrong: none. +- Ruling: TranGridOracleTest tan grids run with positions compared within ulp(pi/2) rad, hash skipped, traced to runtime atan2/sin/cos — cost if wrong: a port error below 2.2e-16 rad or at an unsampled grid position goes unseen. + +## Task 9 + +- Ruling: FITS-CLASS write refuses every FrameSet of this library (no SPECSYS without a SpecFrame); throws needs SpecFrame where C's checks would pass — cost if wrong: none. +- Ruling: DSS PLTRAS/PLTDECS in 7 encodings-oracle cases compared to the effect of 4 ULP of CRVAL — traced (lldb + replays) to atan2 at identical arguments (forward SphMap; eraFk5hz eraC2s with Epoch), libm correctly rounded, Java ~0.6 ULP off; the fields hold 3600×CRVAL's fractional part, amplifying the last bit — cost if wrong: a port error within 4 ULP of CRVAL in those fields goes unseen. +- Ruling: PLTDECSN negative only when its first word is exactly "-" (C; Rust: any leading -); PLTSCALE and PPO1/2/4/5 marked used (C; Rust leaves them) — recorded — cost if wrong: none. +- Ruling: C quirk kept: FITS-CLASS writer with one-pixel celestial axes transforms three coordinates whatever the FrameSet, so a four-pixel-axis FrameSet fails AST__NCPIN (probed) — cost if wrong: differs from a fixed C. + +## Task 10 + +- Ruling: alt_axes_offset{,_none} CDELT2/CDELT2A within 1e-13 relative; azel/supergalactic CDELTn and PCi_j within 1e-14 abs + 1e-13 rel — each traced to atan2/sin/cos at identical argument bits (lldb + replays) — cost if wrong: a port error of that size in those cards goes unseen; Galactic PC1_2 margin only ~4.6x (2.8e-15 vs 1.3e-14). +- Ruling: 13 rust-tests.txt additions for never-listed files: test_fitschan_wcs_write.rs 9 (SpecFrame, GrismMap, SplineMap, MathMap), test_fitschan_encodings.rs 4 (SpecFrame, FITS-CLASS read, MathMap) — reasons measured from the exceptions — cost if wrong: none; the list was incomplete. +- Ruling: roundtrip helper is C's (testfitschan.c, with its pixel round-trip fallback), not Rust's (recorded); sky_systems_through_five_encodings asserts C's exact outcome per System/encoding; translated tests assert C's full card lists where Rust checked presence; C's Galactic block translated with Supergalactic, including C's System-after-remap (conversion held twice) — cost if wrong: none. + +## Final review and fix pass + +- Ruling: I1 (LogAxis throws needs MathMap for any non-linear non-celestial axis with non-zero CRVAL, where C's MathMap only feeds an IsMapLinear test and C, when that fails, goes on to write the axis linearly within FitsTol; fuzz: 231 writes C succeeds on) — reverses the Task 4 LogAxis ruling: the log-linearity test is ported with a package-private Mapping computing exactly what C's MathMap "logs=log(s)"/"s=exp(logs)" computes (bad values as mathmap.c gives them); `needs MathMap` is thrown only when the test passes and C would build the -LOG Mapping from the MathMap — why: C does not need the MathMap's class there, only its function, and users get C's cards — cost if wrong: the internal log Mapping departs from MathMap's evaluation in an edge case (log of 0 or negatives, simplification) and a write differs from C. +- Ruling: M1-M3 re-graded Important (public write() Javadoc and the report state wrong card placement / rollback; a test name says the opposite of what it asserts) — fixed in the pass; M4 (FitsSkyPoleTest 1e-9 looser than its reason) stays minor. +- Ruling: FitsLogMap gives AST__BAD for an overflowing exp, as mathmap.c's CATCH_MATHS_OVERFLOW intends and a glibc build gives; the pinned macOS build gives Infinity (its libm does not set errno) — cost if wrong: only an IsMapLinear inverse that overflows, which a real axis does not reach. +- Ruling: FitsLogMap treats NaN/infinite inputs as bad (the library's rule for every Mapping) where C's MathMap gives log(inf)=inf, exp(NaN)=NaN — cost if wrong: none for LogAxis inputs. +- Ruling: LogAxis throws needs MathMap whenever C's test passes, including where C then drops the description and writes 0 (alt_axes_alt_offset; fuzz c01255) — the convention for a reached class — cost if wrong: a throw where C returns 0 for such FrameSets. +- Ruling: sky_offset_system_rw licensed as runtime Math (CDELT1/CDELT2 within 1e-13 relative, PC1_2/PC2_1 within 1e-13), on identical fitted Mappings, bit-equal FitLine inputs and first differences at SphMap/TAN WcsMap with equal inputs; no elementary-function replay for this case; runtime-Math card comparison trims comments (a longer value moves the comment) — cost if wrong: a port error below 1e-13 in those cards; observed 8 ULP / 2e-15. +- Ruling: skyref.head round trip expects READ_FAILS (C's own outcome, probe rt7) — cost if wrong: none. +- Ruling: the Task 4 LogAxis ruling (throw for any non-zero CRVAL) is reversed by I1; the Review Focus 4 test name in Task 6's ruling is now cardsGoAfterTheLastWcsCard — cost if wrong: none. diff --git a/docs/rust-c-differences.md b/docs/rust-c-differences.md index 5bb68dc..c1de275 100644 --- a/docs/rust-c-differences.md +++ b/docs/rust-c-differences.md @@ -387,6 +387,20 @@ Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follow - Rust: `fitschan/wcs_keywords.rs` looks each keyword up and takes the first card, so that header reads as FK5. - Java: as C; of the cards for one keyword the last whose value converts gives the value, and a later card that does not convert is passed over (`fitschan.c:37357-37373`). +### SpecTrans translations of a keyword the header repeats + +- C: `SpecTrans` writes each translation into a new FitsChan, which `WcsToStore` reads after every card of the header, so a translation outranks every card with its keyword: `CDELT1 = 0.0` then `CDELT1 = 0.25` reads with CDELT1 1.0, and a CD matrix gives CDELTj 1.0 however many CDELTj cards the header has (C probe). + A second translation of one keyword replaces the first, its comment kept by `SetFits`'s rules in that FitsChan. + `WcsFcRead` stores the comment of each CTYPE card it visits, but `SetItemC` ignores a card with none, so the comment kept is that of the last card with one; with several "other" axes it becomes the axis Label (`fitschan.c:36848-36860`, `fitschan.c:39283-39304`). +- Rust: `put_or_append` in `fitschan/card_list.rs` writes the translation over the card after the current one or the first card with the keyword, keeping that card's comment when the values are alike, so a later card with the keyword outranks it; the comment stored for a CTYPE is that of its last card, none if that card has none. +- Java: as C (`FitsCardList.setTranslation`, `FitsCardList.getStoredComment`). + +### A NAXISn that is not a number + +- C: `DistortMaps` reads NAXIS1 to NAXISn, n the number of WCS axes of the description, with `astGetFitsF`, so `NAXIS1 = 'abc'` or `NAXIS1 = (1.0, 2.0)` makes the read fail with AST__FTCNV; a NAXISn beyond the WCS axes is not read (`fitschan.c:9017-9021`, C probe). +- Rust: `fitschan/wcs_keywords.rs` reads the NAXISn it can convert and leaves the others unset, so the read succeeds. +- Java: as C. + ### More than 99 WCS axes - C: the FitsStore holds the keywords of intermediate axes 0 to 98 only, and `GetItem`, `GetItemC`, `SetItem` and `SetItemC` raise AST__INTER for any other axis (`fitschan.c:13354-13357`, `fitschan.c:13869-13872`, `fitschan.c:27993-27996`), so a header with `WCSAXES = 1000` fails with "intermediate axis index 99 is invalid". @@ -398,7 +412,15 @@ Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follow - C: `SpecTrans` reads RADECSYS, LONGPOLE and CmVALi, CmPIXi, CmYPEi and CmNITi, and writes CDELTis and PCj_is from CmELTi, whatever the encoding (`fitschan.c:31656-31675`, `fitschan.c:31962-32098`). - Rust: `fitschan/spec_trans.rs` does these only for FITS-PC and FITS-IRAF. -- Java: as C for the FITS-WCS read; the FITS-PC, FITS-IRAF and FITS-CLASS reads are out of scope. +- Java: as C. + +### SpecTrans translations for FITS-PC and FITS-IRAF + +- C: `SpecTrans` writes the RADESYS, LONPOLE, PVi_m (from PROJPm), CRVALis, CRPIXis, CTYPEis and CUNITis it translates into its own FitsChan, whose values `WcsToStore` reads after those of the header, so they replace any the header has: with both RADECSYS and RADESYS the RADECSYS value is used (C probe). + Each of these cards, and each CDELTis from CmELTi, is given the comment of the current card of the header, `CardComm( this )`, which at the start of a read is the first card, not the comment of the card translated. + The alternate letter of the CmVALi, CmPIXi, CmYPEi, CmNITi and CmELTi of each `m` is `A` for the lowest `m` the header has for that keyword and the next letter for each `m` after it, so `C2VAL1` alone becomes `CRVAL1A` (`fitschan.c:31656-31675`, `fitschan.c:31948-32098`). **C quirk** (the comment and the letter). +- Rust: `rename_keyword` in `fitschan/spec_trans.rs` keeps a RADESYS, CRVALis or other keyword the header already has, and moves the comment of the card it renames; `translate_cnxxx` gives `m` the letter `A + m - 1`. +- Java: as C. ### SpecTrans PC matrix translations @@ -502,6 +524,263 @@ Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follow - Rust: `fitschan/wcs_read.rs` has no limit. - Java: as C. +### The cards of a write that fails with an error + +- C: `Write` removes the cards a write added, and makes the card that was current current again, through `FixNew` and `astSetCard`, which do nothing once the error status is set, so a write that fails with an error leaves the cards it had added and the current card where the failure left it (`fitschan.c` `Write`, `FixNew`). **C quirk.** +- Rust: `Channel::write` for `FitsChan` in `fitschan/mod.rs` removes the cards and restores the current card after any failure, an error included. +- Java: as Rust: `FitsChan.write` undoes a write that throws as it undoes one that writes nothing. + +### The largest grid dimension of `FindBasisVectors` + +- C: `FindBasisVectors` takes the largest dimension, which limits its search, from the dimensions before the first unknown one (`fitschan.c` `FindBasisVectors`). +- Rust: `fitschan/wcs_decompose.rs` `find_basis_vectors` uses 10240 whenever any dimension is unknown. +- Java: as C. + +### The tolerance test of `FitOK` + +- C: `FitOK` accepts a fit whose mean squared residual is strictly less than the squared tolerance (`fitschan.c` `FitOK`). +- Rust: `fitschan/wcs_decompose.rs` `fit_ok` accepts a root mean square residual less than or equal to the tolerance. +- Java: as C. + +### Celestial axes in `MakeIntWorld` + +- C: `MakeIntWorld` finds the longitude axis for `SIPIntWorld` with `astIsASkyFrame`, and calls it when SipOK is set and there is a longitude axis; when scaling degenerate axes it pairs celestial axes with the file's `IsASkyFrame` macro, which also needs the Domain to be `SKY` (`fitschan.c` `MakeIntWorld`). +- Rust: `fitschan/fset_to_store/make_int_world.rs` calls `sip_int_world` only when both a longitude and a latitude axis are found, and pairs any SkyFrame axes whatever their Domain. +- Java: as C. + +### CDELT values of a failed `MakeIntWorld` + +- C: when no linear description is found, `MakeIntWorld` still calls `SplitMat` on its CD matrix, which is all bad, and stores the CDELT array, which `SplitMat` has not set, so the store holds uninitialised values (`fitschan.c` `MakeIntWorld`). **C quirk.** +- Rust: `fitschan/fset_to_store/make_int_world.rs` stores nothing on failure. +- Java: as Rust; `FsetToStore` discards the store when the primary description fails, but keeps an alternate description's partial values. + +### Dimensions of degenerate axes in `MakeInvertable` + +- C: `MakeInvertable` reads a dimension for every input of the square matrix, but its caller's array has one per pixel axis, so for degenerate axes it reads past the end of the array (`fitschan.c` `MakeInvertable`, `Write`). **C quirk.** +- Rust: `fitschan/fset_to_store/invertable.rs` stops at the end of the array. +- Java: as Rust: an input with no dimension is not patched. + +### `OrthVector` with no vectors, and its normalisation + +- C: `OrthVector` with no vectors solves an empty system, which `palDmat` does not find singular, and gives the unit vector of the first column, so `OrthVectorSet` with no vectors gives the unit basis; it normalises by dividing by the length (`fitschan.c` `OrthVector`). +- Rust: `fitschan/fset_to_store/orth.rs` `orth_vector` returns `None` with no vectors, and normalises by multiplying by the reciprocal of the length, which can differ in the last bit. +- Java: as C. + +### `WorldAxes` + +- C: `WorldAxes` simplifies the Mapping first, takes as the root pixel position the inverse-transformed root world position even when it is bad, compares tangents with `astEQUAL`, and, for a Mapping with only a forward transformation, reads `perm[j]` for each input `j`, past the end of the array when there are more inputs than outputs (`fitschan.c` `WorldAxes`); the last is a **C quirk.** +- Rust: `fitschan/fset_to_store/world_axes.rs` does not simplify, keeps the previous root position on an axis whose inverse-transformed value is not finite, compares tangents with a local `ast_equal` scaled by the larger magnitude rather than the sum of the two, with a floor of the smallest normal double rather than 1e-12, and treats an input with no output of the same index as not retained. +- Java: as C, except that an input with no output of the same index is treated as Rust treats it. + +### `NearestPix` + +- C: `NearestPix` uses the Mapping split off for the axis whatever its number of outputs (`fitschan.c` `NearestPix`). +- Rust: `nearest_pix_value` in `fitschan/fset_to_store/spectral_axes.rs` uses the split Mapping only when it has one output. +- Java: as C. + +### What `SIPIntWorld` stores + +- C: `SIPIntWorld` stores the SIP coefficients only, by power, each table first filled with bad values up to the largest powers used, which for an iterative inverse is the single element (0, 0); `WcsFromStore` finds each order when it writes the cards (`fitschan.c` `SIPIntWorld`, `WcsFromStore`). +- Rust: `fitschan/fset_to_store/sip_int_world.rs` also stores the A, B, AP and BP orders, zero for an empty table, and stores no AP or BP table for an iterative inverse. +- Java: as C. + +### The `-SIP` code on a short CTYPE + +- C: `SIPIntWorld` copies the CTYPE value into a buffer and writes `-SIP` from its ninth character, so a value of fewer than eight characters keeps the null that ends it and is stored unchanged (`fitschan.c` `SIPIntWorld`). +- Rust: `append_sip_suffix` in `fitschan/fset_to_store/sip_int_world.rs` appends `-SIP` to a value of any length. +- Java: as C. + +### The grid axes of the other outputs in `SIPIntWorld` + +- C: `SIPIntWorld` reads one grid axis for each of the `Nin - 2` other inputs from the array `astMapSplit` returns for the other outputs, past its end if the split has fewer inputs (`fitschan.c` `SIPIntWorld`). **C quirk.** +- Rust: `build_perm_inputs` in `fitschan/fset_to_store/sip_int_world.rs` uses the inputs the split returns, however many there are. +- Java: reports `AST__INTER` when the split has fewer inputs. + +### Shifting a PolyMap in `AnalysePoly` + +- C: `AnalysePoly` merges the shift into the PolyMap with `astMergeShift`, which expands each term with `ExpandTerm` and simplifies the result, adding coefficients of the same powers in the order the expansion gives them and keeping the order of the terms (`polymap.c` `MergeShift`, `MergeShifts`, `ExpandTerm`); it simplifies the new PolyMap in the same way (`fitschan.c` `AnalysePoly`). +- Rust: `mappings/helpers/analyse_poly.rs` expands the terms with binomial coefficients (`merge_shift_2d`) and adds coefficients in a `BTreeMap`, as does `amalgamate`, so the terms come in sorted order and sums can differ in the last bit. +- Java: as C; `PolyMap.mergeShift` ports `astMergeShift`. + +### Failures of `AnalysePoly` and `ScalePolyInputs` + +- C: `AnalysePoly` reports `AST__INTER` for a PolyMap without two inputs and two outputs, and goes on with whatever the iterative inverse gives for the shift; `ScalePolyInputs` reports `AST__INTER` for a zero or bad scale, which reaches it from `SIPIntWorld` when the Mapping before the PolyMap has a zero scale (`fitschan.c` `AnalysePoly`, `ScalePolyInputs`). +- Rust: `analyse_poly` returns `None` for these PolyMaps and for a shift that is not finite, and `scale_poly_inputs` returns `None` for a zero or non-finite scale or a scale array of the wrong length; `sip_int_world` returns `None` before calling it for a zero scale. +- Java: as C. + +### Output indices past the end of `AnalysePoly`'s coefficient array + +- C: `AnalysePoly` sets the output index of the next coefficient before testing whether the coefficient is used, so once the last coefficient of the new PolyMap is written it writes past the end of its array for each remaining unused one (`fitschan.c` `AnalysePoly`). **C quirk.** +- Rust: `analyse_poly` builds a list of terms. +- Java: sets the index only for a coefficient that is used. + +### The number of outputs in `astMergeShift` + +- C: `MergeShift` reads the number of outputs with `astGetNin`, which matters only for a PolyMap with unequal numbers of inputs and outputs; its one caller, `AnalysePoly`, passes a 2-input, 2-output PolyMap (`polymap.c` `MergeShift`). **C quirk.** +- Rust: has no `astMergeShift`. +- Java: reads the number of outputs. + +### Systems, Domain and Labels in `SkySys` + +- C: `SkySys` stores nothing and returns 0 for a SkyFrame whose Domain is not `SKY` (`IsASkyFrame`), and stores WCSNAME only when the Domain is set, so only as `SKY`; a SkyFrame in the J2000 system, which is none of the systems it names, is described as an unknown one, its default Symbols giving `UNLN` and `UNLT` with no RADESYS; it stores EQUINOX, bad (unset) for the systems without one, replacing any earlier value; and a Label that is set becomes the CTYPE comment and CNAME even when empty (`fitschan.c` `SkySys`). +- Rust: `fitschan/fset_to_store/sky_sys.rs` stores WCSNAME for any Domain other than `SKY`, describes J2000 as RA and Dec with RADESYS ICRS, leaves an earlier EQUINOX in place, and ignores an empty Label. +- Java: as C. + +### The pole of a non-zenithal projection in `SkyPole` + +- C: `SkyPole` passes a bad native longitude of the celestial pole to `WcsNatPole`, which replaces it with its default, and stores LONPOLE and LATPOLE, bad (unset) when they take their defaults, replacing earlier values, and copies them, bad or not, to parameters 3 and 4 of the longitude axis (`fitschan.c` `SkyPole`). +- Rust: `fitschan/fset_to_store/sky_pole.rs` stores nothing when the pole's native coordinates are not finite or its Mapping cannot be inverted, and stores or copies only values that are set, leaving earlier ones. +- Java: as C. + +### The WcsMap `SplitMap2` makes for a projection found in parallel + +- C: `SplitMap2` gives a projection found among Mappings in parallel a new WcsMap with as many axes as the parallel outputs, copies every set projection parameter of every axis, and inverts it whatever the Invert value of the WcsMap found, the new WcsMap having none of that WcsMap's other attributes; and it searches a CmpMap with Ident set, which `astMapList` gives back whole for either decomposition, again without end, a **C quirk** (`fitschan.c` `SplitMap2`). +- Rust: `lift_wcsmap_to_full_axes` in `fitschan/fset_to_store/celestial_axes.rs` copies the parameters of the longitude and latitude axes only and keeps the Invert value of the WcsMap found. +- Java: as C, except that a CmpMap with Ident set is taken to hold no WcsMap. + +### The Mapping and axis exchange of `CelestialAxes` + +- C: `CelestialAxes` builds the Mapping from intermediate world to world coordinates from a ShiftMap, a MatrixMap, a copy of the WcsMap with parameters 3 and 4 of the longitude axis cleared, and `WcsNative`, between PermMaps when the axes need it; it exchanges the CRVAL values and the projection parameters of an exchanged celestial pair, and their CTYPE and CNAME values only when both are set (`fitschan.c` `CelestialAxes`). +- Rust: `build_wcs_to_iwc` in `fitschan/fset_to_store/celestial_axes.rs` builds its own rotation, and the exchange swaps CTYPE and CNAME whether or not they are set. +- Java: as C. + +### A WCS axis fed by several grid axes in `IsMapTab1D` + +- C: when the split of a WCS output from the inverse Mapping gives more than one grid axis, `IsMapTab1D` skips the table and returns the split Mapping, with no table columns, so `IsMapTab2D` and `CelestialAxes` go on to use a FitsTable that was never made (`fitschan.c` `IsMapTab1D`). **C quirk.** +- Rust: `is_map_tab_1d` in `fitschan/fset_to_store/map_tab.rs` returns `None` for such an output. +- Java: as C as far as `IsMapTab2D`; the use of the missing table that follows throws `UnsupportedOperationException` (this library has no FitsTable). + +### A Mapping without a table in `OtherAxes` + +- C: when `IsMapTab1D` returns a Mapping for an axis, `OtherAxes` stores the table version in the header of the FitsTable it expects to have been made, so for a Mapping returned with no table columns it dereferences a null FitsTable (`fitschan.c` `OtherAxes`). **C quirk.** +- Rust: `other_axes` in `fitschan/fset_to_store/other_axes.rs` gets `None` from `is_map_tab_1d` for such an axis. +- Java: throws `UnsupportedOperationException` for any Mapping `IsMapTab1D` returns there (this library has no FitsTable). + +### Two SkyFrames in `MakeFitsFrameSet` + +- C: `MakeFitsFrameSet` marks a world Frame with axes of two SkyFrames (of Domain `SKY`) unusable and makes no FrameSet, but then passes the null FrameSet to `AddEncodingFrame`, which dereferences it (a C-oracle probe writing a CmpFrame of two SkyFrames crashes in `astGetFrame_`) (`fitschan.c` `MakeFitsFrameSet`, `AddEncodingFrame`). **C quirk.** +- Rust: `make_fits_frameset` in `fitschan/fset_to_store/mod.rs` does not look for a second SkyFrame. +- Java: makes no FrameSet, so that the description cannot be made, which is what `AddVersion` does with the null FrameSet C means to return. + +### Units in `MakeFitsFrameSet` + +- C: `MakeFitsFrameSet` always builds a new FrameSet from copies of the pixel Frame, the world Frame and the Mapping; for an axis whose internal units cannot be converted to its Unit it sets the Unit to the internal units (degrees for radians, converted with a ZoomMap); and it appends the parallel CmpMap of conversions, not its simplification, to the Mapping (`fitschan.c` `MakeFitsFrameSet`). +- Rust: `apply_unit_remap` in `fitschan/fset_to_store/mod.rs` returns a clone of the FrameSet when nothing converts, leaves the Unit unchanged, and appends the simplified conversion. +- Java: as C. + +### The FrameSet an absolute description is made from + +- C: `AddVersion` clears SkyRefIs of an offset SkyFrame on the caller's FrameSet, through its integrity, and sets it back afterwards, so the caller's FrameSet is remapped twice and its Mapping can change in the last bits (a C-oracle probe writing the same FrameSet twice gives CRVAL1 1.0357383636595399, then 1.0357383636595427) (`fitschan.c` `AddVersion`). **C quirk.** +- Rust: `fset_to_store_absolute` in `fitschan/fset_to_store/mod.rs` clears SkyRefIs on a clone, leaving the caller's FrameSet unchanged. +- Java: as C. + +### Version letters of absolute descriptions + +- C: `FsetToStore` gives the description of absolute coordinates of an offset SkyFrame the letter after the last one it handed out, without checking it against the letters Frames took from their Ident, so the two descriptions can share a letter and are then stored together, the second replacing the values both store (a C-oracle probe writes version `A` with the CRVAL, CTYPE and CDELT of the Frame whose Ident is `A`, and the SkyRef, RADESYS and EQUINOX of the absolute sky description) (`fitschan.c` `FsetToStore`). **C quirk.** +- Rust: `collect_plane_stores` in `fitschan/wcs_write/plane_stores.rs` makes the two planes separately, with the same letter. +- Java: as C. + +### The order of the versions written + +- C: the store holds each value under the letter of its description, and `WcsFromStore` writes the descriptions in letter order, so the description of a Frame whose Ident is `Z` follows that of a later Frame given `A` (`fitschan.c` `WcsFromStore`). +- Rust: `encode_wcs` in `fitschan/wcs_write/mod.rs` writes the planes in the order `collect_plane_stores` made them, primary first and then by Frame. +- Java: the store is indexed by letter, as C's (`FitsPlaneStores`). + +### WCSNAME and the pixel axis count in `AddVersion` and `FsetToStore` + +- C: `AddVersion` stores the Domain of a world Frame whose Domain is set as WCSNAME, replacing a value `SkySys` stored; the store's `naxis` is the number of pixel axes `FsetToStore` is given (`fitschan.c` `AddVersion`, `FsetToStore`). +- Rust: `fset_to_store` in `fitschan/fset_to_store/mod.rs` stores a Domain that is not empty only when there is no WCSNAME yet, and its store's `naxis` is the larger of the numbers of pixel and world axes. +- Java: as C; the pixel axis count is `FitsPlaneStores.naxis`. + +### The comment of a card a write replaces + +- C: `SetValue` replaces a card with the keyword it writes, and `SetFits` keeps that card's comment when the new card has none or when the old value, converted to the type of the new one by `CnvValue`, is the same: equal integers, floating values equal to `astEQUAL` (whose floor is 1.0E-12), or strings `Similar` finds alike; a string's comment equal to its value is dropped (`fitschan.c` `SetValue`, `SetFits`, `MAKE_FSET`). + A probe keeps the comment of `CRPIX1 = 1 / old int comment` when `CRPIX1 = 1.0` is written. +- Rust: `put_or_append` in `fitschan/card_list.rs` keeps the comment only when the two values have the same type and are similar, comparing floating values with a `DBL_MIN` floor and strings ignoring case and trailing blanks only. +- Java: the writers of the foreign encodings follow C (`FitsCardList.setValueAsWriter`); the read's keyword translations keep the comparison they had. + +### A failed write loses a card it replaced + +- C: a writer that stores a keyword a card already has replaces that card with a new one (`SetValue`), and when the write then fails `FixNew` removes the new cards, so the card replaced is lost: a FITS-PC write of a TPN FrameSet into a FitsChan holding `CRVAL1 = 5 / mine` stores CRVAL1 before refusing TPN, returns 0, and leaves the FitsChan without a CRVAL1 card (C probe) (`fitschan.c` `SetValue`, `FixNew`, `PCFromStore`). **C quirk.** +- Rust: the same (`put_or_append` in `fitschan/card_list.rs` replaces the card with one flagged new, which `fix_new` removes). +- Java: as C (`FitsChanWriteTest.aFailedWriteLosesACardItReplaced`). + +### `Similar` does not compare the last character + +- C: `Similar` compares two strings ignoring case and blanks up to, but not including, the last character that is not blank in either, so `ABCD` and `ABCX` are alike; `WcsFromStore` then keeps the old comment of a card it replaces with a value differing only there, and leaves out the WCSNAME of a one-axis description whose CTYPE1 differs from it only there (C probe) (`fitschan.c` `Similar`). **C quirk.** + Two blank strings make it read past the end of both. +- Rust: `write_store_to_cards` in `fitschan/wcs_write/mod.rs` compares WCSNAME with CTYPE1 with `eq_ignore_ascii_case`. +- Java: as C (`FitsCardList.similar`), two blank strings being alike. + +### Where FITS-WCS writes the SIP coefficients and their orders + +- C: `WcsFromStore` writes each version's SIP coefficients at the end of its loop over versions, after which `FindWcs` puts the current card after the last card describing WCS, which the SIP cards are not, so the next version's cards go in front of them; the coefficient keywords carry the version letter but `A_ORDER`, `B_ORDER`, `AP_ORDER` and `BP_ORDER` do not, and each order is the largest sum of powers of the coefficients written (`fitschan.c` `WcsFromStore`). **C quirk** (the order keywords). +- Rust: `encode_wcs` writes the primary description's SIP block after the loop over planes, from the orders `fset_to_store` stores. +- Java: as C. + +### IMAGFREQ, QV parameters and CNAME in `WcsFromStore` + +- C: IMAGFREQ is written, without a version letter, for any version that has one; once one axis's CTYPE ends `-TPN`, the projection parameters of every axis of that version are written with the prefix `QV`; CNAME is left out when it equals the CTYPE or its comment (`fitschan.c` `WcsFromStore`). +- Rust: `write_store_to_cards` writes IMAGFREQ for the primary description only, chooses `QV` axis by axis, and writes no CNAME. +- Java: as C. + +### The DATE-OBS of a FITS-WCS write + +- C: `WcsFromStore` formats DATE-OBS from MJD-OBS with `palDjcal` before 1999 and with `palDjcl` and `palDd2tf` (milliseconds) after, so a time of day that rounds up is written `T24:00:00.000` on the same day, and a year before 1900 as a negative two-digit year (`fitschan.c` `WcsFromStore`; C probe). **C quirk.** +- Rust: `mjd_to_date_str` in `fitschan/wcs_write/mod.rs` works the date out with Meeus's algorithm and carries a rounded-up time into the next second. +- Java: as C (`FitsDates.mjdToDateStr`). + +### Alternate descriptions in `PCFromStore` + +- C: `PCFromStore` compares an alternate description's PC matrix with the primary one's element by element in storage order, so matrices of different sizes are compared as flat arrays and C reads past the primary matrix for an alternate with more axes; it compares an alternate RADECSYS with the primary one's even when the primary description has none, reading an uninitialised string, and an alternate's projection parameters with values never set when the primary description has no celestial axes (`fitschan.c` `PCFromStore`). **C quirk** (undefined behaviour). +- Rust: `write_pc` in `fitschan/enc_pc.rs` compares the two matrices as far as the shorter goes, and holds the unset values as absent or `AST__BAD`. +- Java: an element past the primary matrix differs; an unset primary RADECSYS differs from any; unset primary parameters are `AST__BAD` (`FitsEncPc`). + +### `IRAFFromStore` writes the primary description only + +- C: `IRAFFromStore` writes the primary description alone, its keywords without a version letter, refusing it when the number of CRPIX values differs from the number of pixel axes (`store->naxis`); it stops part way, leaving its cards for `Write` to remove, at a missing CRPIX, CRVAL or CTYPE or a `-TAB` axis; it writes DATE-OBS from MJD-OBS, and MJD-OBS only over a card the header already has (`fitschan.c` `IRAFFromStore`). +- Rust: `encode_wcs_per_plane` in `fitschan/wcs_write/mod.rs` passes the primary plane to `enc_iraf::write_to_cards`, which checks the plane's own axis count, checks CRPIX, CRVAL and CTYPE before writing, and writes DATE-OBS from the plane's stored date string. +- Java: as C (`FitsEncIraf`). + +### `AIPSFromStore` and `AIPSPPFromStore` + +- C: both write the primary description alone, refusing it when the number of CRPIX values differs from the number of pixel axes (`store->naxis`). + Writing CRPIX, CRVAL and CTYPE stops at a missing value or a `-TAB` axis, but CDELT, CUNIT, CROTA (or the CD matrix), EPOCH, LATPOLE, LONPOLE, DATE-OBS, MJD-OBS, PROJPm and RESTFREQ are still written before the function returns 0, leaving the cards for `Write` to remove. + `AIPSFromStore` writes CROTA whenever there is a pair of rotation axes, zero included; `AIPSPPFromStore` writes it only when it is not zero, and a CD matrix when the two estimates of CROTA disagree. + `AIPSPPFromStore` writes any LONPOLE and LATPOLE stored, 180 degrees included. + RESTFREQ is written only with a spectral axis; a spectral axis needs a SPECSYS of LSRK, LSRD, BARYCENT or GEOCENTR (not TOPOCENT) and units of Hz or m/s or a multiple of them. + DATE-OBS is formatted from MJD-OBS, and MJD-OBS is written only over a card the header already has (`fitschan.c` `AIPSFromStore`, `AIPSPPFromStore`). +- Rust: `aips_store_ok` and `write_to_cards`/`write_to_cards_pp` in `fitschan/enc_aips.rs` check every value before writing; `write_to_cards_pp` leaves out a LONPOLE of 180 degrees; `write_to_cards` writes RESTFREQ without a spectral axis and CROTA only with two or more axes; `translate_aips_spectral_write` writes TOPOCENT as `-OBS`; DATE-OBS comes from the store's date string. +- Java: as C (`FitsEncAips`). + +### `PROJPm` written by `AIPSPPFromStore` are not read back + +- C: `AIPSPPFromStore` writes the projection parameters of the latitude axis as `PROJPm`, but `SpecTrans` translates `PROJPm` to `PV_m` only for FITS-PC and FITS-IRAF (`fitschan.c` `SpecTrans`), so a FITS-AIPS++ header read as FITS-AIPS++ loses them. **C quirk**. +- Rust: as C. +- Java: as C. + +### The SIN check of `AIPSFromStore` + +- C: `AIPSFromStore` sets its status from the SIN projection parameters alone, overriding an earlier refusal for a missing CRVAL on a celestial axis; the description is then refused when CRVAL is written (`fitschan.c` `AIPSFromStore`). **C quirk** (no effect on the result). +- Rust: `aips_store_ok` in `fitschan/enc_aips.rs` combines the checks. +- Java: as C. + +### The cards a DSS read uses, and the sign of PLTDECSN + +- C: `DSSToStore` reads every keyword with `GetValue`, which marks the card it finds as used: the plate solution's keywords, and PLTSCALE, PPO1, PPO2, PPO4 and PPO5, read only so that they are not copied to another header. + A required keyword that is missing stops the read, the cards read before it marked (used if Clean is set, made available again otherwise). + The declination is negative only when the first word of PLTDECSN is `-` (`fitschan.c` `DSSToStore`). + The description has WCSAXES 2. +- Rust: `read_from_cards` in `fitschan/enc_dss.rs` does not read PLTSCALE, PPO1, PPO2, PPO4 or PPO5, so they stay unused; it takes the declination to be negative when PLTDECSN starts with `-` (so `-5` is negative where C's is positive); and it sets no WCSAXES. +- Java: as C (`FitsEncDss`). + +### `CLASSFromStore` with celestial pixel axes of one pixel + +- C: when the image has three or more pixel axes and both celestial pixel axes span one pixel, `CLASSFromStore` transforms pixel (1, 1, 1) with the FrameSet written and stores the celestial result as CRVAL, with CRPIX 1, before its other checks; `astTranN` is given three coordinates whatever the number of pixel and world axes, so a FrameSet with four pixel axes makes the write fail with `AST__NCPIN`. + It looks up the sizes of those pixel axes in `dim` at the indices of the celestial WCS axes (`fitschan.c` `CLASSFromStore`). **C quirk** (three coordinates for any FrameSet; WCS axis indices into the pixel dimensions). +- Rust: `class_store_ok` in `fitschan/enc_class.rs` reads the NAXIS cards for the rotation and LONPOLE checks but neither moves the reference point nor transforms anything, so it writes the reference point unchanged and reports no error for four axes. +- Java: as C (`FitsEncClass`), as far as C goes without a SpecFrame: every FrameSet of this library's classes is refused, as C refuses it, since only a SpecFrame gives SPECSYS. + ## Test harness ### Round trips where C's own recorded inverse fails @@ -509,3 +788,9 @@ Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follow - C: the transform-oracle checker has no exception for rows whose recorded inverse does not round-trip. - Rust: `test_transform_oracle.rs` excuses them. - Java: as Rust, pinned to the affected rows by `RTRIP_REFERENCE_GAPS_LICENSED`. + +### `roundtrip` of `testfitschan.c` when the current Frames do not align + +- C: `roundtrip` compares the pixel coordinates after a round trip through the first FrameSet and back through the second when `astConvert` finds no conversion between the two current Frames, and its sky System block (errors 500-534) accepts a write an encoding refuses. +- Rust: `roundtrip` in `test_fitschan_c_inline.rs` expects the current Frames to align and has no fallback, and `sky_systems_through_five_encodings` accepts either outcome of each write. +- Java: `FitsChanCInlineTest.roundtrip` is C's, fallback included, and each sky System and encoding expects the outcome C gives (FK4-NO-E and ICRS refused by FITS-AIPS and FITS-AIPS++, Supergalactic by FITS-IRAF, FITS-AIPS and FITS-AIPS++). diff --git a/docs/superpowers/plans/2026-11-15-pure-java-ast-phase3-fitschan-write.md b/docs/superpowers/plans/2026-11-15-pure-java-ast-phase3-fitschan-write.md new file mode 100644 index 0000000..f356d18 --- /dev/null +++ b/docs/superpowers/plans/2026-11-15-pure-java-ast-phase3-fitschan-write.md @@ -0,0 +1,239 @@ +# Pure-Java AST Phase 3 (FitsChan Writing and Encodings) Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. +> Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** `FitsChan.write()` writes FrameSets of the classes this library has as FITS-WCS, NATIVE, FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and DSS cards, and `FitsChan.read()` reads the FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and DSS encodings, as C does. + +**Architecture:** Port the Rust port's FitsChan write path (`crates/starlink-ast/src/fitschan/`: `wcs_write/`, `fset_to_store/`, `enc_*.rs`, `sip_int_world.rs`) onto the phase 1 read side (`FitsStore`, `FitsCardList`, `FitsSpecTrans`, `FitsWcsRead`), taking from C (`reference/starlink-ast/src/fitschan.c`) every part whose Rust structure follows from Rust's ownership rules (listed under Shared Design). +The FitsStore is built from a FrameSet (`FsetToStore`) and then turned into cards by one writer per encoding (`WcsFromStore`, `PCFromStore`, ...); the reads of the other encodings reuse the FITS-WCS read with their keyword translations. +C's `wcsconv/cases.txt` rows and the Rust port's C-probe oracles are the gates, checked both ways through the deferred lists. + +**Tech Stack:** as phases 1 and 2: Java 8 (`--release 8`), Maven, JUnit 5, Jackson (test scope), Error Prone, Checkstyle, PMD, Spotless; JDK 21 to build. + +**Spec:** `docs/superpowers/specs/2026-11-02-pure-java-ast-design.md` ("Later phases", item 2). +The phase 1 plan's Shared Design and the phase 2 plan's rulings (`docs/reports/2026-11-13-phase2-rulings.md`) still apply where this plan does not change them. + +## Global Constraints + +- Every Global Constraint of the phase 1 plan applies unchanged (Java 8, no runtime dependencies, jniast signatures, C at `3d3f255f`, `default` and final `else` throw `AST__INTER`, `MODERN-JAVA` tags, no heuristics the original lacks, expected values from C only, share where C calls `astClone` and copy where C calls `astCopy`, British spelling, one sentence per line in Markdown). +- `FitsChan.write` keeps its jniast signature and return value; nothing else public is added. +- Before porting, read Rust `docs/porting-hazards.md` (H2, H5, H8, H11) and `docs/issues/c-library-quirks.md` entries 592, 1527, 1970, 2304, 2411-2575, 2916, 3280 and 3876, and the Rust repo's `docs/audits/fitschan-c-parity.md`. +- Rust comments cite an older `fitschan.c`; find each C function by name in the pinned `fitschan.c`, not by the line number a Rust comment gives. +- Branches needing a class outside this library (SpecFrame, DSBSpecFrame, SpecMap, GrismMap, MathMap, LutMap, FitsTable, TranMap) are not ported; each place C or Rust reaches one throws `UnsupportedOperationException` whose message ends `needs ` (the convention `Deferred.unavailableReason` reads), except where C itself finds no such Mapping in a FrameSet of this library's classes, which is ported as C behaves (for example `SpectralAxes` finding no SpecFrame). +- Output must match C's cards, card order and comments: the `wcsconv` gate compares written cards with C's within 4 units in the last place. + +## Review Focus + +1. A write that fails (the encoding cannot describe the FrameSet, or Strict and a warning) returns C's value and leaves the FitsChan's cards, card order and current card exactly as before the call (C `FixNew`) (test in Task 6). +2. Writing a FrameSet and reading the cards back gives a FrameSet that transforms as the original, within the `headers.oracle` tolerance, for every in-scope header and every encoding that accepted it (test in Task 6, extended in Tasks 7 to 9). +3. A FrameSet that needs a class this library lacks (a non-linear axis that would need `-LOG`, a table that would need `-TAB` with TabOK set) makes `write` return C's failure value or throw `UnsupportedOperationException` naming the class, never another exception (test in Task 4). +4. Cards written into a FitsChan that already holds cards go where C puts them (before the card that was current when the write began) and the existing cards keep their order (test in Task 6). +5. Two threads writing copies of one FrameSet into their own FitsChans get identical cards (test in Task 6). + +--- + +## Shared Design + +### Where the code goes + +- Java file names follow the Rust module they port, prefixed `Fits` as on the read side: `FitsWcsWrite` (`wcs_write/mod.rs`), `FitsPlaneStores` (`plane_stores.rs`), `FitsFsetToStore` (`fset_to_store/mod.rs`), `FitsCelestialAxes`, `FitsSkySys`, `FitsSkyPole`, `FitsOtherAxes`, `FitsIsMapLinear`, `FitsWorldAxes`, `FitsMakeIntWorld`, `FitsInvertable`, `FitsOrth`, `FitsWcsDecompose`, `FitsSipIntWorld`, `FitsNativeWriter` (the write half of `enc_native.rs`), `FitsEncPc`, `FitsEncIraf`, `FitsEncAips`, `FitsEncDss`, `FitsEncClass` (refusal only, Task 9); `AnalysePoly` and `ScalePolyInputs` go beside the Mapping helpers (`MappingHelpers` or their own package-private classes). +- The phase 1 `FitsStore` is the store; the writers fill the fields it already has. +- Every new class and method is package-private. + +### Taken from C rather than Rust + +Each of these is a place where the Rust code's structure follows from its ownership rules; Java follows C's structure (phase 2 ruling: Java objects are shared references as C's are): + +1. Alternate descriptions: C's `AddVersion` works on the caller's FrameSet by base and current Frame index, not on a cloned FrameSet with its current Frame set. +2. The offset-sky absolute description: C clears SkyRefIs on the caller's FrameSet and restores it with `astSetC` (`AddVersion`), through FrameSet integrity, as Java's FrameSet already supports. +3. `MakeFitsFrameSet` builds a new two-Frame FrameSet from copies of the pixel Frame, the WCS Frame and the Mapping, as C does. +4. The writers receive the FitsChan and the FrameSet as C's do (`CLASSFromStore` gets `fs`; `GetCDMatrix` is called, not passed in), so CLASS's adjustments stay inside the CLASS writer. +5. Warnings are inserted at the cursor as C's `Warn` raises them. +6. Mappings are assembled by sharing components where C clones them, so `IsSimp` records fall as C's do. +7. The store is indexed by version letter as C's is, if that is what the `wcsconv` gate needs for C's card order (the SIP block is written inside C's version loop); otherwise the read side's layout is kept and the ledger records it. + +The NATIVE write follows Rust's walk over a `NativeNode` tree, since the Java Channel already renders `NativeNode`s; C's overrides of the Channel `Write*` methods give the same cards. + +### Gates and deferred lists + +- `WcsconvTest` (C's `wcsconv/cases.txt`): a row written with an encoding this phase adds must match C's output; the reason `out-of-scope method FitsChan.write` disappears, rows needing an absent class keep `needs `, and FITS-CLASS rows keep their class reasons. +- `TransformOracleTest` with `deferred/headers.txt`: the FITS-IRAF, FITS-PC, FITS-AIPS and DSS headers that need no absent class read and transform as C. +- New C-probe oracle tests, each converted from the Rust repo's `tests/_oracle/cases.rs` with the existing `CasesToJson` (as phase 1 did): `FitsChanEncodingsOracleTest`, `FitsChanSipokOracleTest`, `SkyPoleOracleTest` (already exists for read; extend), `FitsChanSplitmapOracleTest`, `FitsChanAltNaxesOracleTest`, `FitsChanAltEpochOracleTest`. + Cases needing an absent class are listed in each test as phase 1's oracle tests list them, checked both ways. +- `deferred/rust-tests.txt` entries `out-of-scope method FitsChan.write` and the read entries for the encodings added here are translated by the task that makes them possible. + +--- + +### Task 1: The write entry and the NATIVE encoding + +**Files:** +- Create: `FitsNativeWriter.java` +- Modify: `FitsChan.java` (`write`, from Rust `mod.rs` `write`/`write_inner`/`write_attrs`/`store_keyword_native`; C `Write`, `FitsFromStore`, `FindWcs`, `CreateKeyword`, `MakeBanner`, `MakeIndentedComment`, `MakeIntoComment`, `PreQuote`) +- Test: `FitsChanNativeWriteTest` (new), `WcsconvTest`, `FitsChanTest` + +**Interfaces:** +- Produces: `int FitsChan.write(AstObject)` dispatching on Encoding; for any encoding but NATIVE, a package-private hook `boolean writeForeign(FrameSet fs, FitsChan.Encoding enc)` that returns false (C's failure) until Task 6 fills it; the card-rollback scope (`FitsCardList.fixNew`) around every write. + +- [ ] **Step 1: Write the failing tests:** the Rust `test_fitschan.rs` tests `native_round_trip_*`, `native_rewind_and_reread` (listed `out-of-scope method FitsChan.write` in `rust-tests.txt`); the 30 unit tests of `enc_native.rs` that exercise this library's classes; in `WcsconvTest`, every `native` row whose input this library reads must now match C's cards (the reason for such rows becomes the read's reason or nothing). +- [ ] **Step 2: Run** `mvn test -Dtest='FitsChanNativeWriteTest,FitsChanTest,WcsconvTest'` — Expected: FAIL. +- [ ] **Step 3: Implement.** The keyword sequence follows C's `CreateKeyword` with the FitsChan's persistent sequence counters and skips keywords already present (quirk 2575); a nested Object without comments gets the `" ="` card (H11). +- [ ] **Step 4: Rewrite `wcsconv.txt`** with `-Dast.writeDeferred=true`; read the diff: only `native` rows may leave the list, and none may be added. +- [ ] **Step 5: Run** the step 2 tests and the full suite — Expected: PASS. +- [ ] **Step 6: Commit** — `git commit -m "Port FitsChan's write entry and the NATIVE encoding"` + +### Task 2: Intermediate world coordinates and linear axes + +**Files:** +- Create: `FitsMakeIntWorld.java` (`make_int_world.rs`; C `MakeIntWorld`, `NearestPix`), `FitsIsMapLinear.java` (C `IsMapLinear`), `FitsWorldAxes.java` (C `WorldAxes`), `FitsInvertable.java` (C `MakeInvertable`), `FitsOrth.java` (C `OrthVector`, `OrthVectorSet`), `FitsWcsDecompose.java` (C `FindBasisVectors`, `MakeBasisVectors`, `FitLine`, `FitOK`) +- Test: one test class per created class, translating that Rust module's unit tests + +**Interfaces:** +- Produces: `static MatrixMap FitsMakeIntWorld.makeIntWorld(Mapping cmap, Frame fr, int[] wperm, char s, FitsStore store, double[] dim, FitsChan fc)` returning C's result (null where C returns NULL), and the helpers' static methods named after their C functions (`isMapLinear`, `worldAxes`, `makeInvertable`, `orthVector`, `orthVectorSet`, `findBasisVectors`, `fitLine`), whose signatures follow the C functions with Java arrays for C's pointer outputs. + +- [ ] **Step 1: Write the failing tests:** each module's Rust unit tests, with their hand-derived expectations; `IsMapLinear` far from zero (quirk 2469). +- [ ] **Step 2: Run** them — Expected: FAIL. +- [ ] **Step 3: Implement.** Port `FindBasisVectors`/`FitLine` (hazard H5), not a fitting loop. +- [ ] **Step 4: Run** them and the full suite — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "Port MakeIntWorld and the linear-axis helpers of FitsChan writing"` + +### Task 3: Celestial axes + +**Files:** +- Create: `FitsCelestialAxes.java` (C `CelestialAxes`, `SplitMap`, `SplitMap2`; not the `-TAB` branch), `FitsSkySys.java` (C `SkySys`, `IsSkyOff`, `TDBConv` through TimeFrame, hazard H8), `FitsSkyPole.java` (C `SkyPole`; reuses `FitsNativePole.wcsNatPole`) +- Modify: `FitsFiducial.java` (C `GetFiducialWCS`) +- Test: `FitsCelestialAxesTest`, `FitsSkySysTest`, `FitsSkyPoleTest` translating the Rust unit tests (29 for `sky_sys`) + +**Interfaces:** +- Consumes: Task 2's `makeIntWorld`. +- Produces: `static boolean FitsCelestialAxes.celestialAxes(...)` with C's arguments and result; `FitsSkySys.skySys(...)`, `FitsSkyPole.skyPole(...)`, `FitsFiducial.getFiducialWcs(...)`. + +- [ ] **Step 1: Write the failing tests.** +- [ ] **Step 2: Run** — Expected: FAIL. +- [ ] **Step 3: Implement**; the `-TAB` branch throws `UnsupportedOperationException` ending `needs LutMap` when TabOK is set and C would take it. +- [ ] **Step 4: Run** them and the full suite — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "Port the celestial axes of FitsChan writing"` + +### Task 4: FrameSet to store + +**Files:** +- Create: `FitsFsetToStore.java` (C `FsetToStore`, `AddVersion`, `MakeFitsFrameSet`, `FitsAxisOrder`, `FindLonLatSpecAxes`, CRPIX snapping and CRVAL rounding as Rust's `fset_to_store/mod.rs` has them), `FitsPlaneStores.java` (`plane_stores.rs`), `FitsOtherAxes.java` (C `OtherAxes`, linear branch) +- Test: `FitsFsetToStoreTest`, `FitsOtherAxesTest`, `FitsWriteUnsupportedTest` + +**Interfaces:** +- Consumes: Tasks 2 and 3. +- Produces: `static boolean FitsFsetToStore.fsetToStore(FitsChan fc, FrameSet fs, int naxis, double[] dim, FitsChan.Encoding enc, String method, String cls)` filling the store C's `FsetToStore` fills; C's `SpectralAxes` path for a FrameSet with no SpecFrame (no spectral axes found). + +- [ ] **Step 1: Write the failing tests:** the unit tests of `fset_to_store/mod.rs` and `other_axes.rs` that need no absent class; `FitsWriteUnsupportedTest.aNonLinearAxisNeedingLogIsUnsupported` (a FrameSet whose non-celestial axis is a non-linear PolyMap with a non-zero CRVAL: `write` throws `UnsupportedOperationException` ending `needs MathMap`, or returns C's failure value if C's `OtherAxes` fails before reaching `LogAxis`; read `OtherAxes` to decide and record it) and `aTableWithTabOkIsUnsupported` (TabOK = 1 and an axis C would describe with `-TAB`: ends `needs LutMap`). +- [ ] **Step 2: Run** — Expected: FAIL. +- [ ] **Step 3: Implement**, following "Taken from C rather than Rust" items 1 to 3, 6 and 7; C's warning-method order quirk (1527) is kept. +- [ ] **Step 4: Run** them and the full suite — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "Port FsetToStore"` + +### Task 5: The SIP building blocks + +**Files:** +- Create: `FitsSipIntWorld.java` (C `SIPIntWorld`, with its nout fix as quirk 3280 records), `AnalysePoly.java` (C `AnalysePoly`), `ScalePolyInputs.java` (C `ScalePolyInputs`) +- Test: `FitsSipIntWorldTest`, `AnalysePolyTest`, `ScalePolyInputsTest`, translating the unit tests of `sip_int_world.rs`, `analyse_poly.rs` and `scale_poly_inputs.rs` + +**Interfaces:** +- Consumes: Task 2's `makeIntWorld`. +- Produces: `static MatrixMap FitsSipIntWorld.sipIntWorld(...)` with C's arguments and result (null where C returns NULL), filling the store's SIP orders and coefficient arrays; `AnalysePoly.analysePoly(...)` and `ScalePolyInputs.scalePolyInputs(...)` with C's arguments. + +- [ ] **Step 1: Write the failing tests.** +- [ ] **Step 2: Run** — Expected: FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** them and the full suite — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "Port SIPIntWorld, AnalysePoly and ScalePolyInputs"` + +### Task 6: Writing FITS-WCS + +**Files:** +- Create: `FitsWcsWrite.java` (`wcs_write/mod.rs`; C `WcsFromStore`, with the SIP block written where C writes it, inside the version loop; SipOK applies only to FITS-WCS, quirk 2558) +- Modify: `FitsChan.java` (`writeForeign` for FITS-WCS; C's `GetCDMatrix` saving and restoring the current card, quirk 2446) +- Test: `WcsconvTest`, new `FitsChanWriteTest`, new `FitsChanSipokOracleTest` (the 21 C-probe cases; the non-FITS-WCS encodings' cases are listed until Tasks 7 to 9), new `SkyPoleOracleTest` write cases, `FitsChanSplitmapOracleTest`, `FitsChanAltNaxesOracleTest`, `FitsChanAltEpochOracleTest`, `FitsChanEncodingsOracleTest` (FITS-WCS column) + +**Interfaces:** +- Consumes: Task 4's `fsetToStore`; Task 5's `sipIntWorld`; Task 1's `writeForeign` hook. +- Produces: `static void FitsWcsWrite.wcsFromStore(FitsChan fc, FitsStore store, ...)`, the date helpers C uses (`mjd_to_date_str`). + +- [ ] **Step 1: Write the failing tests:** + - The C-probe oracle tests named above (convert each Rust `cases.rs` to JSON with `CasesToJson`), FITS-WCS cases only in `FitsChanEncodingsOracleTest` for now, cases needing an absent class listed and checked both ways. + - In `FitsChanWriteTest`: + - `aFailedWriteLeavesTheCardsAsTheyWere`: a FitsChan holding 5 cards with the 3rd current; writing a FrameSet FITS-WCS cannot describe (C: `write` returns 0); afterwards the same 5 cards in the same order, the 3rd current. + - `strictWriteFailsAndLeavesTheCards`: as above with Strict set and a FrameSet that raises a warning. + - `cardsAreWrittenBeforeTheCurrentCard`: a FitsChan with cards A, B, C, B current; after a successful write the new cards lie between A and B, and A, B, C keep their order. + - `everyInScopeHeaderRoundTrips`: each `headers.oracle` FITS-WCS header the read side accepts, read, written FITS-WCS into a new FitsChan, read back: transforms its oracle inputs within the oracle tolerance. + - `threadsWriteCopiesIdentically`: 4 threads write `copy()`s of the FrameSet read from `sip.head` into their own FitsChans; all card lists are identical. + - In `WcsconvTest`, the `fits-wcs` rows in scope match C. +- [ ] **Step 2: Run** — Expected: FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Rewrite `wcsconv.txt`** and read the diff (rows only leave). +- [ ] **Step 5: Run** the tests and the full suite — Expected: PASS. +- [ ] **Step 6: Commit** — `git commit -m "Write FrameSets as FITS-WCS"` + +### Task 7: FITS-PC and FITS-IRAF + +**Files:** +- Create: `FitsEncPc.java` (C `PCFromStore`; alternates as `Cxxx`), `FitsEncIraf.java` (C `IRAFFromStore`) +- Modify: `FitsSpecTrans.java` (the PC and IRAF translations: RADECSYS/LONGPOLE renaming, PROJP to PV, `Cnxxx`, the CDjjjiii branch; remove the refusal at its lines 166-176 for these two), `FitsChan.java` (`readForeign` and `writeForeign` for them) +- Test: `TransformOracleTest` (`headers.txt` IRAF and PC rows), `WcsconvTest` (`fits-pc`, `fits-iraf` rows and `native` rows whose input is a PC or IRAF header), `FitsChanEncodingsOracleTest` (PC and IRAF columns), the `rust-tests.txt` entries for reading these encodings, the PC and IRAF unit tests of `enc_pc.rs` and `enc_iraf.rs` (writers only; their `read_from_cards` is dead code and is not ported) + +- [ ] **Step 1: Write the failing tests**; in `FitsChanWriteTest`, extend `everyInScopeHeaderRoundTrips` to these two encodings. +- [ ] **Step 2: Run** — Expected: FAIL. +- [ ] **Step 3: Implement**, with the C fixes the Rust writers follow (quirks 2458, 2483). +- [ ] **Step 4: Rewrite `wcsconv.txt` and `headers.txt`**; run the tests and the full suite — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "Read and write FITS-PC and FITS-IRAF"` + +### Task 8: FITS-AIPS and FITS-AIPS++ + +**Files:** +- Create: `FitsEncAips.java` (C `AIPSFromStore`, `AIPSPPFromStore`) +- Modify: `FitsChan.java` (`readForeign` no longer refuses AIPS and AIPS++; `writeForeign` for them) +- Test: as Task 7 for these encodings (`headers.txt` AIPS rows cobe, CAR_model, cmap_3years; `fits-aips` and `fits-aips++` `wcsconv` rows; the `enc_aips.rs` unit tests that need no SpecFrame) + +- [ ] **Step 1: Write the failing tests**; extend `everyInScopeHeaderRoundTrips` to these encodings. +- [ ] **Step 2: Run** — Expected: FAIL. +- [ ] **Step 3: Implement**; spectral branches are reached only through a SpecFrame, which a FrameSet of this library cannot hold. +- [ ] **Step 4: Rewrite the lists**; run the tests and the full suite — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "Read and write FITS-AIPS and FITS-AIPS++"` + +### Task 9: DSS, and FITS-CLASS's refusal + +**Files:** +- Create: `FitsEncDss.java` (C `DSSToStore`, `DSSFromStore`; a TPN WcsMap, no DssMap, Rust quirk note 409), `FitsEncClass.java` (C `CLASSFromStore` as far as its refusal of a FrameSet with no spectral axis) +- Modify: `FitsChan.java` (DSS read with its mark handling, DSS write; FITS-CLASS write) +- Test: `WcsconvTest` (`dss_ast_dss`, `dss_fits-dss_ast`), `headers.txt` DSS rows if any, `FitsChanEncodingsOracleTest` (DSS and CLASS columns: CLASS cases of FrameSets without a spectral axis expect C's refusal), `FitsChanSipokOracleTest` CLASS rows, the `enc_dss.rs` unit tests + +- [ ] **Step 1: Write the failing tests.** +- [ ] **Step 2: Run** — Expected: FAIL. +- [ ] **Step 3: Implement.** Reading FITS-CLASS stays unavailable: every CLASS header needs SpecFrame and DSBSpecFrame. +- [ ] **Step 4: Rewrite the lists**; run the tests and the full suite — Expected: PASS. +- [ ] **Step 5: Commit** — `git commit -m "Read and write DSS, and refuse FITS-CLASS as C does"` + +### Task 10: The remaining write tests + +**Files:** +- Test: translations of the in-scope tests of Rust `test_fitschan_wcs_write.rs` (14, less the spectral and SplineMap ones), `test_fitschan_c_inline.rs` (its write tests from `testfitschan.c`), and the write tests deferred in `test_fitschan_astwarn.rs` and `test_fitschan_cursor_oracle.rs` +- Modify: whatever the tests show is missing + +- [ ] **Step 1: Translate** the tests and remove their `rust-tests.txt` entries. +- [ ] **Step 2: Run** — Expected: they pass, or fail on a gap; fix each gap with the C source and record it. +- [ ] **Step 3: Full suite** — Expected: PASS. +- [ ] **Step 4: Commit** — `git commit -m "Translate the remaining FitsChan write tests"` + +### Task 11: Sweep the deferred lists + +- [ ] **Step 1: Rewrite every list** with `mvn test -Dast.writeDeferred=true` and read each diff. + Expected: no entry reads `out-of-scope method FitsChan.write`; the remaining encoding reasons are FITS-CLASS reading only; every other remaining reason names an absent class; nothing added; `rg UNEXPLAINED src/test/resources/deferred` prints nothing. +- [ ] **Step 2: Run `mvn verify`** — Expected: BUILD SUCCESS; record the count. +- [ ] **Step 3: Run on JDK 27** — `mvn test -Djvm=/opt/homebrew/opt/openjdk/bin/java` — Expected: PASS. +- [ ] **Step 4: Commit** if anything changed — `git commit -m "Clear the deferrals FitsChan writing resolves"` + +### Task 12: The phase 3 report + +**Files:** +- Create: `docs/reports/-phase3-report.md`, `docs/reports/-phase3-rulings.md` + +- [ ] **Step 1: Write the report** in phase 2's form: what was ported (lines per task), the gate counts (wcsconv rows by encoding and reason, headers, oracle cases), every tolerance or excuse added or removed, C defects found (in `docs/rust-c-differences.md`), and every ledger ruling in the rulings file. +- [ ] **Step 2: Commit** — `git commit -m "Report phase 3"` diff --git a/src/main/java/uk/ac/starlink/ast/AnalysePoly.java b/src/main/java/uk/ac/starlink/ast/AnalysePoly.java new file mode 100644 index 0000000..50f0bff --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/AnalysePoly.java @@ -0,0 +1,208 @@ +package uk.ac.starlink.ast; + +/** + * C's {@code AnalysePoly} (fitschan.c): the analysis of a 2-input, 2-output PolyMap into a shift + * of origin, a polynomial meeting the requirements of the SIP convention, and a linear + * transformation. + * + *

Ported from Rust {@code mappings/helpers/analyse_poly.rs}, following fitschan.c. + */ +final class AnalysePoly { + + private AnalysePoly() {} + + /** + * Analyses {@code polymap} into three Mappings which, applied in series, are equivalent to it: + * a ShiftMap holding any shift of origin; a PolyMap with no constant terms whose linear terms + * are an unscaled copy of the corresponding input, as the SIP convention needs; and a UnitMap, + * or a MatrixMap holding any scaling or rotation. Only a PolyMap with an iterative inverse can + * be analysed. + * + *

The shift is found by transforming the origin with the iterative inverse. The PolyMap + * with that shift merged in, {@code pm1}, has linear terms {@code a*x0 + b*x1} and {@code c*x0 + * + d*x1} on its two outputs. If they are the unit matrix, {@code pm1} itself is the middle + * Mapping. Otherwise, if their determinant is not zero, the higher terms {@code f} and {@code + * g} of the two outputs become {@code (d*f - b*g)/det} and {@code (a*g - c*f)/det}, each after + * a unit linear term, and the PolyMap made from them is simplified. The Invert attribute of + * {@code polymap} is cleared while it is analysed, and set again afterwards if it was set. + * + * @param polymap the PolyMap + * @param maps an array of at least three elements, which receives the three Mappings, or nulls + * if the PolyMap cannot be analysed + * @return whether the PolyMap was analysed + * @throws AstException with status {@code AST__INTER} if {@code polymap} does not have two + * inputs and two outputs + */ + static boolean analysePoly(PolyMap polymap, Mapping[] maps) { + maps[0] = null; + maps[1] = null; + maps[2] = null; + + // A PolyMap whose inverse is defined by coefficients would need a merge of a MatrixMap + // into it, which C does not have. + if (!polymap.getIterInverse()) { + return false; + } + + if (polymap.getNin() != 2 || polymap.getNout() != 2) { + throw Ast.err( + AstException.AST__INTER, + "AnalysePoly(fitschan): AST internal error; the supplied PolyMap is not 2-in, 2-out (internal AST" + + " programming error)."); + } + + // With Invert cleared, the forward transformation is the one defined by coefficients. + boolean inverted = polymap.getInvert(); + if (inverted) { + polymap.clearInvert(); + } + Mapping map1; + Mapping map2 = null; + Mapping map3 = null; + try { + // The input position the PolyMap takes to the origin; map1 shifts it to the origin. + double[][] origin = polymap.tran2(1, new double[] {0.0}, new double[] {0.0}, false); + double[] shift = {origin[0][0], origin[1][0]}; + shift[0] *= -1.0; + shift[1] *= -1.0; + ShiftMap shiftMap = new ShiftMap(shift); + map1 = shiftMap; + + // pm1, with polymap equivalent to map1 followed by pm1, has no constant terms. + shiftMap.invert(); + PolyMap pm1; + try { + pm1 = polymap.mergeShift(shiftMap, true, true); + } finally { + shiftMap.invert(); + } + + double[] coeffsF = pm1.polyCoeffs(true); + int ncoeffF = coeffsF.length / 4; + + // The linear terms y0 = a*x0 + b*x1 + f(x0, x1) and y1 = c*x0 + d*x1 + g(x0, x1), and + // the number of quadratic or higher terms. + double a = 0.0; + int aIco = -1; + double b = 0.0; + int bIco = -1; + double c = 0.0; + int cIco = -1; + double d = 0.0; + int dIco = -1; + int nhigh = 0; + for (int ico = 0; ico < ncoeffF; ico++) { + int pv = 4 * ico; + if (coeffsF[pv + 1] == 1) { + if (coeffsF[pv + 2] == 1 && coeffsF[pv + 3] == 0) { + a = coeffsF[pv]; + aIco = ico; + } else if (coeffsF[pv + 2] == 0 && coeffsF[pv + 3] == 1) { + b = coeffsF[pv]; + bIco = ico; + } else { + nhigh++; + } + } else { + if (coeffsF[pv + 2] == 1 && coeffsF[pv + 3] == 0) { + c = coeffsF[pv]; + cIco = ico; + } else if (coeffsF[pv + 2] == 0 && coeffsF[pv + 3] == 1) { + d = coeffsF[pv]; + dIco = ico; + } else { + nhigh++; + } + } + } + + double det = a * d - b * c; + + if (a == 1.0 && b == 0.0 && c == 0.0 && d == 1.0) { + map3 = new UnitMap(2); + map2 = pm1; + } else if (det != 0.0) { + map3 = new MatrixMap(2, 2, MatrixMap.FULL, new double[] {a, b, c, d}); + + // w0 = 1*x0 + f'(x0, x1) and w1 = 1*x1 + g'(x0, x1), with f' = (d*f - b*g)/det + // and g' = -(c*f - a*g)/det. C sets the output index of the next group before + // testing whether a coefficient is used, past the end of its array after the + // last group; it is set here only for a group that is used. + double[] coeffsNew = new double[4 * (2 * nhigh + 2)]; + int pw = 0; + coeffsNew[pw] = 1.0; + coeffsNew[pw + 1] = 1; + coeffsNew[pw + 2] = 1; + coeffsNew[pw + 3] = 0; + pw += 4; + for (int ico = 0; ico < ncoeffF; ico++) { + int pv = 4 * ico; + if (coeffsF[pv] != 0.0 && ico != aIco && ico != bIco && ico != cIco && ico != dIco) { + coeffsNew[pw + 1] = 1; + if (coeffsF[pv + 1] == 1) { + coeffsNew[pw] = d * coeffsF[pv] / det; + } else { + coeffsNew[pw] = -b * coeffsF[pv] / det; + } + coeffsNew[pw + 2] = coeffsF[pv + 2]; + coeffsNew[pw + 3] = coeffsF[pv + 3]; + pw += 4; + } + } + + coeffsNew[pw] = 1.0; + coeffsNew[pw + 1] = 2; + coeffsNew[pw + 2] = 0; + coeffsNew[pw + 3] = 1; + pw += 4; + for (int ico = 0; ico < ncoeffF; ico++) { + int pv = 4 * ico; + if (coeffsF[pv] != 0.0 && ico != aIco && ico != bIco && ico != cIco && ico != dIco) { + coeffsNew[pw + 1] = 2; + if (coeffsF[pv + 1] == 1) { + coeffsNew[pw] = -c * coeffsF[pv] / det; + } else { + coeffsNew[pw] = a * coeffsF[pv] / det; + } + coeffsNew[pw + 2] = coeffsF[pv + 2]; + coeffsNew[pw + 3] = coeffsF[pv + 3]; + pw += 4; + } + } + + // Simplifying amalgamates coefficients that refer to the same powers. + PolyMap tmap = new PolyMap(2, 2, 2 * nhigh + 2, coeffsNew, 0, null); + map2 = tmap.simplify(); + if (polymap.testIterInverse() || polymap.testNiterInverse() || polymap.testTolInverse()) { + ScalePolyInputs.copyIterInverse(polymap, asPolyMap(map2)); + } + } + } finally { + if (inverted) { + polymap.setInvert(true); + } + } + + if (map2 == null || map3 == null) { + return false; + } + maps[0] = map1; + maps[1] = map2; + maps[2] = map3; + return true; + } + + /** + * {@code map} as a PolyMap, for setting a PolyMap attribute on it; C's {@code astCheckPolyMap} + * reports any other class as an invalid object. + * + * @throws AstException with status {@code AST__OBJIN} if {@code map} is not a PolyMap + */ + private static PolyMap asPolyMap(Mapping map) { + if (map instanceof PolyMap) { + return (PolyMap) map; + } + throw Ast.err( + AstException.AST__OBJIN, "Pointer to PolyMap required, but pointer to " + map.astClass() + " given."); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/AstObject.java b/src/main/java/uk/ac/starlink/ast/AstObject.java index e995795..f9484e6 100644 --- a/src/main/java/uk/ac/starlink/ast/AstObject.java +++ b/src/main/java/uk/ac/starlink/ast/AstObject.java @@ -360,8 +360,16 @@ public static int tune(String name, int value) { * space. */ static boolean chrMatch(String a, String b) { - int n = Math.max(a.length(), b.length()); - for (int i = 0; i < n; i++) { + return chrMatchN(a, b, Integer.MAX_VALUE); + } + + /** + * C's {@code astChrMatchN}: whether the first {@code n} characters of two strings are equal + * ignoring case and trailing white space. + */ + static boolean chrMatchN(String a, String b, int n) { + int len = Math.min(Math.max(a.length(), b.length()), n); + for (int i = 0; i < len; i++) { boolean ea = i >= a.length(); boolean eb = i >= b.length(); boolean match = (ea && CScan.isCSpace(b.charAt(i))) diff --git a/src/main/java/uk/ac/starlink/ast/FitsCard.java b/src/main/java/uk/ac/starlink/ast/FitsCard.java index f59d6ce..2782d16 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsCard.java +++ b/src/main/java/uk/ac/starlink/ast/FitsCard.java @@ -256,12 +256,19 @@ static final class Flags { /** Added during the current axis-description pass of a write, C's {@code NEW2}. */ boolean newVersion; + /** + * A translation a read made of the header's cards: the card is in C's FitsChan of + * translations ({@code SpecTrans}'s {@code ret}), not in the header. + */ + boolean translation; + Flags copy() { Flags f = new Flags(); f.consumption = consumption; f.retained = retained; f.newWrite = newWrite; f.newVersion = newVersion; + f.translation = translation; return f; } diff --git a/src/main/java/uk/ac/starlink/ast/FitsCardList.java b/src/main/java/uk/ac/starlink/ast/FitsCardList.java index 20a28e1..d110691 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsCardList.java +++ b/src/main/java/uk/ac/starlink/ast/FitsCardList.java @@ -61,7 +61,7 @@ static final class Occurrence { /** Keywords recorded as consumed by the current read pass (C's {@code MarkCard} of a read). */ private List consumedNames = new ArrayList<>(); - /** The keywords {@link #setFloat} and {@link #setString} have written while recording, or null. */ + /** The keywords {@link #setTranslation} has written while recording, or null. */ private List writtenNames; /** Whether cards added now are flagged new, C's {@code mark_new}. */ @@ -381,17 +381,18 @@ String getStoredStringMarked(String keyword, int fitsrnd) { /** * The comment C's {@code WcsFcRead} stores for a CTYPE keyword: that of the last card not - * consumed with {@code keyword}, whether or not its value converts (fitschan.c:36848-36860), - * or null if there is none. + * consumed with {@code keyword} and a comment, whether or not its value converts + * (fitschan.c:36848-36860), since {@code SetItemC} ignores a card with none; null if there is + * none. */ String getStoredComment(String keyword) { - FitsCard last = null; + String com = null; for (FitsCard c : list) { - if (!c.isConsumed() && c.keyword.equalsIgnoreCase(keyword)) { - last = c; + if (!c.isConsumed() && c.keyword.equalsIgnoreCase(keyword) && c.cComment() != null) { + com = c.cComment(); } } - return last == null ? null : last.cComment(); + return com; } /** {@link #find}, recording the keyword as consumed when a card is found. */ @@ -403,7 +404,7 @@ FitsCard findMarked(String keyword) { return c; } - /** Starts recording the keywords {@link #setFloat} and {@link #setString} write. */ + /** Starts recording the keywords {@link #setTranslation} writes. */ void recordWrites() { writtenNames = new ArrayList<>(); } @@ -559,10 +560,14 @@ boolean deleteConsumed(String keyword) { return delete(keyword); } - /** Deletes the first card with {@code keyword}; whether there was one. */ + /** + * Deletes the first card with {@code keyword}, passing over translations, which are not in the + * header; whether there was one. + */ boolean delete(String keyword) { for (int idx = 0; idx < list.size(); idx++) { - if (list.get(idx).keyword.equalsIgnoreCase(keyword)) { + FitsCard c = list.get(idx); + if (!c.flags.translation && c.keyword.equalsIgnoreCase(keyword)) { list.remove(idx); if (pos > idx && pos > 0) { pos--; @@ -595,6 +600,18 @@ int position() { return pos; } + /** The position of {@code card}, this very card, or end-of-file if the list does not hold it. */ + // A card is found by identity, as C holds a pointer to it. + @SuppressWarnings("PMD.CompareObjectsWithEquals") + int indexOf(FitsCard card) { + for (int k = 0; k < list.size(); k++) { + if (list.get(k) == card) { + return k; + } + } + return list.size(); + } + /** * The keyword of the card at {@code index} and how many cards with it precede it, by which * {@link #occurrenceIndex} finds it again after other cards change; null at end-of-file. @@ -925,6 +942,87 @@ boolean searchCard(String name, String method) { return findKeyCard(name, method); } + /** + * C's {@code SearchCard} with used cards included (C's {@code ignore_used} zero), as C's + * {@code GetValue} uses it, which then restores the current card: the card after the current + * one if it has keyword {@code keyword} (ignoring case), otherwise the first card that has; + * null if there is none. The current card is not changed. + */ + FitsCard searchCardAnyUse(String keyword) { + if (pos + 1 < list.size() && list.get(pos + 1).cName().equalsIgnoreCase(keyword)) { + return list.get(pos + 1); + } + for (FitsCard c : list) { + if (c.cName().equalsIgnoreCase(keyword)) { + return c; + } + } + return null; + } + + /** + * C's {@code GetValue} (fitschan.c:18399): the value of the card with keyword {@code keyword} + * that {@link #searchCard} finds, passing over used cards, converted to {@code want} as C's + * {@code CnvValue} converts it with FitsRounding {@code fitsRounding}; with {@code mark}, a + * card whose value converts is marked as provisionally used (C's {@code MarkCard}). The + * current card is restored. Null if there is no such card or its value does not convert. + * + * @param report whether a missing card or a value that does not convert is an error + * @throws AstException with status {@code AST__BDFTS} for a missing card and {@code + * AST__FTCNV} for a value that does not convert, with {@code report}; {@code AST__FUNDEF} + * for a card with no value, which C's {@code CnvValue} reports whatever {@code report} + */ + FitsCardValue.Got getValue( + String keyword, + FitsCardValue.Want want, + boolean report, + boolean mark, + int fitsRounding, + String method, + String cls) { + int icard = getCard(); + try { + if (!searchCard(keyword, method)) { + if (report) { + throw Ast.err( + AstException.AST__BDFTS, + method + "(" + cls + "): Unable to find a value for FITS keyword \"" + keyword + "\"."); + } + return null; + } + FitsCard c = list.get(pos); + FitsCardValue.Got got = FitsCardValue.cnvType(c.value, want, fitsRounding, c.cName()); + if (got == null) { + if (report) { + throw Ast.err( + AstException.AST__FTCNV, + method + "(" + cls + "): Cannot convert FITS keyword '" + keyword + "' to " + want.cName() + + "."); + } + return null; + } + if (mark) { + markAt(pos); + } + return got; + } finally { + setCard(icard); + } + } + + /** + * C's {@code HasCard}: whether a card, consumed or not, has the keyword {@code keyword} + * exactly. + */ + boolean hasCard(String keyword) { + for (FitsCard c : list) { + if (c.keyword.equals(keyword)) { + return true; + } + } + return false; + } + /** Whether the list is at end-of-file. */ boolean atEof() { return pos >= list.size(); @@ -934,23 +1032,52 @@ private static String nullIfEmpty(String comment) { return comment.isEmpty() ? null : comment; } - /** Stores an integer as C's {@code SetValue}: overwriting a card with the keyword, or inserting. */ - void setInt(String keyword, long value, String comment) { - putOrAppend(new FitsCard(keyword.toUpperCase(Locale.ROOT), FitsCard.Value.ofInt(value), nullIfEmpty(comment))); - } - - /** Stores a floating value as {@link #setInt} stores an integer. */ - void setFloat(String keyword, double value, String comment) { + /** + * Stores a translation as C's {@code SpecTrans} stores one, with {@code SetValue} in its + * FitsChan of translations ({@code ret}), which C's {@code WcsToStore} reads after every card + * of the header: a translation with the keyword is replaced, keeping its comment as {@link + * #setValueAsWriter} keeps one at the FitsRounding of a new FitsChan, and otherwise the card + * follows the last card. The current card stays where it was, and the keyword is recorded as + * written. + * + * @throws AstException with status {@code AST__BDFTS} if a floating value is {@code AST__BAD}, + * as C's {@code SetValue} reports + */ + void setTranslation(String keyword, FitsCard.Value value, String comment) { + checkNotBad(keyword, value); noteWritten(keyword); - putOrAppend( - new FitsCard(keyword.toUpperCase(Locale.ROOT), FitsCard.Value.ofFloat(value), nullIfEmpty(comment))); + FitsCard card = new FitsCard(keyword.toUpperCase(Locale.ROOT), value, null); + card.flags.translation = true; + String com = commentToStore(value, comment); + int found = -1; + for (int k = 0; k < list.size(); k++) { + FitsCard c = list.get(k); + if (c.flags.translation && c.keyword.equals(card.keyword)) { + found = k; + break; + } + } + if (found >= 0) { + card.comment = trimComment(keptComment(list.get(found), value, com, NEW_FITS_ROUNDING)); + list.set(found, card); + } else { + card.comment = trimComment(com); + boolean eof = pos >= list.size(); + list.add(card); + if (eof) { + pos = list.size(); + } + } } - /** Stores a string as {@link #setInt} stores an integer. */ - void setString(String keyword, String value, String comment) { - noteWritten(keyword); - putOrAppend( - new FitsCard(keyword.toUpperCase(Locale.ROOT), FitsCard.Value.ofString(value), nullIfEmpty(comment))); + /** The translation {@link #setTranslation} stored for {@code keyword}, or null. */ + FitsCard findTranslation(String keyword) { + for (FitsCard c : list) { + if (c.flags.translation && c.keyword.equalsIgnoreCase(keyword)) { + return c; + } + } + return null; } /** @@ -968,11 +1095,26 @@ void positionWriteCursor() { } /** - * Stores a card as C's {@code SetValue} does: overwriting a card with the same keyword (the card - * after the current one, else the first, used or not), which keeps its comment if the value is - * unchanged, or else inserting the card in front of the current card. + * C's {@code SetValue} as the writers of the foreign encodings call it, with the comment rules + * of C's {@code SetFits} and {@code astSetFits}: a card with keyword {@code keyword} (the + * card after the current one, else the first, consumed or not) is replaced, and otherwise the + * card is inserted in front of the current card; the current card is the same card after + * either. + * + *

The comment of a string equal to the value is dropped. A card replaced keeps its comment + * when the new card has none, or when its value, converted to the type of the new value as C's + * {@code CnvValue} converts it (with {@code fitsRounding}), is the same as the new value: equal + * integers or logical values, floating values equal to C's {@code astEQUAL}, or strings that + * C's {@code Similar} finds alike. + * + * @throws AstException with status {@code AST__BDFTS} if a floating value is {@code AST__BAD}, + * as C's {@code SetValue} reports; {@code AST__FUNDEF} if the card replaced has an + * undefined value, which C's {@code CnvValue} reports */ - private void putOrAppend(FitsCard card) { + void setValueAsWriter(String keyword, FitsCard.Value value, String comment, int fitsRounding) { + checkNotBad(keyword, value); + String com = commentToStore(value, comment); + FitsCard card = new FitsCard(keyword.toUpperCase(Locale.ROOT), value, null); if (markNew) { card.flags.newWrite = true; card.flags.newVersion = true; @@ -989,19 +1131,138 @@ private void putOrAppend(FitsCard card) { } } if (found >= 0) { - FitsCard old = list.get(found); - if (old.comment != null && valuesSimilar(old.value, card.value)) { - card.comment = old.comment; - } - // SetValue (fitschan.c:28510) leaves the current card as it was. + card.comment = trimComment(keptComment(list.get(found), value, com, fitsRounding)); list.set(found, card); } else { + card.comment = trimComment(com); int at = Math.min(pos, list.size()); list.add(at, card); pos = at + 1; } } + /** The FitsRounding of a new FitsChan, such as C's FitsChan of translations. */ + private static final int NEW_FITS_ROUNDING = 10; + + /** C's {@code SetValue} refusal of a floating value of {@code AST__BAD}. */ + private static void checkNotBad(String keyword, FitsCard.Value value) { + if (value.kind == FitsCard.Kind.FLOAT && value.d == AstObject.AST__BAD) { + throw Ast.err( + AstException.AST__BDFTS, + "astWrite(FitsChan): The required FITS keyword \"" + keyword + "\" is indeterminate."); + } + } + + /** The comment C's {@code SetFits} stores with {@code value}: none if blank or, for a string, equal to the value. */ + private static String commentToStore(FitsCard.Value value, String comment) { + if (comment == null || FitsCard.isBlank(comment)) { + return null; + } + return value.kind == FitsCard.Kind.STRING && comment.equals(value.s) ? null : comment; + } + + /** + * The comment a card replacing {@code old} gets: {@code old}'s when {@code com} is null, or when + * {@code old}'s value, converted as C's {@code CnvValue} converts it, is the same as {@code + * value}; otherwise {@code com}. + */ + private static String keptComment(FitsCard old, FitsCard.Value value, String com, int fitsRounding) { + FitsCardValue.Got got = FitsCardValue.cnvType(old.value, want(value.kind), fitsRounding, old.cName()); + if (com == null || (got != null && old.comment != null && sameValue(got, value))) { + return old.comment; + } + return com; + } + + /** A comment trimmed as C's {@code NewCard} trims one, or null if none is left. */ + private static String trimComment(String com) { + return com == null ? null : nullIfEmpty(FitsCard.trim(com)); + } + + /** The type C's {@code CnvValue} converts a card's value to, to compare it with {@code kind}. */ + private static FitsCardValue.Want want(FitsCard.Kind kind) { + // MODERN-JAVA(21): switch expression + switch (kind) { + case INT: + return FitsCardValue.Want.INT; + case KINT: + return FitsCardValue.Want.KINT; + case FLOAT: + return FitsCardValue.Want.FLOAT; + case STRING: + return FitsCardValue.Want.STRING; + case LOGICAL: + return FitsCardValue.Want.LOGICAL; + case COMPLEX_FLOAT: + return FitsCardValue.Want.COMPLEXF; + case COMPLEX_INT: + return FitsCardValue.Want.COMPLEXI; + default: + throw Ast.err(AstException.AST__INTER, "SetValue(FitsChan): unexpected card type " + kind + "."); + } + } + + /** Whether a value converted for comparison is the same as {@code value}, as C's {@code SetFits} compares them. */ + private static boolean sameValue(FitsCardValue.Got got, FitsCard.Value value) { + // MODERN-JAVA(21): switch expression + switch (value.kind) { + case INT: + case KINT: + return got.i == value.i; + case FLOAT: + return MappingHelpers.astEqual(got.d, value.d); + case STRING: + return similar(got.s, value.s); + case LOGICAL: + return got.b == value.b; + case COMPLEX_FLOAT: + return MappingHelpers.astEqual(got.d, value.d) && MappingHelpers.astEqual(got.dIm, value.dIm); + case COMPLEX_INT: + return got.i == value.i && got.iIm == value.iIm; + default: + throw Ast.err(AstException.AST__INTER, "SetFits(FitsChan): unexpected card type " + value.kind + "."); + } + } + + /** + * C's {@code Similar}: whether two strings are alike, ignoring case, leading and trailing + * blanks, and any blank after a blank. C compares the strings only up to the last character + * before the last that is not blank, so two strings that differ only in that character are + * alike (C-library quirk, kept). Two blank strings, for which C reads past the end of both, are + * alike. + */ + static boolean similar(String str1, String str2) { + int ea = FitsCard.trimEnd(str1).length() - 1; + int eb = FitsCard.trimEnd(str2).length() - 1; + if (ea < 0 && eb < 0) { + return true; + } + int a = 0; + int b = 0; + boolean ss = true; + while (true) { + while (a < ea && str1.charAt(a) == ' ' && ss) { + a++; + } + while (b < eb && str2.charAt(b) == ' ' && ss) { + b++; + } + if ((a < ea && b == eb) || (a == ea && b < eb)) { + return false; + } else if (b == eb && a == ea) { + return true; + } + char ca = a < str1.length() ? str1.charAt(a) : '\0'; + char cb = b < str2.length() ? str2.charAt(b) : '\0'; + if (Character.toLowerCase(ca) != Character.toLowerCase(cb)) { + return false; + } + ss = ca == ' '; + a++; + b++; + } + } + /** * Parses header text, one card per line; a line that cannot be read as a card is left out. A * card whose keyword name holds an illegal character, or whose value cannot be typed, is @@ -1070,57 +1331,41 @@ static List lines(String text) { // WCS keywords // ------------------------------------------------------------------ - private static boolean allDigits(String s) { - for (int k = 0; k < s.length(); k++) { - char c = s.charAt(k); - if (c < '0' || c > '9') { - return false; - } - } - return true; - } - - private static boolean allDigitsOr(String s, char extra) { - for (int k = 0; k < s.length(); k++) { - char c = s.charAt(k); - if ((c < '0' || c > '9') && c != extra) { - return false; - } - } - return true; - } - - private static boolean isUpper(char c) { - return c >= 'A' && c <= 'Z'; - } - - private static final Set FINDWCS_ALT = new HashSet<>(java.util.Arrays.asList( - "LONPOLE", "LATPOLE", "EQUINOX", "RADESYS", "RESTFRQ", "WCSNAME", "SPECSYS", "SSYSSRC", "ZSOURCE", - "VELOSYS", "MJD_AVG")); - - private static final Set FINDWCS_EXACT = new HashSet<>(java.util.Arrays.asList( + /** The templates of the keywords C's {@code FindWcs} recognises as describing WCS, in its order. */ + private static final List FINDWCS_TEMPLATES = java.util.Arrays.asList( + "CRVAL%d%0c", + "CRPIX%d%0c", + "CDELT%d%0c", + "CROTA%d", + "CTYPE%d%0c", + "CUNIT%d%0c", + "PC%3d%3d%0c", + "CD%3d%3d%0c", + "CD%1d_%1d%0c", + "PC%1d_%1d%0c", "LONGPOLE", - "LONPOLE", - "LATPOLE", + "LONPOLE%0c", + "LATPOLE%0c", + "PROJP%d", + "PV%d_%d%0c", + "PS%d_%d%0c", "EPOCH", - "EQUINOX", + "EQUINOX%0c", "MJD-OBS", "DATE-OBS", "TIMESYS", "RADECSYS", - "RADESYS", - "WCSNAME", - "SPECSYS", - "SSYSSRC", - "ZSOURCE", - "VELOSYS", - "RESTFRQ", - "MJD_AVG", - "OBSGEO-X", - "OBSGEO-Y", - "OBSGEO-Z", + "RADESYS%0c", + "C%1dVAL%d", + "C%1dPIX%d", + "C%1dELT%d", + "C%1dYPE%d", + "C%1dNIT%d", "CNPIX1", "CNPIX2", + "PPO%d", + "AMDX%d", + "AMDY%d", "XPIXELSZ", "YPIXELSZ", "PLTRAH", @@ -1134,123 +1379,29 @@ private static boolean isUpper(char c) { "PPO1", "PPO2", "PPO4", - "PPO5")); + "PPO5", + "WCSNAME%0c", + "SPECSYS%0c", + "SSYSSRC%0c", + "ZSOURCE%0c", + "VELOSYS%0c", + "RESTFRQ%0c", + "MJD_AVG%0c", + "OBSGEO-X", + "OBSGEO-Y", + "OBSGEO-Z"); /** - * Whether a keyword is one of those C's {@code FindWcs} (fitschan.c:10904-10960) recognises as - * describing WCS, which places the cards a write adds and which {@code astPurgeWCS} removes. + * Whether a keyword is one of those C's {@code FindWcs} recognises as describing WCS, which + * places the cards a write adds and which {@code astPurgeWCS} removes: one matching a template + * of {@link #FINDWCS_TEMPLATES}, as C's {@code Match} matches it. */ static boolean isFindWcsKeyword(String keyword) { - String kw = keyword.toUpperCase(Locale.ROOT); - String bare = kw; - if (!kw.isEmpty() && isUpper(kw.charAt(kw.length() - 1))) { - String stripped = kw.substring(0, kw.length() - 1); - if (FINDWCS_ALT.contains(stripped)) { + for (String template : FINDWCS_TEMPLATES) { + if (FitsMatch.matchKeyword(keyword, template, 0) != null) { return true; } } - if (FINDWCS_EXACT.contains(bare)) { - return true; - } - if (kw.length() >= 6) { - String prefix5 = kw.substring(0, 5); - if ("CRPIX".equals(prefix5) - || "CRVAL".equals(prefix5) - || "CDELT".equals(prefix5) - || "CTYPE".equals(prefix5) - || "CUNIT".equals(prefix5)) { - boolean ok = true; - for (int k = 5; k < kw.length(); k++) { - char c = kw.charAt(k); - if (!(c >= '0' && c <= '9') && !isUpper(c)) { - ok = false; - break; - } - } - if (ok) { - return true; - } - } - if (kw.startsWith("CROTA")) { - return true; - } - } - if ((kw.startsWith("CD") || kw.startsWith("PC")) && kw.length() >= 4) { - String rest = kw.substring(2); - if ((rest.indexOf('_') >= 0 && allDigitsOr(rest, '_')) || allDigits(rest)) { - return true; - } - } - if ((kw.startsWith("PV") || kw.startsWith("PS")) && kw.length() >= 4) { - String rest = kw.substring(2); - if (rest.indexOf('_') >= 0 && allDigitsOr(rest, '_')) { - return true; - } - } - if (kw.startsWith("PROJP") || kw.startsWith("AMDX") || kw.startsWith("AMDY")) { - return true; - } - if (kw.startsWith("PPO") && kw.length() >= 4 && allDigits(kw.substring(3))) { - return true; - } - if (kw.length() >= 5 && kw.charAt(0) == 'C' && kw.charAt(1) >= '0' && kw.charAt(1) <= '9') { - String suffix = kw.substring(2); - return suffix.startsWith("VAL") - || suffix.startsWith("PIX") - || suffix.startsWith("ELT") - || suffix.startsWith("YPE") - || suffix.startsWith("NIT"); - } return false; } - - /** - * Whether two values are the same for keeping a comment on overwrite, as C's {@code SetFits} - * compares them (fitschan.c:15744): strings ignoring case and trailing spaces, floating values - * with C's {@code EQUAL}, others exactly. - */ - // MODERN-JAVA(21): a switch over a sealed Value hierarchy. - private static boolean valuesSimilar(FitsCard.Value a, FitsCard.Value b) { - if (a.kind != b.kind) { - return false; - } - switch (a.kind) { - case STRING: - return FitsCard.trimEnd(a.s).equalsIgnoreCase(FitsCard.trimEnd(b.s)); - case FLOAT: - return floatsSimilar(a.d, b.d); - case INT: - case KINT: - return a.i == b.i; - case LOGICAL: - return a.b == b.b; - case COMPLEX_FLOAT: - return floatsSimilar(a.d, b.d) && floatsSimilar(a.dIm, b.dIm); - case COMPLEX_INT: - return a.i == b.i && a.iIm == b.iIm; - default: - return false; - } - } - - /** - * C's {@code EQUAL} macro (object.h): {@code fabs(a - b) <= 1.0E5 * max((|a| + |b|) * - * DBL_EPSILON, DBL_MIN)}. - */ - private static boolean floatsSimilar(double a, double b) { - if (a == b) { - return true; - } - double scale = (Math.abs(a) + Math.abs(b)) * Math.ulp(1.0); - return Math.abs(a - b) <= 1.0e5 * Math.max(scale, Double.MIN_NORMAL); - } - - /** - * Stores a value of any type as {@link #setFloat} stores a floating value: C's {@code SetValue} - * given the data and type of another card, as {@code SpecTrans} copies a QVi_m card to PVi_m. - */ - void setValue(String keyword, FitsCard.Value value, String comment) { - noteWritten(keyword); - putOrAppend(new FitsCard(keyword.toUpperCase(Locale.ROOT), value, nullIfEmpty(comment))); - } } diff --git a/src/main/java/uk/ac/starlink/ast/FitsCelestialAxes.java b/src/main/java/uk/ac/starlink/ast/FitsCelestialAxes.java new file mode 100644 index 0000000..e86be9c --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsCelestialAxes.java @@ -0,0 +1,620 @@ +package uk.ac.starlink.ast; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * The celestial axes of a FITS-WCS description being written: C's {@code CelestialAxes}, {@code + * SplitMap} and {@code SplitMap2} (fitschan.c). + * + *

Ported from Rust {@code fitschan/fset_to_store/celestial_axes.rs}, following fitschan.c. + * Describing celestial axes with the {@code -TAB} algorithm needs a FitsTable, which this library + * does not have. + */ +final class FitsCelestialAxes { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** C's {@code AST__DD2R}: degrees to radians. */ + private static final double AST__DD2R = 0.017453292519943295; + + /** C's {@code AST__DR2D}: radians to degrees. */ + private static final double AST__DR2D = 57.29577951308232; + + /** C's {@code WCSLIB_MXPAR}: the number of projection parameters searched. */ + private static final int WCSLIB_MXPAR = 100; + + /** C's {@code AST__DBL_DIG}: the significant digits C's {@code %.*g} gives a double. */ + private static final int AST__DBL_DIG = 17; + + private FitsCelestialAxes() {} + + /** + * A Mapping split about its projection, as C's {@code SplitMap} and {@code SplitMap2} return + * it in {@code map1}, {@code map2} and {@code map3}. + */ + static final class Split { + /** The Mappings before the projection, from pixel to intermediate world coordinates. */ + final Mapping map1; + + /** The WcsMap with FITSProj set. */ + final WcsMap map2; + + /** The Mappings after the projection, from native spherical to world coordinates. */ + final Mapping map3; + + Split(Mapping map1, WcsMap map2, Mapping map3) { + this.map1 = map1; + this.map2 = map2; + this.map3 = map3; + } + } + + /** + * C's {@code CelestialAxes}: finds the celestial axes of the current Frame of {@code fs}, and + * if the pixel to world Mapping describes them with a projection stores the FITS-WCS values + * describing them other than CRPIX, PC and CDELT (CRVAL, the projection parameters, CTYPE, + * CNAME, RADESYS, EQUINOX, MJD-OBS, LONPOLE, LATPOLE and the others {@link FitsSkySys#skySys} + * stores), and returns the Mapping from the current Frame to intermediate world coordinates, + * which embodies the rest. That Mapping has an output for every current Frame axis, and passes + * the non-celestial axes unchanged. + * + *

The projection is the one {@link #splitMap} finds, unless the FitsChan's ForceTab is set. + * With FitsAxisOrder {@code }, when the rotation from world to intermediate world + * coordinates exchanges the celestial axes (a LONPOLE of 90 degrees, for example), their FITS + * axes, and the CRVAL, CTYPE, CNAME and projection parameters stored for them, are exchanged + * to keep each intermediate world axis close to the pixel axis of the same number. + * + * @param fc the FitsChan + * @param fs the FrameSet, whose base Frame is pixel coordinates and current Frame world + * coordinates + * @param dim the number of pixels along each pixel axis, {@code AST__BAD} where unknown + * @param wperm the zero-based FITS axis describing each current Frame axis; the celestial + * axes' are exchanged if their intermediate world axes are + * @param s the coordinate version character + * @param store the store + * @param axisDone a flag for each current Frame axis, set for each celestial axis + * @param isoff as {@link FitsSkySys#skySys} takes it + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return the Mapping from the current Frame to intermediate world coordinates for the + * celestial axes, or a UnitMap if they cannot be described + * @throws UnsupportedOperationException if C would describe the celestial axes with the {@code + * -TAB} algorithm (TabOK positive, no projection or ForceTab set, and axes {@link + * FitsMapTab#isMapTab2D} can tabulate), which needs FitsTable + */ + static Mapping celestialAxes( + FitsChan fc, + FrameSet fs, + double[] dim, + int[] wperm, + char s, + FitsStore store, + boolean[] axisDone, + int isoff, + String method, + String cls) { + Mapping ret = null; + Frame wcsfrm = fs.getFrame(FrameSet.AST__CURRENT); + int nwcs = fs.getNout(); + + // The celestial axes of the WCS Frame, and the SkyFrame they belong to; MakeFitsFrameSet + // ensures there is at most one SkyFrame. + SkyFrame skyfrm = null; + int ilon = -1; + int ilat = -1; + int[] paxis = new int[1]; + for (int iax = 0; iax < nwcs; iax++) { + Frame pframe = wcsfrm.primaryFrame(iax + 1, paxis); + if (FitsMakeIntWorld.isASkyFrame(pframe)) { + if (skyfrm == null) { + skyfrm = (SkyFrame) pframe; + } + if (paxis[0] == 1) { + ilon = iax; + } else { + ilat = iax; + } + axisDone[iax] = true; + } + } + + if (ilon != -1 && ilat != -1) { + int fitsIlon = wperm[ilon]; + int fitsIlat = wperm[ilat]; + + // The projection plane coordinates of the fiducial point. + double[] ppcfid = new double[nwcs]; + + Mapping map = + fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT).simplify(); + + // The table version for the -TAB algorithm: TabOK, if positive. + int extver = fc.getTabOK(); + + Split split = fc.getForceTab() == 0 ? splitMap(map, map.getInvert(), ilon, ilat) : null; + if (split != null) { + WcsMap map2 = split.map2; + Mapping map3 = split.map3; + + // The axes of latitude and longitude within the SkyFrame, which may be permuted. + int skylataxis = skyfrm.getLatAxis() - 1; + int skylonaxis = skyfrm.getLonAxis() - 1; + + // The reference point: the fiducial point in native spherical coordinates + // transformed to world coordinates by map3. + double[] fid = FitsFiducial.getFiducialWcs(map2, map3, ilon, ilat); + if (fid != null) { + double[] skyfid = new double[2]; + skyfid[skylonaxis] = fid[0]; + skyfid[skylataxis] = fid[1]; + + // The longitude and latitude outputs of the WcsMap, which permutations in + // map3 may make differ from ilon and ilat. + int axlon = map2.getWcsAxis(1) - 1; + int axlat = map2.getWcsAxis(2) - 1; + + // CRVAL, normalised, in degrees. + if (zeroAng(skyfid[0])) { + skyfid[0] = 0.0; + } + if (zeroAng(skyfid[1])) { + skyfid[1] = 0.0; + } + skyfrm.norm(skyfid); + store.crval[fitsIlon] = AST__DR2D * skyfid[skylonaxis]; + store.crval[fitsIlat] = AST__DR2D * skyfid[skylataxis]; + + // The projection parameters, except 3 and 4 of the longitude axis, which hold + // LONPOLE and LATPOLE, unless the projection is TPN, whose parameters are + // polynomial terms. + boolean tpn = map2.getWcsType() == WcsMap.AST__TPN; + for (int m = 0; m < WCSLIB_MXPAR; m++) { + if (map2.testPV(axlon, m) && (m < 3 || m > 4 || tpn)) { + double pv = map2.getPV(axlon, m); + if (pv != AST__BAD) { + store.setPv(fitsIlon, m, pv); + } + } + if (map2.testPV(axlat, m)) { + double pv = map2.getPV(axlat, m); + if (pv != AST__BAD) { + store.setPv(fitsIlat, m, pv); + } + } + } + + // A non-zero PVi_0 on the longitude axis shifts projection plane coordinates + // to intermediate world coordinates by those of the fiducial point, so that + // CRPIX maps onto CRVAL (FITS-WCS paper II); not for TPN. + if (!tpn && map2.getPV(axlon, 0) != 0.0) { + double[] ppc = FitsFiducial.getFiducialPpc(map2); + ppcfid[ilon] = ppc[0]; + ppcfid[ilat] = ppc[1]; + if (ppcfid[ilon] == AST__BAD) { + ppcfid[ilon] = 0.0; + } + if (ppcfid[ilat] == AST__BAD) { + ppcfid[ilat] = 0.0; + } + ppcfid[ilon] *= AST__DR2D; + ppcfid[ilat] *= AST__DR2D; + } + + FitsSkySys.skySys( + fc, skyfrm, 1, map2.getWcsType(), store, fitsIlon, fitsIlat, s, isoff, method, cls); + FitsSkyPole.skyPole(map2, map3, ilon, ilat, wperm, s, store, method, cls); + + // WcsNative prefers parameters 3 and 4 of the longitude axis to the LONPOLE + // and LATPOLE just stored, so they are cleared in a copy (except for TPN). + WcsMap map2b; + if (map2.getWcsType() != WcsMap.AST__TPN) { + map2b = (WcsMap) map2.copy(); + map2b.clearPV(axlon, 3); + map2b.clearPV(axlon, 4); + } else { + map2b = map2; + } + + // The Mapping from intermediate world coordinates to world coordinates: the + // shift to projection plane coordinates, degrees to radians on the celestial + // axes, the projection, and the rotation to celestial coordinates. + Mapping tmap0 = new ShiftMap(ppcfid); + double[] mat = new double[nwcs]; + Arrays.fill(mat, 1.0); + mat[ilon] = AST__DD2R; + mat[ilat] = AST__DD2R; + Mapping tmap1 = new MatrixMap(nwcs, nwcs, mat); + Mapping tmap2 = FitsWcsCelestial.wcsNative(store, map2b, fitsIlon, fitsIlat, null, method, cls); + Mapping tmap3 = new CmpMap(map2b, tmap2, true); + + // A UnitMap for WCS axes beyond those of the projection. + int nwcsmap = map3.getNin(); + if (nwcsmap < nwcs) { + tmap3 = new CmpMap(tmap3, new UnitMap(nwcs - nwcsmap), false); + nwcsmap = nwcs; + } + + // Between two PermMaps selecting the axes, when a PermMap in the pixel to + // world Mapping selects a subset or superset of the WCS axes, or permutes the + // celestial ones. + if (nwcsmap != nwcs || ilon != axlon || ilat != axlat) { + tmap3 = permuted(tmap3, nwcs, nwcsmap, ilon, ilat, axlon, axlat); + } + + // The Mapping from world to intermediate world coordinates. + Mapping tmap4 = new CmpMap(tmap0, tmap1, true); + ret = new CmpMap(tmap4, tmap3, true); + ret.invert(); + + // With the axis order chosen automatically, the FITS axes of the celestial + // axes are exchanged if the pixel to intermediate world Mapping exchanges + // them. + if (AstObject.chrMatch(fc.getFitsAxisOrder(), "")) { + Mapping pixToIwc = CmpMap.transientCmpMap(map, ret, true); + int[] tperm = new int[nwcs]; + if (!FitsWorldAxes.worldAxes(fc, pixToIwc, dim, tperm)) { + ret = null; + } + if (ret != null && fitsIlon == tperm[ilat] && fitsIlat == tperm[ilon]) { + wperm[ilon] = fitsIlat; + wperm[ilat] = fitsIlon; + swapAxes(store, fitsIlon, fitsIlat); + } + } + } + + } else if (extver > 0) { + // The -TAB algorithm, if the axes can be tabulated. C takes any FitsTable already in + // the store, which a write of this library's Mappings never holds (only a -TAB axis + // makes one). + int[] icolmainlon = new int[1]; + int[] icolmainlat = new int[1]; + int[] icolindexlon = new int[1]; + int[] icolindexlat = new int[1]; + int[] mlon = new int[1]; + int[] mlat = new int[1]; + int[] interplon = new int[1]; + int[] interplat = new int[1]; + Mapping tmap0 = FitsMapTab.isMapTab2D( + map, + AST__DR2D, + "deg", + wcsfrm, + dim, + ilon, + ilat, + fitsIlon, + fitsIlat, + icolmainlon, + icolmainlat, + icolindexlon, + icolindexlat, + mlon, + mlat, + interplon, + interplat); + if (tmap0 != null) { + // C goes on to store the table's details, and the table, in its FitsTable. + throw new UnsupportedOperationException(method + "(" + cls + + "): describing celestial axes with the -TAB algorithm needs FitsTable"); + } + } + } + + if (ret != null) { + return ret.simplify(); + } + return new UnitMap(nwcs); + } + + /** + * {@code tmap3}, with {@code nwcsmap} inputs and outputs, between a PermMap from the {@code + * nwcs} WCS axes, taking WCS axes {@code ilon} and {@code ilat} to the WcsMap's {@code axlon} + * and {@code axlat} and the rest in order, and its inverse. + */ + private static Mapping permuted(Mapping tmap3, int nwcs, int nwcsmap, int ilon, int ilat, int axlon, int axlat) { + int[] inperm = new int[nwcs]; + int[] outperm = new int[nwcsmap]; + + // The WcsMap's longitude and latitude axes are the WCS Frame's; the rest are assigned in + // turn, the WcsMap being a UnitMap on them. + Arrays.fill(inperm, -1); + inperm[ilon] = axlon; + inperm[ilat] = axlat; + int iax = 0; + for (int i = 0; i < nwcs; i++) { + while (iax == axlon || iax == axlat) { + iax++; + } + if (inperm[i] == -1) { + inperm[i] = iax++; + } + } + + Arrays.fill(outperm, -1); + outperm[axlon] = ilon; + outperm[axlat] = ilat; + iax = 0; + for (int i = 0; i < nwcsmap; i++) { + while (iax == ilon || iax == ilat) { + iax++; + } + if (outperm[i] == -1) { + outperm[i] = iax++; + } + } + + PermMap pm = PermMap.fromInternal(nwcs, inperm, nwcsmap, outperm, new double[] {AST__BAD}); + Mapping tmap4 = new CmpMap(pm, tmap3, true); + pm.invert(); + return new CmpMap(tmap4, pm, true); + } + + /** + * Exchanges the CRVAL values, and the projection parameters up to the highest stored, of FITS + * axes {@code a} and {@code b}, and their CTYPE and CNAME values when both are set. + */ + private static void swapAxes(FitsStore store, int a, int b) { + Double val = store.crval[b]; + store.crval[b] = store.crval[a]; + store.crval[a] = val; + + String cval = store.ctype[b]; + if (cval != null && store.ctype[a] != null) { + store.ctype[b] = store.ctype[a]; + store.ctype[a] = cval; + } + + cval = store.cname[b]; + if (cval != null && store.cname[a] != null) { + store.cname[b] = store.cname[a]; + store.cname[a] = cval; + } + + int maxm = store.maxPvM(); + for (int m = 0; m <= maxm; m++) { + val = pv(store, b, m); + store.setPv(b, m, pv(store, a, m)); + store.setPv(a, m, val); + } + } + + /** Projection parameter {@code m} of FITS axis {@code i}, null when not stored. */ + private static Double pv(FitsStore store, int i, int m) { + return m < store.pv[i].length ? store.pv[i][m] : null; + } + + /** C's {@code ZEROANG}: an angle less than 1.0E-9 in magnitude. */ + private static boolean zeroAng(double a) { + return Math.abs(a) < 1.0e-9; + } + + /** + * C's {@code SplitMap}: {@code map}, applied with Invert value {@code invert}, as three + * Mappings in series, the second an inverted WcsMap with FITSProj set, with no such WcsMap in + * the others. Failing that, a linear Mapping is given a CAR projection, with a ShiftMap moving + * the origin of the longitude axis of intermediate world coordinates to the pixel origin (the + * latitude axis cannot be moved, since readers before FITS-WCS could not handle the rotation + * that would need); and a Mapping whose celestial outputs {@code ilon} and {@code ilat} are + * constant is given the Mappings of a TAN header with those values at its reference point. + * + * @return the three Mappings, or null if none of these applies + */ + static Split splitMap(Mapping map, boolean invert, int ilon, int ilat) { + Split ret = null; + Split split = splitMap2(map, invert); + if (split != null + && split.map2.getInvert() + && splitMap2(split.map1, split.map1.getInvert()) == null + && splitMap2(split.map3, split.map3.getInvert()) == null) { + ret = split; + } + + // A linear Mapping: a CAR projection. + if (ret == null && map.isLinear()) { + int nwcs = map.getNout(); + int npix = map.getNin(); + double[][] iwc = map.transform(new double[npix][1], 1, true); + double[] iwcOrigin = new double[nwcs]; + for (int i = 0; i < nwcs; i++) { + iwcOrigin[i] = i != ilon ? 0.0 : iwc[i][0] * -1; + } + Mapping mapa = new ShiftMap(iwcOrigin); + Mapping map1 = new CmpMap(map, mapa, true); + WcsMap map2 = new WcsMap(nwcs, WcsMap.AST__CAR, ilon + 1, ilat + 1); + map2.setInvert(true); + mapa.invert(); + ret = new Split(map1, map2, mapa); + } + + // Constant celestial outputs: two pixel positions with the same good longitude and + // latitude. + if (ret == null) { + int npix = map.getNin(); + double[][] ptr1 = new double[npix][2]; + for (int i = 0; i < npix; i++) { + ptr1[i][0] = 1.0; + ptr1[i][1] = 1000.0; + } + double[][] ptr2 = map.transform(ptr1, 2, true); + if (ptr2[ilon][0] == ptr2[ilon][1] + && ptr2[ilon][0] != AST__BAD + && ptr2[ilat][0] == ptr2[ilat][1] + && ptr2[ilat][0] != AST__BAD) { + ret = constantSplit(map, ilon, ilat, ptr2[ilon][0], ptr2[ilat][0]); + } + } + return ret; + } + + /** + * The Mappings of C's {@code SplitMap} for a Mapping {@code map} whose outputs {@code ilon} + * and {@code ilat} are the constants {@code lon} and {@code lat}: those of a FITS-WCS header, + * read by a FitsChan, describing a TAN projection with them at its reference point, the + * keywords that do not affect them given arbitrary values; the Mapping before the projection + * is {@code map} followed by a ShiftMap subtracting the constants, giving zero on the + * celestial axes. Null if the header gives no FrameSet. + */ + private static Split constantSplit(Mapping map, int ilon, int ilat, double lon, double lat) { + int nwcs = map.getNout(); + FitsChan fc = new FitsChan(); + for (int i = 0; i < nwcs; i++) { + fc.putFits("CRPIX" + (i + 1) + " = 0", false); + fc.putFits("CDELT" + (i + 1) + " = 0.0003", false); + if (i == ilon) { + fc.putFits("CTYPE" + (i + 1) + " = 'RA---TAN'", false); + } else if (i == ilat) { + fc.putFits("CTYPE" + (i + 1) + " = 'DEC--TAN'", false); + } else { + fc.putFits("CTYPE" + (i + 1) + " = 'DUMMY'", false); + } + if (i == ilon) { + fc.putFits( + "CRVAL" + (i + 1) + " = " + CFormat.format("%." + AST__DBL_DIG + "g", AST__DR2D * lon), false); + } else if (i == ilat) { + fc.putFits( + "CRVAL" + (i + 1) + " = " + CFormat.format("%." + AST__DBL_DIG + "g", AST__DR2D * lat), false); + } else { + fc.putFits("CRVAL" + (i + 1) + " = 0.0", false); + } + } + fc.cards().clearCard(); + AstObject tfs = fc.read(); + if (tfs == null) { + return null; + } + Mapping tmap2 = ((FrameSet) tfs).getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Split tsplit = splitMap(tmap2, tmap2.getInvert(), 0, 1); + if (tsplit == null) { + // C goes on to annul the null pre-projection Mapping SplitMap gave, which is an error. + throw Ast.err( + AstException.AST__INTER, + "SplitMap(FitsChan): AST internal error; no projection found in a TAN header."); + } + double[] w1 = new double[nwcs]; + w1[ilon] = -lon; + w1[ilat] = -lat; + Mapping map1 = new CmpMap(map, new ShiftMap(w1), true); + return new Split(map1, tsplit.map2, tsplit.map3); + } + + /** + * C's {@code SplitMap2}: {@code map}, applied with Invert value {@code invert}, as three + * Mappings in series, the second a WcsMap with FITSProj set, inverted or not; the others may + * hold WcsMaps without FITSProj. A CmpMap is searched through its Mappings in series or in + * parallel, any combination of the two, the first WcsMap found being used. For a WcsMap found + * in parallel with other Mappings, a WcsMap of the same projection, with as many axes as the + * parallel Mappings have outputs, its longitude and latitude axes and projection parameters + * moved to the WcsMap's place among them, is made, and is inverted whatever the Invert value + * of the WcsMap found; it has none of that WcsMap's other attributes. + * + *

A CmpMap with Ident set, which C's {@code astMapList} gives back whole for either + * decomposition, is taken to hold no WcsMap: C searches it again without end. + * + * @return the three Mappings, copies of those in {@code map}, the first and last UnitMaps + * where there are none; or null if no WcsMap with FITSProj set is found + */ + static Split splitMap2(Mapping map, boolean invert) { + String cls = map.astClass(); + if ("CmpMap".equals(cls)) { + List maps = new ArrayList<>(); + List inverts = new ArrayList<>(); + map.mapList(true, invert, maps, inverts); + if (maps.size() > 1) { + return splitSeries(map, invert, maps, inverts); + } + maps.clear(); + inverts.clear(); + map.mapList(false, invert, maps, inverts); + @SuppressWarnings({"ReferenceEquality", "PMD.CompareObjectsWithEquals"}) + boolean whole = maps.size() == 1 && maps.get(0) == map; + if (whole) { + return null; + } + return splitParallel(maps, inverts); + } else if ("WcsMap".equals(cls) && ((WcsMap) map).getFITSProj()) { + int naxes = map.getNin(); + WcsMap map2 = (WcsMap) map.copy(); + map2.setInvert(invert); + return new Split(new UnitMap(naxes), map2, new UnitMap(naxes)); + } + return null; + } + + /** {@link #splitMap2} for a CmpMap {@code map} that is {@code maps} in series. */ + private static Split splitSeries(Mapping map, boolean invert, List maps, List inverts) { + Mapping map1 = invert == map.getInvert() ? new UnitMap(map.getNin()) : new UnitMap(map.getNout()); + WcsMap map2 = null; + Mapping map3 = null; + for (int imap = 0; imap < maps.size(); imap++) { + if (map2 == null) { + Split sub = splitMap2(maps.get(imap), inverts.get(imap)); + Mapping mapa; + if (sub != null) { + mapa = sub.map1; + map2 = sub.map2; + map3 = sub.map3; + } else { + mapa = copyWithInvert(maps.get(imap), inverts.get(imap)); + } + map1 = new CmpMap(map1, mapa, true); + } else { + map3 = new CmpMap(map3, copyWithInvert(maps.get(imap), inverts.get(imap)), true); + } + } + return map2 == null ? null : new Split(map1, map2, map3); + } + + /** {@link #splitMap2} for a CmpMap that is {@code maps} in parallel. */ + private static Split splitParallel(List maps, List inverts) { + Mapping map1 = null; + Mapping map3 = null; + WcsMap mapb = null; + int axis = 0; + int wcsaxis = -1; + for (int imap = 0; imap < maps.size(); imap++) { + Split sub = mapb == null ? splitMap2(maps.get(imap), inverts.get(imap)) : null; + Mapping mapa; + Mapping mapc; + if (sub != null) { + mapb = sub.map2; + wcsaxis = axis; + mapa = sub.map1; + mapc = sub.map3; + } else { + mapa = copyWithInvert(maps.get(imap), inverts.get(imap)); + mapc = new UnitMap(mapa.getNout()); + } + axis += mapa.getNout(); + map1 = map1 != null ? new CmpMap(map1, mapa, false) : mapa; + map3 = map3 != null ? new CmpMap(map3, mapc, false) : mapc; + } + if (mapb == null) { + return null; + } + int axlat = mapb.getWcsAxis(2) - 1; + int axlon = mapb.getWcsAxis(1) - 1; + WcsMap map2 = new WcsMap(axis, mapb.getWcsType(), axlon + wcsaxis + 1, axlat + wcsaxis + 1); + for (int i = 0; i < mapb.getNin(); i++) { + for (int m = 0; m < WCSLIB_MXPAR; m++) { + if (mapb.testPV(i, m)) { + double pv = mapb.getPV(i, m); + if (pv != AST__BAD) { + map2.setPV(i + wcsaxis, m, pv); + } + } + } + } + map2.invert(); + return new Split(map1, map2, map3); + } + + /** A copy of {@code map} with Invert value {@code invert}. */ + private static Mapping copyWithInvert(Mapping map, boolean invert) { + Mapping copy = (Mapping) map.copy(); + copy.setInvert(invert); + return copy; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsChan.java b/src/main/java/uk/ac/starlink/ast/FitsChan.java index de5b8d8..39e684a 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsChan.java +++ b/src/main/java/uk/ac/starlink/ast/FitsChan.java @@ -8,9 +8,11 @@ import java.nio.file.InvalidPathException; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.NoSuchElementException; /** @@ -118,6 +120,12 @@ static Encoding fromName(String name) { private FitsCardList cardList = new FitsCardList(); + /** + * The last sequence number a NATIVE write used for each keyword base, C's {@code keyseq} + * ({@link FitsNativeWriter#createKeyword}). + */ + private Map keySeq = new HashMap<>(); + /** The Encoding attribute, or null if unset. */ private Encoding encodingSet; @@ -557,6 +565,7 @@ public AstObject copy() { void deepCopy() { super.deepCopy(); cardList = cardList.copy(); + keySeq = new HashMap<>(keySeq); cardIt = null; sourcePending = false; sourceSaved = false; @@ -845,13 +854,14 @@ private AstObject readForeign(Encoding enc) { // MODERN-JAVA(21): switch expression switch (enc) { case FITS_WCS: - return FitsWcsRead.read(this); case FITS_PC: case FITS_IRAF: case FITS_AIPS: case FITS_AIPSPP: - case FITS_CLASS: + return FitsWcsRead.read(this, enc); case DSS: + return FitsWcsRead.readDss(this); + case FITS_CLASS: throw new UnsupportedOperationException( "FitsChan: reading the " + enc.cName() + " encoding is not available"); default: @@ -860,15 +870,114 @@ private AstObject readForeign(Encoding enc) { } /** - * Writes an Object to this FitsChan, using the encoding the Encoding attribute gives. + * Writes an Object to this FitsChan, using the encoding the Encoding attribute gives. The + * warnings of the previous read or write are discarded. + * + *

With the NATIVE encoding any Object can be written, as header cards in front of the + * current card, whose keywords are made unique with a two-character suffix ({@code BEGAST_A}, + * {@code NIN_A}, ...), passing over any keyword a card already has. Unless the Comment + * attribute is clear the cards are framed by comment cards, and the Full attribute selects the + * default values and markers written, as for a Channel. The current card stays current. + * + *

Any other encoding describes only a FrameSet, and only one the encoding can describe; for + * anything else nothing is written and 0 is returned. The cards go after the last card that + * describes WCS in any of the encodings, or at the end if there is none, whichever card is + * current; a card already present with the keyword of a card written is replaced where it is. + * When a FrameSet is written, the FitsChan is left at end-of-file. + * + *

A write that writes nothing, or fails, leaves the cards and the current card as they were, + * except that a card the write replaced before it failed is lost, as in C. * * @param obj the Object to write - * @return the number of Objects written - * @throws UnsupportedOperationException always: writing Objects to a FitsChan is out of scope + * @return the number of Objects written: 1, or 0 if the Object could not be written */ @Override public int write(AstObject obj) { - throw new UnsupportedOperationException("FitsChan.write is out of scope"); + // fitschan.c Write, with astWrite's discarding of the warnings (channel.c astWrite_). + clearWarnings(); + readFromSource(); + int card0 = cardList.position(); + cardList.beginMarkingNew(); + int ret = 0; + try { + Encoding enc = encoding(); + if (enc == Encoding.NATIVE) { + new FitsNativeWriter(this).write(obj); + ret = 1; + } else if (obj instanceof FrameSet && writeForeign((FrameSet) obj, enc)) { + ret = 1; + cardList.setCard(Integer.MAX_VALUE); + } + } finally { + // C's FixNew: the cards a write that wrote nothing added are removed, and the card that + // was current is current again. A write that throws has its new cards removed in the + // same way. + boolean remove = ret == 0; + cardList.fixNew(FitsCardList.NewScope.WRITE, remove); + cardList.fixNew(FitsCardList.NewScope.VERSION, remove); + cardList.endMarkingNew(); + if (remove) { + cardList.setPosition(card0); + } + } + return ret; + } + + /** + * Writes {@code fs} with {@code enc}, an encoding other than NATIVE, as fitschan.c {@code + * Write} does from reading the image dimensions on: false, C's failure, if the encoding cannot + * describe the FrameSet. The axis descriptions are made from the FrameSet ({@link + * FitsFsetToStore#fsetToStore}), raising their warnings, and written as cards by the encoding's + * writer ({@link #fitsFromStore}). {@link #write} removes the cards a write that gives false + * wrote, as C's {@code FixNew} does, which does not bring back a card one of them replaced, + * and leaves end-of-file current after one that gives true. + * + * @throws UnsupportedOperationException where describing the FrameSet needs a class this + * library lacks + */ + boolean writeForeign(FrameSet fs, Encoding enc) { + // The image dimensions, where known. + int naxis = fs.getNin(); + double[] dim = new double[naxis]; + for (int i = 0; i < naxis; i++) { + Double d = getFitsF("NAXIS" + (i + 1)); + dim[i] = d != null ? d : AST__BAD; + } + + // C's Write passes FsetToStore its method and class names in the wrong order, so the + // method its warnings name is the class (C-library quirk, kept). + FitsPlaneStores store = FitsFsetToStore.fsetToStore(this, fs, naxis, dim, enc, astClass(), "astWrite"); + return store != null && fitsFromStore(store, enc, dim, fs, "astWrite", astClass()); + } + + /** + * C's {@code FitsFromStore}: puts the current card after the last card describing WCS ({@link + * FitsCardList#positionWriteCursor}, C's {@code FindWcs}), and writes the descriptions in + * {@code store} with the writer of {@code enc}. The FITS-CLASS writer also takes the image + * dimensions {@code dim} and the FrameSet {@code fs} the descriptions were made from. + */ + private boolean fitsFromStore( + FitsPlaneStores store, Encoding enc, double[] dim, FrameSet fs, String method, String cls) { + cardList.positionWriteCursor(); + // MODERN-JAVA(21): switch expression + switch (enc) { + case FITS_WCS: + return FitsWcsWrite.wcsFromStore(this, store, method, cls); + case FITS_PC: + return FitsEncPc.pcFromStore(this, store, method, cls); + case FITS_IRAF: + return FitsEncIraf.irafFromStore(this, store, method, cls); + case FITS_AIPS: + return FitsEncAips.aipsFromStore(this, store, method, cls); + case FITS_AIPSPP: + return FitsEncAips.aipsppFromStore(this, store, method, cls); + case FITS_CLASS: + return FitsEncClass.classFromStore(this, store, fs, dim, method, cls); + case DSS: + return FitsEncDss.dssFromStore(this, store, method, cls); + default: + throw Ast.err(AstException.AST__INTER, "astWrite(FitsChan): unexpected encoding " + enc + "."); + } } // ------------------------------------------------------------------ @@ -880,6 +989,11 @@ FitsCardList cards() { return cardList; } + /** C's {@code keyseq}: the last sequence number a NATIVE write used for each keyword base. */ + Map keySequences() { + return keySeq; + } + /** * An empty list for the warnings {@code method} raises: with Strict in force, a warning that * {@link #issueWarning} would store becomes an error where it is raised, as C's {@code Warn} makes it. @@ -1144,6 +1258,7 @@ void emptyFits() { private void emptyFitsInner() { cardList = new FitsCardList(); + keySeq = new HashMap<>(); tables = null; } @@ -1419,6 +1534,11 @@ void setFitsK(String name, long value, String comment, boolean overwrite) { setValue(name, FitsCard.Value.ofKInt(value), comment, overwrite, "astSetFitsK"); } + /** C's {@code astSetFitsI}: stores an integer value. */ + void setFitsI(String name, long value, String comment, boolean overwrite) { + setValue(name, FitsCard.Value.ofInt(value), comment, overwrite, "astSetFitsI"); + } + /** C's {@code astSetFitsU}: stores a keyword with no value. */ void setFitsU(String name, String comment, boolean overwrite) { setValue(name, FitsCard.Value.UNDEF, comment, overwrite, "astSetFitsU"); @@ -1433,7 +1553,7 @@ void setFitsCM(String comment, boolean overwrite) { * C's {@code SetFitsCom}: stores a commentary card with keyword {@code name}. When overwriting * a card with the same keyword, the card keeps its type and value and takes the new comment. */ - private void setFitsCom(String name, String comment, boolean overwrite) { + void setFitsCom(String name, String comment, boolean overwrite) { readFromSource(); String lname = splitName(name, "astSetFitsCom")[0]; String com = comment == null || FitsCard.isBlank(comment) ? null : comment; diff --git a/src/main/java/uk/ac/starlink/ast/FitsDates.java b/src/main/java/uk/ac/starlink/ast/FitsDates.java index 764bef8..d9520e0 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsDates.java +++ b/src/main/java/uk/ac/starlink/ast/FitsDates.java @@ -1,16 +1,19 @@ package uk.ac.starlink.ast; import uk.ac.starlink.ast.internal.erfa.Cal2jd; +import uk.ac.starlink.ast.internal.erfa.Jd2cal; import uk.ac.starlink.ast.internal.erfa.Tf2d; import uk.ac.starlink.ast.internal.pal.Pal; /** * The Modified Julian Date of a FITS {@code DATE-OBS} string, as a FitsChan read uses it to supply - * an MJD-OBS the header lacks. + * an MJD-OBS the header lacks, and the DATE-OBS string a FITS-WCS write gives an MJD-OBS. * *

Ported from the date helpers of Rust {@code fitschan/wcs_write/mod.rs} ({@code * date_str_to_mjd}, {@code parse_legacy_date}, {@code gregorian_to_mjd}); the strings accepted are - * those of the {@code sscanf} patterns of C's {@code DateObs} (fitschan.c:8589). + * those of the {@code sscanf} patterns of C's {@code DateObs} (fitschan.c:8589). The string written + * follows C's {@code WcsFromStore}, which formats the date with {@code palDjcal}, {@code palDjcl} + * and {@code palDd2tf} where Rust works the calendar out itself. */ final class FitsDates { @@ -260,4 +263,43 @@ Integer decimal(int width) { return (int) value; } } + + /** + * The DATE-OBS string C's {@code WcsFromStore} writes for the MJD-OBS {@code mjd}: before 1999 + * the old form {@code dd/mm/yy}, the day {@code palDjcal} gives with no rounding, the year less + * 1900 (or 2000 after 1999); from 1999 the form {@code ccyy-mm-ddThh:mm:ss.sss}, the time of day + * rounded to milliseconds by {@code palDd2tf}, which can give {@code 24:00:00.000}. Each field + * is written with C's {@code %2.2d} (or {@code %3.3d}, {@code %4.4d}): at least that many + * digits, after a minus sign for a negative value. + * + * @throws AstException with status {@code AST__INTER} if {@code mjd} is outside the range of + * {@code palDjcl}, where C formats fields its calendar routine never set + */ + static String mjdToDateStr(double mjd) { + // palCaldj( 99, 1, 1 ) is 1999 January 1. + double mjd99 = Pal.cldj(1999, 1, 1).djm; + // palDjcal and palDjcl both convert with eraJd2cal. + Jd2cal.Result ymd = Pal.djcl(mjd); + if (ymd == null) { + throw Ast.err( + AstException.AST__INTER, + "WcsFromStore(FitsChan): AST internal error; MJD-OBS " + mjd + " has no calendar date."); + } + if (mjd < mjd99) { + return digits(ymd.id, 2) + "/" + digits(ymd.im, 2) + "/" + + digits(ymd.iy - (ymd.iy > 1999 ? 2000 : 1900), 2); + } + int[] hmsf = Pal.dd2tf(3, ymd.fd).ihmsf; + return digits(ymd.iy, 4) + "-" + digits(ymd.im, 2) + "-" + digits(ymd.id, 2) + "T" + digits(hmsf[0], 2) + ":" + + digits(hmsf[1], 2) + ":" + digits(hmsf[2], 2) + "." + digits(hmsf[3], 3); + } + + /** C's {@code %.d}: {@code v} with at least {@code n} digits, after a minus sign if negative. */ + private static String digits(int v, int n) { + StringBuilder b = new StringBuilder(Integer.toString(Math.abs(v))); + while (b.length() < n) { + b.insert(0, '0'); + } + return v < 0 ? "-" + b : b.toString(); + } } diff --git a/src/main/java/uk/ac/starlink/ast/FitsEncAips.java b/src/main/java/uk/ac/starlink/ast/FitsEncAips.java new file mode 100644 index 0000000..561a3d2 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsEncAips.java @@ -0,0 +1,732 @@ +package uk.ac.starlink.ast; + +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * The cards of a FITS-AIPS or FITS-AIPS++ header for the primary axis description of a FrameSet: + * C's {@code AIPSFromStore} and {@code AIPSPPFromStore}, which write the description {@link + * FitsFsetToStore#fsetToStore} made. + * + *

FITS-AIPS is FITS-WCS with these restrictions: only the primary description is written; the + * celestial projection has no parameters, except a SIN projection whose parameters are zero or give + * the old NCP projection, written as {@code -NCP}; AIT, MER and SFL are written only with the + * reference point at the origin of the celestial coordinates, and SFL with the older code {@code + * GLS}; the celestial axes are RA/DEC, galactic or ecliptic, with no LONPOLE or LATPOLE; EPOCH is + * written in place of EQUINOX and RADECSYS, so the system must follow the IAU 1984 rule (FK4 before + * 1984, FK5 after), and ICRS cannot be written; any rotation is in the celestial plane (or, with no + * celestial axes, that of the first two non-spectral axes), with no shear, and is written as CROTA + * and CDELT; a spectral axis has a CTYPE of {@code FREQ}, {@code VRAD} or {@code VOPT-F2W}, written + * with the standard of rest in AIPS's form ({@code VELO-LSR} and so on), a standard of rest of LSRK, + * LSRD, BARYCENT or GEOCENTR, and units of Hz or m/s or a multiple of them; and there is no WCSAXES + * keyword, so there must be as many WCS axes as pixel axes. + * + *

FITS-AIPS++ lifts some of these: the latitude axis may have up to ten projection parameters, + * written as {@code PROJPm}, with any projection but TPN; LONPOLE and LATPOLE are written; and a + * rotation that CROTA cannot describe is written as a CD matrix. + * + *

Ported from fitschan.c {@code AIPSFromStore} and {@code AIPSPPFromStore}, which include the fix + * of upstream 6c47ddde: an MJD-OBS card already in the header, which a read leaves there, is set to + * the date written as DATE-OBS. The Rust port's {@code fitschan/enc_aips.rs} is organised + * differently. + */ +final class FitsEncAips { + + /** C's {@code AST__DD2R}: radians per degree. */ + private static final double AST__DD2R = 0.017453292519943295; + + /** C's {@code AST__DR2D}: degrees per radian. */ + private static final double AST__DR2D = 57.29577951308232; + + /** C's {@code AST__BAD}, for the values C tests against it. */ + private static final double BAD = AstObject.AST__BAD; + + private FitsEncAips() {} + + /** What the checks of the spectral axis give: the AIPS CTYPE, units and unit factor. */ + private static final class Spectral { + /** The AIPS CTYPE, null until the FITS-WCS CTYPE is recognised. */ + String type; + + /** The AIPS units, empty until the units are recognised. */ + String unit = ""; + + /** The factor converting the FITS-WCS units to {@link #unit}. */ + double factor = 1.0; + } + + /** The rotation and pixel sizes the CD matrix gives. */ + private static final class Rotation { + /** The first and second rotation axes, -1 for none. */ + int axrot1; + + int axrot2; + + /** The CDELT value of each axis. */ + double[] cdelt; + + /** The CROTA value in degrees, or {@link #BAD} if the rotation is not one CROTA can give. */ + double crota; + + /** False if the CD matrix rotates outside the plane of the rotation axes. */ + boolean ok = true; + } + + /** + * C's {@code AIPSFromStore}: writes the primary description in {@code store} to {@code fc} as + * FITS-AIPS cards, each in front of the current card, if the description meets the + * restrictions of the encoding. A description lacking a CRPIX, CRVAL or CTYPE on one of its + * axes, or with a {@code -TAB} axis, gives false after the cards written; {@link + * FitsChan#write} then removes them. + * + * @param fc the FitsChan written to + * @param store the descriptions + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return true if the description was written + */ + static boolean aipsFromStore(FitsChan fc, FitsPlaneStores store, String method, String cls) { + int rnd = fc.getFitsRounding(); + FitsCardList cards = fc.cards(); + FitsStore st = primary(store); + + // Whether the description meets the restrictions of the encoding. + boolean ok = true; + int[] axes = st.lonLatSpecAxes(store.naxis); + int axlon = axes[0]; + int axlat = axes[1]; + int axspec = axes[2]; + String lontype = null; + String lattype = null; + if (axlon >= 0 && axlat >= 0) { + double latval = value(at(st.crval, axlat), BAD); + if (latval == BAD) { + ok = false; + } + double lonval = value(at(st.crval, axlon), BAD); + if (lonval == BAD) { + ok = false; + } + + // The CTYPE values of both axes, which name a longitude and a latitude axis, and the + // projection the latitude axis gives. + lontype = at(st.ctype, axlon); + lattype = at(st.ctype, axlat); + int prj = FitsWcsCelestial.wcsPrjType(lattype.substring(4)); + + if (prj == WcsMap.AST__WCSBAD) { + ok = false; + } else if (prj != WcsMap.AST__SIN) { + if (st.maxPvM() >= 0) { + // There must be no projection parameters. + ok = false; + } else if (prj == WcsMap.AST__TPN) { + // FITS-AIPS cannot hold the AST-specific TPN projection. + ok = false; + } else if (prj == WcsMap.AST__MER || prj == WcsMap.AST__AIT || prj == WcsMap.AST__SFL) { + // These need the reference point at the origin of the celestial coordinates; + // SFL is written with the older code GLS. + if (latval != 0.0 || lonval != 0.0) { + ok = false; + } else if (prj == WcsMap.AST__SFL) { + lontype = withCode(lontype, "-GLS"); + lattype = withCode(lattype, "-GLS"); + } + } + } else { + // A SIN projection whose parameters are both zero, or the first zero and the second + // the cotangent of the reference latitude (the old NCP projection). + double p1 = value(at(st.pv, axlat, 1), 0.0); + double p2 = value(at(st.pv, axlat, 2), 0.0); + ok = false; + if (p1 == 0.0) { + if (p2 == 0.0) { + ok = true; + } else if (Math.abs(p2) >= 1.0e14 && latval == 0.0) { + ok = true; + lontype = withCode(lontype, "-NCP"); + lattype = withCode(lattype, "-NCP"); + } else if (Math.abs(p2 * Math.tan(AST__DD2R * latval) - 1.0) < 0.01) { + ok = true; + lontype = withCode(lontype, "-NCP"); + lattype = withCode(lattype, "-NCP"); + } + } + } + + // Only RA, galactic longitude and ecliptic longitude can be held. + if (ok && !isAipsLongitude(lontype)) { + ok = false; + } + + // Nor can a LONPOLE or LATPOLE. + if (st.latpole != null || st.lonpole != null) { + ok = false; + } + } + + // The spectral axis. + Spectral spec = new Spectral(); + if (ok && axspec >= 0) { + String cval = at(st.ctype, axspec); + if (cval == null) { + ok = false; + } else { + spec.type = specType(cval); + if (spec.type == null) { + ok = false; + } + } + cval = st.specsys; + if (cval == null) { + ok = false; + } else if (ok) { + String sor = standardOfRest(cval); + if (sor == null) { + ok = false; + } else { + spec.type += sor; + } + } + cval = at(st.cunit, axspec); + if (cval == null) { + ok = false; + } else if (ok && !specUnit(cval, spec)) { + ok = false; + } + } + + // There is no WCSAXES keyword, so there must be as many WCS axes as pixel axes. + int naxis = st.maxCrpixAxis() + 1; + if (naxis != store.naxis) { + ok = false; + } + + // The rotation, which must be one CROTA can give. + Rotation rot = rotation(st, naxis, axlon, axlat, axspec, ok); + ok = ok && rot.ok; + double crota = 0.0; + if (ok && rot.axrot1 >= 0 && rot.axrot2 >= 0) { + if (rot.crota == BAD) { + ok = false; + } else { + crota = rot.crota; + } + } + + // The reference equinox, called EPOCH, which must agree with RADECSYS. + double[] epoch = {value(st.equinox, BAD)}; + if (!epochAgrees(st.radesys, epoch)) { + ok = false; + } + if (!ok) { + return false; + } + + ok = writeAxes(cards, st, naxis, axlon, axlat, axspec, lontype, lattype, spec, rot.cdelt, rnd); + + // CROTA, on the second rotation axis. + if (rot.axrot2 != -1) { + setFloat(cards, "CROTA" + (rot.axrot2 + 1), crota, "Axis rotation", rnd); + } else if ((axspec == -1 && naxis > 1) || (axspec != -1 && naxis > 2)) { + setFloat(cards, "CROTA1", crota, "Axis rotation", rnd); + } + + if (epoch[0] != BAD) { + setFloat(cards, "EPOCH", epoch[0], "Epoch of reference equinox", rnd); + } + writeDate(cards, st, rnd); + writeRestFrequency(cards, st, axspec, rnd); + return ok; + } + + /** + * C's {@code AIPSPPFromStore}: writes the primary description in {@code store} to {@code fc} as + * FITS-AIPS++ cards, each in front of the current card, if the description meets the + * restrictions of the encoding. A description lacking a CRPIX, CRVAL or CTYPE on one of its + * axes, or with a {@code -TAB} axis, gives false after the cards written; {@link + * FitsChan#write} then removes them. + * + * @param fc the FitsChan written to + * @param store the descriptions + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return true if the description was written + */ + static boolean aipsppFromStore(FitsChan fc, FitsPlaneStores store, String method, String cls) { + int rnd = fc.getFitsRounding(); + FitsCardList cards = fc.cards(); + FitsStore st = primary(store); + + // Whether the description meets the restrictions of the encoding. + boolean ok = true; + int naxis = st.maxCrpixAxis() + 1; + int maxm = 0; + int[] axes = st.lonLatSpecAxes(store.naxis); + int axlon = axes[0]; + int axlat = axes[1]; + int axspec = axes[2]; + String lontype = null; + String lattype = null; + if (axlon >= 0 && axlat >= 0) { + // The CTYPE values of both axes, which name a longitude and a latitude axis, and the + // projection the latitude axis gives. FITS-AIPS++ cannot hold the AST-specific TPN + // projection. + lontype = at(st.ctype, axlon); + lattype = at(st.ctype, axlat); + int prj = FitsWcsCelestial.wcsPrjType(lattype.substring(4)); + if (prj == WcsMap.AST__TPN || prj == WcsMap.AST__WCSBAD) { + ok = false; + } + + // Projection parameters: only the first ten of the latitude axis; those of the + // longitude axis are left out. + maxm = st.maxPvM(); + for (int i = 0; i < naxis && ok; i++) { + if (i != axlon) { + for (int m = 0; m <= maxm; m++) { + if (at(st.pv, i, m) != null && (i != axlat || m >= 10)) { + ok = false; + break; + } + } + } + } + + // Only RA, galactic longitude and ecliptic longitude can be held. + if (ok && !isAipsLongitude(lontype)) { + ok = false; + } + } + + // The spectral axis. + Spectral spec = new Spectral(); + if (axspec >= 0) { + String cval = at(st.ctype, axspec); + if (cval == null) { + ok = false; + } else { + spec.type = specType(cval); + if (spec.type == null) { + ok = false; + } + } + cval = st.specsys; + if (cval == null) { + ok = false; + } else { + String sor = standardOfRest(cval); + if (sor == null) { + ok = false; + } else if (spec.type != null) { + spec.type += sor; + } + } + cval = at(st.cunit, axspec); + if (cval == null) { + ok = false; + } else if (ok && !specUnit(cval, spec)) { + ok = false; + } + } + + // There is no WCSAXES keyword, so there must be as many WCS axes as pixel axes. + if (naxis != store.naxis) { + ok = false; + } + + // The rotation; one CROTA cannot give is written as a CD matrix. + Rotation rot = rotation(st, naxis, axlon, axlat, axspec, ok); + ok = ok && rot.ok; + double crota = 0.0; + if (ok && rot.axrot1 >= 0 && rot.axrot2 >= 0) { + crota = rot.crota; + } + + // The reference equinox, called EPOCH, which must agree with RADECSYS. + double[] epoch = {value(st.equinox, BAD)}; + if (!epochAgrees(st.radesys, epoch)) { + ok = false; + } + if (!ok) { + return false; + } + + ok = writeAxes(cards, st, naxis, axlon, axlat, axspec, lontype, lattype, spec, rot.cdelt, rnd); + + if (crota == BAD) { + // The CD matrix, the PC matrix with each row multiplied by its CDELT; zero elements + // left out. + for (int i = 0; i < naxis; i++) { + for (int j = 0; j < naxis; j++) { + double val = st.cdElement(i, j); + if (val != 0.0) { + setFloat(cards, "CD" + (i + 1) + "_" + (j + 1), val, "Transformation matrix element", rnd); + } + } + } + } else if (crota != 0.0) { + // CROTA, on the second rotation axis. + if (rot.axrot2 != -1) { + setFloat(cards, "CROTA" + (rot.axrot2 + 1), crota, "Axis rotation", rnd); + } else if ((axspec == -1 && naxis > 1) || (axspec != -1 && naxis > 2)) { + setFloat(cards, "CROTA1", crota, "Axis rotation", rnd); + } + } + + if (epoch[0] != BAD) { + setFloat(cards, "EPOCH", epoch[0], "Epoch of reference equinox", rnd); + } + if (st.latpole != null) { + setFloat(cards, "LATPOLE", st.latpole, "Latitude of native north pole", rnd); + } + if (st.lonpole != null) { + setFloat(cards, "LONPOLE", st.lonpole, "Longitude of native north pole", rnd); + } + writeDate(cards, st, rnd); + + // The projection parameters of the latitude axis. + if (axlat >= 0 && axlon >= 0) { + for (int m = 0; m <= maxm; m++) { + Double val = at(st.pv, axlat, m); + if (val != null) { + setFloat(cards, "PROJP" + m, val, "Projection parameter", rnd); + } + } + } + writeRestFrequency(cards, st, axspec, rnd); + return ok; + } + + /** The primary description, or an empty one for a version with nothing stored, which C reads as unset values. */ + private static FitsStore primary(FitsPlaneStores store) { + FitsStore st = store.get(' '); + return st != null ? st : new FitsStore(0); + } + + /** + * The rotation axes and the CDELT values and CROTA (in degrees) of the CD matrix, as both + * writers of C find them: the rotation is in the celestial plane, or, with no celestial axes, + * that of the first two non-spectral axes. The matrix is examined only if {@code ok}; {@link + * Rotation#ok} is false if it rotates outside that plane, and {@link Rotation#crota} is {@link + * #BAD} if its two estimates of CROTA disagree, and zero if there is no pair of rotation axes. + */ + private static Rotation rotation(FitsStore st, int naxis, int axlon, int axlat, int axspec, boolean ok) { + Rotation rot = new Rotation(); + if (axlat < 0 && axlon < 0) { + if (axspec >= 0 && naxis > 2) { + rot.axrot2 = axspec == 0 ? 1 : 0; + rot.axrot1 = rot.axrot2 + 1; + if (rot.axrot1 == axspec) { + rot.axrot1++; + } + } else if (naxis > 1) { + rot.axrot2 = 0; + rot.axrot1 = 1; + } else { + rot.axrot2 = -1; + rot.axrot1 = -1; + } + } else { + rot.axrot1 = axlon; + rot.axrot2 = axlat; + } + rot.cdelt = new double[Math.max(naxis, 0)]; + if (!ok) { + return rot; + } + + // The diagonal of the CD matrix, and its elements in the plane of the rotation axes. + double cdlatLon = 0.0; + double cdlonLat = 0.0; + for (int i = 0; i < naxis && rot.ok; i++) { + for (int j = 0; j < naxis && rot.ok; j++) { + double val = st.cdElement(i, j); + if (i == j) { + rot.cdelt[i] = val; + } else if (i == rot.axrot2 && j == rot.axrot1) { + cdlatLon = val; + } else if (i == rot.axrot1 && j == rot.axrot2) { + cdlonLat = val; + } else if (val != 0.0) { + rot.ok = false; + } + } + } + if (!rot.ok || rot.axrot1 < 0 || rot.axrot2 < 0) { + rot.crota = 0.0; + return rot; + } + + // Two estimates of CROTA, which must agree; the CDELT values of the rotation axes follow + // from their mean. + double rhoA; + if (cdlatLon > 0.0) { + rhoA = Math.atan2(cdlatLon, rot.cdelt[rot.axrot1]); + } else if (cdlatLon == 0.0) { + rhoA = 0.0; + } else { + rhoA = Math.atan2(-cdlatLon, -rot.cdelt[rot.axrot1]); + } + double rhoB; + if (cdlonLat > 0.0) { + rhoB = Math.atan2(cdlonLat, -rot.cdelt[rot.axrot2]); + } else if (cdlonLat == 0.0) { + rhoB = 0.0; + } else { + rhoB = Math.atan2(-cdlonLat, rot.cdelt[rot.axrot2]); + } + if (Math.abs(Pal.drange(rhoA - rhoB)) < 1.0e-2) { + double crota = 0.5 * (Pal.dranrm(rhoA) + Pal.dranrm(rhoB)); + double coscro = Math.cos(crota); + double sincro = Math.sin(crota); + if (Math.abs(coscro) > Math.abs(sincro)) { + rot.cdelt[rot.axrot2] /= coscro; + rot.cdelt[rot.axrot1] /= coscro; + } else { + rot.cdelt[rot.axrot2] = -cdlonLat / sincro; + rot.cdelt[rot.axrot1] = cdlatLon / sincro; + } + rot.crota = crota * AST__DR2D; + } else { + rot.crota = BAD; + } + return rot; + } + + /** + * Whether the reference equinox {@code epoch[0]} ({@link #BAD} if unset) agrees with {@code + * radesys} as the IAU 1984 rule has it: FK4 before 1984 and FK5 after. ICRS, or any other + * system, does not. An unset equinox is set to the default of the system, 1950 for FK4 and 2000 + * for FK5. With no {@code radesys}, any equinox agrees. + */ + private static boolean epochAgrees(String radesys, double[] epoch) { + if (radesys == null) { + return true; + } + boolean ok = !"ICRS".equals(radesys); + if (epoch[0] == BAD) { + if ("FK4".equals(radesys)) { + epoch[0] = 1950.0; + } else if ("FK5".equals(radesys)) { + epoch[0] = 2000.0; + } else { + ok = false; + } + } else if ("FK4".equals(radesys)) { + if (epoch[0] >= 1984.0) { + ok = false; + } + } else if ("FK5".equals(radesys)) { + if (epoch[0] < 1984.0) { + ok = false; + } + } else { + ok = false; + } + return ok; + } + + /** + * The cards both writers write for each axis: CRPIX, CRVAL (the spectral axis's in the AIPS + * units), CTYPE (the celestial and spectral axes with the values chosen for them), CDELT and + * CUNIT. Writing CRPIX, CRVAL and CTYPE stops at the first axis without one, or with a {@code + * -TAB} CTYPE, giving false, after which CDELT and CUNIT are still written, as in C. + */ + private static boolean writeAxes( + FitsCardList cards, + FitsStore st, + int naxis, + int axlon, + int axlat, + int axspec, + String lontype, + String lattype, + Spectral spec, + double[] cdelt, + int rnd) { + boolean ok = true; + for (int j = 0; j < naxis && ok; j++) { + Double val = at(st.crpix, j); + if (val == null) { + ok = false; + } else { + setFloat(cards, "CRPIX" + (j + 1), val, "Reference pixel on axis " + (j + 1), rnd); + } + } + for (int i = 0; i < naxis && ok; i++) { + Double val = at(st.crval, i); + if (val == null) { + ok = false; + } else { + double v = val; + if (i == axspec) { + v *= spec.factor; + } + setFloat(cards, "CRVAL" + (i + 1), v, "Value at ref. pixel on axis " + (i + 1), rnd); + } + } + for (int i = 0; i < naxis && ok; i++) { + String cval; + if (i == axlat) { + cval = lattype; + } else if (i == axlon) { + cval = lontype; + } else if (i == axspec) { + cval = spec.type; + } else { + cval = at(st.ctype, i); + } + if (cval != null && (cval.length() < 5 || !"-TAB".equals(cval.substring(4)))) { + String comm = at(st.ctypeCom, i); + if (comm == null) { + comm = "Type of co-ordinate on axis " + (i + 1); // codespell:ignore + } + setString(cards, "CTYPE" + (i + 1), cval, comm, rnd); + } else { + ok = false; + } + } + + if (axspec != -1) { + cdelt[axspec] *= spec.factor; + } + for (int i = 0; i < naxis; i++) { + setFloat(cards, "CDELT" + (i + 1), cdelt[i], "Pixel size", rnd); + } + for (int i = 0; i < naxis; i++) { + String cval = at(st.cunit, i); + if (cval != null) { + if (i == axspec) { + cval = spec.unit; + } + setString(cards, "CUNIT" + (i + 1), cval, "Units for axis " + (i + 1), rnd); + } + } + return ok; + } + + /** + * The date of observation as DATE-OBS. A read leaves any MJD-OBS card in the header, since + * other software may use it, so such a card is set to the same date. + */ + private static void writeDate(FitsCardList cards, FitsStore st, int rnd) { + if (st.mjdobs != null) { + double val = st.mjdobs; + setString(cards, "DATE-OBS", FitsDates.mjdToDateStr(val), "Date of observation", rnd); + if (cards.hasCard("MJD-OBS")) { + setFloat(cards, "MJD-OBS", val, "Modified Julian Date of observation", rnd); + } + } + } + + /** The rest frequency, as RESTFREQ, when there is a spectral axis. */ + private static void writeRestFrequency(FitsCardList cards, FitsStore st, int axspec, int rnd) { + if (axspec >= 0 && st.restfrq != null) { + setFloat(cards, "RESTFREQ", st.restfrq, "[Hz] Rest frequency", rnd); + } + } + + /** Whether a longitude CTYPE is one FITS-AIPS can hold: RA, galactic or ecliptic longitude. */ + private static boolean isAipsLongitude(String lontype) { + return lontype.startsWith("RA--") || lontype.startsWith("GLON") || lontype.startsWith("ELON"); + } + + /** + * The first four characters of the AIPS CTYPE of a spectral axis whose FITS-WCS CTYPE is {@code + * cval}, or null if AIPS has none: {@code FREQ}, {@code VELO} for {@code VRAD} and {@code FELO} + * for {@code VOPT-F2W}, each matched as C's {@code strncmp} over the length of {@code cval} + * without trailing spaces. + */ + private static String specType(String cval) { + if (FitsStore.namesStartOf(cval, "FREQ")) { + return "FREQ"; + } else if (FitsStore.namesStartOf(cval, "VRAD")) { + return "VELO"; + } else if (FitsStore.namesStartOf(cval, "VOPT-F2W")) { + return "FELO"; + } + return null; + } + + /** + * The end of the AIPS CTYPE of a spectral axis for the SPECSYS {@code cval}, or null if AIPS has + * none: {@code -LSR} for LSRK, {@code -LSD} for LSRD, {@code -HEL} for BARYCENT and {@code + * -GEO} for GEOCENTR, matched as {@link #specType} matches. + */ + private static String standardOfRest(String cval) { + if (FitsStore.namesStartOf(cval, "LSRK")) { + return "-LSR"; + } else if (FitsStore.namesStartOf(cval, "LSRD")) { + return "-LSD"; + } else if (FitsStore.namesStartOf(cval, "BARYCENT")) { + return "-HEL"; + } else if (FitsStore.namesStartOf(cval, "GEOCENTR")) { + return "-GEO"; + } + return null; + } + + /** + * Sets the AIPS units of a spectral axis whose units are {@code cval}, Hz or m/s, and the + * factor converting to them, in {@code spec}; false if AIPS cannot hold the units. + */ + private static boolean specUnit(String cval, Spectral spec) { + // MODERN-JAVA(21): switch expression + switch (cval) { + case "Hz": + spec.unit = "HZ"; + spec.factor = 1.0; + return true; + case "kHz": + spec.unit = "HZ"; + spec.factor = 1.0e3; + return true; + case "MHz": + spec.unit = "HZ"; + spec.factor = 1.0e6; + return true; + case "GHz": + spec.unit = "HZ"; + spec.factor = 1.0e9; + return true; + case "m/s": + spec.unit = "m/s"; + spec.factor = 1.0; + return true; + case "km/s": + spec.unit = "m/s"; + spec.factor = 1.0e3; + return true; + default: + return false; + } + } + + /** C's {@code strcpy( type + 4, code )}: the first four characters of {@code ctype} and {@code code}. */ + private static String withCode(String ctype, String code) { + return ctype.substring(0, 4) + code; + } + + /** {@code v}, or {@code unset} (in place of C's unset item) if it is null. */ + private static double value(Double v, double unset) { + return v != null ? v : unset; + } + + /** Element {@code i} of {@code a}, null (C's unset item) beyond its end. */ + private static T at(T[] a, int i) { + return i < a.length ? a[i] : null; + } + + /** Element {@code [i][j]} of {@code a}, null beyond its ends. */ + private static T at(T[][] a, int i, int j) { + return i < a.length && j < a[i].length ? a[i][j] : null; + } + + private static void setFloat(FitsCardList cards, String keyword, double value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofFloat(value), comment, rnd); + } + + private static void setString(FitsCardList cards, String keyword, String value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofString(value), comment, rnd); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsEncClass.java b/src/main/java/uk/ac/starlink/ast/FitsEncClass.java new file mode 100644 index 0000000..4532577 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsEncClass.java @@ -0,0 +1,256 @@ +package uk.ac.starlink.ast; + +/** + * The FITS-CLASS encoding's writer, C's {@code CLASSFromStore}, as far as this library reaches it. + * + *

FITS-CLASS, the encoding of the GILDAS CLASS package, describes a cube whose first three WCS + * axes are a frequency axis and two celestial axes (RA/DEC or galactic, in a projection CLASS + * knows, with no rotation), with the frequency given as an offset from the rest frequency and in + * the source's rest frame, and the reference point's radio velocity in the LSRK (VELO-LSR) and its + * azimuth and elevation. C checks the description first, and writes it only if FITS-CLASS can hold + * it; to write it, C makes a SpecFrame, which this library does not have, to find the VELO-LSR + * value. A description FITS-CLASS can hold has the SPECSYS of the source's rest frame, which only + * a SpecFrame gives it; so every FrameSet of this library's classes is refused, as C refuses it, + * and a description that passes the checks (which can be made only by hand) throws + * UnsupportedOperationException. + * + *

Ported from fitschan.c {@code CLASSFromStore}, which includes the fix of upstream aea3090b + * (a LONPOLE of +180 or -180 degrees is allowed); the Rust port's {@code fitschan/enc_class.rs} is + * organised differently. + */ +final class FitsEncClass { + + /** C's {@code AST__DR2D}: degrees per radian. */ + private static final double AST__DR2D = 57.29577951308232; + + /** C's {@code AST__BAD}, for the values C tests against it. */ + private static final double BAD = AstObject.AST__BAD; + + private FitsEncClass() {} + + /** + * C's {@code CLASSFromStore}: the checks it makes of the primary description in {@code store} + * before it writes it as FITS-CLASS cards. The spectral and celestial axes must be among the + * first three; the projection TAN, ARC or STG, AIT or SFL with the reference point at the + * origin, or SIN with zero parameters; the longitude RA or galactic; the spectral axis FREQ in + * the source's rest frame (SPECSYS SOURCE), in Hz, kHz, MHz or GHz; no rotation unless both + * celestial pixel axes span one pixel; an FK4 or FK5 system (when there is one) whose equinox + * the IAU 1984 rule allows; a rest frequency; and, unless both celestial pixel axes span one + * pixel, no LATPOLE and no LONPOLE but +180 or -180 degrees. + * + *

When the celestial pixel axes span one pixel, C first puts the reference point at pixel + * (1, 1, 1), transforming that pixel with {@code fs}, which must then have three inputs and + * three outputs. + * + * @param fc the FitsChan written to, whose NAXISi cards give the size of the celestial pixel + * axes + * @param store the descriptions + * @param fs the FrameSet the descriptions were made from + * @param dim the size of each pixel axis, or {@code AST__BAD} where unknown, indexed (as C + * indexes it) by the WCS axis + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return false: the description is refused + * @throws AstException as {@code fs} reports, with status {@code AST__NCPIN}, a transformation + * of pixel (1, 1, 1) by a FrameSet without three inputs and outputs + * @throws UnsupportedOperationException if the description passes the checks, since C then + * makes a SpecFrame + */ + static boolean classFromStore( + FitsChan fc, FitsPlaneStores store, FrameSet fs, double[] dim, String method, String cls) { + FitsStore st = store.get(' '); + if (st == null) { + st = new FitsStore(0); + } + FitsCardList cards = fc.cards(); + int rnd = fc.getFitsRounding(); + boolean ok = false; + + // The primary celestial and spectral axes. + int[] axes = st.lonLatSpecAxes(store.naxis); + int axlon = axes[0]; + int axlat = axes[1]; + int axspec = axes[2]; + Frame curfrm = fs.getFrame(FrameSet.AST__CURRENT); + + // They must be among WCS axes 1, 2 and 3. + if (axspec >= 0 && axspec < 3 && axlon >= 0 && axlon < 3 && axlat >= 0 && axlat < 3) { + // When the celestial pixel axes span one pixel, the reference point becomes the centre + // of that pixel, pixel (1, 1, 1). + if (store.naxis >= 3 && dim[axlon] == 1.0 && dim[axlat] == 1.0) { + double[] xout = fs.tranN(1, 3, new double[] {1.0, 1.0, 1.0}, true, 3); + if (xout[axlon] != BAD && xout[axlat] != BAD) { + // The celestial axes of the current Frame may not be the FITS axes of those + // indices, so the values are taken from its longitude and latitude axes. + double lonval = 0.0; + double latval = 0.0; + for (int i = 0; i < 3; i++) { + Boolean isLon = isLonAxis(curfrm, i + 1); + if (isLon != null) { + if (isLon) { + lonval = xout[i]; + } else { + latval = xout[i]; + } + } + } + st.crval[axlon] = lonval * AST__DR2D; + st.crval[axlat] = latval * AST__DR2D; + st.crpix[axlon] = 1.0; + st.crpix[axlat] = 1.0; + } + } + + // The projection, from the latitude CTYPE, decides whether the description is + // usable so far. C first sets ok, and clears it for a missing CRVAL or CTYPE of either + // celestial axis, but the test of the projection sets it again whatever it was; a + // missing CRVAL is BAD, which fails the test of AIT and SFL. The CTYPE values are + // never missing, as they name the celestial axes. + double latval = value(at(st.crval, axlat)); + double lonval = value(at(st.crval, axlon)); + String lontype = at(st.ctype, axlon); + String lattype = at(st.ctype, axlat); + int prj = lattype == null ? WcsMap.AST__WCSBAD : FitsWcsCelestial.wcsPrjType(lattype.substring(4)); + if (prj == WcsMap.AST__WCSBAD) { + ok = false; + } else if (prj != WcsMap.AST__SIN) { + ok = prj == WcsMap.AST__TAN + || prj == WcsMap.AST__ARC + || prj == WcsMap.AST__STG + || prj == WcsMap.AST__AIT + || prj == WcsMap.AST__SFL; + // AIT and SFL need the reference point at the origin of the celestial coordinates. + if (ok && (prj == WcsMap.AST__AIT || prj == WcsMap.AST__SFL) && (latval != 0.0 || lonval != 0.0)) { + ok = false; + } + } else { + // A SIN projection whose parameters are both zero. + double p1 = value(at(st.pv, axlat, 1)); + double p2 = value(at(st.pv, axlat, 2)); + ok = (p1 == BAD ? 0.0 : p1) == 0.0 && (p2 == BAD ? 0.0 : p2) == 0.0; + } + + // RA or galactic longitude. + if (ok && !lontype.startsWith("RA--") && !lontype.startsWith("GLON")) { + ok = false; + } + + // A FREQ spectral axis: the CTYPE must be a leading part of "FREQ". + String cval = at(st.ctype, axspec); + if (cval == null || !"FREQ".startsWith(cval.substring(0, FitsCard.chrLen(cval)))) { + ok = false; + } + + // The source's rest frame: SPECSYS a leading part of "SOURCE". + cval = st.specsys; + if (cval == null) { + ok = false; + } else if (ok && !"SOURCE".startsWith(cval.substring(0, FitsCard.chrLen(cval)))) { + ok = false; + } + + // Units of frequency. + cval = at(st.cunit, axspec); + if (cval == null) { + ok = false; + } else if (ok && !"Hz".equals(cval) && !"kHz".equals(cval) && !"MHz".equals(cval) && !"GHz".equals(cval)) { + ok = false; + } + } + + // The number of WCS axes, at most three. + int naxis = Math.min(st.maxCrpixAxis() + 1, 3); + + // The sizes of the celestial pixel axes, 0 where unknown; the rotation check is skipped + // when both span one pixel. + int naxis2 = naxisValue(cards, axlon, rnd, method, cls); + int naxis3 = naxisValue(cards, axlat, rnd, method, cls); + for (int i = 0; i < naxis && ok; i++) { + for (int j = 0; j < naxis && ok; j++) { + if (i != j && st.cdElement(i, j) != 0.0 && (naxis2 != 1 || naxis3 != 1)) { + ok = false; + } + } + } + + // FK4 or FK5, and the equinox the IAU 1984 rule gives them. + String radesys = st.radesys; + if (radesys != null) { + Double equ = st.equinox; + if ("FK4".equals(radesys)) { + if (equ != null && equ >= 1984.0) { + ok = false; + } + } else if ("FK5".equals(radesys)) { + if (equ != null && equ < 1984.0) { + ok = false; + } + } else { + ok = false; + } + } + + // A rest frequency. + if (st.restfrq == null) { + ok = false; + } + + // No LATPOLE, and a LONPOLE of +180 or -180 degrees, unless the celestial pixel axes span + // one pixel. + if (ok && (naxis2 != 1 || naxis3 != 1)) { + if (st.lonpole != null && st.lonpole != -180.0 && st.lonpole != 180.0) { + ok = false; + } + if (st.latpole != null) { + ok = false; + } + } + + if (ok) { + throw new UnsupportedOperationException( + method + "(" + cls + "): the VELO-LSR value of a FITS-CLASS header needs SpecFrame"); + } + return false; + } + + /** + * C's {@code astHasAttribute( frame, "IsLonAxis(axis)" )} and {@code astGetI}: whether axis + * {@code axis} (from 1) of {@code frame} is a longitude axis, or null if the Frame has no such + * attribute for that axis (it is not an axis of a SkyFrame). + */ + private static Boolean isLonAxis(Frame frame, int axis) { + try { + return frame.getI("IsLonAxis(" + axis + ")") != 0; + } catch (AstException e) { + if (e.getStatus() != AstException.AST__BADAT) { + throw e; + } + return null; + } + } + + /** + * The integer value of keyword NAXIS{@code axis + 1}, read as C's {@code GetValue} reads it, + * unmarked and with no error for a card that is absent or does not convert, which give 0. + */ + private static int naxisValue(FitsCardList cards, int axis, int rnd, String method, String cls) { + FitsCardValue.Got g = + cards.getValue("NAXIS" + (axis + 1), FitsCardValue.Want.INT, false, false, rnd, method, cls); + return g == null ? 0 : (int) g.i; + } + + /** {@code v}, or {@link #BAD} (C's unset item) if it is null. */ + private static double value(Double v) { + return v != null ? v : BAD; + } + + /** Element {@code i} of {@code a}, null (C's unset item) beyond its end. */ + private static T at(T[] a, int i) { + return i < a.length ? a[i] : null; + } + + /** Element {@code [i][j]} of {@code a}, null beyond its ends. */ + private static T at(T[][] a, int i, int j) { + return i < a.length && j < a[i].length ? a[i][j] : null; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsEncDss.java b/src/main/java/uk/ac/starlink/ast/FitsEncDss.java new file mode 100644 index 0000000..9ddc092 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsEncDss.java @@ -0,0 +1,438 @@ +package uk.ac.starlink.ast; + +/** + * The DSS encoding: the plate solutions of the Digitized Sky Survey. C's {@code DSSToStore} turns + * the plate solution in a header into an axis description that FITS-WCS can hold, and {@code + * DSSFromStore} writes such a description as DSS cards. + * + *

The description is two-dimensional: FK5 right ascension and declination at equinox J2000, + * with LONPOLE 180, in the TPN projection (TAN with polynomial corrections), whose projection + * parameters hold the plate solution's polynomial (the AMDXi and AMDYi coefficients divided by + * 3600), with a CDELT of 1 and the pixel sizes, in millimetres, in a diagonal PC matrix (plate + * coordinates in millimetres, "lambda = 1" in the draft of Calabretta and Greisen C cites). A + * plain TAN projection is written as the TPN projection whose only polynomial term is the unit + * one. A description with a rotation, or whose polynomial DSS cannot hold, is not written. + * + *

No DssMap is made: C's FitsChan no longer uses that class, so a DSS read gives a FrameSet + * whose Mapping holds a TPN WcsMap (Rust c-library-quirks.md, "The DssMap documentation says a + * DSS FitsChan read creates a DssMap"). + * + *

Ported from fitschan.c {@code DSSToStore} and {@code DSSFromStore}, with Rust {@code + * fitschan/enc_dss.rs}. + */ +final class FitsEncDss { + + /** C's {@code AST__BAD}, for the coefficients C marks as absent with it. */ + private static final double BAD = AstObject.AST__BAD; + + private FitsEncDss() {} + + /** + * C's {@code DSSToStore}: the axis description of the DSS plate solution the cards of {@code + * fc} hold. Each keyword is found as C's {@code GetValue} finds it, from the current card, + * and each card whose value is read is marked as provisionally used: the plate solution's + * cards, and PLTSCALE, PPO1, PPO2, PPO4 and PPO5, which are read only so that they are not + * copied to another header. CNPIX1 and CNPIX2 default to zero, and an absent AMDXi or AMDYi + * leaves the projection parameters it gives unset. + * + * @param method the calling method, for messages + * @param cls the class of the FitsChan, for messages + * @throws AstException with status {@code AST__BDFTS} if PPO3, PPO6, XPIXELSZ, YPIXELSZ, + * PLTRAH, PLTRAM, PLTRAS, PLTDECD, PLTDECM, PLTDECS or PLTDECSN is missing, or XPIXELSZ or + * YPIXELSZ is zero; {@code AST__FTCNV} if one of them does not convert; {@code AST__FUNDEF} + * if a card read has no value + */ + static FitsStore dssToStore(FitsChan fc, String method, String cls) { + FitsCardList cards = fc.cards(); + int rnd = fc.getFitsRounding(); + + // The optional keywords, with their defaults. + double cnpix1 = value(getFloat(cards, "CNPIX1", false, rnd, method, cls), 0.0); + double cnpix2 = value(getFloat(cards, "CNPIX2", false, rnd, method, cls), 0.0); + + // The required keywords. + double ppo3 = getFloat(cards, "PPO3", true, rnd, method, cls); + double ppo6 = getFloat(cards, "PPO6", true, rnd, method, cls); + double xpixelsz = getFloat(cards, "XPIXELSZ", true, rnd, method, cls); + double ypixelsz = getFloat(cards, "YPIXELSZ", true, rnd, method, cls); + double pltrah = getFloat(cards, "PLTRAH", true, rnd, method, cls); + double pltram = getFloat(cards, "PLTRAM", true, rnd, method, cls); + double pltras = getFloat(cards, "PLTRAS", true, rnd, method, cls); + double pltdecd = getFloat(cards, "PLTDECD", true, rnd, method, cls); + double pltdecm = getFloat(cards, "PLTDECM", true, rnd, method, cls); + double pltdecs = getFloat(cards, "PLTDECS", true, rnd, method, cls); + + // The first word of PLTDECSN, up to 10 characters. C copies them with strncpy into a + // buffer of 11, leaving it unterminated for a longer word; any such word differs from the + // "-" it is compared with. + String text = cards.getValue("PLTDECSN", FitsCardValue.Want.STRING, true, true, rnd, method, cls).s; + int start = 0; + while (start < text.length() && text.charAt(start) == ' ') { + start++; + } + int end = text.indexOf(' ', start); + String word = text.substring(start, end < 0 ? text.length() : end); + String pltdecsn = word.length() > 10 ? word.substring(0, 10) : word; + + // Related keywords, read only so that they are marked as used. + for (String key : new String[] {"PLTSCALE", "PPO1", "PPO2", "PPO4", "PPO5"}) { + getFloat(cards, key, false, rnd, method, cls); + } + + // The polynomial coefficients, BAD where absent. + double[] amdx = new double[20]; + double[] amdy = new double[20]; + for (int i = 0; i < 20; i++) { + amdx[i] = value(getFloat(cards, "AMDX" + (i + 1), false, rnd, method, cls), BAD); + amdy[i] = value(getFloat(cards, "AMDY" + (i + 1), false, rnd, method, cls), BAD); + } + + FitsStore store = new FitsStore(2); + + // The projection parameters equivalent to the coefficients. + pvFromAmd(store, 0, amdx); + pvFromAmd(store, 1, amdy); + + // The reference pixel. + if (xpixelsz == 0.0) { + throw Ast.err( + AstException.AST__BDFTS, method + "(" + cls + "): FITS keyword XPIXELSZ has illegal value 0.0"); + } + store.crpix[0] = (ppo3 / xpixelsz) - cnpix1 + 0.5; + if (ypixelsz == 0.0) { + throw Ast.err( + AstException.AST__BDFTS, method + "(" + cls + "): FITS keyword YPIXELSZ has illegal value 0.0"); + } + store.crpix[1] = (ppo6 / ypixelsz) - cnpix2 + 0.5; + + // The reference point. + store.crval[0] = 15.0 * (pltrah + pltram / 60.0 + pltras / 3600.0); + double crval2 = pltdecd + pltdecm / 60.0 + pltdecs / 3600.0; + if ("-".equals(pltdecsn)) { + crval2 = -crval2; + } + store.crval[1] = crval2; + + // The pixel sizes as the PC matrix, with CDELT 1. + store.pc[0][0] = -0.001 * xpixelsz; + store.pc[1][1] = 0.001 * ypixelsz; + store.cdelt[0] = 1.0; + store.cdelt[1] = 1.0; + + store.lonpole = 180.0; + store.equinox = 2000.0; + store.radesys = "FK5"; + store.wcsaxes = 2; + store.ctype[0] = "RA---TPN"; + store.ctype[1] = "DEC--TPN"; + return store; + } + + /** + * Sets the projection parameters of axis {@code axis} from the coefficients {@code amd} of + * that axis, each divided by 3600, as C's {@code DSSToStore} does for each axis; a parameter + * whose coefficients are not all present is left unset. + */ + private static void pvFromAmd(FitsStore store, int axis, double[] amd) { + Double[] pv = store.pv[axis]; + if (amd[2] != BAD) { + pv[0] = amd[2] / 3600.0; + } + if (amd[0] != BAD) { + pv[1] = amd[0] / 3600.0; + } + if (amd[1] != BAD) { + pv[2] = amd[1] / 3600.0; + } + if (amd[3] != BAD && amd[6] != BAD) { + pv[4] = (amd[3] + amd[6]) / 3600.0; + } + if (amd[4] != BAD) { + pv[5] = amd[4] / 3600.0; + } + if (amd[5] != BAD && amd[6] != BAD) { + pv[6] = (amd[5] + amd[6]) / 3600.0; + } + if (amd[7] != BAD && amd[11] != BAD) { + pv[7] = (amd[7] + amd[11]) / 3600.0; + } + if (amd[8] != BAD) { + pv[8] = amd[8] / 3600.0; + } + if (amd[9] != BAD && amd[11] != BAD) { + pv[9] = (amd[9] + amd[11]) / 3600.0; + } + if (amd[10] != BAD) { + pv[10] = amd[10] / 3600.0; + } + if (amd[12] != BAD) { + double p = amd[12] / 3600.0; + pv[17] = p; + pv[19] = 2 * p; + pv[21] = p; + } + } + + /** + * C's {@code DSSFromStore}: writes the primary description in {@code store} to {@code fc} as + * DSS cards, each in front of the current card or over a card with its keyword, if DSS can + * hold it: two pixel axes, RA and DEC in the TAN or TPN projection, LONPOLE unset or 180, + * FK5 at equinox J2000 (or no equinox), non-zero pixel sizes, no rotation, and projection + * parameters (TPN only) of the polynomial DSS describes. The corner pixel CNPIX is written as + * (1, 1), with the plate centre PPO3, PPO6 to match; AMDX7, AMDY7, AMDX12 and AMDY12, which + * duplicate other coefficients, are written as zero. + * + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return true if the description was written, false (with nothing written) if DSS cannot + * hold it + */ + static boolean dssFromStore(FitsChan fc, FitsPlaneStores store, String method, String cls) { + FitsStore st = store.get(' '); + if (st == null) { + st = new FitsStore(0); + } + + // Two-dimensional. + if (st.maxCrpixAxis() != 1) { + return false; + } + + // RA and DEC, both TAN or both TPN. + String cval = at(st.ctype, 0); + if (cval == null) { + return false; + } + boolean gottpn = "RA---TPN".equals(cval); + if (!"RA---TAN".equals(cval) && !gottpn) { + return false; + } + cval = at(st.ctype, 1); + if (cval == null) { + return false; + } + if (gottpn ? !"DEC--TPN".equals(cval) : !"DEC--TAN".equals(cval)) { + return false; + } + + // LONPOLE unset or 180, FK5, and the equinox unset or 2000. + if (st.lonpole != null && st.lonpole != 180.0) { + return false; + } + if (!"FK5".equals(st.radesys)) { + return false; + } + if (st.equinox != null && st.equinox != 2000.0) { + return false; + } + + // The pixel sizes, from CDELT and the diagonal of the PC matrix; both must be non-zero. + Double cdelt = at(st.cdelt, 0); + if (cdelt == null) { + return false; + } + double xpixelsz = cdelt * value(at(st.pc, 0, 0), 1.0); + cdelt = at(st.cdelt, 1); + if (cdelt == null) { + return false; + } + double ypixelsz = cdelt * value(at(st.pc, 1, 1), 1.0); + if (xpixelsz == 0.0 || ypixelsz == 0.0) { + return false; + } + xpixelsz *= -1000.0; + ypixelsz *= 1000.0; + + // No rotation. + Double val = at(st.pc, 0, 1); + if (val != null && val != 0.0) { + return false; + } + val = at(st.pc, 1, 0); + if (val != null && val != 0.0) { + return false; + } + + // The projection parameters, those of the unit polynomial for a TAN projection. + double[] pvx = new double[22]; + double[] pvy = new double[22]; + for (int m = 0; m < 22; m++) { + Double px = at(st.pv, 0, m); + pvx[m] = px == null || !gottpn ? (m == 1 ? 1.0 : 0.0) : px; + Double py = at(st.pv, 1, m); + pvy[m] = py == null || !gottpn ? (m == 1 ? 1.0 : 0.0) : py; + } + + // No other parameters, those DSS has no coefficient for zero, and the related ones + // related. + if (st.maxPvM() > 21) { + return false; + } + if (pvx[3] != 0.0 || pvy[3] != 0.0) { + return false; + } + for (int m = 11; m < 17; m++) { + if (pvx[m] != 0.0 || pvy[m] != 0.0) { + return false; + } + } + if (pvx[18] != 0.0 || pvy[18] != 0.0) { + return false; + } + if (pvx[20] != 0.0 || pvy[20] != 0.0) { + return false; + } + if (!MappingHelpers.astEqual(2 * pvx[17], pvx[19]) + || !MappingHelpers.astEqual(pvx[17], pvx[21]) + || !MappingHelpers.astEqual(2 * pvy[17], pvy[19]) + || !MappingHelpers.astEqual(pvy[17], pvy[21])) { + return false; + } + + // The polynomial coefficients. + double[] amdx = amdFromPv(pvx); + double[] amdy = amdFromPv(pvy); + + // The plate scale is the mean of the first X and Y coefficients. + double pltscl = 0.5 * (amdx[0] + amdy[0]); + + // The corner pixel (1, 1) and the plate centre that goes with it. + double cnpix1 = 1.0; + double cnpix2 = 1.0; + double ppo1 = 0.0; + double ppo2 = 0.0; + val = at(st.crpix, 0); + if (val == null) { + return false; + } + double ppo3 = xpixelsz * (val + cnpix1 - 0.5); + double ppo4 = 0.0; + double ppo5 = 0.0; + val = at(st.crpix, 1); + if (val == null) { + return false; + } + double ppo6 = ypixelsz * (val + cnpix2 - 0.5); + + // The reference RA in hours, from 0 to 24, as hours, minutes and seconds. + val = at(st.crval, 0); + if (val == null) { + return false; + } + double h = val / 15.0; + while (h < 0) { + h += 24.0; + } + while (h >= 24.0) { + h -= 24.0; + } + double pltrah = (int) h; + h = 60.0 * (h - pltrah); + double pltram = (int) h; + double pltras = 60.0 * (h - pltram); + + // The reference DEC in degrees, from -180 to 180, as a sign, degrees, minutes and + // seconds. + val = at(st.crval, 1); + if (val == null) { + return false; + } + double d = val; + while (d < -180.0) { + d += 360.0; + } + while (d >= 180.0) { + d -= 360.0; + } + String pltdecsn; + if (d > 0.0) { + pltdecsn = "+"; + } else { + pltdecsn = "-"; + d = -d; + } + double pltdecd = (int) d; + d = 60.0 * (d - pltdecd); + double pltdecm = (int) d; + double pltdecs = 60.0 * (d - pltdecm); + + FitsCardList cards = fc.cards(); + int rnd = fc.getFitsRounding(); + setFloat(cards, "CNPIX1", cnpix1, "X corner (pixels)", rnd); + setFloat(cards, "CNPIX2", cnpix2, "Y corner (pixels)", rnd); + setFloat(cards, "PPO1", ppo1, "Orientation co-efficients", rnd); + setFloat(cards, "PPO2", ppo2, "", rnd); + setFloat(cards, "PPO3", ppo3, "", rnd); + setFloat(cards, "PPO4", ppo4, "", rnd); + setFloat(cards, "PPO5", ppo5, "", rnd); + setFloat(cards, "PPO6", ppo6, "", rnd); + setFloat(cards, "XPIXELSZ", xpixelsz, "X pixel size (microns)", rnd); + setFloat(cards, "YPIXELSZ", ypixelsz, "Y pixel size (microns)", rnd); + setFloat(cards, "PLTRAH", pltrah, "RA at plate centre", rnd); + setFloat(cards, "PLTRAM", pltram, "", rnd); + setFloat(cards, "PLTRAS", pltras, "", rnd); + setFloat(cards, "PLTDECD", pltdecd, "DEC at plate centre", rnd); + setFloat(cards, "PLTDECM", pltdecm, "", rnd); + setFloat(cards, "PLTDECS", pltdecs, "", rnd); + cards.setValueAsWriter("PLTDECSN", FitsCard.Value.ofString(pltdecsn), "", rnd); + setFloat(cards, "PLTSCALE", pltscl, "Plate scale (arcsec/mm)", rnd); + String comm = "Plate solution x co-efficients"; + for (int i = 0; i < 20; i++) { + setFloat(cards, "AMDX" + (i + 1), amdx[i], comm, rnd); + comm = null; + } + comm = "Plate solution y co-efficients"; + for (int i = 0; i < 20; i++) { + setFloat(cards, "AMDY" + (i + 1), amdy[i], comm, rnd); + comm = null; + } + return true; + } + + /** + * The 20 coefficients of one axis of the polynomial that the projection parameters {@code pv} + * of that axis give, each times 3600, as C's {@code DSSFromStore} sets them; AMD7 and AMD12, + * which duplicate other coefficients, are zero. + */ + private static double[] amdFromPv(double[] pv) { + double[] amd = new double[20]; + amd[0] = 3600.0 * pv[1]; + amd[1] = 3600.0 * pv[2]; + amd[2] = 3600.0 * pv[0]; + amd[3] = 3600.0 * pv[4]; + amd[4] = 3600.0 * pv[5]; + amd[5] = 3600.0 * pv[6]; + amd[7] = 3600.0 * pv[7]; + amd[8] = 3600.0 * pv[8]; + amd[9] = 3600.0 * pv[9]; + amd[10] = 3600.0 * pv[10]; + amd[12] = 3600.0 * pv[17]; + return amd; + } + + /** C's {@code GetValue} of a floating value, marking the card read. */ + private static Double getFloat( + FitsCardList cards, String keyword, boolean report, int rnd, String method, String cls) { + FitsCardValue.Got g = cards.getValue(keyword, FitsCardValue.Want.FLOAT, report, true, rnd, method, cls); + return g == null ? null : g.d; + } + + /** {@code v}, or {@code unset} (in place of C's unset item) if it is null. */ + private static double value(Double v, double unset) { + return v != null ? v : unset; + } + + /** Element {@code i} of {@code a}, null (C's unset item) beyond its end. */ + private static T at(T[] a, int i) { + return i < a.length ? a[i] : null; + } + + /** Element {@code [i][j]} of {@code a}, null beyond its ends. */ + private static T at(T[][] a, int i, int j) { + return i < a.length && j < a[i].length ? a[i][j] : null; + } + + private static void setFloat(FitsCardList cards, String keyword, double value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofFloat(value), comment, rnd); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsEncIraf.java b/src/main/java/uk/ac/starlink/ast/FitsEncIraf.java new file mode 100644 index 0000000..9a8dadb --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsEncIraf.java @@ -0,0 +1,223 @@ +package uk.ac.starlink.ast; + +/** + * The cards of a FITS-IRAF header for the primary axis description of a FrameSet: C's {@code + * IRAFFromStore}, which writes the description {@link FitsFsetToStore#fsetToStore} made. + * + *

FITS-IRAF is FITS-WCS with these restrictions: only the primary description is written; the + * celestial axes must be RA/DEC, galactic or ecliptic, with no LONPOLE or LATPOLE, and a projection + * with no parameters other than TPN, or a SIN projection with parameters that are zero or give the + * old NCP projection, which is written as {@code -NCP}; SFL is written with the older code {@code + * GLS}; there is no WCSAXES keyword, so there must be as many WCS axes as pixel axes; RADECSYS is + * used in place of RADESYS; and the CD matrix is used in place of CDELT and PC. + * + *

Ported from fitschan.c {@code IRAFFromStore}, which includes the fix of upstream 6c47ddde: an + * MJD-OBS card already in the header, which a read leaves there, is set to the date written as + * DATE-OBS. The Rust port's {@code fitschan/enc_iraf.rs} is organised differently. + */ +final class FitsEncIraf { + + /** C's {@code AST__DD2R}: radians per degree. */ + private static final double AST__DD2R = 0.017453292519943295; + + private FitsEncIraf() {} + + /** + * C's {@code IRAFFromStore}: writes the primary description in {@code store} to {@code fc} as + * FITS-IRAF cards, each in front of the current card, if the description meets the + * restrictions of the encoding. A description lacking a CRPIX, CRVAL or CTYPE on one of its + * axes, or with a {@code -TAB} axis, stops the write part way, as C returns there; {@link + * FitsChan#write} then removes the cards written. + * + * @param fc the FitsChan written to + * @param store the descriptions + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return true if the description was written + */ + static boolean irafFromStore(FitsChan fc, FitsPlaneStores store, String method, String cls) { + int rnd = fc.getFitsRounding(); + FitsCardList cards = fc.cards(); + + // Only the primary description is written. + FitsStore st = store.get(' '); + if (st == null) { + // C reads unset values from the store of a version with nothing stored. + st = new FitsStore(0); + } + + // Whether the description meets the restrictions of the encoding. + boolean ok = true; + int[] axes = st.lonLatSpecAxes(store.naxis); + int axlon = axes[0]; + int axlat = axes[1]; + String lontype = null; + String lattype = null; + if (axlon >= 0 && axlat >= 0) { + lontype = at(st.ctype, axlon); + if (lontype == null) { + return false; + } + lattype = at(st.ctype, axlat); + if (lattype == null) { + return false; + } + int prj = FitsWcsCelestial.wcsPrjType(lattype.substring(4)); + ok = false; + if (prj == WcsMap.AST__TPN || prj == WcsMap.AST__WCSBAD) { + // FITS-IRAF cannot hold the AST-specific TPN projection. + ok = false; + } else if (prj != WcsMap.AST__SIN) { + // There must be no projection parameters. + if (st.maxPvM() == -1) { + ok = true; + } + if (prj == WcsMap.AST__SFL) { + lontype = withCode(lontype, "-GLS"); + lattype = withCode(lattype, "-GLS"); + } + } else { + // A SIN projection whose parameters are both zero, or the first zero and the + // second the cotangent of the reference latitude (the old NCP projection). + double p1 = value(at(st.pv, axlat, 1), 0.0); + double p2 = value(at(st.pv, axlat, 2), 0.0); + Double val = at(st.crval, axlat); + if (val != null && p1 == 0.0) { + if (p2 == 0.0) { + ok = true; + } else if (Math.abs(p2) >= 1.0e14 && val == 0.0) { + ok = true; + lontype = withCode(lontype, "-NCP"); + lattype = withCode(lattype, "-NCP"); + } else if (Math.abs(p2 * Math.tan(AST__DD2R * val) - 1.0) < 0.01) { + ok = true; + lontype = withCode(lontype, "-NCP"); + lattype = withCode(lattype, "-NCP"); + } + } + } + + // Only RA, galactic longitude and ecliptic longitude can be held. + if (!lontype.startsWith("RA--") && !lontype.startsWith("GLON") && !lontype.startsWith("ELON")) { + ok = false; + } + + // Nor can a LONPOLE or LATPOLE. + if (st.latpole != null || st.lonpole != null) { + ok = false; + } + } + + // There is no WCSAXES keyword, so there must be as many WCS axes as pixel axes. + int naxis = st.maxCrpixAxis() + 1; + if (naxis != store.naxis) { + ok = false; + } + if (!ok) { + return false; + } + + for (int i = 0; i < naxis; i++) { + Double val = at(st.crpix, i); + if (val == null) { + return false; + } + setFloat(cards, "CRPIX" + (i + 1), val, "Reference pixel on axis " + (i + 1), rnd); + } + for (int j = 0; j < naxis; j++) { + Double val = at(st.crval, j); + if (val == null) { + return false; + } + setFloat(cards, "CRVAL" + (j + 1), val, "Value at ref. pixel on axis " + (j + 1), rnd); + } + + // CTYPE, the celestial axes with the projection codes chosen above. + for (int i = 0; i < naxis; i++) { + String cval; + if (i == axlat) { + cval = lattype; + } else if (i == axlon) { + cval = lontype; + } else { + cval = at(st.ctype, i); + if (cval == null) { + return false; + } + } + if (cval.length() > 4 && "-TAB".equals(cval.substring(4))) { + return false; + } + String comm = at(st.ctypeCom, i); + if (comm == null) { + comm = "Type of co-ordinate on axis " + (i + 1); // codespell:ignore + } + setString(cards, "CTYPE" + (i + 1), cval, comm, rnd); + } + + // The CD matrix, the PC matrix with each row multiplied by its CDELT; zero elements left out. + for (int i = 0; i < naxis; i++) { + double cdelt = value(at(st.cdelt, i), 1.0); + for (int j = 0; j < naxis; j++) { + double val = value(at(st.pc, i, j), i == j ? 1.0 : 0.0); + val *= cdelt; + if (val != 0.0) { + setFloat(cards, "CD" + (i + 1) + "_" + (j + 1), val, "Transformation matrix element", rnd); + } + } + } + + for (int i = 0; i < naxis; i++) { + String cval = at(st.cunit, i); + if (cval != null) { + setString(cards, "CUNIT" + (i + 1), cval, "Units for axis " + (i + 1), rnd); + } + } + + if (st.radesys != null) { + setString(cards, "RADECSYS", st.radesys, "Reference frame for RA/DEC values", rnd); + } + if (st.equinox != null) { + setFloat(cards, "EQUINOX", st.equinox, "Epoch of reference equinox", rnd); + } + + // The date of observation as DATE-OBS. A read leaves any MJD-OBS card in the header, since + // other software may use it, so such a card is set to the same date. + if (st.mjdobs != null) { + double val = st.mjdobs; + setString(cards, "DATE-OBS", FitsDates.mjdToDateStr(val), "Date of observation", rnd); + if (cards.hasCard("MJD-OBS")) { + setFloat(cards, "MJD-OBS", val, "Modified Julian Date of observation", rnd); + } + } + return true; + } + + /** C's {@code strcpy( type + 4, code )}: the first four characters of {@code ctype} and {@code code}. */ + private static String withCode(String ctype, String code) { + return ctype.substring(0, 4) + code; + } + + /** {@code v}, or {@code unset} (in place of C's unset item) if it is null. */ + private static double value(Double v, double unset) { + return v != null ? v : unset; + } + + /** Element {@code i} of {@code a}, null (C's unset item) beyond its end. */ + private static T at(T[] a, int i) { + return i < a.length ? a[i] : null; + } + + /** Element {@code [i][j]} of {@code a}, null beyond its ends. */ + private static T at(T[][] a, int i, int j) { + return i < a.length && j < a[i].length ? a[i][j] : null; + } + + private static void setFloat(FitsCardList cards, String keyword, double value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofFloat(value), comment, rnd); + } + + private static void setString(FitsCardList cards, String keyword, String value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofString(value), comment, rnd); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsEncPc.java b/src/main/java/uk/ac/starlink/ast/FitsEncPc.java new file mode 100644 index 0000000..c46fb75 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsEncPc.java @@ -0,0 +1,356 @@ +package uk.ac.starlink.ast; + +import java.util.Locale; + +/** + * The cards of a FITS-PC header for the axis descriptions of a FrameSet: C's {@code PCFromStore}, + * which writes the descriptions {@link FitsFsetToStore#fsetToStore} made, the primary description + * and then the alternates {@code A} to the last with a CRVAL, in letter order. + * + *

FITS-PC, the encoding of the 1996 draft of the FITS-WCS papers, holds at most ten descriptions: + * the primary one and {@code A} to {@code I}. An alternate description is written as {@code + * CELT}, {@code CPIX}, {@code CVAL}, {@code CYPE} and {@code CNIT}, + * {@code } being 1 for {@code A}, and must share the primary description's PC matrix (written as + * {@code PCiiijjj}), RADECSYS, EQUINOX, LATPOLE, LONGPOLE, MJD-OBS and projection parameters (the + * latitude axis's, written as {@code PROJPm}). A description that cannot be written leaves no + * cards. Before the descriptions and after each, the current card is put after the last card + * describing WCS ({@link FitsCardList#positionWriteCursor}, C's {@code FindWcs}). + * + *

Ported from fitschan.c {@code PCFromStore}, with the Rust port's {@code fitschan/enc_pc.rs} + * ({@code write_pc}) as a guide; both include the fix of upstream bcbd87fa (an alternate + * description's MJD-OBS is compared with the primary one's only when it has one). + */ +final class FitsEncPc { + + /** C's {@code AST__BAD}, for the values C tests against it. */ + private static final double BAD = AstObject.AST__BAD; + + private FitsEncPc() {} + + /** The values the alternate descriptions must share with the primary one. */ + private static final class Primary { + /** The PC matrix, row by row, unit matrix elements included. */ + double[] pc; + + /** RADECSYS, or null if the primary description has none. */ + String sys; + + double eq = BAD; + double lt = BAD; + double ln = BAD; + double dt = BAD; + + /** The first ten projection parameters of the latitude axis, {@link #BAD} if unset. */ + final double[] pv = {BAD, BAD, BAD, BAD, BAD, BAD, BAD, BAD, BAD, BAD}; + } + + /** + * C's {@code PCFromStore}: writes the descriptions in {@code store} to {@code fc} as FITS-PC + * cards, each in front of the current card. Nothing is written if a version after {@code I} + * has a CRVAL. A description lacking a CDELT, CRPIX, CRVAL or CTYPE on one of its axes, whose + * CTYPE C's FITS-PC cannot express ({@code xxLT-}, {@code xxLN-}, {@code -TAB} or TPN), or + * whose projection parameters FITS-PC cannot hold, is not written: the cards it added are + * removed. So is an alternate description that does not share the primary one's values. An + * error while writing an alternate description is dropped, and the description not written, + * as C clears it. Alternate descriptions are written only if the primary one is. + * + * @param fc the FitsChan written to + * @param store the descriptions + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return true if any description was written, which is when the primary one was + */ + static boolean pcFromStore(FitsChan fc, FitsPlaneStores store, String method, String cls) { + FitsCardList cards = fc.cards(); + boolean ret = false; + + // FITS-PC can encode only 10 axis descriptions, the primary one included. + char sup = store.maxCrvalVersion(); + if (sup > 'I') { + return false; + } + + // The primary description, then the alternates A to sup. + Primary prim = new Primary(); + int maxm = maxPv(store.get(' ')); + char s = ' '; + while (s <= sup) { + FitsStore st = store.get(s); + if (st == null) { + // A version with nothing stored, which C reads as unset values, as it does in + // the store of every version. + st = new FitsStore(0); + } + boolean ok; + if (s == ' ') { + ok = writeVersion(fc, st, s, store.naxis, maxm, prim); + } else { + // C clears the error status after an alternate description, which is then not + // written, so that the next can be. + try { + ok = writeVersion(fc, st, s, store.naxis, maxm, prim); + } catch (AstException e) { + ok = false; + } + } + if (ok) { + ret = true; + } + + // The cards of a description not written are removed. + cards.fixNew(FitsCardList.NewScope.VERSION, !ok); + cards.positionWriteCursor(); + + if (s == ' ') { + // Alternate descriptions cannot stand on their own. + if (!ok) { + break; + } + s = 'A'; + } else { + s++; + } + } + return ret; + } + + /** C's {@code GetMaxJM( &(store->pv), ' ' )}: the highest PV index of the primary description, or -1. */ + private static int maxPv(FitsStore primary) { + return primary == null ? -1 : primary.maxPvM(); + } + + /** + * The cards of one description, {@code s}, from the body of C's version loop: false, C's + * {@code ok = 0; goto next}, if the description cannot be written. The primary description + * records in {@code prim} the values the alternates must share. + * + * @param storeNaxis C's {@code store->naxis}, the number of pixel axes + * @param maxm the highest projection parameter index of the primary description, or -1 + */ + private static boolean writeVersion(FitsChan fc, FitsStore st, char s, int storeNaxis, int maxm, Primary prim) { + int rnd = fc.getFitsRounding(); + FitsCardList cards = fc.cards(); + boolean primary = s == ' '; + int is = primary ? 0 : s - 'A' + 1; + + // The number of WCS axes, written as WCSAXES if the store has one. + int naxis; + if (st.wcsaxes != null) { + naxis = st.wcsaxes; + setInt(cards, primary ? "WCSAXES" : "WCSAXES" + s, naxis, "Number of WCS axes", rnd); + } else { + naxis = st.maxCrpixAxis() + 1; + } + + // The PC matrix, which all descriptions share: the primary description's is written, + // leaving out the elements equal to the unit matrix's, and each alternate must have the + // same. + double[] matrix = new double[naxis * naxis]; + for (int i = 0; i < naxis; i++) { + for (int j = 0; j < naxis; j++) { + Double v = at(st.pc, i, j); + matrix[i * naxis + j] = v != null ? v : (i == j ? 1.0 : 0.0); + } + } + if (primary) { + prim.pc = matrix; + for (int i = 0; i < naxis; i++) { + for (int j = 0; j < naxis; j++) { + double val = matrix[i * naxis + j]; + if (!MappingHelpers.astEqual(val, i == j ? 1.0 : 0.0)) { + setFloat(cards, String.format(Locale.ROOT, "PC%03d%03d", i + 1, j + 1), val, null, rnd); + } + } + } + } else if (prim.pc != null) { + // C compares the two matrices element by element in storage order, so matrices of + // different sizes are compared as flat arrays; C reads past the primary matrix for an + // alternate with more axes, where an element beyond it is taken as different here. + for (int k = 0; k < matrix.length; k++) { + if (k >= prim.pc.length || !MappingHelpers.astEqual(matrix[k], prim.pc[k])) { + return false; + } + } + } + + for (int i = 0; i < naxis; i++) { + Double val = at(st.cdelt, i); + if (val == null) { + return false; + } + setFloat(cards, key("CDELT", "ELT", is, i + 1), val, "Pixel scale on axis " + (i + 1), rnd); + } + for (int j = 0; j < naxis; j++) { + Double val = at(st.crpix, j); + if (val == null) { + return false; + } + setFloat(cards, key("CRPIX", "PIX", is, j + 1), val, "Reference pixel on axis " + (j + 1), rnd); + } + for (int i = 0; i < naxis; i++) { + Double val = at(st.crval, i); + if (val == null) { + return false; + } + setFloat(cards, key("CRVAL", "VAL", is, i + 1), val, "Value at ref. pixel on axis " + (i + 1), rnd); + } + + // CTYPE: FITS-PC has no -TAB axes, no celestial axes of type xxLT or xxLN, and no TPN + // projection (an AST code); SFL is written with the older code GLS. + for (int i = 0; i < naxis; i++) { + String cval = at(st.ctype, i); + if (cval == null) { + return false; + } + int nc = cval.length(); + if (nc > 4 && "-TAB".equals(cval.substring(4))) { + return false; + } + String comm = at(st.ctypeCom, i); + if (comm == null) { + comm = "Type of co-ordinate on axis " + (i + 1); // codespell:ignore + } + if ((nc > 2 && cval.startsWith("LT-", 2)) + || (nc > 2 && cval.startsWith("LN-", 2)) + || (nc > 4 && cval.startsWith("-TAB", 4))) { + return false; + } + int prj = nc > 4 ? FitsWcsCelestial.wcsPrjType(cval.substring(4)) : WcsMap.AST__WCSBAD; + if (prj == WcsMap.AST__SFL) { + cval = cval.substring(0, 4) + "-GLS"; + } + if (prj == WcsMap.AST__TPN) { + return false; + } + setString(cards, key("CTYPE", "YPE", is, i + 1), cval, comm, rnd); + } + + for (int i = 0; i < naxis; i++) { + String cval = at(st.cunit, i); + if (cval != null) { + setString(cards, key("CUNIT", "NIT", is, i + 1), cval, "Units for axis " + (i + 1), rnd); + } + } + + // RADECSYS, EQUINOX, LATPOLE and LONGPOLE: written for the primary description, and the + // same for each alternate one. C compares an alternate RADECSYS with the primary one's + // even when the primary description has none, reading an unset string; here they then + // differ. + if (st.radesys != null) { + if (primary) { + prim.sys = st.radesys; + setString(cards, "RADECSYS", st.radesys, "Reference frame for RA/DEC values", rnd); + } else if (!st.radesys.equals(prim.sys)) { + return false; + } + } + double val = value(st.equinox); + if (primary) { + prim.eq = val; + if (val != BAD) { + setFloat(cards, "EQUINOX", val, "Epoch of reference equinox", rnd); + } + } else if (!MappingHelpers.astEqual(val, prim.eq)) { + return false; + } + val = value(st.latpole); + if (primary) { + prim.lt = val; + if (val != BAD) { + setFloat(cards, "LATPOLE", val, "Latitude of native north pole", rnd); + } + } else if (!FitsStore.equalAng(val, prim.lt)) { + return false; + } + val = value(st.lonpole); + if (primary) { + prim.ln = val; + if (val != BAD) { + setFloat(cards, "LONGPOLE", val, "Longitude of native north pole", rnd); + } + } else if (!FitsStore.equalAng(val, prim.ln)) { + return false; + } + + // The date of observation: an alternate description with one must have the primary one's. + val = value(st.mjdobs); + if (primary) { + prim.dt = val; + if (val != BAD) { + setFloat(cards, "MJD-OBS", val, "Modified Julian Date of observation", rnd); + setString(cards, "DATE-OBS", FitsDates.mjdToDateStr(val), "Date of observation", rnd); + } + } else if (val != BAD && !MappingHelpers.astEqual(val, prim.dt)) { + return false; + } + + // Projection parameters: only those of the latitude axis, and only the first ten, with + // none for TAN, which in the 1996 draft had none. An alternate description must have the + // primary one's. + int[] axes = st.lonLatSpecAxes(storeNaxis); + int axlon = axes[0]; + int axlat = axes[1]; + if (axlon >= 0 && axlat >= 0) { + String cval = at(st.ctype, axlat); + int prj = cval != null ? FitsWcsCelestial.wcsPrjType(cval.substring(4)) : WcsMap.AST__WCSBAD; + for (int i = 0; i < naxis; i++) { + if (i == axlon) { + continue; + } + for (int m = 0; m <= maxm; m++) { + double pv = value(at(st.pv, i, m)); + if (primary) { + if (pv != BAD) { + if (i != axlat || prj == WcsMap.AST__TAN || m >= 10) { + return false; + } + setFloat(cards, "PROJP" + m, pv, "Projection parameter", rnd); + } + if (i == axlat && m < 10) { + prim.pv[m] = pv; + } + } else if (((i != axlat || m >= 10) && pv != BAD) + || (i == axlat && m < 10 && !MappingHelpers.astEqual(pv, prim.pv[m]))) { + return false; + } + } + } + } + return true; + } + + /** + * The keyword of axis {@code i} of description {@code is} (0 for the primary one): {@code + * }, or {@code C} for an alternate one. + */ + private static String key(String primary, String alt, int is, int i) { + return is == 0 ? primary + i : "C" + is + alt + i; + } + + /** {@code v}, or {@link #BAD} (C's unset item) if it is null. */ + private static double value(Double v) { + return v != null ? v : BAD; + } + + /** Element {@code i} of {@code a}, null (C's unset item) beyond its end. */ + private static T at(T[] a, int i) { + return i < a.length ? a[i] : null; + } + + /** Element {@code [i][j]} of {@code a}, null beyond its ends. */ + private static T at(T[][] a, int i, int j) { + return i < a.length && j < a[i].length ? a[i][j] : null; + } + + private static void setFloat(FitsCardList cards, String keyword, double value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofFloat(value), comment, rnd); + } + + private static void setString(FitsCardList cards, String keyword, String value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofString(value), comment, rnd); + } + + private static void setInt(FitsCardList cards, String keyword, int value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofInt(value), comment, rnd); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsFiducial.java b/src/main/java/uk/ac/starlink/ast/FitsFiducial.java index d71d021..d6f547c 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsFiducial.java +++ b/src/main/java/uk/ac/starlink/ast/FitsFiducial.java @@ -1,10 +1,10 @@ package uk.ac.starlink.ast; /** - * The fiducial point of a WcsMap projection in native spherical coordinates, as a FITS-WCS read - * needs it. + * The fiducial point of a WcsMap projection, in native spherical, projection plane and celestial + * coordinates, as FITS-WCS reads and writes need it. * - *

Ported from Rust {@code fitschan/fset_to_store/fiducial.rs} ({@code get_fiducial_nsc}). + *

Ported from Rust {@code fitschan/fset_to_store/fiducial.rs}, following fitschan.c. */ final class FitsFiducial { @@ -31,4 +31,48 @@ static double[] getFiducialNsc(WcsMap wcsmap) { } return new double[] {wcsmap.natLon(), wcsmap.natLat()}; } + + /** + * C's {@code GetFiducialPPC} (fitschan.c:12977): the projection plane coordinates, in radians, + * of the fiducial point of {@code map}, an inverted WcsMap, as {@code {x0, y0}}; found by + * transforming the native spherical coordinates of the fiducial point through the inverse of + * {@code map}, with zero on the other axes. + */ + static double[] getFiducialPpc(WcsMap map) { + int naxes = map.getNin(); + int axlon = map.getWcsAxis(1) - 1; + int axlat = map.getWcsAxis(2) - 1; + double[][] in = new double[naxes][1]; + double[] nsc = getFiducialNsc(map); + in[axlon][0] = nsc[0]; + in[axlat][0] = nsc[1]; + double[][] out = map.tranP(1, naxes, in, false, naxes); + return new double[] {out[axlon][0], out[axlat][0]}; + } + + /** + * C's {@code GetFiducialWCS} (fitschan.c:13076): the celestial longitude and latitude, in + * radians, of the fiducial point of the projection of {@code wcsmap}, as {@code {fidlon, + * fidlat}}; found by transforming the native spherical coordinates of the fiducial point, with + * zero on the other axes, through {@code map2}, from native spherical to world coordinates, + * and taking outputs {@code colon} and {@code colat}. + * + * @return the position, or null if either value is bad + */ + static double[] getFiducialWcs(WcsMap wcsmap, Mapping map2, int colon, int colat) { + int naxin = map2.getNin(); + int axlon = wcsmap.getWcsAxis(1) - 1; + int axlat = wcsmap.getWcsAxis(2) - 1; + double[][] ptr1 = new double[naxin][1]; + double[] nsc = getFiducialNsc(wcsmap); + ptr1[axlon][0] = nsc[0]; + ptr1[axlat][0] = nsc[1]; + double[][] ptr2 = map2.transform(ptr1, 1, true); + double fidlon = ptr2[colon][0]; + double fidlat = ptr2[colat][0]; + if (fidlon == AstObject.AST__BAD || fidlat == AstObject.AST__BAD) { + return null; + } + return new double[] {fidlon, fidlat}; + } } diff --git a/src/main/java/uk/ac/starlink/ast/FitsFsetToStore.java b/src/main/java/uk/ac/starlink/ast/FitsFsetToStore.java new file mode 100644 index 0000000..3e0c56f --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsFsetToStore.java @@ -0,0 +1,466 @@ +package uk.ac.starlink.ast; + +import java.util.ArrayList; +import java.util.List; + +/** + * C's {@code FsetToStore} (fitschan.c): the FITS-WCS axis descriptions of a FrameSet that a write + * turns into cards, with the functions it calls to make each description ({@code AddVersion}, + * {@code MakeFitsFrameSet}, {@code FitsAxisOrder}, {@code ReadCrval} and {@code SpectralAxes}). + * + *

The base Frame of the FrameSet is the pixel Frame and its current Frame gives the primary + * description; each other Frame (but those whose Domain begins {@code IWC}) gives an alternate + * description, and an offset SkyFrame also one of the absolute coordinates it is offset in. + * + *

Ported from Rust {@code fitschan/fset_to_store/mod.rs} and {@code wcs_write/plane_stores.rs}, + * following fitschan.c, whose structure is kept where Rust's follows from its ownership rules: the + * descriptions are made from the caller's FrameSet by Frame index, the SkyRefIs attribute of an + * offset SkyFrame is cleared and restored on the caller's FrameSet, and the store is indexed by + * version letter. + */ +final class FitsFsetToStore { + + /** Seconds per day, C's {@code SPD}. */ + private static final double SPD = 86400.0; + + /** Radians to degrees, C's {@code AST__DR2D}. */ + private static final double AST__DR2D = 57.29577951308232; + + /** Machine precision, C's {@code DBL_EPSILON}. */ + private static final double DBL_EPSILON = Math.ulp(1.0); + + private FitsFsetToStore() {} + + /** + * C's {@code FsetToStore}: the axis descriptions of {@code fset} for a FITS write. The primary + * description is made from the current Frame; then, unless AltAxes is NONE, a description of + * absolute coordinates if the current Frame is an offset SkyFrame, and for each other Frame in + * turn that is given a version letter ({@link FitsPlaneStores#versionLetters}) its description + * and, if it is an offset SkyFrame, one of absolute coordinates. Each description of absolute + * coordinates takes the letter after the last one taken, which C does not check against the + * letters Frames take from their Ident. + * + *

The SkyRefIs attribute of an offset SkyFrame is cleared through the FrameSet while its + * absolute description is made, and set back, so the FrameSet is remapped twice. + * + * @param fc the FitsChan written to, whose attributes control the descriptions, from whose + * cards {@link #readCrval} reads reference values, and to which warnings go + * @param fset the FrameSet + * @param naxis the number of axes of the base Frame + * @param dim the number of pixels along each pixel axis, {@code AST__BAD} where unknown + * @param enc the encoding written + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return the descriptions, or null if the primary description cannot be made + * @throws UnsupportedOperationException where a description needs a class this library lacks + */ + static FitsPlaneStores fsetToStore( + FitsChan fc, FrameSet fset, int naxis, double[] dim, FitsChan.Encoding enc, String method, String cls) { + FitsPlaneStores ret = new FitsPlaneStores(naxis); + int ibase = fset.getBase(); + int icurr = fset.getCurrent(); + int isoff = FitsSkySys.isSkyOff(fset, icurr); + + boolean primok = addVersion(fc, fset, ibase, icurr, ret, dim, ' ', enc, isoff, method, cls); + + int altaxes = fc.getAltAxes(); + if (primok && altaxes != 2) { + FitsPlaneStores.Letters letters = FitsPlaneStores.versionLetters(fset, ibase, icurr, altaxes); + char[] sid = letters.sid; + char s = letters.last; + + if (isoff != 0 && ++s <= 'Z') { + addVersion(fc, fset, ibase, icurr, ret, dim, s, enc, -1, method, cls); + } + + for (int ifrm = 1; ifrm <= fset.getNframe(); ifrm++) { + char s0 = sid[ifrm]; + if (s0 != 0 && s0 != 1) { + isoff = FitsSkySys.isSkyOff(fset, ifrm); + addVersion(fc, fset, ibase, ifrm, ret, dim, s0, enc, isoff, method, cls); + if (isoff != 0 && ++s <= 'Z') { + addVersion(fc, fset, ibase, ifrm, ret, dim, s, enc, -1, method, cls); + } + } + } + } + return primok ? ret : null; + } + + /** + * C's {@code AddVersion}: stores in version {@code s} of {@code stores} the description of + * Frame {@code iwcs} of {@code fs} relative to the pixel Frame {@code ipix}, and whether it + * could be made: the celestial axes ({@link FitsCelestialAxes#celestialAxes}), the spectral + * axes ({@link #spectralAxes}) and the rest ({@link FitsOtherAxes#otherAxes}) give the Mapping + * from world to intermediate world coordinates, and {@link FitsMakeIntWorld#makeIntWorld} the + * CRPIX, PC and CDELT values that make the pixel to intermediate world Mapping. For a + * description it makes, WCSNAME is the Frame's Domain if that is set, the primary description + * stores DUT1 (in days) and DTAI if they are set, a CRVAL smaller than {@code + * sqrt(DBL_EPSILON)} times the pixel size becomes zero, and each CRPIX is rounded to a + * millionth of a pixel. + * + *

The description cannot be made if the Frames cannot ({@link #makeFitsFrameSet}), if the + * Mapping has no inverse and TabOK is not positive, if no FITS axis order is found, or if the + * pixel to intermediate world Mapping is not linear enough. + * + * @param isoff positive to describe the offset coordinates of an offset SkyFrame; negative to + * describe the absolute coordinates it is offset in, its SkyRefIs being cleared meanwhile; + * zero for a Frame that is no offset SkyFrame + * @return whether the description was made + */ + static boolean addVersion( + FitsChan fc, + FrameSet fs, + int ipix, + int iwcs, + FitsPlaneStores stores, + double[] dim, + char s, + FitsChan.Encoding enc, + int isoff, + String method, + String cls) { + // For the absolute coordinates of an offset SkyFrame, clear its SkyRefIs through the + // FrameSet, so that it is remapped, noting the original value as a negative isoff. + String oldSkyrefis = null; + int icurr = 0; + int jsoff = isoff; + if (isoff < 0) { + icurr = fs.getCurrent(); + fs.setCurrent(iwcs); + oldSkyrefis = fs.getC("SkyRefIs"); + if ("POLE".equalsIgnoreCase(oldSkyrefis)) { + jsoff = -1; + } else if ("ORIGIN".equalsIgnoreCase(oldSkyrefis)) { + jsoff = -2; + } else { + jsoff = -3; + } + fs.clear("SkyRefIs"); + fs.setCurrent(icurr); + } + + FrameSet fset; + try { + fset = makeFitsFrameSet(fc, fs, ipix, iwcs, enc, method, cls); + } finally { + if (oldSkyrefis != null) { + fs.setCurrent(iwcs); + fs.setC("SkyRefIs", oldSkyrefis); + fs.setCurrent(icurr); + } + } + if (fset == null) { + return false; + } + + Mapping mapping = fset.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Frame wcsfrm = fset.getFrame(FrameSet.AST__CURRENT); + if (!mapping.getTranInverse() && fc.getTabOK() <= 0) { + return false; + } + + int nwcs = mapping.getNout(); + int[] wperm = new int[nwcs]; + if (!fitsAxisOrder(fc, nwcs, wcsfrm, wperm) && !FitsWorldAxes.worldAxes(fc, mapping, dim, wperm)) { + return false; + } + + boolean[] axisDone = new boolean[nwcs]; + double[] crvals = readCrval(fc, wcsfrm, s, method, cls); + + FitsStore store = stores.version(s, Math.max(fset.getNin(), nwcs)); + + Mapping iwcmap = FitsCelestialAxes.celestialAxes(fc, fset, dim, wperm, s, store, axisDone, jsoff, method, cls); + Mapping tmap = spectralAxes(fset); + iwcmap = new CmpMap(iwcmap, tmap, true); + tmap = FitsOtherAxes.otherAxes(fc, fset, dim, wperm, s, store, crvals, axisDone, method, cls); + iwcmap = new CmpMap(iwcmap, tmap, true); + + // The pixel to world Mapping is taken again, as C takes it again in case SpectralAxes + // remapped the world Frame. + mapping = fset.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Mapping pixiwcmap = new CmpMap(mapping, iwcmap, true); + + double fitstol = fc.getFitsTol(); + // Only FITS-WCS writes SIP coefficients. + boolean sipok = enc == FitsChan.Encoding.FITS_WCS && fc.getSipOK() != 0; + + boolean ret = + FitsMakeIntWorld.makeIntWorld(pixiwcmap, wcsfrm, wperm, s, store, dim, fitstol, sipok, method, cls); + + if (ret) { + if (wcsfrm.testDomain()) { + store.wcsname = wcsfrm.getDomain(); + } + if (wcsfrm.testDut1() && s == ' ') { + store.dut1 = wcsfrm.getDut1() / SPD; + } + if (wcsfrm.testDtai() && s == ' ') { + store.dtai = wcsfrm.getDtai(); + } + + // CRVAL values very small compared with the pixel size become zero. + for (int iax = 0; iax < nwcs; iax++) { + int fitsI = wperm[iax]; + Double crval = store.crval[fitsI]; + if (crval != null) { + double cdelt2 = 0.0; + for (int fitsJ = 0; fitsJ < nwcs; fitsJ++) { + Double p = store.pc[fitsI][fitsJ]; + double pc = p != null ? p : (fitsI == fitsJ ? 1.0 : 0.0); + cdelt2 += pc * pc; + } + double cdelt = store.cdelt[fitsI] != null ? store.cdelt[fitsI] : 1.0; + cdelt2 *= cdelt * cdelt; + if (Math.abs(crval) < Math.sqrt(DBL_EPSILON * cdelt2)) { + store.crval[fitsI] = 0.0; + } + } + } + + // CRPIX values are rounded to the nearest millionth of a pixel. + for (int iax = 0; iax < nwcs; iax++) { + Double crpix = store.crpix[iax]; + if (crpix != null) { + store.crpix[iax] = Math.floor(crpix * 1.0e6 + 0.5) * 1.0e-6; + } + } + } + return ret; + } + + /** + * C's {@code MakeFitsFrameSet}: a new FrameSet whose base Frame is a copy of Frame {@code ipix} + * of {@code fset} and whose current Frame is a copy of Frame {@code iwcs}, joined by a copy of + * the Mapping between them, made to fit the FITS model. Each axis of the world Frame that is + * neither a SkyFrame axis (of a SkyFrame whose Domain is {@code SKY}) nor a spectral axis is + * changed from its internal units to its Unit: the Mapping gains the conversion, or where + * there is none, the Unit is set to the internal units (to degrees for internal radians, + * converted by a ZoomMap). + * + *

C's other changes are for a SpecFrame, which this library lacks: one with a celestial + * reference point gains celestial axes, or has the reference point made that of the celestial + * axes; and for FITS-CLASS {@code AddEncodingFrame} adds a Frame for the SpecFrame and + * SkyFrame. + * + * @return the FrameSet, or null if the world Frame holds axes of two SkyFrames + */ + // C compares the pointers astPrimaryFrame returns: whether two axes are in the same SkyFrame. + @SuppressWarnings({"ReferenceEquality", "PMD.CompareObjectsWithEquals"}) + static FrameSet makeFitsFrameSet( + FitsChan fc, FrameSet fset, int ipix, int iwcs, FitsChan.Encoding enc, String method, String cls) { + Frame pixfrm = (Frame) fset.getFrame(ipix).copy(); + Frame wcsfrm = (Frame) fset.getFrame(iwcs).copy(); + Mapping map = (Mapping) fset.getMapping(ipix, iwcs).copy(); + int nwcs = wcsfrm.getNaxes(); + + // The SkyFrame of the world Frame, which must be its only one, and the Mapping from the + // internal units of each axis to its Unit. + Mapping remap = null; + Frame skyfrm = null; + boolean ok = true; + int[] paxis = new int[1]; + for (int iax = 0; iax < nwcs; iax++) { + Frame pframe = wcsfrm.primaryFrame(iax + 1, paxis); + Mapping umap = null; + if (FitsMakeIntWorld.isASkyFrame(pframe)) { + if (skyfrm != null) { + if (pframe != skyfrm) { + ok = false; + break; + } + } else { + skyfrm = pframe; + } + } else { + String extunit = pframe.getUnit(paxis[0]); + String intunit = pframe.getInternalUnit(paxis[0]); + if (!extunit.equals(intunit)) { + // An error from the unit mapper is ignored, as C ignores it. + try { + umap = Units.unitMapper(intunit, extunit); + } catch (AstException e) { + umap = null; + } + if (umap == null) { + if ("rad".equals(intunit)) { + umap = new ZoomMap(1, AST__DR2D); + extunit = "deg"; + } else { + extunit = intunit; + } + wcsfrm.setUnit(iax + 1, extunit); + } + } + } + if (umap == null) { + umap = new UnitMap(1); + } + remap = remap != null ? new CmpMap(remap, umap, false) : umap; + } + + if (remap != null && !(remap.simplify() instanceof UnitMap)) { + map = new CmpMap(map, remap, true); + } + + // Two SkyFrames make the FrameSet unusable. C then passes a NULL FrameSet to + // AddEncodingFrame, which dereferences it; the FrameSet that is not made is reported here + // as C's caller expects. + if (!ok) { + return null; + } + FrameSet ret = new FrameSet(pixfrm); + ret.addFrame(FrameSet.AST__BASE, map, wcsfrm); + return ret; + } + + /** + * C's {@code FitsAxisOrder}: sets {@code perm} to the zero-based FITS axis of each axis of + * {@code wcsfrm} that the FitsChan's FitsAxisOrder gives, and returns whether it gives them + * (it does unless it is {@code }). {@code } keeps the Frame's order; a list of + * axis Symbols, matched ignoring case and with words naming no axis passed over, gives the + * axes their places in the list. + * + * @throws AstException with status {@code AST__ATTIN} if the list names an axis twice or + * leaves one out + */ + static boolean fitsAxisOrder(FitsChan fc, int nwcs, Frame wcsfrm, int[] perm) { + for (int i = 0; i < nwcs; i++) { + perm[i] = i; + } + String attr = fc.getFitsAxisOrder(); + boolean result = !AstObject.chrMatch(attr, ""); + if (result && !AstObject.chrMatch(attr, "")) { + // C's KeyMap with KeyCase=0: the axis index of each Symbol, ignoring case. + KeyMap km = new KeyMap(); + km.setKeyCase(false); + for (int i = 0; i < nwcs; i++) { + km.mapPut0I(wcsfrm.getC("Symbol(" + (i + 1) + ")"), i, null); + } + int k = 0; + for (String word : chrSplit(attr)) { + Integer j = km.mapGet0I(word); + if (j != null) { + if (j < 0) { + throw Ast.err( + AstException.AST__ATTIN, + "astWrite(fitschan): attribute FitsAxisOrder (" + attr + ") refers to axis " + word + + " more than once."); + } + perm[j] = k++; + km.mapPut0I(word, -1, null); + } + } + for (int i = 0; i < nwcs; i++) { + String sym = wcsfrm.getC("Symbol(" + (i + 1) + ")"); + Integer j = km.mapGet0I(sym); + if (j != null && j >= 0) { + throw Ast.err( + AstException.AST__ATTIN, + "astWrite(fitschan): attribute FitsAxisOrder (" + attr + + ") does not specify a position for WCS axis '" + sym + "'."); + } + } + } + return result; + } + + /** C's {@code astChrSplit}: the words of {@code str}, separated by white space. */ + private static List chrSplit(String str) { + List words = new ArrayList<>(); + int i = 0; + int n = str.length(); + while (i < n) { + while (i < n && CScan.isCSpace(str.charAt(i))) { + i++; + } + int start = i; + while (i < n && !CScan.isCSpace(str.charAt(i))) { + i++; + } + if (i > start) { + words.add(str.substring(start, i)); + } + } + return words; + } + + /** + * C's {@code ReadCrval}: the reference point of axis description {@code s} in the cards of + * {@code fc}, in the coordinates of {@code wcsfrm}, or null if there is none. The cards are + * read afresh, as if none had been read: in a copy of the FitsChan with its Encoding cleared + * and every card marked unused, the CRVAL values of the description are read (all of them up + * to the highest axis number, or none), a FrameSet is read, and the CRVAL position is + * transformed from its Frame whose Ident is {@code s} to {@code wcsfrm}, if that Frame has as + * many axes as there are CRVAL values and can be converted to {@code wcsfrm} with the Domain + * of {@code wcsfrm}. An error in reading the FrameSet gives null, as C clears it. + * + * @return the reference point, with an element for each axis of {@code wcsfrm}, or null + * @throws UnsupportedOperationException if reading the FrameSet needs a class or encoding this + * library lacks + */ + static double[] readCrval(FitsChan fc0, Frame wcsfrm, char s, String method, String cls) { + FitsChan fc = (FitsChan) fc0.copy(); + fc.clear("Encoding"); + fc.cards().resetUsed(); + + String template = s == ' ' ? "CRVAL%d" : "CRVAL%d" + s; + FitsCardList.KeyFields kf = fc.cards().keyFields(template, 1); + if (kf.n <= 0) { + return null; + } + int hii = kf.hi[0]; + double[] crval = new double[hii]; + boolean ok = true; + for (int iax = 0; iax < hii && ok; iax++) { + Double v = fc.cards().getFloat(FitsWcsKeywords.keyFor("CRVAL", iax + 1, s)); + if (v == null) { + ok = false; + } else { + crval[iax] = v; + } + } + if (!ok) { + return null; + } + + double[] ret = null; + fc.cards().clearCard(); + FrameSet fs; + try { + AstObject obj = fc.read(); + fs = obj instanceof FrameSet ? (FrameSet) obj : null; + } catch (AstException e) { + fs = null; + } + if (fs != null) { + int nfr = fs.getNframe(); + int ifr; + for (ifr = 1; ifr <= nfr; ifr++) { + fs.setCurrent(ifr); + Frame tfrm = fs.getFrame(ifr); + String id = tfrm.test("Ident") ? tfrm.getIdent() : null; + if (id != null && id.length() == 1 && id.charAt(0) == s) { + break; + } + } + if (ifr <= nfr && fs.getNaxes() == hii) { + FrameSet tfs = fs.convert(wcsfrm, wcsfrm.getDomain()); + if (tfs != null) { + ret = tfs.tranN(1, hii, crval, true, wcsfrm.getNaxes()); + } + } + } + return ret; + } + + /** + * C's {@code SpectralAxes} for a FrameSet of this library, which holds no SpecFrame: no axis is + * spectral, nothing is stored, and the Mapping from world to intermediate world coordinates + * is a UnitMap passing every axis of the current Frame. + */ + static Mapping spectralAxes(FrameSet fs) { + return new UnitMap(fs.getNout()); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsInvertable.java b/src/main/java/uk/ac/starlink/ast/FitsInvertable.java new file mode 100644 index 0000000..5b874a7 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsInvertable.java @@ -0,0 +1,39 @@ +package uk.ac.starlink.ast; + +/** + * C's {@code MakeInvertable} (fitschan.c): makes a square CD matrix invertible where degenerate + * grid axes allow it. + * + *

Ported from Rust {@code fitschan/fset_to_store/invertable.rs}, following fitschan.c. + */ +final class FitsInvertable { + + private FitsInvertable() {} + + /** + * Sets to 1 the diagonal element of each input of {@code fullmat} that affects no output and + * whose grid axis spans a single pixel: such an input is always zero, so the outputs do not + * change. + * + *

C reads a dimension for every input of the matrix, though its caller holds one per pixel + * axis, fewer than the inputs when degenerate axes have been added, and so reads past the end + * of the array; an input with no dimension is taken to be one whose dimension is not 1. + * + * @param fullmat the {@code n} by {@code n} matrix, indexed {@code [input][output]} + * @param dim the dimension of each pixel axis, {@code AST__BAD} where unknown + */ + static void makeInvertable(double[][] fullmat, int n, double[] dim) { + for (int i = 0; i < n; i++) { + boolean unused = true; + for (int j = 0; j < n; j++) { + if (fullmat[i][j] != 0.0) { + unused = false; + break; + } + } + if (unused && i < dim.length && dim[i] == 1.0) { + fullmat[i][i] = 1.0; + } + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsIsMapLinear.java b/src/main/java/uk/ac/starlink/ast/FitsIsMapLinear.java new file mode 100644 index 0000000..a3097e6 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsIsMapLinear.java @@ -0,0 +1,202 @@ +package uk.ac.starlink.ast; + +import java.util.Arrays; + +/** + * C's {@code IsMapLinear} (fitschan.c): whether an output of a Mapping is a linear function of its + * inputs over a box. + * + *

Ported from Rust {@code fitschan/fset_to_store/is_map_linear.rs}, following fitschan.c. + */ +final class FitsIsMapLinear { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** The number of positions fitted, C's {@code NP}. */ + private static final int NP = 20; + + private FitsIsMapLinear() {} + + /** + * Whether output {@code coordOut} of {@code smap} is linear in its inputs over the box from + * {@code lbndIn} to {@code ubndIn}: {@code NP} positions evenly spread over the range of the + * output (from C's {@code MapBox}), the other outputs held at their values where it is lowest, + * are transformed back to the inputs, and a straight line fitted to each input that varies + * must reproduce it to within 1e-7 of its range. The fit is made to values offset by the first + * of each. When a single input feeds the output, the Mapping split off for it is used. + * + *

As C does, the search for the largest input value starts from {@code DBL_MIN}, the smallest + * positive normal value, so for inputs that are all negative it is {@code DBL_MIN}. + * + * @param smap the Mapping, which is inverted and inverted back to split it, as C does + * @param coordOut the output to test, zero-based + * @param coordIn null, or an array whose first element receives the zero-based index of the + * input that alone feeds the output, or -1 if there is none + */ + static boolean isMapLinear(Mapping smap, double[] lbndIn, double[] ubndIn, int coordOut, int[] coordIn) { + if (coordIn != null) { + coordIn[0] = -1; + } + + // Split off the output, inverting the Mapping so that other outputs whose inverse is not + // defined do not stop the split. + MapSplit split; + smap.invert(); + try { + split = smap.mapSplit(new int[] {coordOut}); + } finally { + smap.invert(); + } + Mapping map; + double[] lbnd = lbndIn; + double[] ubnd = ubndIn; + int cout = coordOut; + if (split != null && split.map.getNout() == 1) { + int ins0 = split.outputs[0]; + if (coordIn != null) { + coordIn[0] = ins0; + } + map = split.map; + map.invert(); + lbnd = Arrays.copyOfRange(lbndIn, ins0, lbndIn.length); + ubnd = Arrays.copyOfRange(ubndIn, ins0, ubndIn.length); + cout = 0; + } else { + map = smap; + } + + boolean ret = false; + if (map.getTranForward() && map.getTranInverse()) { + int nin = map.getNin(); + int nout = map.getNout(); + double[] xl = new double[nin]; + + // The bounds of the output, and the input position of its lowest value. A box that + // cannot be found leaves the Mapping non-linear, C clearing the error. + boolean boxok; + double lbndOut = 0.0; + double ubndOut = 0.0; + try { + double[] bounds = MapBox.mapBox(map, lbnd, ubnd, true, cout, xl, null); + lbndOut = bounds[0]; + ubndOut = bounds[1]; + boxok = true; + if (MappingHelpers.astEqual(lbndOut, ubndOut)) { + double m = 0.5 * (lbndOut + ubndOut); + if (Math.abs(m) > 1.0e-15) { + lbndOut = 0.9 * m; + ubndOut = 1.1 * m; + } else { + lbndOut = -1.0; + ubndOut = 1.0; + } + } + } catch (AstException e) { + boxok = false; + } + + if (boxok) { + double[][] ptr1 = new double[nin][NP]; + for (int i = 0; i < nin; i++) { + Arrays.fill(ptr1[i], AST__BAD); + ptr1[i][0] = xl[i]; + } + double[][] ptr2 = map.transform(ptr1, NP, true); + + // NP positions spread along the output from its lowest value, the other outputs + // held at their values there. + double delta = (ubndOut - lbndOut) / (NP - 1); + for (int i = 0; i < nout; i++) { + double[] p = ptr2[i]; + if (i == cout) { + for (int j = 0; j < NP; j++) { + p[j] = lbndOut + j * delta; + } + } else { + double p0 = p[0]; + Arrays.fill(p, p0); + } + } + ptr1 = map.transform(ptr2, NP, false); + + ret = true; + double[] s = ptr2[cout]; + double soff = s[0]; + for (int i = 0; i < nin; i++) { + double[] p = ptr1[i]; + double poff = p[0]; + double sp = 0.0; + double ss = 0.0; + double sps = 0.0; + double sn = 0.0; + double ss2 = 0.0; + double inLbnd = Double.MAX_VALUE; + double inUbnd = Double.MIN_NORMAL; + for (int j = 0; j < NP; j++) { + double sv = s[j]; + double pv = p[j]; + if (pv != AST__BAD && sv != AST__BAD) { + if (pv < inLbnd) { + inLbnd = pv; + } + if (pv > inUbnd) { + inUbnd = pv; + } + sv -= soff; + pv -= poff; + sp += pv; + ss += sv; + sps += pv * sv; + sn += 1.0; + ss2 += sv * sv; + } else { + sn = 0.0; + break; + } + } + + // Inputs independent of the output are ignored. + if (!MappingHelpers.astEqual(inLbnd, inUbnd)) { + double d = ss * ss - sn * ss2; + if (sn > 0.0 && d != 0.0) { + double m = (sp * ss - sps * sn) / d; + double c = (sps * ss - sp * ss2) / d; + for (int j = 0; j < NP; j++) { + p[j] -= poff + m * (s[j] - soff) + c; + } + + // A second fit, to the residuals, which the first sometimes leaves + // with a gradient. + sp = 0.0; + sps = 0.0; + for (int j = 0; j < NP; j++) { + double pv = p[j]; + sp += pv; + sps += pv * (s[j] - soff); + } + m = (sp * ss - sps * sn) / d; + c = (sps * ss - sp * ss2) / d; + for (int j = 0; j < NP; j++) { + p[j] -= m * (s[j] - soff) + c; + } + + double tol = 1.0e-7 * (inUbnd - inLbnd); + for (int j = 0; j < NP; j++) { + if (Math.abs(p[j]) > tol) { + ret = false; + break; + } + } + } else { + ret = false; + } + } + if (!ret) { + break; + } + } + } + } + return ret; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsLogMap.java b/src/main/java/uk/ac/starlink/ast/FitsLogMap.java new file mode 100644 index 0000000..6893417 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsLogMap.java @@ -0,0 +1,42 @@ +package uk.ac.starlink.ast; + +/** + * The MathMap C's {@code LogAxis} (fitschan.c) makes to test an axis for the {@code -LOG} + * algorithm: forward {@code logs=log(s)}, inverse {@code s=exp(logs)}, with SimpFI and SimpIF set. + * It computes what that MathMap computes, as mathmap.c's evaluator does it: the logarithm of a + * value that is not positive is bad, and so is an exponential that overflows. + * + *

A MathMap merges in simplification only with another MathMap (mathmap.c {@code MapMerge}). The + * Mappings this one meets come from FrameSets of this library, which hold no MathMap, so it never + * merges with anything; nor does C override any other Mapping method for MathMap but {@code + * Equal}, which nothing in {@code LogAxis} reaches. + */ +final class FitsLogMap extends Mapping { + + /** Constructs the Mapping, one input and one output, defined in both directions. */ + FitsLogMap() { + super(1, 1, true, true); + } + + @Override + void transformInto(double[][] in, int npoint, boolean forward, double[][] out) { + validateTransformInto(in, npoint, forward, out); + boolean fwd = effectiveForward(forward); + double[] a = in[0]; + double[] o = out[0]; + for (int p = 0; p < npoint; p++) { + double x = a[p]; + if (isBad(x)) { + o[p] = AST__BAD; + } else if (fwd) { + // mathmap.c OP_LOG: ( x > 0.0 ) ? log( x ) : AST__BAD. + o[p] = x > 0.0 ? Math.log(x) : AST__BAD; + } else { + // mathmap.c OP_EXP through CATCH_MATHS_OVERFLOW: an overflow, which only a finite + // argument reaches here, is AST__BAD. + double r = Math.exp(x); + o[p] = Double.isInfinite(r) ? AST__BAD : r; + } + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsMakeIntWorld.java b/src/main/java/uk/ac/starlink/ast/FitsMakeIntWorld.java new file mode 100644 index 0000000..c17bf84 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsMakeIntWorld.java @@ -0,0 +1,440 @@ +package uk.ac.starlink.ast; + +import java.util.Arrays; +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * C's {@code MakeIntWorld} and {@code NearestPix} (fitschan.c): the CRPIX, PC, CDELT and WCSAXES + * values of a FitsChan write, from the Mapping from grid to intermediate world coordinates. + * + *

Ported from Rust {@code fitschan/fset_to_store/make_int_world.rs}, following fitschan.c. + */ +final class FitsMakeIntWorld { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** Degrees to radians, C's {@code AST__DD2R}. */ + private static final double AST__DD2R = 0.017453292519943295; + + /** C's {@code DBL_EPSILON}. */ + private static final double DBL_EPSILON = Math.ulp(1.0); + + private FitsMakeIntWorld() {} + + /** + * Stores in {@code store} the CRPIX, PC and CDELT values (and WCSAXES, when there are fewer + * grid than WCS axes) describing {@code cmap}, which must be linear with an optional shift of + * origin. A Mapping with more outputs than inputs gets degenerate grid axes, whose unit + * vectors are chosen orthogonal to the other grid axes and scaled to look natural; the CRVAL + * values, which the caller stores first, may be changed for them. When {@code sipok} is true + * and {@code fr} holds a celestial longitude axis, any distortion of the celestial axes that + * {@link FitsSipIntWorld#sipIntWorld} can describe with SIP coefficients is stored as those + * coefficients, and its CRPIX and CD values are used for the celestial axes. + * + *

C stores CDELT values even when it fails, from memory it never sets; when the + * description fails nothing is stored here but the SIP coefficients and CTYPE values, which C + * stores too. + * + * @param cmap the grid to intermediate world coordinate Mapping, with at least as many + * outputs as inputs + * @param fr the final WCS Frame + * @param wperm for each axis of {@code fr}, the zero-based index of the FITS-WCS axis that + * describes it + * @param s the axis description character: a space for the primary description, else + * {@code 'A'} to {@code 'Z'} + * @param store the store, which must hold as many axes as {@code cmap} has outputs + * @param dim the grid dimensions, {@code AST__BAD} where unknown, one per input of {@code + * cmap} + * @param fitstol the largest departure from linearity allowed on any axis, as a fraction of a + * grid pixel + * @param sipok whether distortion may be described with SIP coefficients + * @param method the calling method, for messages + * @param cls the class of the object being written, for messages + * @return whether the values were found + */ + // C compares the pointers astPrimaryFrame returns: whether two axes are in the same SkyFrame. + @SuppressWarnings({"ReferenceEquality", "PMD.CompareObjectsWithEquals"}) + static boolean makeIntWorld( + Mapping cmap, + Frame fr, + int[] wperm, + char s, + FitsStore store, + double[] dim, + double fitstol, + boolean sipok, + String method, + String cls) { + int nin = cmap.getNin(); + int nout = cmap.getNout(); + if (nout < nin) { + return false; + } + Mapping map = cmap.simplify(); + + // The Mapping outputs of the longitude and latitude axes of any SkyFrame. + int lonax = -1; + int latax = -1; + int[] paxis = new int[1]; + for (int i = 0; i < nout; i++) { + Frame pfrm = fr.primaryFrame(i + 1, paxis); + if (pfrm instanceof SkyFrame) { + if (paxis[0] == 1) { + lonax = i; + } else { + latax = i; + } + } + } + + // SIP coefficients for any distortion of the celestial axes, with their CRPIX and CD + // values; the Mapping without the distortion is used from here on, so that it does not + // break the linearity test of the other axes. + boolean havesip = false; + int[] sipax = new int[2]; + double[] crpixSip = new double[2]; + double[] cdSip = new double[4]; + if (sipok && lonax != -1) { + Mapping sipmap = FitsSipIntWorld.sipIntWorld( + map, fitstol, lonax, latax, s, store, dim, sipax, crpixSip, cdSip, method, cls); + if (sipmap != null) { + map = sipmap; + havesip = true; + } + } + + int nwcs = fr.getNaxes(); + + double[] g = new double[nin]; + double[] g0 = new double[nin]; + double[] w0 = new double[nout]; + double[] tol = new double[nout]; + double[][] partmat = new double[nout][]; + boolean[] lin = new boolean[nout]; + int[] pperm = new int[nout]; + int[] skycol = new int[nout]; + double[] cdmat = new double[nout * nout]; + double[] cdelt = new double[nout]; + double[][] ptrg = new double[nin][nin + 1]; + double[][] ptrw = new double[nout][nin + 1]; + + // A root grid position with good IWC coordinates, those coordinates, and a tolerance on + // each IWC axis: a fraction fitstol of the largest change caused by moving 1 pixel along + // any grid axis, or, if that is zero, a very small fraction of the axis value. + boolean ret = FitsWcsDecompose.findBasisVectors(map, nin, nout, dim, ptrg, ptrw); + for (int j = 0; j < nin; j++) { + g0[j] = ptrg[j][0]; + } + for (int j = 0; j < nout; j++) { + w0[j] = ptrw[j][0]; + tol[j] = 0.0; + for (int i = 0; i < nin; i++) { + double err = Math.abs(ptrw[j][i + 1] - w0[j]); + if (err > tol[j]) { + tol[j] = err; + } + } + tol[j] *= fitstol; + if (tol[j] == 0.0) { + tol[j] = w0[j] * DBL_EPSILON * 1.0e5; + } + if (tol[j] == 0.0) { + tol[j] = Math.sqrt(Double.MIN_NORMAL); + } + } + + // The CD matrix: column i is the IWC vector of a unit vector along grid axis i. + Arrays.fill(cdmat, AST__BAD); + for (int i = 0; i < nin && ret; i++) { + Arrays.fill(g, 0.0); + g[i] = 1.0; + partmat[i] = FitsWcsDecompose.fitLine(map, g, g0, w0, dim[i], tol); + if (partmat[i] == null) { + ret = false; + } + } + + // The CD values SIPIntWorld found replace those of the celestial axes, once every column + // has been found. + if (ret && havesip) { + partmat[sipax[0]][lonax] = cdSip[0]; + partmat[sipax[1]][lonax] = cdSip[1]; + partmat[sipax[0]][latax] = cdSip[2]; + partmat[sipax[1]][latax] = cdSip[3]; + } + + // Columns for the degenerate grid axes, orthogonal to the others. + double[][] fullmat = null; + if (ret) { + fullmat = FitsOrth.orthVectorSet(nout, nin, partmat); + if (fullmat == null) { + ret = false; + } + } + if (!ret) { + return false; + } + + FitsInvertable.makeInvertable(fullmat, nout, dim); + + // The Mapping output of each FITS axis (the inverse of wperm); the columns and diagonal + // elements of the first pair of celestial axes; and whether the Mapping from IWC to + // world coordinates is linear on each axis, as it is taken to be for a plain Frame. + Frame sfrm = null; + double skydiag0 = AST__BAD; + double skydiag1 = AST__BAD; + int skycol0 = -1; + int skycol1 = -1; + for (int i = 0; i < nout; i++) { + pperm[wperm[i]] = i; + Frame pfrm = fr.primaryFrame(i + 1, paxis); + if (isASkyFrame(pfrm)) { + skycol[wperm[i]] = paxis[0]; + lin[i] = false; + if (sfrm == null) { + sfrm = pfrm; + skycol0 = wperm[i]; + skydiag0 = fullmat[skycol0][i]; + } else if (sfrm == pfrm) { + skycol1 = wperm[i]; + skydiag1 = fullmat[skycol1][i]; + } + } else { + skycol[wperm[i]] = 0; + lin[i] = "Frame".equals(pfrm.astClass()); + } + } + + // CRPIX: w0 = fullmat * (g0 - crpix), solved for y = g0 - crpix, with g0 zero on the + // degenerate axes. C ignores palDmat's singularity flag. + double[] mat = new double[nout * nout]; + double[] y = w0.clone(); + int m = 0; + for (int i = 0; i < nout; i++) { + for (int j = 0; j < nout; j++) { + mat[m++] = fullmat[j][i]; + } + } + Pal.dmat(nout, mat, y); + + for (int j = 0; j < nout; j++) { + double[] colvec = fullmat[j]; + + // A degenerate axis is at grid value 1, where w0 has it at 0. + double crp; + if (j < nin) { + crp = g0[j] - y[j]; + if (havesip) { + if (j == sipax[0]) { + crp = crpixSip[0]; + } else if (j == sipax[1]) { + crp = crpixSip[1]; + } + } + } else { + crp = 1.0 - y[j]; + } + + if (j < nin || crp == 0.0) { + for (int i = 0; i < nout; i++) { + cdmat[wperm[i] * nout + j] = colvec[i]; + } + store.crpix[j] = crp; + } else { + // The unit vector of a degenerate axis has length 1; scale it to look natural. + // First, a celestial pair is given equal scales, longitude increasing east. + double k = AST__BAD; + if (skydiag0 != AST__BAD && skydiag1 != AST__BAD) { + if (skycol0 == j && skycol1 < nin) { + if (skydiag0 != 0.0) { + k = -skydiag1 / skydiag0; + } + } else if (skycol1 == j && skycol0 < nin && skydiag1 != 0.0) { + k = -skydiag0 / skydiag1; + } + } + + // Next, the element with the largest diagonally opposite element is made its + // negative. + if (k == AST__BAD) { + double mxcv = 0.0; + int ii = pperm[j]; + for (int i = 0; i < nout; i++) { + int jj = wperm[i]; + if (jj < nin) { + double cv = fullmat[jj][ii]; + if (!MappingHelpers.astEqual(colvec[i], 0.0) && Math.abs(cv) > mxcv) { + mxcv = Math.abs(cv); + k = -cv / colvec[i]; + } + } + } + } + + // Next, a diagonal element of 1 degree on a latitude axis, -1 degree on a + // longitude axis, and 1 on any other axis. + if (k == AST__BAD && colvec[pperm[j]] != 0.0) { + if (skycol[j] != 0) { + k = AST__DD2R / colvec[pperm[j]]; + if (skycol[j] == 1) { + k = -k; + } + } else { + k = 1.0 / colvec[pperm[j]]; + } + } + + if (k == AST__BAD) { + k = 1.0; + } + for (int i = 0; i < nout; i++) { + cdmat[wperm[i] * nout + j] = k * colvec[i]; + } + crp = 1.0 + (crp - 1.0) / k; + store.crpix[j] = crp; + } + } + + // A degenerate axis that alone feeds a linear world axis, and feeds no other, has its + // reference point moved to grid value 1. + for (int i = 0; i < nout; i++) { + if (lin[i]) { + int jax = -1; + for (int j = 0; j < nout; j++) { + if (!MappingHelpers.astEqual(fullmat[j][i], 0.0)) { + if (jax == -1) { + jax = j; + } else { + jax = -1; + break; + } + } + } + if (jax >= nin) { + for (int ii = 0; ii < nout; ii++) { + if (ii != i && !MappingHelpers.astEqual(fullmat[jax][ii], 0.0)) { + jax = -1; + break; + } + } + if (jax != -1) { + double crv = item(store.crval[wperm[i]]); + double cd = cdmat[wperm[i] * nout + jax]; + double crp = item(store.crpix[jax]); + if (crv != AST__BAD && crp != AST__BAD && cd != AST__BAD) { + store.crpix[jax] = 1.0; + store.crval[wperm[i]] = cd * (1.0 - crp) + crv; + } + } + } + } + } + + if (nin < nwcs) { + store.wcsaxes = nwcs; + } + + // PC and CDELT from the CD matrix; a unit diagonal and zero off-diagonal PC element is + // not stored. + FitsWcsDecompose.splitMat(nout, cdmat, cdelt); + int c = 0; + for (int i = 0; i < nout; i++) { + for (int j = 0; j < nout; j++) { + double val = cdmat[c++]; + if (i == j) { + if (MappingHelpers.astEqual(val, 1.0)) { + val = AST__BAD; + } + } else { + if (MappingHelpers.astEqual(val, 0.0)) { + val = AST__BAD; + } + } + if (val != AST__BAD) { + store.pc[i][j] = val; + } + } + store.cdelt[i] = cdelt[i]; + } + return true; + } + + /** + * C's {@code IsASkyFrame} macro in fitschan.c: a SkyFrame whose Domain is {@code SKY}. + */ + static boolean isASkyFrame(Frame frame) { + return frame instanceof SkyFrame && "SKY".equals(frame.getDomain()); + } + + /** A store value as C's {@code GetItem} gives it: {@code AST__BAD} when it is not set. */ + private static double item(Double v) { + return v == null ? AST__BAD : v; + } + + /** + * C's {@code NearestPix}: the value of output {@code axis} of {@code map} at the grid position + * nearest to where it is {@code val}. The value is transformed back with the other outputs + * bad, each good grid value rounded to the nearest integer, and the result transformed + * forward. A Mapping with no inverse is first split, the output split off it being used if + * the split succeeds. + * + * @param map the Mapping, which is inverted and inverted back to split it, as C does + * @param axis the zero-based output index + * @return the value at the nearest grid position, or {@code val} if it is bad, the Mapping + * has no inverse, or the value found is bad + */ + static double nearestPix(Mapping map, double val, int axis) { + double result = val; + if (result == AST__BAD) { + return result; + } + Mapping tmap; + int tax = axis; + if (!map.getTranInverse()) { + MapSplit split; + map.invert(); + try { + split = map.mapSplit(new int[] {axis}); + } finally { + map.invert(); + } + if (split != null) { + tmap = split.map; + tmap.invert(); + tax = 0; + } else { + tmap = map; + } + } else { + tmap = map; + } + + if (tmap.getTranInverse()) { + int nin = tmap.getNin(); + int nout = tmap.getNout(); + double[][] ptr2 = new double[nout][1]; + for (int i = 0; i < nout; i++) { + ptr2[i][0] = AST__BAD; + } + ptr2[tax][0] = val; + double[][] ptr1 = tmap.transform(ptr2, 1, false); + for (int i = 0; i < nin; i++) { + if (ptr1[i][0] != AST__BAD) { + ptr1[i][0] = roundHalfAway(ptr1[i][0]); + } + } + ptr2 = tmap.transform(ptr1, 1, true); + if (ptr2[tax][0] != AST__BAD) { + result = ptr2[tax][0]; + } + } + return result; + } + + /** C's {@code round}: to the nearest integer, halfway cases away from zero. */ + static double roundHalfAway(double x) { + double a = Math.abs(x); + double fl = Math.floor(a); + return Math.copySign(a - fl >= 0.5 ? fl + 1.0 : fl, x); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsMapTab.java b/src/main/java/uk/ac/starlink/ast/FitsMapTab.java new file mode 100644 index 0000000..b76e62d --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsMapTab.java @@ -0,0 +1,303 @@ +package uk.ac.starlink.ast; + +import java.util.Arrays; + +/** + * Whether WCS axes of a pixel to WCS Mapping can be described by the {@code -TAB} algorithm of + * FITS-WCS paper III: C's {@code IsMapTab1D}, {@code IsMapTab2D}, {@code AdaptLut} and {@code + * ChangePermSplit} (fitschan.c). + * + *

C decides with the Mapping alone whether an axis can be tabulated, and then writes the table + * into a FitsTable. This library has neither FitsTable nor LutMap, so the decision is ported as C + * makes it, and where C would create or use a FitsTable an {@link UnsupportedOperationException} + * is thrown instead. + * + *

Ported from Rust {@code fitschan/fset_to_store/map_tab.rs}, following fitschan.c. + */ +final class FitsMapTab { + + private static final double AST__BAD = AstObject.AST__BAD; + + private FitsMapTab() {} + + /** + * C's {@code IsMapTab1D}: whether output {@code iax} of the pixel to WCS Mapping {@code map} + * can be described by a look-up table for FITS-WCS axis {@code iwcs}, and if so the Mapping + * from that WCS axis to the one grid axis that feeds it. + * + *

The grid axis is found by splitting off the output from the inverse of {@code map}; + * failing that, by splitting off each input of {@code map} in turn until one feeds the output; + * and failing that, by splitting the inverse again with every PermMap using its alternative + * split. The output can be tabulated if exactly one grid axis feeds it and either the Mapping + * from the grid axis holds a LutMap (which no Mapping of this library does) or the number of + * pixels on the grid axis is known; C then samples the Mapping and stores the samples in a + * FitsTable. + * + *

When the inverse split gives more than one grid axis, C returns the split Mapping as it + * is, with no table columns; that is kept. + * + * @param map the pixel to WCS Mapping; its Invert attribute is changed while it is split, and + * restored + * @param scale the factor from AST units to FITS units of the tabulated values + * @param unit the unit of the table column, or null for the Unit of axis {@code iax} of + * {@code wcsfrm} + * @param wcsfrm the WCS Frame + * @param dim the number of pixels along each grid axis, {@code AST__BAD} where unknown + * @param iax the zero-based output of {@code map} + * @param iwcs the zero-based FITS-WCS axis, which names the table columns + * @param icolmain receives -1 in its first element: the main column C adds, which there is none of + * @param icolindex receives -1 in its first element: the index column C adds, which there is + * none of + * @param interp receives 0 in its first element: the interpolation method of a LutMap + * @return C's Mapping, or null where C returns NULL (the output cannot be tabulated) + * @throws UnsupportedOperationException where C would create a FitsTable to hold the table, + * which needs FitsTable + */ + static Mapping isMapTab1D( + Mapping map, + double scale, + String unit, + Frame wcsfrm, + double[] dim, + int iax, + int iwcs, + int[] icolmain, + int[] icolindex, + int[] interp) { + icolmain[0] = -1; + icolindex[0] = -1; + interp[0] = 0; + String colunit = unit != null ? unit : wcsfrm.getUnit(iax + 1); + + // The grid inputs feeding the output and the Mapping from the output to them: split off + // the output from the inverse Mapping, since astMapSplit splits off inputs. + MapSplit split = splitInverse(map, iax); + int[] ins = split != null ? split.outputs : null; + Mapping ret = split != null ? split.map : null; + + // Failing that, each input in turn, to see if it alone feeds the output. + if (ins == null) { + int nin = map.getNin(); + for (int iin = 0; iin < nin && ins == null; iin++) { + MapSplit s = map.mapSplit(new int[] {iin}); + if (s != null) { + int[] outs = s.outputs; + int nout = s.map.getNout(); + int iout = 0; + while (iout < nout && outs[iout] != iax) { + iout++; + } + if (iout < nout) { + // The 1-input split followed by a PermMap selecting the output, inverted + // to map the WCS axis to the grid axis. + int[] inperm = new int[nout]; + Arrays.fill(inperm, -1); + inperm[iout] = 0; + PermMap pm = PermMap.fromInternal(nout, inperm, 1, new int[] {iout}, null); + ret = new CmpMap(s.map, pm, true); + ret.invert(); + ins = new int[] {iin}; + } + } + } + } + + // Failing that, the inverse again, with every PermMap using its alternative split. + if (ins == null) { + map.invert(); + MapSplit s; + try { + Mapping tmap = (Mapping) map.copy(); + changePermSplit(tmap); + s = tmap.mapSplit(new int[] {iax}); + } finally { + map.invert(); + } + ins = s != null ? s.outputs : null; + ret = s != null ? s.map : null; + } + + if (ins != null && ret != null && ret.getNout() == 1) { + // From the grid axis to the WCS axis. + ret.invert(); + + // C searches the Mappings in series for a non-inverted LutMap, whose table it would + // use; this library has no LutMap. Without one, C samples the Mapping when the number + // of pixels along the grid axis is known. + if (dim[ins[0]] != AST__BAD) { + double[] x = {1.0, dim[ins[0]]}; + double[] v = ret.tran1(2, x, true); + double[][] work = {{x[0]}, {v[0]}}; + int[] nlut = {1}; + adaptLut(ret, 3, 0.25, x[0], x[1], v[0], v[1], work, nlut); + throw new UnsupportedOperationException("IsMapTab1D(FitsChan): the look-up table for FITS-WCS axis " + + (iwcs + 1) + " (unit '" + colunit + "') needs FitsTable"); + } + ret = null; + } + return ret; + } + + /** The split of output {@code iax} from the inverse of {@code map}, which is left as it was. */ + private static MapSplit splitInverse(Mapping map, int iax) { + map.invert(); + try { + return map.mapSplit(new int[] {iax}); + } finally { + map.invert(); + } + } + + /** + * C's {@code IsMapTab2D}: whether outputs {@code iax1} and {@code iax2} of {@code map} can be + * described by look-up tables, for FITS-WCS axes {@code iwcs1} and {@code iwcs2}. Each must be + * separable ({@link #isMapTab1D}); C then gives the Mapping from the two WCS axes to their grid + * axes, split from the inverse of {@code map} where it can be and otherwise the two 1-D + * Mappings in parallel. When only one is separable, C removes its columns from the FitsTable. + * Non-separable outputs are not tabulated (C has no 2-D table yet). + * + * @param max1 receives 1 in its first element when both outputs are separable: each axis is + * the first of its coordinate array + * @param max2 as {@code max1}, for the second output + * @return C's Mapping, or null where C returns NULL + * @throws UnsupportedOperationException where C would create a FitsTable, or remove the + * columns of a separable output from one, which needs FitsTable + */ + static Mapping isMapTab2D( + Mapping map, + double scale, + String unit, + Frame wcsfrm, + double[] dim, + int iax1, + int iax2, + int iwcs1, + int iwcs2, + int[] icolmain1, + int[] icolmain2, + int[] icolindex1, + int[] icolindex2, + int[] max1, + int[] max2, + int[] interp1, + int[] interp2) { + Mapping ret = null; + Mapping ret1 = isMapTab1D(map, scale, unit, wcsfrm, dim, iax1, iwcs1, icolmain1, icolindex1, interp1); + Mapping ret2 = isMapTab1D(map, scale, unit, wcsfrm, dim, iax2, iwcs2, icolmain2, icolindex2, interp2); + + if (ret1 != null && ret2 != null) { + max1[0] = 1; + max2[0] = 1; + + // The Mapping from the two WCS axes to their grid axes, split from the inverse. + map.invert(); + MapSplit split; + try { + split = map.mapSplit(new int[] {iax1, iax2}); + } finally { + map.invert(); + } + if (split != null) { + ret = split.map; + if (ret.getNout() > 2) { + ret = null; + } else if (ret.getNout() == 1) { + // Both WCS axes fed by one grid axis: a PermMap duplicates it. + PermMap pm = PermMap.fromInternal(1, new int[] {0}, 2, new int[] {0, 0}, null); + ret = new CmpMap(ret, pm, true); + } + } + if (ret == null) { + ret = new CmpMap(ret1, ret2, false); + } + } else if (ret1 != null || ret2 != null) { + throw new UnsupportedOperationException( + "IsMapTab2D(FitsChan): removing the columns of a separable axis from the look-up table needs" + + " FitsTable"); + } + return ret; + } + + /** + * C's {@code AdaptLut}: appends to the samples {@code work[0]} (grid positions) and {@code + * work[1]} (values), of which {@code nsamp[0]} are used, samples of the 1-D Mapping {@code map} + * over the interval from {@code x0} (value {@code v0}) to {@code x1} (value {@code v1}), + * excluding {@code x0}: {@code npos} evenly spaced interior samples and {@code x1}, each + * sub-interval being sampled again in the same way wherever a sample departs from the straight + * line between the ends by more than {@code eps} in input (or is bad). + */ + static void adaptLut( + Mapping map, + int npos, + double eps, + double x0, + double x1, + double v0, + double v1, + double[][] work, + int[] nsamp) { + double dx = (x1 - x0) / (npos + 1); + double xx0 = x0 + dx; + double[] xx = new double[npos]; + for (int ipos = 0; ipos < npos; ipos++) { + xx[ipos] = xx0 + ipos * dx; + } + double[] vv = map.tran1(npos, xx, true); + + boolean subdivide = false; + if (v0 == v1) { + for (int ipos = 0; ipos < npos; ipos++) { + if (vv[ipos] != v0) { + subdivide = true; + break; + } + } + } else { + double rg = (x1 - x0) / (v1 - v0); + for (int ipos = 0; ipos < npos; ipos++) { + if (vv[ipos] == AST__BAD || Math.abs(rg * (vv[ipos] - v0) - (xx[ipos] - x0)) > eps) { + subdivide = true; + break; + } + } + } + + if (subdivide) { + for (int ipos = 0; ipos < npos; ipos++) { + adaptLut(map, npos, eps, x0, xx[ipos], v0, vv[ipos], work, nsamp); + x0 = xx[ipos]; + v0 = vv[ipos]; + } + adaptLut(map, npos, eps, x0, x1, v0, v1, work, nsamp); + } else { + int isamp = nsamp[0]; + nsamp[0] += npos + 1; + if (work[0].length < nsamp[0]) { + work[0] = Arrays.copyOf(work[0], Math.max(nsamp[0], 2 * work[0].length)); + work[1] = Arrays.copyOf(work[1], work[0].length); + } + for (int ipos = 0; ipos < npos; ipos++, isamp++) { + work[0][isamp] = xx[ipos]; + work[1][isamp] = vv[ipos]; + } + work[0][isamp] = x1; + work[1][isamp] = v1; + } + } + + /** + * C's {@code ChangePermSplit}: sets PermSplit on every PermMap in {@code map}, looking inside + * the Mappings C's {@code astDecompose} gives two components for. + */ + static void changePermSplit(Mapping map) { + if (map instanceof PermMap) { + ((PermMap) map).setPermSplit(true); + } else { + Mapping[] parts = map.decomposeInto(new boolean[3]); + if (parts.length == 2) { + changePermSplit(parts[0]); + changePermSplit(parts[1]); + } + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsNativeWriter.java b/src/main/java/uk/ac/starlink/ast/FitsNativeWriter.java new file mode 100644 index 0000000..6e16bc4 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsNativeWriter.java @@ -0,0 +1,391 @@ +package uk.ac.starlink.ast; + +import java.util.Map; + +/** + * Writes an Object to a FitsChan in the NATIVE encoding: as header cards holding the items of the + * Object's description, each with a keyword made unique by a two-character sequence suffix ({@code + * BEGAST_A}, {@code NIN_A}, {@code ISA_A}, {@code ENDAST_A}, ...), framed by banners of comment + * cards. + * + *

C's FitsChan {@code Write} adds the banners and calls the Channel's {@code Write}, which has + * the Object dump itself through the FitsChan's {@code WriteBegin}, {@code WriteIsA}, {@code + * WriteEnd}, {@code WriteInt}, {@code WriteDouble}, {@code WriteString} and {@code WriteObject} + * (fitschan.c); a nested Object is written by a recursive {@code Write}. Here the description is + * the Object's {@link NativeNode}, as for the Channel's text ({@link NativeWriter}), and its items + * are stored as those functions store them, one card at a time in front of the current card. + * + *

Ported from the write half of Rust {@code fitschan/enc_native.rs} and {@code + * FitsChan::store_keyword_native}; the cards are stored in the FitsChan as C stores them, so a + * keyword already used is found among the FitsChan's cards as C's {@code HasCard} finds it. + */ +final class FitsNativeWriter { + + /** C's {@code INDENT_INC}: the indentation added for each level of nesting. */ + static final int INDENT_INC = 3; + + /** C's {@code HEADER_TEXT}. */ + private static final String HEADER_TEXT = "Beginning of AST data for "; + + /** C's {@code FOOTER_TEXT}. */ + private static final String FOOTER_TEXT = "End of AST data for "; + + private static final String PLUSES = "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"; + private static final String DOTS = "................................................................"; + private static final String DASHES = "----------------------------------------------------------------"; + + /** A blank keyword, as C passes it to {@code astSetFitsCom}. */ + private static final String BLANK_NAME = " "; + + /** The characters of a commentary card after the keyword: {@code FITSCARDLEN - FITSNAMLEN}. */ + private static final int MXLEN = FitsCard.FITS_CARD_LEN - FitsCard.FITS_NAME_LEN; + + private final FitsChan fc; + + /** The FitsChan's Comment attribute. */ + private final boolean comm; + + /** C's {@code current_indent}: the indentation of the comments marking nested Objects. */ + private int currentIndent; + + /** C's {@code items_written}: the items written since the last Begin or IsA. */ + private int itemsWritten; + + FitsNativeWriter(FitsChan fc) { + this.fc = fc; + this.comm = fc.getComment(); + } + + /** + * Writes {@code obj} as fitschan.c {@code Write} does for the NATIVE encoding: unless Comment + * is clear, a blank card and a banner of COMMENT cards (with two more lines for a FrameSet), + * then the Object, then a closing banner. + */ + void write(AstObject obj) { + String cls = obj.astClass(); + if (comm) { + fc.setFitsCom(BLANK_NAME, "", false); + banner(PLUSES, "", ""); + if (obj instanceof FrameSet) { + banner("WCS information in AST format", "", ""); + banner("See http://www.starlink.ac.uk/ast/", "", ""); + } + banner(HEADER_TEXT, cls, " object"); + banner(DOTS, "", ""); + } + writeObject(NativeNode.of(obj), fc.getFull(), false); + if (comm) { + banner(DOTS, "", ""); + banner(FOOTER_TEXT, cls, " object"); + banner(DASHES, "", ""); + } + } + + private void banner(String prefix, String middle, String suffix) { + fc.setFitsCom("COMMENT", makeBanner(prefix, middle, suffix), false); + } + + /** The comment, if comments are written (C's {@code astGetComment( this ) ? comment : NULL}). */ + private String com(String comment) { + return comm ? comment : null; + } + + /** + * Writes one Object's description as channel.c {@code Write} has the Object dump itself: its + * Begin item, its items and its End item. {@code full} is the Full attribute in force for it + * (Full -1 for an Object whose writer caps it, as frame.c does for its Axes) and {@code nested} + * is false for the top-level Object (C's {@code write_nest} zero). + */ + void writeObject(NativeNode node, int full, boolean nested) { + writeBegin(node.className, node.classComment, full, nested); + for (NativeNode.Item item : node.items) { + if (item.isIsA()) { + if (item.value.kind != NativeNode.Kind.STRING) { + throw Ast.err(AstException.AST__INTER, "astWrite(FitsChan): an IsA item holds " + item.value + "."); + } + writeIsA(item.value.stringValue, item.comment, full); + } else if (use(item.set, item.helpful, full)) { + writeItem(item, full); + } + } + writeEnd(node.className, full, nested); + } + + /** C's {@code Use}: whether a value is written, given whether it is set and helpful. */ + private static boolean use(boolean set, boolean helpful, int full) { + return set || (helpful && full > -1) || full > 0; + } + + /** One item that is written, as C's {@code Write} functions write it. */ + private void writeItem(NativeNode.Item item, int full) { + NativeNode.Value value = item.value; + // MODERN-JAVA(21): switch expression + switch (value.kind) { + case INT: + // C's WriteInt. + fc.setFitsI(createKeyword(item.key), value.intValue, com(item.comment), false); + if (!item.set) { + makeIntoComment(); + } + itemsWritten++; + break; + case DOUBLE: + // C's WriteDouble. + fc.setFits(createKeyword(item.key), value.doubleValue, com(item.comment), false); + if (!item.set) { + makeIntoComment(); + } + itemsWritten++; + break; + case STRING: + writeString(item.key, item.set, value.stringValue, item.comment); + break; + case OBJECT: + writeObjectItem(item, full); + break; + default: + throw Ast.err(AstException.AST__INTER, "astWrite(FitsChan): unexpected value kind " + value.kind + "."); + } + } + + /** + * C's {@code WriteObject}: a blank string value, not pre-quoted, marking the description that + * follows, then the Object's description written as a nested Object; for a value that is not + * set the card is made a COMMENT card and no description follows. + */ + private void writeObjectItem(NativeNode.Item item, int full) { + fc.setFits(createKeyword(item.key), "", com(item.comment), false); + if (item.set) { + NativeNode child = item.value.object; + writeObject(child, child.fullCapped && full <= 0 ? -1 : full, true); + } else { + makeIntoComment(); + } + itemsWritten++; + } + + /** + * C's {@code WriteBegin}: increments the indentation, marks a nested Object with an indented + * comment when Full is not negative, and writes the class name with a {@code BEGAST} keyword. + */ + private void writeBegin(String cls, String comment, int full, boolean nested) { + currentIndent += INDENT_INC; + if (nested && full >= 0) { + fc.setFitsCom(BLANK_NAME, makeIndentedComment(currentIndent, '+', "Beginning of ", cls), false); + } + fc.setFits(createKeyword("BEGAST"), preQuote(cls), com(comment), false); + itemsWritten = 0; + } + + /** + * C's {@code WriteIsA}: the class name with an {@code ISA} keyword, and a comment marking the + * class boundary when Full is not negative, written only if an item has been written since + * the last Begin or IsA or Full is positive. + */ + private void writeIsA(String cls, String comment, int full) { + if (itemsWritten > 0 || full > 0) { + fc.setFits(createKeyword("ISA"), preQuote(cls), com(comment), false); + if (full >= 0) { + fc.setFitsCom(BLANK_NAME, makeIndentedComment(currentIndent, '.', "Class boundary", ""), false); + } + } + itemsWritten = 0; + } + + /** + * C's {@code WriteEnd}: the class name with an {@code ENDAST} keyword, a comment marking the + * end of a nested Object when Full is not negative, and the indentation decremented. + */ + private void writeEnd(String cls, int full, boolean nested) { + fc.setFits(createKeyword("ENDAST"), preQuote(cls), com("End of object definition"), false); + if (nested && full >= 0) { + fc.setFitsCom(BLANK_NAME, makeIndentedComment(currentIndent, '-', "End of ", cls), false); + } + currentIndent -= INDENT_INC; + } + + /** + * C's {@code WriteString}: the value, pre-quoted, in as many cards as it needs, the first with + * a keyword made from {@code name} and the others {@code CONTINUE} cards, each card but the + * last ending in an ampersand. The first card leaves room for the comment, whether or not + * comments are written, and, for a value that is not set, for the keyword of the COMMENT card + * it is made into. An empty value writes no card. + */ + void writeString(String name, boolean set, String value, String comment) { + String keyword = createKeyword(name); + int start = 0; + boolean first = true; + while (start < value.length()) { + // The columns for this part: the card less the keyword, "= ", the delimiting quotes + // and the two double quotes PreQuote may add. + int nc = FitsCard.FITS_CARD_LEN - FitsCard.FITS_NAME_LEN - 6; + if (first) { + if (comment != null && !comment.isEmpty()) { + nc -= FitsCard.chrLen(comment) + 3; + } + if (!set) { + nc -= FitsCard.FITS_NAME_LEN + 5; + } + } + if (nc <= 0) { + throw Ast.err( + AstException.AST__INTER, + "astWrite(FitsChan): no room for the value of " + keyword + " beside its comment."); + } + // A single quote takes two columns, as it is doubled when the card is formatted. + StringBuilder buf = new StringBuilder(); + while (start < value.length() && nc > 0) { + char cc = value.charAt(start++); + buf.append(cc); + nc -= cc == '\'' ? 2 : 1; + } + // A last single quote that leaves no room for its double goes to the next part. + if (nc < 0) { + start--; + buf.setLength(buf.length() - 1); + } + // If the value goes on, the last character makes room for an ampersand. + if (start < value.length()) { + start--; + buf.setLength(buf.length() - 1); + buf.append('&'); + } + String part = preQuote(buf.toString()); + if (first) { + fc.setFits(keyword, part, com(comment), false); + if (!set) { + makeIntoComment(); + } + } else { + fc.setFitsContinue("CONTINUE", part, null, false); + } + first = false; + } + itemsWritten++; + } + + /** + * C's {@code MakeIntoComment}: replaces the card before the current one, the card just + * written, by a COMMENT card holding its text, formatted with the FitsChan's FitsDigits and + * FitsRounding. + */ + private void makeIntoComment() { + FitsCardList cards = fc.cards(); + cards.moveCard(-1); + String text = cards.current().formatWithDigitsAndRounding(fc.getFitsDigits(), fc.getFitsRounding()); + fc.setFitsCom("COMMENT", text, true); + } + + /** + * C's {@code CreateKeyword}: a keyword for the item {@code name}, its first {@code FITSNAMLEN - + * 2} characters in upper case followed by two of {@link FitsNativeReader#SEQ_CHARS} encoding + * the next sequence number for that base. The FitsChan keeps the last number used for each + * base from one write to the next, and a number whose keyword a card in the FitsChan already + * has is passed over; once the two characters run out the last number is used again. + */ + String createKeyword(String name) { + String seqChars = FitsNativeReader.SEQ_CHARS; + int nseq = seqChars.length(); + StringBuilder base = new StringBuilder(); + for (int nc = 0; nc < FitsCard.FITS_NAME_LEN - 2 && nc < name.length(); nc++) { + base.append(CScan.toUpper(name.charAt(nc))); + } + Map keySeq = fc.keySequences(); + Integer last = keySeq.get(base.toString()); + int seq = last == null ? 0 : last; + String keyword; + while (true) { + boolean limit = seq >= nseq * nseq - 1; + if (!limit) { + seq++; + } + keyword = base.toString() + seqChars.charAt(seq / nseq) + seqChars.charAt(seq % nseq); + if (limit || !fc.cards().hasCard(keyword)) { + break; + } + } + keySeq.put(base.toString(), seq); + return keyword; + } + + /** + * C's {@code MakeBanner}: {@code prefix}, {@code middle} and {@code suffix} centred in the 72 + * columns of a comment card with the token {@code AST} at each end, the text truncated so it + * never reaches the last token. + */ + static String makeBanner(String prefix, String middle, String suffix) { + String token = "AST"; + int ltok = token.length(); + int start = + ltok + 2 + (MXLEN - ltok - 1 - (prefix.length() + middle.length() + suffix.length()) - 1 - ltok) / 2; + if (start < ltok + 2) { + start = ltok + 2; + } + StringBuilder banner = new StringBuilder(MXLEN); + for (int i = 0; i < ltok && banner.length() < MXLEN; i++) { + banner.append(token.charAt(i)); + } + while (banner.length() < start - 1) { + banner.append(' '); + } + for (String s : new String[] {prefix, middle, suffix}) { + for (int i = 0; i < s.length() && banner.length() < MXLEN - ltok - 1; i++) { + banner.append(s.charAt(i)); + } + } + while (banner.length() < MXLEN - ltok) { + banner.append(' '); + } + for (int i = 0; i < ltok && banner.length() < MXLEN; i++) { + banner.append(token.charAt(i)); + } + return banner.toString(); + } + + /** + * C's {@code MakeIndentedComment}: {@code indent} copies of {@code token}, padded to the + * comment column of a card, then {@code "/ "}, {@code comment} and {@code data}, all within the + * 72 columns of a comment card. + */ + static String makeIndentedComment(int indent, char token, String comment, String data) { + StringBuilder s = new StringBuilder(MXLEN); + while (s.length() < indent && s.length() < MXLEN) { + s.append(token); + } + while (s.length() < FitsCard.FITS_COM_COL - FitsCard.FITS_NAME_LEN - 1) { + s.append(' '); + } + String text = "/ " + comment + data; + for (int i = 0; i < text.length() && s.length() < MXLEN; i++) { + s.append(text.charAt(i)); + } + return s.toString(); + } + + /** + * C's {@code PreQuote}: as much of {@code value} as a card's string value holds, its single + * quotes counted twice as the card doubles them, in double quotes when the last character kept + * is white space (which FITS does not keep) or the value starts with a double quote and the + * last character kept is one (so that removing the quotes on reading leaves both). An empty + * value is two double quotes. + */ + static String preQuote(String value) { + int dquotes = 2; + int nc = 0; + int sq = 0; + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c == '\'') { + sq++; + } + int dq = CScan.isCSpace(c) || (value.charAt(0) == '"' && c == '"') ? 2 : 0; + if (nc + 1 + dq + sq > FitsCard.FITS_CARD_LEN - FitsCard.FITS_NAME_LEN - 4) { + break; + } + nc = i + 1; + dquotes = dq; + } + String body = value.substring(0, nc); + return dquotes != 0 ? "\"" + body + "\"" : body; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsOrth.java b/src/main/java/uk/ac/starlink/ast/FitsOrth.java new file mode 100644 index 0000000..c800853 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsOrth.java @@ -0,0 +1,119 @@ +package uk.ac.starlink.ast; + +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * Completion of a set of vectors with unit vectors orthogonal to it: C's {@code OrthVector} and + * {@code OrthVectorSet} (fitschan.c), with which a FitsChan write invents the CD matrix columns of + * degenerate grid axes. + * + *

Ported from Rust {@code fitschan/fset_to_store/orth.rs}, following fitschan.c. + */ +final class FitsOrth { + + private FitsOrth() {} + + /** + * C's {@code OrthVector}: a unit {@code n}-vector orthogonal to the {@code m} vectors {@code + * in}, where {@code m < n}. The {@code m} components of largest column magnitude are found by + * solving the equations that the dot products are zero with the component of the next largest + * column set to 1 and the others to 0. + * + * @param in {@code m} vectors of {@code n} elements + * @return the unit vector, or null if a supplied vector is null or the vectors span fewer than + * {@code m} axes + */ + static double[] orthVector(int n, int m, double[][] in) { + for (int i = 0; i < m; i++) { + if (in[i] == null) { + return null; + } + } + double[] colmag = new double[n]; + int[] colperm = new int[n]; + for (int i = 0; i < n; i++) { + colperm[i] = i; + colmag[i] = 0.0; + for (int j = 0; j < m; j++) { + colmag[i] += in[j][i] * in[j][i]; + } + } + + // A bubble sort of the column indices into order of decreasing magnitude. + int ii = n; + boolean done = false; + while (!done) { + done = true; + for (int i = 1; i < ii; i++) { + int ih = colperm[i]; + int il = colperm[i - 1]; + if (colmag[ih] > colmag[il]) { + colperm[i] = il; + colperm[i - 1] = ih; + done = false; + } + } + ii--; + } + + double[] mat = new double[m * m]; + double[] rhs = new double[m]; + int mel = 0; + for (int i = 0; i < m; i++) { + double[] d = in[i]; + for (int j = 0; j < m; j++) { + mat[mel++] = d[colperm[j]]; + } + rhs[i] = -d[colperm[m]]; + } + if (!Pal.dmat(m, mat, rhs)) { + return null; + } + + double[] ret = new double[n]; + double sl = 0.0; + for (int j = 0; j < m; j++) { + sl += rhs[j] * rhs[j]; + ret[colperm[j]] = rhs[j]; + } + sl += 1.0; + ret[colperm[m]] = 1.0; + for (int j = m + 1; j < n; j++) { + ret[colperm[j]] = 0.0; + } + + // A unit vector, with any negative zero made positive. + sl = Math.sqrt(sl); + for (int j = 0; j < n; j++) { + ret[j] /= sl; + if (ret[j] == 0.0) { + ret[j] = 0.0; + } + } + return ret; + } + + /** + * C's {@code OrthVectorSet}: {@code n} vectors of {@code n} elements, the first {@code m} + * copies of {@code in} and each of the others the unit vector {@link #orthVector} finds + * orthogonal to all those before it. + * + * @param in {@code m} vectors of {@code n} elements + * @return the vectors, or null if one cannot be found + */ + static double[][] orthVectorSet(int n, int m, double[][] in) { + double[][] ret = new double[n][]; + boolean bad = false; + int i; + for (i = 0; i < m; i++) { + ret[i] = in[i].clone(); + } + for (; i < n; i++) { + ret[i] = orthVector(n, i, ret); + if (ret[i] == null) { + bad = true; + } + } + return bad ? null : ret; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsOtherAxes.java b/src/main/java/uk/ac/starlink/ast/FitsOtherAxes.java new file mode 100644 index 0000000..610d4ef --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsOtherAxes.java @@ -0,0 +1,227 @@ +package uk.ac.starlink.ast; + +/** + * C's {@code OtherAxes} (fitschan.c): the FITS-WCS description of the world axes that neither the + * celestial nor the spectral axes took, with the helpers it uses ({@code LogAxis}, {@code + * AddUnitMaps}, {@code SetAlgCode}). + * + *

Each such axis is described, in order of preference, as linear, with the {@code -LOG} + * algorithm, or, when TabOK is positive, with the {@code -TAB} algorithm; ForceTab passes over the + * first two. An axis none of them describes is given the linear description, which makes the + * pixel to intermediate world Mapping non-linear, so that {@link FitsMakeIntWorld#makeIntWorld} + * rejects it. The {@code -LOG} description needs a MathMap and the {@code -TAB} description a + * FitsTable, neither of which this library has, so where C would make one an {@link + * UnsupportedOperationException} is thrown. + * + *

Ported from Rust {@code fitschan/fset_to_store/other_axes.rs} and {@code log_axis.rs}, + * following fitschan.c. + */ +final class FitsOtherAxes { + + private static final double AST__BAD = AstObject.AST__BAD; + + private FitsOtherAxes() {} + + /** + * C's {@code OtherAxes}: stores CRVAL, CTYPE, its comment, CNAME and CUNIT for each axis of the + * current Frame of {@code fs} not yet flagged in {@code axisDone}, flags it, and returns the + * Mapping from the current Frame to intermediate world coordinates for those axes, which + * passes the other axes unchanged. + * + *

The CRVAL of an axis is its element of {@code crvals}, if that is given and good, or else + * the world value at the centre pixel ({@code floor(dim/2)} on each pixel axis, 1 where the + * dimension is unknown); at an axis with neither, the axes from there on are left undescribed. + * The CTYPE is the axis Symbol ({@code AXIS} if it is blank), with {@code -LOG} or {@code + * -TAB} for those algorithms; its comment and CNAME are the Label when that is set and differs + * from the Symbol, the comment otherwise being C's default naming the axis number; and + * CUNIT is the Unit when that is set. + * + * @param fc the FitsChan, whose TabOK and ForceTab attributes are used + * @param fs the FrameSet, whose base Frame is pixel coordinates and current Frame world + * coordinates + * @param dim the number of pixels along each pixel axis, {@code AST__BAD} where unknown + * @param wperm the zero-based FITS axis describing each current Frame axis + * @param s the coordinate version character + * @param store the store + * @param crvals the reference value of each current Frame axis, {@code AST__BAD} where there + * is none, or null for none at all + * @param axisDone a flag for each current Frame axis, set for each axis described + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return the Mapping from the current Frame to intermediate world coordinates + * @throws UnsupportedOperationException where C would describe an axis with the {@code -LOG} + * algorithm (an axis that is not linear but whose logarithm is, with a CRVAL other than + * zero, and ForceTab not set), which needs MathMap, or with the {@code -TAB} algorithm, + * which needs FitsTable + */ + static Mapping otherAxes( + FitsChan fc, + FrameSet fs, + double[] dim, + int[] wperm, + char s, + FitsStore store, + double[] crvals, + boolean[] axisDone, + String method, + String cls) { + Mapping ret = null; + int nwcs = fs.getNaxes(); + + int nother = 0; + for (int iax = 0; iax < nwcs; iax++) { + if (!axisDone[iax]) { + nother++; + } + } + + if (nother > 0) { + Frame wcsfrm = fs.getFrame(FrameSet.AST__CURRENT); + Mapping map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + int npix = fs.getNin(); + nwcs = fs.getNout(); + + double[] lbndP = new double[npix]; + double[] ubndP = new double[npix]; + for (int iax = 0; iax < npix; iax++) { + lbndP[iax] = 1.0; + ubndP[iax] = dim[iax] != AST__BAD ? dim[iax] : 500; + } + + // The world coordinates of the central pixel. + double[][] ptr1 = new double[npix][1]; + for (int iax = 0; iax < npix; iax++) { + ptr1[iax][0] = dim[iax] != AST__BAD ? Math.floor(0.5 * dim[iax]) : 1.0; + } + double[][] ptr2 = map.transform(ptr1, 1, true); + + for (int iax = 0; iax < nwcs; iax++) { + if (axisDone[iax]) { + continue; + } + int fitsI = wperm[iax]; + + double crval = crvals != null ? crvals[iax] : AST__BAD; + if (crval == AST__BAD) { + crval = ptr2[iax][0]; + } + if (crval == AST__BAD) { + break; + } + store.crval[fitsI] = crval; + + boolean logAxis = false; + int extver = fc.getTabOK(); + boolean forceTab = fc.getForceTab() != 0; + + Mapping axmap = null; + if (!forceTab && FitsIsMapLinear.isMapLinear(map, lbndP, ubndP, iax, null)) { + axmap = addUnitMaps(new ShiftMap(new double[] {-crval}), iax, nwcs); + } else { + if (!forceTab) { + axmap = logAxis(map, iax, nwcs, lbndP, ubndP, crval); + logAxis = axmap != null; + } + if (axmap == null && extver > 0) { + // The -TAB algorithm: where IsMapTab1D gives a Mapping, C stores the table + // version in the header of the FitsTable holding the table, and the column + // names, so the description needs FitsTable. + Mapping tmap0 = FitsMapTab.isMapTab1D( + map, 1.0, null, wcsfrm, dim, iax, fitsI, new int[1], new int[1], new int[1]); + if (tmap0 != null) { + throw new UnsupportedOperationException( + "OtherAxes(FitsChan): the -TAB description of FITS-WCS axis " + (fitsI + 1) + + " needs FitsTable"); + } + } + } + + // An axis no algorithm describes is described as linear, which gives a non-linear + // pixel to intermediate world Mapping that MakeIntWorld rejects. + if (axmap == null) { + axmap = addUnitMaps(new ShiftMap(new double[] {-crval}), iax, nwcs); + } + + ret = ret != null ? new CmpMap(ret, axmap, true) : axmap; + + String sym = wcsfrm.getSymbol(iax + 1); + String lab = wcsfrm.getLabel(iax + 1); + String buf = !sym.isEmpty() ? sym : "AXIS" + (iax + 1); + if (logAxis) { + buf = setAlgCode(buf, "-LOG"); + } + store.ctype[fitsI] = buf; + + if (!lab.isEmpty() && wcsfrm.testLabel(iax + 1) && !sym.equals(lab)) { + store.ctypeCom[fitsI] = lab; + store.cname[fitsI] = lab; + } else { + store.ctypeCom[fitsI] = "Type of co-ordinate on axis " + (iax + 1); // codespell:ignore + } + + if (wcsfrm.testUnit(iax + 1)) { + store.cunit[fitsI] = wcsfrm.getUnit(iax + 1); + } + + axisDone[iax] = true; + } + } + + return ret != null ? ret.simplify() : new UnitMap(nwcs); + } + + /** + * C's {@code LogAxis}: the Mapping from world to intermediate world coordinates of the {@code + * -LOG} algorithm for output {@code iax} of the pixel to world Mapping {@code map}, if that + * output is logarithmic in the pixel coordinates over the box from {@code lbndP} to {@code + * ubndP}, or null if it is not or {@code crval} is zero. + * + *

As C does, the output is logarithmic if its logarithm, computed by the MathMap C makes + * here ({@link FitsLogMap}), is linear by {@link FitsIsMapLinear#isMapLinear}. + * + * @return null if {@code crval} is zero or the output is not logarithmic + * @throws UnsupportedOperationException if the output is logarithmic, where C makes the {@code + * -LOG} Mapping, which holds that MathMap, so needs MathMap + */ + static Mapping logAxis(Mapping map, int iax, int nwcs, double[] lbndP, double[] ubndP, double crval) { + if (crval == 0.0) { + return null; + } + Mapping tmap0 = new CmpMap(map, addUnitMaps(new FitsLogMap(), iax, nwcs), true); + if (!FitsIsMapLinear.isMapLinear(tmap0, lbndP, ubndP, iax, null)) { + return null; + } + throw new UnsupportedOperationException( + "LogAxis(FitsChan): the -LOG description of world axis " + (iax + 1) + " needs MathMap"); + } + + /** + * C's {@code AddUnitMaps}: a Mapping of {@code naxes} axes in which {@code map}, a Mapping with as + * many inputs as outputs, transforms the axes from {@code iax} (zero-based), with UnitMaps in + * parallel for the axes before and after; {@code map} itself if there are none. + */ + static Mapping addUnitMaps(Mapping map, int iax, int naxes) { + Mapping ret = map; + int nmap = map.getNin(); + if (iax > 0) { + ret = new CmpMap(new UnitMap(iax), ret, false); + } + if (iax + nmap < naxes) { + ret = new CmpMap(ret, new UnitMap(naxes - iax - nmap), false); + } + return ret; + } + + /** + * C's {@code SetAlgCode}: {@code buf} padded with {@code -} to 4 characters and {@code + * algcode} put in place of everything from its fifth character on. + */ + static String setAlgCode(String buf, String algcode) { + StringBuilder b = new StringBuilder(buf); + while (b.length() < 4) { + b.append('-'); + } + b.setLength(4); + return b.append(algcode).toString(); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsPlaneStores.java b/src/main/java/uk/ac/starlink/ast/FitsPlaneStores.java new file mode 100644 index 0000000..68b99dd --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsPlaneStores.java @@ -0,0 +1,157 @@ +package uk.ac.starlink.ast; + +/** + * The axis descriptions C's {@code FsetToStore} makes from a FrameSet for a FITS write: one {@link + * FitsStore} for each coordinate version letter, the primary description (a space) and the + * alternates {@code A} to {@code Z}, as C's single {@code FitsStore} holds each item under the + * letter of the description it belongs to. A writer takes the versions in letter order, as C's + * writers loop over the letters. + * + *

A version's store holds whatever C's {@code AddVersion} stored under its letter, also when + * the description could not be completed (an alternate whose pixel to intermediate world Mapping + * is not linear has values from its axes but no CRPIX, which is how C's writers recognise it), and + * when two descriptions are given the same letter, as C's {@code FsetToStore} can do, both are + * stored in the one store, the second replacing the values both store. + * + *

Ported from Rust {@code fitschan/wcs_write/plane_stores.rs}, following fitschan.c {@code + * FsetToStore}. + */ +final class FitsPlaneStores { + + /** C's {@code store->naxis}: the number of pixel axes, the base Frame's. */ + final int naxis; + + /** The store of each version, indexed by {@link #index}; null for a version with none. */ + private final FitsStore[] versions = new FitsStore[27]; + + FitsPlaneStores(int naxis) { + this.naxis = naxis; + } + + /** + * The index of version {@code s} in {@link #versions}: 0 for the primary description, 1 to 26 + * for {@code A} to {@code Z}. + * + * @throws AstException with status {@code AST__INTER} for any other character + */ + private static int index(char s) { + if (s == ' ') { + return 0; + } + if (s >= 'A' && s <= 'Z') { + return s - 'A' + 1; + } + throw Ast.err( + AstException.AST__INTER, + "FsetToStore(fitschan): AST internal error; coordinate version character '" + s + "' is invalid."); + } + + /** The store of version {@code s}, or null if nothing has been stored for it. */ + FitsStore get(char s) { + return versions[index(s)]; + } + + /** + * C's {@code GetMaxS( &(store->crval) )}: the last version letter with a CRVAL value, or the + * primary description's (a space) if no alternate has one. + */ + char maxCrvalVersion() { + for (char s = 'Z'; s >= 'A'; s--) { + FitsStore st = get(s); + if (st != null) { + for (Double v : st.crval) { + if (v != null) { + return s; + } + } + } + } + return ' '; + } + + /** + * The store of version {@code s}, made empty if there is none, with room for at least {@code + * naxes} axes. + */ + FitsStore version(char s, int naxes) { + int i = index(s); + if (versions[i] == null) { + versions[i] = new FitsStore(naxes); + } else { + versions[i].ensureAxes(naxes); + } + return versions[i]; + } + + /** + * The version letters C's {@code FsetToStore} gives the Frames of a FrameSet: {@link #sid} + * for each Frame, and the last letter handed out. + */ + static final class Letters { + /** + * Indexed by Frame index (from 1; element 0 is unused): 0 for a Frame given no letter + * (among them the base and current Frames), 1 for an IWC Frame, otherwise the letter. + */ + final char[] sid; + + /** + * The last letter the second pass handed out, or the character before {@code A} if it + * handed out none; the descriptions of absolute coordinates added for offset SkyFrames + * take the letters after it. + */ + final char last; + + Letters(char[] sid, char last) { + this.sid = sid; + this.last = last; + } + } + + /** + * C's assignment of version letters in {@code FsetToStore}: each Frame other than the base and + * current Frames and the IWC Frames (those whose Domain begins {@code IWC}) takes its Ident if + * that is a single upper case letter no earlier Frame has taken; then, unless AltAxes is + * IDENT, each Frame still without one takes the next letter no Frame has, in Frame order. + * + *

When the letters run out C reads past the end of its table of letters; here a Frame + * finding no free letter gets none, as C's test of the letter against {@code Z} then gives. + * + * @param altaxes C's AltAxes code, 0 ALL, 1 IDENT, 2 NONE + */ + static Letters versionLetters(FrameSet fset, int ibase, int icurr, int altaxes) { + int nfrm = fset.getNframe(); + char[] sid = new char[nfrm + 1]; + int[] frms = new int['Z' + 1]; + for (int ifrm = 1; ifrm <= nfrm; ifrm++) { + sid[ifrm] = 0; + if (ifrm != icurr && ifrm != ibase) { + Frame frame = fset.getFrame(ifrm); + if (AstObject.chrMatchN(frame.getDomain(), "IWC", 3)) { + sid[ifrm] = 1; + } else { + String id = frame.getIdent(); + if (id.length() == 1 && id.charAt(0) >= 'A' && id.charAt(0) <= 'Z' && frms[id.charAt(0)] == 0) { + frms[id.charAt(0)] = ifrm; + sid[ifrm] = id.charAt(0); + } + } + } + } + + char s = 'A' - 1; + if (altaxes != 1) { + for (int ifrm = 1; ifrm <= nfrm; ifrm++) { + if (ifrm != icurr && ifrm != ibase && sid[ifrm] == 0) { + do { + s++; + } while (s <= 'Z' && frms[s] != 0); + if (s <= 'Z') { + sid[ifrm] = s; + frms[s] = ifrm; + } + } + } + } + return new Letters(sid, s); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsSipIntWorld.java b/src/main/java/uk/ac/starlink/ast/FitsSipIntWorld.java new file mode 100644 index 0000000..ca3ec4c --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsSipIntWorld.java @@ -0,0 +1,517 @@ +package uk.ac.starlink.ast; + +import java.util.ArrayList; +import java.util.List; + +/** + * C's {@code SIPIntWorld} (fitschan.c): the CRPIX and CD values of celestial axes whose Mapping + * from grid to intermediate world coordinates includes a polynomial distortion the SIP convention + * can describe, and the SIP coefficients describing it. + * + *

Ported from Rust {@code fitschan/fset_to_store/sip_int_world.rs}, following fitschan.c. + */ +final class FitsSipIntWorld { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** The largest departure from a unit scale, zero rotation or zero shift C accepts. */ + private static final double LINEAR_TOL = 1.0E-7; + + private FitsSipIntWorld() {} + + /** + * Finds CRPIX and CD values for the celestial axes of {@code map}, and stores in {@code store} + * the SIP coefficients of the distortion it holds, as C's {@code SIPIntWorld} does. + * + *

The Mapping from the grid axes to the two celestial outputs is split off, simplified and + * searched for a PolyMap. The Mappings before the PolyMap must be linear over the image with + * no rotation; any scaling is moved into the PolyMap. The PolyMap is then analysed into a + * shift, a SIP polynomial and a linear transformation where it can be, and the Mappings after + * the polynomial must be linear over the region they are used in, with no shift of origin. + * Their linear fit gives the CD values, and the grid position of the origin of intermediate + * world coordinates gives CRPIX. The coefficients of each transformation of the polynomial are + * stored, less one for the unit linear terms, as the A and B (forward) and AP and BP (inverse) + * coefficients, and {@code -SIP} is written into the CTYPE values of the celestial axes from + * their ninth character. + * + *

{@code map} is inverted while it is split, and inverted back. + * + * @param map the Mapping from grid to intermediate world coordinates + * @param tol the tolerance, in pixels, of the linearity tests + * @param lonax the zero-based output of {@code map} giving celestial longitude + * @param latax the zero-based output of {@code map} giving celestial latitude + * @param s the axis description character: a space for the primary description, else {@code + * 'A'} to {@code 'Z'} + * @param store the store which receives the SIP coefficients and CTYPE values + * @param dim the image dimensions in pixels, {@code AST__BAD} where unknown, which then counts + * as 1000 + * @param inaxes receives the zero-based inputs of {@code map} which {@code crpix} and {@code + * cd} refer to, once the celestial Mapping is split off + * @param crpix receives the CRPIX values of the inputs {@code inaxes} once the SIP coefficients + * are stored + * @param cd receives the CD values (CDlonax_j1, CDlonax_j2, CDlatax_j1, CDlatax_j2), where + * {@code j1} and {@code j2} are the inputs {@code inaxes}, once the SIP coefficients are + * stored + * @param method the calling method, for messages + * @param cls the class of the object being written, for messages + * @return a Mapping equivalent to {@code map} without the polynomial distortion, or null if + * the celestial axes cannot be described with SIP coefficients, when nothing is stored + */ + static Mapping sipIntWorld( + Mapping map, + double tol, + int lonax, + int latax, + char s, + FitsStore store, + double[] dim, + int[] inaxes, + double[] crpix, + double[] cd, + String method, + String cls) { + int nin = map.getNin(); + int nout = map.getNout(); + if (!map.getTranForward() || !map.getTranInverse()) { + return null; + } + + // The Mapping from grid coordinates to the celestial outputs, split off the inverse of + // map, since a split names the inputs it keeps. + MapSplit split1 = splitOutputs(map, new int[] {lonax, latax}); + if (split1 == null || split1.map.getNout() != 2) { + return null; + } + int[] inax1 = split1.outputs; + Mapping tmap1 = split1.map; + tmap1.invert(); + inaxes[0] = inax1[0]; + inaxes[1] = inax1[1]; + + // The first PolyMap of the simplified Mapping as a list in series. + Mapping smap = tmap1.simplify(); + List mapList = new ArrayList<>(); + List invertList = new ArrayList<>(); + smap.mapList(true, smap.getInvert(), mapList, invertList); + int nmap = mapList.size(); + int imapPm = -1; + PolyMap polymap = null; + for (int imap = 0; imap < nmap; imap++) { + if (mapList.get(imap) instanceof PolyMap) { + imapPm = imap; + polymap = (PolyMap) mapList.get(imap).copy(); + polymap.setInvert(invertList.get(imap)); + break; + } + } + if (polymap == null || polymap.getNin() != 2 || polymap.getNout() != 2) { + return null; + } + + // The Mappings before and after the PolyMap, each joined into one, or a UnitMap if there + // are none. + Mapping mapLower = accumulate(mapList, invertList, 0, imapPm); + Mapping mapUpper = accumulate(mapList, invertList, imapPm + 1, nmap); + if (mapLower == null) { + mapLower = new UnitMap(2); + } + if (mapUpper == null) { + mapUpper = new UnitMap(2); + } + boolean ok = + mapLower.getNin() == 2 && mapLower.getNout() == 2 && mapUpper.getNin() == 2 && mapUpper.getNout() == 2; + + // The lower Mapping must be linear over the image, and may scale but not rotate. + double[] lbnd = new double[2]; + double[] ubnd = new double[2]; + double[] fit = null; + boolean scaling = false; + boolean rotation = false; + if (ok) { + lbnd[0] = 0.0; + lbnd[1] = 0.0; + ubnd[0] = dim[0]; + ubnd[1] = dim[1]; + if (ubnd[0] == AST__BAD) { + ubnd[0] = 1000.0; + } + if (ubnd[1] == AST__BAD) { + ubnd[1] = 1000.0; + } + fit = mapLower.linearApprox(lbnd, ubnd, tol); + ok = fit != null; + if (ok) { + if (Math.abs(fit[2] - 1.0) > LINEAR_TOL || Math.abs(fit[5] - 1.0) > LINEAR_TOL) { + scaling = true; + } + if (Math.abs(fit[3]) > LINEAR_TOL || Math.abs(fit[4]) > LINEAR_TOL) { + rotation = true; + } + } + } + if (rotation) { + ok = false; + } + + // A scaling is moved into the PolyMap, leaving the shift of origin, which the fit applies + // after the scaling, as a shift applied before it. + if (scaling && ok) { + double[] shift = {fit[0] / fit[2], fit[1] / fit[5]}; + mapLower = new ShiftMap(shift); + polymap = ScalePolyInputs.scalePolyInputs(polymap, new double[] {fit[2], fit[5]}); + } + + // The SIP polynomial has no constant or linear terms (beyond a unit copy of each input), + // so any shift in the PolyMap goes into the lower Mapping and any scaling or rotation into + // the upper. + Mapping polyStage = polymap; + if (ok) { + Mapping[] parts = new Mapping[3]; + if (AnalysePoly.analysePoly(polymap, parts)) { + mapLower = new CmpMap(mapLower, parts[0], true); + mapUpper = new CmpMap(parts[2], mapUpper, true); + polyStage = parts[1]; + } + } + + // The upper Mapping must be linear, with no shift of origin, over the region it is used + // in: the bounding box of a 3x3 grid of positions spanning the image, taken through the + // lower Mapping and the polynomial. Two positions a pixel from the image centre along each + // grid axis express the tolerance, in pixels, in the output space of the upper Mapping. + double utol = 0.0; + if (ok) { + double[] upx = new double[11]; + double[] upy = new double[11]; + int isamp = 0; + for (int ix = 0; ix < 3; ix++) { + for (int iy = 0; iy < 3; iy++) { + upx[isamp] = 0.5 * ix * ubnd[0]; + upy[isamp] = 0.5 * iy * ubnd[1]; + isamp++; + } + } + upx[9] = 0.5 * ubnd[0] + 1.0; + upy[9] = 0.5 * ubnd[1]; + upx[10] = 0.5 * ubnd[0]; + upy[10] = 0.5 * ubnd[1] + 1.0; + + double[][] uw = mapLower.tran2(11, upx, upy, true); + double[][] up = polyStage.tran2(11, uw[0], uw[1], true); + upx = up[0]; + upy = up[1]; + + for (isamp = 0; isamp < 9 && ok; isamp++) { + if (upx[isamp] == AST__BAD || upy[isamp] == AST__BAD) { + ok = false; + } else if (isamp == 0) { + lbnd[0] = upx[0]; + ubnd[0] = upx[0]; + lbnd[1] = upy[0]; + ubnd[1] = upy[0]; + } else { + if (upx[isamp] < lbnd[0]) { + lbnd[0] = upx[isamp]; + } + if (upx[isamp] > ubnd[0]) { + ubnd[0] = upx[isamp]; + } + if (upy[isamp] < lbnd[1]) { + lbnd[1] = upy[isamp]; + } + if (upy[isamp] > ubnd[1]) { + ubnd[1] = upy[isamp]; + } + } + } + + if (ok) { + double[][] st = mapUpper.tran2( + 3, new double[] {upx[4], upx[9], upx[10]}, new double[] {upy[4], upy[9], upy[10]}, true); + double[] sx = st[0]; + double[] sy = st[1]; + double uscale; + if (sx[0] != AST__BAD + && sy[0] != AST__BAD + && sx[1] != AST__BAD + && sy[1] != AST__BAD + && sx[2] != AST__BAD + && sy[2] != AST__BAD) { + double d1 = Math.sqrt((sx[1] - sx[0]) * (sx[1] - sx[0]) + (sy[1] - sy[0]) * (sy[1] - sy[0])); + double d2 = Math.sqrt((sx[2] - sx[0]) * (sx[2] - sx[0]) + (sy[2] - sy[0]) * (sy[2] - sy[0])); + // C's astMAX. + uscale = d1 > d2 ? d1 : d2; + } else { + uscale = 0.0; + } + if (uscale > 0.0) { + utol = tol * uscale; + } else { + ok = false; + } + } + + if (ok) { + fit = mapUpper.linearApprox(lbnd, ubnd, utol); + ok = fit != null && Math.abs(fit[0]) <= LINEAR_TOL && Math.abs(fit[1]) <= LINEAR_TOL; + } + } + + // The Mapping giving any other outputs, split off the inverse of map in the same way. + int[] outrem = null; + int noutrem = 0; + int[] inax2 = null; + Mapping tmap2 = null; + if (nout > 2 && ok) { + noutrem = nout - 2; + outrem = new int[noutrem]; + int ioutrem = 0; + for (int iout = 0; iout < nout; iout++) { + if (iout != lonax && iout != latax) { + outrem[ioutrem++] = iout; + } + } + MapSplit split2 = splitOutputs(map, outrem); + if (split2 != null) { + inax2 = split2.outputs; + tmap2 = split2.map; + tmap2.invert(); + } else { + ok = false; + } + } else if (nout != 2 || nin != 2) { + ok = false; + } + + // CRPIX: the grid position of the origin of intermediate world coordinates. The inverse + // may not be defined there, when SIP cannot describe the celestial axes. + if (ok) { + double[][] ref = smap.tran2(1, new double[] {0.0}, new double[] {0.0}, false); + crpix[0] = ref[0][0]; + crpix[1] = ref[1][0]; + if (crpix[0] == AST__BAD || crpix[1] == AST__BAD) { + ok = false; + } + } + if (!ok) { + return null; + } + + // The linear fit to the upper Mapping gives the CD matrix. + cd[0] = fit[2]; + cd[1] = fit[3]; + cd[2] = fit[4]; + cd[3] = fit[5]; + + storeCoefficients(polyStage, inaxes, store); + + store.ctype[latax] = sipCtype(store.ctype[latax]); + store.ctype[lonax] = sipCtype(store.ctype[lonax]); + + // The Mapping without the polynomial: the lower and upper Mappings in series, in parallel + // with the Mapping of any other axes, between PermMaps restoring the order of the inputs + // and outputs that the splits changed. + Mapping result = new CmpMap(mapLower, mapUpper, true); + if (tmap2 != null) { + result = new CmpMap(result, tmap2, false); + } + + int[] inperm1 = new int[nout]; + int[] outperm1 = new int[nout]; + inperm1[0] = lonax; + inperm1[1] = latax; + outperm1[lonax] = 0; + outperm1[latax] = 1; + if (tmap2 != null) { + System.arraycopy(outrem, 0, inperm1, 2, noutrem); + for (int iout = 0; iout < noutrem; iout++) { + outperm1[outrem[iout]] = iout + 2; + } + } + result = new CmpMap(result, PermMap.fromInternal(nout, inperm1, nout, outperm1, null), true); + + int[] inperm2 = new int[nin]; + int[] outperm2 = new int[nin]; + outperm2[0] = inax1[0]; + outperm2[1] = inax1[1]; + inperm2[inax1[0]] = 0; + inperm2[inax1[1]] = 1; + if (tmap2 != null) { + if (inax2.length < nin - 2) { + // C reads past the end of its array of inputs here. + throw Ast.err( + AstException.AST__INTER, + method + "(" + cls + "): the axes other than the celestial axes are fed by " + inax2.length + + " grid axes, not " + (nin - 2) + " (internal AST programming error)."); + } + System.arraycopy(inax2, 0, outperm2, 2, nin - 2); + for (int iin = 0; iin < nin - 2; iin++) { + inperm2[inax2[iin]] = iin + 2; + } + } + return new CmpMap(PermMap.fromInternal(nin, inperm2, nin, outperm2, null), result, true); + } + + /** + * C's {@code astInvert}, {@code astMapSplit} and {@code astInvert} on {@code map}: the split + * of the inverse of {@code map} that keeps the zero-based outputs {@code outax}, whose own + * outputs are the inputs of {@code map} feeding them; null if there is none. + */ + private static MapSplit splitOutputs(Mapping map, int[] outax) { + map.invert(); + try { + return map.mapSplit(outax); + } finally { + map.invert(); + } + } + + /** + * The Mappings of the list from {@code from} to before {@code to}, each applied with the + * Invert value the list gives it, joined in series: a copy of the first, which C copies, and + * each later one added in a CmpMap, which C makes from shared Mappings; null if there are + * none. + */ + private static Mapping accumulate(List mapList, List invertList, int from, int to) { + Mapping acc = null; + for (int imap = from; imap < to; imap++) { + Mapping m = mapList.get(imap); + int saved = m.swapInvert(invertList.get(imap)); + try { + if (acc != null) { + acc = new CmpMap(acc, m, true); + } else { + acc = (Mapping) m.copy(); + } + } finally { + m.restoreInvert(saved); + } + } + return acc; + } + + /** + * Stores the SIP coefficients of the defined transformations of {@code polymap}, forward (A + * and B) then inverse (AP and BP), as C does. A coefficient for celestial output 1 is an A (or + * AP) coefficient if the first of {@code inaxes} is the lower, and a B (or BP) coefficient + * otherwise, the powers {@code i} and {@code j} being those of the first and second input in + * the first case and exchanged in the second. Every power up to the largest used is first + * stored as {@code AST__BAD}; the unit linear terms are reduced by one, and the coefficients + * that are then neither zero nor bad stored over them. + */ + private static void storeCoefficients(Mapping polyStage, int[] inaxes, FitsStore store) { + for (int fwd = 1; fwd >= 0; fwd--) { + boolean forward = fwd == 1; + if (!(forward ? polyStage.getTranForward() : polyStage.getTranInverse())) { + continue; + } + double[] coeffs = polyCoeffs(polyStage, forward); + int ncoeff = coeffs.length / 4; + + // The largest power used on each input. + int aimax = 0; + int ajmmax = 0; + int bimax = 0; + int bjmmax = 0; + for (int icoeff = 0; icoeff < ncoeff; icoeff++) { + int pc = 4 * icoeff; + if (inaxes[0] < inaxes[1]) { + int i = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 2]); + int jm = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 3]); + if (coeffs[pc + 1] == 1) { + aimax = Math.max(aimax, i); + ajmmax = Math.max(ajmmax, jm); + } else { + bimax = Math.max(bimax, i); + bjmmax = Math.max(bjmmax, jm); + } + } else { + int i = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 3]); + int jm = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 2]); + if (coeffs[pc + 1] == 1) { + bimax = Math.max(bimax, i); + bjmmax = Math.max(bjmmax, jm); + } else { + aimax = Math.max(aimax, i); + ajmmax = Math.max(ajmmax, jm); + } + } + } + + double[][] a = forward ? store.sipA : store.sipAp; + double[][] b = forward ? store.sipB : store.sipBp; + for (int i = 0; i <= aimax; i++) { + for (int jm = 0; jm <= ajmmax; jm++) { + a = FitsStore.setItem(a, i, jm, AST__BAD); + } + } + for (int i = 0; i <= bimax; i++) { + for (int jm = 0; jm <= bjmmax; jm++) { + b = FitsStore.setItem(b, i, jm, AST__BAD); + } + } + + for (int icoeff = 0; icoeff < ncoeff; icoeff++) { + int pc = 4 * icoeff; + boolean toA; + int i; + int jm; + if (inaxes[0] < inaxes[1]) { + toA = coeffs[pc + 1] == 1; + i = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 2]); + jm = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 3]); + } else { + toA = coeffs[pc + 1] != 1; + i = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 3]); + jm = (int) FitsMakeIntWorld.roundHalfAway(coeffs[pc + 2]); + } + double val = coeffs[pc]; + if ((coeffs[pc + 1] == 1 && i == 1 && jm == 0) || (coeffs[pc + 1] == 2 && i == 0 && jm == 1)) { + val -= 1.0; + } + if (val != 0.0 && val != AST__BAD) { + if (toA) { + a = FitsStore.setItem(a, i, jm, val); + } else { + b = FitsStore.setItem(b, i, jm, val); + } + } + } + + if (forward) { + store.sipA = a; + store.sipB = b; + } else { + store.sipAp = a; + store.sipBp = b; + } + } + } + + /** + * C's {@code astPolyCoeffs} on the middle Mapping, which C takes to be a PolyMap. + * + * @throws AstException with status {@code AST__OBJIN} if it is not a PolyMap, as C's {@code + * astCheckPolyMap} reports + */ + private static double[] polyCoeffs(Mapping polyStage, boolean forward) { + if (polyStage instanceof PolyMap) { + return ((PolyMap) polyStage).polyCoeffs(forward); + } + throw Ast.err( + AstException.AST__OBJIN, + "Pointer to PolyMap required, but pointer to " + polyStage.astClass() + " given."); + } + + /** + * The CTYPE value C stores for a SIP axis: it copies the value into a buffer and writes + * {@code -SIP} from the ninth character. A value of fewer than eight characters keeps the + * null that ends it, so the buffer still holds the value; a longer one is cut to eight + * characters. An unset value stays unset. + */ + private static String sipCtype(String cval) { + if (cval == null || cval.length() < 8) { + return cval; + } + return cval.substring(0, 8) + "-SIP"; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsSkyPole.java b/src/main/java/uk/ac/starlink/ast/FitsSkyPole.java new file mode 100644 index 0000000..8ebfa58 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsSkyPole.java @@ -0,0 +1,138 @@ +package uk.ac.starlink.ast; + +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * The LONPOLE and LATPOLE values of a FITS-WCS description being written: C's {@code SkyPole} + * (fitschan.c). + * + *

Ported from Rust {@code fitschan/fset_to_store/sky_pole.rs}, following fitschan.c. + */ +final class FitsSkyPole { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** C's {@code AST__DD2R}: degrees to radians. */ + private static final double AST__DD2R = 0.017453292519943295; + + /** C's {@code AST__DR2D}: radians to degrees. */ + private static final double AST__DR2D = 57.29577951308232; + + /** C's {@code AST__DPI}: pi. */ + private static final double AST__DPI = 3.141592653589793; + + /** C's {@code AST__DPIBY2}: pi/2. */ + private static final double AST__DPIBY2 = 1.5707963267948966; + + /** The LATPOLE C's {@code SkyPole} passes to {@code WcsNatPole}. */ + private static final double LATPOLE_PROBE = 999.0; + + private FitsSkyPole() {} + + /** + * C's {@code SkyPole}: stores LONPOLE and LATPOLE, in degrees, for the projection {@code + * map2}, and for any projection but TPN copies them to parameters 3 and 4 of the FITS + * longitude axis. A value taking its default is stored as unset. + * + *

For a zenithal projection any LONPOLE can be had by a rotation in the projection plane, + * so the values are parameters 3 and 4 of the longitude axis of {@code map2}, where set (and + * never for TPN, whose parameters are polynomial terms). For any other projection, the + * celestial north pole is transformed to native spherical coordinates through the inverse of + * {@code map3}; its native latitude is LATPOLE unless it is the default {@code WcsNatPole} + * gives for the CRVAL already stored, and its native longitude, normalised to 0 to 2pi, is + * LONPOLE unless it is the default, 0 when the celestial latitude of the fiducial point is at + * least its native latitude and pi otherwise. + * + * @param map2 the inverted WcsMap, from intermediate world coordinates to native spherical + * coordinates + * @param map3 the Mapping from native spherical to celestial coordinates + * @param ilon the zero-based output of {@code map3} giving longitude + * @param ilat the zero-based output of {@code map3} giving latitude + * @param wperm the zero-based FITS axis describing each axis of the WCS Frame + * @param s the coordinate version character + * @param store the store, holding the CRVAL values + * @param method the calling method (unused, as in C) + * @param cls the class of the object written (unused, as in C) + */ + static void skyPole( + WcsMap map2, + Mapping map3, + int ilon, + int ilat, + int[] wperm, + char s, + FitsStore store, + String method, + String cls) { + int axlon = map2.getWcsAxis(1) - 1; + int axlat = map2.getWcsAxis(2) - 1; + int fitsIlon = wperm[ilon]; + int fitsIlat = wperm[ilat]; + + double lonpole = AST__BAD; + double latpole = AST__BAD; + if (map2.isZenithal()) { + if (map2.getWcsType() != WcsMap.AST__TPN) { + lonpole = map2.testPV(axlon, 3) ? map2.getPV(axlon, 3) : AST__BAD; + latpole = map2.testPV(axlon, 4) ? map2.getPV(axlon, 4) : AST__BAD; + } + } else { + // The celestial north pole in native spherical coordinates, through the inverse of + // map3: LONPOLE and LATPOLE. + int nax2 = map3.getNout(); + double[][] ptr2 = new double[nax2][1]; + ptr2[ilat][0] = AST__DPIBY2; + double[][] ptr1 = map3.transform(ptr2, 1, false); + + // The fiducial point (CRVAL) in radians. + Double crvalLat = store.crval[fitsIlat]; + double delta0 = (crvalLat == null ? 0.0 : crvalLat) * AST__DD2R; + Double crvalLon = store.crval[fitsIlon]; + double alpha0 = (crvalLon == null ? 0.0 : crvalLon) * AST__DD2R; + + // The default LATPOLE, by equation 8 of FITS-WCS paper II taking the positive signs; + // LATPOLE need not be stored if the pole has it. WcsNatPole sets a bad LONPOLE to its + // default, which C then uses below. + double phip = ptr1[axlon][0]; + FitsNativePole.NativePole np = FitsNativePole.wcsNatPole( + map2, alpha0, delta0, LATPOLE_PROBE, phip == AST__BAD ? null : phip, null); + ptr1[axlon][0] = np.phip; + if (np.pole != null) { + latpole = FitsStore.equalAng(ptr1[axlat][0], np.pole[1]) ? AST__BAD : ptr1[axlat][0]; + } else { + latpole = ptr1[axlat][0]; + } + + // The default LONPOLE is 0 if the celestial latitude of the fiducial point is at + // least its native latitude, and pi otherwise. + double theta0 = FitsFiducial.getFiducialNsc(map2)[1]; + lonpole = Pal.dranrm(ptr1[axlon][0]); + double deflonpole = delta0 >= theta0 ? 0.0 : AST__DPI; + if (FitsStore.equalAng(lonpole, deflonpole)) { + lonpole = AST__BAD; + } + + if (lonpole != AST__BAD) { + lonpole *= AST__DR2D; + } + if (latpole != AST__BAD) { + latpole *= AST__DR2D; + } + } + + store.lonpole = valueOrNull(lonpole); + store.latpole = valueOrNull(latpole); + + // FITS-WCS paper II recommends copies in parameters 3 and 4 of the longitude axis, which + // TPN uses for other purposes. + if (map2.getWcsType() != WcsMap.AST__TPN) { + store.setPv(fitsIlon, 3, valueOrNull(lonpole)); + store.setPv(fitsIlon, 4, valueOrNull(latpole)); + } + } + + /** A store value: null for {@code AST__BAD}, as C's {@code GetItem} reads a bad value as unset. */ + private static Double valueOrNull(double v) { + return v == AST__BAD ? null : v; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsSkySys.java b/src/main/java/uk/ac/starlink/ast/FitsSkySys.java new file mode 100644 index 0000000..c3137d2 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsSkySys.java @@ -0,0 +1,337 @@ +package uk.ac.starlink.ast; + +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * The FITS-WCS description of a celestial coordinate system, as a FitsChan write stores it: C's + * {@code SkySys} and {@code IsSkyOff} (fitschan.c). Dates are converted between time scales by + * C's {@code TDBConv}, {@link FitsEpoch#tdbConv}, through a TimeFrame. + * + *

Ported from Rust {@code fitschan/fset_to_store/sky_sys.rs}, following fitschan.c. + */ +final class FitsSkySys { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** C's {@code SkySys} system codes. */ + private static final int RADEC = 0; + + private static final int ECLIP = 1; + + private static final int HECLIP = 2; + + private static final int GALAC = 3; + + private static final int SUPER = 4; + + private static final int AZEL = 5; + + private static final int NOCEL = 6; + + private FitsSkySys() {} + + /** + * C's {@code IsSkyOff}: 1 if Frame {@code iframe} of {@code fset} is, or contains, a SkyFrame + * describing offset coordinates, one whose SkyRefIs is {@code Pole} or {@code Origin}; + * otherwise 0. The SkyRefIs attribute is read from the Frame, an error from a Frame without + * one being cleared as C clears it. + * + * @param iframe the index of the Frame, from 1, or {@link FrameSet#AST__CURRENT} or {@link + * FrameSet#AST__BASE} + */ + static int isSkyOff(FrameSet fset, int iframe) { + Frame frm = fset.getFrame(iframe); + String skyrefis; + try { + skyrefis = frm.getC("SkyRefIs"); + } catch (AstException e) { + skyrefis = null; + } + if (skyrefis != null && (ustrcmp(skyrefis, "POLE") || ustrcmp(skyrefis, "ORIGIN"))) { + return 1; + } + return 0; + } + + /** + * C's {@code SkySys}: stores in {@code store} the CTYPE, CNAME, RADESYS, EQUINOX, MJD-OBS, + * TIMESYS, CUNIT, WCSNAME and OBSGEO-X/Y/Z values describing the celestial axes of {@code + * skyfrm}, at FITS axes {@code axlon} and {@code axlat}. + * + *

The date of observation is the Epoch, written in the time scale the FitsChan's TIMESYS + * card names (used or not), and then TIMESYS too, or else in UTC; it is stored only when it + * differs from the equinox and only for the primary description ({@code s} a space). A TIMESYS + * value AST does not support raises a {@code badval} warning in front of the current card. + * + * @param fc the FitsChan, whose TIMESYS card is used and to which warnings go + * @param skyfrm the SkyFrame; nothing is stored unless its Domain is {@code SKY} + * @param wcstype 0 for the {@code -TAB} algorithm, 1 for a WcsMap projection + * @param wcsproj the WcsMap projection type, used when {@code wcstype} is 1 + * @param store the store + * @param axlon the zero-based FITS axis of longitude + * @param axlat the zero-based FITS axis of latitude + * @param s the coordinate version character, a space for the primary description + * @param isoff positive to describe offset coordinates; negative to describe absolute + * coordinates with the SkyRefIs (-1 Pole, -2 Origin, otherwise Ignored), SkyRef and SkyRefP + * attributes; zero to ignore offsets + * @param method the calling method, for warnings + * @param cls the class of the object written, for warnings + * @return whether the values stored are usable: false for a SkyFrame whose Domain is not + * {@code SKY} + */ + static boolean skySys( + FitsChan fc, + SkyFrame skyfrm, + int wcstype, + int wcsproj, + FitsStore store, + int axlon, + int axlat, + char s, + int isoff, + String method, + String cls) { + if (!FitsMakeIntWorld.isASkyFrame(skyfrm)) { + return false; + } + + // The equinox, the epoch of observation in TDB, and the system. + double eq = skyfrm.getEquinoxMjd(); + String sys = skyfrm.getC("system"); + double epTdb = skyfrm.testEpoch() ? skyfrm.getEpochMjd() : AST__BAD; + double epUtc = FitsEpoch.tdbConv(epTdb, TimeFrame.AST__UTC, true); + + // A TIMESYS card other than UTC, used or not, gives the time scale of the date, and is + // stored; its padding is removed first. + String timesys = timesysValue(fc); + double ep; + if (timesys != null && !"UTC".equals(timesys)) { + FitsWarnings warnings = new FitsWarnings(); + int scale = FitsEpoch.timeSysToAst(timesys, warnings); + for (FitsWarnings.Warning w : warnings.list()) { + fc.issueWarning(w, method); + } + ep = FitsEpoch.tdbConv(epTdb, scale, true); + store.timesys = timesys; + } else { + ep = epUtc; + } + + // MJD-OBS defaults to the epoch of the equinox, so need not be written when equal to it. + boolean defdate = MappingHelpers.astEqual(epUtc, eq); + + // The equinox as a Julian or Besselian epoch, and RADESYS. + int isys; + if (ustrcmp(sys, "FK4")) { + eq = Pal.epb(eq); + isys = RADEC; + store.radesys = "FK4"; + } else if (ustrcmp(sys, "FK4_NO_E") || ustrcmp(sys, "FK4-NO-E")) { + eq = Pal.epb(eq); + isys = RADEC; + store.radesys = "FK4-NO-E"; + } else if (ustrcmp(sys, "FK5")) { + eq = Pal.epj(eq); + isys = RADEC; + store.radesys = "FK5"; + } else if (ustrcmp(sys, "ICRS")) { + eq = AST__BAD; + isys = RADEC; + store.radesys = "ICRS"; + } else if (ustrcmp(sys, "GAPPT") || ustrcmp(sys, "Apparent") || ustrcmp(sys, "Geocentric")) { + eq = AST__BAD; + isys = RADEC; + store.radesys = "GAPPT"; + } else if (ustrcmp(sys, "Ecliptic")) { + // With no RADESYS, WcsSkyFrame reads an EQUINOX below 1984.0 as a Besselian epoch and + // any other as a Julian epoch. + eq = Pal.epb(eq) < 1984.0 ? Pal.epb(eq) : Pal.epj(eq); + isys = ECLIP; + } else if (ustrcmp(sys, "Helioecliptic")) { + eq = AST__BAD; + isys = HECLIP; + } else if (ustrcmp(sys, "Galactic")) { + eq = AST__BAD; + isys = GALAC; + } else if (ustrcmp(sys, "Supergalactic")) { + eq = AST__BAD; + isys = SUPER; + } else if (ustrcmp(sys, "AzEl")) { + eq = AST__BAD; + isys = AZEL; + } else { + eq = AST__BAD; + isys = NOCEL; + } + + // FITS has a single date of observation, which an alternate description must not change. + store.equinox = valueOrNull(eq); + if (!defdate && s == ' ') { + store.mjdobs = valueOrNull(ep); + } + + // The zero-based axes of latitude and longitude within the SkyFrame. + int latax = skyfrm.getLatAxis() - 1; + int lonax = 1 - latax; + + // The first four characters of CTYPE name the system, or offset coordinates. + String lontype; + String lattype; + if (isoff > 0) { + lontype = "OFLN"; + lattype = "OFLT"; + } else if (isys == RADEC) { + lontype = "RA--"; + lattype = "DEC-"; + } else if (isys == ECLIP) { + lontype = "ELON"; + lattype = "ELAT"; + } else if (isys == HECLIP) { + lontype = "HLON"; + lattype = "HLAT"; + } else if (isys == GALAC) { + lontype = "GLON"; + lattype = "GLAT"; + } else if (isys == SUPER) { + lontype = "SLON"; + lattype = "SLAT"; + } else if (isys == AZEL) { + lontype = "AZ--"; + lattype = "EL--"; + } else if (isys == NOCEL) { + // The axis symbols, when they have the form FITS-WCS requires ("xxLN/xxLT" or + // "xLON/xLAT"), otherwise "UNLN/UNLT". + String latsym = skyfrm.getSymbol(latax + 1); + String lonsym = skyfrm.getSymbol(lonax + 1); + boolean ok = false; + if (latsym.length() == 4 && lonsym.length() == 4) { + if ("LT".equals(latsym.substring(2)) + && "LN".equals(lonsym.substring(2)) + && latsym.regionMatches(0, lonsym, 0, 2)) { + ok = true; + } else if ("LAT".equals(latsym.substring(1)) + && "LON".equals(lonsym.substring(1)) + && latsym.charAt(0) == lonsym.charAt(0)) { + ok = true; + } + } + if (!ok) { + latsym = "UNLT"; + lonsym = "UNLN"; + } + lontype = padWithDashes(lonsym); + lattype = padWithDashes(latsym); + } else { + throw Ast.err(AstException.AST__INTER, "SkySys(FitsChan): unexpected celestial system code " + isys + "."); + } + + // The last four characters name the projection. + String prjName = wcstype == 0 ? "-TAB" : WcsMap.wcsPrjName(wcsproj); + store.ctype[axlon] = lontype + prjName; + store.ctype[axlat] = lattype + prjName; + + if (isoff > 0) { + // The CTYPE comments of offset coordinates say what they are offsets from. + String skyref = skyfrm.getC("SkyRef"); + String text = skyfrm.getC("Symbol(" + (lonax + 1) + ")"); + store.ctypeCom[axlon] = withoutFirst(text) + " offset from " + skyref; + text = skyfrm.getC("Symbol(" + (latax + 1) + ")"); + store.ctypeCom[axlat] = withoutFirst(text) + " offset from " + skyref; + } else if (isoff < 0) { + // Absolute coordinates keep the SkyFrame's offset attributes in AST-specific keywords. + double skyrefLon = skyfrm.getD("SkyRef(" + (lonax + 1) + ")"); + double skyrefLat = skyfrm.getD("SkyRef(" + (latax + 1) + ")"); + double skyrefpLon = skyfrm.getD("SkyRefP(" + (lonax + 1) + ")"); + double skyrefpLat = skyfrm.getD("SkyRefP(" + (latax + 1) + ")"); + store.skyrefis = isoff < -2 ? "IGNORED" : (isoff < -1 ? "ORIGIN" : "POLE"); + if (skyfrm.test("SkyRef(1)")) { + store.skyref[axlon] = skyrefLon; + store.skyref[axlat] = skyrefLat; + } + if (skyfrm.test("SkyRefP(1)")) { + store.skyrefp[axlon] = skyrefpLon; + store.skyrefp[axlat] = skyrefpLat; + } + } + + // A Label set for an axis is the CTYPE comment and CNAME. + if (skyfrm.testLabel(latax + 1)) { + String label = skyfrm.getLabel(latax + 1); + store.ctypeCom[axlat] = label; + store.cname[axlat] = label; + } + if (skyfrm.testLabel(lonax + 1)) { + String label = skyfrm.getLabel(lonax + 1); + store.ctypeCom[axlon] = label; + store.cname[axlon] = label; + } + + // Celestial axes are always in degrees, CUNIT's default. + store.cunit[axlat] = null; + store.cunit[axlon] = null; + + if (skyfrm.testDomain()) { + store.wcsname = skyfrm.getDomain(); + } + + // The observer's position, which AzEl needs, for the primary description only. + if (skyfrm.testObsLon() && skyfrm.testObsLat() && s == ' ') { + double geolon = skyfrm.getObsLonValue(); + double geolat = skyfrm.getObsLatValue(); + double h = skyfrm.getObsAlt(); + if (geolat != AST__BAD && geolon != AST__BAD && h != AST__BAD) { + double[] xyz = Pal.gd2gc(geolon, geolat, h); + store.obsgeox = xyz[0]; + store.obsgeoy = xyz[1]; + store.obsgeoz = xyz[2]; + } + } + return true; + } + + /** + * The value of the FitsChan's TIMESYS card as C's {@code GetValue} finds it with used cards + * included, as a string with trailing white space removed; null if there is none or its value + * is not a string. + */ + private static String timesysValue(FitsChan fc) { + FitsCard card = fc.cards().searchCardAnyUse("TIMESYS"); + if (card == null) { + return null; + } + FitsCardValue.Got got = + FitsCardValue.cnvType(card.value, FitsCardValue.Want.STRING, fc.getFitsRounding(), card.cName()); + if (got == null) { + return null; + } + String value = got.s; + if (value.length() > FitsCard.FITS_CARD_LEN) { + value = value.substring(0, FitsCard.FITS_CARD_LEN); + } + return FitsCard.trimEnd(value); + } + + /** {@code text} without its first character, as C's {@code text + 1}. */ + private static String withoutFirst(String text) { + return text.isEmpty() ? text : text.substring(1); + } + + /** The first four characters of {@code sym}, padded with dashes to four. */ + private static String padWithDashes(String sym) { + StringBuilder sb = new StringBuilder(sym.length() > 4 ? sym.substring(0, 4) : sym); + while (sb.length() < 4) { + sb.append('-'); + } + return sb.toString(); + } + + /** A store value: null for {@code AST__BAD}, as C's {@code GetItem} reads a bad value as unset. */ + private static Double valueOrNull(double v) { + return v == AST__BAD ? null : v; + } + + /** C's {@code !Ustrcmp( a, b )}: whether the strings are equal, ignoring case. */ + private static boolean ustrcmp(String a, String b) { + return a.equalsIgnoreCase(b); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsSpecTrans.java b/src/main/java/uk/ac/starlink/ast/FitsSpecTrans.java index 746d70c..113965b 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsSpecTrans.java +++ b/src/main/java/uk/ac/starlink/ast/FitsSpecTrans.java @@ -1,10 +1,8 @@ package uk.ac.starlink.ast; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.Locale; -import java.util.Set; import uk.ac.starlink.ast.internal.pal.Pal; /** @@ -13,16 +11,17 @@ * *

C writes the equivalents into a new FitsChan {@code ret}, reads keyword values from {@code * ret} in preference to the FitsChan {@code this} ({@code GetValue2}), and marks each card of - * {@code this} it reads as used. Here the equivalents are written into a copy of the cards, which - * then holds both, as C's reader sees them; the cards read are recorded as consumed with {@link - * FitsCardList#recordConsumed}, and no card is removed except where C deletes one. + * {@code this} it reads as used. Here the equivalents are added to a copy of the cards as + * translations ({@link FitsCardList#setTranslation}), which follow the header's cards, as C's + * {@code WcsToStore} reads {@code ret} after {@code this}; the cards read are recorded as consumed + * with {@link FitsCardList#recordConsumed}, and no card is removed except where C deletes one. * - *

The translations only the FITS-PC, FITS-IRAF and FITS-CLASS encodings make (RADECSYS to - * RADESYS, LONGPOLE to LONPOLE, PROJPi to PVi_m, CmVALi and its relatives to alternate axis - * descriptions, CDjjjiii to PCi_j, and C's {@code ClassTrans}) are not available, since those - * encodings are not read; asking for one of them throws {@link UnsupportedOperationException}. The - * reads C makes of those keywords under every encoding, and the CmELTi translation C makes under - * every encoding, are made. + *

Some translations are made only for some encodings, as in C: RADECSYS to RADESYS, LONGPOLE to + * LONPOLE, PROJPi to PVi_m, and CmVALi, CmPIXi, CmYPEi and CmNITi to alternate axis descriptions + * for FITS-PC and FITS-IRAF, and CDjjjiii to PCi_j for FITS-IRAF; C reads those keywords under + * every encoding, and translates CmELTi under every encoding. C's {@code ClassTrans}, the + * translation FITS-CLASS makes, is not available, since that encoding is not read; asking for it + * throws {@link UnsupportedOperationException}. * *

Ported from Rust {@code fitschan/spec_trans.rs}, following the order and tests of C's {@code * SpecTrans}. @@ -134,7 +133,7 @@ static final class WatCoeffs { * (those at the entry card first), is thrown as the error C reports; the translations change * only the copy, so stopping once they are done ends the read where C's ends. * - * @throws UnsupportedOperationException for the FITS-PC, FITS-IRAF and FITS-CLASS encodings + * @throws UnsupportedOperationException for the FITS-CLASS encoding * @throws AstException where C's {@code SpecTrans} reports an error: a keyword it needs is * absent or has no value, or an IRAF WAT string holds a word that is not a number */ @@ -160,21 +159,16 @@ static FitsCardList specTrans( * The translations of {@link #specTrans}, written into {@code cards} itself. C's {@code this} * is {@code cards} as supplied, and its {@code ret} the keywords written here. * - * @throws UnsupportedOperationException for the FITS-PC, FITS-IRAF and FITS-CLASS encodings + * @throws UnsupportedOperationException for the FITS-CLASS encoding * @throws AstException as {@link #specTrans} does */ static void specTransInplace( FitsCardList cards, FitsChan.Encoding encoding, TransAttrs attrs, TransWarnings warnings) { - switch (encoding) { - case FITS_PC: - case FITS_IRAF: - case FITS_CLASS: - throw new UnsupportedOperationException( - "FitsChan: reading the " + encoding.cName() + " encoding is not available"); - default: - break; - } - Translator t = new Translator(cards, attrs, warnings); + if (encoding == FitsChan.Encoding.FITS_CLASS) { + throw new UnsupportedOperationException( + "FitsChan: reading the " + encoding.cName() + " encoding is not available"); + } + Translator t = new Translator(cards, encoding, attrs, warnings); // The primary axis description, then 'A' to 'Z' (fitschan.c:31558-31559, 32615). t.version(' '); for (char s = 'A'; s <= 'Z'; s++) { @@ -510,17 +504,45 @@ private static final class Translator { /** C's {@code this}: the cards as supplied. */ private final FitsCardList src; - /** The keywords C's {@code ret} holds, in upper case. */ - private final Set ret = new HashSet<>(); - private final TransAttrs attrs; private final TransWarnings warnings; - Translator(FitsCardList cards, TransAttrs attrs, TransWarnings warnings) { + /** Whether the encoding is FITS-PC or FITS-IRAF, which translate the most keywords. */ + private final boolean pcOrIraf; + + /** Whether the encoding is FITS-IRAF, which alone translates the CDjjjiii matrix. */ + private final boolean iraf; + + /** + * C's {@code CardComm( this )} where C gives it as the comment of a translated card: the + * comment of the current card of the cards as supplied, which is the first card not + * consumed when a read starts (C's {@code Read} reads only at start-of-file, and {@code + * astClearCard} passes over used cards), or empty if there is none or it has no comment. + * Every such use precedes the first that moves the current card. + */ + private final String cardComm; + + Translator(FitsCardList cards, FitsChan.Encoding encoding, TransAttrs attrs, TransWarnings warnings) { this.cards = cards; this.src = cards.copy(); this.attrs = attrs; this.warnings = warnings; + this.pcOrIraf = encoding == FitsChan.Encoding.FITS_PC || encoding == FitsChan.Encoding.FITS_IRAF; + this.iraf = encoding == FitsChan.Encoding.FITS_IRAF; + this.cardComm = currentComment(src); + } + + /** The comment of the current card of {@code list}, passing over consumed cards, or empty. */ + private static String currentComment(FitsCardList list) { + List all = list.cards(); + for (int k = list.position(); k < all.size(); k++) { + FitsCard c = all.get(k); + if (!c.isConsumed()) { + String com = c.cComment(); + return com == null ? "" : com; + } + } + return ""; } // ------------------------------------------------------------------ @@ -562,8 +584,9 @@ private static FitsCardValue.Got getValue( */ private FitsCardValue.Got getValue2(String keyword, FitsCardValue.Want want, boolean report) { String k = keyword.toUpperCase(Locale.ROOT); - if (ret.contains(k)) { - FitsCardValue.Got g = getValue(cards, k, want, false); + FitsCard t = cards.findTranslation(k); + if (t != null) { + FitsCardValue.Got g = FitsCardValue.cnvType(t.value, want, 10, k); if (g != null) { return g; } @@ -604,25 +627,21 @@ private Double getFloatThis(String keyword, boolean mark) { /** C's {@code SetValue( ret, keyword, ... )} of a floating value. */ private void setFloat(String keyword, double value, String comment) { - ret.add(keyword.toUpperCase(Locale.ROOT)); - cards.setFloat(keyword, value, comment); + cards.setTranslation(keyword, FitsCard.Value.ofFloat(value), comment); } /** C's {@code SetValue( ret, keyword, ... )} of a string. */ private void setString(String keyword, String value, String comment) { - ret.add(keyword.toUpperCase(Locale.ROOT)); - cards.setString(keyword, value, comment); + cards.setTranslation(keyword, FitsCard.Value.ofString(value), comment); } /** * C's {@code SetValue( ret, keyword, ... )} of a string with no comment, which leaves the * comment of the keyword in {@code this} as the one a reader sees ({@code SetItemC} ignores - * a null comment): the value replaces the card's and keeps its comment. + * a null comment). */ private void replaceString(String keyword, String value) { - FitsCard old = cards.find(keyword); - String comment = old == null || old.comment == null ? "" : old.comment; - setString(keyword, value, comment); + setString(keyword, value, null); } /** @@ -679,8 +698,14 @@ void version(char s) { if (s == ' ') { // RADECSYS and LONGPOLE are read under every encoding, and translated only for // FITS-PC and FITS-IRAF (fitschan.c:31656-31675). - getString2("RADECSYS"); - getFloat2("LONGPOLE", false); + String radecsys = getString2("RADECSYS"); + if (radecsys != null && pcOrIraf) { + setString("RADESYS", radecsys, cardComm); + } + Double longpole = getFloat2("LONGPOLE", false); + if (longpole != null && pcOrIraf) { + setFloat("LONPOLE", longpole, cardComm); + } } zeroCdelt(s); pcFamily(s); @@ -827,16 +852,36 @@ private void zeroCdelt(char s) { /** * The conversions that produce PCi_j keywords, made only if there are none - * (fitschan.c:31718-31906): CDj_i, and then the 6-digit PCjjjiii or CROTAi. The legacy - * CDjjjiii matrix is converted only for FITS-IRAF. + * (fitschan.c:31718-31906): the legacy CDjjjiii matrix of the primary description, for + * FITS-IRAF only, then CDj_i, and then the 6-digit PCjjjiii or CROTAi. */ private void pcFamily(char s) { if (src.keyFields(versioned("PC%d_%d", s), 1).n > 0) { return; } boolean gotpcij = false; - FitsCardList.KeyFields kf = src.keyFields(versioned("CD%d_%d", s), 1); - if (kf.n > 0) { + FitsCardList.KeyFields kf; + // The CDjjjiii cards are read, and so consumed, only under FITS-IRAF, which alone + // translates them; the matrix gives PCj_i and a CDELT of 1.0 for each row with an + // element (fitschan.c:31727-31760). + if (iraf && s == ' ') { + kf = src.keyFields("CD%3d%3d", 1); + if (kf.n > 0) { + int naxis = kf.hi[0]; + for (int j = 0; j < naxis; j++) { + for (int i = 0; i < naxis; i++) { + Double dval = getFloat2(String.format(Locale.ROOT, "CD%03d%03d", j + 1, i + 1), false); + if (dval != null) { + setFloat(key2("PC", j + 1, i + 1, ' '), dval, ""); + setFloat(key("CDELT", j + 1, s), 1.0, ""); + gotpcij = true; + } + } + } + } + } + kf = src.keyFields(versioned("CD%d_%d", s), 1); + if (!gotpcij && kf.n > 0) { int naxis = kf.hi[0]; for (int j = 0; j < naxis; j++) { // The CDELT is the length of the row, signed so that the diagonal PC element @@ -916,7 +961,7 @@ private void pcFamily(char s) { /** * PROJPi keywords (fitschan.c:31910-31958). When there are PV values for the longitude axis * that look complete, C trusts them; otherwise it reads the PROJP values, which it - * translates to PV values only for FITS-PC and FITS-IRAF. + * translates to PV values of the latitude axis only for FITS-PC and FITS-IRAF. */ private void projp() { FitsCardList.KeyFields kf = src.keyFields("PROJP%d", 1); @@ -941,22 +986,27 @@ private void projp() { } if (useProjp) { for (int i = kf.lo[0]; i <= kf.hi[0]; i++) { - getFloat2(key("PROJP", i, ' '), false); + Double dval = getFloat2(key("PROJP", i, ' '), false); + if (dval != null && pcOrIraf) { + setFloat(key2("PV", axlat + 1, i, ' '), dval, cardComm); + } } } } /** * CmVALi, CmPIXi, CmYPEi, CmNITi and CmELTi keywords (fitschan.c:31962-32100). C reads the - * first four under every encoding but translates them only for FITS-PC and FITS-IRAF; it - * translates CmELTi, and the PCjjjiii matrix with it, into CDELTis and PCj_is under every - * encoding. + * first four under every encoding but translates them, into CRVALis, CRPIXis, CTYPEis and + * CUNITis, only for FITS-PC and FITS-IRAF; it translates CmELTi, and the PCjjjiii matrix + * with it, into CDELTis and PCj_is under every encoding. The letter {@code s} is {@code A} + * for the lowest {@code m} of each keyword, whatever that is, and the next letter for each + * {@code m} after it. */ private void cmxxx() { - readCmxxx("C%1dVAL%d", "VAL", FitsCardValue.Want.FLOAT); - readCmxxx("C%1dPIX%d", "PIX", FitsCardValue.Want.FLOAT); - readCmxxx("C%1dYPE%d", "YPE", FitsCardValue.Want.STRING); - readCmxxx("C%1dNIT%d", "NIT", FitsCardValue.Want.STRING); + readCmxxx("C%1dVAL%d", "VAL", "CRVAL", FitsCardValue.Want.FLOAT); + readCmxxx("C%1dPIX%d", "PIX", "CRPIX", FitsCardValue.Want.FLOAT); + readCmxxx("C%1dYPE%d", "YPE", "CTYPE", FitsCardValue.Want.STRING); + readCmxxx("C%1dNIT%d", "NIT", "CUNIT", FitsCardValue.Want.STRING); FitsCardList.KeyFields kf = src.keyFields("C%1dELT%d", 2); if (kf.n == 0) { return; @@ -974,7 +1024,7 @@ private void cmxxx() { cdeltj = 1.0; } } - setFloat(key("CDELT", j + 1, ss), cdeltj, ""); + setFloat(key("CDELT", j + 1, ss), cdeltj, cardComm); for (int i = 0; i < naxis; i++) { Double e = getFloat2(String.format(Locale.ROOT, "PC%03d%03d", j + 1, i + 1), false); double dval; @@ -990,16 +1040,28 @@ private void cmxxx() { } } - /** Reads every {@code C} keyword the template's bounds cover, as C does. */ - private void readCmxxx(String template, String kind, FitsCardValue.Want want) { + /** + * Reads every {@code C} keyword the template's bounds cover, as C does, and for + * FITS-PC and FITS-IRAF writes each value found as {@code }. + */ + private void readCmxxx(String template, String kind, String root, FitsCardValue.Want want) { FitsCardList.KeyFields kf = src.keyFields(template, 2); if (kf.n == 0) { return; } + char ss = 'A'; for (int m = kf.lo[0]; m <= kf.hi[0]; m++) { for (int i = kf.lo[1]; i <= kf.hi[1]; i++) { - getValue2("C" + m + kind + i, want, false); + FitsCardValue.Got g = getValue2("C" + m + kind + i, want, false); + if (g != null && pcOrIraf) { + if (want == FitsCardValue.Want.STRING) { + setString(key(root, i, ss), g.s, cardComm); + } else { + setFloat(key(root, i, ss), g.d, cardComm); + } + } } + ss++; } } @@ -1171,8 +1233,7 @@ private void qv(char s) { cards.recordConsumed(c.keyword); String keyname = "P" + c.keyword.substring(1); if (getValue2(keyname, FitsCardValue.Want.FLOAT, false) == null) { - ret.add(keyname); - cards.setValue(keyname, c.value, c.cComment() == null ? "" : c.cComment()); + cards.setTranslation(keyname, c.value, c.cComment()); } } } diff --git a/src/main/java/uk/ac/starlink/ast/FitsStore.java b/src/main/java/uk/ac/starlink/ast/FitsStore.java index d1c21f0..f330e7c 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsStore.java +++ b/src/main/java/uk/ac/starlink/ast/FitsStore.java @@ -1,5 +1,6 @@ package uk.ac.starlink.ast; +import java.util.Arrays; import java.util.Locale; /** @@ -208,6 +209,46 @@ final class FitsStore { axref = new Double[naxis]; } + /** + * Lengthens the axis-indexed arrays to hold at least {@code n} axes, keeping their values, as + * C's {@code SetItem} lengthens an item to hold the index it is given; {@link #naxis} becomes + * the new length. Nothing changes if the store already holds {@code n} axes. + */ + void ensureAxes(int n) { + if (n <= naxis) { + return; + } + crpix = Arrays.copyOf(crpix, n); + crval = Arrays.copyOf(crval, n); + cdelt = Arrays.copyOf(cdelt, n); + dims = Arrays.copyOf(dims, n); + pc = grow(pc, n, n); + cd = grow(cd, n, n); + ctype = Arrays.copyOf(ctype, n); + ctypeCom = Arrays.copyOf(ctypeCom, n); + cunit = Arrays.copyOf(cunit, n); + cname = Arrays.copyOf(cname, n); + pv = grow(pv, n, MAX_PV_PARAMS); + String[][] newPs = new String[n][]; + for (int i = 0; i < n; i++) { + newPs[i] = i < ps.length ? ps[i] : new String[MAX_PV_PARAMS]; + } + ps = newPs; + skyref = Arrays.copyOf(skyref, n); + skyrefp = Arrays.copyOf(skyrefp, n); + axref = Arrays.copyOf(axref, n); + naxis = n; + } + + /** {@code a} with {@code rows} rows of at least {@code cols} elements, keeping its values. */ + private static Double[][] grow(Double[][] a, int rows, int cols) { + Double[][] g = new Double[rows][]; + for (int i = 0; i < rows; i++) { + g[i] = i < a.length ? Arrays.copyOf(a[i], Math.max(cols, a[i].length)) : new Double[cols]; + } + return g; + } + /** A copy of this store, sharing no arrays with it. */ FitsStore copy() { FitsStore c = new FitsStore(naxis); @@ -286,6 +327,63 @@ private static double[][] copyOf(double[][] a) { return c; } + /** + * C's {@code SetItem} for a table indexed by two numbers, such as the SIP coefficients: {@code + * item} with element {@code [i][jm]} set to {@code val}, rows added and lengthened as needed, + * new rows empty and new elements {@code AST__BAD}. The table is changed in place unless it + * has to gain rows, when a longer copy is returned. + * + * @throws AstException with status {@code AST__INTER} if {@code i} is outside 0 to 98 or + * {@code jm} outside 0 to 99, as C checks + */ + static double[][] setItem(double[][] item, int i, int jm, double val) { + if (i < 0 || i > 98) { + throw Ast.err( + AstException.AST__INTER, + "SetItem(fitschan): AST internal error; intermediate axis index " + i + " is invalid."); + } + if (jm < 0 || jm > 99) { + throw Ast.err( + AstException.AST__INTER, + "SetItem(fitschan): AST internal error; pixel axis or parameter index " + jm + " is invalid."); + } + double[][] table = item; + if (table.length < i + 1) { + int nel = table.length; + table = Arrays.copyOf(table, i + 1); + for (int el = nel; el <= i; el++) { + table[el] = new double[0]; + } + } + if (table[i].length < jm + 1) { + int nel = table[i].length; + table[i] = Arrays.copyOf(table[i], jm + 1); + Arrays.fill(table[i], nel, jm + 1, AstObject.AST__BAD); + } + table[i][jm] = val; + return table; + } + + /** + * C's {@code SetItem( &(store->pv), i, m, ... )}: sets PVi_m (zero-based axis {@code i}) to + * {@code val}, null being C's {@code AST__BAD}, lengthening the axis's parameters as C's table + * grows when {@code m} is beyond them. + * + * @throws AstException with status {@code AST__INTER} if {@code m} is outside 0 to 99, as C + * checks + */ + void setPv(int i, int m, Double val) { + if (m < 0 || m > 99) { + throw Ast.err( + AstException.AST__INTER, + "SetItem(fitschan): AST internal error; pixel axis or parameter index " + m + " is invalid."); + } + if (pv[i].length <= m) { + pv[i] = Arrays.copyOf(pv[i], m + 1); + } + pv[i][m] = val; + } + /** Whether any PC matrix element is set. */ boolean hasPcMatrix() { for (Double[] row : pc) { @@ -368,17 +466,18 @@ int maxPvM() { /** * C's {@code FindLonLatSpecAxes} (fitschan.c:10822): the longitude, latitude and spectral axes, - * numbered from 0 (-1 for none), among the first WCSAXES (or NAXIS) CTYPE values. A spectral - * axis is one {@code IsSpectral} or {@code IsAIPSSpectral} recognises; a celestial axis has - * {@code -} as its fifth character, and is a longitude axis for {@code RA--}, {@code AZ--}, - * {@code xLON} and {@code xyLN}, and a latitude axis for {@code DEC-}, {@code EL--}, {@code - * xLAT} and {@code xyLT}. The last axis of each kind is the one given. + * numbered from 0 (-1 for none), among the first WCSAXES CTYPE values, or, without WCSAXES, + * the first {@code storeNaxis}, C's {@code store->naxis}. A spectral axis is one {@code + * IsSpectral} or {@code IsAIPSSpectral} recognises; a celestial axis has {@code -} as its fifth + * character, and is a longitude axis for {@code RA--}, {@code AZ--}, {@code xLON} and {@code + * xyLN}, and a latitude axis for {@code DEC-}, {@code EL--}, {@code xLAT} and {@code xyLT}. The + * last axis of each kind is the one given. */ - int[] lonLatSpecAxes() { + int[] lonLatSpecAxes(int storeNaxis) { int axlon = -1; int axlat = -1; int axspec = -1; - int n = wcsaxes != null ? wcsaxes : naxis; + int n = wcsaxes != null ? wcsaxes : storeNaxis; for (int i = 0; i < n; i++) { String ct = i < ctype.length ? ctype[i] : null; if (ct == null) { diff --git a/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java b/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java index ebc2df3..0b0de53 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java +++ b/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java @@ -347,7 +347,7 @@ static CelestialResult buildCelestialWithDefB1950( map2 = new WcsMap(naxes, latprj, axlon + 1, axlat + 1); setProjectionParameters(store, map2, axlon, axlat, warnings); map2.invert(); - map3 = wcsNative(store, map2, -1, -1, warnings); + map3 = wcsNative(store, map2, -1, -1, warnings, "astRead", "FitsChan"); reflon = store.crval[axlon] != null ? store.crval[axlon] * AST__DD2R : AST__BAD; reflat = store.crval[axlat] != null ? store.crval[axlat] * AST__DD2R : AST__BAD; } @@ -356,7 +356,7 @@ static CelestialResult buildCelestialWithDefB1950( // origin, so the IWC are shifted onto the projection plane coordinates of the fiducial // point (fitschan.c:36491-36520). TPN uses the parameter for a polynomial term. if (map2.getWcsType() != WcsMap.AST__TPN && map2.getPV(axlon, 0) != 0.0) { - double[] ppc = getFiducialPpc(map2); + double[] ppc = FitsFiducial.getFiducialPpc(map2); if (ppc[0] != AST__BAD && ppc[1] != AST__BAD) { double[] shifts = new double[naxes]; shifts[axlon] = ppc[0]; @@ -438,24 +438,6 @@ private static void setOrWarn( } } - /** - * C's {@code GetFiducialPPC} (fitschan.c): the projection plane coordinates, in radians, of - * the fiducial point of {@code map}, an inverted WcsMap, as {@code {x0, y0}}; found by - * transforming the native spherical coordinates of the fiducial point through the inverse of - * {@code map}, with zero on the other axes. - */ - private static double[] getFiducialPpc(WcsMap map) { - int naxes = map.getNin(); - int axlon = map.getWcsAxis(1) - 1; - int axlat = map.getWcsAxis(2) - 1; - double[][] in = new double[naxes][1]; - double[] nsc = FitsFiducial.getFiducialNsc(map); - in[axlon][0] = nsc[0]; - in[axlat][0] = nsc[1]; - double[][] out = map.tranP(1, naxes, in, false, naxes); - return new double[] {out[axlon][0], out[axlat][0]}; - } - /** * C's {@code WcsNative} (fitschan.c:38518): the Mapping from native spherical coordinates to * celestial coordinates for the inverted WcsMap {@code wcsmap}, leaving any other axes @@ -472,11 +454,21 @@ private static double[] getFiducialPpc(WcsMap map) { * 3 and 4 of the longitude axis when set (except for TPN), and otherwise the store's, which * are then set as those parameters. * + *

{@code warnings} is null where C passes no FitsChan, and then nothing is warned of. + * + * @param method the calling method, for the error message + * @param cls the class of the object read or written, for the error message * @throws AstException with status {@code AST__BDFTS} if {@link FitsNativePole#wcsNatPole} * cannot place the native pole */ - private static Mapping wcsNative( - FitsStore store, WcsMap wcsmap, int fitsIlon, int fitsIlat, FitsWarnings warnings) { + static Mapping wcsNative( + FitsStore store, + WcsMap wcsmap, + int fitsIlon, + int fitsIlat, + FitsWarnings warnings, + String method, + String cls) { int naxis = wcsmap.getNin(); int axlon = wcsmap.getWcsAxis(1) - 1; int axlat = wcsmap.getWcsAxis(2) - 1; @@ -516,7 +508,7 @@ private static Mapping wcsNative( } else if (delta0 < -AST__DPIBY2) { delta0 = -AST__DPIBY2; } - if (unlimited != delta0) { + if (unlimited != delta0 && warnings != null) { warnings.push(new FitsWarnings.Warning( "badlat", "The original FITS header specified a fiducial point with latitude " @@ -556,7 +548,10 @@ private static Mapping wcsNative( FitsNativePole.NativePole np = FitsNativePole.wcsNatPole( wcsmap, alpha0, delta0, latpole != AST__BAD ? latpole : null, phip != AST__BAD ? phip : null, warnings); if (np.pole == null) { - throw bdfts("Conversion from FITS WCS native coordinates to celestial coordinates is ill-conditioned."); + throw Ast.err( + AstException.AST__BDFTS, + method + "(" + cls + "): Conversion from FITS WCS native coordinates to celestial coordinates is" + + " ill-conditioned."); } phip = np.phip; double alphap = np.pole[0]; diff --git a/src/main/java/uk/ac/starlink/ast/FitsWcsDecompose.java b/src/main/java/uk/ac/starlink/ast/FitsWcsDecompose.java new file mode 100644 index 0000000..f43fd29 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsWcsDecompose.java @@ -0,0 +1,298 @@ +package uk.ac.starlink.ast; + +/** + * The linear-fit helpers with which a FitsChan write finds the CRPIX and CD values of a grid to + * intermediate world coordinate Mapping: C's {@code FindBasisVectors}, {@code MakeBasisVectors}, + * {@code FitLine}, {@code FitOK} and {@code SplitMat} (fitschan.c). + * + *

Arrays of points are indexed {@code [axis][point]}, as the coordinate arrays of C's + * PointSets are. + * + *

Ported from Rust {@code fitschan/wcs_decompose.rs}, following fitschan.c. + */ +final class FitsWcsDecompose { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** Half the number of points FitLine fits, C's {@code NPO2}. */ + private static final int NPO2 = 50; + + /** The number of points FitLine fits, C's {@code NP}. */ + private static final int NP = 2 * NPO2 + 1; + + private FitsWcsDecompose() {} + + /** + * C's {@code MakeBasisVectors}: puts in {@code ptrg} the grid position {@code g0} followed by + * the {@code nin} positions one unit from it along each grid axis, and in {@code ptrw} those + * positions transformed into intermediate world coordinates by {@code map}. + * + * @param ptrg receives the grid positions, {@code [nin][nin + 1]} + * @param ptrw receives the transformed positions, {@code [nout][nin + 1]} + * @return whether every transformed value is good + */ + static boolean makeBasisVectors(Mapping map, int nin, int nout, double[] g0, double[][] ptrg, double[][] ptrw) { + for (int i = 0; i < nin; i++) { + double[] c = ptrg[i]; + for (int ii = 0; ii < nin + 1; ii++) { + c[ii] = g0[i]; + } + c[i + 1] += 1.0; + } + double[][] out = map.transform(ptrg, nin + 1, true); + for (int j = 0; j < nout; j++) { + System.arraycopy(out[j], 0, ptrw[j], 0, nin + 1); + } + boolean ret = true; + for (int j = 0; j < nout; j++) { + for (int ii = 0; ii < nin + 1; ii++) { + if (ptrw[j][ii] == AST__BAD) { + ret = false; + break; + } + } + } + return ret; + } + + /** + * C's {@code FindBasisVectors}: finds a grid position at which {@code map} gives good + * intermediate world coordinates, as do the positions one unit from it along each grid axis, + * trying the grid centre (when every dimension is known), then (1, 1, ...), then positions + * moving out along the diagonal and along each axis, doubling the distance each time up to + * the largest dimension, or 10240 when none is known. + * + * @param dim the grid dimensions, {@code AST__BAD} where unknown, or null if none is known + * @param ptrg receives the grid positions, {@code [nin][nin + 1]}, as {@link #makeBasisVectors} + * gives them for the position found + * @param ptrw receives the transformed positions, {@code [nout][nin + 1]} + * @return whether a position was found + */ + static boolean findBasisVectors(Mapping map, int nin, int nout, double[] dim, double[][] ptrg, double[][] ptrw) { + double[] g0 = new double[nin]; + + // The grid centre, if known. A dimension that is not known stops the search for the + // largest dimension, which keeps the largest of those before it. + double ddlim = 0.0; + boolean ret = false; + if (dim != null) { + ret = true; + for (int i = 0; i < nin; i++) { + if (dim[i] != AST__BAD) { + g0[i] = 0.5 * (1 + dim[i]); + if (dim[i] > ddlim) { + ddlim = dim[i]; + } + } else { + ret = false; + break; + } + } + } + if (ret) { + ret = makeBasisVectors(map, nin, nout, g0, ptrg, ptrw); + } + + // Grid position (1, 1, ...). + if (!ret) { + for (int i = 0; i < nin; i++) { + g0[i] = 1.0; + } + ret = makeBasisVectors(map, nin, nout, g0, ptrg, ptrw); + } + + // Positions moving out from (1, 1, ...), first across the middle of the grid, then along + // each grid axis in turn. + double dd = 10.0; + if (ddlim == 0.0) { + ddlim = 10240.0; + } + while (!ret && dd <= ddlim) { + for (int i = 0; i < nin; i++) { + if (dim != null && dim[i] != AST__BAD) { + g0[i] = dd * dim[i] / ddlim; + } else { + g0[i] = dd; + } + } + ret = makeBasisVectors(map, nin, nout, g0, ptrg, ptrw); + for (int ii = 0; !ret && ii < nin; ii++) { + for (int i = 0; i < nin; i++) { + g0[i] = 1.0; + } + g0[ii] = dd; + ret = makeBasisVectors(map, nin, nout, g0, ptrg, ptrw); + } + dd *= 2.0; + } + return ret; + } + + /** + * C's {@code FitOK}: whether the root mean square difference between the good pairs of actual + * and estimated values is below {@code tol}; false if there is no good pair. + */ + static boolean fitOK(int n, double[] act, double[] est, double tol) { + double s1 = 0.0; + double s2 = 0.0; + for (int i = 0; i < n; i++) { + if (act[i] != AST__BAD && est[i] != AST__BAD) { + double diff = act[i] - est[i]; + s1 += diff * diff; + s2 += 1.0; + } + } + boolean ret = false; + if (s2 > 0.0) { + double mserr = s1 / s2; + if (mserr < tol * tol) { + ret = true; + } + } + return ret; + } + + /** + * C's {@code FitLine}: transforms 101 points along the line through {@code g0} with direction + * {@code g}, spread over the axis length {@code dim} (or 1 apart when it is unknown), and fits + * a straight line to each output by least squares. + * + * @param g a unit vector in the input space + * @param g0 the central position of the line in the input space + * @param w0 the output position corresponding to {@code g0} + * @param dim the length of the pixel axis, or {@code AST__BAD} if unknown + * @param tol the largest root mean square residual allowed on each output + * @return the output vector corresponding to a unit step along {@code g}, or null if the + * Mapping is not linear along the line, {@code dim} is zero, or {@code w0} has a bad value + */ + static double[] fitLine(Mapping map, double[] g, double[] g0, double[] w0, double dim, double[] tol) { + if (dim == 0.0) { + return null; + } + int nin = map.getNin(); + int nout = map.getNout(); + if (nout < nin) { + return null; + } + for (int j = 0; j < nout; j++) { + if (w0[j] == AST__BAD) { + return null; + } + } + double gap = (dim != AST__BAD) ? dim / NP : 1.0; + + double[][] ptr1 = new double[nin][NP]; + for (int j = 0; j < nin; j++) { + double[] pax = ptr1[j]; + double dax = g[j] * gap; + int k = 0; + for (int i = -NPO2; i <= NPO2; i++) { + pax[k++] = g0[j] + dax * i; + } + } + double[][] ptr2 = map.transform(ptr1, NP, true); + + double[] ret = new double[nout]; + double[] offset = new double[nout]; + for (int j = 0; j < nout; j++) { + double[] pax = ptr2[j]; + double sdw = 0.0; + double sw = 0.0; + double sd = 0.0; + double sd2 = 0.0; + int n = 0; + double wmax = -Double.MAX_VALUE; + double wmin = Double.MAX_VALUE; + int k = 0; + for (int i = -NPO2; i <= NPO2; i++) { + double v = pax[k++]; + if (v != AST__BAD) { + sdw += i * v; + sw += v; + sd += i; + sd2 += i * i; + n++; + if (v > wmax) { + wmax = v; + } + if (v < wmin) { + wmin = v; + } + } + } + double denom = sd2 * n - sd * sd; + if (n > NP / 4 && denom != 0.0) { + if (wmax > wmin) { + ret[j] = (sdw * n - sw * sd) / denom; + } else { + ret[j] = 0.0; + } + offset[j] = (sw * sd2 - sdw * sd) / denom; + } else { + return null; + } + } + + // The values the fit gives are put in the no longer needed first input row. + for (int j = 0; j < nout; j++) { + double[] pax = ptr1[0]; + int k = 0; + for (int i = -NPO2; i <= NPO2; i++) { + pax[k++] = i * ret[j] + offset[j]; + } + if (fitOK(NP, ptr2[j], ptr1[0], tol[j])) { + ret[j] /= gap; + } else { + return null; + } + } + return ret; + } + + /** + * C's {@code SplitMat}: factorises the CD matrix {@code matrix}, {@code naxis} by {@code + * naxis} in row order, into CDELT values and a PC matrix, so that each row of the PC matrix is + * a unit vector with a positive diagonal element; PC elements below 1e-7 in magnitude are + * set to zero. + * + * @param matrix the CD matrix, replaced by the PC matrix + * @param cdelt receives the CDELT values + * @return false if a bad value is found, the matrix and CDELT values then holding what the + * rows before it gave + */ + static boolean splitMat(int naxis, double[] matrix, double[] cdelt) { + boolean ok = true; + for (int i = 0; i < naxis; i++) { + int row = i * naxis; + boolean dineg = matrix[row + i] < 0.0; + double s2 = 0.0; + for (int j = 0; j < naxis; j++) { + double a = matrix[row + j]; + if (a == AST__BAD) { + ok = false; + break; + } + s2 += a * a; + } + if (!ok) { + break; + } + double cdlt = Math.sqrt(Math.max(0.0, s2)); + if (dineg) { + cdlt = -cdlt; + } + cdelt[i] = cdlt; + for (int j = 0; j < naxis; j++) { + if (cdlt != 0.0) { + matrix[row + j] /= cdlt; + if (Math.abs(matrix[row + j]) < 1.0e-7) { + matrix[row + j] = 0.0; + } + } else { + matrix[row + j] = 0.0; + } + } + } + return ok; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsWcsMatrix.java b/src/main/java/uk/ac/starlink/ast/FitsWcsMatrix.java index 585a817..879427c 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsWcsMatrix.java +++ b/src/main/java/uk/ac/starlink/ast/FitsWcsMatrix.java @@ -73,6 +73,40 @@ private static Mapping append(Mapping acc, Mapping next) { return acc == null ? next : new CmpMap(acc, next, true); } + /** + * C's {@code DistortMaps} notes the image dimensions NAXIS1 to NAXIS{@code naxes} with {@code + * astGetFitsF} (fitschan.c:9017-9021), which reports a card whose value does not convert to a + * floating value; an absent card gives no error. The extraction has stored the values; this + * makes the read fail where C's does. The current card is left as it was. + * + * @throws AstException with status {@code AST__FTCNV} for a NAXIS card whose value does not + * convert + */ + private static void checkImageDimensions(FitsCardList cards, int naxes) { + int icard = cards.getCard(); + try { + for (int i = 1; i <= naxes; i++) { + String key = "NAXIS" + i; + if (cards.searchCard(key, "astGetFitsF")) { + FitsCard c = cards.current(); + try { + if (FitsCardValue.cnvType(c.value, FitsCardValue.Want.FLOAT, 10, c.cName()) == null) { + throw Ast.err( + AstException.AST__FTCNV, + "astGetFitsF(FitsChan): Cannot convert FITS keyword '" + c.cName() + "' to " + + FitsCardValue.Want.FLOAT.cName() + "."); + } + } catch (AstException e) { + throw Ast.withContext( + e, "astGetFitsF(FitsChan): Cannot get value for FITS keyword '" + key + "'."); + } + } + } + } finally { + cards.setCard(icard); + } + } + /** * C's {@code DistortMaps} (fitschan.c:8915): the Mappings that apply the Paper IV distortion * codes of the CTYPE values, at the four points of the chain C's {@code WcsIntWorld} splices @@ -89,6 +123,7 @@ private static Mapping append(Mapping acc, Mapping next) { private static Mapping[] distortMaps( FitsStore store, FitsCardList cards, int naxes, FitsWarnings warnings, List cursors) { Mapping[] ret = new Mapping[4]; + checkImageDimensions(cards, naxes); // Spitzer distortion is applied to the translated pixel coordinates. if (store.hasSip()) { diff --git a/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java b/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java index 0a8fc6b..ea3a868 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java +++ b/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java @@ -4,10 +4,14 @@ import java.util.List; /** - * The FITS-WCS read of a FitsChan: the FrameSet its cards describe in the FITS-WCS encoding (C's - * {@code FitsToStore} and {@code FsetFromStore} for that encoding). + * The FITS-WCS read of a FitsChan: the FrameSet its cards describe in the FITS-WCS encoding, or in + * an encoding C reads as a variant of it, FITS-PC, FITS-IRAF, FITS-AIPS or FITS-AIPS++ (C's {@code + * FitsToStore} and {@code FsetFromStore} for those encodings); and the DSS read, whose one axis + * description {@link FitsEncDss#dssToStore} makes from the plate solution, made into a FrameSet in + * the same way. * - *

The read translates the header ({@code SpecTrans}), sweeps the WCS cards as C's {@code + *

The read translates the header ({@code SpecTrans}, whose translations depend on the + * encoding), sweeps the WCS cards as C's {@code * WcsFcRead} does, extracts every axis description into a {@link FitsStore} and makes from them a * FrameSet whose base Frame describes pixel coordinates and whose current Frame describes the * primary axis description, with a Frame for each alternate description. For each description the @@ -37,9 +41,9 @@ private FitsWcsRead() {} // ------------------------------------------------------------------ /** - * The FrameSet the cards of {@code fc} describe in the FITS-WCS encoding, or null when they - * describe none (C's {@code Read} for a foreign encoding, fitschan.c:26007, through {@code - * FitsToStore} and {@code FsetFromStore}). + * The FrameSet the cards of {@code fc} describe in {@code encoding}, FITS-WCS or a variant of it + * (FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++), or null when they describe none (C's {@code Read} for a foreign + * encoding, fitschan.c:26007, through {@code FitsToStore} and {@code FsetFromStore}). * *

The cards the read uses are marked as provisionally used, and the warnings it raises are * stored as {@code ASTWARN} cards. {@link FitsChan#read} then makes the marked cards used, or, @@ -49,15 +53,15 @@ private FitsWcsRead() {} * @throws UnsupportedOperationException if the header has a spectral axis, a {@code -TAB} axis * with TabOK above zero, or a non-spectral {@code -LOG} axis */ - static FrameSet read(FitsChan fc) { + static FrameSet read(FitsChan fc, FitsChan.Encoding encoding) { FitsCardList cards = fc.cards(); boolean defB1950 = fc.getDefB1950(); // SpecTrans works on a copy of the cards (C's temporary FitsChan), whose warnings are // stored on the FitsChan itself. int entry = cards.position(); FitsSpecTrans.TransWarnings transWarnings = new FitsSpecTrans.TransWarnings(); - FitsCardList trans = FitsSpecTrans.specTrans( - cards, FitsChan.Encoding.FITS_WCS, transAttrs(fc), transWarnings, fc.warnList(METHOD)); + FitsCardList trans = + FitsSpecTrans.specTrans(cards, encoding, transAttrs(fc), transWarnings, fc.warnList(METHOD)); // The cards SpecTrans used, which C marks before WcsFcRead runs. List specNames = trans.takeConsumedNames(); // C's WcsFcRead sweeps the cards before the FrameSet is made, and makes nothing when the @@ -77,6 +81,50 @@ static FrameSet read(FitsChan fc) { return finishForeignRead(fc, decoded, decodeError, swept, readWarnings, cursors, trans, specNames); } + /** + * The FrameSet the DSS plate solution in the cards of {@code fc} describes (C's {@code Read} + * for the DSS encoding, through {@code FitsToStore}, which calls {@code DSSToStore}, and + * {@code FsetFromStore}). {@link FitsEncDss#dssToStore} makes the axis description, marking + * each card it reads as provisionally used; the FrameSet is made from it as for a FITS-WCS + * header with that one description, and the warnings that raises are stored as {@code ASTWARN} + * cards. {@link FitsChan#read} then makes the marked cards used, or available again, as for the + * other encodings. + * + * @throws AstException as C's read reports it + */ + static FrameSet readDss(FitsChan fc) { + FitsCardList cards = fc.cards(); + FitsCard entry = cards.current(); + FitsStore store = FitsEncDss.dssToStore(fc, METHOD, fc.astClass()); + // C's DistortMaps reads the image dimensions from the FitsChan whatever the encoding. + for (int i = 0; i < store.naxis; i++) { + store.dims[i] = cards.getFloat("NAXIS" + (i + 1)); + } + store.sipReplace = fc.getSipReplace(); + store.carLin = fc.getCarLin(); + FitsWcsKeywords.WcsStores stores = + new FitsWcsKeywords.WcsStores(store.naxis, store, new ArrayList<>(), new ArrayList<>()); + FitsWarnings readWarnings = fc.warnList(METHOD); + List cursors = new ArrayList<>(); + FrameSet decoded; + try { + decoded = decodeWcsWithAltsInner( + stores, + fc.getDefB1950(), + fc.getIgnoreBadAlt() != 0, + fc.getIwc(), + cards, + fc.getTabOK(), + readWarnings, + cursors); + } catch (AstException e) { + pushReadWarnings(fc, readWarnings, cursors, entry); + throw e; + } + pushReadWarnings(fc, readWarnings, cursors, entry); + return decoded; + } + /** The attributes the header translations of a read depend on. */ private static FitsSpecTrans.TransAttrs transAttrs(FitsChan fc) { FitsSpecTrans.TransAttrs attrs = new FitsSpecTrans.TransAttrs(); @@ -186,7 +234,7 @@ private static FrameSet finishForeignRead( for (String name : extractNames) { cards.markAllCards(name); } - pushReadWarnings(fc, readWarnings, cursors); + pushReadWarnings(fc, readWarnings, cursors, null); if (decodeError != null) { throw decodeError; } @@ -242,10 +290,11 @@ private static void pushSweepWarnings(FitsChan fc, List warnings) { * Stores the {@code ASTWARN} blocks the decoding raised, each in front of the card current in * C when it was raised (see {@link #decodeWcsWithAltsInner} for {@code cursors}). C's {@code * DistortMaps} reads NAXIS1 to NAXIS{@code n} as each axis description is read, {@code n} its - * number of WCS axes, leaving the cursor {@link #moveCursorToLastNaxis} reproduces; a cursor - * of -1 is end-of-file. + * number of WCS axes, from the card {@code start} (null for end-of-file, where the sweep of a + * FITS-WCS read leaves the cursor), leaving the cursor {@link #moveCursorToLastNaxis} + * reproduces; a cursor of -1 is end-of-file. */ - private static void pushReadWarnings(FitsChan fc, FitsWarnings warnings, List cursors) { + private static void pushReadWarnings(FitsChan fc, FitsWarnings warnings, List cursors, FitsCard start) { if (fc.getClean()) { return; } @@ -263,7 +312,7 @@ private static void pushReadWarnings(FitsChan fc, FitsWarnings warnings, List= 0) { - moveCursorToLastNaxis(cards, cursor); + moveCursorToLastNaxis(cards, cursor, start); } else { cards.setPosition(cards.len()); } @@ -276,15 +325,17 @@ private static void pushReadWarnings(FitsChan fc, FitsWarnings warnings, ListEach description's cards are written in C's order: WCSAXES, WCSNAME, CRPIX, CRVAL, CTYPE, + * CNAME, the CD matrix or CDELT and the PC matrix, CUNIT, the AST extensions AXREF, SREFIS, SREF + * and SREFP, the date of observation (primary description only), the projection parameters, the + * celestial and spectral keywords, OBSGEO (primary only), and the SIP coefficients with their + * orders. Before each description and after it the current card is put after the last card + * describing WCS ({@link FitsCardList#positionWriteCursor}, C's {@code FindWcs}); the SIP + * coefficients are not such cards, so the next description's cards go in front of them. + * + *

Ported from fitschan.c {@code WcsFromStore}, the Rust port's {@code wcs_write/mod.rs} ({@code + * write_store_to_cards}) being organised differently. + */ +final class FitsWcsWrite { + + private FitsWcsWrite() {} + + /** + * C's {@code WcsFromStore}: writes the descriptions in {@code store} to {@code fc} as FITS-WCS + * cards, each in front of the current card, which is first put after the last card describing + * WCS. A description without CRPIX1 and CRVAL1, or lacking a CRPIX, CRVAL, CTYPE or (without + * CDMatrix) CDELT on one of its axes, is not written: the cards it added are removed. An error + * while writing an alternate description is dropped, and the description not written, as C + * clears it. Alternate descriptions are written only if the primary one is. + * + * @param fc the FitsChan written to + * @param store the descriptions + * @param method the calling method, for messages + * @param cls the class of the object written, for messages + * @return true if any description was written, which is when the primary one was + */ + static boolean wcsFromStore(FitsChan fc, FitsPlaneStores store, String method, String cls) { + FitsCardList cards = fc.cards(); + boolean ret = false; + + // The NAXIS value, or -1 if there is none. + Integer naxisCard = fc.getFitsI("NAXIS"); + int naxis = naxisCard != null ? naxisCard : -1; + + cards.positionWriteCursor(); + + // The primary description, then the alternates A to the last with a CRVAL. + char sup = store.maxCrvalVersion(); + char s = ' '; + while (s <= sup) { + boolean ok; + if (s == ' ') { + ok = writeVersion(fc, store.get(s), s, naxis); + } else { + // C clears the error status after an alternate description, which is then not + // written, so that the next can be. + try { + ok = writeVersion(fc, store.get(s), s, naxis); + } catch (AstException e) { + ok = false; + } + } + if (ok) { + ret = true; + } + + // The cards of a description not written are removed. + cards.fixNew(FitsCardList.NewScope.VERSION, !ok); + cards.positionWriteCursor(); + + if (s == ' ') { + // Alternate descriptions cannot stand on their own. + if (!ok) { + break; + } + s = 'A'; + } else { + s++; + } + } + return ret; + } + + /** + * The cards of one description, {@code s}, from the body of C's version loop: false, C's + * {@code ok = 0; goto next}, if the description is incomplete. + */ + private static boolean writeVersion(FitsChan fc, FitsStore st, char s, int naxis) { + // A description without CRPIX1 or CRVAL1 is not written. + if (st == null || at(st.crpix, 0) == null || at(st.crval, 0) == null) { + return false; + } + int rnd = fc.getFitsRounding(); + FitsCardList cards = fc.cards(); + + // WCSAXES, if the store has one or the number of axes differs from NAXIS. + int nwcs; + boolean writeWcsaxes; + if (st.wcsaxes != null) { + nwcs = st.wcsaxes; + writeWcsaxes = true; + } else { + nwcs = st.maxCrpixAxis() + 1; + writeWcsaxes = nwcs != 0 && nwcs != naxis; + } + if (writeWcsaxes) { + setInt(cards, key("WCSAXES", s), nwcs, "Number of WCS axes", rnd); + } + + // WCSNAME, not needed; for one axis, left out when C's Similar finds it like CTYPE1. + String cval = st.wcsname; + if (cval != null && nwcs == 1) { + String ctype = at(st.ctype, 0); + if (ctype != null && FitsCardList.similar(ctype, cval)) { + cval = null; + } + } + if (cval != null) { + setString(cards, key("WCSNAME", s), cval, "Reference name for the coord. frame", rnd); + } + + // The prefix of the numerical projection parameters, QV once an axis uses TPN. + String parprefix = "PV"; + + for (int i = 0; i < nwcs; i++) { + Double val = at(st.crpix, i); + if (val == null) { + return false; + } + setFloat(cards, axisKey("CRPIX", i + 1, s), val, "Reference pixel on axis " + (i + 1), rnd); + } + for (int i = 0; i < nwcs; i++) { + Double val = at(st.crval, i); + if (val == null) { + return false; + } + setFloat(cards, axisKey("CRVAL", i + 1, s), val, "Value at ref. pixel on axis " + (i + 1), rnd); + } + + // CTYPE: a TPN projection (an AST code) is written as TAN with its parameters as QV. + boolean[] tabaxis = new boolean[nwcs]; + for (int i = 0; i < nwcs; i++) { + String ctype = at(st.ctype, i); + if (ctype == null) { + return false; + } + String comm = at(st.ctypeCom, i); + if (comm == null) { + comm = "Type of co-ordinate on axis " + (i + 1); // codespell:ignore + } + int nc = ctype.length(); + int prj = nc > 4 ? FitsWcsCelestial.wcsPrjType(ctype.substring(nc - 4)) : WcsMap.AST__WCSBAD; + if (prj == WcsMap.AST__TPN) { + parprefix = "QV"; + ctype = ctype.substring(0, nc - 4) + "-TAN"; + } + tabaxis[i] = prj == WcsMap.AST__WCSBAD && ctype.length() >= 8 && ctype.startsWith("-TAB", 4); + setString(cards, axisKey("CTYPE", i + 1, s), ctype, comm, rnd); + } + + // CNAME, unless it is the CTYPE value or its comment. + for (int i = 0; i < nwcs; i++) { + String cname = at(st.cname, i); + if (cname != null) { + String comm = at(st.ctype, i); + if (comm == null || !comm.equals(cname)) { + comm = at(st.ctypeCom, i); + if (comm == null || !comm.equals(cname)) { + setString(cards, axisKey("CNAME", i + 1, s), cname, "Description of axis " + (i + 1), rnd); + } + } + } + } + + if (fc.getCDMatrix()) { + // The CD matrix: each row of the PC matrix times its CDELT; zero elements left out. + for (int i = 0; i < nwcs; i++) { + Double c = at(st.cdelt, i); + double cdl = c != null ? c : 1.0; + for (int j = 0; j < nwcs; j++) { + Double p = at(st.pc, i, j); + double val = p != null ? p : (i == j ? 1.0 : 0.0); + val *= cdl; + if (val != 0.0) { + setFloat(cards, matrixKey("CD", i + 1, j + 1, s), val, "Transformation matrix element", rnd); + } + } + } + } else { + for (int i = 0; i < nwcs; i++) { + Double val = at(st.cdelt, i); + if (val == null) { + return false; + } + setFloat(cards, axisKey("CDELT", i + 1, s), val, "Pixel size on axis " + (i + 1), rnd); + } + // The PC matrix, leaving out elements equal to the unit matrix's. + for (int i = 0; i < nwcs; i++) { + for (int j = 0; j < nwcs; j++) { + Double val = at(st.pc, i, j); + if (val != null && !MappingHelpers.astEqual(val, i == j ? 1.0 : 0.0)) { + setFloat(cards, matrixKey("PC", i + 1, j + 1, s), val, "Transformation matrix element", rnd); + } + } + } + } + + for (int i = 0; i < nwcs; i++) { + String cunit = at(st.cunit, i); + if (cunit != null) { + setString(cards, axisKey("CUNIT", i + 1, s), cunit, "Units for axis " + (i + 1), rnd); + } + } + + // AXREF, SREFIS, SREF and SREFP: AST extensions, the reference position of a -TAB axis + // with no inverse, and the SkyRefIs, SkyRef and SkyRefP of an offset SkyFrame. + for (int i = 0; i < nwcs; i++) { + Double val = at(st.axref, i); + if (val != null) { + setFloat(cards, axisKey("AXREF", i + 1, s), val, "Reference WCS value on axis " + (i + 1), rnd); + } + } + if (st.skyrefis != null) { + setString(cards, key("SREFIS", s), st.skyrefis, "Is SkyRef used as pole or origin?", rnd); + } + for (int i = 0; i < nwcs; i++) { + Double val = at(st.skyref, i); + if (val != null) { + setFloat(cards, axisKey("SREF", i + 1, s), val, "Sky reference position on axis " + (i + 1), rnd); + } + } + for (int i = 0; i < nwcs; i++) { + Double val = at(st.skyrefp, i); + if (val != null) { + setFloat( + cards, + axisKey("SREFP", i + 1, s), + val, + "Sky primary meridian position on axis " + (i + 1), + rnd); + } + } + + // The date of observation and its timescale, for the primary description only. No write + // stores an MJD-AVG, which C would write after DATE-OBS. + if (s == ' ') { + if (st.mjdobs != null) { + setFloat(cards, "MJD-OBS", st.mjdobs, "Modified Julian Date of observation", rnd); + setString(cards, "DATE-OBS", FitsDates.mjdToDateStr(st.mjdobs), "Date of observation", rnd); + } + if (st.timesys != null) { + setString(cards, "TIMESYS", st.timesys, "Timescale for MJD-OBS/MJD-AVG values", rnd); + } + } + + // Numerical projection parameters. The interpolation method of a -TAB axis, an AST + // extension in PVi_4, is written as QVi_4 when it is not zero, its default. + int maxm = st.maxPvM(); + for (int i = 0; i < nwcs; i++) { + for (int m = 0; m <= maxm; m++) { + Double val = at(st.pv, i, m); + if (val == null) { + continue; + } + if (m == 4 && tabaxis[i]) { + if (val != 0.0) { + setFloat(cards, matrixKey("QV", i + 1, m, s), val, "Use nearest neighbour interpolation", rnd); + } + } else { + setFloat(cards, matrixKey(parprefix, i + 1, m, s), val, "Projection parameter", rnd); + } + } + } + + // String projection parameters. + int maxms = maxPsM(st); + for (int i = 0; i < nwcs; i++) { + for (int m = 0; m <= maxms; m++) { + String val = at(st.ps, i, m); + if (val != null) { + setString(cards, matrixKey("PS", i + 1, m, s), val, "Projection parameter", rnd); + } + } + } + + // Celestial axes. + if (st.radesys != null) { + setString(cards, key("RADESYS", s), st.radesys, "Reference frame for RA/DEC values", rnd); + } + if (st.equinox != null) { + setFloat(cards, key("EQUINOX", s), st.equinox, "[yr] Epoch of reference equinox", rnd); + } + if (st.latpole != null) { + setFloat(cards, key("LATPOLE", s), st.latpole, "[deg] Latitude of native north pole", rnd); + } + if (st.lonpole != null) { + setFloat(cards, key("LONPOLE", s), st.lonpole, "[deg] Longitude of native north pole", rnd); + } + + // Spectral axes. + if (st.specsys != null) { + setString(cards, key("SPECSYS", s), st.specsys, "Standard of rest for spectral axis", rnd); + } + if (st.ssyssrc != null) { + setString(cards, key("SSYSSRC", s), st.ssyssrc, "Standard of rest for source redshift", rnd); + } + if (st.zsource != null) { + setFloat(cards, key("ZSOURCE", s), st.zsource, "[] Redshift of source", rnd); + } + if (st.velosys != null) { + setFloat(cards, key("VELOSYS", s), st.velosys, "[m/s] Topo. apparent velocity of rest frame", rnd); + } + if (st.restfrq != null) { + setFloat(cards, key("RESTFRQ", s), st.restfrq, "[Hz] Rest frequency", rnd); + } + if (st.restwav != null) { + setFloat(cards, key("RESTWAV", s), st.restwav, "[m] Rest wavelength", rnd); + } + // IMAGFREQ, an extension for double sideband data, has no version letter. + if (st.imagfreq != null) { + setFloat(cards, "IMAGFREQ", st.imagfreq, "[Hz] Image frequency", rnd); + } + + // The observer's position, for the primary description only. + if (s == ' ') { + if (st.obsgeox != null) { + setFloat(cards, "OBSGEO-X", st.obsgeox, "[m] Observatory geocentric X", rnd); + } + if (st.obsgeoy != null) { + setFloat(cards, "OBSGEO-Y", st.obsgeoy, "[m] Observatory geocentric Y", rnd); + } + if (st.obsgeoz != null) { + setFloat(cards, "OBSGEO-Z", st.obsgeoz, "[m] Observatory geocentric Z", rnd); + } + } + + // The SIP coefficients, forward then inverse, each table followed by its order. The + // coefficients carry the version letter but the order keywords do not (C-library quirk, + // kept). + writeSip(cards, st.sipA, "A_", "A_ORDER", s, "SIP forward distortion coeff", "SIP max order", rnd); + writeSip(cards, st.sipB, "B_", "B_ORDER", s, "SIP forward distortion coeff", "SIP max order", rnd); + writeSip(cards, st.sipAp, "AP_", "AP_ORDER", s, "SIP inverse distortion coeff", "SIP inverse max order", rnd); + writeSip(cards, st.sipBp, "BP_", "BP_ORDER", s, "SIP inverse distortion coeff", "SIP inverse max order", rnd); + return true; + } + + /** + * One table of SIP coefficients: a card {@code

_} for each coefficient set, in + * order of the power {@code p} and then {@code q}, and, if the highest {@code p + q} is above + * zero, the order keyword with it. + */ + private static void writeSip( + FitsCardList cards, + double[][] item, + String prefix, + String orderKwd, + char s, + String comment, + String orderComment, + int rnd) { + int order = 0; + for (int p = 0; p < item.length; p++) { + for (int q = 0; q < item[p].length; q++) { + double val = item[p][q]; + if (val != AstObject.AST__BAD) { + setFloat(cards, matrixKey(prefix, p, q, s), val, comment, rnd); + if (p + q > order) { + order = p + q; + } + } + } + } + if (order > 0) { + setInt(cards, orderKwd, order, orderComment, rnd); + } + } + + /** C's {@code GetMaxJMC( &(store->ps) )}: the highest PS parameter index stored, or -1. */ + private static int maxPsM(FitsStore st) { + int max = -1; + for (String[] axis : st.ps) { + for (int m = axis.length - 1; m > max; m--) { + if (axis[m] != null) { + max = m; + break; + } + } + } + return max; + } + + /** C's {@code FormatKey( name, -1, -1, s )}: {@code name} and the version letter. */ + private static String key(String name, char s) { + return s == ' ' ? name : name + s; + } + + /** C's {@code FormatKey( name, i, -1, s )}. */ + private static String axisKey(String name, int i, char s) { + return key(name + i, s); + } + + /** C's {@code FormatKey( name, i, j, s )}. */ + private static String matrixKey(String name, int i, int j, char s) { + return key(name + i + "_" + j, s); + } + + /** Element {@code i} of {@code a}, null (C's unset item) beyond its end. */ + private static T at(T[] a, int i) { + return i < a.length ? a[i] : null; + } + + /** Element {@code [i][j]} of {@code a}, null beyond its ends. */ + private static T at(T[][] a, int i, int j) { + return i < a.length && j < a[i].length ? a[i][j] : null; + } + + private static void setFloat(FitsCardList cards, String keyword, double value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofFloat(value), comment, rnd); + } + + private static void setString(FitsCardList cards, String keyword, String value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofString(value), comment, rnd); + } + + private static void setInt(FitsCardList cards, String keyword, int value, String comment, int rnd) { + cards.setValueAsWriter(keyword, FitsCard.Value.ofInt(value), comment, rnd); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsWorldAxes.java b/src/main/java/uk/ac/starlink/ast/FitsWorldAxes.java new file mode 100644 index 0000000..3147cc4 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsWorldAxes.java @@ -0,0 +1,263 @@ +package uk.ac.starlink.ast; + +/** + * C's {@code WorldAxes} (fitschan.c): the pixel axis associated with each world axis of a pixel to + * world Mapping, the one most nearly parallel to it. + * + *

Ported from Rust {@code fitschan/fset_to_store/world_axes.rs}, following fitschan.c. + */ +final class FitsWorldAxes { + + private static final double AST__BAD = AstObject.AST__BAD; + + private FitsWorldAxes() {} + + /** + * Finds the pixel axis associated with each output of {@code cmap}. For a Mapping defined in + * both directions, a small step along each world axis from a position with good world + * coordinates is transformed back to pixel coordinates, and pixel axes are assigned to world + * axes in order of the smallest angle between them, ties going to the longest projection; + * world axes left over take the unused pixel axes in turn, numbering past the pixel axes when + * they run out. A Mapping with only a forward transformation is analysed when the FitsChan's + * TabOK is positive: each output takes the input that alone feeds it, and an input feeding + * several outputs keeps one (the output of the same index if it is one of them, else the + * first), the others taking unused inputs. + * + * @param fc the FitsChan, whose TabOK attribute is used + * @param cmap the pixel to world Mapping, which is simplified + * @param dim the number of pixels along each pixel axis, {@code AST__BAD} where unknown + * @param perm receives, for each output, the zero-based index of the associated pixel axis + * @return whether the axes were associated + */ + static boolean worldAxes(FitsChan fc, Mapping cmap, double[] dim, int[] perm) { + boolean ret = false; + Mapping map = cmap.simplify(); + int nin = map.getNin(); + int nout = map.getNout(); + for (int i = 0; i < nout; i++) { + perm[i] = i; + } + + if (map.getTranForward() && map.getTranInverse()) { + double[][] ptrg = new double[nin][nin + 1]; + double[][] ptrw = new double[nout][nin + 1]; + if (!FitsWcsDecompose.findBasisVectors(map, nin, nout, dim, ptrg, ptrw)) { + return ret; + } + double[] g0 = new double[nin]; + for (int j = 0; j < nin; j++) { + g0[j] = ptrg[j][0]; + } + + // The root position and a position 1 pixel away along every pixel axis, in world + // coordinates, and a small increment along each world axis. + double[][] ptr1 = new double[nin][2]; + for (int j = 0; j < nin; j++) { + ptr1[j][0] = g0[j]; + ptr1[j][1] = g0[j] + 1.0; + } + double[][] ptr2 = map.transform(ptr1, 2, true); + double[] w0 = new double[nout]; + double[] dw = new double[nout]; + for (int i = 0; i < nout; i++) { + w0[i] = ptr2[i][0]; + if (w0[i] != AST__BAD && ptr2[i][1] != AST__BAD) { + dw[i] = Math.abs(0.1 * (ptr2[i][1] - w0[i])); + if (dw[i] <= Math.abs(0.001 * w0[i])) { + if (w0[i] != 0.0) { + dw[i] = Math.abs(0.001 * w0[i]); + } else { + dw[i] = 1.0; + } + } + } else { + dw[i] = AST__BAD; + } + } + + // The inverse transformation need not be a true inverse (constants fed to degenerate + // axes by a PermMap), so the root position is the world position transformed back. + ptr1 = map.transform(ptr2, 2, false); + for (int j = 0; j < nin; j++) { + g0[j] = ptr1[j][0]; + } + + // The tan of the angle between each world axis and each pixel axis, and the length of + // the projection onto the pixel axis. + double[] tn = new double[nout * nin]; + double[] wt = new double[nout * nin]; + for (int i = 0; i < nout; i++) { + int ntn = i * nin; + for (int j = 0; j < nin; j++) { + tn[ntn + j] = AST__BAD; + } + perm[i] = -1; + if (dw[i] != AST__BAD) { + ptr2[i][0] += dw[i]; + ptr1 = map.transform(ptr2, 2, false); + ptr2[i][0] = w0[i]; + for (int j = 0; j < nin; j++) { + double s = 0.0; + double sj = 0.0; + for (int j2 = 0; j2 < nin; j2++) { + if (ptr1[j2][0] != AST__BAD) { + double dg = ptr1[j2][0] - g0[j2]; + if (j2 != j) { + s += dg * dg; + } else { + sj = Math.abs(dg); + } + } else { + s = AST__BAD; + break; + } + } + if (s != AST__BAD && sj != 0.0) { + tn[ntn + j] = Math.sqrt(s) / sj; + wt[ntn + j] = sj; + } + } + } + } + + // Assign pixel axes to world axes, smallest tan first, equal tans going to the + // highest weight, until no tan is left. + while (true) { + double tnmin = AST__BAD; + double wtmax = AST__BAD; + int imin = 0; + int jmin = 0; + int k = 0; + for (int i = 0; i < nout; i++) { + for (int j = 0; j < nin; j++) { + if (tn[k] != AST__BAD) { + if (tnmin == AST__BAD || tn[k] < tnmin) { + tnmin = tn[k]; + wtmax = wt[k]; + imin = i; + jmin = j; + } else if (MappingHelpers.astEqual(tn[k], tnmin) && wt[k] > wtmax) { + wtmax = wt[k]; + imin = i; + jmin = j; + } + } + k++; + } + } + if (tnmin == AST__BAD) { + break; + } + perm[imin] = jmin; + k = 0; + for (int i = 0; i < nout; i++) { + for (int j = 0; j < nin; j++) { + if (i == imin || j == jmin) { + tn[k] = AST__BAD; + } + k++; + } + } + } + + // World axes with no pixel axis take the unused pixel axes, lowest first. + int j; + for (j = 0; j < nin; j++) { + if (!isUsed(perm, nout, j)) { + break; + } + } + for (int i = 0; i < nout; i++) { + if (perm[i] == -1) { + perm[i] = j++; + for (; j < nin; j++) { + if (!isUsed(perm, nout, j)) { + break; + } + } + } + } + ret = true; + + } else if (map.getTranForward() && fc.getTabOK() > 0) { + ret = true; + for (int i = 0; i < nout; i++) { + perm[i] = -1; + } + + // The output associated with each input. + for (int j = 0; j < nin; j++) { + MapSplit split = map.mapSplit(new int[] {j}); + if (split != null) { + int nouts = split.map.getNout(); + for (int i = 0; i < nouts; i++) { + if (perm[split.outputs[i]] == -1) { + perm[split.outputs[i]] = j; + } else { + ret = false; + } + } + } + } + for (int i = 0; i < nout && ret; i++) { + if (perm[i] == -1) { + ret = false; + } + } + + // An input feeding several outputs keeps the output of the same index if that is one + // of them, else the first; the others take the next unused input. C reads perm[j] + // for every input, past the end of the array when there are more inputs than + // outputs; such an input has no output of the same index. + if (ret) { + for (int j = 0; j < nin; j++) { + int nused = 0; + for (int i = 0; i < nout; i++) { + if (perm[i] == j) { + nused++; + } + } + if (nused > 1) { + int retain = 0; + if (j < nout && perm[j] == j) { + retain = j; + } else { + for (int i = 0; i < nout; i++) { + if (perm[i] == j) { + retain = i; + break; + } + } + } + for (int i = 0; i < nout && ret; i++) { + if (perm[i] == j && i != retain) { + boolean used = true; + for (int j2 = 0; j2 < nin; j2++) { + used = isUsed(perm, nout, j2); + if (!used) { + perm[i] = j2; + break; + } + } + if (used) { + ret = false; + } + } + } + } + } + } + } + return ret; + } + + /** Whether pixel axis {@code j} is assigned to one of the {@code nout} world axes. */ + private static boolean isUsed(int[] perm, int nout, int j) { + for (int i = 0; i < nout; i++) { + if (perm[i] == j) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/PolyMap.java b/src/main/java/uk/ac/starlink/ast/PolyMap.java index 0d0c621..562573d 100644 --- a/src/main/java/uk/ac/starlink/ast/PolyMap.java +++ b/src/main/java/uk/ac/starlink/ast/PolyMap.java @@ -1,6 +1,8 @@ package uk.ac.starlink.ast; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import uk.ac.starlink.ast.internal.pal.Pal; /** @@ -537,6 +539,194 @@ final boolean hasCoeffs(boolean forward) { return out; } + /** + * C's protected {@code astMergeShift} (polymap.c {@code MergeShift}): a new PolyMap equivalent + * to {@code shift} and this PolyMap applied in series, the ShiftMap first if {@code before} and + * last otherwise. If {@code force} is true the constant terms of the new PolyMap are made zero. + * The new PolyMap is simplified, which amalgamates the coefficients of each output that refer + * to the same powers and removes zero coefficients; it is inverted if this PolyMap is. While + * the coefficients are merged this PolyMap's Invert attribute is cleared and {@code shift} is + * inverted, as C does; both are restored afterwards. + * + * @throws AstException with status {@code AST__INTER} if {@code shift} has the wrong number of + * inputs, or the simplified result is not a PolyMap + */ + PolyMap mergeShift(ShiftMap shift, boolean before, boolean force) { + boolean inverted = getInvert(); + boolean bef = before; + if (inverted) { + clearInvert(); + shift.invert(); + bef = !bef; + } + try { + int nin = getNin(); + int nout = getNout(); + int nshift = bef ? nin : nout; + if (shift.getNin() != nshift) { + throw Ast.err( + AstException.AST__INTER, + "astMergeShift(" + astClass() + "): Supplied ShiftMap has incorrect number of inputs - " + + nshift + " are required (internal AST programming error)."); + } + double[] shifts = shift.getShifts(); + + // A copy whose coefficients are replaced, so any record that it is simple, its linear + // truncation and its Jacobian no longer apply. + PolyMap result = (PolyMap) copy(); + result.clearIsSimple(); + result.lintrunc = null; + result.jacobian = null; + + result.setForward(mergeShifts(nin, nout, force, ncoeffF, coeffF, powerF, mxpowF, shifts, bef)); + + // The inverse of the series is the inverse of the PolyMap and the negated shifts, in + // the other order. + if (ncoeffI != null) { + for (int iin = 0; iin < nshift; iin++) { + shifts[iin] = -shifts[iin]; + } + result.setInverse(mergeShifts(nout, nin, force, ncoeffI, coeffI, powerI, mxpowI, shifts, !bef)); + } + + Mapping tmap = result.simplify(); + if (!(tmap instanceof PolyMap)) { + throw Ast.err( + AstException.AST__INTER, + "astMergeShift(" + astClass() + "): Result is a " + tmap.astClass() + + " - expected a PolyMap (internal AST programming error)."); + } + PolyMap merged = (PolyMap) tmap; + if (inverted) { + merged.invert(); + } + return merged; + } finally { + if (inverted) { + setInvert(true); + shift.invert(); + } + } + } + + /** + * C's {@code MergeShifts} (polymap.c): the coefficient arrays of a polynomial transformation + * of {@code nin} inputs and {@code nout} outputs equivalent to the one given and the shifts + * {@code shifts} applied in series, added to the inputs first if {@code before}, else to the + * outputs afterwards. Shifts added afterwards go into the first constant term of each output, + * or a new constant term appended to it. Shifts added first expand each term with {@link + * #expandTerm}, the terms of the expansion being appended in order. If {@code force} is true + * the constant terms are then set to zero, and left in the arrays. The maximum powers start as + * those given. + */ + private static Coeffs mergeShifts( + int nin, + int nout, + boolean force, + int[] ncoeff, + double[][] coeff, + int[][][] power, + int[] mxpow, + double[] shifts, + boolean before) { + Coeffs c = new Coeffs(nout, nin); + System.arraycopy(mxpow, 0, c.mxpow, 0, nin); + if (before) { + List ks = new ArrayList<>(); + List qs = new ArrayList<>(); + for (int iout = 0; iout < nout; iout++) { + for (int ico = 0; ico < ncoeff[iout]; ico++) { + ks.clear(); + qs.clear(); + expandTerm(nin, coeff[iout][ico], power[iout][ico].clone(), shifts, ks, qs); + for (int iexp = 0; iexp < ks.size(); iexp++) { + addCoeff(iout, ks.get(iexp), qs.get(iexp), c.nco, c.cof, c.pow, c.mxpow); + } + } + } + } else { + for (int iout = 0; iout < nout; iout++) { + c.nco[iout] = ncoeff[iout]; + c.cof[iout] = coeff[iout].clone(); + c.pow[iout] = new int[ncoeff[iout]][]; + for (int ico = 0; ico < ncoeff[iout]; ico++) { + c.pow[iout][ico] = power[iout][ico].clone(); + } + } + for (int iout = 0; iout < nout; iout++) { + boolean shiftAdded = false; + for (int ico = 0; ico < c.nco[iout]; ico++) { + if (isConstant(c.pow[iout][ico])) { + c.cof[iout][ico] += shifts[iout]; + shiftAdded = true; + break; + } + } + if (!shiftAdded) { + addCoeff(iout, shifts[iout], new int[nin], c.nco, c.cof, c.pow, c.mxpow); + } + } + } + if (force) { + for (int iout = 0; iout < nout; iout++) { + for (int ico = 0; ico < c.nco[iout]; ico++) { + if (isConstant(c.pow[iout][ico])) { + c.cof[iout][ico] = 0.0; + } + } + } + } + return c; + } + + /** Whether every power of a term is zero. */ + private static boolean isConstant(int[] pows) { + for (int pow : pows) { + if (pow != 0) { + return false; + } + } + return true; + } + + /** + * C's {@code ExpandTerm} (polymap.c): appends to {@code ks} and {@code qs} the coefficients and + * powers of the expansion of {@code c * (x0 + s0)^p0 * (x1 + s1)^p1 * ...} in powers of the + * unshifted inputs. The first input {@code i} with a non-zero power is factored out once: each + * term {@code k * x^q} of the expansion of the reduced term gives {@code k * x^q * xi} and then + * {@code k * si * x^q}, in that order. Terms with the same powers are not combined. {@code p} + * is changed while the expansion is made and restored afterwards. + */ + private static void expandTerm(int nin, double c, int[] p, double[] s, List ks, List qs) { + int i = -1; + for (int iin = 0; iin < nin; iin++) { + if (p[iin] > 0) { + i = iin; + break; + } + } + if (i == -1) { + ks.add(c); + qs.add(new int[nin]); + return; + } + p[i] -= 1; + List ks1 = new ArrayList<>(); + List qs1 = new ArrayList<>(); + expandTerm(nin, c, p, s, ks1, qs1); + p[i] += 1; + for (int ico = 0; ico < ks1.size(); ico++) { + double k = ks1.get(ico); + int[] q = qs1.get(ico); + q[i] += 1; + ks.add(k); + qs.add(q.clone()); + q[i] -= 1; + ks.add(k * s[i]); + qs.add(q.clone()); + } + } + // ------------------------------------------------------------------ // Definedness // ------------------------------------------------------------------ diff --git a/src/main/java/uk/ac/starlink/ast/ScalePolyInputs.java b/src/main/java/uk/ac/starlink/ast/ScalePolyInputs.java new file mode 100644 index 0000000..26588aa --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/ScalePolyInputs.java @@ -0,0 +1,88 @@ +package uk.ac.starlink.ast; + +/** + * C's {@code ScalePolyInputs} (fitschan.c): a PolyMap that scales each of its inputs before + * applying a supplied PolyMap. + * + *

Ported from Rust {@code mappings/helpers/scale_poly_inputs.rs}, following fitschan.c. + */ +final class ScalePolyInputs { + + private ScalePolyInputs() {} + + /** + * A new PolyMap equivalent to {@code polymap} applied after each input {@code i} is multiplied + * by {@code scales[i]}. Each coefficient of the forward transformation is multiplied by each + * scale raised to the power of its input in the term; each coefficient of any inverse + * transformation is multiplied by the reciprocal of the scale of the input it gives. An + * inverted PolyMap gives a PolyMap made uninverted and then inverted. The IterInverse, + * NiterInverse and TolInverse values set on {@code polymap} are set on the new PolyMap. + * + * @param polymap the PolyMap, which is not changed + * @param scales the scale of each input of {@code polymap} + * @return the new PolyMap + * @throws AstException with status {@code AST__INTER} if a scale is zero or bad + */ + static PolyMap scalePolyInputs(PolyMap polymap, double[] scales) { + int nin = polymap.getNin(); + int nout = polymap.getNout(); + + for (int iin = 0; iin < nin; iin++) { + if (scales[iin] == 0.0 || scales[iin] == AstObject.AST__BAD) { + throw Ast.err( + AstException.AST__INTER, + "ScalePolyInputs(fitschan): AST internal programming error - Scale factor for input " + iin + + " is zero or bad."); + } + } + + // Each forward coefficient, (value, output, nin powers), times the product of the scales + // raised to their powers. + double[] coeffsF = polymap.polyCoeffs(true); + int ncoeffF = coeffsF.length / (nin + 2); + for (int ico = 0; ico < ncoeffF; ico++) { + int pv = ico * (nin + 2); + double cof = coeffsF[pv]; + for (int iin = 0; iin < nin; iin++) { + cof *= Math.pow(scales[iin], coeffsF[pv + 2 + iin]); + } + coeffsF[pv] = cof; + } + + // Each inverse coefficient, (value, input, nout powers), times the reciprocal of the scale + // of the input it gives. + double[] coeffsI = polymap.polyCoeffs(false); + int ncoeffI = coeffsI.length / (nout + 2); + for (int ico = 0; ico < ncoeffI; ico++) { + int pv = ico * (nout + 2); + int iin = (int) coeffsI[pv + 1] - 1; + coeffsI[pv] *= 1.0 / scales[iin]; + } + + PolyMap result; + if (polymap.getInvert()) { + result = new PolyMap(nout, nin, ncoeffI, coeffsI, ncoeffF, coeffsF); + result.invert(); + } else { + result = new PolyMap(nin, nout, ncoeffF, coeffsF, ncoeffI, coeffsI); + } + copyIterInverse(polymap, result); + return result; + } + + /** + * Sets on {@code to} each of the IterInverse, NiterInverse and TolInverse attributes that is + * set on {@code from}, as C's {@code ScalePolyInputs} and {@code AnalysePoly} do. + */ + static void copyIterInverse(PolyMap from, PolyMap to) { + if (from.testIterInverse()) { + to.setIterInverse(from.getIterInverse()); + } + if (from.testNiterInverse()) { + to.setNiterInverse(from.getNiterInverse()); + } + if (from.testTolInverse()) { + to.setTolInverse(from.getTolInverse()); + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/WcsMap.java b/src/main/java/uk/ac/starlink/ast/WcsMap.java index f79295a..7a29d95 100644 --- a/src/main/java/uk/ac/starlink/ast/WcsMap.java +++ b/src/main/java/uk/ac/starlink/ast/WcsMap.java @@ -489,6 +489,49 @@ final double natLon() { return 0.0; } + /** + * C's {@code IsZenithal} (wcsmap.c): whether the projection is zenithal. TAN, STG, ARC, ZPN, + * ZEA, AIR and TPN always are; AZP is when parameter 2 of the latitude axis is unset or zero; + * SIN when parameters 1 and 2 of the latitude axis are both unset or zero; and SZP when + * parameter 2 of the latitude axis, defaulting to 90, is +/-90. C tests parameter 2 of SZP, + * whose default is 0, where the point of projection is given by parameter 3, so a default SZP + * projection is not zenithal; this C quirk is kept. + */ + final boolean isZenithal() { + int type = getWcsType(); + int latax = axes[1]; + boolean ret = false; + if (type == AST__TAN + || type == AST__STG + || type == AST__ARC + || type == AST__ZPN + || type == AST__ZEA + || type == AST__AIR + || type == AST__TPN) { + ret = true; + } else if (type == AST__AZP) { + double p2 = getPV(latax, 2); + ret = p2 == AST__BAD || p2 == 0.0; + } else if (type == AST__SIN) { + double p1 = getPV(latax, 1); + double p2 = getPV(latax, 2); + if (p1 == AST__BAD) { + p1 = 0.0; + } + if (p2 == AST__BAD) { + p2 = 0.0; + } + ret = p1 == 0.0 && p2 == 0.0; + } else if (type == AST__SZP) { + double p3 = getPV(latax, 2); + if (p3 == AST__BAD) { + p3 = 90.0; + } + ret = p3 == 90.0 || p3 == -90.0; + } + return ret; + } + /** * Gets the attribute named {@code PVi_m}, as jniast's generated accessor does. No attribute * has that name ({@code i} and {@code m} must be numbers), so this always fails; read a diff --git a/src/test/java/uk/ac/starlink/ast/AnalysePolyTest.java b/src/test/java/uk/ac/starlink/ast/AnalysePolyTest.java new file mode 100644 index 0000000..5fb4e13 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/AnalysePolyTest.java @@ -0,0 +1,175 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static uk.ac.starlink.ast.PolyTerms.flat; +import static uk.ac.starlink.ast.PolyTerms.term; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code mappings/helpers/analyse_poly.rs} (C {@code + * AnalysePoly}, fitschan.c, and the {@code astMergeShift} it uses, polymap.c). The expected values + * were captured from C by the Rust repository's {@code tools/oracle_fixtures/analyse_poly.c}, which + * gives the coefficients of the middle PolyMap in the order {@code astPolyCoeffs} returns them. + */ +class AnalysePolyTest { + + /** A 2-input, 2-output PolyMap with IterInverse set, from coefficients in C's layout. */ + private static PolyMap polyWithIterInverse(double... coeffs) { + PolyMap pm = new PolyMap(2, 2, coeffs.length / 4, coeffs, 0, null); + pm.setIterInverse(true); + return pm; + } + + /** The shift a ShiftMap applies, from transforming the origin as the C oracle does. */ + private static double[] shift(Mapping map1) { + double[][] out = map1.tran2(1, new double[] {0.0}, new double[] {0.0}, true); + return new double[] {out[0][0], out[1][0]}; + } + + /** The matrix (a, b, c, d) of a MatrixMap, from transforming unit vectors as the C oracle does. */ + private static double[] matrix(Mapping map3) { + double[][] out = map3.tran2(3, new double[] {0.0, 1.0, 0.0}, new double[] {0.0, 0.0, 1.0}, true); + return new double[] {out[0][1], out[0][2], out[1][1], out[1][2]}; + } + + private static Mapping[] analyse(PolyMap pm) { + Mapping[] maps = new Mapping[3]; + assertTrue(AnalysePoly.analysePoly(pm, maps)); + return maps; + } + + /** C's ANALYSE_POLY_SIP_SHAPE fixture: no shift, no linear part beyond the unit matrix. */ + @Test + void sipShapePolyMap() { + PolyMap pm = polyWithIterInverse(1.0, 1, 1, 0, 0.001, 1, 1, 1, 1.0, 2, 0, 1, 0.002, 2, 2, 0); + Mapping[] maps = analyse(pm); + assertArrayEquals(new double[] {0.0, 0.0}, shift(maps[0])); + assertInstanceOf(UnitMap.class, maps[2]); + assertArrayEquals( + new double[] {1.0, 1, 1, 0, 0.001, 1, 1, 1, 1.0, 2, 0, 1, 0.002, 2, 2, 0}, + ((PolyMap) maps[1]).polyCoeffs(true)); + } + + /** + * C's ANALYSE_POLY_WITH_CONSTANT fixture: the constant terms are taken out as a shift found + * with the iterative inverse, and the linear terms the shift leaves as a matrix. + */ + @Test + void polyMapWithConstantsExtractsShift() { + PolyMap pm = + polyWithIterInverse(5.0, 1, 0, 0, 1.0, 1, 1, 0, 1.0, 1, 1, 1, 7.0, 2, 0, 0, 1.0, 2, 0, 1, 1.0, 2, 2, 0); + Mapping[] maps = analyse(pm); + double[] shift = shift(maps[0]); + assertEquals(-3.712254771232298, shift[0]); + assertEquals(6.496117295794907, shift[1]); + assertInstanceOf(MatrixMap.class, maps[2]); + double[] mat = matrix(maps[2]); + assertArrayEquals(new double[] {-5.496117295794907, 3.712254771232298, 7.424509542464596, 1.0}, mat); + double[] coeffs = ((PolyMap) maps[1]).polyCoeffs(true); + double[] wantCoeffs = flat( + term(1.0, 1, 1, 0), + term(-0.030250057622327978, 1, 1, 1), + term(0.11229592073853897, 1, 2, 0), + term(1.0, 2, 0, 1), + term(0.22459184147707795, 2, 1, 1), + term(0.16625786489686933, 2, 2, 0)); + assertArrayEquals(wantCoeffs, coeffs); + } + + /** C's ANALYSE_POLY_ROTATION_SCALE fixture: a linear part with rotation and scaling. */ + @Test + void polyMapWithLinearExtractsMatrix() { + PolyMap pm = polyWithIterInverse( + 2.0, 1, 1, 0, 3.0, 1, 0, 1, 0.01, 1, 1, 1, -1.0, 2, 1, 0, 4.0, 2, 0, 1, 0.02, 2, 2, 0); + Mapping[] maps = analyse(pm); + double[] shift = shift(maps[0]); + assertEquals(0.0, shift[0]); + assertEquals(0.0, shift[1]); + assertInstanceOf(MatrixMap.class, maps[2]); + assertArrayEquals(new double[] {2.0, 3.0, -1.0, 4.0}, matrix(maps[2])); + double[] coeffs = ((PolyMap) maps[1]).polyCoeffs(true); + double[] wantCoeffs = flat( + term(1.0, 1, 1, 0), + term(0.0036363636363636364, 1, 1, 1), + term(-0.005454545454545454, 1, 2, 0), + term(1.0, 2, 0, 1), + term(0.0009090909090909091, 2, 1, 1), + term(0.0036363636363636364, 2, 2, 0)); + assertArrayEquals(wantCoeffs, coeffs); + } + + /** C's ANALYSE_POLY_SINGULAR fixture: a singular linear part cannot be analysed. */ + @Test + void singularReturnsFalse() { + PolyMap pm = polyWithIterInverse( + 1.0, 1, 1, 0, 1.0, 1, 0, 1, 0.01, 1, 2, 0, 1.0, 2, 1, 0, 1.0, 2, 0, 1, 0.01, 2, 2, 0); + Mapping[] maps = new Mapping[3]; + assertFalse(AnalysePoly.analysePoly(pm, maps)); + assertNull(maps[0]); + assertNull(maps[1]); + assertNull(maps[2]); + } + + /** A PolyMap whose inverse is not iterative is not analysed (fitschan.c AnalysePoly). */ + @Test + void noIterInverseReturnsFalse() { + PolyMap pm = new PolyMap(2, 2, 3, new double[] {1.0, 1, 1, 0, 1.0, 2, 0, 1, 0.001, 1, 1, 1}, 0, null); + pm.setIterInverse(false); + Mapping[] maps = new Mapping[3]; + assertFalse(AnalysePoly.analysePoly(pm, maps)); + assertNull(maps[1]); + } + + /** The supplied PolyMap's Invert attribute is cleared while it is analysed, then set again. */ + @Test + void invertedPolyMapIsRestored() { + PolyMap pm = polyWithIterInverse(1.0, 1, 1, 0, 0.001, 1, 1, 1, 1.0, 2, 0, 1, 0.002, 2, 2, 0); + pm.invert(); + analyse(pm); + assertTrue(pm.getInvert()); + } + + /** + * {@code astMergeShift} with zero shifts applied first and {@code force} set keeps every term + * but the constant, which it sets to zero and the simplification then drops (polymap.c + * MergeShift). + */ + @Test + void mergeShiftZeroDropsConstants() { + PolyMap pm = new PolyMap(2, 2, 3, new double[] {1.0, 1, 2, 1, 2.0, 1, 0, 0, 3.0, 2, 0, 1}, 0, null); + PolyMap merged = pm.mergeShift(new ShiftMap(new double[] {0.0, 0.0}), true, true); + assertArrayEquals(new double[] {1.0, 1, 2, 1, 3.0, 2, 0, 1}, merged.polyCoeffs(true)); + } + + /** + * {@code astMergeShift} with a shift applied first expands each term about the shifted inputs: + * {@code (x0 + 2)^2} is {@code x0^2 + 4*x0 + 4}, the terms coming in the order C's {@code + * ExpandTerm} gives them. + */ + @Test + void mergeShiftExpandsAShiftedTerm() { + PolyMap pm = new PolyMap(1, 1, 1, new double[] {1.0, 1, 2}, 0, null); + PolyMap merged = pm.mergeShift(new ShiftMap(new double[] {2.0}), true, false); + assertArrayEquals(new double[] {1.0, 1, 2, 4.0, 1, 1, 4.0, 1, 0}, merged.polyCoeffs(true)); + } + + /** + * {@code astMergeShift} with a shift applied after the PolyMap adds it to the first constant + * term of each output, or appends a constant term to an output without one. + */ + @Test + void mergeShiftAfterAddsToTheConstants() { + PolyMap pm = + new PolyMap(2, 2, 4, new double[] {1.0, 1, 1, 0, 5.0, 1, 0, 0, 1.0, 2, 0, 1, 0.5, 2, 2, 0}, 0, null); + PolyMap merged = pm.mergeShift(new ShiftMap(new double[] {1.0, 2.0}), false, false); + assertArrayEquals( + new double[] {1.0, 1, 1, 0, 6.0, 1, 0, 0, 1.0, 2, 0, 1, 0.5, 2, 2, 0, 2.0, 2, 0, 0}, + merged.polyCoeffs(true)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsCelestialAxesTest.java b/src/test/java/uk/ac/starlink/ast/FitsCelestialAxesTest.java new file mode 100644 index 0000000..17b3560 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsCelestialAxesTest.java @@ -0,0 +1,387 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/celestial_axes.rs} (C + * {@code CelestialAxes}, {@code SplitMap} and {@code SplitMap2}, fitschan.c); the values C writes + * for the FrameSets of Rust {@code tests/fitschan_splitmap_oracle/cases.rs} (made by {@code + * tools/oracle_fixtures/fitschan_splitmap_probe.c}), whose pixel to sky Mapping holds no WcsMap; + * and tests of branches read from C's code. + */ +class FitsCelestialAxesTest { + + /** A FrameSet from a GRID Frame to {@code current} through {@code map}. */ + private static FrameSet frameSet(Mapping map, Frame current) { + Frame pixel = new Frame(map.getNin()); + pixel.setDomain("GRID"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, map, current); + return fs; + } + + private static SkyFrame fk5() { + SkyFrame sky = new SkyFrame(); + sky.setSystem("FK5"); + return sky; + } + + /** The result of a call: the Mapping, with the store, FITS axes and flags it changed. */ + private static final class Result { + final Mapping map; + final FitsStore store; + final int[] wperm; + final boolean[] axisDone; + + Result(Mapping map, FitsStore store, int[] wperm, boolean[] axisDone) { + this.map = map; + this.store = store; + this.wperm = wperm; + this.axisDone = axisDone; + } + } + + private static Result celestialAxes(FitsChan fc, FrameSet fs, double[] dim) { + int nwcs = fs.getNout(); + int[] wperm = new int[nwcs]; + for (int i = 0; i < nwcs; i++) { + wperm[i] = i; + } + FitsStore store = new FitsStore(nwcs); + boolean[] axisDone = new boolean[nwcs]; + Mapping map = + FitsCelestialAxes.celestialAxes(fc, fs, dim, wperm, ' ', store, axisDone, 0, "astWrite", "FitsChan"); + return new Result(map, store, wperm, axisDone); + } + + private static Result celestialAxes(FrameSet fs) { + double[] dim = new double[fs.getNin()]; + java.util.Arrays.fill(dim, 100.0); + return celestialAxes(new FitsChan(), fs, dim); + } + + /** A pixel to sky Mapping of an inverted TAN WcsMap. */ + private static FrameSet tanFrameSet() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.invert(); + return frameSet(wm, fk5()); + } + + @Test + void noCelestialAxesReturnsUnitmap() { + Result r = celestialAxes(frameSet(new UnitMap(2), new Frame(2))); + assertEquals(2, r.map.getNin()); + assertEquals(2, r.map.getNout()); + assertInstanceOf(UnitMap.class, r.map); + assertFalse(r.axisDone[0]); + assertFalse(r.axisDone[1]); + assertNull(r.store.crval[0]); + assertNull(r.store.crval[1]); + } + + /** + * Pixel axes exchanged before the projection: the intermediate world axes are those of the + * pixel axes the other way round, so the celestial FITS axes are exchanged. + */ + @Test + void autoAxisSwapFiresWhenPixelToIwcTransposes() { + PermMap swap = new PermMap(2, new int[] {2, 1}, 2, new int[] {2, 1}, null); + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.invert(); + Result r = celestialAxes(frameSet(new CmpMap(swap, wm, true), fk5())); + assertArrayEquals(new int[] {1, 0}, r.wperm); + assertEquals("DEC--TAN", r.store.ctype[0]); + assertEquals("RA---TAN", r.store.ctype[1]); + assertEquals(90.0, r.store.crval[0]); + assertEquals(0.0, r.store.crval[1]); + } + + /** + * A default TAN projection: its fiducial point, the native pole, is CRVAL (0, 90) through a + * UnitMap. + */ + @Test + void tan2axisWritesCelestialKeywords() { + Result r = celestialAxes(tanFrameSet()); + assertTrue(r.axisDone[0]); + assertTrue(r.axisDone[1]); + assertEquals("RA---TAN", r.store.ctype[0]); + assertEquals("DEC--TAN", r.store.ctype[1]); + assertEquals("FK5", r.store.radesys); + assertNotNull(r.store.equinox); + assertEquals(0.0, r.store.crval[0]); + assertEquals(90.0, r.store.crval[1]); + assertNull(r.store.lonpole); + assertNull(r.store.latpole); + assertEquals(2, r.map.getNin()); + assertEquals(2, r.map.getNout()); + + // The Mapping takes world coordinates to intermediate world coordinates in degrees. The + // pixel to world Mapping has native and celestial coordinates the same, a native + // longitude of the celestial pole of 180 degrees; with no LONPOLE stored, WcsNative uses + // the FITS-WCS default for a fiducial point at the pole, 0, so the intermediate world + // coordinates are the projection plane coordinates turned through 180 degrees. + Mapping pixToIwc = new CmpMap(tanFrameSet().getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT), r.map, true); + double[][] iwc = pixToIwc.transform(new double[][] {{0.01}, {-0.02}}, 1, true); + assertEquals(-Math.toDegrees(0.01), iwc[0][0], 1e-10); + assertEquals(Math.toDegrees(0.02), iwc[1][0], 1e-10); + } + + // ------------------------------------------------------------------ + // The FrameSets of Rust tests/fitschan_splitmap_oracle/cases.rs + // ------------------------------------------------------------------ + + /** The probe's SkyFrame: ICRS, its System cleared. */ + private static SkyFrame probeSky() { + SkyFrame sky = new SkyFrame(); + sky.setSystem("ICRS"); + sky.clear("System"); + return sky; + } + + /** A diagonal MatrixMap followed by a ShiftMap. */ + private static Mapping linear(double[] diag, double[] shift) { + return new CmpMap(new MatrixMap(diag.length, diag.length, diag), new ShiftMap(shift), true); + } + + /** C's cards for the celestial axes of the probe's {@code linear} and {@code linear_3d} cases. */ + private static void assertLinearCase(Result r) { + assertEquals(11.459155902616466, r.store.crval[0]); + assertEquals(0.0, r.store.crval[1]); + assertEquals("RA---CAR", r.store.ctype[0]); + assertEquals("DEC--CAR", r.store.ctype[1]); + assertEquals("ICRS", r.store.radesys); + // C writes 348.54084409738351. + assertEquals(348.5408440973835, r.store.lonpole, 1e-12); + assertEquals(348.5408440973835, r.store.pv[0][3], 1e-12); + assertNull(r.store.latpole); + assertNull(r.store.pv[0][4]); + assertNull(r.store.equinox); + } + + /** A linear Mapping is given a CAR projection, its longitude origin moved to the pixel origin. */ + @Test + void linearMappingIsGivenACarProjection() { + Result r = celestialAxes(frameSet(linear(new double[] {-0.001, 0.002}, new double[] {0.2, 0.3}), probeSky())); + assertLinearCase(r); + } + + @Test + void linear3dMappingIsGivenACarProjection() { + Frame x = new Frame(1); + x.setDomain("X"); + Result r = celestialAxes(frameSet( + linear(new double[] {-0.001, 0.002, 3.0}, new double[] {0.2, 0.3, 4.0}), new CmpFrame(probeSky(), x))); + assertLinearCase(r); + assertTrue(r.axisDone[0]); + assertTrue(r.axisDone[1]); + assertFalse(r.axisDone[2]); + assertEquals(3, r.map.getNin()); + assertEquals(3, r.map.getNout()); + assertNull(r.store.crval[2]); + } + + /** Constant celestial values are given the projection of a TAN header with them at CRVAL. */ + @Test + void constantCelestialValuesAreGivenATanProjection() { + PermMap pm = new PermMap(2, new int[] {0, 0}, 2, new int[] {-1, -2}, new double[] {0.5, -0.25}); + Result r = celestialAxes(frameSet(pm, probeSky())); + assertEquals(28.647889756541154, r.store.crval[0]); + // C writes -14.323944878270581. + assertEquals(-14.32394487827058, r.store.crval[1]); + assertEquals("RA---TAN", r.store.ctype[0]); + assertEquals("DEC--TAN", r.store.ctype[1]); + assertEquals("ICRS", r.store.radesys); + assertNull(r.store.lonpole); + assertNull(r.store.latpole); + } + + // ------------------------------------------------------------------ + // Branches read from C's code + // ------------------------------------------------------------------ + + /** + * A non-linear Mapping with no projection and celestial outputs that vary, each fed by one + * grid axis: a 1-D PolyMap (x + 0.001 x^2) beside a 1-D ZoomMap, then a ZoomMap to radians. (A + * 2-D PolyMap would not do: C's PolyMap has no MapSplit, so its outputs cannot be split off.) + */ + private static FrameSet noProjectionFrameSet() { + PolyMap poly = new PolyMap(1, 1, 2, new double[] {1, 1, 1, 0.001, 1, 2}, 0, new double[0]); + Mapping map = new CmpMap(new CmpMap(poly, new ZoomMap(1, 1.0), false), new ZoomMap(2, 0.001), true); + return frameSet(map, fk5()); + } + + /** With no projection and TabOK 0, C describes nothing: a UnitMap, the axes still classified. */ + @Test + void noProjectionWithoutTabOkGivesAUnitMap() { + Result r = celestialAxes(noProjectionFrameSet()); + assertInstanceOf(UnitMap.class, r.map); + assertTrue(r.axisDone[0]); + assertTrue(r.axisDone[1]); + assertNull(r.store.ctype[0]); + } + + /** + * With TabOK positive and no projection, C tabulates separable celestial axes whose grid + * dimensions are known (IsMapTab1D samples each and creates a FitsTable), which needs + * FitsTable. + */ + @Test + void separableAxesWithTabOkNeedFitsTable() { + FitsChan fc = new FitsChan(); + fc.set("TabOK=1"); + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> celestialAxes(fc, noProjectionFrameSet(), new double[] {100, 100})); + assertTrue(e.getMessage().endsWith("needs FitsTable"), e.getMessage()); + } + + /** + * With unknown grid dimensions IsMapTab1D cannot sample the axes and returns NULL, so C + * describes nothing: a UnitMap, with no exception. + */ + @Test + void separableAxesWithUnknownDimensionsAreNotTabulated() { + FitsChan fc = new FitsChan(); + fc.set("TabOK=1"); + Result r = celestialAxes(fc, noProjectionFrameSet(), new double[] {AstObject.AST__BAD, AstObject.AST__BAD}); + assertInstanceOf(UnitMap.class, r.map); + assertTrue(r.axisDone[0]); + assertNull(r.store.ctype[0]); + assertNull(r.store.crval[0]); + } + + /** + * Celestial axes through a projection that is not a FITS projection (FITSProj cleared): each + * depends on both grid axes, so neither can be split off, IsMapTab1D returns NULL, and C + * describes nothing even with TabOK set. + */ + @Test + void nonSeparableAxesWithTabOkAreNotTabulated() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.setFITSProj(false); + wm.invert(); + FitsChan fc = new FitsChan(); + fc.set("TabOK=1"); + Result r = celestialAxes( + fc, frameSet(new CmpMap(new ZoomMap(2, 0.001), wm, true), fk5()), new double[] {100, 100}); + assertInstanceOf(UnitMap.class, r.map); + assertTrue(r.axisDone[0]); + assertTrue(r.axisDone[1]); + assertNull(r.store.ctype[0]); + assertNull(r.store.crval[0]); + } + + /** + * ForceTab asks for -TAB even with a projection. Without TabOK nothing is described; with it, + * the TAN axes are not separable, so nothing is described either. + */ + @Test + void forceTab() { + FitsChan fc = new FitsChan(); + fc.set("ForceTab=1"); + Result r = celestialAxes(fc, tanFrameSet(), new double[] {100, 100}); + assertInstanceOf(UnitMap.class, r.map); + assertNull(r.store.crval[0]); + + FitsChan tab = new FitsChan(); + tab.set("ForceTab=1, TabOK=1"); + r = celestialAxes(tab, tanFrameSet(), new double[] {100, 100}); + assertInstanceOf(UnitMap.class, r.map); + assertNull(r.store.crval[0]); + assertNull(r.store.ctype[0]); + } + + /** A SkyFrame whose Domain is not SKY is not celestial (C's {@code IsASkyFrame}). */ + @Test + void aSkyFrameWithAnotherDomainIsNotCelestial() { + SkyFrame sky = fk5(); + sky.setDomain("OTHER"); + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.invert(); + Result r = celestialAxes(frameSet(wm, sky)); + assertInstanceOf(UnitMap.class, r.map); + assertFalse(r.axisDone[0]); + } + + /** Without FitsAxisOrder {@code }, the FITS axes are kept whatever the rotation. */ + @Test + void noSwapWithAFixedAxisOrder() { + PermMap swap = new PermMap(2, new int[] {2, 1}, 2, new int[] {2, 1}, null); + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.invert(); + FitsChan fc = new FitsChan(); + fc.set("FitsAxisOrder="); + Result r = celestialAxes(fc, frameSet(new CmpMap(swap, wm, true), fk5()), new double[] {100, 100}); + assertArrayEquals(new int[] {0, 1}, r.wperm); + assertEquals("RA---TAN", r.store.ctype[0]); + } + + /** + * A WcsMap in parallel with another Mapping: SplitMap2 makes a WcsMap with as many axes as the + * parallel outputs, its axes moved by the outputs before it and its parameters with them, and + * inverts it whatever the Invert value of the WcsMap found. + */ + @Test + void splitMap2LiftsAWcsMapInParallel() { + WcsMap wm = new WcsMap(2, WcsMap.AST__SIN, 2, 1); + wm.setPV(0, 1, 0.1); + CmpMap par = new CmpMap(new ZoomMap(1, 2.0), wm, false); + FitsCelestialAxes.Split split = FitsCelestialAxes.splitMap2(par, false); + assertNotNull(split); + assertEquals(3, split.map2.getNin()); + assertEquals(WcsMap.AST__SIN, split.map2.getWcsType()); + assertEquals(3, split.map2.getWcsAxis(1)); + assertEquals(2, split.map2.getWcsAxis(2)); + assertEquals(0.1, split.map2.getPV(1, 1)); + assertTrue(split.map2.getInvert()); + assertEquals(3, split.map1.getNout()); + assertEquals(3, split.map3.getNin()); + } + + /** A WcsMap without FITSProj is not a projection. */ + @Test + void aWcsMapWithoutFitsProjIsNotFound() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.setFITSProj(false); + assertNull(FitsCelestialAxes.splitMap2(wm, true)); + WcsMap fp = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + FitsCelestialAxes.Split split = FitsCelestialAxes.splitMap2(fp, true); + assertNotNull(split); + assertTrue(split.map2.getInvert()); + assertInstanceOf(UnitMap.class, split.map1); + assertInstanceOf(UnitMap.class, split.map3); + } + + /** SplitMap needs no projection in the Mappings either side of the one it uses. */ + @Test + void twoProjectionsAreRefused() { + WcsMap a = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + a.invert(); + WcsMap b = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + b.invert(); + CmpMap two = new CmpMap(a, b, true); + assertNotNull(FitsCelestialAxes.splitMap2(two, false)); + // Not linear, and the celestial outputs vary. + assertNull(FitsCelestialAxes.splitMap(two, false, 0, 1)); + } + + /** A CmpMap with Ident set, which astMapList gives back whole, holds no WcsMap that is found. */ + @Test + void anIdentCmpMapIsNotSearched() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.invert(); + CmpMap cmp = new CmpMap(new ZoomMap(2, 0.001), wm, true); + cmp.setIdent("keep"); + assertNull(FitsCelestialAxes.splitMap2(cmp, false)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanAltEpochOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanAltEpochOracleTest.java new file mode 100644 index 0000000..6b7a12c --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanAltEpochOracleTest.java @@ -0,0 +1,118 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_fitschan_alt_epoch_oracle.rs}: where a FITS-WCS write + * takes MJD-OBS and DATE-OBS from when the axis descriptions have different epochs, against C. + * {@code SkySys} (fitschan.c) stores the date of observation only for the primary axis + * description. A header has a single MJD-OBS, which an alternate description must not change, + * whether or not that alternate is written. + * + *

Each case reads a celestial header with a primary (FK5) and an alternate (galactic, {@code + * A}) description, with or without MJD-OBS, then optionally sets the Epoch of either Frame, and + * optionally remaps the alternate Frame with a non-linear MathMap so that its description cannot + * be written. The FrameSet is written with NAXIS1 and NAXIS2 set. Compared with C: the value the + * write returns and the cards written. The cases are those of {@code + * oracle/fitschan_alt_epoch.json}, made by {@code tools/oracle_fixtures/fitschan_alt_epoch_probe.c}. + * + *

The cases that remap the alternate Frame with a MathMap, which this library does not have, + * do not run; their number is pinned. + */ +class FitsChanAltEpochOracleTest { + + /** The number of cases that remap the alternate Frame with a MathMap. */ + private static final int NEED_MATHMAP = 3; + + private static final String[] HEADER = { + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 20", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "RADESYS = 'FK5'", + "EQUINOX = 2000.0", + "CRPIX1A = 50", + "CRPIX2A = 50", + "CRVAL1A = 100", + "CRVAL2A = 30", + "CDELT1A = -0.001", + "CDELT2A = 0.001", + "CTYPE1A = 'GLON-TAN'", + "CTYPE2A = 'GLAT-TAN'", + }; + + /** + * The value the write returns and the cards written. {@code prim} and {@code alt} are the MJD + * epochs set on the primary and alternate Frames, or 0 for none. + */ + private static List written(String mjdobs, double prim, double alt) { + FitsChan fc = new FitsChan(); + for (String card : HEADER) { + fc.putFits(card, false); + } + if (!mjdobs.isEmpty()) { + fc.putFits(mjdobs, false); + } + FrameSet fs = FitsHeaders.readFrameSet(rewound(fc)); + // Frame 2 is the primary description and Frame 3 the alternate. + if (prim != 0.0) { + fs.setCurrent(2); + fs.setEpoch(String.format(java.util.Locale.ROOT, "MJD %.1f", prim)); + } + fs.setCurrent(3); + if (alt != 0.0) { + fs.setEpoch(String.format(java.util.Locale.ROOT, "MJD %.1f", alt)); + } + fs.setCurrent(2); + FitsChan out = new FitsChan(); + out.setEncoding("FITS-WCS"); + out.putFits("NAXIS1 = 100", false); + out.putFits("NAXIS2 = 100", false); + List got = new ArrayList<>(); + got.add("wrote " + out.write(fs)); + got.addAll(FitsHeaders.foundCards(out)); + return got; + } + + private static FitsChan rewound(FitsChan fc) { + fc.clear("Card"); + return fc; + } + + @Test + void datesMatchC() { + List failed = new ArrayList<>(); + int needMathMap = 0; + for (JsonNode c : ProbeData.load("fitschan_alt_epoch").get("CASES")) { + String name = c.get(0).asText(); + if (c.get(4).asBoolean()) { + needMathMap++; + continue; + } + List want = new ArrayList<>(); + want.add("wrote " + c.get(5).asInt()); + want.addAll(FitsHeaders.strings(c.get(6))); + List got = + written(c.get(1).asText(), c.get(2).asDouble(), c.get(3).asDouble()); + if (!FitsHeaders.cardsMatchC(got, want)) { + failed.add(name + ":\n--- Java\n" + String.join("\n", got) + "\n--- C\n" + String.join("\n", want)); + } + } + assertTrue(failed.isEmpty(), String.join("\n", failed)); + assertEquals(NEED_MATHMAP, needMathMap, "cases that need MathMap"); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanAltNaxesOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanAltNaxesOracleTest.java new file mode 100644 index 0000000..d96e834 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanAltNaxesOracleTest.java @@ -0,0 +1,82 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_fitschan_alt_naxes_oracle.rs}: how a FITS-WCS write + * describes axis descriptions with different numbers of axes, against C. {@code WcsFromStore} + * (fitschan.c) bounds its per-axis loops, for each version, by WCSAXES if the version has one, and + * otherwise by the highest CRPIX index stored for it. + * + *

Each FrameSet has a 3-D GRID Frame, a primary Frame and an alternate Frame (Ident {@code A}), + * joined to the GRID Frame by PermMaps that drop or add axes, and is written with {@code NAXIS = + * 3}. Compared with C: the value the write returns and the cards written. The cases are those of + * {@code oracle/fitschan_alt_naxes.json}, made by {@code + * tools/oracle_fixtures/fitschan_alt_naxes_probe.c}. + */ +class FitsChanAltNaxesOracleTest { + + /** + * The probe's Mapping from 3 pixel axes to {@code nout} axes: a PermMap passing the axes they + * share and giving any extra output the value 5, then a ShiftMap adding {@code shift + i} to + * output {@code i}. + */ + private static Mapping mapTo(int nout, double shift) { + int[] inperm = new int[3]; + for (int i = 0; i < 3; i++) { + inperm[i] = i < nout ? i + 1 : -1; + } + int[] outperm = new int[nout]; + double[] shifts = new double[nout]; + for (int i = 0; i < nout; i++) { + outperm[i] = i < 3 ? i + 1 : -1; + shifts[i] = shift + i; + } + PermMap perm = new PermMap(3, inperm, nout, outperm, new double[] {5.0}); + return new CmpMap(perm, new ShiftMap(shifts), true); + } + + /** The value the write returns and the cards written. */ + private static List written(int nprim, int nalt) { + Frame grid = new Frame(3); + grid.setDomain("GRID"); + Frame prim = new Frame(nprim); + prim.setDomain("PRI"); + Frame alt = new Frame(nalt); + alt.setDomain("ALT"); + alt.setIdent("A"); + FrameSet fs = new FrameSet(grid); + fs.addFrame(FrameSet.AST__BASE, mapTo(nprim, 10.0), prim); + fs.addFrame(FrameSet.AST__BASE, mapTo(nalt, 100.0), alt); + fs.setCurrent(2); + FitsChan fc = new FitsChan(); + fc.setEncoding("FITS-WCS"); + fc.putFits("NAXIS = 3", false); + List out = new ArrayList<>(); + out.add("wrote " + fc.write(fs)); + out.addAll(FitsHeaders.foundCards(fc)); + return out; + } + + @Test + void versionsMatchC() { + List failed = new ArrayList<>(); + for (JsonNode c : ProbeData.load("fitschan_alt_naxes").get("CASES")) { + String name = c.get(0).asText(); + List want = new ArrayList<>(); + want.add("wrote " + c.get(3).asInt()); + want.addAll(FitsHeaders.strings(c.get(4))); + List got = written(c.get(1).asInt(), c.get(2).asInt()); + if (!FitsHeaders.cardsMatchC(got, want)) { + failed.add(name + ":\n--- Java\n" + String.join("\n", got) + "\n--- C\n" + String.join("\n", want)); + } + } + assertTrue(failed.isEmpty(), String.join("\n", failed)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanApiTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanApiTest.java index 53155eb..43c6067 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanApiTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanApiTest.java @@ -145,9 +145,9 @@ void cardIsZeroWhenEmpty() { assertFalse(fc.test("Card")); } - /** {@code write} is out of scope. */ + /** {@code write} with the default NATIVE encoding writes any Object. */ @Test - void writeIsUnsupported() { - assertThrows(UnsupportedOperationException.class, () -> new FitsChan().write(new UnitMap(1))); + void writeWritesNative() { + assertEquals(1, new FitsChan().write(new UnitMap(1))); } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java index a247f46..b6309f9 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java @@ -20,12 +20,7 @@ * {@code DistortMaps} looked up with {@code astGetFitsF} (fitschan.c:9019). * *

Listed in {@code deferred/rust-tests.txt}: {@code - * badpv_warning_names_each_unusable_parameter_in_ascending_order} (its header, with {@code - * RADECSYS} and {@code PROJPi} but no {@code PVi_m}, is read with the FITS-IRAF encoding), {@code - * badctype_warning_names_the_legal_ctype_and_precedes_naxis1} (a spectral axis, SpecFrame) and - * {@code strict_write_warning_is_an_error} (a write); {@code strict_read_warning_is_an_error} and - * {@code strict_sweep_warning_is_an_error}, whose header has {@code RADECSYS} and no {@code - * RADESYS}, so that C reads it with the FITS-PC encoding (fitschan.c {@code GetEncoding}). + * badctype_warning_names_the_legal_ctype_and_precedes_naxis1} (a spectral axis, SpecFrame). */ class FitsChanAstwarnTest { @@ -175,4 +170,152 @@ void strictPutFitsWarningIsAnError() { clean.putFits(card, false); assertEquals(1, clean.getNcard()); } + + /** The cards of Rust's {@code NO_EQUINOX} before its {@code RADECSYS}. */ + private static final String[] TAN_CARDS = { + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 20", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + }; + + @Test + void strictWriteWarningIsAnError() { + // A C probe: a FrameSet with an MJD-OBS written to a FitsChan holding TIMESYS = 'ET', with + // Warnings badval and Strict set, fails naming the method "FitsChan", since C's Write + // passes FsetToStore its method and class names in the wrong order. + FitsChan fc = new FitsChan(); + for (String card : TAN_CARDS) { + fc.putFits(card, false); + } + fc.putFits("EQUINOX = 2000", false); + fc.putFits("MJD-OBS = 55000", false); + fc.setCard(1); + AstObject obj = fc.read(); + assertNotNull(obj); + + FitsChan out = strictChan("badval"); + out.setEncoding("FITS-WCS"); + out.putFits("TIMESYS = 'ET'", false); + out.setCard(1); + String before = out.toHeader(); + AstException e = assertThrows(AstException.class, () -> out.write(obj)); + assertEquals(AstException.AST__BADIN, e.getStatus()); + assertMessage( + "FitsChan(FitsChan): The original FITS header contained a value of ET for keyword TIMESYS. TT will be" + + " used instead.", + e); + assertEquals(before, out.toHeader()); + } + + /** + * A 2-axis TAN header with {@code PROJPi} and {@code RADECSYS}, which C reads with the + * FITS-IRAF encoding: the PROJP values become PV2_m, which TAN does not use. + */ + private static final String TWO_AXIS_BADPV = String.join( + "\n", + "NAXIS1 = 512 / length of data axis 1", + "NAXIS2 = 512 / length of data axis 2", + "CTYPE1 = 'RA---TAN' / Gnomonic projection", + "CTYPE2 = 'DEC--TAN' / Gnomonic projection", + "CRVAL1 = 180.000 / Reference RA (deg)", + "CRVAL2 = 45.000 / Reference Dec (deg)", + "CRPIX1 = 256.500 / Reference pixel on axis 1", + "CRPIX2 = 256.500 / Reference pixel on axis 2", + "CD1_1 = -8.3332205E-4 / CD matrix", + "CD1_2 = 0.0 / CD matrix", + "CD2_1 = 0.0 / CD matrix", + "CD2_2 = 0.00083332205 / CD matrix", + "RADECSYS= 'FK5 ' / Old-style reference frame keyword", + "EQUINOX = 2000.0 / Equinox", + "PROJP0 = 0.0 / Legacy projection parameter 0", + "PROJP1 = 0.0 / Legacy projection parameter 1", + "PROJP2 = 0.0 / Legacy projection parameter 2", + "LONGPOLE= 180.000 / Native longitude of celestial pole", + ""); + + @Test + void badpvWarningNamesEachUnusableParameterInAscendingOrder() { + FitsChan fc = FitsChan.fromHeader(TWO_AXIS_BADPV); + fc.read(); + // Text and wrapping from wcsconv/expected/projp.native, with the trailing space where C's + // 60-character wrap breaks the line. + assertEquals( + Arrays.asList( + " ", + "Projection parameter PV2_1 found, but is not used by -TAN ", + "projections.", + " ", + " ", + "Projection parameter PV2_2 found, but is not used by -TAN ", + "projections.", + " "), + FitsHeaders.astwarnValues(fc)); + } + + /** Rust's {@code NO_EQUINOX}: a TAN header with {@code RADECSYS} and no EQUINOX, read as FITS-PC. */ + private static String[] noEquinox() { + String[] cards = Arrays.copyOf(TAN_CARDS, TAN_CARDS.length + 1); + cards[TAN_CARDS.length] = "RADECSYS= 'FK5'"; + return cards; + } + + @Test + void strictReadWarningIsAnError() { + // A C probe: the read of NO_EQUINOX with Warnings noequinox gives an Object and an ASTWARN + // block; with Strict set too it fails with AST__BADIN, leaving the 12 cards, Card 1 and no + // warnings; with ReportLevel 0 as well it succeeds as without Strict. + FitsChan fc = strictChan("noequinox"); + for (String card : noEquinox()) { + fc.putFits(card, false); + } + fc.clear("Card"); + String before = fc.toHeader(); + AstException e = assertThrows(AstException.class, fc::read); + assertEquals(AstException.AST__BADIN, e.getStatus()); + assertMessage( + "astRead(FitsChan): The original FITS header did not specify the reference equinox. A default value" + + " of J2000 was assumed.", + e); + assertEquals(before, fc.toHeader()); + assertEquals(1, fc.getCard()); + assertTrue(fc.warningTexts().isEmpty()); + + FitsChan fc0 = strictChan("noequinox"); + fc0.setReportLevel(0); + for (String card : noEquinox()) { + fc0.putFits(card, false); + } + fc0.clear("Card"); + assertNotNull(fc0.read()); + assertEquals(7, fc0.getNcard()); + } + + @Test + void strictSweepWarningIsAnError() { + // A C probe: NO_EQUINOX with CRVAL1 = 'abc', read with Warnings badval, gives an Object + // and a badval ASTWARN block in front of CRVAL1; with Strict set the read fails with + // AST__BADIN, leaving the 12 cards and Card 1. + FitsChan fc = strictChan("badval"); + for (String card : noEquinox()) { + fc.putFits(card.startsWith("CRVAL1") ? "CRVAL1 = 'abc'" : card, false); + } + fc.clear("Card"); + String before = fc.toHeader(); + AstException e = assertThrows(AstException.class, fc::read); + assertEquals(AstException.AST__BADIN, e.getStatus()); + assertMessage( + "astRead(FitsChan): The original FITS header contained a value for keyword CRVAL1 which could not be" + + " converted to a floating point number.", + e); + assertEquals(before, fc.toHeader()); + assertEquals(1, fc.getCard()); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java index cad6d54..84d1f73 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java @@ -8,18 +8,25 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; import org.junit.jupiter.api.Test; import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.Fixtures; /** * Translation of Rust {@code tests/test_fitschan_c_inline.rs}: checks made inline in {@code main()} * of C's {@code ast_tester/testfitschan.c}, each named by C's error numbers and made with C's * values. * - *

Listed in {@code deferred/rust-tests.txt}: the tests that write a FrameSet to a FitsChan - * ({@code sip_header_does_not_write_as_fits_wcs}, {@code azel_writes_as_fits_wcs}, {@code - * supergalactic_writes_slon}, {@code sky_systems_through_five_encodings} and {@code - * date_and_observatory_write_back}), those that need a SpecFrame ({@code + *

The write tests use {@link #roundtrip}, C's helper of the same name, and expect the values a + * C probe of the pinned library gives ({@code c1.c} beside the task report): where C's test accepts + * either of two outcomes, the one C gives. + * + *

Listed in {@code deferred/rust-tests.txt}: those that need a SpecFrame ({@code * alternate_axes_with_a_bad_set}, whose header has a VRAD axis, {@code non_linear_spectral_writes}, * {@code spectral_systems_through_fits_wcs} and {@code log_spectral_axis_writes_freq_log}), and * {@code show_fits_succeeds} (jniast has no {@code showFits}). @@ -242,4 +249,378 @@ void everyTimesysReads() { } } } + + /** C's {@code roundtrip} result: the write or read failed. */ + private static final int RT_FAILED = 0; + + /** C's {@code roundtrip} result: the keyword did not have the expected value. */ + private static final int RT_WRONG_KEY = -2; + + /** C's {@code roundtrip} result: the coordinates disagreed. */ + private static final int RT_DISAGREE = -1; + + /** C's {@code roundtrip} result: all is well. */ + private static final int RT_OK = 1; + + /** The pixel value on every axis of each point {@link #roundtrip} compares. */ + private static final double[] OFFSETS = {50.0, 50.5, 51.0, 55.0, 45.0}; + + /** + * C's {@code roundtrip} (testfitschan.c): writes {@code fs} with {@code encoding} into a new + * FitsChan, checks that {@code key} (any {@code CTYPEn}, n from 1 to 9, for {@code "CTYPE"}) + * has the value {@code val}, reads it back, and, unless {@code tol} is negative, compares the + * world coordinates of the two FrameSets at {@link #OFFSETS} on every axis, after converting + * the first FrameSet's to the current Frame of the second, to {@code tol} absolute or relative. + * When the current Frames cannot be converted, the pixel coordinates are compared after a + * round trip through the first FrameSet and back through the second. An error clears to + * {@link #RT_FAILED}, as C clears the status. + */ + private static int roundtrip(FrameSet fs, String encoding, double tol, String key, String val) { + try { + FitsChan fc = new FitsChan(); + fc.setEncoding(encoding); + if (fc.write(fs) != 1) { + return RT_FAILED; + } + boolean found = false; + List keys = new ArrayList<>(); + if ("CTYPE".equals(key)) { + for (int iax = 1; iax <= 9; iax++) { + keys.add("CTYPE" + iax); + } + } else { + keys.add(key); + } + for (String k : keys) { + fc.clear("Card"); + if (val.equals(fc.getFitsS(k))) { + found = true; + break; + } + } + if (!found) { + return RT_WRONG_KEY; + } + fc.clear("Card"); + AstObject obj = fc.read(); + if (obj == null) { + return RT_FAILED; + } + FrameSet fs2 = (FrameSet) obj; + if (tol < 0.0) { + return RT_OK; + } + Mapping map1 = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Mapping map2 = fs2.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Frame curfrm2 = fs2.getFrame(FrameSet.AST__CURRENT); + int nin = fs.getNin(); + int nout = fs.getNout(); + FrameSet cvt = fs.getFrame(FrameSet.AST__CURRENT).convert(curfrm2, " "); + if (cvt != null) { + for (double offset : OFFSETS) { + double[] pix = new double[nin]; + Arrays.fill(pix, offset); + double[] wcs1 = map1.tranN(1, nin, pix, true, nout); + double[] wcs2 = map2.tranN(1, nin, pix, true, nout); + double[] wcs1c = cvt.tranN(1, nout, wcs1, true, nout); + for (int iax = 0; iax < nout; iax++) { + double v1 = wcs1c[iax]; + double v2 = wcs2[iax]; + if (v1 == AstObject.AST__BAD || v2 == AstObject.AST__BAD) { + continue; + } + double diff = Math.abs(curfrm2.axDistance(iax + 1, v1, v2)); + if (diff > tol) { + double scale = Math.max(Math.abs(v1), Math.abs(v2)); + if (scale > 0.0 && diff / scale > tol) { + return RT_DISAGREE; + } + } + } + } + } else { + Mapping roundmap = new CmpMap(map1, fs2.getMapping(FrameSet.AST__CURRENT, FrameSet.AST__BASE), true); + for (double offset : OFFSETS) { + double[] pixIn = new double[nin]; + Arrays.fill(pixIn, offset); + double[] pixOut = roundmap.tranN(1, nin, pixIn, true, nin); + for (int iax = 0; iax < nin; iax++) { + if (pixIn[iax] == AstObject.AST__BAD || pixOut[iax] == AstObject.AST__BAD) { + continue; + } + double diff = Math.abs(pixOut[iax] - pixIn[iax]); + if (diff > tol) { + double scale = Math.abs(pixIn[iax]); + if (scale > 0.0 && diff / scale > tol) { + return RT_DISAGREE; + } + } + } + } + } + return RT_OK; + } catch (AstException e) { + return RT_FAILED; + } + } + + /** + * The keywords whose values {@link #azelWritesAsFitsWcs} and {@link #supergalacticWritesSlon} + * compare within libm rounding ({@link FitsHeaders#cardsMatchC(List, List, java.util.Set)}). + * The Mappings fitted are C's, but java.lang.Math differs from C's libm by 1 ULP at the same + * arguments: in the sine MtrRot takes of the rotation angles (AZEL), in an arctangent of + * palEqgal and palGalsup giving the fiducial latitude, and so the angle, of the rotation + * (Supergalactic), and in the SphMap, SlaMap and TAN WcsMap transforms of the points FitLine + * fits (Galactic); IWC computed near the native pole amplify those differences (probes g1, + * a2, rep, sla and cs beside the task report). + */ + private static final Set LIBM_KEYWORDS = + new HashSet<>(Arrays.asList("CDELT1", "CDELT2", "PC1_1", "PC1_2", "PC2_1", "PC2_2")); + + /** The FrameSet {@code fc} reads from {@code cards}. */ + private static FrameSet readCards(String... cards) { + return FitsHeaders.readFrameSet(FitsHeaders.chan(cards)); + } + + /** 12-13: with SipOK off, a SIP header reads but is too non-linear to write as FITS-WCS. */ + @Test + void sipHeaderDoesNotWriteAsFitsWcs() { + FitsChan fc = new FitsChan(); + fc.set("SipOK=0"); + fc.setC("SourceFile", Fixtures.root().resolve("wcsconv/inputs/sip.head").toString()); + fc.clear("Card"); + FrameSet fs = FitsHeaders.readFrameSet(fc); + fc.setEncoding("FITS-WCS"); + assertEquals(0, fc.write(fs), "Error 13"); + // C leaves the 244 cards the read left. + assertEquals(244, fc.getNcard()); + } + + /** The header of the AZEL test (630-633), without its MJD-OBS. */ + private static final String[] AZEL_SOURCE = { + "SIMPLE = T", + "BITPIX = -32", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRVAL1 = 180.000", + "CRVAL2 = 45.000", + "CRPIX1 = 50.500", + "CRPIX2 = 50.500", + "CDELT1 = -0.0100", + "CDELT2 = 0.0100", + "RADESYS = 'FK5'", + "EQUINOX = 2000.0", + "DATE-OBS= '2017-07-21T08:38:39.087'", + "OBSGEO-X= -5464586.5949660344", + "OBSGEO-Y= -2492996.5580556658", + "OBSGEO-Z= 2150654.3760909005", + "END", + }; + + /** + * 630-633: an FK5 header with an observation date and place, changed to AZEL, writes {@code + * AZ---TAN} as FITS-WCS (C puts the elevation axis first) and reads back. + */ + @Test + void azelWritesAsFitsWcs() { + FrameSet fs = readCards(AZEL_SOURCE); + fs.setC("System", "AZEL"); + assertEquals(RT_OK, roundtrip(fs, "FITS-WCS", 1e-3, "CTYPE", "AZ---TAN"), "Error 630-633"); + + FitsChan fc = new FitsChan(); + fc.setEncoding("FITS-WCS"); + assertEquals(1, fc.write(fs)); + List want = FitsHeaders.padded( + "WCSAXES = 2 / Number of WCS axes", + "CRPIX1 = 50.499968 / Reference pixel on axis 1", + "CRPIX2 = 50.499981 / Reference pixel on axis 2", + "CRVAL1 = 11.615311196755748 / Value at ref. pixel on axis 1", + "CRVAL2 = 313.79068013639778 / Value at ref. pixel on axis 2", + "CTYPE1 = 'EL---TAN' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'AZ---TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CDELT1 = -0.010000493460993179 / Pixel size on axis 1", + "CDELT2 = 0.010000494181343293 / Pixel size on axis 2", + "PC1_1 = 0.95887433689593371 / Transformation matrix element", + "PC1_2 = -0.28383094623804417 / Transformation matrix element", + "PC2_1 = 0.28383092720225839 / Transformation matrix element", + "PC2_2 = 0.95887434253060821 / Transformation matrix element", + "MJD-OBS = 57955.360174618057 / Modified Julian Date of observation", + "DATE-OBS= '2017-07-21T08:38:39.087' / Date of observation", + "OBSGEO-X= -5464586.5949660344 / [m] Observatory geocentric X", + "OBSGEO-Y= -2492996.5580556653 / [m] Observatory geocentric Y", + "OBSGEO-Z= 2150654.376090901 / [m] Observatory geocentric Z"); + List got = FitsHeaders.foundCards(fc); + assertTrue(FitsHeaders.cardsMatchC(got, want, LIBM_KEYWORDS), String.join("\n", got)); + } + + /** + * 835-836: an FK5 header remapped to Galactic and to Supergalactic writes {@code GLON} and + * {@code SLON} as FITS-WCS; C puts the Galactic latitude axis first. + */ + @Test + void supergalacticWritesSlon() { + String[][] want = { + { + "WCSAXES = 2 / Number of WCS axes", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 50.0 / Reference pixel on axis 2", + "CRVAL1 = 40.885263413197158 / Value at ref. pixel on axis 1", + "CRVAL2 = 141.58712489261552 / Value at ref. pixel on axis 2", + "CTYPE1 = 'GLAT-TAN' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'GLON-TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CDELT1 = 0.01 / Pixel size on axis 1", + "CDELT2 = 0.01 / Pixel size on axis 2", + "PC1_1 = 0.99949812396986037 / Transformation matrix element", + "PC1_2 = 0.031678070975510009 / Transformation matrix element", + "PC2_1 = -0.031678070968866552 / Transformation matrix element", + "PC2_2 = 0.99949812397007098 / Transformation matrix element", + "MJD-OBS = 51544.499257130781 / Modified Julian Date of observation", + "DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation", + }, + { + "WCSAXES = 2 / Number of WCS axes", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 50.0 / Reference pixel on axis 2", + "CRVAL1 = 320.87048231548192 / Value at ref. pixel on axis 1", + "CRVAL2 = -52.245457827546453 / Value at ref. pixel on axis 2", + "CTYPE1 = 'SLON-TAN' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'SLAT-TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CDELT1 = -0.0099999999998425602 / Pixel size on axis 1", + "CDELT2 = 0.01 / Pixel size on axis 2", + "PC1_1 = 0.99019598050830937 / Transformation matrix element", + "PC1_2 = 0.13968507502660274 / Transformation matrix element", + "PC2_1 = -0.13968507500640948 / Transformation matrix element", + "PC2_2 = 0.99019598051115809 / Transformation matrix element", + "MJD-OBS = 51544.499257130781 / Modified Julian Date of observation", + "DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation", + }, + }; + String[] systems = {"Galactic", "Supergalactic"}; + for (int it = 0; it < systems.length; it++) { + FrameSet fs = readCards( + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRVAL1 = 180.000", + "CRVAL2 = 45.000", + "CRPIX1 = 50.000", + "CRPIX2 = 50.000", + "CDELT1 = -0.0100", + "CDELT2 = 0.0100", + "RADESYS = 'FK5'", + "EQUINOX = 2000.0", + "END"); + SkyFrame tgt = new SkyFrame(); + tgt.setC("System", systems[it]); + FrameSet cvt = fs.getFrame(FrameSet.AST__CURRENT).convert(tgt, ""); + fs.remapFrame(FrameSet.AST__CURRENT, cvt.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT)); + fs.setC("System", systems[it]); + + FitsChan wfc = FitsHeaders.chan("NAXIS1 = 100", "NAXIS2 = 100"); + wfc.setEncoding("FITS-WCS"); + assertEquals(1, wfc.write(fs), systems[it]); + List w = FitsHeaders.padded("NAXIS1 = 100", "NAXIS2 = 100"); + w.addAll(FitsHeaders.padded(want[it])); + List got = FitsHeaders.foundCards(wfc); + assertTrue( + FitsHeaders.cardsMatchC(got, w, LIBM_KEYWORDS), + "Error " + (835 + it) + ": SkySys " + systems[it] + ":\n" + String.join("\n", got)); + } + } + + /** + * 500-534: a Galactic TAN header changed to each sky System and written in each of five + * encodings. C's test accepts a refused write; C refuses FK4-NO-E and ICRS with FITS-AIPS and + * FITS-AIPS++, and Supergalactic with FITS-IRAF, FITS-AIPS and FITS-AIPS++. Every write made + * has C's longitude CTYPE and reads back to the same sky positions. + */ + @Test + void skySystemsThroughFiveEncodings() { + String[] systems = {"FK5", "FK4", "FK4-NO-E", "ICRS", "GALACTIC", "SUPERGALACTIC", "ECLIPTIC"}; + String[] ctypes = {"RA---TAN", "RA---TAN", "RA---TAN", "RA---TAN", "GLON-TAN", "SLON-TAN", "ELON-TAN"}; + String[] encodings = {"FITS-WCS", "FITS-PC", "FITS-IRAF", "FITS-AIPS", "FITS-AIPS++"}; + int[][] want = { + {1, 1, 1, 1, 1}, + {1, 1, 1, 1, 1}, + {1, 1, 1, 0, 0}, + {1, 1, 1, 0, 0}, + {1, 1, 1, 1, 1}, + {1, 1, 0, 0, 0}, + {1, 1, 1, 1, 1}, + }; + for (int is = 0; is < systems.length; is++) { + for (int ie = 0; ie < encodings.length; ie++) { + FrameSet fs = readCards( + "SIMPLE = T", + "BITPIX = -32", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'GLON-TAN'", + "CTYPE2 = 'GLAT-TAN'", + "CRVAL1 = 180.000", + "CRVAL2 = 0.000", + "CRPIX1 = 50.500", + "CRPIX2 = 50.500", + "CDELT1 = -0.0100", + "CDELT2 = 0.0100", + "END"); + fs.setC("System", systems[is]); + assertEquals( + want[is][ie], + roundtrip(fs, encodings[ie], 1e-3, "CTYPE", ctypes[is]), + "Error " + (500 + is * encodings.length + ie) + ": " + systems[is] + " with " + encodings[ie]); + } + } + } + + /** + * 650-659 (DATE-OBS block): an FK5 header with MJD-OBS and OBSGEO writes them back as FITS-WCS + * within 1e-3 days and 1 m, as the cards C writes. + */ + @Test + void dateAndObservatoryWriteBack() { + String[] source = Arrays.copyOf(AZEL_SOURCE, AZEL_SOURCE.length + 1); + System.arraycopy(AZEL_SOURCE, 15, source, 16, AZEL_SOURCE.length - 15); + source[15] = "MJD-OBS = 57955.360174621412"; + FrameSet fs = readCards(source); + FitsChan wfc = new FitsChan(); + wfc.setEncoding("FITS-WCS"); + assertEquals(1, wfc.write(fs), "Error 651"); + String[] keys = {"MJD-OBS", "OBSGEO-X", "OBSGEO-Y", "OBSGEO-Z"}; + // C's values, to the digits of its header cards. + String[] values = {"57955.360174621412", "-5464586.5949660344", "-2492996.5580556658", "2150654.3760909005"}; + double[] tols = {1e-3, 1.0, 1.0, 1.0}; + for (int i = 0; i < keys.length; i++) { + wfc.clear("Card"); + Double got = wfc.getFitsF(keys[i]); + assertNotNull(got, "Error " + (652 + 2 * i) + ": " + keys[i] + " not written"); + assertTrue( + Math.abs(got - Double.parseDouble(values[i])) <= tols[i], + "Error " + (653 + 2 * i) + ": " + keys[i] + " = " + got); + } + List want = FitsHeaders.padded( + "WCSAXES = 2 / Number of WCS axes", + "CRPIX1 = 50.5 / Reference pixel on axis 1", + "CRPIX2 = 50.5 / Reference pixel on axis 2", + "CRVAL1 = 180.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 45.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CDELT1 = -0.01 / Pixel size on axis 1", + "CDELT2 = 0.01 / Pixel size on axis 2", + "MJD-OBS = 57955.360174621412 / Modified Julian Date of observation", + "DATE-OBS= '2017-07-21T08:38:39.087' / Date of observation", + "RADESYS = 'FK5 ' / Reference frame for RA/DEC values", + "EQUINOX = 2000.0 / [yr] Epoch of reference equinox", + "OBSGEO-X= -5464586.5949660344 / [m] Observatory geocentric X", + "OBSGEO-Y= -2492996.5580556653 / [m] Observatory geocentric Y", + "OBSGEO-Z= 2150654.376090901 / [m] Observatory geocentric Z"); + List got = FitsHeaders.foundCards(wfc); + assertTrue(FitsHeaders.cardsMatchC(got, want), String.join("\n", got)); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java index 4823386..c026d6f 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java @@ -35,35 +35,29 @@ * transcript C printed: the result of each operation and then the state. The same script is run * here, through the same string attribute interface the probe uses, and the transcripts compared. * - *

Cases whose scripts read from the FitsChan ({@code R}, {@code RN} and {@code PW}) run when - * their reads need only the NATIVE and FITS-WCS encodings. A read that reaches another foreign - * encoding (FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++, FITS-CLASS or DSS), whose read is out of - * scope, throws {@code UnsupportedOperationException}; the number of such cases is pinned by {@link - * #WAITING_FOR_ANOTHER_ENCODING}. A read that stops at another out-of-scope class (such as {@code - * needs SpecFrame}) must be in {@link #EXCLUDED} with that reason, measured from the exception. - * Cases whose scripts write to the - * FitsChan ({@code W}, {@code WF}, {@code WFT}, {@code WC}, {@code WCF}, {@code RW}, {@code RCIW} - * and {@code RSW}) need {@code FitsChan.write}, which is out of scope, as do the Rust tests {@code - * excluded_cases_still_differ} (whose list holds a writing case) and {@code - * native_full_1_matches_c_but_for_process_counts} (listed in {@code deferred/rust-tests.txt}). + *

Cases whose scripts read from the FitsChan ({@code R}, {@code RN}, {@code PW}, and {@code + * RW}, {@code RCIW} and {@code RSW}, which write what they read back into it) run when their reads + * and writes need only the encodings and classes of this library. A read that reaches FITS-CLASS, + * whose read is out of scope, throws {@code UnsupportedOperationException}; the number of such + * cases is pinned by {@link #WAITING_FOR_ANOTHER_ENCODING}. A read or write that stops at another + * out-of-scope class (such as {@code needs SpecFrame}) must be in {@link #EXCLUDED} with that + * reason, measured from the exception. Cases whose scripts write an Object they make ({@code W}, + * {@code WF}, {@code WFT}, {@code WC} and {@code WCF}) run; {@code native_full_1}, whose Object + * parts C writes with counts this library does not keep, is excluded and compared without them. */ class FitsChanCursorOracleTest { - /** The operations that write to the FitsChan. */ - private static final Set WRITES = - new HashSet<>(Arrays.asList("W", "WF", "WFT", "WC", "WCF", "RW", "RCIW", "RSW")); - - /** The operations that only read from the FitsChan. */ - private static final Set READS = new HashSet<>(Arrays.asList("R", "RN", "PW")); + /** The operations that read from the FitsChan, and write what they read. */ + private static final Set READS = new HashSet<>(Arrays.asList("R", "RN", "PW", "RW", "RCIW", "RSW")); /** - * The number of cases run here: those that write no Object, are not excluded, and whose reads - * need only the NATIVE and FITS-WCS encodings. + * The number of cases run here: those that write no Object read, are not excluded, and whose reads + * need only the encodings read here. */ - private static final int RUNNABLE = 147; + private static final int RUNNABLE = 247; - /** The number of cases whose reads reach the read of an encoding other than NATIVE and FITS-WCS. */ - private static final int WAITING_FOR_ANOTHER_ENCODING = 5; + /** The number of cases whose reads reach the read of an encoding whose read is not available. */ + private static final int WAITING_FOR_ANOTHER_ENCODING = 2; /** * The start of the reason of a case whose transcript hangs on the last bit of an elementary @@ -88,15 +82,40 @@ private static Map excludedCases() { "sao_three_ctypes", "iwc_on_spectral", "iwc_off_spectral", - "iwc_on_spectral_cunit")) { + "iwc_on_spectral_cunit", + "sao_three_ctypes_rw", + "fao_spec_order")) { m.put(name, "needs SpecFrame"); } + // The absolute description of the offset SkyFrame passes C's LogAxis test on its first + // axis, so C builds the -LOG Mapping, which holds a MathMap; the description then fails + // MakeIntWorld and is not written (lldb probe s2 of the final review fixes). + m.put("alt_axes_alt_offset", "needs MathMap"); + // The Mapping C's FitLine fits for the offset coordinates, written without a projection, + // is the same as this library's (probe s1, dumps equal); of the 101 points of each grid + // axis, 81 and 67 differ, each first at a SphMap, SphMap inverse or TAN WcsMap inverse + // given equal inputs (the components whose sines, cosines and arctangents the replays for + // alt_axes_offset found 1 ULP from C's libm at equal arguments), and the slopes of the + // differences (2e-18) are the differences of the fitted gradients. + // runtimeMathCasesMatchCButForLicensedCards compares them. + m.put("sky_offset_system_rw", RUNTIME_MATH + " SphMap and TAN WcsMap transforms 1 ULP from C's libm"); + // The Mapping C's FitLine fits for the primary description is the same as this library's + // (probe a1), but its SphMaps and inverse TAN WcsMap take sines, cosines and arctangents + // where java.lang.Math differs from C's libm by 1 ULP at the same arguments (probes a2 and + // rep), so the fitted CDELT2 differs by 1 ULP. runtimeMathCasesMatchCButForLicensedCards + // compares them. + m.put("alt_axes_offset", RUNTIME_MATH + " SphMap and TAN WcsMap transforms 1 ULP from C's libm"); + m.put("alt_axes_offset_none", RUNTIME_MATH + " SphMap and TAN WcsMap transforms 1 ULP from C's libm"); // Its transcript shows the FrameSet read. The rotation of the alternate description // (fitschan.c WcsNative, three astMtrRot calls) takes the sine of 2 deg - pi/2, for which // java.lang.Math gives -0x1.ffb0278bf0566p-1 and C's libm -0x1.ffb0278bf0567p-1 (measured // on aarch64, JDK 21 and macOS libm), so the forward matrix element M2 is // 0.9992386149554825 here and 0.99923861495548261 in C. m.put("iwc_on_alt", RUNTIME_MATH + " the sine of 2 deg - pi/2 differs from C's libm by 1 ULP"); + // With Full positive C also writes the unset RefCnt and Nobj of each Object part as comment + // cards: counts of pointers to the Object and of Objects of its class, which this library + // does not keep. nativeFull1MatchesCButForProcessCounts compares the rest. + m.put("native_full_1", "RefCnt and Nobj are counts this library does not keep"); return Collections.unmodifiableMap(m); } @@ -369,6 +388,19 @@ private String op(FitsChan fc, String op) throws IOException { return ""; case "QE": return "= " + fc.getC("Encoding") + "\n"; + case "W": + return "= " + fc.write(new ZoomMap(2, 2.0)) + "\n"; + case "WF": + return "= " + fc.write(new Frame(2)) + "\n"; + case "WFT": { + Frame fr = new Frame(2); + fr.setTitle(a1); + return "= " + fc.write(fr) + "\n"; + } + case "WC": + return "= " + fc.write(new CmpMap(new ZoomMap(2, 2.0), new ZoomMap(2, 3.0), true)) + "\n"; + case "WCF": + return "= " + fc.write(new CmpFrame(new Frame(1), new Frame(1))) + "\n"; case "RDF": fc.readFits(); return ""; @@ -403,6 +435,23 @@ private String op(FitsChan fc, String op) throws IOException { "FrameSet".equals(cls) || "ZoomMap".equals(cls) || "Frame".equals(cls) || "CmpMap".equals(cls); return "= " + (named ? cls : "another class") + "\n"; } + case "RW": { + AstObject obj = fc.read(); + return obj == null ? "= null 0\n" : "= " + obj.astClass() + " " + fc.write(obj) + "\n"; + } + case "RCIW": { + AstObject obj = fc.read(); + if (obj == null) { + return "= null 0\n"; + } + ((FrameSet) obj).getFrame(Integer.parseInt(a1)).clear("Ident"); + return "= " + obj.astClass() + " " + fc.write(obj) + "\n"; + } + case "RSW": { + AstObject obj = fc.read(); + fc.setC("Warnings", a1); + return obj == null ? "= null 0\n" : "= " + obj.astClass() + " " + fc.write(obj) + "\n"; + } case "RN": { AstObject obj = fc.read(); if (obj == null) { @@ -566,7 +615,7 @@ void cardFunctionsMatchTheCLibrary() throws IOException { for (JsonNode c : ProbeData.load("fitschan_cursor").get("CASES")) { List ops = ops(c); String name = c.get(0).asText(); - if (uses(ops, WRITES) || EXCLUDED.containsKey(name)) { + if (EXCLUDED.containsKey(name)) { continue; } String want = c.get(2).asText(); @@ -604,6 +653,104 @@ void cardFunctionsMatchTheCLibrary() throws IOException { "cases waiting for the read of another encoding: " + waitingCases); } + /** + * The cards of each case excluded for {@value #RUNTIME_MATH} whose values may differ from C's + * within libm rounding: a difference of at most {@link #LIBM_RTOL} relative to the value, or, + * for an element of the PC matrix, whose diagonal elements are 1, relative to 1. + */ + private static final Map> RUNTIME_MATH_CARDS = runtimeMathCards(); + + /** The relative difference of a value computed with java.lang.Math from C's libm value. */ + private static final double LIBM_RTOL = 1.0e-14; + + private static Map> runtimeMathCards() { + Map> m = new LinkedHashMap<>(); + m.put("alt_axes_offset", Arrays.asList("CDELT2", "CDELT2A")); + m.put("alt_axes_offset_none", Arrays.asList("CDELT2")); + m.put("sky_offset_system_rw", Arrays.asList("CDELT1", "CDELT2", "PC1_2", "PC2_1")); + return Collections.unmodifiableMap(m); + } + + /** + * The cases whose cards C computes with elementary functions of its libm match C's transcript + * line for line, but for the values of the named cards, which are within {@link #LIBM_RTOL}. + */ + @Test + void runtimeMathCasesMatchCButForLicensedCards() throws IOException { + List failed = new ArrayList<>(); + for (Map.Entry> e : RUNTIME_MATH_CARDS.entrySet()) { + assertTrue(EXCLUDED.get(e.getKey()).startsWith(RUNTIME_MATH), e.getKey()); + JsonNode c = findCase(e.getKey()); + List g = CValues.lines(transcript(ops(c))); + List w = CValues.lines(c.get(2).asText()); + if (g.size() != w.size()) { + failed.add(e.getKey() + ": " + g.size() + " lines, C " + w.size()); + continue; + } + for (int i = 0; i < g.size(); i++) { + if (!g.get(i).equals(w.get(i)) && !withinLibmRounding(g.get(i), w.get(i), e.getValue())) { + failed.add(e.getKey() + " line " + (i + 1) + ":\n" + g.get(i) + "\n" + w.get(i)); + } + } + } + assertTrue(failed.isEmpty(), String.join("\n", failed)); + } + + /** Whether two transcript lines are the same card of {@code keys} with values within libm rounding. */ + private static boolean withinLibmRounding(String got, String want, List keys) { + if (!got.startsWith("|") || !want.startsWith("|") || got.length() < 9 || want.length() < 9) { + return false; + } + String key = got.substring(1, 9).trim(); + if (!keys.contains(key) || !got.substring(0, 11).equals(want.substring(0, 11))) { + return false; + } + int gs = got.indexOf(" /"); + int ws = want.indexOf(" /"); + // A value of another length moves the comment, so the padding after it differs. + if (gs < 0 + || ws < 0 + || !got.substring(gs).trim().equals(want.substring(ws).trim())) { + return false; + } + double g = Double.parseDouble(got.substring(11, gs).trim()); + double w = Double.parseDouble(want.substring(11, ws).trim()); + double scale = key.startsWith("PC") ? Math.max(Math.abs(w), 1.0) : Math.abs(w); + return Math.abs(g - w) <= LIBM_RTOL * scale; + } + + /** + * Case {@code native_full_1} with C's {@code REFCNT} and {@code NOBJ} comment cards left out, + * and the card counts that include them: everything else C writes with Full positive, every + * unset value and every {@code IsA} marker, matches. + */ + @Test + void nativeFull1MatchesCButForProcessCounts() throws IOException { + JsonNode c = findCase("native_full_1"); + String want = c.get(2).asText(); + int refcnt = 0; + for (String line : CValues.lines(want)) { + if (line.startsWith("|COMMENT REFCNT_")) { + refcnt++; + } + } + // The Frame and its two Axes each have an Object part. + assertEquals(3, refcnt); + assertEquals(withoutProcessCounts(want), withoutProcessCounts(transcript(ops(c)))); + } + + private static List withoutProcessCounts(String transcript) { + List out = new ArrayList<>(); + for (String line : CValues.lines(transcript)) { + if (!line.startsWith("card=") + && !line.startsWith("|COMMENT REFCNT_") + && !line.startsWith("|COMMENT NOBJ_")) { + out.add(line); + } + } + return out; + } + private static String context(List lines, int at) { return String.join("\n", lines.subList(Math.max(0, at - 3), Math.min(lines.size(), at + 3))); } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsOracleTest.java new file mode 100644 index 0000000..8f9ba5d --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsOracleTest.java @@ -0,0 +1,220 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_fitschan_encodings_oracle.rs}: what each FITS encoding + * writes for a set of headers, against C's. Each header is read into a FrameSet, which is written + * back to the same FitsChan with each encoding in turn, some cases first setting the FrameSet's + * Epoch, or its SkyRef and SkyRefIs. Each encoding's writer writes nothing for a description it + * cannot hold, and the write then leaves every card the FitsChan had, those the read consumed + * included. + * + *

For each header and encoding, compared with C: the value the write returns, Ncard, the cards + * not used, and the name of every card, from a native dump of the FitsChan. The cases are those of + * {@code oracle/fitschan_encodings.json}, made by {@code + * tools/oracle_fixtures/fitschan_encodings_probe.c}. + * + *

Every encoding's column runs; C's FITS-CLASS writer refuses each FrameSet here, none having + * the SpecFrame that encoding needs. A header whose read needs a class this library does not have + * is in {@link #EXCLUDED} with the reason its read gives, measured, so the list is checked both + * ways. + */ +class FitsChanEncodingsOracleTest { + + /** Headers whose read stops for want of a class, with the reason the read gives. */ + private static final Map EXCLUDED = excludedCases(); + + private static Map excludedCases() { + Map m = new LinkedHashMap<>(); + for (String name : Arrays.asList( + "freq_cube", + "class_cube", + "class_lonpole_180", + "class_lonpole_90", + "class_new_epoch", + "source_zsource", + "topocent", + "velolsr_late", + "velolsr_dup")) { + m.put(name, "needs SpecFrame"); + } + return Collections.unmodifiableMap(m); + } + + /** + * The keywords whose numbers depend on the runtime's elementary functions, by header, for the + * FITS-WCS write. Setting SkyRef and SkyRefIs builds the same Mappings as C (the MatrixMaps + * agree to the last bit), but the transforms through them differ from C's by 1 ULP, as + * java.lang.Math's atan2 does from C's libm (atan2(0.3420201433256688, 0.9396926207859083) is + * 0.34906585039886606 here and 0.349065850398866 in libm); {@code FitLine}'s least-squares + * fit raises that to 1e-16 in the PC elements, small differences of terms of order 1 (C probe + * {@code p5.c}, beside the task report). Rust licenses the same two writes + * ({@code SPHMAP_DRIFT_LICENSED}). + */ + private static final Map> RUNTIME_MATH = runtimeMath(); + + private static Map> runtimeMath() { + Map> m = new HashMap<>(); + m.put("tan_offset_origin", new HashSet<>(Arrays.asList("PC1_2", "PC2_1"))); + m.put("tan_offset_pole", new HashSet<>(Arrays.asList("CRVAL2", "PC1_1", "PC1_2", "PC2_1", "PC2_2"))); + return Collections.unmodifiableMap(m); + } + + /** + * The DSS cards whose numbers depend on the runtime's elementary functions, by header, with + * the absolute tolerance each is compared with. DSS writes the reference point as degrees (or + * hours), minutes and seconds, so PLTRAS and PLTDECS hold the difference of CRVAL1 / 15 or + * CRVAL2 from a whole number, times 3600: there, a difference of CRVAL in its last bits is + * the number's leading digits. CRVAL is made as C makes it but for java.lang.Math's atan2, + * which differs from C's libm by 1 ULP at identical arguments: in the forward SphMap ({@code + * atan2(0.34202014332566877, 0.9396926207859083)}, 0x3fd657184ae74489 here and + * 0x3fd657184ae74488 in libm, which is correctly rounded), and for the headers whose Epoch is + * set, also in the FK5HZ step of the SlaMap that follows ({@code eraFk5hz}'s {@code eraC2s}, + * 0x3fc65716f92aed2c here and 0x3fc65716f92aed2b in libm); every other operation agrees to + * the bit (C probes {@code p3.c}, {@code rep.c} and {@code at.c} of Task 9, beside the task + * report). C's store then holds CRVAL (10, 20) one or two ULP from this library's, which the + * FITS-WCS cards absorb. The tolerance is the difference 4 ULP of CRVAL (10, 20) makes, the + * difference the cards of the wcsconv gate allow CRVAL itself: 4 ULP of 10 degrees times 240 + * seconds of time per degree, and 4 ULP of 20 degrees times 3600 arcseconds per degree. + */ + private static final Map> DSS_RUNTIME_MATH = dssRuntimeMath(); + + private static Map> dssRuntimeMath() { + Map sexagesimal = new HashMap<>(); + sexagesimal.put("PLTRAS", 4 * Math.ulp(10.0) * 240.0); + sexagesimal.put("PLTDECS", 4 * Math.ulp(20.0) * 3600.0); + Map> m = new HashMap<>(); + for (String name : + Arrays.asList("tan_fk5", "tpn", "alt_pc", "alt_j", "tan_new_epoch", "tan_new_epoch_no_mjd", "cname")) { + m.put(name, Collections.unmodifiableMap(sexagesimal)); + } + return Collections.unmodifiableMap(m); + } + + /** The outcome of one write, in the form C's probe prints it. */ + private static final class Written { + final int ret; + final int ncard; + final List cards; + final List names; + + Written(int ret, int ncard, List cards, List names) { + this.ret = ret; + this.ncard = ncard; + this.cards = cards; + this.names = names; + } + + @Override + public String toString() { + return "wrote " + ret + ", Ncard " + ncard + "\n" + String.join("\n", cards) + "\nnames " + names; + } + } + + /** The FrameSet {@code header} reads as, after the case's change of Epoch or SkyRef. */ + private static AstObject read(FitsChan fc, List header, String epoch) { + for (String card : header) { + fc.putFits(card, false); + } + fc.clear("Card"); + AstObject fs = fc.read(); + if (fs != null && epoch.startsWith("SKYREF ")) { + // SkyRef(1), SkyRef(2) and SkyRefIs, each set through the FrameSet, one at a time. + String[] words = CValues.splitWhitespace(epoch.substring(7)); + fs.setD("SkyRef(1)", Double.parseDouble(words[0])); + fs.setD("SkyRef(2)", Double.parseDouble(words[1])); + fs.setC("SkyRefIs", words[2]); + } else if (fs != null && !epoch.isEmpty()) { + fs.setC("Epoch", epoch); + } + return fs; + } + + /** The header written with {@code enc} into the FitsChan it was read from. */ + private static Written written(List header, String epoch, String enc) { + FitsChan fc = new FitsChan(); + AstObject fs = read(fc, header, epoch); + fc.setEncoding(enc); + int ret = fs != null ? fc.write(fs) : -1; + int ncard = fc.getNcard(); + List cards = FitsHeaders.foundCards(fc); + List names = new ArrayList<>(); + for (String line : CValues.lines(ChannelText.dump(fc))) { + if (line.startsWith(" Nm")) { + int q = line.indexOf('"'); + names.add(line.substring(q + 1, line.indexOf('"', q + 1))); + } + } + return new Written(ret, ncard, cards, names); + } + + /** The reason the read of {@code header} stops for want of a class, or null. */ + private static String readNeeds(List header) { + try { + read(new FitsChan(), header, ""); + return null; + } catch (UnsupportedOperationException e) { + return FitsHeaders.outOfScope(e); + } + } + + @Test + void writesMatchC() { + List failed = new ArrayList<>(); + int run = 0; + for (JsonNode c : ProbeData.load("fitschan_encodings").get("CASES")) { + String name = c.get(0).asText(); + List header = FitsHeaders.strings(c.get(1)); + String epoch = c.get(2).asText(); + String needs = readNeeds(header); + String listed = EXCLUDED.get(name); + if (needs != null || listed != null) { + if (needs == null || !needs.equals(listed)) { + failed.add(name + ": the read gives \"" + needs + "\" but it is listed as \"" + listed + "\""); + } + continue; + } + for (JsonNode w : c.get(3)) { + String enc = w.get(0).asText(); + run++; + Written want = new Written( + w.get(1).asInt(), + w.get(2).asInt(), + FitsHeaders.strings(w.get(3)), + FitsHeaders.strings(w.get(4))); + Written got = written(header, epoch, enc); + boolean same = got.ret == want.ret + && got.ncard == want.ncard + && got.names.equals(want.names) + && FitsHeaders.cardsMatchC( + got.cards, + want.cards, + RUNTIME_MATH.getOrDefault(name, Collections.emptySet()), + "DSS".equals(enc) + ? DSS_RUNTIME_MATH.getOrDefault(name, Collections.emptyMap()) + : Collections.emptyMap()); + if (!same) { + failed.add(name + " " + enc + ":\n--- Java\n" + got + "\n--- C\n" + want); + } + } + } + assertTrue(failed.isEmpty(), String.join("\n", failed)); + assertEquals(7 * (25 - EXCLUDED.size()), run, "writes run, seven encodings for each header"); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsTest.java new file mode 100644 index 0000000..1969cbe --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsTest.java @@ -0,0 +1,96 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** + * Translation of Rust {@code tests/test_fitschan_encodings.rs}: the encoding a FitsChan guesses for + * a header of each encoding, and the FrameSets the FITS-IRAF, FITS-PC and DSS reads give. Each + * fixture line is given to {@code putFits}, and the values expected are those C gives (probe + * {@code c2.c} beside the task report). + * + *

{@code read_dss_produces_frameset} is translated in {@link FitsEncDssTest}. Listed in {@code + * deferred/rust-tests.txt}: {@code read_aips_spectral} (a spectral axis, SpecFrame), {@code + * read_class_produces_frameset} (the FITS-CLASS read), {@code freq_log_builds_log_mapping} + * (MathMap and SpecFrame) and {@code grism_builds_grism_mapping} (SpecFrame and GrismMap). + */ +class FitsChanEncodingsTest { + + private static void assertGuess(String rel, String encoding) { + assertEquals(encoding, FitsHeaders.fixture(rel).getEncoding(), rel); + } + + /** The FrameSet read from {@code rel} with {@code encoding} set. */ + private static FrameSet read(String rel, String encoding) { + FitsChan fc = FitsHeaders.fixture(rel); + fc.setEncoding(encoding); + return FitsHeaders.readFrameSet(fc); + } + + /** A FrameSet of two Frames whose current Frame has two axes and the System {@code system}. */ + private static void assertSky(FrameSet fs, String system) { + assertEquals(2, fs.getNframe()); + assertEquals(2, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + assertEquals(system, fs.getC("System")); + } + + @Test + void guessEncodingIraf() { + // CDi_j keywords and RADECSYS. + assertGuess("wcsconv/inputs/serpens.head", "FITS-IRAF"); + } + + @Test + void guessEncodingPc() { + // PC001001. + assertGuess("wcsconv/inputs/pc-sparse.head", "FITS-PC"); + } + + @Test + void guessEncodingAips() { + // An AIPS spectral CTYPE (VELO-LSR). + assertGuess("wcsconv/inputs/velo-aips.head", "FITS-AIPS"); + } + + @Test + void guessEncodingClass() { + // DELTAV and VELO-LSR. + assertGuess("wcsconv/inputs/class-write.head", "FITS-CLASS"); + } + + @Test + void guessEncodingDss() { + // PLTRAH. + assertGuess("wcsconv/expected/dss.dss", "DSS"); + } + + @Test + void readIrafProducesFrameSet() { + FrameSet fs = read("wcsconv/inputs/serpens.head", "FITS-IRAF"); + assertEquals(2, fs.getNframe()); + assertEquals(2, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + } + + @Test + void readPcProducesFrameSet() { + FrameSet fs = read("wcsconv/inputs/pc-sparse.head", "FITS-PC"); + assertEquals(2, fs.getNframe()); + assertEquals(2, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + } + + @Test + void irafFrameSetHasSky() { + assertSky(read("wcsconv/inputs/serpens.head", "FITS-IRAF"), "FK5"); + } + + @Test + void pcFrameSetHasSky() { + assertSky(read("wcsconv/inputs/pc-sparse.head", "FITS-PC"), "FK5"); + } + + @Test + void dssFrameSetHasSky() { + assertSky(read("wcsconv/expected/dss.dss", "DSS"), "FK5"); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java index 4f0c3b9..67b3d54 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java @@ -27,10 +27,8 @@ * {@code error-set-readonly}) run here; {@code excluded_cases_are_in_the_c_table} has no * counterpart, since none of those is excluded. * - *

A case naming a write encoding ({@code write_enc}) is checked by C writing the FrameSet read to - * that encoding, which must refuse it, and to FITS-WCS, which must accept it; {@code - * FitsChan.write} is out of scope, so those cases are run up to the read and the writes are left - * out. A case whose read stops at something out of scope ({@code UnsupportedOperationException}) + *

A case naming a write encoding ({@code write_enc}) is checked by writing the FrameSet read to + * that encoding, which must refuse it, and to FITS-WCS, which must accept it, as C does. A case whose read stops at something out of scope ({@code UnsupportedOperationException}) * cannot be compared with C, and is in {@link #EXCLUDED} with the reason measured from the * exception; {@code port_gap_cases_still_differ} becomes {@code excludedCasesStillDiffer}, which * checks every excluded case still differs from C, for that reason where it is measured. @@ -121,9 +119,10 @@ private static String check(JsonNode c) { } } AstException readError = null; + AstObject obj = null; if (!c.get("skip_read").asBoolean()) { try { - fc.read(); + obj = fc.read(); } catch (AstException e) { readError = e; } catch (UnsupportedOperationException e) { @@ -159,8 +158,23 @@ private static String check(JsonNode c) { } return null; } - // A write_enc case goes on in C to write the FrameSet read (testfitschanerrors.c - // test_bad_header); FitsChan.write is out of scope, so that is left out. + // A write_enc case goes on in C to write the Object read (testfitschanerrors.c + // test_bad_header): its encoding must refuse it, and FITS-WCS must accept it. + String writeEnc = text(c, "write_enc"); + if (writeEnc != null && obj != null) { + FitsChan wfc = new FitsChan(); + wfc.setEncoding(writeEnc); + int nw = wfc.write(obj); + if (nw != 0) { + return "write to " + writeEnc + " returned " + nw + ", expected 0"; + } + wfc.emptyFits(); + wfc.setEncoding("FITS-WCS"); + nw = wfc.write(obj); + if (nw != 1) { + return "write to FITS-WCS returned " + nw + ", expected 1"; + } + } return null; } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanModuleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanModuleTest.java index a728846..2f7471e 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanModuleTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanModuleTest.java @@ -5,13 +5,13 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import org.junit.jupiter.api.Test; /** * Translation of the card unit tests of Rust {@code fitschan/mod.rs}. - * - *

{@code native_round_trip} and {@code rewrite_after_read_re_emits_wcs_cards} write to the - * FitsChan and are listed in {@code deferred/rust-tests.txt}. */ class FitsChanModuleTest { @@ -25,6 +25,19 @@ void newFitschanIsEmpty() { assertEquals(17, fc.getFitsDigits()); } + @Test + void nativeRoundTrip() { + FitsChan fc = new FitsChan(); + fc.setEncoding("NATIVE"); + assertEquals(1, fc.write(new ZoomMap(2, 3.5))); + assertTrue(fc.getNcard() > 0); + + fc.clear("Card"); + AstObject obj = fc.read(); + assertNotNull(obj); + assertEquals(2, ((Mapping) obj).getNin()); + } + @Test void fromHeaderCreatesFitschan() { FitsChan fc = FitsChan.fromHeader("SIMPLE = T / Fits standard\n" @@ -216,6 +229,51 @@ void protectedCardSurvivesRead() { assertFalse(out.contains("CRVAL2"), "CRVAL2 should be consumed:\n" + out); } + /** + * The cards a read consumed are written again when the FrameSet read is written FITS-WCS into + * the same FitsChan: C puts each card back where the read found it, with its comment, and + * keeps MJD-OBS, which it does not write again (probe {@code c1.c} beside the task report). + */ + @Test + void rewriteAfterReadReEmitsWcsCards() { + FitsChan fc = FitsChan.fromHeader(WCS_HEADER_WITH_MJDOBS); + AstObject obj = fc.read(); + assertNotNull(obj, "reads a FrameSet"); + fc.setEncoding("FITS-WCS"); + assertEquals(1, fc.write(obj)); + assertEquals( + Arrays.asList( + "SIMPLE = T / Fits standard", + "BITPIX = -32 / Bits per pixel", + "NAXIS = 2 / Number of axes", + "NAXIS1 = 100 / Axis 1 length", + "NAXIS2 = 100 / Axis 2 length", + "MJD-OBS = 51544.5 / MJD of observation", + "CTYPE1 = 'RA---TAN' / X type", + "CTYPE2 = 'DEC--TAN' / Y type", + "CRVAL1 = 10.0 / Reference value", + "CRVAL2 = 20.0 / Reference value", + "CRPIX1 = 50.5 / Reference pixel", + "CRPIX2 = 50.5 / Reference pixel", + "CDELT1 = -0.1 / Degrees/pixel", + "CDELT2 = 0.1 / Degrees/pixel", + "RADESYS = 'ICRS ' / Reference frame for RA/DEC values", + "END"), + trimmed(FitsHeaders.foundCards(fc))); + } + + private static List trimmed(List cards) { + List out = new ArrayList<>(); + for (String c : cards) { + int end = c.length(); + while (end > 0 && c.charAt(end - 1) == ' ') { + end--; + } + out.add(c.substring(0, end)); + } + return out; + } + /** {@code s} padded with spaces to 80 characters. */ static String pad(String s) { StringBuilder sb = new StringBuilder(s); diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanNativeWriteTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanNativeWriteTest.java new file mode 100644 index 0000000..3aa33fa --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanNativeWriteTest.java @@ -0,0 +1,515 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * Translation of the write-side unit tests of Rust {@code fitschan/enc_native.rs}: the keyword-card + * form of the NATIVE encoding a FitsChan writes (fitschan.c {@code CreateKeyword}, {@code + * MakeBanner}, {@code PreQuote}, {@code WriteString} and the other Channel {@code Write} + * overrides), with tests of {@link FitsChan#write} itself whose expected cards come from the C + * library. + * + *

The Rust port builds the cards in a list and inserts them into the FitsChan at the end; here + * they are stored in the FitsChan one at a time, as C stores them, so the tests look at the + * FitsChan's cards. + */ +class FitsChanNativeWriteTest { + + /** The cards of {@code fc} a read has not consumed, formatted, as C's {@code astFindFits} gives them. */ + private static List cards(FitsChan fc) { + int icard = fc.getCard(); + fc.clear("Card"); + List out = new ArrayList<>(); + String card; + while ((card = fc.findFits("%f", true)) != null) { + out.add(card); + } + fc.setCard(icard); + return out; + } + + /** {@code text} padded with blanks to a card's 80 characters. */ + private static String pad(String text) { + StringBuilder sb = new StringBuilder(text); + while (sb.length() < FitsCard.FITS_CARD_LEN) { + sb.append(' '); + } + return sb.toString(); + } + + private static List padded(String... lines) { + List out = new ArrayList<>(); + for (String l : lines) { + out.add(pad(l)); + } + return out; + } + + // ----------------------------------------------------------------- + // Keyword-card writer (CreateKeyword, MakeBanner, PreQuote, WriteString) + // ----------------------------------------------------------------- + + @Test + void createKeywordSequencesPerBase() { + FitsNativeWriter seq = new FitsNativeWriter(new FitsChan()); + // First use of each base starts at suffix `_A` (seq = 1). + assertEquals("BEGAST_A", seq.createKeyword("BEGAST")); + assertEquals("BEGAST_B", seq.createKeyword("BEGAST")); + assertEquals("BEGAST_C", seq.createKeyword("BEGAST")); + // A different base keeps its own counter. + assertEquals("ISA_A", seq.createKeyword("ISA")); + assertEquals("BEGAST_D", seq.createKeyword("BEGAST")); + // Long names are truncated to FITSNAMLEN - 2 = 6 characters. + assertEquals("MATRIX_A", seq.createKeyword("MatrixMap")); + } + + @Test + void createKeywordWrapsAfterFirstBlock() { + FitsNativeWriter seq = new FitsNativeWriter(new FitsChan()); + // 26 second characters after '_': seq 1..=26 map to _A.._Z, then the high character + // advances (seq 27 -> "A_"). + String last = ""; + for (int i = 0; i < 27; i++) { + last = seq.createKeyword("X"); + } + assertEquals("XA_", last); + } + + @Test + void makeBannerCentresTextWithAstTokens() { + String b = FitsNativeWriter.makeBanner("Beginning of AST data for ", "FrameSet", " object"); + // 72 columns in all, with the AST token at each end. + assertEquals(72, b.length()); + assertTrue(b.startsWith("AST")); + assertTrue(b.endsWith("AST")); + assertTrue(b.contains("Beginning of AST data for FrameSet object")); + } + + /** Write a small object tree to keyword cards and read it straight back. */ + @Test + void writeKeywordNativeRoundTrips() { + NativeNode inner = new NativeNode("UnitMap", "Unit (null) Mapping"); + inner.writeInt("Nin", true, true, 2, "Number of input coordinates"); + inner.writeIsA("Mapping", "Mapping between coordinate systems"); + + NativeNode outer = new NativeNode("CmpMap", "Compound Mapping"); + outer.writeInt("Nin", true, true, 2, "Number of input coordinates"); + outer.writeDouble("Zoom", true, true, 5.5, "Zoom factor"); + outer.writeIsA("Mapping", "Mapping between coordinate systems"); + outer.writeObject("MapA", true, true, inner, "First component Mapping"); + + FitsChan fc = new FitsChan(); + fc.setFull(-1); + new FitsNativeWriter(fc).writeObject(outer, -1, false); + + // The first card opens the outer object; the last closes it. + List block = fc.cards().cards(); + assertEquals("BEGAST_A", block.get(0).keyword); + assertEquals("CmpMap", block.get(0).value.s); + assertTrue(block.get(block.size() - 1).keyword.startsWith("ENDAST")); + + // Read the cards back, from the first, as the data items of a Channel read. + fc.clear("Card"); + FitsNativeReader r = new FitsNativeReader(fc.cards(), 10); + List items = new ArrayList<>(); + NativeStream.Datum d = r.next(true, new ArrayList<>()); + while (d != null) { + items.add(d.name + "=" + d.val); + d = r.next(false, new ArrayList<>()); + } + assertEquals( + Arrays.asList( + "begin=CmpMap", + "nin=2", + "zoom=5.5", + "isa=Mapping", + "mapa=null", + "begin=UnitMap", + "nin=2", + "isa=Mapping", + "end=UnitMap", + "end=CmpMap"), + items); + } + + @Test + void preQuoteEmptyValueIsTwoDoubleQuotes() { + // C PreQuote initialises dquotes = 2 and the loop never runs, so a zero-length value is + // given as "". + assertEquals("\"\"", FitsNativeWriter.preQuote("")); + } + + @Test + void preQuoteTruncatesAtTheFitsValueLimit() { + // The accommodation test is nc + 1 + dq + sq > AST__FITSCHAN_FITSCARDLEN - FITSNAMLEN - 4, + // i.e. > 68 for the standard 80/8 card layout. + assertEquals(repeat('x', 68), FitsNativeWriter.preQuote(repeat('x', 80))); + // Each single quote will be doubled by the card formatter, so it costs two of the 68 + // columns. + assertEquals(repeat('\'', 34), FitsNativeWriter.preQuote(repeat('\'', 80))); + } + + @Test + void preQuoteUsesTheLastAccommodatedCharacter() { + // Trailing white space that is truncated away does not force quotes, because dquotes + // tracks the last accepted character. + assertEquals(repeat('y', 68), FitsNativeWriter.preQuote(repeat('y', 68) + " ")); + // Trailing white space that survives does force them. + assertEquals("\"z \"", FitsNativeWriter.preQuote("z ")); + } + + @Test + void preQuoteUnPreQuoteRoundTrip() { + for (String v : Arrays.asList("", "z ", "\"lead", "plain", "a\"b")) { + String q = FitsNativeWriter.preQuote(v); + assertEquals(v, FitsNativeReader.unPreQuote(q), "round trip failed for " + v); + } + } + + /** + * A long string value is split across CONTINUE cards with a trailing ampersand on each card + * but the last, as C's {@code WriteString} does. + */ + @Test + void writeStringValueSplitsLongStrings() { + FitsChan fc = new FitsChan(); + String text = "Pixel coordinates; first pixel at (-128.5,-127.5) plus padding"; + new FitsNativeWriter(fc).writeString("Title", true, text, "Title"); + List block = fc.cards().cards(); + assertTrue(block.size() >= 2, "a long value is split"); + // The first card holds the keyword and ends with an ampersand. + assertEquals("TITLE_A", block.get(0).keyword); + assertEquals(FitsCard.Kind.STRING, block.get(0).value.kind); + assertTrue(block.get(0).value.s.endsWith("&"), block.get(0).value.s); + // The cards after it are CONTINUE cards. + assertEquals("CONTINUE", block.get(1).keyword); + } + + /** C's {@code WriteString} loops while characters remain, so an empty value writes no card. */ + @Test + void writeStringValueWritesNothingForAnEmptyValue() { + FitsChan fc = new FitsChan(); + new FitsNativeWriter(fc).writeString("Title", true, "", "Title"); + assertEquals(0, fc.cards().len()); + } + + // ----------------------------------------------------------------- + // FitsChan.write with the NATIVE encoding; the expected cards are those the C library writes + // (oracle/fitschan_cursor.json, from tools/oracle_fixtures/fitschan_cursor_probe.c) + // ----------------------------------------------------------------- + + /** The cards C writes for {@code astZoomMap( 2, 2.0, " " )} with keyword suffix {@code zoom}. */ + private static List zoomMapCards(String zoom) { + return padded( + "", + "COMMENT AST ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AST", + "COMMENT AST Beginning of AST data for ZoomMap object AST", + "COMMENT AST ................................................................ AST", + "BEGAST_A= 'ZoomMap ' / Zoom about the origin", + "NIN_A = 2 / Number of input coordinates", + "ISA_A = 'Mapping ' / Mapping between coordinate systems", + "ZOOM_" + zoom + " = 2.0 / Zoom factor", + "ENDAST_A= 'ZoomMap ' / End of object definition", + "COMMENT AST ................................................................ AST", + "COMMENT AST End of AST data for ZoomMap object AST", + "COMMENT AST ---------------------------------------------------------------- AST"); + } + + /** + * C's {@code CreateKeyword} passes over a keyword a card already has: with a {@code ZOOM_A} + * card present the ZoomMap's zoom factor is {@code ZOOM_B} (case {@code + * native_write_after_duplicate_delete}, where the card left after deleting one of two {@code + * ZOOM_A} cards still holds the keyword). + */ + @Test + void createKeywordPassesOverKeywordsPresent() { + FitsChan fc = new FitsChan(); + fc.setEncoding("NATIVE"); + fc.putFits("ZOOM_A = 1", false); + fc.putFits("ZOOM_A = 2", false); + fc.clear("Card"); + fc.delFits(); + fc.setCard(2); + assertEquals(1, fc.write(new ZoomMap(2, 2.0))); + List want = new ArrayList<>(); + want.add(pad("ZOOM_A = 2")); + want.addAll(zoomMapCards("B")); + assertEquals(want, cards(fc)); + assertEquals(14, fc.getCard()); + } + + /** + * The cards go in front of the current card, which stays current (case {@code + * write_inserts_before_current}). + */ + @Test + void writeInsertsBeforeTheCurrentCard() { + FitsChan fc = new FitsChan(); + fc.putFits("A = 1", false); + fc.putFits("B = 2", false); + fc.putFits("C = 3", false); + fc.setCard(2); + assertEquals(1, fc.write(new ZoomMap(2, 2.0))); + List want = new ArrayList<>(); + want.add(pad("A = 1")); + want.addAll(zoomMapCards("A")); + want.add(pad("B = 2")); + want.add(pad("C = 3")); + assertEquals(want, cards(fc)); + assertEquals(14, fc.getCard()); + assertEquals("B", fc.getC("CardName")); + } + + /** + * The FitsChan keeps the last sequence number of each keyword from one write to the next + * (C's {@code keyseq}), so a second Object's keywords follow the first's (case {@code + * native_two_objects}). + */ + @Test + void sequenceNumbersPersistFromOneWriteToTheNext() { + FitsChan fc = new FitsChan(); + fc.setEncoding("NATIVE"); + fc.write(new ZoomMap(2, 2.0)); + fc.write(new ZoomMap(2, 2.0)); + List got = cards(fc); + assertTrue(got.contains(pad("BEGAST_B= 'ZoomMap ' / Zoom about the origin")), got.toString()); + assertTrue(got.contains(pad("ZOOM_B = 2.0 / Zoom factor")), got.toString()); + assertTrue(got.contains(pad("ENDAST_B= 'ZoomMap ' / End of object definition")), got.toString()); + // A copy keeps the sequence numbers, as C's astCopy copies keyseq. + FitsChan copy = (FitsChan) fc.copy(); + copy.write(new ZoomMap(2, 2.0)); + assertTrue(cards(copy).contains(pad("ZOOM_C = 2.0 / Zoom factor"))); + } + + /** + * With Comment clear there are no banners and no comments, but the first card of a string still + * leaves room for its comment, and a nested Object's card is a blank string (case {@code + * native_long_title_no_comments}). + */ + @Test + void noCommentsStillReservesRoomForTheComment() { + FitsChan fc = new FitsChan(); + fc.setComment(false); + Frame fr = new Frame(2); + fr.setTitle(repeat('t', 100)); + assertEquals(1, fc.write(fr)); + assertEquals( + padded( + "BEGAST_A= 'Frame '", + "TITLE_A = 'tttttttttttttttttttttttttttttttttttt&'", + "CONTINUE 'tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt'", + "NAXES_A = 2", + "AX1_A = ' '", + "BEGAST_B= 'Axis '", + "ENDAST_A= 'Axis '", + "AX2_A = ' '", + "BEGAST_C= 'Axis '", + "ENDAST_B= 'Axis '", + "ENDAST_C= 'Frame '"), + cards(fc)); + AstObject back = readBack(fc); + assertEquals(repeat('t', 100), ((Frame) back).getTitle()); + } + + /** + * With Full 0 nested Objects and class boundaries are marked by indented comment cards with a + * blank keyword (case {@code native_full_0_nested}). + */ + @Test + void fullZeroMarksNestedObjects() { + FitsChan fc = new FitsChan(); + fc.setFull(0); + assertEquals(1, fc.write(new CmpMap(new ZoomMap(2, 2.0), new ZoomMap(2, 3.0), true))); + assertEquals( + padded( + "", + "COMMENT AST ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AST", + "COMMENT AST Beginning of AST data for CmpMap object AST", + "COMMENT AST ................................................................ AST", + "BEGAST_A= 'CmpMap ' / Compound Mapping", + "NIN_A = 2 / Number of input coordinates", + "ISA_A = 'Mapping ' / Mapping between coordinate systems", + " ... / Class boundary", + "MAPA_A = ' ' / First component Mapping", + " ++++++ / Beginning of ZoomMap", + "BEGAST_B= 'ZoomMap ' / Zoom about the origin", + "NIN_B = 2 / Number of input coordinates", + "ISA_B = 'Mapping ' / Mapping between coordinate systems", + " ...... / Class boundary", + "ZOOM_A = 2.0 / Zoom factor", + "ENDAST_A= 'ZoomMap ' / End of object definition", + " ------ / End of ZoomMap", + "MAPB_A = ' ' / Second component Mapping", + " ++++++ / Beginning of ZoomMap", + "BEGAST_C= 'ZoomMap ' / Zoom about the origin", + "NIN_C = 2 / Number of input coordinates", + "ISA_C = 'Mapping ' / Mapping between coordinate systems", + " ...... / Class boundary", + "ZOOM_B = 3.0 / Zoom factor", + "ENDAST_B= 'ZoomMap ' / End of object definition", + " ------ / End of ZoomMap", + "ENDAST_C= 'CmpMap ' / End of object definition", + "COMMENT AST ................................................................ AST", + "COMMENT AST End of AST data for CmpMap object AST", + "COMMENT AST ---------------------------------------------------------------- AST"), + cards(fc)); + assertEquals("CmpMap", readBack(fc).astClass()); + } + + /** + * An unset value written because Full is positive becomes a COMMENT card holding the text of + * the card (C's {@code MakeIntoComment}); the lines are from case {@code native_full_1}. + */ + @Test + void unsetValuesBecomeCommentCards() { + FitsChan fc = new FitsChan(); + fc.setFull(1); + assertEquals(1, fc.write(new Frame(2))); + List got = cards(fc); + for (String want : padded( + "COMMENT TITLE_A = '2-d coordinate system' / Title of coordinate system", + "NAXES_A = 2 / Number of coordinate axes", + "COMMENT BOT1_A = -1.7976931348623157E+308 / Lowest legal axis value", + "COMMENT LABEL_A = 'Coordinate axis' / Axis Label", + " ++++++ / Beginning of Axis")) { + assertTrue(got.contains(want), want + " in " + got); + } + } + + // ----------------------------------------------------------------- + // The write entry + // ----------------------------------------------------------------- + + /** + * An encoding other than NATIVE describes only a FrameSet: C's {@code Write} writes nothing for + * any other Object, returns 0 and leaves the cards and the current card as they were. + */ + @Test + void foreignEncodingWritesNoOtherObject() { + FitsChan fc = new FitsChan(); + fc.putFits("A = 1", false); + fc.putFits("B = 2", false); + fc.setCard(2); + fc.setEncoding("FITS-WCS"); + assertEquals(0, fc.write(new ZoomMap(2, 2.0))); + assertEquals(padded("A = 1", "B = 2"), cards(fc)); + assertEquals(2, fc.getCard()); + } + + /** + * A write the encoding cannot make returns 0 and leaves the cards and the current card as they + * were (C's {@code FixNew}), whatever the hook for that encoding did to them. + */ + @Test + void failedForeignWriteRollsBackItsCards() { + FitsChan fc = new FitsChan() { + @Override + boolean writeForeign(FrameSet fs, FitsChan.Encoding enc) { + setFits("NEW1", 1, null, false); + cards().setPosition(0); + setFits("NEW2", 2, null, false); + return false; + } + }; + fc.putFits("A = 1", false); + fc.putFits("B = 2", false); + fc.setCard(2); + fc.setEncoding("FITS-WCS"); + assertEquals(0, fc.write(new FrameSet(new Frame(2)))); + assertEquals(padded("A = 1", "B = 2"), cards(fc)); + assertEquals(2, fc.getCard()); + } + + /** A successful foreign write leaves the FitsChan at end-of-file, as C's {@code Write} does. */ + @Test + void successfulForeignWriteLeavesEndOfFile() { + FitsChan fc = new FitsChan() { + @Override + boolean writeForeign(FrameSet fs, FitsChan.Encoding enc) { + setFits("NEW1", 1, null, false); + return true; + } + }; + fc.putFits("A = 1", false); + fc.putFits("B = 2", false); + fc.clear("Card"); + fc.setEncoding("FITS-WCS"); + assertEquals(1, fc.write(new FrameSet(new Frame(2)))); + assertEquals( + padded( + "NEW1 = 1", + "A = 1", + "B = 2"), + cards(fc)); + assertEquals(4, fc.getCard()); + } + + /** A write that throws leaves the cards and the current card as they were. */ + @Test + void writeThatThrowsRollsBackItsCards() { + FitsChan fc = new FitsChan() { + @Override + boolean writeForeign(FrameSet fs, FitsChan.Encoding enc) { + setFits("NEW1", 1, null, false); + throw Ast.err(AstException.AST__INTER, "test"); + } + }; + fc.putFits("A = 1", false); + fc.setCard(1); + fc.setEncoding("FITS-WCS"); + assertEquals( + AstException.AST__INTER, + org.junit.jupiter.api.Assertions.assertThrows( + AstException.class, () -> fc.write(new FrameSet(new Frame(2)))) + .getStatus()); + assertEquals(padded("A = 1"), cards(fc)); + assertEquals(1, fc.getCard()); + } + + /** + * A FrameSet of one Frame written FITS-WCS goes through the foreign hook, which describes the + * identity, and leaves the FitsChan at end-of-file (C probe {@code p7.c} of phase 3 Task 6). + */ + @Test + void foreignFrameSetWriteGoesThroughTheHook() { + FitsChan fc = new FitsChan(); + fc.setEncoding("FITS-WCS"); + assertEquals(1, fc.write(new FrameSet(new Frame(2)))); + assertEquals(9, fc.getNcard()); + assertEquals(10, fc.getCard()); + assertEquals( + padded( + "WCSAXES = 2 / Number of WCS axes", + "CRPIX1 = 1.0 / Reference pixel on axis 1", + "CRPIX2 = 1.0 / Reference pixel on axis 2", + "CRVAL1 = 1.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 1.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'x2 ' / Type of co-ordinate on axis 2", // codespell:ignore + "CDELT1 = 1.0 / Pixel size on axis 1", + "CDELT2 = 1.0 / Pixel size on axis 2"), + cards(fc)); + } + + private static AstObject readBack(FitsChan fc) { + fc.clear("Card"); + AstObject obj = fc.read(); + assertNotNull(obj); + return obj; + } + + private static String repeat(char c, int n) { + StringBuilder sb = new StringBuilder(n); + for (int i = 0; i < n; i++) { + sb.append(c); + } + return sb.toString(); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java index b68fdbd..fbf4068 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java @@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; @@ -172,4 +173,117 @@ void twoUnclassifiedAxesJoinTheirCtypesWithADash() { ""); assertEquals("AAAA-BBBB", currentFrame(header).getDomain()); } + + /** The FrameSet read from {@code cards}, one card per element. */ + private static FrameSet readCards(String... cards) { + return FitsHeaders.readFrameSet(FitsChan.fromHeader(String.join("\n", cards) + "\n")); + } + + @Test + void aZeroCdeltTranslationOutranksALaterCardWithItsKeyword() { + // C reads its translations after every card of the header (fitschan.c WcsToStore), so the + // 1.0 that replaces the zero CDELT1 outranks the 0.25 of the second CDELT1 (C probe dup). + FrameSet fs = readCards( + "NAXIS = 1", + "NAXIS1 = 10", + "CRPIX1 = 1", + "CRVAL1 = 0", + "CTYPE1 = 'LINEAR'", + "CDELT1 = 0.0", + "CDELT1 = 0.25"); + assertEquals(2.0, fs.tran1(1, new double[] {3.0}, true)[0]); + } + + @Test + void aLogicalFalseCdeltIsTranslatedAsAZero() { + FrameSet fs = readCards( + "NAXIS = 1", + "NAXIS1 = 10", + "CRPIX1 = 1", + "CRVAL1 = 0", + "CTYPE1 = 'LINEAR'", + "CDELT1 = F", + "CDELT1 = 0.25"); + assertEquals(2.0, fs.tran1(1, new double[] {3.0}, true)[0]); + } + + @Test + void theCdeltsACdMatrixGivesOutrankEveryCdeltCard() { + // The CDj_i matrix gives CDELTj 1.0 among C's translations, which outrank all three CDELT2 + // cards wherever the translation is stored (C probe dup). + FrameSet fs = readCards( + "NAXIS = 2", + "NAXIS1 = 10", + "NAXIS2 = 10", + "CRPIX1 = 1", + "CRPIX2 = 1", + "CRVAL1 = 0", + "CRVAL2 = 0", + "CTYPE1 = 'LINEAR'", + "CTYPE2 = 'LINEAR'", + "CDELT2 = 0.5", + "CDELT2 = 0.5", + "CDELT2 = 0.5", + "CD1_1 = 2.0", + "CD2_2 = 3.0"); + double[][] out = fs.tran2(1, new double[] {3.0}, new double[] {3.0}, true); + assertEquals(4.0, out[0][0]); + assertEquals(6.0, out[1][0]); + } + + @Test + void aCtypeCardWithoutACommentKeepsTheCommentOfAnEarlierOne() { + // C's WcsFcRead stores the comment of each CTYPE card it visits, and SetItemC ignores a + // card with none, so the first CTYPE1's comment still labels the axis (C probe dup). + Frame f = readCards( + "NAXIS = 2", + "NAXIS1 = 10", + "NAXIS2 = 10", + "CRPIX1 = 1", + "CRPIX2 = 1", + "CRVAL1 = 0", + "CRVAL2 = 0", + "CTYPE1 = 'XLIN' / Comment one", + "CTYPE1 = 'XLIN'", + "CTYPE2 = 'YLIN' / Comment two", + "CDELT1 = 0.25", + "CDELT2 = 0.5") + .getFrame(FrameSet.AST__CURRENT); + assertEquals("Comment one", f.getLabel(1)); + assertEquals("Comment two", f.getLabel(2)); + } + + @Test + void aNaxisOfADescribedAxisThatIsNotANumberFailsTheRead() { + // C's DistortMaps reads NAXIS1 to NAXISn, n the number of WCS axes, with astGetFitsF, + // which reports a value it cannot convert (C probe dup). + for (String naxis1 : new String[] {"'abc'", "(1.0, 2.0)"}) { + FitsChan fc = FitsChan.fromHeader(String.join( + "\n", + "NAXIS = 1", + "NAXIS1 = " + naxis1, + "CRPIX1 = 1", + "CRVAL1 = 0", + "CTYPE1 = 'LINEAR'", + "CDELT1 = 0.25", + "")); + AstException e = assertThrows(AstException.class, fc::read, naxis1); + assertEquals(AstException.AST__FTCNV, e.getStatus(), naxis1); + assertTrue( + e.getMessage().contains("Cannot convert FITS keyword 'NAXIS1' to floating point."), e.getMessage()); + } + } + + @Test + void aNaxisBeyondTheWcsAxesIsNotRead() { + FrameSet fs = readCards( + "NAXIS = 2", + "NAXIS1 = 10", + "NAXIS2 = 'abc'", + "CRPIX1 = 1", + "CRVAL1 = 0", + "CTYPE1 = 'LINEAR'", + "CDELT1 = 0.25"); + assertEquals(0.5, fs.tran1(1, new double[] {3.0}, true)[0]); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanSipokOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanSipokOracleTest.java new file mode 100644 index 0000000..a0df16a --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanSipokOracleTest.java @@ -0,0 +1,93 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.Fixtures; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_fitschan_sipok_oracle.rs}: FitsChan's SipOK attribute + * against the C library. A FrameSet with SIP distortion, read from {@code + * wcsconv/inputs/sip.head} with SipReplace false, is written with every encoding and SipOK unset, + * false and true. Only FITS-WCS writes SIP coefficients; with SipOK false, or another encoding, + * the write uses a linear approximation if FitsTol allows one. + * + *

The cases are those of {@code oracle/fitschan_sipok.json}, made by {@code + * tools/oracle_fixtures/fitschan_sipok_probe.c} against the C library fixed upstream in bdc6336c + * (Rust c-library-quirks.md: SipOK applies only to FITS-WCS). Each case is compared byte for byte: + * what {@code write} returns, then every card. + */ +class FitsChanSipokOracleTest { + + /** What this library writes for one case, in the probe's format. */ + private static String run(String enc, String sipOk) { + FitsChan fin = new FitsChan(); + fin.set("SipReplace=0"); + for (String line : CValues.lines(Fixtures.read("wcsconv/inputs/sip.head"))) { + fin.putFits(line, false); + } + fin.clear("Card"); + AstObject obj = fin.read(); + + FitsChan out = new FitsChan(); + out.setEncoding(enc); + // MODERN-JAVA(21): switch expression + switch (sipOk) { + case "unset": + break; + case "0": + out.set("SipOK=0"); + break; + case "1": + out.set("SipOK=1"); + break; + default: + throw new IllegalArgumentException("no SipOK " + sipOk); + } + StringBuilder got = new StringBuilder("wrote ").append(out.write(obj)).append('\n'); + out.clear("Card"); + String card; + while ((card = out.findFits("%f", true)) != null) { + got.append(card).append('\n'); + } + return got.toString(); + } + + @Test + void sipOkWritesMatchTheCLibrary() { + List failed = new ArrayList<>(); + int run = 0; + for (JsonNode c : ProbeData.load("fitschan_sipok").get("CASES")) { + String enc = c.get(0).asText(); + String sipOk = c.get(1).asText(); + run++; + String want = c.get(2).asText(); + String got = run(enc, sipOk); + if (!got.equals(want)) { + failed.add(enc + " SipOK=" + sipOk + "\n--- Java\n" + got + "--- C\n" + want); + } + } + assertTrue(failed.isEmpty(), String.join("\n", failed)); + assertEquals(21, run, "cases run, three for each of seven encodings"); + } + + @Test + void sipOkAccessors() { + FitsChan fc = new FitsChan(); + assertEquals(1, fc.getI("SipOK")); + assertFalse(fc.test("SipOK")); + fc.set("SipOK=0"); + assertEquals(0, fc.getI("SipOK")); + assertTrue(fc.test("SipOK")); + fc.clear("SipOK"); + assertEquals(1, fc.getI("SipOK")); + assertFalse(fc.test("SipOK")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanSplitmapOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanSplitmapOracleTest.java new file mode 100644 index 0000000..351dbaf --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanSplitmapOracleTest.java @@ -0,0 +1,102 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_fitschan_splitmap_oracle.rs}: FITS-WCS headers written + * for FrameSets whose pixel to sky Mapping holds no WcsMap, against C's. fitschan.c {@code + * SplitMap} gives such a Mapping one: a linear Mapping a CAR projection, with its longitude origin + * moved to the pixel origin, and one giving constant celestial values the WcsMap of a TAN header + * with those values at its reference point. + * + *

The cases are those of {@code oracle/fitschan_splitmap.json}, made by {@code + * tools/oracle_fixtures/fitschan_splitmap_probe.c}; each FrameSet is built as the probe builds it. + * The cards are compared as {@link FitsHeaders#cardsMatchC} compares them, the keywords of {@link + * #RUNTIME_MATH} within libm rounding. + */ +class FitsChanSplitmapOracleTest { + + /** + * The keywords whose numbers depend on the runtime's elementary functions, by case. The CAR + * projection's native rotation (fitschan.c {@code WcsNative}) is a rotation by -LONPOLE, 2 pi + * - 0.2, about the z axis; java.lang.Math gives its cosine as 0.9800665778412416 where C's libm + * (and StrictMath) give 0.9800665778412415, and the least-squares slope of {@code FitLine} + * over 101 points raises the 1 ULP to 5 ULP in CDELT2 (C probe {@code p4.c} with lldb, beside + * the task report). + */ + private static final Map> RUNTIME_MATH = runtimeMath(); + + private static Map> runtimeMath() { + Map> m = new HashMap<>(); + m.put("linear", Collections.singleton("CDELT2")); + m.put("linear_3d", Collections.singleton("CDELT2")); + return Collections.unmodifiableMap(m); + } + + /** The probe's linear Mapping: a MatrixMap, then a ShiftMap by (0.2, 0.3, 4.0). */ + private static Mapping linear(MatrixMap matrix, int n) { + double[] shift = {0.2, 0.3, 4.0}; + double[] s = new double[n]; + System.arraycopy(shift, 0, s, 0, n); + return new CmpMap(matrix, new ShiftMap(s), true); + } + + /** The probe's current Frame and pixel to WCS Mapping for {@code name}. */ + private static Object[] probeCase(String name) { + // MODERN-JAVA(21): switch expression + switch (name) { + case "linear": + return new Object[] {new SkyFrame(), linear(new MatrixMap(2, 2, new double[] {-0.001, 0.002}), 2)}; + case "linear_3d": { + Frame x = new Frame(1); + x.setDomain("X"); + double[][] zoom = {{-0.001, 0.0, 0.0}, {0.0, 0.002, 0.0}, {0.0, 0.0, 3.0}}; + return new Object[] {new CmpFrame(new SkyFrame(), x), linear(new MatrixMap(3, 3, zoom), 3)}; + } + case "constant": + return new Object[] { + new SkyFrame(), new PermMap(2, new int[] {0, 0}, 2, new int[] {-1, -2}, new double[] {0.5, -0.25}) + }; + default: + throw new IllegalArgumentException("no case " + name); + } + } + + @Test + void headersMatchC() { + List failed = new ArrayList<>(); + for (JsonNode c : ProbeData.load("fitschan_splitmap").get("CASES")) { + String name = c.get(0).asText(); + Object[] pc = probeCase(name); + Frame frame = (Frame) pc[0]; + Mapping map = (Mapping) pc[1]; + Frame grid = new Frame(map.getNin()); + grid.setDomain("GRID"); + FrameSet fs = new FrameSet(grid); + fs.addFrame(FrameSet.AST__BASE, map, frame); + FitsChan fc = new FitsChan(); + fc.setEncoding("FITS-WCS"); + List got = new ArrayList<>(); + got.add("wrote " + fc.write(fs)); + got.addAll(FitsHeaders.foundCards(fc)); + List want = new ArrayList<>(); + want.add("wrote " + c.get(1).asInt()); + want.addAll(FitsHeaders.strings(c.get(2))); + Set libm = RUNTIME_MATH.getOrDefault(name, Collections.emptySet()); + if (!FitsHeaders.cardsMatchC(got, want, libm)) { + failed.add(name + ":\n--- Java\n" + String.join("\n", got) + "\n--- C\n" + String.join("\n", want)); + } + } + assertTrue(failed.isEmpty(), String.join("\n", failed)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanTest.java index e3d043b..7893ca6 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanTest.java @@ -26,9 +26,9 @@ * follows them, and {@code FITSCHAN_OPTIONS}. None of its tests waits for the FITS-WCS read (Task * 23). * - *

The tests that write to the FitsChan ({@code native_round_trip_zoommap}, - * {@code native_round_trip_skyframe}, {@code native_rewind_and_reread} and {@code - * translate_projp_retains_source_cards}) are listed in {@code deferred/rust-tests.txt}. + *

Of the tests that write to the FitsChan, {@code native_round_trip_zoommap}, {@code + * native_round_trip_skyframe}, {@code native_rewind_and_reread} and {@code + * translate_projp_retains_source_cards} use the NATIVE encoding and are translated here. */ class FitsChanTest { @@ -163,6 +163,62 @@ void findFitsSearchesForwardOnly() { assertEquals(fc.getNcard() + 1, fc.getCard()); } + @Test + void nativeRoundTripZoommap() { + FitsChan fc = new FitsChan(); + fc.setEncoding("NATIVE"); + assertEquals(1, fc.write(new ZoomMap(3, 2.5))); + assertTrue(fc.getNcard() > 0, "the FitsChan holds cards after the write"); + + fc.clear("Card"); + AstObject obj = fc.read(); + assertNotNull(obj, "read should return an object"); + Mapping mapping = (Mapping) obj; + assertEquals(3, mapping.getNin()); + assertEquals(3, mapping.getNout()); + double[] out = mapping.tranN(1, 3, new double[] {1.0, 2.0, 3.0}, true, 3); + assertTrue(Math.abs(out[0] - 2.5) < 1e-10); + assertTrue(Math.abs(out[1] - 5.0) < 1e-10); + assertTrue(Math.abs(out[2] - 7.5) < 1e-10); + } + + @Test + void nativeRoundTripSkyframe() { + SkyFrame sky = new SkyFrame(); + sky.set("System=FK5,Epoch=MJD 51544.0,Equinox=MJD 51544.0"); + + FitsChan fc = new FitsChan(); + fc.setEncoding("NATIVE"); + assertEquals(1, fc.write(sky)); + assertTrue(fc.getNcard() > 0); + + fc.clear("Card"); + AstObject obj = fc.read(); + assertNotNull(obj, "read should return an object"); + Frame frame = (Frame) obj; + assertEquals(2, frame.getNaxes()); + assertEquals("FK5", frame.getSystem()); + } + + /** + * A NATIVE read removes the cards it read (C's {@code Read} calls {@code FixUsed} with {@code + * remove} set for the NATIVE encoding), so after a rewind there is nothing left to read. + */ + @Test + void nativeRewindAndReread() { + FitsChan fc = new FitsChan(); + fc.setEncoding("NATIVE"); + fc.write(new ZoomMap(2, 3.0)); + + fc.clear("Card"); + AstObject obj1 = fc.read(); + assertNotNull(obj1, "first read"); + assertEquals(2, ((Mapping) obj1).getNin()); + + fc.clear("Card"); + assertNull(fc.read(), "second read should find no object"); + } + @Test void encodingDefaultForEmptyChanIsNative() { // C's astGetEncoding (fitschan.c:12603): NATIVE when no WCS keyword is present. @@ -402,4 +458,40 @@ private static String readAll(InputStream in) throws IOException { } return new String(buf.toByteArray(), StandardCharsets.UTF_8); } + + @Test + void translateProjpRetainsSourceCards() { + // C reads PROJPm only when the PV values of the longitude axis look incomplete + // (fitschan.c:31910-31947); with PV1_0, PV1_1 and PV1_2 it trusts them, so the PROJP cards + // are not read, not consumed, and are kept by a later write. + String header = String.join( + "\n", + "SIMPLE = T / Fits standard", + "NAXIS = 2 / Number of dimensions", + "CTYPE1 = 'RA---TAN' / Axis type", + "CTYPE2 = 'DEC--TAN' / Axis type", + "CRVAL1 = 40.0 / Reference value", + "CRVAL2 = 60.0 / Reference value", + "CRPIX1 = 256.0 / Reference pixel", + "CRPIX2 = 256.0 / Reference pixel", + "CDELT1 = -0.01 / Pixel size", + "CDELT2 = 0.01 / Pixel size", + "PROJP0 = 999.0 / Projection parameter", + "PROJP1 = 999.0 / Projection parameter", + "PROJP2 = 999.0 / Projection parameter", + "PV1_0 = 0.0 / Standard PV", + "PV1_1 = 0.0 / Standard PV", + "PV1_2 = 0.0 / Standard PV", + "END", + ""); + FitsChan fc = FitsChan.fromHeader(header); + AstObject obj = fc.read(); + assertNotNull(obj); + fc.setEncoding("NATIVE"); + assertEquals(1, fc.write(obj)); + String out = fc.toHeader(); + for (String key : new String[] {"PROJP0", "PROJP1", "PROJP2"}) { + assertTrue(out.contains(key), key + " is kept"); + } + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java index 5f7a2c5..bf81c60 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java @@ -18,9 +18,7 @@ *

Listed in {@code deferred/rust-tests.txt}: {@code read_spectral_header}, {@code * axes_swap_non_adjacent_celestial_axes} and {@code crota_3d_forward_matches_oracle_inverse_undefined} * (spectral axes, SpecFrame; {@code crota-3d.head} is also read with the FITS-AIPS encoding), {@code - * jan_class_no_naxis_keyword} and {@code class_noproj_builds_sfl} (the FITS-CLASS encoding), {@code - * serpens_dut1_is_seconds} and {@code serpens_swapped_axis_transform} ({@code serpens.head} is read - * with the FITS-IRAF encoding). + * jan_class_no_naxis_keyword} and {@code class_noproj_builds_sfl} (the FITS-CLASS encoding). */ class FitsChanWcsTest { @@ -269,4 +267,24 @@ void carlinKeepsTheCartesianProjectionDescription() { assertInstanceOf(SkyFrame.class, cur, "current Frame is a " + cur.astClass()); assertEquals("Cartesian", ((SkyFrame) cur).getProjection()); } + + @Test + void serpensDut1IsSeconds() { + // serpens.head, read with the FITS-IRAF encoding C guesses for it, has DUT1 = + // -1.145603703E-6 in days; C multiplies it by the seconds in a day before setting Dut1. + FrameSet fs = FitsHeaders.readFrameSet(FitsChan.fromHeader(fixture("serpens.head"))); + double expected = -1.145603703e-6 * 86400.0; + assertTrue(fs.test("Dut1"), "Dut1 is set from the DUT1 card"); + assertTrue(Math.abs(fs.getD("Dut1") - expected) < 1e-9, "Dut1 " + fs.getD("Dut1")); + } + + @Test + void serpensSwappedAxisTransform() { + // serpens.head has CTYPE1 = 'DEC--TAN' and CTYPE2 = 'RA---TAN'. Pixel (150, 120) gives + // (0.018049750, -1.440691695) radians on (axis 1, axis 2) in the C library. + Mapping map = FitsHeaders.readFrameSet(FitsChan.fromHeader(fixture("serpens.head"))); + double[] out = FitsHeaders.tran(map, new double[] {150.0, 120.0}, true); + assertTrue(Math.abs(out[0] - 0.018_049_750) < 1e-6, "axis 1 " + out[0]); + assertTrue(Math.abs(out[1] - -1.440_691_695) < 1e-6, "axis 2 " + out[1]); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanWcsWriteTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanWcsWriteTest.java new file mode 100644 index 0000000..34de474 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanWcsWriteTest.java @@ -0,0 +1,127 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; + +/** + * Translation of Rust {@code tests/test_fitschan_wcs_write.rs}: a FrameSet read from a FITS-WCS + * header written FITS-WCS into a new FitsChan, and read back. The cards and coordinates expected + * are those C gives (probe {@code c1.c} beside the task report). + * + *

Listed in {@code deferred/rust-tests.txt}: {@code write_spectral_frameset} and {@code + * write_spectral_round_trip} (SpecFrame), {@code grism_interference_order_survives_a_round_trip} + * and {@code a_non_linear_grism_axis_writes_a_header_that_reads_back} (SpecFrame and GrismMap), + * the four tests of the {@code lsst2.ast} FrameSet (SplineMap), and {@code + * a_sip_description_is_rejected_when_it_is_not_linear_over_the_image} (MathMap). + */ +class FitsChanWcsWriteTest { + + /** A two-dimensional TAN header whose reference pixel is (1, 1). */ + private static final String[] MINIMAL_TAN_HEADER = { + "NAXIS = 2 / Number of axes", + "CRPIX1 = 1.000 / Reference pixel", + "CRPIX2 = 1.000 / Reference pixel", + "CRVAL1 = 202.4820000 / Reference RA", + "CRVAL2 = 47.1750000 / Reference Dec", + "CDELT1 = -0.00027778000 / Degrees per pixel", + "CDELT2 = 0.00027778000 / Degrees per pixel", + "CTYPE1 = 'RA---TAN' / RA with TAN projection", + "CTYPE2 = 'DEC--TAN' / Dec with TAN projection", + "RADESYS = 'ICRS ' / Reference frame", + "EQUINOX = 2000.0 / Equinox", + }; + + /** The FrameSet read FITS-WCS from {@link #MINIMAL_TAN_HEADER}. */ + private static FrameSet readMinimalTan() { + FitsChan fc = FitsHeaders.chan(MINIMAL_TAN_HEADER); + fc.setEncoding("FITS-WCS"); + return FitsHeaders.readFrameSet(fc); + } + + /** A new FITS-WCS FitsChan holding {@code fs}, which it must write. */ + private static FitsChan written(FrameSet fs) { + FitsChan fc = new FitsChan(); + fc.setEncoding("FITS-WCS"); + assertEquals(1, fc.write(fs)); + return fc; + } + + @Test + void writeProducesFitsCards() { + FitsChan fc = written(readMinimalTan()); + List want = FitsHeaders.padded( + "WCSAXES = 2 / Number of WCS axes", + "CRPIX1 = 1.0 / Reference pixel on axis 1", + "CRPIX2 = 1.0 / Reference pixel on axis 2", + "CRVAL1 = 202.482 / Value at ref. pixel on axis 1", + "CRVAL2 = 47.175 / Value at ref. pixel on axis 2", + "CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CDELT1 = -2.7778E-4 / Pixel size on axis 1", + "CDELT2 = 0.00027778 / Pixel size on axis 2", + "MJD-OBS = 51544.499257130781 / Modified Julian Date of observation", + "DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation", + "RADESYS = 'ICRS ' / Reference frame for RA/DEC values"); + assertEquals(12, fc.getNcard()); + List got = FitsHeaders.foundCards(fc); + assertTrue(FitsHeaders.cardsMatchC(got, want), got.toString()); + } + + @Test + void writeCelestialHasCorrectCtype() { + FitsChan fc = written(readMinimalTan()); + assertEquals("RA---TAN", fc.getFitsS("CTYPE1")); + fc.clear("Card"); + assertEquals("DEC--TAN", fc.getFitsS("CTYPE2")); + } + + @Test + void writeCelestialHasRadesys() { + FitsChan fc = written(readMinimalTan()); + assertEquals("ICRS", fc.getFitsS("RADESYS")); + } + + @Test + void roundTripReadWriteRead() { + FrameSet fs1 = readMinimalTan(); + FitsChan fc = written(fs1); + fc.clear("Card"); + FrameSet fs2 = FitsHeaders.readFrameSet(fc); + double[] want = {-2.7492077311564285, 0.8233590746283249}; + CValues.assertCValues(FitsHeaders.tran(fs1, new double[] {1, 1}, true), want, "the original at (1, 1)"); + CValues.assertCValues(FitsHeaders.tran(fs2, new double[] {1, 1}, true), want, "read back, at (1, 1)"); + CValues.assertCValues( + FitsHeaders.tran(fs2, new double[] {2, 2}, true), + new double[] {-2.7492148633663933, 0.8233639227912407}, + "read back, at (2, 2)"); + } + + /** + * A FrameSet whose Mapping has no inverse cannot be described: C derives CRPIX by + * transforming the IWC origin back to grid coordinates. The write gives 0 and leaves the cards + * it was given. + */ + @Test + void aFrameSetWhoseMappingHasNoInverseWritesNothing() { + // Forward only, and IterInverse off, so there is no numerical inverse either. + PolyMap poly = new PolyMap(2, 2, 2, new double[] {1.0, 1, 1, 0, 1.0, 2, 0, 1}, 0, null); + poly.set("IterInverse=0"); + assertFalse(poly.getTranInverse()); + Frame pixel = new Frame(2); + pixel.setDomain("PIXEL"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, poly, new Frame(2)); + + FitsChan fc = FitsHeaders.chan("NAXIS1 = 100", "NAXIS2 = 100"); + fc.setEncoding("FITS-WCS"); + assertEquals(0, fc.write(fs)); + assertEquals( + FitsHeaders.padded("NAXIS1 = 100", "NAXIS2 = 100"), + FitsHeaders.foundCards(fc)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanWriteTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanWriteTest.java new file mode 100644 index 0000000..b9fa22c --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanWriteTest.java @@ -0,0 +1,438 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.Deferred; +import uk.ac.starlink.ast.testsupport.OracleSection; + +/** + * Writing FrameSets as FITS-WCS through {@link FitsChan#write}: what a failed write leaves, where + * the cards of a successful one go, that the cards read back transform as the FrameSet written, + * also for FITS-PC, FITS-IRAF, FITS-AIPS and FITS-AIPS++, and that writes in several threads + * agree. The cards expected come from C probes of the pinned library (fitschan.c {@code Write}, + * {@code FitsFromStore}, {@code WcsFromStore}, {@code PCFromStore}, {@code IRAFFromStore}, {@code + * AIPSFromStore}, {@code AIPSPPFromStore}). + */ +class FitsChanWriteTest { + + /** The cards {@code fc} holds, consumed or not, as {@code findFits} lists them, and its current card. */ + private static String state(FitsChan fc) { + int card = fc.getCard(); + String cards = String.join("\n", FitsHeaders.foundCards(fc)); + fc.setCard(card); + return "card " + card + "\n" + cards; + } + + /** A 1-D FrameSet whose world axis is {@code c0 + c1 p + c2 p^2} of the pixel axis. */ + private static FrameSet quadratic(double c0, double c1, double c2) { + PolyMap pm = new PolyMap(1, 1, 3, new double[] {c0, 1, 0, c1, 1, 1, c2, 1, 2}, 0, new double[0]); + pm.set("IterInverse=1"); + Frame pixel = new Frame(1); + pixel.setDomain("GRID"); + Frame wcs = new Frame(1); + wcs.setDomain("WORLD"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, pm, wcs); + return fs; + } + + /** The FrameSet a TAN header with 100 by 100 pixels reads as, with {@code extra} cards. */ + private static FrameSet tan(String... extra) { + List cards = new ArrayList<>(Arrays.asList( + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 20", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "RADESYS = 'ICRS'")); + cards.addAll(Arrays.asList(extra)); + return FitsHeaders.readFrameSet(FitsHeaders.chan(cards.toArray(new String[0]))); + } + + /** The cards a FITS-WCS write of {@link #tan(String...)} with no extra cards adds (C probe). */ + private static final List TAN_CARDS = Arrays.asList( + "WCSAXES = 2 / Number of WCS axes ", + "CRPIX1 = 50.0 / Reference pixel on axis 1 ", + "CRPIX2 = 50.0 / Reference pixel on axis 2 ", + "CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ", + "CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ", + "CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ", // codespell:ignore + "CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ", // codespell:ignore + "CDELT1 = -0.001 / Pixel size on axis 1 ", + "CDELT2 = 0.001 / Pixel size on axis 2 ", + "RADESYS = 'ICRS ' / Reference frame for RA/DEC values "); + + private static String card(String keyword, String value) { + return String.format("%-8s= %20s", keyword, value) + String.format("%50s", ""); + } + + @Test + void aFailedWriteLeavesTheCardsAsTheyWere() { + // C probe: a non-linear axis whose CRVAL is zero cannot be described, so write returns 0, + // and the cards and the current card are as they were. + FitsChan fc = FitsHeaders.chan( + "NAXIS = 1", "NAXIS1 = 100", "CRVAL1 = 3.0 / a WCS card", "DDD = 4", "EEE = 5"); + fc.setEncoding("FITS-WCS"); + fc.setCard(3); + String before = state(fc); + assertEquals(0, fc.write(quadratic(-25, 0, 0.01))); + assertEquals(before, state(fc)); + assertEquals(3, fc.getCard()); + assertEquals(5, fc.getNcard()); + } + + @Test + void aFailedWriteLosesACardItReplaced() { + // C probe ovr.c: FITS-PC stores CRVAL1, replacing the card of that keyword, before it + // refuses the TPN projection; the write returns 0 and removes the cards it wrote, so the + // card it replaced is gone, and the current card is as it was. + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.chan( + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 20", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "CTYPE1 = 'RA---TPN'", + "CTYPE2 = 'DEC--TPN'", + "RADESYS = 'ICRS'", + "PV1_1 = 1.0", + "PV2_1 = 1.0", + "PV1_4 = 0.001")); + FitsChan fc = FitsHeaders.chan("AAA = 1", "CTYPE1 = 'XXX' / mine", "CRVAL1 = 5 / mine", "ZZZ = 1"); + fc.setEncoding("FITS-PC"); + fc.setCard(2); + assertEquals(0, fc.write(fs)); + assertEquals( + "card 2\n" + card("AAA", "1") + "\n" + + "CTYPE1 = 'XXX ' / mine \n" + + card("ZZZ", "1"), + state(fc)); + } + + @Test + void aSlightlyNonLinearAxisIsWrittenAsLinear() { + // The logarithm of 10 + p + 1e-6 p^2 is not linear, so C's LogAxis returns NULL, and the + // axis described as linear is within FitsTol of the FrameSet (C probe loglin.c). + FitsChan fc = FitsHeaders.chan("NAXIS1 = 100"); + fc.setEncoding("FITS-WCS"); + assertEquals(1, fc.write(quadratic(10, 1, 1e-6))); + List want = Arrays.asList( + "NAXIS1 = 100 ", + "WCSAXES = 1 / Number of WCS axes ", + "WCSNAME = 'WORLD ' / Reference name for the coord. frame ", + "CRPIX1 = 50.0 / Reference pixel on axis 1 ", + "CRVAL1 = 60.0025 / Value at ref. pixel on axis 1 ", + "CTYPE1 = 'WORLD1 ' / Type of co-ordinate on axis 1 ", // codespell:ignore + "CDELT1 = 1.000101 / Pixel size on axis 1 "); + assertEquals(want, FitsHeaders.foundCards(fc)); + } + + @Test + void strictWriteFailsAndLeavesTheCards() { + // A FrameSet with an MJD-OBS written to a FitsChan holding TIMESYS = 'ET' raises a badval + // warning, which Strict makes an error (C probe, FitsChanAstwarnTest). + FrameSet fs = tan("MJD-OBS = 55000"); + FitsChan fc = FitsHeaders.chan("AAA = 1", "TIMESYS = 'ET'", "CCC = 3", "DDD = 4", "EEE = 5"); + fc.setEncoding("FITS-WCS"); + fc.set("Strict=1,Warnings=badval"); + fc.setCard(3); + String before = state(fc); + AstException e = assertThrows(AstException.class, () -> fc.write(fs)); + assertEquals(AstException.AST__BADIN, e.getStatus()); + assertEquals(before, state(fc)); + assertEquals(3, fc.getCard()); + } + + /** + * C's {@code FitsFromStore} puts the cards after the last card {@code FindWcs} recognises as + * describing WCS, whichever card is current, or at the end if there is none; the write then + * leaves the FitsChan at end-of-file (C probe). + */ + @Test + void cardsGoAfterTheLastWcsCard() { + String a = card("EPOCH", "2000.0"); + String b = card("BBB", "2"); + String c = card("CCC", "3"); + List want = new ArrayList<>(); + want.add(a); + want.addAll(TAN_CARDS); + want.add(b); + want.add(c); + for (int current : new int[] {2, 3}) { + FitsChan fc = FitsHeaders.chan(a, b, c); + fc.setEncoding("FITS-WCS"); + fc.setCard(current); + assertEquals(1, fc.write(tan())); + assertEquals(14, fc.getCard(), "end-of-file"); + assertEquals(want, FitsHeaders.foundCards(fc), "card " + current + " current"); + } + + // With no card describing WCS the cards go at the end. + String aaa = card("AAA", "1"); + FitsChan fc = FitsHeaders.chan(aaa, b, c); + fc.setEncoding("FITS-WCS"); + fc.setCard(2); + assertEquals(1, fc.write(tan())); + List atEnd = new ArrayList<>(Arrays.asList(aaa, b, c)); + atEnd.addAll(TAN_CARDS); + assertEquals(atEnd, FitsHeaders.foundCards(fc)); + } + + /** + * Written into the FitsChan it was read from, a FrameSet's new cards go in front of the card + * after the last card describing WCS though the read consumed that card (here WCSAXES): C's + * {@code GetCDMatrix} saves and restores the current card itself, not its index among the + * cards not consumed (Rust c-library-quirks.md, upstream 35f3a372; C probe {@code p6.c}). + */ + @Test + void cardsGoInFrontOfAConsumedCurrentCard() { + FitsChan fc = FitsHeaders.chan( + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 20", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "RADESYS = 'ICRS'", + "WCSAXES = 2", + "AAA = 1"); + FrameSet fs = FitsHeaders.readFrameSet(fc); + fs.set("Epoch=MJD 55000"); + fc.setEncoding("FITS-WCS"); + fc.clear("Card"); + assertEquals(1, fc.write(fs)); + List want = + new ArrayList<>(Arrays.asList(card("NAXIS", "2"), card("NAXIS1", "100"), card("NAXIS2", "100"))); + for (String t : TAN_CARDS.subList(1, 5)) { + want.add(t); + } + want.add(TAN_CARDS.get(7)); + want.add(TAN_CARDS.get(8)); + want.add(TAN_CARDS.get(5)); + want.add(TAN_CARDS.get(6)); + want.add(TAN_CARDS.get(9)); + want.add("MJD-OBS = 54999.999233975963 / Modified Julian Date of observation "); + want.add("DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation "); + want.add(card("AAA", "1")); + assertTrue( + FitsHeaders.cardsMatchC(FitsHeaders.foundCards(fc), want), + String.join("\n", FitsHeaders.foundCards(fc))); + } + + /** The outcome of a header whose write returns 0. */ + private static final String WRITE_FAILS = "the write returns 0"; + + /** The outcome of a header whose cards read back do not transform as C's read of the header. */ + private static final String DIFFERS = "the cards read back transform differently"; + + /** The outcome of a header whose cards the read rejects with {@code AST__BDFTS}. */ + private static final String READ_FAILS = "the cards written do not read back"; + + /** + * The headers that do not round-trip, with their outcome, which C's gives too (C probes {@code + * p3.c} for FITS-WCS and {@code rt.c} for the other encodings, beside the task reports, and + * {@code rt7.c} and {@code rtc.c} of the final review fixes for the offset SkyFrames): C's + * write returns 0 (for FITS-IRAF, a description with a LONPOLE or projection parameters, or a + * TNX or ZPX projection read as TPN or ZPN), or C's cards read back give values where C's read + * of the header gives BAD (the CAR headers whose longitude range the projection bounds, among + * them the FITS-AIPS header cmap_3years_GP_D2) or other values (scp, at a point 1.3E-6 radians + * from the pole, where longitude changes fast; and the offset SkyFrames, whose offset + * coordinates C describes without a projection, with the absolute coordinates as an alternate + * description), or C's read of the cards written fails (skyref, whose alternate description, + * CTYPE1A {@code RA} and CTYPE2A {@code Dec}, C's read rejects as a longitude axis without a + * latitude axis). + */ + private static final Map NOT_ROUND_TRIPPED = notRoundTripped(); + + private static Map notRoundTripped() { + Map m = new LinkedHashMap<>(); + for (String h : Arrays.asList( + "programs/joye_car_headers/CHIPASS_Equ.head", + "wcsconv/inputs/car6.head", + "wcsconv/inputs/tsc.head", + "wcsconv/inputs/iraf-longpole.head", + "wcsconv/inputs/projp-nopv0.head", + "wcsconv/inputs/projp-pv.head", + "wcsconv/inputs/projp-pv0only.head", + "wcsconv/inputs/projp.head", + "wcsconv/inputs/tnx-cheb.head", + "wcsconv/inputs/tnx.head", + "wcsconv/inputs/zpx.head")) { + m.put(h, WRITE_FAILS); + } + for (String h : Arrays.asList( + "programs/joye_car_headers/car1.head", + "programs/joye_car_headers/car2.head", + "programs/joye_car_headers/cmap_3years_GP_D2.head", + "wcsconv/inputs/car1.head", + "wcsconv/inputs/car2.head", + "wcsconv/inputs/offset-sky-pole.head", + "wcsconv/inputs/offset-sky.head", + "wcsconv/inputs/offset-sref.head", + "wcsconv/inputs/scp.head", + "wcsconv/inputs/skyref-alt.head")) { + m.put(h, DIFFERS); + } + m.put("wcsconv/inputs/skyref.head", READ_FAILS); + return Collections.unmodifiableMap(m); + } + + /** + * What a header gives when its FrameSet is written with {@code encoding} into a new FitsChan + * and read back: null if the FrameSet read back transforms the inputs of the header's forward + * section to the outputs C recorded, within the section's tolerances, and otherwise {@link + * #WRITE_FAILS}, {@link #DIFFERS}, {@link #READ_FAILS} or the class the write needs. + */ + private static String roundTrip( + OracleSection s, + FrameSet fs, + String encoding, + TransformOracleTest.Overrides overrides, + Map excused) { + FitsChan out = new FitsChan(); + out.setEncoding(encoding); + try { + if (out.write(fs) != 1) { + return WRITE_FAILS; + } + } catch (UnsupportedOperationException e) { + return FitsHeaders.outOfScope(e); + } + out.clear("Card"); + FrameSet back; + try { + back = FitsHeaders.readFrameSet(out); + } catch (AstException e) { + if (e.getStatus() != AstException.AST__BDFTS) { + throw e; + } + return READ_FAILS; + } + double[][] live = back.tranP(s.npoint(), s.nin, s.inputs(), true, s.nout); + List misses = new ArrayList<>(); + if (!overrides.goldenOff(s.path, true)) { + misses = TransformOracleTest.compareGolden( + TransformOracleTest.CheckKind.GOLDEN_FWD, + live, + s.outputs(), + TransformOracleTest.angularFlags(back, s), + overrides.goldenSkipRows(s.path, true), + s.rtol, + s.atol); + } + TransformOracleTest.ExcusedRows listed = excused.get(TransformOracleTest.sectionKey(s.path, true)); + if (listed != null) { + misses = TransformOracleTest.excuseRows(misses, listed.rows).misses; + } + return misses.isEmpty() ? null : DIFFERS; + } + + /** The encodings whose headers {@link #everyInScopeHeaderRoundTrips} writes and reads back. */ + private static final Set ROUND_TRIP_ENCODINGS = + new LinkedHashSet<>(Arrays.asList("FITS-WCS", "FITS-PC", "FITS-IRAF", "FITS-AIPS", "FITS-AIPS++", "DSS")); + + /** + * Every FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and DSS header of {@code + * headers.oracle} whose sections match C here, read, written with its own encoding into a new + * FitsChan and read back, transforms the inputs of its forward section to the outputs C + * recorded, within the section's tolerances, unless it is in {@link #NOT_ROUND_TRIPPED} with + * the outcome it gives, which is checked. {@code headers.oracle} has no DSS header (C probe + * {@code rt.c} of Task 9); {@code FitsEncDssTest.writtenAndReadBackAsC} round-trips C's DSS + * header. Its FITS-CLASS headers need SpecFrame. + */ + @Test + void everyInScopeHeaderRoundTrips() { + Map deferredHeaders = Deferred.load("headers"); + TransformOracleTest.Overrides overrides = TransformOracleTest.committedOverrides(); + Map excused = TransformOracleTest.committedOracleRows(); + Set seen = new LinkedHashSet<>(); + List failed = new ArrayList<>(); + int roundTripped = 0; + for (OracleSection s : TransformOracleTest.parseOracle("headers")) { + if (!s.forward || !s.path.endsWith(".head") || deferredHeaders.containsKey(s.path) || !seen.add(s.path)) { + continue; + } + FitsChan in = FitsHeaders.fixture(s.path); + String encoding = in.getEncoding(); + if (!ROUND_TRIP_ENCODINGS.contains(encoding)) { + continue; + } + String got = roundTrip(s, FitsHeaders.readFrameSet(in), encoding, overrides, excused); + String want = NOT_ROUND_TRIPPED.get(s.path); + if (got == null && want == null) { + roundTripped++; + } else if (got == null || !got.equals(want)) { + failed.add(s.path + " gives \"" + got + "\", listed as \"" + want + "\""); + } + } + for (String h : NOT_ROUND_TRIPPED.keySet()) { + if (!seen.contains(h)) { + failed.add(h + " is listed but is not an in-scope header of headers.oracle of those encodings"); + } + } + assertTrue(failed.isEmpty(), String.join("\n", failed)); + assertTrue(roundTripped > 0, "headers round-tripped"); + } + + // MODERN-JAVA(19): ExecutorService is AutoCloseable; try-with-resources would replace shutdown. + @SuppressWarnings("PMD.CloseResource") // shut down in the finally block, as Java 8 allows + @Test + void threadsWriteCopiesIdentically() throws Exception { + FitsChan in = FitsHeaders.fixture("wcsconv/inputs/sip.head"); + FrameSet fs = FitsHeaders.readFrameSet(in); + int nthread = 4; + ExecutorService pool = Executors.newFixedThreadPool(nthread); + try { + List>> results = new ArrayList<>(); + for (int i = 0; i < nthread; i++) { + FrameSet copy = (FrameSet) fs.copy(); + Callable> task = () -> { + FitsChan out = new FitsChan(); + out.setEncoding("FITS-WCS"); + assertEquals(1, out.write(copy)); + return FitsHeaders.foundCards(out); + }; + results.add(pool.submit(task)); + } + List first = results.get(0).get(); + assertNotNull(first); + assertTrue(first.size() > 10, "cards written"); + for (Future> r : results) { + assertEquals(first, r.get()); + } + } finally { + pool.shutdown(); + } + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsDatesTest.java b/src/test/java/uk/ac/starlink/ast/FitsDatesTest.java index b23a94e..ab823b8 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsDatesTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsDatesTest.java @@ -7,12 +7,13 @@ import org.junit.jupiter.api.Test; /** - * Translation of the {@code date_str_to_mjd_*} unit tests of Rust {@code fitschan/wcs_write/mod.rs}: - * the MJD of a FITS DATE-OBS string (fitschan.c {@code DateObs}). + * Translation of the {@code date_str_to_mjd_*} and {@code mjd_to_date_str_*} unit tests of Rust + * {@code fitschan/wcs_write/mod.rs}: the MJD of a FITS DATE-OBS string (fitschan.c {@code + * DateObs}), and the DATE-OBS string C's {@code WcsFromStore} writes for an MJD. * - *

The two round-trip tests need {@code mjd_to_date_str}, the write side, and are deferred. The - * tests after them check the strings C's {@code sscanf} patterns accept or reject - * (fitschan.c:8662-8710), which the Rust parser treats differently. + *

The tests after them check the strings C's {@code sscanf} patterns accept or reject + * (fitschan.c:8662-8710), which the Rust parser treats differently, and the DATE-OBS C writes + * where its calendar routines round. */ class FitsDatesTest { @@ -112,4 +113,64 @@ void anInvalidDateOrTimeGivesNull() { assertNull(FitsDates.dateStrToMjd("2000-01-01T24:00:00")); assertNull(FitsDates.dateStrToMjd("not a date")); } + + @Test + void mjdToDateStrModernIso() { + assertEquals("2000-01-01T12:00:00.000", FitsDates.mjdToDateStr(51544.5)); + } + + @Test + void mjdToDateStrModernWithMsPrecision() { + String s = FitsDates.mjdToDateStr(52414.59); + assertTrue(s.startsWith("2002-05-20T"), s); + assertEquals("14:09", s.substring(11, 16)); + } + + @Test + void mjdToDateStrLegacyFormat() { + // Before 1999 the old form dd/mm/yy: MJD 40000 is 1968-05-24. + assertEquals("24/05/68", FitsDates.mjdToDateStr(40000.0)); + } + + @Test + void mjdToDateStrCutoffBoundary() { + // MJD 51179 is 1999-01-01, palCaldj( 99, 1, 1 ). + assertTrue(FitsDates.mjdToDateStr(51179.0).startsWith("1999-01-01T")); + assertEquals("31/12/98", FitsDates.mjdToDateStr(51178.0)); + } + + @Test + void dateStrToMjdRoundtripModern() { + double original = 52414.59; + double parsed = FitsDates.dateStrToMjd(FitsDates.mjdToDateStr(original)); + assertTrue(Math.abs(parsed - original) < 1e-3); + } + + @Test + void dateStrToMjdRoundtripLegacy() { + double original = 40000.0; + double parsed = FitsDates.dateStrToMjd(FitsDates.mjdToDateStr(original)); + assertTrue(Math.abs(parsed - original) < 1e-6); + } + + /** + * Values from a C probe of {@code WcsFromStore}'s formatting. The old form is not rounded: {@code palDjcal} with no decimal places gives the day the MJD + * falls in. The new form rounds the time of day to milliseconds with {@code palDd2tf}, which + * can give 24 hours on the day the MJD falls in (fitschan.c {@code WcsFromStore}). + */ + @Test + void mjdToDateStrRoundsOnlyTheTimeOfDay() { + assertEquals("31/12/98", FitsDates.mjdToDateStr(51178.9999999)); + assertEquals("2009-06-18T24:00:00.000", FitsDates.mjdToDateStr(55000.99999999999)); + assertEquals("2009-06-18T23:59:59.999", FitsDates.mjdToDateStr(55000.0 + 86399.999 / 86400.0)); + } + + /** Before 1900 the year less 1900 is negative, written with C's {@code %2.2d}. */ + @Test + void mjdToDateStrBefore1900() { + // MJD 0 is 1858-11-17. + assertEquals("17/11/-42", FitsDates.mjdToDateStr(0.0)); + // MJD 15020 is 1900-01-01; the day before is 1899-12-31. + assertEquals("31/12/-01", FitsDates.mjdToDateStr(15019.0)); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsEncAipsTest.java b/src/test/java/uk/ac/starlink/ast/FitsEncAipsTest.java new file mode 100644 index 0000000..bd2b9bf --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsEncAipsTest.java @@ -0,0 +1,456 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; + +/** + * Translation of the tests of Rust {@code fitschan/enc_aips.rs}: C's {@code AIPSFromStore} and + * {@code AIPSPPFromStore}, which write the primary axis description as FITS-AIPS and FITS-AIPS++ + * cards, and the reads of AIPS headers, whose translations to FITS-WCS C's {@code SpecTrans} makes + * whatever the encoding. + * + *

{@code read_aips_spectral_felo_geo} is not translated: its header reads as a SpecFrame, which + * this library does not have. Rust's {@code write_aipspp_with_lonpole_latpole} expects no LONPOLE + * card for a LONPOLE of 180 degrees; C's {@code AIPSPPFromStore} writes any LONPOLE stored, so the + * translation expects C's card, as C probe {@code p2.c} shows for a FrameSet. The values of the + * reads through a FitsChan come from C probe {@code p1.c} (probes beside the task report). + */ +class FitsEncAipsTest { + + /** The primary axis description C's read makes of {@code header}: {@code SpecTrans}, then {@code WcsToStore}. */ + private static FitsStore readStore(String header) { + FitsCardList cards = FitsCardList.fromHeader(header); + FitsSpecTrans.specTransInplace( + cards, FitsChan.Encoding.FITS_AIPS, new FitsSpecTrans.TransAttrs(), new FitsSpecTrans.TransWarnings()); + FitsStore store = FitsWcsKeywords.extractWcsKeywordsWithAlts(cards).primary; + assertNotNull(store, "a primary axis description"); + return store; + } + + /** The stores of an image of {@code n} pixel axes, with a primary description of {@code n} axes. */ + private static FitsPlaneStores axes(int n) { + FitsPlaneStores stores = new FitsPlaneStores(n); + stores.version(' ', n); + return stores; + } + + /** The cards {@code AIPSFromStore} writes for {@code stores}, which must be written. */ + private static FitsCardList aips(FitsPlaneStores stores) { + FitsChan fc = new FitsChan(); + assertTrue(FitsEncAips.aipsFromStore(fc, stores, "astWrite", "FitsChan")); + return fc.cards(); + } + + /** The cards {@code AIPSPPFromStore} writes for {@code stores}, which must be written. */ + private static FitsCardList aipspp(FitsPlaneStores stores) { + FitsChan fc = new FitsChan(); + assertTrue(FitsEncAips.aipsppFromStore(fc, stores, "astWrite", "FitsChan")); + return fc.cards(); + } + + /** A FitsChan holding the lines of {@code header}, rewound, with Encoding {@code enc}. */ + private static FitsChan chan(String header, String enc) { + FitsChan fc = FitsHeaders.chanFromLines(header); + fc.setEncoding(enc); + return fc; + } + + private static final String CROTA_HEADER = "NAXIS = 2 / Number of axes\n" + + "CRPIX1 = 512.0 / Reference pixel\n" + + "CRPIX2 = 512.0 / Reference pixel\n" + + "CRVAL1 = 180.000000 / Reference value\n" + + "CRVAL2 = -45.000000 / Reference value\n" + + "CDELT1 = -0.0002778 / Pixel scale\n" + + "CDELT2 = 0.0002778 / Pixel scale\n" + + "CTYPE1 = 'RA---TAN' / Axis type\n" + + "CTYPE2 = 'DEC--TAN' / Axis type\n"; + + @Test + void readAipsCrota() { + // SpecTrans turns CROTA2 into a PC matrix on the celestial axes, with lambda = CDELT2 / + // CDELT1 = -1: PC2_1 = sin / lambda and PC1_2 = -sin * lambda. + FitsStore store = readStore(CROTA_HEADER + + "CROTA2 = 30.0 / Rotation angle\n" + + "EPOCH = 2000.0 / Epoch\n" + + "END"); + assertEquals(2, store.naxis); + double cos30 = Math.cos(Math.toRadians(30.0)); + double sin30 = Math.sin(Math.toRadians(30.0)); + double lambda = 0.0002778 / -0.0002778; + assertTrue(Math.abs(store.pc[0][0] - cos30) < 1e-10, "PC1_1 = cos(30)"); + assertTrue(Math.abs(store.pc[0][1] - -sin30 * lambda) < 1e-10, "PC1_2 = -sin(30) * lambda"); + assertTrue(Math.abs(store.pc[1][0] - sin30 / lambda) < 1e-10, "PC2_1 = sin(30) / lambda"); + assertTrue(Math.abs(store.pc[1][1] - cos30) < 1e-10, "PC2_2 = cos(30)"); + } + + @Test + void readAipsEpoch() { + // C probe p1 (a): EPOCH is the equinox, 0 meaning 1950, FK4 before 1984 and FK5 after. + String[][] cases = {{"2000.0", "FK5", "2000.0"}, {"1950.0", "FK4", "1950.0"}, {"0.0", "FK4", "1950.0"}}; + for (String[] c : cases) { + String header = "NAXIS = 2\n" + + "CRPIX1 = 512.0\n" + + "CRPIX2 = 512.0\n" + + "CRVAL1 = 180.000000\n" + + "CRVAL2 = -45.000000\n" + + "CDELT1 = -0.0002778\n" + + "CDELT2 = 0.0002778\n" + + "CTYPE1 = 'RA---TAN'\n" + + "CTYPE2 = 'DEC--TAN'\n" + + String.format("EPOCH = %20s", c[0]); + FrameSet fs = FitsHeaders.readFrameSet(chan(header, "FITS-AIPS")); + assertEquals(c[1], fs.getC("System"), "EPOCH " + c[0]); + assertEquals(Double.parseDouble(c[2]), fs.getD("Equinox"), "EPOCH " + c[0]); + } + } + + @Test + void readAipsppLatitudeWithoutLongitudeFails() { + // C probe p1 (b): the read reports an error. + String header = "NAXIS = 2\n" + + "CRPIX1 = 256.0\n" + + "CRPIX2 = 256.0\n" + + "CRVAL1 = 180.000000\n" + + "CRVAL2 = -30.000000\n" + + "CTYPE1 = 'VELO-LSR'\n" + + "CTYPE2 = 'DEC--TAN'\n" + + "CD1_1 = 1000.0\n" + + "CD2_2 = 0.001\n" + + "EQUINOX = 2000.0\n" + + "LONPOLE = 180.0"; + AstException e = assertThrows( + AstException.class, () -> chan(header, "FITS-AIPS++").read()); + assertTrue( + e.getMessage() + .contains("A latitude axis ('DEC--TAN') was found without a corresponding longitude axis."), + e.getMessage()); + } + + @Test + void readAipsSpectralVeloLsr() { + FitsStore store = readStore("NAXIS = 1 / Number of axes\n" + + "CRPIX1 = 1.0 / Reference pixel\n" + + "CRVAL1 = 10000.0 / Reference value\n" + + "CDELT1 = 1000.0 / Channel width\n" + + "CTYPE1 = 'VELO-LSR' / Axis type\n" + + "END"); + assertEquals("VRAD", store.ctype[0]); + assertEquals("LSRK", store.specsys); + } + + @Test + void readAipsSpectralFreqHel() { + FitsStore store = readStore("NAXIS = 1 / Number of axes\n" + + "CRPIX1 = 1.0 / Reference pixel\n" + + "CRVAL1 = 1.4e9 / Reference value\n" + + "CDELT1 = 1.0e6 / Channel width\n" + + "CTYPE1 = 'FREQ-HEL' / Axis type\n" + + "END"); + assertEquals("FREQ", store.ctype[0]); + assertEquals("BARYCENT", store.specsys); + } + + @Test + void readAipsExplicitRadesysOverrides() { + FitsStore store = readStore(CROTA_HEADER + + "EPOCH = 2000.0 / Epoch\n" + + "RADESYS = 'ICRS' / Reference frame\n" + + "END"); + assertEquals(2000.0, store.equinox); + assertEquals("ICRS", store.radesys); + } + + @Test + void writeAipsCrota() { + FitsPlaneStores stores = axes(2); + FitsStore store = stores.get(' '); + store.crpix[0] = 512.0; + store.crpix[1] = 512.0; + store.crval[0] = 180.0; + store.crval[1] = -45.0; + store.cdelt[0] = 0.0002778; + store.cdelt[1] = 0.0002778; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + double angle = Math.toRadians(30.0); + store.pc[0][0] = Math.cos(angle); + store.pc[0][1] = -Math.sin(angle); + store.pc[1][0] = Math.sin(angle); + store.pc[1][1] = Math.cos(angle); + store.equinox = 2000.0; + + FitsCardList cards = aips(stores); + double crota2 = cards.getFloat("CROTA2"); + assertTrue(Math.abs(crota2 - 30.0) < 1e-10, "CROTA2 should be ~30, got " + crota2); + assertNull(cards.getFloat("PC1_1")); + assertNull(cards.getFloat("CD1_1")); + } + + @Test + void writeAipsEpoch() { + FitsPlaneStores stores = axes(2); + FitsStore store = stores.get(' '); + store.crpix[0] = 100.0; + store.crpix[1] = 100.0; + store.crval[0] = 45.0; + store.crval[1] = 60.0; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.equinox = 2000.0; + + FitsCardList cards = aips(stores); + assertEquals(2000.0, cards.getFloat("EPOCH")); + assertNull(cards.getFloat("EQUINOX")); + } + + @Test + void writeAipsSpectral() { + FitsPlaneStores stores = axes(1); + FitsStore store = stores.get(' '); + store.crpix[0] = 1.0; + store.crval[0] = 10000.0; + store.cdelt[0] = 1000.0; + store.ctype[0] = "VRAD"; + store.cunit[0] = "m/s"; + store.specsys = "LSRK"; + + assertEquals("VELO-LSR", aips(stores).getString("CTYPE1")); + } + + @Test + void writeAipsSpectralFreqBarycent() { + FitsPlaneStores stores = axes(1); + FitsStore store = stores.get(' '); + store.crpix[0] = 1.0; + store.crval[0] = 1.4e9; + store.cdelt[0] = 1.0e6; + store.ctype[0] = "FREQ"; + store.cunit[0] = "Hz"; + store.specsys = "BARYCENT"; + + assertEquals("FREQ-HEL", aips(stores).getString("CTYPE1")); + } + + @Test + void writeAipsppCdeltForDiagonalCd() { + FitsPlaneStores stores = axes(2); + FitsStore store = stores.get(' '); + store.crpix[0] = 256.0; + store.crpix[1] = 256.0; + store.crval[0] = 180.0; + store.crval[1] = -30.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.cdelt[0] = -0.0005; + store.cdelt[1] = 0.0005; + store.equinox = 2000.0; + store.radesys = "FK5"; + + FitsCardList cards = aipspp(stores); + // No rotation: no CROTA, and CDELT from the diagonal of the CD matrix. + assertEquals(-0.0005, cards.getFloat("CDELT1")); + assertEquals(0.0005, cards.getFloat("CDELT2")); + assertNull(cards.getFloat("CROTA2")); + assertNull(cards.getFloat("CD1_1")); + assertEquals(2000.0, cards.getFloat("EPOCH")); + assertNull(cards.getFloat("EQUINOX")); + assertNull(cards.getString("RADESYS")); + } + + @Test + void writeAipsppEmitsCrotaWhenRotationConsistent() { + FitsPlaneStores stores = axes(2); + FitsStore store = stores.get(' '); + store.crpix[0] = 100.0; + store.crpix[1] = 100.0; + store.crval[0] = 45.0; + store.crval[1] = 60.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + double angle = Math.toRadians(30.0); + store.pc[0][0] = Math.cos(angle); + store.pc[0][1] = -Math.sin(angle); + store.pc[1][0] = Math.sin(angle); + store.pc[1][1] = Math.cos(angle); + store.cdelt[0] = 0.001; + store.cdelt[1] = 0.001; + store.equinox = 2000.0; + + FitsCardList cards = aipspp(stores); + double crota2 = cards.getFloat("CROTA2"); + assertTrue(Math.abs(crota2 - 30.0) < 1e-10, "CROTA2 should be ~30, got " + crota2); + assertNull(cards.getFloat("CD1_1")); + assertEquals(2000.0, cards.getFloat("EPOCH")); + assertNull(cards.getFloat("EQUINOX")); + } + + @Test + void writeAipsppWithLonpoleLatpole() { + FitsPlaneStores stores = axes(2); + FitsStore store = stores.get(' '); + store.crpix[0] = 256.0; + store.crpix[1] = 256.0; + store.crval[0] = 180.0; + store.crval[1] = -30.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + store.lonpole = 180.0; + store.latpole = -30.0; + + FitsCardList cards = aipspp(stores); + // C's AIPSPPFromStore writes any LONPOLE stored, the default included. + assertEquals(180.0, cards.getFloat("LONPOLE")); + assertEquals(-30.0, cards.getFloat("LATPOLE")); + } + + @Test + void writeAipsppNonDefaultLonpoleEmitted() { + FitsPlaneStores stores = axes(2); + FitsStore store = stores.get(' '); + store.crpix[0] = 256.0; + store.crpix[1] = 256.0; + store.crval[0] = 180.0; + store.crval[1] = -30.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + store.lonpole = 45.0; + + assertEquals(45.0, aipspp(stores).getFloat("LONPOLE")); + } + + @Test + void writeAipsppSpectralWithSpecsys() { + FitsPlaneStores stores = axes(3); + FitsStore store = stores.get(' '); + store.crpix[0] = 512.0; + store.crpix[1] = 512.0; + store.crpix[2] = 1.0; + store.crval[0] = 180.0; + store.crval[1] = -30.0; + store.crval[2] = 10000.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.ctype[2] = "VRAD"; + store.cunit[2] = "m/s"; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + store.cdelt[2] = 1000.0; + store.specsys = "LSRK"; + + FitsCardList cards = aipspp(stores); + // The standard of rest goes into the CTYPE; there is no SPECSYS card. + assertEquals("VELO-LSR", cards.getString("CTYPE3")); + assertNull(cards.getString("SPECSYS")); + } + + @Test + void readAipsCrota1Fallback() { + // C reads CROTA on the latitude axis first, then on the longitude axis, so CROTA1 is used + // when there is no CROTA2. + FitsStore store = readStore(CROTA_HEADER + + "CROTA1 = 45.0 / Rotation angle\n" + + "EPOCH = 2000.0 / Epoch\n" + + "END"); + double cos45 = Math.cos(Math.toRadians(45.0)); + double sin45 = Math.sin(Math.toRadians(45.0)); + double lambda = 0.0002778 / -0.0002778; + assertTrue(Math.abs(store.pc[0][0] - cos45) < 1e-10); + assertTrue(Math.abs(store.pc[0][1] - -sin45 * lambda) < 1e-10); + assertTrue(Math.abs(store.pc[1][0] - sin45 / lambda) < 1e-10); + assertTrue(Math.abs(store.pc[1][1] - cos45) < 1e-10); + } + + @Test + void crota1FallbackTransformsAsC() { + // C probe p1 (c): the header is guessed to be FITS-AIPS, and its FrameSet transforms two + // pixels to these sky positions. + FitsChan fc = FitsHeaders.chanFromLines(CROTA_HEADER + + "CROTA1 = 45.0 / Rotation angle\n" + + "EPOCH = 2000.0 / Epoch"); + assertEquals("FITS-AIPS", fc.getEncoding()); + FrameSet fs = FitsHeaders.readFrameSet(fc); + double[][] out = fs.tranP(2, 2, new double[][] {{512.0, 600.0}, {512.0, 400.0}}, true, 2); + CValues.assertCValues( + new double[] {out[0][0], out[1][0], out[0][1], out[1][1]}, + new double[] {3.141592653589793, -0.7853981633974482, -3.141476209154235, -0.7860838448336191}, + "pixels (512, 512) and (600, 400)"); + } + + @Test + void aipsWriteRefusesIcrs() { + // C's AIPSFromStore: ICRS is not supported. + FitsPlaneStores stores = axes(2); + FitsStore store = stores.get(' '); + store.crpix[0] = 100.0; + store.crpix[1] = 100.0; + store.crval[0] = 45.0; + store.crval[1] = 60.0; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.radesys = "ICRS"; + assertFalse(FitsEncAips.aipsFromStore(new FitsChan(), stores, "astWrite", "FitsChan")); + assertFalse(FitsEncAips.aipsppFromStore(new FitsChan(), stores, "astWrite", "FitsChan")); + } + + @Test + void aipsppWritesALonpoleOf180() { + // C probe p2: a TAN header at the north pole, where the default LONPOLE is 0, with LONPOLE + // 180, written as FITS-AIPS++ gives these cards. + FitsChan in = FitsHeaders.chan( + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 90", + "CDELT1 = -0.01", + "CDELT2 = 0.01", + "LONPOLE = 180.0", + "RADESYS = 'FK5'", + "EQUINOX = 2000.0"); + FrameSet fs = FitsHeaders.readFrameSet(in); + FitsChan out = new FitsChan(); + out.setEncoding("FITS-AIPS++"); + assertEquals(1, out.write(fs)); + out.clear("Card"); + List got = new ArrayList<>(); + String card; + while ((card = out.findFits("%f", true)) != null) { + got.add(card); + } + List want = Arrays.asList( + "CRPIX1 = 50.0 / Reference pixel on axis 1 ", + "CRPIX2 = 50.0 / Reference pixel on axis 2 ", + "CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ", + "CRVAL2 = 90.0 / Value at ref. pixel on axis 2 ", + "CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ", // codespell:ignore + "CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ", // codespell:ignore + "CDELT1 = -0.01 / Pixel size ", + "CDELT2 = 0.01 / Pixel size ", + "EPOCH = 2000.0 / Epoch of reference equinox ", + "LONPOLE = 180.0 / Longitude of native north pole ", + "DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "); + assertEquals(want, got); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsEncClassTest.java b/src/test/java/uk/ac/starlink/ast/FitsEncClassTest.java new file mode 100644 index 0000000..24da306 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsEncClassTest.java @@ -0,0 +1,217 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * C's {@code CLASSFromStore}, which writes FITS-CLASS cards, as far as this library reaches it: + * the checks it makes before it writes, which refuse every FrameSet without a SpecFrame, since + * only a SpecFrame gives the description a SPECSYS; and the tests of Rust {@code + * fitschan/enc_class.rs} that need no SpecFrame. + * + *

Rust's {@code write_class_subtracts_restfreq} and {@code write_class_sfl_to_gls} write a + * description holding SPECSYS and a rest frequency; C's {@code CLASSFromStore} then makes a + * SpecFrame for the VELO-LSR card, so they are translated to that ({@link + * #aDescriptionClassCanHoldNeedsSpecFrame}). The other reads of FITS-CLASS headers and {@code + * round_trip_class} need C's {@code ClassTrans}, part of the FITS-CLASS read, which is not + * available. The FrameSets with a FREQ axis but no SpecFrame are C probe {@code p2.c}'s (beside + * the task report). + */ +class FitsEncClassTest { + + /** The header of Rust's {@code CLASS_HEADER}. */ + private static final String CLASS_HEADER = "NAXIS = 3\n" + + "CTYPE1 = 'FREQ '\n" + + "CRVAL1 = 0.000000000000E+000\n" + + "CRPIX1 = 512.500\n" + + "CDELT1 = 0.390625000000E+005\n" + + "CTYPE2 = 'RA---TAN'\n" + + "CRVAL2 = 40.738\n" + + "CRPIX2 = 0.5\n" + + "CDELT2 = -0.0100\n" + + "CTYPE3 = 'DEC--TAN'\n" + + "CRVAL3 = 62.933\n" + + "CRPIX3 = 0.5\n" + + "CDELT3 = 0.0100\n" + + "RADESYS = 'FK5 '\n" + + "EQUINOX = 2000.0\n" + + "SPECSYS = 'SOURCE '\n" + + "RESTFREQ= 0.110201354300E+012\n" + + "VELO-LSR= 0.250000000000E+004\n" + + "DELTAV = -0.106265872717E+003\n" + + "MJD-OBS = 52413.59\n"; + + /** The primary description C's {@code WcsToStore} makes of {@link #CLASS_HEADER}, untranslated. */ + private static FitsStore classStore() { + return FitsWcsKeywords.extractWcsKeywordsWithAlts(FitsCardList.fromHeader(CLASS_HEADER)).primary; + } + + @Test + void readClassSpatialAxesUnchanged() { + FitsStore store = classStore(); + assertEquals(40.738, store.crval[1]); + assertEquals(62.933, store.crval[2]); + } + + @Test + void readClassEquinoxAndRadesys() { + FitsStore store = classStore(); + assertEquals(2000.0, store.equinox); + assertEquals("FK5", store.radesys); + } + + @Test + void readClassMjdobs() { + assertEquals(52413.59, classStore().mjdobs); + } + + @Test + void aDescriptionClassCanHoldNeedsSpecFrame() { + // The descriptions of Rust's write_class_subtracts_restfreq (RA/DEC TAN) and + // write_class_sfl_to_gls (galactic SFL at the origin): every check of CLASSFromStore + // passes, and C then makes a SpecFrame to find the VELO-LSR value. + String[][] cases = {{"RA---TAN", "DEC--TAN", "40.738", "62.933"}, {"GLON-SFL", "GLAT-SFL", "0.0", "0.0"}}; + for (String[] c : cases) { + FitsPlaneStores stores = new FitsPlaneStores(3); + FitsStore store = stores.version(' ', 3); + store.ctype[0] = "FREQ"; + store.crval[0] = 0.110201354300e12; + store.crpix[0] = 512.5; + store.cdelt[0] = 39062.5; + store.ctype[1] = c[0]; + store.crval[1] = Double.parseDouble(c[2]); + store.crpix[1] = 0.5; + store.cdelt[1] = -0.01; + store.ctype[2] = c[1]; + store.crval[2] = Double.parseDouble(c[3]); + store.crpix[2] = 0.5; + store.cdelt[2] = 0.01; + store.restfrq = 0.110201354300e12; + store.radesys = "FK5"; + store.equinox = 2000.0; + store.specsys = "SOURCE"; + store.cunit[0] = "Hz"; + FrameSet fs = new FrameSet(new Frame(3)); + double[] dim = {AstObject.AST__BAD, AstObject.AST__BAD, AstObject.AST__BAD}; + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> FitsEncClass.classFromStore(new FitsChan(), stores, fs, dim, "astWrite", "FitsChan")); + assertTrue(e.getMessage().endsWith("needs SpecFrame"), e.getMessage()); + store.specsys = null; + assertFalse(FitsEncClass.classFromStore(new FitsChan(), stores, fs, dim, "astWrite", "FitsChan"), c[0]); + } + } + + /** + * C probe p2's FrameSet: {@code npix} pixel axes; a world Frame, a CmpFrame of a plain Frame + * with Symbol FREQ and Unit Hz and the FK5 SkyFrame of a TAN header, and with four pixel axes a + * plain Frame with Symbol STOKES; the frequency axis linear. + */ + private static FrameSet freqFrameSet(int npix) { + FrameSet sky2 = FitsHeaders.readFrameSet(FitsHeaders.chan( + "NAXIS = 2", + "CRPIX1 = 5", + "CRPIX2 = 5", + "CRVAL1 = 10", + "CRVAL2 = 20", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "RADESYS = 'FK5'", + "EQUINOX = 2000")); + Mapping skymap = sky2.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Frame skyfrm = sky2.getFrame(FrameSet.AST__CURRENT); + Frame freq = new Frame(1); + freq.set("Symbol(1)=FREQ,Unit(1)=Hz,Label(1)=Frequency"); + Frame wcs = new CmpFrame(freq, skyfrm); + WinMap fmap = new WinMap( + 1, new double[] {0.0}, new double[] {1.0}, new double[] {1.0e11}, new double[] {1.0e11 + 1.0e6}); + Mapping map = new CmpMap(fmap, skymap, false); + Frame pix = new Frame(npix); + pix.setDomain("GRID"); + if (npix == 4) { + Frame stokes = new Frame(1); + stokes.set("Symbol(1)=STOKES"); + wcs = new CmpFrame(wcs, stokes); + map = new CmpMap(map, new UnitMap(1), false); + } + FrameSet fs = new FrameSet(pix); + fs.addFrame(FrameSet.AST__BASE, map, wcs); + return fs; + } + + /** A FitsChan holding the NAXIS cards of C probe p2, with Encoding {@code enc}. */ + private static FitsChan naxisChan(int npix, int naxis2, String enc) { + FitsChan fc = npix == 4 + ? FitsHeaders.chan("NAXIS = 4", "NAXIS1 = 10", "NAXIS2 = " + naxis2, "NAXIS3 = 1", "NAXIS4 = 1") + : FitsHeaders.chan("NAXIS = 3", "NAXIS1 = 10", "NAXIS2 = " + naxis2, "NAXIS3 = 1"); + fc.setEncoding(enc); + return fc; + } + + @Test + void aFrequencyAxisWithoutSpecFrameIsRefused() { + // C probe p2 (a) and (b): the description has a spectral axis (the FITS-WCS write gives + // CTYPE1 FREQ) but no SPECSYS, so CLASSFromStore refuses it, with the spatial axes + // spanning one pixel (when it first transforms pixel (1, 1, 1)) or not. + FrameSet fs = freqFrameSet(3); + FitsChan wcs = naxisChan(3, 1, "FITS-WCS"); + assertEquals(1, wcs.write(fs)); + List want = Arrays.asList( + "NAXIS = 3 ", + "NAXIS1 = 10 ", + "NAXIS2 = 1 ", + "NAXIS3 = 1 ", + "CRPIX1 = 5.0 / Reference pixel on axis 1 ", + "CRPIX2 = 5.0 / Reference pixel on axis 2 ", + "CRPIX3 = 5.0 / Reference pixel on axis 3 ", + "CRVAL1 = 100005000000.0 / Value at ref. pixel on axis 1 ", + "CRVAL2 = 10.0 / Value at ref. pixel on axis 2 ", + "CRVAL3 = 20.0 / Value at ref. pixel on axis 3 ", + "CTYPE1 = 'FREQ ' / Frequency ", + "CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ", // codespell:ignore + "CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ", // codespell:ignore + "CDELT1 = 1000000.0 / Pixel size on axis 1 ", + "CDELT2 = -0.001 / Pixel size on axis 2 ", + "CDELT3 = 0.001 / Pixel size on axis 3 ", + "CUNIT1 = 'Hz ' / Units for axis 1 ", + "MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ", + "DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ", + "RADESYS = 'FK5 ' / Reference frame for RA/DEC values ", + "EQUINOX = 2000.0 / [yr] Epoch of reference equinox "); + List got = FitsHeaders.foundCards(wcs); + assertTrue(FitsHeaders.cardsMatchC(got, want), "--- Java\n" + String.join("\n", got)); + + for (int naxis2 : new int[] {1, 5}) { + FitsChan fc = naxisChan(3, naxis2, "FITS-CLASS"); + assertEquals(0, fc.write(fs), "NAXIS2 = " + naxis2); + assertEquals(4, FitsHeaders.foundCards(fc).size(), "NAXIS2 = " + naxis2); + } + } + + @Test + void oneSpatialPixelOfAFourAxisImageFailsAsC() { + // C probe p2 (c): with four pixel axes and the spatial axes spanning one pixel, + // CLASSFromStore transforms pixel (1, 1, 1) with three coordinates, which the FrameSet's + // four inputs refuse. + FrameSet fs = freqFrameSet(4); + FitsChan wcs = naxisChan(4, 1, "FITS-WCS"); + assertEquals(1, wcs.write(fs)); + FitsChan fc = naxisChan(4, 1, "FITS-CLASS"); + AstException e = assertThrows(AstException.class, () -> fc.write(fs)); + assertEquals(AstException.AST__NCPIN, e.getStatus()); + assertTrue( + e.getMessage() + .contains("astTranN(FrameSet): Bad number of input coordinate values (3).\nThe FrameSet given" + + " requires 4 coordinate values for each input point."), + e.getMessage()); + assertEquals(5, FitsHeaders.foundCards(fc).size()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsEncDssTest.java b/src/test/java/uk/ac/starlink/ast/FitsEncDssTest.java new file mode 100644 index 0000000..c435495 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsEncDssTest.java @@ -0,0 +1,456 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.Fixtures; + +/** + * Translation of the tests of Rust {@code fitschan/enc_dss.rs}: C's {@code DSSToStore}, which + * makes the axis description of a DSS plate solution (a TPN projection whose polynomial is held as + * projection parameters), and {@code DSSFromStore}, which writes one as DSS cards; with the reads + * and writes of DSS headers through a FitsChan that C probe {@code p1.c} (beside the task report) + * makes. + * + *

Rust's {@code read_from_cards} takes the sign of the declination from the first character of + * PLTDECSN; C's {@code DSSToStore} takes it to be negative only when the first word of PLTDECSN is + * {@code -}, so {@link #pltdecsnOtherThanAMinusIsPositive} expects C's result. + */ +class FitsEncDssTest { + + /** C's {@code AST__DR2D}: degrees per radian. */ + private static final double AST__DR2D = 57.29577951308232; + + /** The header of Rust's {@code dss_test_cards}, part of the wcsconv {@code dss.fits-dss} fixture. */ + private static final String DSS_HEADER = "PLTRAH = 10 / Plate centre RA hours\n" + + "PLTRAM = 47 / Plate centre RA minutes\n" + + "PLTRAS = 57.3 / Plate centre RA seconds\n" + + "PLTDECD = 60 / Plate centre DEC degrees\n" + + "PLTDECM = 15 / Plate centre DEC arcminutes\n" + + "PLTDECS = 51.85 / Plate centre DEC arcseconds\n" + + "PLTDECSN= '-' / Plate centre DEC sign\n" + + "XPIXELSZ= 25.28 / Pixel size X (microns)\n" + + "YPIXELSZ= 25.28 / Pixel size Y (microns)\n" + + "PPO3 = -18825.9 / Plate offset X (microns)\n" + + "PPO6 = -22216.5 / Plate offset Y (microns)\n" + + "CNPIX1 = 1.0 / Corner pixel X\n" + + "CNPIX2 = 1.0 / Corner pixel Y\n" + + "AMDX1 = 67.23 / Plate solution x co-efficients\n" + + "AMDX3 = 1.36\n" + + "AMDY1 = 67.23 / Plate solution y co-efficients\n" + + "AMDY3 = 0.74\n"; + + /** {@link #DSS_HEADER} without the card of {@code skip}, and with {@code extra} added. */ + private static FitsChan dssChan(String skip, String extra, String attrs) { + StringBuilder text = new StringBuilder(); + for (String line : CValues.lines(DSS_HEADER)) { + if (skip == null || !line.startsWith(skip)) { + text.append(line).append('\n'); + } + } + if (extra != null) { + text.append(extra).append('\n'); + } + FitsChan fc = new FitsChan(); + if (!attrs.isEmpty()) { + fc.set(attrs); + } + for (String line : CValues.lines(text.toString())) { + fc.putFits(line, false); + } + fc.clear("Card"); + fc.setEncoding("DSS"); + return fc; + } + + /** The axis description C's {@code DSSToStore} makes of {@code header}. */ + private static FitsStore readStore(String header) { + return FitsEncDss.dssToStore(FitsHeaders.chanFromLines(header), "astRead", "FitsChan"); + } + + /** A FitsPlaneStores whose primary description is Rust's {@code tpn_store}: a plate scale only. */ + private static FitsPlaneStores tpnStore() { + FitsPlaneStores stores = new FitsPlaneStores(2); + FitsStore store = stores.version(' ', 2); + store.crval[0] = 180.0; + store.crval[1] = 45.0; + store.crpix[0] = 512.0; + store.crpix[1] = 512.0; + store.cdelt[0] = 1.0; + store.cdelt[1] = 1.0; + store.pc[0][0] = -0.001 * 25.0; + store.pc[1][1] = 0.001 * 25.0; + store.ctype[0] = "RA---TPN"; + store.ctype[1] = "DEC--TPN"; + store.radesys = "FK5"; + store.pv[0][1] = 67.0 / 3600.0; + store.pv[1][1] = 67.0 / 3600.0; + return stores; + } + + /** The cards {@code DSSFromStore} writes for {@code stores} into a new FitsChan, which must be written. */ + private static FitsCardList write(FitsPlaneStores stores) { + FitsChan fc = new FitsChan(); + assertTrue(FitsEncDss.dssFromStore(fc, stores, "astWrite", "FitsChan")); + return fc.cards(); + } + + @Test + void readDssPlateCentre() { + FitsStore store = readStore(DSS_HEADER); + assertEquals(15.0 * (10.0 + 47.0 / 60.0 + 57.3 / 3600.0), store.crval[0]); + } + + @Test + void readDssNegativeDec() { + FitsStore store = readStore(DSS_HEADER); + assertEquals(-(60.0 + 15.0 / 60.0 + 51.85 / 3600.0), store.crval[1]); + } + + @Test + void readDssCrpix() { + FitsStore store = readStore(DSS_HEADER); + assertEquals((-18825.9 / 25.28) - 1.0 + 0.5, store.crpix[0]); + assertEquals((-22216.5 / 25.28) - 1.0 + 0.5, store.crpix[1]); + } + + @Test + void readDssIsTpnWithUnitCdelt() { + // C's DSSToStore makes a TPN projection with CDELT 1 and the pixel sizes in the PC matrix. + FitsStore store = readStore(DSS_HEADER); + assertEquals(2, store.naxis); + assertEquals(2, (int) store.wcsaxes); + assertEquals("RA---TPN", store.ctype[0]); + assertEquals("DEC--TPN", store.ctype[1]); + assertEquals("FK5", store.radesys); + assertEquals(2000.0, store.equinox); + assertEquals(180.0, store.lonpole); + assertEquals(1.0, store.cdelt[0]); + assertEquals(1.0, store.cdelt[1]); + assertEquals(-0.001 * 25.28, store.pc[0][0]); + assertEquals(0.001 * 25.28, store.pc[1][1]); + } + + @Test + void readDssPvFromAmd() { + // AMDX1 gives PV1_1 and AMDX3 PV1_0, each divided by 3600; likewise for Y. + FitsStore store = readStore(DSS_HEADER); + assertEquals(67.23 / 3600.0, store.pv[0][1]); + assertEquals(1.36 / 3600.0, store.pv[0][0]); + assertEquals(67.23 / 3600.0, store.pv[1][1]); + assertEquals(0.74 / 3600.0, store.pv[1][0]); + } + + @Test + void readDssDefaultCnpix() { + String header = "PLTRAH = 12 / Plate centre RA hours\n" + + "PLTRAM = 0 / Plate centre RA minutes\n" + + "PLTRAS = 0.0 / Plate centre RA seconds\n" + + "PLTDECD = 45 / Plate centre DEC degrees\n" + + "PLTDECM = 0 / Plate centre DEC arcminutes\n" + + "PLTDECS = 0.0 / Plate centre DEC arcseconds\n" + + "PLTDECSN= '+'\n" + + "XPIXELSZ= 25.0 / Pixel size X (microns)\n" + + "YPIXELSZ= 25.0 / Pixel size Y (microns)\n" + + "PPO3 = 1000.0 / Plate offset X (microns)\n" + + "PPO6 = 2000.0 / Plate offset Y (microns)\n" + + "AMDX1 = 67.0 / Plate scale (arcsec/mm)\n"; + FitsStore store = readStore(header); + assertEquals(40.5, store.crpix[0]); + assertEquals(80.5, store.crpix[1]); + } + + @Test + void readDssMissingKeywordError() { + // C probe p1 (d): the message C's GetValue reports. + AstException e = assertThrows(AstException.class, () -> readStore(DSS_HEADER.replace("XPIXELSZ", "XPIXELSY"))); + assertEquals(AstException.AST__BDFTS, e.getStatus()); + assertTrue( + e.getMessage().contains("astRead(FitsChan): Unable to find a value for FITS keyword \"XPIXELSZ\"."), + e.getMessage()); + } + + @Test + void writeDssRaDecomposition() { + // RA 161.98875 degrees is 10h 47m 57.3s. + FitsPlaneStores stores = tpnStore(); + FitsStore store = stores.get(' '); + store.crval[0] = 161.98875; + FitsCardList cards = write(stores); + assertEquals(10.0, cards.getFloat("PLTRAH")); + assertEquals(47.0, cards.getFloat("PLTRAM")); + assertTrue(Math.abs(cards.getFloat("PLTRAS") - 57.3) < 0.01, "PLTRAS " + cards.getFloat("PLTRAS")); + } + + @Test + void writeDssNegativeDecSign() { + FitsPlaneStores stores = tpnStore(); + stores.get(' ').crval[1] = -60.264; + FitsCardList cards = write(stores); + assertEquals("-", cards.getString("PLTDECSN")); + assertEquals(60.0, cards.getFloat("PLTDECD")); + } + + @Test + void writeDssPositiveDecSign() { + FitsPlaneStores stores = tpnStore(); + stores.get(' ').crval[1] = 45.5; + assertEquals("+", write(stores).getString("PLTDECSN")); + } + + @Test + void writeDssEmitsFullAmdArrays() { + FitsCardList cards = write(tpnStore()); + for (int i = 1; i <= 20; i++) { + assertNotNull(cards.getFloat("AMDX" + i), "AMDX" + i); + assertNotNull(cards.getFloat("AMDY" + i), "AMDY" + i); + } + for (int i = 1; i <= 6; i++) { + assertNotNull(cards.getFloat("PPO" + i), "PPO" + i); + } + } + + @Test + void writeDssRejectsRotation() { + FitsPlaneStores stores = tpnStore(); + stores.get(' ').pc[0][1] = 0.1; + FitsChan fc = new FitsChan(); + assertFalse(FitsEncDss.dssFromStore(fc, stores, "astWrite", "FitsChan")); + assertEquals(0, fc.cards().len()); + } + + @Test + void writeDssRequires2d() { + FitsPlaneStores stores = tpnStore(); + FitsStore store = stores.version(' ', 3); + store.crpix[2] = 1.0; + assertFalse(FitsEncDss.dssFromStore(new FitsChan(), stores, "astWrite", "FitsChan")); + } + + @Test + void writeDssRequiresFk5TanOrTpn() { + FitsPlaneStores stores = tpnStore(); + stores.get(' ').radesys = "GALACTIC"; + assertFalse(FitsEncDss.dssFromStore(new FitsChan(), stores, "astWrite", "FitsChan")); + } + + @Test + void roundTripPreservesCoordinates() { + FitsPlaneStores stores = tpnStore(); + FitsStore original = stores.get(' '); + original.crval[0] = 161.98875; + original.crval[1] = -60.264; + FitsChan fc = new FitsChan(); + assertTrue(FitsEncDss.dssFromStore(fc, stores, "astWrite", "FitsChan")); + fc.clear("Card"); + FitsStore recovered = FitsEncDss.dssToStore(fc, "astRead", "FitsChan"); + assertTrue(Math.abs(original.crval[0] - recovered.crval[0]) < 1.0 / 3600.0); + assertTrue(Math.abs(original.crval[1] - recovered.crval[1]) < 1.0 / 3600.0); + } + + // ------------------------------------------------------------------ + // Reads and writes through a FitsChan (C probe p1) + // ------------------------------------------------------------------ + + /** The pixels C probe p1 transforms, as tranP takes them. */ + private static final double[][] PIXELS = {{1.0, 265.0, 530.0, 100.5}, {1.0, 265.0, 530.0, 400.25}}; + + /** {@code fs} applied to {@link #PIXELS}, as (x, y) pairs of outputs, in C probe p1's order. */ + private static double[] transformed(FrameSet fs) { + double[][] out = fs.tranP(4, 2, PIXELS, true, 2); + double[] flat = new double[8]; + for (int i = 0; i < 4; i++) { + flat[2 * i] = out[0][i]; + flat[2 * i + 1] = out[1][i]; + } + return flat; + } + + /** The keyword of each card {@code fc} has not used, in order, as C probe p1 lists them. */ + private static List unusedKeywords(FitsChan fc) { + List out = new ArrayList<>(); + for (String card : FitsHeaders.foundCards(fc)) { + out.add(card.substring(0, 8).trim()); + } + return out; + } + + @Test + void readUsesEveryDssCard() { + // C probe p1 (a): the header's encoding is guessed to be DSS; the read uses every card + // DSSToStore reads (PLTSCALE and PPO1, PPO2, PPO4 and PPO5 among them), but not EQUINOX or + // EPOCH, and the FrameSet transforms as C's. + FitsChan fc = FitsHeaders.fixture("wcsconv/inputs/dss.fits-dss"); + fc.setFitsDigits(8); + assertEquals("DSS", fc.getEncoding()); + assertEquals(108, fc.getNcard()); + FrameSet fs = FitsHeaders.readFrameSet(fc); + assertEquals(50, fc.getNcard()); + List blanks = new ArrayList<>(); + for (int i = 0; i < 15; i++) { + blanks.add(""); + } + List want = new ArrayList<>(Arrays.asList( + "SIMPLE", + "BITPIX", + "NAXIS", + "NAXIS1", + "NAXIS2", + "EXTEND", + "DATE", + "ORIGIN", + "PLTLABEL", + "PLATEID", + "REGION", + "DATE-OBS", + "UT", + "EPOCH", + "EQUINOX", + "EXPOSURE", + "BANDPASS", + "PLTGRADE", + "SITELAT", + "SITELONG", + "TELESCOP", + "DATATYPE", + "SCANIMG", + "SCANNUM", + "DCHOPPED", + "DSHEARED", + "DSCNDNUM")); + want.addAll(blanks); + want.addAll(Arrays.asList("DATAMAX", "DATAMIN", "OBJECT", "OBJCTRA", "OBJCTDEC", "OBJCTX", "OBJCTY", "END")); + assertEquals(want, unusedKeywords(fc)); + assertEquals(2, fs.getNframe()); + CValues.assertCValues( + transformed(fs), + new double[] { + 2.8150213850747887, -1.044517052126356, + 2.810755733626352, -1.042312576865633, + 2.806506259777323, -1.0400918379780315, + 2.8134723132726647, -1.0412170511937375 + }, + "the pixels of probe p1 (a)"); + } + + @Test + void writtenAndReadBackAsC() { + // C probe p1 (b): the FrameSet read, written as DSS into a new FitsChan, gives the cards + // of wcsconv's dss.dss (which C writes from the FrameSet's native dump), and those cards + // read back transform as C's. + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.fixture("wcsconv/inputs/dss.fits-dss")); + FitsChan out = new FitsChan(); + out.set("Encoding=DSS,FitsDigits=8"); + assertEquals(1, out.write(fs)); + assertEquals(58, out.getNcard()); + List want = new ArrayList<>(); + for (String line : CValues.lines(Fixtures.read("wcsconv/expected/dss.dss"))) { + want.add(line); + } + List got = FitsHeaders.foundCards(out); + assertTrue(FitsHeaders.cardsMatchC(got, want), "--- Java\n" + String.join("\n", got)); + out.clear("Card"); + FrameSet back = FitsHeaders.readFrameSet(out); + assertEquals(0, out.getNcard()); + CValues.assertCValues( + transformed(back), + new double[] { + 2.815021385072929, -1.0445170521259821, + 2.8107557336245015, -1.0423125768652555, + 2.8065062597754826, -1.040091837977651, + 2.8134723132708164, -1.0412170511933625 + }, + "the pixels of probe p1 (b)"); + } + + @Test + void failedReadLeavesTheCards() { + // C probe p1 (d): a read that fails reports C's error and, with Clean unset, leaves every + // card unused; with Clean set, the cards read before the error (CNPIX1, CNPIX2, PPO3 and + // PPO6) are used. + FitsChan fc = dssChan("XPIXELSZ", null, ""); + AstException e = assertThrows(AstException.class, fc::read); + assertTrue(e.getMessage().contains("Unable to find a value for FITS keyword \"XPIXELSZ\"."), e.getMessage()); + assertEquals(16, fc.getNcard()); + + FitsChan clean = dssChan("XPIXELSZ", null, "Clean=1"); + assertThrows(AstException.class, clean::read); + assertEquals(12, clean.getNcard()); + List left = unusedKeywords(clean); + for (String used : Arrays.asList("CNPIX1", "CNPIX2", "PPO3", "PPO6")) { + assertFalse(left.contains(used), used + " is used"); + } + + FitsChan zero = dssChan("XPIXELSZ", "XPIXELSZ= 0.0", ""); + e = assertThrows(AstException.class, zero::read); + assertEquals(AstException.AST__BDFTS, e.getStatus()); + assertTrue( + e.getMessage().contains("astRead(FitsChan): FITS keyword XPIXELSZ has illegal value 0.0"), + e.getMessage()); + assertEquals(17, zero.getNcard()); + + FitsChan string = dssChan("PPO3", "PPO3 = 'abc'", ""); + e = assertThrows(AstException.class, string::read); + assertEquals(AstException.AST__FTCNV, e.getStatus()); + assertTrue( + e.getMessage().contains("astRead(FitsChan): Cannot convert FITS keyword 'PPO3' to floating point."), + e.getMessage()); + assertEquals(17, string.getNcard()); + } + + @Test + void pltdecsnOtherThanAMinusIsPositive() { + // C probe p1 (e): the reference pixel transformed, in degrees, for three PLTDECSN values; + // only a first word of '-' makes the declination negative. + String[][] cases = { + {"PLTDECSN= '-5'", "161.98951165622611", "60.264608331152985"}, + {"PLTDECSN= ' - '", "161.98951164665871", "-60.264197220041915"}, + {"PLTDECSN= '+'", "161.98951165622611", "60.264608331152985"} + }; + for (String[] c : cases) { + FrameSet fs = FitsHeaders.readFrameSet(dssChan("PLTDECSN", c[0], "")); + double[] out = FitsHeaders.tran( + fs, new double[] {-18825.9 / 25.28 - 1.0 + 0.5, -22216.5 / 25.28 - 1.0 + 0.5}, true); + CValues.assertCValues( + new double[] {out[0] * AST__DR2D, out[1] * AST__DR2D}, + new double[] {Double.parseDouble(c[1]), Double.parseDouble(c[2])}, + c[0]); + } + } + + @Test + void rustHeaderTransformsAsC() { + // C probe p1 (f): Rust's test header, read, uses every card and transforms as C's. + FitsChan fc = dssChan(null, null, ""); + FrameSet fs = FitsHeaders.readFrameSet(fc); + assertEquals(0, fc.getNcard()); + CValues.assertCValues( + transformed(fs), + new double[] { + 2.8150101217105368, -1.0445227121800418, + 2.810742362755056, -1.042320796878139, + 2.8064910737385897, -1.0401027971023051, + 2.813456552045181, -1.0412243189021584 + }, + "the pixels of probe p1 (f)"); + } + + @Test + void readDssProducesFrameSet() { + // Rust tests/test_fitschan_encodings.rs read_dss_produces_frameset: C's own DSS cards read + // as a FrameSet of two two-dimensional Frames (C probe p1 (b) reads the same cards). + FitsChan fc = FitsHeaders.fixture("wcsconv/expected/dss.dss"); + assertEquals("DSS", fc.getEncoding()); + FrameSet fs = FitsHeaders.readFrameSet(fc); + assertEquals(2, fs.getNframe()); + assertEquals(2, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsEncIrafTest.java b/src/test/java/uk/ac/starlink/ast/FitsEncIrafTest.java new file mode 100644 index 0000000..bcead3b --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsEncIrafTest.java @@ -0,0 +1,99 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the writer tests of Rust {@code fitschan/enc_iraf.rs}: C's {@code IRAFFromStore}, + * which writes the primary axis description as FITS-IRAF cards. The module's reader, {@code + * read_from_cards}, is not used by the Rust port's read and has no counterpart here, so its tests + * are not translated. + */ +class FitsEncIrafTest { + + /** The stores of an image of two pixel axes, with a primary description of two axes. */ + private static FitsPlaneStores twoAxes() { + FitsPlaneStores stores = new FitsPlaneStores(2); + stores.version(' ', 2); + return stores; + } + + @Test + void writeIrafProducesCd() { + FitsPlaneStores stores = twoAxes(); + FitsStore store = stores.get(' '); + store.crpix[0] = 256.0; + store.crpix[1] = 256.0; + store.crval[0] = 180.0; + store.crval[1] = -30.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.cdelt[0] = -0.0005; + store.cdelt[1] = 0.0005; + store.radesys = "FK5"; + store.equinox = 2000.0; + + FitsChan fc = new FitsChan(); + assertTrue(FitsEncIraf.irafFromStore(fc, stores, "astWrite", "FitsChan")); + FitsCardList cards = fc.cards(); + assertEquals(-0.0005, cards.getFloat("CD1_1")); + assertEquals(0.0005, cards.getFloat("CD2_2")); + assertEquals("FK5", cards.getString("RADECSYS")); + assertNull(cards.getString("RADESYS")); + assertNull(cards.getFloat("CDELT1")); + assertNull(cards.getFloat("CDELT2")); + assertNull(cards.getFloat("PC1_1")); + assertNull(cards.find("WCSAXES")); + assertNull(cards.getFloat("LONPOLE")); + } + + @Test + void writeIrafComputesCdFromPc() { + FitsPlaneStores stores = twoAxes(); + FitsStore store = stores.get(' '); + store.crpix[0] = 100.0; + store.crpix[1] = 100.0; + store.crval[0] = 45.0; + store.crval[1] = 60.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + // A rotation by 30 degrees. + store.pc[0][0] = 0.866025; + store.pc[0][1] = -0.5; + store.pc[1][0] = 0.5; + store.pc[1][1] = 0.866025; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + + FitsChan fc = new FitsChan(); + assertTrue(FitsEncIraf.irafFromStore(fc, stores, "astWrite", "FitsChan")); + FitsCardList cards = fc.cards(); + // CDi_j = PCi_j * CDELTi. + assertTrue(Math.abs(cards.getFloat("CD1_1") - -0.000866025) < 1e-10); + assertTrue(Math.abs(cards.getFloat("CD1_2") - 0.0005) < 1e-10); + assertTrue(Math.abs(cards.getFloat("CD2_1") - 0.0005) < 1e-10); + assertTrue(Math.abs(cards.getFloat("CD2_2") - 0.000866025) < 1e-10); + } + + @Test + void translateSflToGls() { + FitsPlaneStores stores = twoAxes(); + FitsStore store = stores.get(' '); + store.crpix[0] = 100.0; + store.crpix[1] = 100.0; + store.crval[0] = 0.0; + store.crval[1] = 0.0; + store.ctype[0] = "GLON-SFL"; + store.ctype[1] = "GLAT-SFL"; + store.cdelt[0] = -0.01; + store.cdelt[1] = 0.01; + + FitsChan fc = new FitsChan(); + assertTrue(FitsEncIraf.irafFromStore(fc, stores, "astWrite", "FitsChan")); + assertEquals("GLON-GLS", fc.cards().getString("CTYPE1")); + assertEquals("GLAT-GLS", fc.cards().getString("CTYPE2")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsEncPcTest.java b/src/test/java/uk/ac/starlink/ast/FitsEncPcTest.java new file mode 100644 index 0000000..974c2fc --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsEncPcTest.java @@ -0,0 +1,126 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the writer tests of Rust {@code fitschan/enc_pc.rs}: C's {@code PCFromStore}, + * which writes axis descriptions as FITS-PC cards. The module's reader, {@code read_from_cards}, is + * not used by the Rust port's read and has no counterpart here, so its tests are not translated. + */ +class FitsEncPcTest { + + /** The stores of an image of two pixel axes, with no descriptions yet. */ + private static FitsPlaneStores twoAxes() { + return new FitsPlaneStores(2); + } + + /** The primary description of {@code stores}, of two axes. */ + private static FitsStore primary(FitsPlaneStores stores) { + return stores.version(' ', 2); + } + + @Test + void writePc3digit() { + FitsPlaneStores stores = twoAxes(); + FitsStore store = primary(stores); + store.crpix[0] = 512.0; + store.crpix[1] = 512.0; + store.crval[0] = 180.0; + store.crval[1] = -45.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.cdelt[0] = -0.0002778; + store.cdelt[1] = 0.0002778; + // A rotation by 30 degrees. + store.pc[0][0] = 0.866025; + store.pc[0][1] = -0.5; + store.pc[1][0] = 0.5; + store.pc[1][1] = 0.866025; + store.radesys = "FK5"; + store.equinox = 2000.0; + + FitsChan fc = new FitsChan(); + assertTrue(FitsEncPc.pcFromStore(fc, stores, "astWrite", "FitsChan")); + FitsCardList cards = fc.cards(); + + assertNotNull(cards.getFloat("PC001001")); + assertNotNull(cards.getFloat("PC001002")); + assertNotNull(cards.getFloat("PC002001")); + assertNotNull(cards.getFloat("PC002002")); + assertNull(cards.getFloat("PC1_1")); + assertEquals(-0.0002778, cards.getFloat("CDELT1")); + assertEquals(0.0002778, cards.getFloat("CDELT2")); + assertEquals("FK5", cards.getString("RADECSYS")); + assertNull(cards.getString("RADESYS")); + assertNull(cards.getFloat("CD1_1")); + } + + @Test + void writePcNeedsCdelt() { + // FITS-PC writes a CDELT for every axis, so a store without them writes nothing, and the + // cards written before the gap was found are removed. + FitsPlaneStores stores = twoAxes(); + FitsStore store = primary(stores); + store.crpix[0] = 256.0; + store.crpix[1] = 256.0; + store.crval[0] = 45.0; + store.crval[1] = 60.0; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.pc[0][1] = 0.5; + + FitsChan fc = new FitsChan(); + fc.cards().beginMarkingNew(); + assertFalse(FitsEncPc.pcFromStore(fc, stores, "astWrite", "FitsChan")); + assertEquals(0, fc.cards().len()); + } + + @Test + void writePcSflToGls() { + FitsPlaneStores stores = twoAxes(); + FitsStore store = primary(stores); + store.crpix[0] = 100.0; + store.crpix[1] = 100.0; + store.crval[0] = 0.0; + store.crval[1] = 0.0; + store.ctype[0] = "GLON-SFL"; + store.ctype[1] = "GLAT-SFL"; + store.cdelt[0] = -0.01; + store.cdelt[1] = 0.01; + + FitsChan fc = new FitsChan(); + assertTrue(FitsEncPc.pcFromStore(fc, stores, "astWrite", "FitsChan")); + assertEquals("GLON-GLS", fc.cards().getString("CTYPE1")); + assertEquals("GLAT-GLS", fc.cards().getString("CTYPE2")); + } + + @Test + void writePcIdentityNotWritten() { + FitsPlaneStores stores = twoAxes(); + FitsStore store = primary(stores); + store.crpix[0] = 50.0; + store.crpix[1] = 50.0; + store.crval[0] = 10.0; + store.crval[1] = 20.0; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.pc[0][0] = 1.0; + store.pc[1][1] = 1.0; + + FitsChan fc = new FitsChan(); + assertTrue(FitsEncPc.pcFromStore(fc, stores, "astWrite", "FitsChan")); + FitsCardList cards = fc.cards(); + assertNull(cards.getFloat("PC001001")); + assertNull(cards.getFloat("PC001002")); + assertNull(cards.getFloat("PC002001")); + assertNull(cards.getFloat("PC002002")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsFiducialTest.java b/src/test/java/uk/ac/starlink/ast/FitsFiducialTest.java index 36f2a7c..d1e1270 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsFiducialTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsFiducialTest.java @@ -1,13 +1,14 @@ package uk.ac.starlink.ast; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import org.junit.jupiter.api.Test; /** - * Translation of the unit tests of Rust {@code fitschan/fset_to_store/fiducial.rs} that test - * {@code get_fiducial_nsc} (C {@code GetFiducialNSC}, fitschan.c:12902). The tests of {@code - * get_fiducial_wcs} belong to the FITS-WCS writer. + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/fiducial.rs} (C {@code + * GetFiducialNSC} and {@code GetFiducialWCS}, fitschan.c). Rust's {@code invalid_axes_return_none} + * is not translated: C reads past its array for an output that does not exist. */ class FitsFiducialTest { @@ -50,4 +51,57 @@ void nscTpnAlwaysUsesNative() { assertEquals(wm.natLon(), nsc[0]); assertEquals(wm.natLat(), nsc[1]); } + + /** Through a UnitMap the celestial fiducial point is the native one. */ + @Test + void wcsWithUnitMap2ReturnsNativeFiducial() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + double[] nsc = FitsFiducial.getFiducialNsc(wm); + double[] r = FitsFiducial.getFiducialWcs(wm, new UnitMap(2), 0, 1); + assertEquals(nsc[0], r[0]); + assertEquals(nsc[1], r[1]); + } + + @Test + void wcsWithPvOverridesPassesThroughToCelestial() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.setPV(0, 0, 1.0); + wm.setPV(0, 1, 45.0); + wm.setPV(0, 2, 30.0); + double[] r = FitsFiducial.getFiducialWcs(wm, new UnitMap(2), 0, 1); + assertEquals(DD2R * 45.0, r[0]); + assertEquals(DD2R * 30.0, r[1]); + } + + /** A bad celestial coordinate means the fiducial point cannot be found (C returns 0). */ + @Test + void wcsWithABadValueReturnsNull() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + PermMap pm = new PermMap(2, new int[] {1, 2}, 2, new int[] {1, 0}, null); + assertNull(FitsFiducial.getFiducialWcs(wm, pm, 0, 1)); + } + + /** + * The projection plane coordinates of the fiducial point: the origin for a default TAN + * projection, whose fiducial point is its reference point, and the projection of the native + * point that parameters 1 and 2 of the longitude axis give otherwise. + */ + @Test + void ppcOfTheFiducialPoint() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.invert(); + double[] ppc = FitsFiducial.getFiducialPpc(wm); + assertEquals(0.0, ppc[0], 1e-15); + assertEquals(0.0, ppc[1], 1e-15); + + WcsMap car = new WcsMap(2, WcsMap.AST__CAR, 1, 2); + car.setPV(0, 0, 1.0); + car.setPV(0, 1, 10.0); + car.setPV(0, 2, 20.0); + car.invert(); + ppc = FitsFiducial.getFiducialPpc(car); + // CAR: x = phi, y = theta. + assertEquals(DD2R * 10.0, ppc[0], 1e-15); + assertEquals(DD2R * 20.0, ppc[1], 1e-15); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsFsetToStoreTest.java b/src/test/java/uk/ac/starlink/ast/FitsFsetToStoreTest.java new file mode 100644 index 0000000..4032637 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsFsetToStoreTest.java @@ -0,0 +1,483 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/mod.rs}, {@code + * fitschan/wcs_write/plane_stores.rs} and {@code spectral_axes.rs} (C {@code FsetToStore}, {@code + * AddVersion}, {@code MakeFitsFrameSet}, {@code FitsAxisOrder}, {@code ReadCrval} and {@code + * SpectralAxes}, fitschan.c) that need no class this library lacks, and the store C fills for + * FrameSets written by a C-oracle probe linked against the pinned C library: each expected value + * is the card C writes from that store entry. C's cards are rounded (its {@code RoundFString} + * removes runs of four or more 0s or 9s), so where the value of a card is rounded it is compared + * to within 4 units in the last place. + * + *

Not translated: the {@code spectral_axes.rs} tests other than {@code + * no_spectral_axis_returns_unitmap}, which need SpecFrame. + */ +class FitsFsetToStoreTest { + + /** A FrameSet from a GRID Frame to {@code current} through {@code map}. */ + private static FrameSet frameSet(Mapping map, Frame current) { + Frame pixel = new Frame(map.getNin()); + pixel.setDomain("GRID"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, map, current); + return fs; + } + + private static Frame frame(int naxes, String settings) { + Frame f = new Frame(naxes); + f.set(settings); + return f; + } + + private static FitsPlaneStores fsetToStore(FitsChan fc, FrameSet fs, double... dim) { + return FitsFsetToStore.fsetToStore( + fc, fs, fs.getNin(), dim, FitsChan.Encoding.FITS_WCS, "FitsChan", "astWrite"); + } + + /** Whether {@code actual} is within 4 units in the last place of {@code expected}. */ + private static void assertUlp(double expected, Double actual) { + assertNotNull(actual); + assertEquals(expected, actual, 4 * Math.ulp(expected), "value " + actual); + } + + /** {@link #assertUlp} for each element. */ + private static void assertUlp(double[] expected, Double[] actual) { + for (int i = 0; i < expected.length; i++) { + assertUlp(expected[i], actual[i]); + } + } + + /** The FrameSet of the probe's {@code basic_shift}, Rust's {@code basic_two_axis_shift}. */ + private static FrameSet basicShift() { + return frameSet( + new ShiftMap(new double[] {10, 20}), + frame(2, "Domain=WORLD,Label(1)=wx,Label(2)=wy,Unit(1)=m,Unit(2)=m")); + } + + @Test + void basicTwoAxisShift() { + FitsPlaneStores stores = fsetToStore(new FitsChan(), basicShift(), 100, 100); + assertNotNull(stores); + assertEquals(2, stores.naxis); + FitsStore store = stores.get(' '); + assertEquals("WORLD", store.wcsname); + assertArrayEquals(new Double[] {50.0, 50.0}, store.crpix); + assertArrayEquals(new Double[] {60.0, 70.0}, store.crval); + assertArrayEquals(new String[] {"WORLD1", "WORLD2"}, store.ctype); + assertArrayEquals(new String[] {"wx", "wy"}, store.ctypeCom); + assertArrayEquals(new Double[] {1.0, 1.0}, store.cdelt); + assertArrayEquals(new String[] {"m", "m"}, store.cunit); + assertNull(store.pc[0][1]); + assertNull(store.wcsaxes); + for (char s = 'A'; s <= 'Z'; s++) { + assertNull(stores.get(s)); + } + } + + @Test + void identityChainYieldsCentralPixelCrpix() { + FitsStore store = fsetToStore(new FitsChan(), frameSet(new UnitMap(2), frame(2, "Domain=WORLD")), 100, 100) + .get(' '); + assertEquals(50.0, store.crpix[0], 1e-6); + assertEquals(50.0, store.crpix[1], 1e-6); + } + + @Test + void noSpectralAxisReturnsUnitMap() { + Mapping map = FitsFsetToStore.spectralAxes(basicShift()); + assertInstanceOf(UnitMap.class, map); + assertEquals(2, map.getNin()); + } + + @Test + void fitsAxisOrderSwapsTheAxes() { + // C probe axisorder_swap and axisorder_extra_words: words naming no axis are passed over. + for (String order : new String[] {"WORLD2 WORLD1", "foo WORLD2 bar world1"}) { + FitsChan fc = new FitsChan(); + fc.setC("FitsAxisOrder", order); + FitsStore store = fsetToStore(fc, basicShift(), 100, 100).get(' '); + assertArrayEquals(new Double[] {70.0, 60.0}, store.crval, order); + assertArrayEquals(new String[] {"WORLD2", "WORLD1"}, store.ctype, order); + assertArrayEquals(new String[] {"wy", "wx"}, store.ctypeCom, order); + assertEquals(0.0, store.pc[0][0], order); + assertEquals(1.0, store.pc[0][1], order); + assertEquals(1.0, store.pc[1][0], order); + assertEquals(0.0, store.pc[1][1], order); + } + } + + @Test + void fitsAxisOrderCopyKeepsTheFrameOrder() { + FitsChan fc = new FitsChan(); + fc.setC("FitsAxisOrder", ""); + FitsStore store = fsetToStore(fc, basicShift(), 100, 100).get(' '); + assertArrayEquals(new Double[] {60.0, 70.0}, store.crval); + } + + @Test + void fitsAxisOrderNamingAnAxisTwiceIsAnError() { + FitsChan fc = new FitsChan(); + fc.setC("FitsAxisOrder", "WORLD1 world1 WORLD2"); + AstException e = assertThrows(AstException.class, () -> fsetToStore(fc, basicShift(), 100, 100)); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertEquals( + "astWrite(fitschan): attribute FitsAxisOrder (WORLD1 world1 WORLD2) refers to axis world1 more" + + " than once. (AST__ATTIN)", + e.getMessage()); + } + + @Test + void fitsAxisOrderLeavingOutAnAxisIsAnError() { + FitsChan fc = new FitsChan(); + fc.setC("FitsAxisOrder", "WORLD2"); + AstException e = assertThrows(AstException.class, () -> fsetToStore(fc, basicShift(), 100, 100)); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertEquals( + "astWrite(fitschan): attribute FitsAxisOrder (WORLD2) does not specify a position for WCS axis" + + " 'WORLD1'. (AST__ATTIN)", + e.getMessage()); + } + + @Test + void primaryOnlyYieldsOnePlane() { + FitsPlaneStores stores = + fsetToStore(new FitsChan(), frameSet(new UnitMap(2), frame(2, "Domain=WORLD")), 100, 100); + assertNotNull(stores.get(' ')); + for (char s = 'A'; s <= 'Z'; s++) { + assertNull(stores.get(s)); + } + } + + @Test + void altFrameWithIdentAYieldsTwoPlanes() { + FrameSet fs = frameSet(new UnitMap(2), frame(2, "Domain=WORLD")); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(2), frame(2, "Domain=WORLD2,Ident=A")); + fs.setCurrent(2); + FitsPlaneStores stores = fsetToStore(new FitsChan(), fs, 100, 100); + assertEquals("WORLD", stores.get(' ').wcsname); + assertEquals("WORLD2", stores.get('A').wcsname); + for (char s = 'B'; s <= 'Z'; s++) { + assertNull(stores.get(s)); + } + } + + /** The FrameSet of the probe's {@code ident_letters}. */ + private static FrameSet identLetters() { + FrameSet fs = frameSet(new ShiftMap(new double[] {10, 20}), frame(2, "Domain=WORLD")); + fs.addFrame(FrameSet.AST__BASE, new ZoomMap(2, 2.0), frame(2, "Domain=A3,Ident=Z")); + fs.addFrame(FrameSet.AST__BASE, new ZoomMap(2, 3.0), frame(2, "Domain=A4")); + fs.addFrame(FrameSet.AST__BASE, new ZoomMap(2, 4.0), frame(2, "Domain=IWCX")); + fs.setCurrent(2); + return fs; + } + + @Test + void altFramesTakeIdentLettersThenTheFreeOnes() { + // C probe ident_letters: frame 3 takes its Ident Z, frame 4 the first free letter A, and + // the IWC frame none. + FitsPlaneStores stores = fsetToStore(new FitsChan(), identLetters(), 100, 100); + FitsStore a = stores.get('A'); + assertEquals("A4", a.wcsname); + assertUlp(new double[] {150.0, 150.0}, a.crval); + assertUlp(new double[] {3.0, 3.0}, a.cdelt); + assertArrayEquals(new String[] {"A41", "A42"}, a.ctype); + FitsStore z = stores.get('Z'); + assertEquals("A3", z.wcsname); + assertUlp(new double[] {100.0, 100.0}, z.crval); + assertUlp(new double[] {2.0, 2.0}, z.cdelt); + assertNull(stores.get('B')); + assertEquals("WORLD", stores.get(' ').wcsname); + } + + @Test + void altAxesIdentUsesOnlyIdentLetters() { + FitsChan fc = new FitsChan(); + fc.setC("AltAxes", "IDENT"); + FitsPlaneStores stores = fsetToStore(fc, identLetters(), 100, 100); + assertNull(stores.get('A')); + assertEquals("A3", stores.get('Z').wcsname); + } + + @Test + void altAxesNoneWritesOnlyThePrimary() { + FitsChan fc = new FitsChan(); + fc.setC("AltAxes", "NONE"); + FitsPlaneStores stores = fsetToStore(fc, identLetters(), 100, 100); + assertNotNull(stores.get(' ')); + for (char s = 'A'; s <= 'Z'; s++) { + assertNull(stores.get(s)); + } + } + + /** A 2-D PolyMap whose first output is a quadratic that is zero at pixel 50. */ + private static PolyMap zeroAtCentreQuadratic() { + PolyMap pm = new PolyMap(2, 2, 3, new double[] {-25.0, 1, 0, 0, 0.01, 1, 2, 0, 1.0, 2, 0, 1}, 0, new double[0]); + pm.set("IterInverse=1"); + return pm; + } + + @Test + void anAlternateThatFailsLeavesNoCrpix() { + // C probe alt_fails: frame 3 cannot be described, so its version A gets no CRPIX (and C + // writes no cards for it); frame 4 is B. + FrameSet fs = frameSet(new ShiftMap(new double[] {10, 20}), frame(2, "Domain=WORLD")); + fs.addFrame(FrameSet.AST__BASE, zeroAtCentreQuadratic(), frame(2, "Domain=BAD")); + fs.addFrame(FrameSet.AST__BASE, new ZoomMap(2, 3.0), frame(2, "Domain=GOOD")); + fs.setCurrent(2); + FitsPlaneStores stores = fsetToStore(new FitsChan(), fs, 100, 100); + FitsStore a = stores.get('A'); + assertNotNull(a); + assertNull(a.crpix[0]); + assertEquals(0.0, a.crval[0]); + assertNull(a.wcsname); + FitsStore b = stores.get('B'); + assertEquals("GOOD", b.wcsname); + assertUlp(new double[] {150.0, 150.0}, b.crval); + } + + @Test + void aPrimaryThatFailsGivesNoStore() { + // C probe primary_fails: the write returns 0. + FrameSet fs = frameSet(zeroAtCentreQuadratic(), frame(2, "Domain=BAD")); + assertNull(fsetToStore(new FitsChan(), fs, 100, 100)); + } + + @Test + void aMappingWithNoInverseNeedsTabOk() { + PolyMap pm = new PolyMap(1, 1, 1, new double[] {2.0, 1, 1}, 0, new double[0]); + pm.set("IterInverse=0"); + assertFalse(pm.getTranInverse()); + assertNull(fsetToStore(new FitsChan(), frameSet(pm, new Frame(1)), 100)); + } + + @Test + void noDomainGivesNoWcsname() { + // C probe no_domain_small_crval. + FitsStore store = fsetToStore(new FitsChan(), frameSet(new ZoomMap(2, 1.0e-9), new Frame(2)), 100, 100) + .get(' '); + assertNull(store.wcsname); + assertArrayEquals(new String[] {"x1", "x2"}, store.ctype); + assertUlp(5.0e-8, store.crval[0]); + assertUlp(1.0e-9, store.cdelt[0]); + } + + @Test + void aCrvalSmallAgainstThePixelSizeIsZero() { + // AddVersion: |CRVAL| below sqrt(DBL_EPSILON) times the pixel size becomes zero; the + // centre pixel 50 maps to 1e-10 here, against a pixel size of 1. + FrameSet fs = frameSet(new ShiftMap(new double[] {-50 + 1.0e-10}), new Frame(1)); + FitsStore store = fsetToStore(new FitsChan(), fs, 100).get(' '); + assertEquals(0.0, store.crval[0]); + FrameSet big = frameSet(new ShiftMap(new double[] {-50 + 1.0e-7}), new Frame(1)); + assertTrue(fsetToStore(new FitsChan(), big, 100).get(' ').crval[0] > 0.0); + } + + /** A FitsChan holding a 1-D header whose reference value is 0.1 at pixel 1, 7 per pixel. */ + private static FitsChan oneAxisHeader() { + return FitsChan.fromHeader(String.join( + "\n", "NAXIS = 1", "NAXIS1 = 100", "CTYPE1 = 'X'", "CRPIX1 = 1", "CRVAL1 = 0.1", "CDELT1 = 7")); + } + + @Test + void crpixIsRoundedToAMillionthOfAPixel() { + // The FrameSet read from the FitsChan, with its pixel coordinates shifted by 1/7, written + // back: the reference value 0.1 the FitsChan holds is at pixel 1 + 1/7 = 1.142857142..., + // which AddVersion rounds to 1.142857. + FitsChan fc = oneAxisHeader(); + FrameSet fs = (FrameSet) fc.read(); + fs.remapFrame(FrameSet.AST__BASE, new ShiftMap(new double[] {1.0 / 7})); + FitsStore store = fsetToStore(fc, fs, 100).get(' '); + assertEquals(0.1, store.crval[0]); + assertEquals(Math.floor((1 + 1.0 / 7) * 1.0e6 + 0.5) * 1.0e-6, store.crpix[0]); + } + + @Test + void aReferencePointThatCannotBeConvertedIsNotUsed() { + // C probe winmap_naxis: a FrameSet to a plain Frame written to a FitsChan holding a + // reference value cannot convert the FitsChan's Frame to its own, and takes the centre + // pixel 50 as reference, with the value 0.3 there. + FitsChan fc = FitsChan.fromHeader( + String.join("\n", "NAXIS1 = 100", "CTYPE1 = 'X'", "CRPIX1 = 1", "CRVAL1 = 0.1")); + FrameSet fs = frameSet( + new WinMap(1, new double[] {0}, new double[] {1}, new double[] {-349.7}, new double[] {-342.7}), + new Frame(1)); + assertNull(FitsFsetToStore.readCrval(fc, fs.getFrame(FrameSet.AST__CURRENT), ' ', "FitsChan", "astWrite")); + FitsStore store = fsetToStore(fc, fs, 100).get(' '); + assertEquals(0.3, store.crval[0], 1.0e-12); + assertArrayEquals(new Double[] {50.0}, store.crpix); + assertUlp(7.0, store.cdelt[0]); + assertArrayEquals(new String[] {"x1"}, store.ctype); + } + + @Test + void dut1AndDtaiAreStoredForThePrimary() { + Frame w = frame(2, "Domain=WORLD,Dut1=0.5,Dtai=37"); + FitsPlaneStores stores = fsetToStore(new FitsChan(), frameSet(new UnitMap(2), w), 100, 100); + assertEquals(0.5 / 86400.0, stores.get(' ').dut1); + assertEquals(37.0, stores.get(' ').dtai); + } + + @Test + void aNonSkyDomainSkyFrameIsRemappedToDegrees() { + // C probe foo_skyframe: MakeFitsFrameSet maps the radians of a SkyFrame whose Domain is + // not SKY into its external degrees, and OtherAxes describes its axes as linear. + SkyFrame sky = new SkyFrame(); + sky.setDomain("FOO"); + FitsStore store = fsetToStore(new FitsChan(), frameSet(new ZoomMap(2, 0.001), sky), 100, 100) + .get(' '); + assertEquals("FOO", store.wcsname); + assertArrayEquals(new Double[] {50.0, 50.0}, store.crpix); + assertUlp(2.8647889756541165, store.crval[0]); + assertUlp(2.8647889756541165, store.crval[1]); + assertArrayEquals(new String[] {"RA", "Dec"}, store.ctype); + assertEquals("Type of co-ordinate on axis 1", store.ctypeCom[0]); // codespell:ignore + assertEquals("Type of co-ordinate on axis 2", store.ctypeCom[1]); // codespell:ignore + assertUlp(0.057295779513082325, store.cdelt[0]); + assertUlp(0.057295779513082325, store.cdelt[1]); + assertArrayEquals(new String[] {"deg", "deg"}, store.cunit); + } + + @Test + void twoSkyFramesCannotBeDescribed() { + // MakeFitsFrameSet finds two SkyFrames and makes no FrameSet; C then passes the NULL + // FrameSet to AddEncodingFrame, which crashes (C probe: EXC_BAD_ACCESS in astGetFrame_). + SkyFrame gal = new SkyFrame(); + gal.setSystem("Galactic"); + CmpFrame cf = new CmpFrame(new SkyFrame(), gal); + FrameSet fs = frameSet(new ZoomMap(4, 0.001), cf); + assertNull(FitsFsetToStore.makeFitsFrameSet( + new FitsChan(), fs, 1, 2, FitsChan.Encoding.FITS_WCS, "FitsChan", "astWrite")); + assertNull(fsetToStore(new FitsChan(), fs, 100, 100, 100, 100)); + } + + @Test + void theReferencePointAlreadyInTheFitsChanIsUsed() { + // C probe readcrval: the FrameSet read from the FitsChan, written back to it, keeps + // CRVAL1 7.5 at CRPIX1 1. + FitsChan fc = FitsChan.fromHeader(String.join( + "\n", "NAXIS = 1", "NAXIS1 = 100", "CTYPE1 = 'X'", "CRPIX1 = 1", "CRVAL1 = 7.5", "CDELT1 = 1")); + FrameSet fs = (FrameSet) fc.read(); + FitsStore store = fsetToStore(fc, fs, 100).get(' '); + assertArrayEquals(new Double[] {7.5}, store.crval); + assertArrayEquals(new Double[] {1.0}, store.crpix); + assertArrayEquals(new String[] {"X"}, store.ctype); + assertUlp(1.0, store.cdelt[0]); + } + + @Test + void readCrvalGivesNullWithoutCrvalCards() { + assertNull(FitsFsetToStore.readCrval(new FitsChan(), new Frame(1), ' ', "FitsChan", "astWrite")); + } + + /** The FrameSet of the probe's {@code offset_sky}: a TAN header with an offset SkyFrame. */ + private static FrameSet offsetSky() { + FitsChan rfc = FitsChan.fromHeader(String.join( + "\n", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 30", + "CRVAL2 = 40", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "RADESYS = 'FK5'", + "EQUINOX = 2000.0")); + FrameSet fs = (FrameSet) rfc.read(); + fs.set("SkyRef(1)=0.5,SkyRef(2)=0.7,SkyRefIs=Origin"); + return fs; + } + + @Test + void anOffsetSkyFrameAlsoGetsAnAbsoluteDescription() { + // C probe offset_sky. + FrameSet fs = offsetSky(); + FitsPlaneStores stores = fsetToStore(new FitsChan(), fs, 100, 100); + FitsStore p = stores.get(' '); + assertArrayEquals(new Double[] {50.0, 50.0}, p.crpix); + // The offset coordinates this FrameSet gives at the centre pixel differ from C's by up + // to 20 units in the last place, before any FITS description is made (C probe: astTran2 + // of pixel 50, 50 gives 1.0357383636595399 degrees, this library 1.0357383636595365). + assertEquals(1.0357383636595399, p.crval[0], 1.0e-14); + assertEquals(-0.0991726866058769, p.crval[1], 1.0e-14); + assertArrayEquals(new String[] {"OFLN-TAN", "OFLT-TAN"}, p.ctype); + assertEquals("RA offset from 1:54:35.5, 40:06:25", p.ctypeCom[0]); + assertEquals(-10.0e-4, p.cdelt[0], 1.0e-14); + assertEquals(0.001, p.cdelt[1], 1.0e-14); + assertEquals(0.9998844526457898, p.pc[0][0], 1.0e-14); + assertEquals(0.01520136037429563, p.pc[0][1], 1.0e-14); + assertEquals(-0.015201360374295859, p.pc[1][0], 1.0e-14); + assertEquals(0.9998844526457898, p.pc[1][1], 1.0e-14); + assertEquals("FK5", p.radesys); + assertEquals(2000.0, p.equinox); + + FitsStore a = stores.get('A'); + assertArrayEquals(new Double[] {50.0, 50.0}, a.crpix); + assertUlp(30.0, a.crval[0]); + assertUlp(40.0, a.crval[1]); + assertArrayEquals(new String[] {"RA---TAN", "DEC--TAN"}, a.ctype); + assertUlp(-0.001, a.cdelt[0]); + assertUlp(0.001, a.cdelt[1]); + assertEquals("ORIGIN", a.skyrefis); + assertEquals("FK5", a.radesys); + assertNull(stores.get('B')); + + // SkyRefIs is restored on the caller's FrameSet. + assertEquals("Origin", fs.getC("SkyRefIs")); + } + + @Test + void theAbsoluteDescriptionsLetterIsNotCheckedAgainstIdentLetters() { + // C probe offset_sky_collide: the absolute description of the offset primary takes the + // letter after the last one handed out, A, which frame 3 also has as its Ident; both + // descriptions are stored as version A, the second overwriting what both store. + FrameSet fs = offsetSky(); + fs.addFrame(FrameSet.AST__BASE, new ZoomMap(2, 3.0), frame(2, "Domain=A3,Ident=A")); + fs.setCurrent(2); + FitsStore a = fsetToStore(new FitsChan(), fs, 100, 100).get('A'); + assertEquals("A3", a.wcsname); + assertArrayEquals(new Double[] {50.0, 50.0}, a.crpix); + assertUlp(new double[] {150.0, 150.0}, a.crval); + assertArrayEquals(new String[] {"A31", "A32"}, a.ctype); + assertUlp(new double[] {3.0, 3.0}, a.cdelt); + // Left by the absolute sky description. + assertEquals("ORIGIN", a.skyrefis); + assertEquals("FK5", a.radesys); + assertEquals(2000.0, a.equinox); + } + + @Test + void planeStoreIndexRejectsOtherCharacters() { + FitsPlaneStores stores = new FitsPlaneStores(2); + AstException e = assertThrows(AstException.class, () -> stores.get('a')); + assertEquals(AstException.AST__INTER, e.getStatus()); + } + + @Test + void aStoreUsedTwiceGrowsToTheLargerAxisCount() { + FitsPlaneStores stores = new FitsPlaneStores(1); + FitsStore s1 = stores.version('A', 1); + s1.crval[0] = 1.0; + FitsStore s2 = stores.version('A', 3); + assertSame(s1, s2); + assertEquals(3, s2.crval.length); + assertEquals(1.0, s2.crval[0]); + assertEquals(3, s2.pc[2].length); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsHeaders.java b/src/test/java/uk/ac/starlink/ast/FitsHeaders.java index f292d63..cb49161 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsHeaders.java +++ b/src/test/java/uk/ac/starlink/ast/FitsHeaders.java @@ -158,4 +158,94 @@ static String[] cards(JsonNode node) { } return out; } + + /** + * Every card of {@code fc} a read has not consumed, as C's probes list them: the FitsChan + * rewound, then {@code findFits} with the template {@code %f} until it finds no more. + */ + static List foundCards(FitsChan fc) { + fc.clear("Card"); + List out = new ArrayList<>(); + String card; + while ((card = fc.findFits("%f", true)) != null) { + out.add(card); + } + return out; + } + + /** {@code cards}, each padded with spaces to 80 characters, as {@link #foundCards} lists them. */ + static List padded(String... cards) { + List out = new ArrayList<>(); + for (String card : cards) { + StringBuilder b = new StringBuilder(card); + while (b.length() < 80) { + b.append(' '); + } + out.add(b.toString()); + } + return out; + } + + /** The strings of a JSON array, in order. */ + static List strings(JsonNode node) { + List out = new ArrayList<>(); + for (JsonNode n : node) { + out.add(n.asText()); + } + return out; + } + + /** + * The largest difference, in units in the last place, of a number on a card written here from + * the number on C's card, as the {@code wcsconv} gate allows. + */ + static final long CARD_ULPS = 4; + + /** + * Whether the cards (or other lines) {@code got} are C's {@code want}: the same text, but for + * numbers within {@link #CARD_ULPS} of C's, written to the same width or a width the white + * space beside them absorbs. + */ + static boolean cardsMatchC(List got, List want) { + return cardsMatchC(got, want, java.util.Collections.emptySet()); + } + + /** + * {@link #cardsMatchC(List, List)}, but the numbers on the cards whose keywords are in {@code + * libm} need only be within {@link CValues#withinLibmRounding} of C's: those that a difference + * of the runtime's elementary functions (java.lang.Math) from C's libm reaches. + */ + static boolean cardsMatchC(List got, List want, java.util.Set libm) { + return cardsMatchC(got, want, libm, java.util.Collections.emptyMap()); + } + + /** + * {@link #cardsMatchC(List, List, java.util.Set)}, but the number on a card whose keyword is + * a key of {@code atol} need only be within that absolute tolerance of C's. + */ + static boolean cardsMatchC( + List got, List want, java.util.Set libm, java.util.Map atol) { + if (got.size() != want.size()) { + return false; + } + for (int i = 0; i < got.size(); i++) { + String g = got.get(i) + "\n"; + String w = want.get(i) + "\n"; + String key = want.get(i).length() >= 8 + ? want.get(i).substring(0, 8).trim() + : want.get(i).trim(); + boolean ok; + if (atol.containsKey(key)) { + ok = CValues.nativeStringsWithin(g, w, atol.get(key)); + } else if (libm.contains(key)) { + ok = CValues.nativeStringsWithinLibmRounding(g, w); + } else { + ok = CValues.nativeStringsEquivalent(g, w, CARD_ULPS); + } + if (!ok) { + return false; + } + } + return true; + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsInvertableTest.java b/src/test/java/uk/ac/starlink/ast/FitsInvertableTest.java new file mode 100644 index 0000000..3c6e2eb --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsInvertableTest.java @@ -0,0 +1,81 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/invertable.rs} (C {@code + * MakeInvertable}). C's matrix is indexed {@code fullmat[input][output]}, the transpose of the + * Rust tests' {@code cd[[output, input]]}; the matrices here are the Rust ones transposed. + */ +class FitsInvertableTest { + + private static final double BAD = AstObject.AST__BAD; + + @Test + void alreadyInvertableUnchanged() { + double[][] m = {{1.0, 0.0}, {0.0, 1.0}}; + FitsInvertable.makeInvertable(m, 2, new double[] {100.0, 100.0}); + assertArrayEquals(new double[] {1.0, 0.0}, m[0]); + assertArrayEquals(new double[] {0.0, 1.0}, m[1]); + } + + /** Input 1 affects no output and spans one pixel: its diagonal element becomes 1. */ + @Test + void degenerateInputZeroedColumnPatched() { + double[][] m = {{2.0, 3.0}, {0.0, 0.0}}; + FitsInvertable.makeInvertable(m, 2, new double[] {100.0, 1.0}); + assertEquals(2.0, m[0][0]); + assertEquals(3.0, m[0][1]); + assertEquals(0.0, m[1][0]); + assertEquals(1.0, m[1][1]); + } + + @Test + void nonDegenerateZeroedColumnLeftAlone() { + double[][] m = {{2.0, 3.0}, {0.0, 0.0}}; + FitsInvertable.makeInvertable(m, 2, new double[] {100.0, 50.0}); + assertEquals(0.0, m[1][1]); + } + + @Test + void unknownDimTreatedAsNonDegenerate() { + double[][] m = {{2.0, 3.0}, {0.0, 0.0}}; + FitsInvertable.makeInvertable(m, 2, new double[] {100.0, BAD}); + assertEquals(0.0, m[1][1]); + } + + @Test + void inputWithPartialZeroColumnUnchanged() { + double[][] m = {{2.0, 3.0}, {0.5, 0.0}}; + FitsInvertable.makeInvertable(m, 2, new double[] {100.0, 1.0}); + assertEquals(0.5, m[1][0]); + assertEquals(0.0, m[1][1]); + } + + @Test + void threeAxisOneDegenerate() { + double[][] m = {{1.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 1.0, 0.0}}; + FitsInvertable.makeInvertable(m, 3, new double[] {100.0, 1.0, 50.0}); + assertEquals(1.0, m[0][0]); + assertEquals(1.0, m[1][1]); + assertEquals(0.0, m[2][2]); + } + + /** + * C reads one dimension per matrix input, though its caller holds one per pixel axis, fewer when + * the matrix has degenerate axes added; an input with no dimension is not patched. + */ + @Test + void inputsBeyondTheDimensionsAreNotPatched() { + double[][] m = {{0.0, 0.0}, {0.0, 0.0}}; + FitsInvertable.makeInvertable(m, 2, new double[0]); + assertEquals(0.0, m[0][0]); + assertEquals(0.0, m[1][1]); + FitsInvertable.makeInvertable(m, 2, new double[] {1.0}); + assertEquals(1.0, m[0][0]); + assertEquals(0.0, m[1][1]); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsIsMapLinearTest.java b/src/test/java/uk/ac/starlink/ast/FitsIsMapLinearTest.java new file mode 100644 index 0000000..8d669d8 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsIsMapLinearTest.java @@ -0,0 +1,83 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Translation of the unit tests of Rust {@code fitschan/fset_to_store/is_map_linear.rs} (C {@code IsMapLinear}). */ +class FitsIsMapLinearTest { + + /** + * A ZoomMap over a narrow range far from zero: the Hz to GHz unit Mapping of 20 channels of + * 39062.5 Hz at 1.1e11 Hz, which C judges linear since its fit is made to offset values + * (c-library-quirks.md, "IsMapLinear judges a linear Mapping non-linear when its values are far + * from zero"). + */ + @Test + void linearFarFromZero() { + ZoomMap m = new ZoomMap(1, 1.0e-9); + double lo = 1.102e11 - 9.0 * 39062.5; + double hi = 1.102e11 + 10.0 * 39062.5; + assertTrue(FitsIsMapLinear.isMapLinear(m, new double[] {lo}, new double[] {hi}, 0, null)); + } + + @Test + void unitMapIsLinear() { + UnitMap m = new UnitMap(2); + assertTrue(FitsIsMapLinear.isMapLinear(m, new double[] {0, 0}, new double[] {1, 1}, 0, null)); + assertTrue(FitsIsMapLinear.isMapLinear(m, new double[] {0, 0}, new double[] {1, 1}, 1, null)); + } + + @Test + void shiftMapIsLinear() { + ShiftMap m = new ShiftMap(new double[] {5.0, 10.0}); + assertTrue(FitsIsMapLinear.isMapLinear(m, new double[] {0, 0}, new double[] {100, 100}, 0, null)); + } + + @Test + void zoomMapIsLinear() { + ZoomMap m = new ZoomMap(2, 7.5); + assertTrue(FitsIsMapLinear.isMapLinear(m, new double[] {0, 0}, new double[] {1, 1}, 0, null)); + } + + @Test + void winMapIsLinear() { + WinMap m = new WinMap(new double[] {-128.0, -128.0}, new double[] {0.001, 0.001}); + assertTrue(FitsIsMapLinear.isMapLinear(m, new double[] {1, 1}, new double[] {100, 100}, 0, null)); + } + + @Test + void tanOverLargeBoxIsNotLinear() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + assertFalse(FitsIsMapLinear.isMapLinear(wm, new double[] {-1, -1}, new double[] {1, 1}, 0, null)); + } + + /** C's {@code MapBox} reports an output that does not exist, and IsMapLinear clears the error. */ + @Test + void outOfRangeAxisReturnsFalse() { + UnitMap m = new UnitMap(2); + assertFalse(FitsIsMapLinear.isMapLinear(m, new double[] {0, 0}, new double[] {1, 1}, 5, null)); + } + + /** The input that alone feeds the output is returned, or -1 when no single input does. */ + @Test + void coordInNamesTheFeedingInput() { + PermMap pm = new PermMap(2, new int[] {2, 1}, 2, new int[] {2, 1}, null); + int[] coordIn = {99}; + assertTrue(FitsIsMapLinear.isMapLinear(pm, new double[] {0, 0}, new double[] {10, 10}, 0, coordIn)); + assertEquals(1, coordIn[0]); + MatrixMap mm = new MatrixMap(2, 2, new double[][] {{1.0, 2.0}, {3.0, 4.0}}); + assertTrue(FitsIsMapLinear.isMapLinear(mm, new double[] {0, 0}, new double[] {10, 10}, 0, coordIn)); + assertEquals(-1, coordIn[0]); + } + + /** Inverting the Mapping to split it leaves it as it was. */ + @Test + void theMappingIsLeftAsItWas() { + ZoomMap m = new ZoomMap(2, 7.5); + assertTrue(FitsIsMapLinear.isMapLinear(m, new double[] {0, 0}, new double[] {1, 1}, 0, null)); + assertFalse(m.getInvert()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsLogMapTest.java b/src/test/java/uk/ac/starlink/ast/FitsLogMapTest.java new file mode 100644 index 0000000..500bc54 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsLogMapTest.java @@ -0,0 +1,66 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * {@link FitsLogMap} transforms as the MathMap {@code logs=log(s)}, {@code s=exp(logs)} of C's + * {@code LogAxis} (fitschan.c) does. The values expected are those of that MathMap in the pinned C + * library (C probe {@code mm.c} of the final review fixes), to within one unit in the last place, + * by which {@link Math#log} and {@link Math#exp} may differ from the C library's. + */ +class FitsLogMapTest { + + private static final double BAD = AstObject.AST__BAD; + + @Test + void forwardIsTheNaturalLogarithmAndBadForNoPositiveValue() { + double[] in = {0.0, -1.0, BAD, 1.0, 1e308, Double.NaN, 1000.0, -1000.0, 709.8}; + double[] want = {BAD, BAD, BAD, 0.0, 709.1962086421661, BAD, 6.907755278982137, BAD, 6.564983240212396}; + double[] got = new FitsLogMap().tran1(in.length, in, true); + for (int i = 0; i < in.length; i++) { + assertEquals(want[i], got[i], Math.ulp(want[i]), "log(" + in[i] + ")"); + } + } + + @Test + void inverseIsTheExponentialAndBadOnOverflow() { + // C's evaluator gives AST__BAD for an exponential that overflows, where the C library + // reports the overflow in errno; the pinned build on macOS, whose libm does not set errno, + // gives an infinity for 1000 and 709.8. + double[] in = {0.0, -1.0, BAD, 1.0, 1e308, Double.NaN, 1000.0, -1000.0, 709.8}; + double[] want = {1.0, 0.36787944117144233, BAD, 2.718281828459045, BAD, BAD, BAD, 0.0, BAD}; + double[] got = new FitsLogMap().tran1(in.length, in, false); + for (int i = 0; i < in.length; i++) { + assertEquals(want[i], got[i], Math.ulp(want[i]), "exp(" + in[i] + ")"); + } + } + + @Test + void invertingSwapsTheDirections() { + FitsLogMap m = new FitsLogMap(); + m.invert(); + assertEquals(2.718281828459045, m.tran1(1, new double[] {1.0}, true)[0], Math.ulp(2.718281828459045)); + assertEquals(6.907755278982137, m.tran1(1, new double[] {1000.0}, false)[0], Math.ulp(6.907755278982137)); + } + + @Test + void neverMergesWithItsNeighbours() { + // A MathMap merges only with another MathMap (mathmap.c MapMerge), and no FrameSet of this + // library holds one, so the Mapping is left in place whatever its neighbours. + FitsLogMap log = new FitsLogMap(); + Mapping s = new CmpMap(new ZoomMap(1, 2.0), new CmpMap(log, new UnitMap(1), true), true).simplify(); + assertInstanceOf(CmpMap.class, s); + Mapping[] parts = s.decompose(null, null); + assertInstanceOf(ZoomMap.class, parts[0]); + assertInstanceOf(FitsLogMap.class, parts[1]); + assertFalse(log.isLinear()); + assertTrue(log.getTranForward() && log.getTranInverse()); + assertEquals(1, log.getNin()); + assertEquals(1, log.getNout()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsMakeIntWorldTest.java b/src/test/java/uk/ac/starlink/ast/FitsMakeIntWorldTest.java new file mode 100644 index 0000000..e9d5cd0 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsMakeIntWorldTest.java @@ -0,0 +1,257 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static uk.ac.starlink.ast.PolyTerms.flat; +import static uk.ac.starlink.ast.PolyTerms.term; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/make_int_world.rs} (C + * {@code MakeIntWorld}), with the values the C function gives for them, and tests of the + * degenerate-axis branches and of C's {@code NearestPix}. + */ +class FitsMakeIntWorldTest { + + private static final double BAD = AstObject.AST__BAD; + + private static final double FITSTOL = 0.001; + + /** A FrameSet from a GRID Frame to an IWC Frame through {@code pixelToIwc}. */ + private static FrameSet frameSet(Mapping pixelToIwc, Frame iwc) { + Frame pixel = new Frame(pixelToIwc.getNin()); + pixel.setDomain("GRID"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, pixelToIwc, iwc); + return fs; + } + + private static boolean makeIntWorld(FrameSet fs, FitsStore store, double[] dim, boolean sipok) { + Mapping map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Frame fr = fs.getFrame(FrameSet.AST__CURRENT); + int[] wperm = new int[map.getNout()]; + for (int i = 0; i < wperm.length; i++) { + wperm[i] = i; + } + return FitsMakeIntWorld.makeIntWorld(map, fr, wperm, ' ', store, dim, FITSTOL, sipok, "astWrite", "FitsChan"); + } + + /** + * Pixel and IWC coordinates equal: the root pixel is the grid centre (50.5, 50.5), which is + * also its IWC position, so CRPIX is (0, 0) and the CD matrix is the unit matrix. + */ + @Test + void identityPixelToIwc() { + FrameSet fs = frameSet(new UnitMap(2), new Frame(2)); + FitsStore store = new FitsStore(2); + assertTrue(makeIntWorld(fs, store, new double[] {100, 100}, false)); + assertEquals(0.0, store.crpix[0], 1e-9); + assertEquals(0.0, store.crpix[1], 1e-9); + assertEquals(1.0, store.cdelt[0], 1e-9); + assertEquals(1.0, store.cdelt[1], 1e-9); + assertNull(store.pc[0][0]); + assertNull(store.pc[0][1]); + assertNull(store.wcsaxes); + } + + /** + * IWC = -128 + 0.001 * pixel: CDELT is 0.001 and CRPIX the pixel at IWC zero, 128000, which + * the Mapping takes back to IWC zero. + */ + @Test + void winMap2x2RecoversCrpixAndCd() { + WinMap win = new WinMap(new double[] {-128.0, -128.0}, new double[] {0.001, 0.001}); + FrameSet fs = frameSet(win, new Frame(2)); + FitsStore store = new FitsStore(2); + assertTrue(makeIntWorld(fs, store, new double[] {100, 100}, false)); + assertEquals(0.001, store.cdelt[0], 1e-9); + assertEquals(0.001, store.cdelt[1], 1e-9); + assertEquals(128000.0, store.crpix[0], 1e-6); + assertEquals(128000.0, store.crpix[1], 1e-6); + Mapping map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + double[][] iwc = map.transform(new double[][] {{store.crpix[0]}, {store.crpix[1]}}, 1, true); + assertEquals(0.0, iwc[0][0], 1e-6); + assertEquals(0.0, iwc[1][0], 1e-6); + } + + /** A CD matrix of 30 degrees rotation and scale 0.5, after a shift putting IWC zero at (50.5, 50.5). */ + @Test + void rotatedMatrixRecoversPcAndCdelt() { + double theta = Math.toRadians(30.0); + double s = Math.sin(theta); + double c = Math.cos(theta); + double cdelt = 0.5; + MatrixMap mm = new MatrixMap(2, 2, new double[][] {{cdelt * c, -cdelt * s}, {cdelt * s, cdelt * c}}); + CmpMap chain = new CmpMap(new ShiftMap(new double[] {-50.5, -50.5}), mm, true); + FrameSet fs = frameSet(chain, new Frame(2)); + FitsStore store = new FitsStore(2); + assertTrue(makeIntWorld(fs, store, new double[] {100, 100}, false)); + assertEquals(cdelt, store.cdelt[0], 1e-9); + assertEquals(cdelt, store.cdelt[1], 1e-9); + assertEquals(50.5, store.crpix[0], 1e-6); + assertEquals(50.5, store.crpix[1], 1e-6); + assertEquals(c, store.pc[0][0], 1e-9); + assertEquals(-s, store.pc[0][1], 1e-9); + assertEquals(s, store.pc[1][0], 1e-9); + assertEquals(c, store.pc[1][1], 1e-9); + } + + /** A Mapping with fewer outputs than inputs cannot be described. */ + @Test + void noutLessThanNinReturnsFalse() { + PermMap pm = new PermMap(3, new int[] {1, 2, -1}, 2, new int[] {1, 2}, new double[] {0.0}); + FrameSet fs = frameSet(pm, new Frame(2)); + FitsStore store = new FitsStore(3); + assertFalse(makeIntWorld(fs, store, new double[] {100, 100, 100}, false)); + assertNull(store.crpix[0]); + assertNull(store.cdelt[0]); + } + + /** + * One pixel axis and two WCS axes, the second constant at 0.25: the degenerate axis gets a + * unit vector orthogonal to the first, its CRPIX is 1 - 0.25 scaled to a unit diagonal element, + * and, the WCS axis being linear and fed by the degenerate axis alone, CRPIX is moved to 1 and + * CRVAL to 1 * (1 - 0.75) + 20. WCSAXES is written since there are fewer pixel than WCS axes. + */ + @Test + void wcsaxesSetWhenNinLessThanNwcs() { + PermMap pm = new PermMap(1, new int[] {1}, 2, new int[] {1, -1}, new double[] {0.25}); + FrameSet fs = frameSet(pm, new Frame(2)); + FitsStore store = new FitsStore(2); + store.crval[0] = 10.0; + store.crval[1] = 20.0; + assertTrue(makeIntWorld(fs, store, new double[] {100}, false)); + assertEquals(2, store.wcsaxes.intValue()); + assertEquals(0.0, store.crpix[0], 1e-9); + assertEquals(1.0, store.crpix[1]); + assertEquals(10.0, store.crval[0]); + assertEquals(20.25, store.crval[1], 1e-12); + assertEquals(1.0, store.cdelt[0], 1e-9); + assertEquals(1.0, store.cdelt[1], 1e-9); + } + + /** The degenerate pixel axis of a SkyFrame pair, as in {@link #degenerateLatitudeAxis}. */ + private static FitsStore degenerateSky(String domain) { + Mapping map = new CmpMap( + new ZoomMap(1, -0.001), new PermMap(1, new int[] {1}, 2, new int[] {1, -1}, new double[] {0.02}), true); + SkyFrame sky = new SkyFrame(); + if (domain != null) { + sky.setDomain(domain); + } + FitsStore store = new FitsStore(2); + assertTrue(makeIntWorld(frameSet(map, sky), store, new double[] {100}, false)); + return store; + } + + /** + * A celestial pair with the latitude axis degenerate: its column is scaled so that its + * diagonal element is minus that of the longitude axis, k = 0.001, and CRPIX = 1 + (1 - 0.02 - + * 1) / k = -19. + */ + @Test + void degenerateLatitudeAxis() { + FitsStore store = degenerateSky(null); + assertEquals(0.0, store.crpix[0], 1e-9); + assertEquals(-19.0, store.crpix[1], 1e-9); + assertEquals(-0.001, store.cdelt[0], 1e-15); + assertEquals(0.001, store.cdelt[1], 1e-15); + } + + /** + * C's MakeIntWorld pairs celestial axes with its IsASkyFrame macro, which also needs the Domain + * SKY; with another Domain the degenerate column keeps a unit diagonal element and CRPIX is 1 + * - 0.02. + */ + @Test + void degenerateSkyAxisNeedsTheSkyDomain() { + FitsStore store = degenerateSky("OTHER"); + assertEquals(0.98, store.crpix[1], 1e-12); + assertEquals(-0.001, store.cdelt[0], 1e-15); + assertEquals(1.0, store.cdelt[1], 1e-15); + } + + /** + * Translation of Rust {@code sip_chain_routes_through_sip_int_world}: with SipOK set and a + * SkyFrame, a SIP-shaped chain goes through {@code SIPIntWorld}, whose CRPIX values (the grid + * position C's simplified chain gives for IWC zero) are used for the celestial axes, whose + * coefficients are stored, and which adds {@code -SIP} to the CTYPE values. + */ + @Test + void sipChainRoutesThroughSipIntWorld() { + double[] fwd = flat( + term(1.0, 1, 1, 0), + term(1.0, 2, 0, 1), + term(2.9656e-06, 1, 0, 2), + term(3.7746e-09, 1, 0, 3), + term(2.1886e-05, 1, 1, 1), + term(-2.3863e-05, 1, 2, 0), + term(2.31e-05, 2, 0, 2), + term(-2.4386e-05, 2, 1, 1), + term(2.1197e-06, 2, 2, 0)); + double[] inv = flat( + term(1.0, 1, 1, 0), + term(1.0, 2, 0, 1), + term(-6.4275e-07, 1, 0, 1), + term(-1.4897e-05, 1, 1, 0), + term(2.4146e-05, 1, 2, 0), + term(-1.6588e-05, 2, 0, 1), + term(2.4753e-05, 2, 1, 1), + term(2.0482e-08, 2, 3, 0)); + double[] cd = {0.000249756880272355, 0.000230177809743655, 0.000230428519265417, -0.000249965770576587}; + Mapping chain = new CmpMap( + new CmpMap( + new ShiftMap(new double[] {-128.0, -128.0}), + new PolyMap(2, 2, fwd.length / 4, fwd, inv.length / 4, inv), + true), + new MatrixMap(2, 2, MatrixMap.FULL, cd), + true); + FrameSet fs = frameSet(chain, new SkyFrame()); + FitsStore store = new FitsStore(2); + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + assertTrue(makeIntWorld(fs, store, new double[] {256, 256}, true)); + assertEquals(128.0, store.crpix[0], 1e-6); + assertEquals(128.0, store.crpix[1], 1e-6); + assertEquals("RA---TAN-SIP", store.ctype[0]); + assertEquals("DEC--TAN-SIP", store.ctype[1]); + assertEquals(2.9656e-06, store.sipA[0][2]); + assertEquals(2.31e-05, store.sipB[0][2]); + assertEquals(-6.4275e-07, store.sipAp[0][1]); + assertEquals(2.0482e-08, store.sipBp[3][0]); + } + + /** With SipOK set, a SkyFrame and no PolyMap, SIPIntWorld finds no SIP distortion. */ + @Test + void sipWithoutAPolyMapTakesTheLinearDescription() { + FitsStore store = new FitsStore(2); + assertTrue(makeIntWorld(frameSet(new UnitMap(2), new SkyFrame()), store, new double[] {100, 100}, true)); + assertEquals(0, store.sipA.length); + assertEquals(0.0, store.crpix[0], 1e-9); + } + + /** NearestPix: 5.3 is pixel 2.65, which rounds to 3, value 6; -5 is pixel -2.5, rounded away from zero. */ + @Test + void nearestPixRoundsThePixelPosition() { + ZoomMap zoom = new ZoomMap(1, 2.0); + assertEquals(6.0, FitsMakeIntWorld.nearestPix(zoom, 5.3, 0)); + assertEquals(-6.0, FitsMakeIntWorld.nearestPix(zoom, -5.0, 0)); + assertEquals(BAD, FitsMakeIntWorld.nearestPix(zoom, BAD, 0)); + } + + /** + * NearestPix on a Mapping with no inverse splits off the axis; an axis whose split Mapping has + * no inverse keeps its value. + */ + @Test + void nearestPixSplitsAMappingWithNoInverse() { + PolyMap square = new PolyMap(1, 1, 1, new double[] {1.0, 1, 2}, 0, null); + square.set("IterInverse=0"); + CmpMap map = new CmpMap(new ZoomMap(1, 2.0), square, false); + assertEquals(6.0, FitsMakeIntWorld.nearestPix(map, 5.3, 0)); + assertEquals(5.3, FitsMakeIntWorld.nearestPix(map, 5.3, 1)); + assertFalse(map.getInvert()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsMapTabTest.java b/src/test/java/uk/ac/starlink/ast/FitsMapTabTest.java new file mode 100644 index 0000000..1f71b7a --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsMapTabTest.java @@ -0,0 +1,158 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +/** + * Tests of C's {@code IsMapTab1D}, {@code IsMapTab2D}, {@code AdaptLut} and {@code + * ChangePermSplit} (fitschan.c), as far as this library can run them without FitsTable; the + * expectations are read from C's code. + */ +class FitsMapTabTest { + + private static final double BAD = AstObject.AST__BAD; + + private static Mapping isMapTab1D(Mapping map, double[] dim, int iax) { + return FitsMapTab.isMapTab1D( + map, 1.0, null, new Frame(map.getNout()), dim, iax, iax, new int[1], new int[1], new int[1]); + } + + /** A WinMap's outputs split off its inverse: with the grid dimension known C samples it into a FitsTable. */ + @Test + void aSeparableAxisWithAKnownDimensionNeedsFitsTable() { + WinMap win = new WinMap(new double[] {-1.0, 2.0}, new double[] {0.5, 3.0}); + UnsupportedOperationException e = + assertThrows(UnsupportedOperationException.class, () -> isMapTab1D(win, new double[] {100, 100}, 1)); + assertTrue(e.getMessage().endsWith("needs FitsTable"), e.getMessage()); + assertFalse(win.getInvert()); + } + + /** Without the grid dimension C cannot sample the axis, and returns NULL. */ + @Test + void aSeparableAxisWithAnUnknownDimensionIsNotTabulated() { + WinMap win = new WinMap(new double[] {-1.0, 2.0}, new double[] {0.5, 3.0}); + int[] icolmain = {5}; + int[] icolindex = {5}; + int[] interp = {5}; + assertNull(FitsMapTab.isMapTab1D( + win, 1.0, "deg", new Frame(2), new double[] {BAD, 100}, 0, 0, icolmain, icolindex, interp)); + assertEquals(-1, icolmain[0]); + assertEquals(-1, icolindex[0]); + assertEquals(0, interp[0]); + // Axis 2's dimension is known. + assertThrows(UnsupportedOperationException.class, () -> isMapTab1D(win, new double[] {BAD, 100}, 1)); + assertFalse(win.getInvert()); + } + + /** An output that depends on two grid axes cannot be split off, so is not tabulated. */ + @Test + void aNonSeparableAxisIsNotTabulated() { + MatrixMap rot = new MatrixMap(2, 2, new double[][] {{1.0, 0.5}, {-0.5, 1.0}}); + assertNull(isMapTab1D(rot, new double[] {100, 100}, 0)); + assertNull(isMapTab1D(rot, new double[] {100, 100}, 1)); + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.invert(); + assertNull(isMapTab1D(wm, new double[] {100, 100}, 0)); + } + + /** + * IsMapTab2D needs both outputs separable; with one the columns of the other would be removed + * from a FitsTable, reached only when it was made, which needs FitsTable first. + */ + @Test + void isMapTab2DNeedsBothOutputs() { + MatrixMap rot = new MatrixMap(2, 2, new double[][] {{1.0, 0.5}, {-0.5, 1.0}}); + int[][] outs = new int[8][1]; + assertNull(FitsMapTab.isMapTab2D( + rot, + 1.0, + "deg", + new Frame(2), + new double[] {100, 100}, + 0, + 1, + 0, + 1, + outs[0], + outs[1], + outs[2], + outs[3], + outs[4], + outs[5], + outs[6], + outs[7])); + // A separable Mapping with unknown dimensions: both NULL. + WinMap win = new WinMap(new double[] {-1.0, 2.0}, new double[] {0.5, 3.0}); + assertNull(FitsMapTab.isMapTab2D( + win, + 1.0, + "deg", + new Frame(2), + new double[] {BAD, BAD}, + 0, + 1, + 0, + 1, + outs[0], + outs[1], + outs[2], + outs[3], + outs[4], + outs[5], + outs[6], + outs[7])); + } + + /** + * A linear Mapping is sampled once: the three interior samples and the end, appended after the + * first sample. + */ + @Test + void adaptLutOfALinearMapping() { + ZoomMap zoom = new ZoomMap(1, 2.0); + double[][] work = {{1.0}, {2.0}}; + int[] nsamp = {1}; + FitsMapTab.adaptLut(zoom, 3, 0.25, 1.0, 9.0, 2.0, 18.0, work, nsamp); + assertEquals(5, nsamp[0]); + assertArrayEquals(new double[] {1, 3, 5, 7, 9}, Arrays.copyOf(work[0], 5)); + assertArrayEquals(new double[] {2, 6, 10, 14, 18}, Arrays.copyOf(work[1], 5)); + } + + /** + * A quadratic departs from the chord by more than 0.25 in input, so each interval is + * subdivided until the chords fit; the samples stay in increasing order and end at the end. + */ + @Test + void adaptLutSubdividesACurve() { + PolyMap sq = new PolyMap(1, 1, 1, new double[] {1.0, 1, 2}, 0, new double[0]); + double[] v = sq.tran1(2, new double[] {1.0, 100.0}, true); + double[][] work = {{1.0}, {v[0]}}; + int[] nsamp = {1}; + FitsMapTab.adaptLut(sq, 3, 0.25, 1.0, 100.0, v[0], v[1], work, nsamp); + assertTrue(nsamp[0] > 5, "subdivided: " + nsamp[0]); + assertEquals(100.0, work[0][nsamp[0] - 1]); + for (int i = 1; i < nsamp[0]; i++) { + assertTrue(work[0][i] > work[0][i - 1]); + assertEquals(work[0][i] * work[0][i], work[1][i], 1e-9 * work[1][i]); + } + } + + /** ChangePermSplit sets PermSplit on the PermMaps inside a compound Mapping. */ + @Test + void changePermSplitReachesPermMapsInCmpMaps() { + PermMap pm = new PermMap(2, new int[] {2, 1}, 2, new int[] {2, 1}, null); + CmpMap cmp = new CmpMap(new ZoomMap(2, 2.0), new CmpMap(pm, new UnitMap(2), true), true); + FitsMapTab.changePermSplit(cmp); + assertTrue(pm.getPermSplit()); + PermMap alone = new PermMap(2, new int[] {2, 1}, 2, new int[] {2, 1}, null); + FitsMapTab.changePermSplit(alone); + assertTrue(alone.getPermSplit()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsOrthTest.java b/src/test/java/uk/ac/starlink/ast/FitsOrthTest.java new file mode 100644 index 0000000..d3257db --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsOrthTest.java @@ -0,0 +1,99 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/orth.rs} (C {@code + * OrthVector} and {@code OrthVectorSet}). The expected sets were captured from C by the Rust + * repository's {@code tools/oracle_fixtures/orth_vector_set.c}. + */ +class FitsOrthTest { + + private static void assertSet(double[][] expected, double[][] actual, String label) { + if (expected == null) { + assertNull(actual, label); + return; + } + assertNotNull(actual, label); + assertEquals(expected.length, actual.length, label + ": row count"); + for (int i = 0; i < expected.length; i++) { + assertEquals(expected[i].length, actual[i].length, label + " row " + i); + for (int j = 0; j < expected[i].length; j++) { + assertEquals(expected[i][j], actual[i][j], 1e-12, label + " [" + i + "][" + j + "]"); + } + } + } + + @Test + void twoOfThreeBasisE0E1() { + double[][] r = FitsOrth.orthVectorSet(3, 2, new double[][] {{1, 0, 0}, {0, 1, 0}}); + assertSet(new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, r, "2_of_3_basis"); + } + + @Test + void oneOfTwoBasisE0() { + double[][] r = FitsOrth.orthVectorSet(2, 1, new double[][] {{1, 0}}); + assertSet(new double[][] {{1, 0}, {0, 1}}, r, "1_of_2_basis"); + } + + @Test + void twoOfThreeSkewed() { + double[][] r = FitsOrth.orthVectorSet(3, 2, new double[][] {{1, 1, 0}, {1, -1, 0}}); + assertSet(new double[][] {{1, 1, 0}, {1, -1, 0}, {0, 0, 1}}, r, "2_of_3_skewed"); + } + + @Test + void twoOfThreeParallelReturnsNull() { + double[][] r = FitsOrth.orthVectorSet(3, 2, new double[][] {{1, 2, 3}, {2, 4, 6}}); + assertSet(null, r, "parallel"); + } + + @Test + void oneOfThreeNonUnitPreservesInput() { + double[][] r = FitsOrth.orthVectorSet(3, 1, new double[][] {{3, 0, 4}}); + assertSet(new double[][] {{3, 0, 4}, {0.8, 0, -0.6}, {0, 1, 0}}, r, "nonunit"); + } + + @Test + void threeOfFourBasisCompletesToE3() { + double[][] r = FitsOrth.orthVectorSet(4, 3, new double[][] {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}}); + assertSet(new double[][] {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}, r, "3_of_4_basis"); + } + + /** + * With no vectors supplied, C's {@code OrthVector} solves an empty system ({@code palDmat} with + * no equations is not singular) and sets the component of the largest column to 1; the columns + * all have zero magnitude, so the bubble sort leaves them in order and the set is the unit + * basis. (The Rust test expects no set.) + */ + @Test + void emptyInputGivesTheUnitBasis() { + double[][] r = FitsOrth.orthVectorSet(3, 0, new double[0][]); + assertSet(new double[][] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}, r, "empty"); + } + + @Test + void orthVectorOrthogonalToInputSet() { + double[][] inputs = {{1, 2, 3}}; + double[] v = FitsOrth.orthVector(3, 1, inputs); + assertNotNull(v); + double dot = 0.0; + double len = 0.0; + for (int i = 0; i < 3; i++) { + dot += v[i] * inputs[0][i]; + len += v[i] * v[i]; + } + assertEquals(0.0, dot, 1e-12); + assertEquals(1.0, Math.sqrt(len), 1e-12); + } + + /** C's {@code OrthVector} returns no vector when a supplied vector is missing. */ + @Test + void orthVectorWithAMissingVectorReturnsNull() { + assertNull(FitsOrth.orthVector(3, 2, new double[][] {{1, 0, 0}, null})); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsOtherAxesTest.java b/src/test/java/uk/ac/starlink/ast/FitsOtherAxesTest.java new file mode 100644 index 0000000..f2cf581 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsOtherAxesTest.java @@ -0,0 +1,333 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/other_axes.rs} and {@code + * log_axis.rs} (C {@code OtherAxes}, {@code LogAxis}, {@code AddUnitMaps} and {@code SetAlgCode}, + * fitschan.c) that need no class this library lacks, and tests of the branches that reach one. + * Expectations not from a Rust test are worked from C's code. + * + *

{@code log_axis.rs} {@code detects_log_axis_and_returns_inverse_mapping} builds its + * logarithmic axis with a MathMap; here it is a PolyMap, and where C goes on to build the {@code + * -LOG} Mapping, which holds a MathMap, the translation expects the throw {@code needs MathMap}. Not + * translated: {@code out_of_range_axis_returns_none}, a check C does not make. + */ +class FitsOtherAxesTest { + + private static final double BAD = AstObject.AST__BAD; + + /** A FrameSet from a GRID Frame to {@code current} through {@code map}. */ + private static FrameSet frameSet(Mapping map, Frame current) { + Frame pixel = new Frame(map.getNin()); + pixel.setDomain("GRID"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, map, current); + return fs; + } + + /** Rust's {@code build_2axis_basic_frameset}. */ + private static FrameSet twoAxisFrameSet() { + Frame wcs = new Frame(2); + wcs.setLabel(1, "world x"); + wcs.setLabel(2, "world y"); + wcs.setSymbol(1, "WX"); + wcs.setSymbol(2, "WY"); + wcs.setUnit(1, "m"); + wcs.setUnit(2, "m"); + return frameSet(new UnitMap(2), wcs); + } + + private static Mapping otherAxes( + FitsChan fc, FrameSet fs, double[] dim, FitsStore store, double[] crvals, boolean[] axisDone) { + int nwcs = fs.getNout(); + int[] wperm = new int[nwcs]; + for (int i = 0; i < nwcs; i++) { + wperm[i] = i; + } + return FitsOtherAxes.otherAxes(fc, fs, dim, wperm, ' ', store, crvals, axisDone, "FitsChan", "astWrite"); + } + + @Test + void twoAxesBasicFrameUnitPixelToWcs() { + FitsStore store = new FitsStore(2); + boolean[] axisDone = new boolean[2]; + Mapping map = otherAxes(new FitsChan(), twoAxisFrameSet(), new double[] {100, 200}, store, null, axisDone); + + assertTrue(axisDone[0] && axisDone[1]); + assertEquals("WX", store.ctype[0]); + assertEquals("WY", store.ctype[1]); + assertEquals("m", store.cunit[0]); + assertEquals("m", store.cunit[1]); + assertEquals("world x", store.ctypeCom[0]); + assertEquals("world x", store.cname[0]); + // The centre pixel (floor(50), floor(100)) under the identity. + assertEquals(50.0, store.crval[0]); + assertEquals(100.0, store.crval[1]); + + assertEquals(2, map.getNin()); + assertEquals(2, map.getNout()); + double[] out = map.tranN(1, 2, new double[] {50, 100}, true, 2); + assertArrayEquals(new double[] {0, 0}, out, 1e-12); + } + + @Test + void noUnclaimedAxesReturnsUnitMap() { + FitsStore store = new FitsStore(2); + boolean[] axisDone = {true, true}; + Mapping map = otherAxes(new FitsChan(), twoAxisFrameSet(), new double[] {100, 100}, store, null, axisDone); + assertNull(store.ctype[0]); + assertNull(store.ctype[1]); + assertEquals(2, map.getNin()); + assertEquals(2, map.getNout()); + assertInstanceOf(UnitMap.class, map); + } + + @Test + void overrideCrvalTakesPrecedence() { + FitsStore store = new FitsStore(2); + otherAxes( + new FitsChan(), + twoAxisFrameSet(), + new double[] {100, 100}, + store, + new double[] {7.5, BAD}, + new boolean[2]); + assertEquals(7.5, store.crval[0]); + assertEquals(50.0, store.crval[1]); + } + + @Test + void partialPreClaimedAxesProducesOneAxisMapping() { + FitsStore store = new FitsStore(2); + boolean[] axisDone = {true, false}; + Mapping map = otherAxes(new FitsChan(), twoAxisFrameSet(), new double[] {100, 100}, store, null, axisDone); + assertTrue(axisDone[0] && axisDone[1]); + assertNull(store.ctype[0]); + assertEquals("WY", store.ctype[1]); + assertEquals(50.0, store.crval[1]); + double[] out = map.tranN(1, 2, new double[] {10, 50}, true, 2); + assertArrayEquals(new double[] {10, 0}, out, 1e-12); + } + + @Test + void unknownDimUsesPixelOne() { + FitsStore store = new FitsStore(2); + otherAxes(new FitsChan(), twoAxisFrameSet(), new double[] {BAD, 200}, store, null, new boolean[2]); + assertEquals(1.0, store.crval[0]); + assertEquals(100.0, store.crval[1]); + } + + @Test + void fallbackAxisLabelWhenNoSymbol() { + // A Frame's default Symbol (frame.c GetDefaultSymbol) is "x" and the axis number. + FitsStore store = new FitsStore(1); + otherAxes( + new FitsChan(), frameSet(new UnitMap(1), new Frame(1)), new double[] {50}, store, null, new boolean[1]); + assertEquals("x1", store.ctype[0]); + assertEquals("Type of co-ordinate on axis 1", store.ctypeCom[0]); // codespell:ignore + assertNull(store.cunit[0]); + assertNull(store.cname[0]); + } + + @Test + void blankSymbolGivesAxisN() { + Frame wcs = new Frame(2); + wcs.setSymbol(2, ""); + FitsStore store = new FitsStore(2); + otherAxes(new FitsChan(), frameSet(new UnitMap(2), wcs), new double[] {50, 50}, store, null, new boolean[2]); + assertEquals("x1", store.ctype[0]); + assertEquals("AXIS2", store.ctype[1]); + } + + @Test + void labelEqualToSymbolIsNotACname() { + Frame wcs = new Frame(1); + wcs.setSymbol(1, "WX"); + wcs.setLabel(1, "WX"); + FitsStore store = new FitsStore(1); + otherAxes(new FitsChan(), frameSet(new UnitMap(1), wcs), new double[] {50}, store, null, new boolean[1]); + assertEquals("Type of co-ordinate on axis 1", store.ctypeCom[0]); // codespell:ignore + assertNull(store.cname[0]); + } + + @Test + void badCentreValueStopsTheAxisLoop() { + // C breaks out of its axis loop at an axis with no CRVAL, leaving it and later axes + // undescribed. + PermMap pm = new PermMap(2, new int[] {1, -1}, 2, new int[] {1, -1}, new double[] {BAD}); + Frame wcs = new Frame(2); + FitsStore store = new FitsStore(2); + boolean[] axisDone = new boolean[2]; + otherAxes(new FitsChan(), frameSet(pm, wcs), new double[] {100, 100}, store, null, axisDone); + assertTrue(axisDone[0]); + assertEquals(50.0, store.crval[0]); + assertFalse(axisDone[1]); + assertNull(store.crval[1]); + assertNull(store.ctype[1]); + } + + /** A 1-D FrameSet whose world axis is {@code c0 + c1 p + c2 p^2} of the pixel axis. */ + private static FrameSet quadratic(double c0, double c1, double c2) { + PolyMap pm = new PolyMap(1, 1, 3, new double[] {c0, 1, 0, c1, 1, 1, c2, 1, 2}, 0, new double[0]); + pm.set("IterInverse=1"); + Frame wcs = new Frame(1); + wcs.setDomain("WORLD"); + return frameSet(pm, wcs); + } + + /** + * The PolyMap of the Taylor series to degree 20 of {@code sr exp(slope p)}, which is that + * function to within rounding for {@code slope p} up to 1. + */ + private static PolyMap exponential(double sr, double slope) { + double[] coeffs = new double[21 * 3]; + double term = sr; + for (int k = 0; k <= 20; k++) { + coeffs[3 * k] = term; + coeffs[3 * k + 1] = 1; + coeffs[3 * k + 2] = k; + term = term * slope / (k + 1); + } + PolyMap pm = new PolyMap(1, 1, 21, coeffs, 0, new double[0]); + pm.set("IterInverse=1"); + return pm; + } + + @Test + void slightlyNonLinearAxisIsDescribedAsLinear() { + // C probe loglin.c: the logarithm of 10 + p + 1e-6 p^2 is not linear, so LogAxis returns + // NULL, and OtherAxes describes the axis as linear (C writes it, CRVAL1 = 60.0025). + FitsStore store = new FitsStore(1); + boolean[] axisDone = new boolean[1]; + Mapping map = otherAxes(new FitsChan(), quadratic(10, 1, 1e-6), new double[] {100}, store, null, axisDone); + assertTrue(axisDone[0]); + assertEquals(60.0025, store.crval[0], 1e-12); + assertEquals("WORLD1", store.ctype[0]); + assertArrayEquals(new double[] {-57.0025}, map.tran1(1, new double[] {3}, true), 1e-12); + assertNull(FitsOtherAxes.logAxis( + quadratic(10, 1, 1e-6).getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT), + 0, + 1, + new double[] {1}, + new double[] {100}, + 60.0025)); + } + + @Test + void logarithmicAxisNeedsMathMap() { + // C probe loglin.c: 10 exp(0.01 p) is written as WORL-LOG, whose Mapping holds a MathMap. + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> otherAxes( + new FitsChan(), + frameSet(exponential(10, 0.01), new Frame(1)), + new double[] {100}, + new FitsStore(1), + null, + new boolean[1])); + assertTrue(e.getMessage().endsWith("needs MathMap"), e.getMessage()); + } + + /** Rust {@code log_axis.rs} {@code linear_axis_is_not_log}. */ + @Test + void linearAxisIsNotLog() { + assertNull(FitsOtherAxes.logAxis( + new ShiftMap(new double[] {10, 20}), 0, 2, new double[] {1, 1}, new double[] {100, 100}, 5.0)); + } + + /** + * Rust {@code log_axis.rs} {@code detects_log_axis_and_returns_inverse_mapping}, with axis 1 + * {@code 2 exp(0.1 p)} from a PolyMap: the axis passes C's test, and the Mapping C then + * returns holds a MathMap. + */ + @Test + void detectsLogAxis() { + Mapping map = new CmpMap(new UnitMap(1), exponential(2.0, 0.1), false); + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> FitsOtherAxes.logAxis(map, 1, 2, new double[] {1, 1}, new double[] {10, 10}, 2.0)); + assertTrue(e.getMessage().endsWith("needs MathMap"), e.getMessage()); + } + + @Test + void nonLinearAxisWithZeroCrvalIsDescribedAsLinear() { + // C probe: a quadratic axis that is zero at the centre pixel is written by nothing (the + // write returns 0); OtherAxes gives it the linear description that MakeIntWorld rejects. + FitsStore store = new FitsStore(1); + boolean[] axisDone = new boolean[1]; + Mapping map = otherAxes(new FitsChan(), quadratic(-25, 0, 0.01), new double[] {100}, store, null, axisDone); + assertTrue(axisDone[0]); + assertEquals(0.0, store.crval[0]); + assertEquals("WORLD1", store.ctype[0]); + assertArrayEquals(new double[] {3}, map.tran1(1, new double[] {3}, true), 0); + } + + @Test + void forceTabWithTabOkNeedsFitsTable() { + // C probe: TabOK=1 and ForceTab=1 write a linear axis as WORL-TAB. + FitsChan fc = new FitsChan(); + fc.set("TabOK=1,ForceTab=1"); + FrameSet fs = frameSet(new ShiftMap(new double[] {5}), new Frame(1)); + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> otherAxes(fc, fs, new double[] {100}, new FitsStore(1), null, new boolean[1])); + assertTrue(e.getMessage().endsWith("needs FitsTable"), e.getMessage()); + } + + @Test + void zeroCrvalNonLinearAxisWithTabOkNeedsFitsTable() { + // C probe: with TabOK=1 the quadratic axis that is zero at the centre is written as WORL-TAB. + FitsChan fc = new FitsChan(); + fc.set("TabOK=1"); + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> otherAxes( + fc, quadratic(-25, 0, 0.01), new double[] {100}, new FitsStore(1), null, new boolean[1])); + assertTrue(e.getMessage().endsWith("needs FitsTable"), e.getMessage()); + } + + @Test + void forceTabWithoutTabOkIsDescribedAsLinear() { + FitsChan fc = new FitsChan(); + fc.set("ForceTab=1"); + FitsStore store = new FitsStore(1); + otherAxes( + fc, + frameSet(new ShiftMap(new double[] {5}), new Frame(1)), + new double[] {100}, + store, + null, + new boolean[1]); + assertEquals(55.0, store.crval[0]); + assertEquals("x1", store.ctype[0]); + } + + @Test + void logAxisZeroCrvalReturnsNull() { + assertNull(FitsOtherAxes.logAxis(new UnitMap(1), 0, 1, new double[] {1}, new double[] {100}, 0.0)); + } + + @Test + void addUnitMapsPlacesTheMapping() { + Mapping m = FitsOtherAxes.addUnitMaps(new ShiftMap(new double[] {-5}), 1, 3); + assertEquals(3, m.getNin()); + assertArrayEquals(new double[] {1, 2, 3}, m.tranN(1, 3, new double[] {1, 7, 3}, true, 3), 0); + assertInstanceOf(ShiftMap.class, FitsOtherAxes.addUnitMaps(new ShiftMap(new double[] {-5}), 0, 1)); + } + + @Test + void setAlgCodePadsAndTruncates() { + assertEquals("WORL-LOG", FitsOtherAxes.setAlgCode("WORLD1", "-LOG")); + assertEquals("X----TAB", FitsOtherAxes.setAlgCode("X", "-TAB")); + assertEquals("FREQ-LOG", FitsOtherAxes.setAlgCode("FREQ", "-LOG")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsSipIntWorldTest.java b/src/test/java/uk/ac/starlink/ast/FitsSipIntWorldTest.java new file mode 100644 index 0000000..c185eb4 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsSipIntWorldTest.java @@ -0,0 +1,282 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static uk.ac.starlink.ast.PolyTerms.flat; +import static uk.ac.starlink.ast.PolyTerms.term; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/sip_int_world.rs} (C {@code + * SIPIntWorld}, fitschan.c). The expected values were captured from C by the Rust repository's + * {@code tools/oracle_fixtures/sip_int_world.c} (fixture SIP_2D), which runs C's function on the + * synthetic chain built here with every image dimension unknown. The oracle's copy of C's + * function fits the Mapping after the polynomial over a box current C no longer uses, which + * changes the CD values it gives in the last bits only, so they are compared to a relative 1e-12; + * the other values do not depend on the box and are compared exactly. + */ +class FitsSipIntWorldTest { + + private static final double BAD = AstObject.AST__BAD; + + private static final double TOL = 0.001; + + /** The SIP coefficients of {@code sip.head} with the identity terms, in C's layout. */ + private static final double[] SIP_FWD = flat( + term(1.0, 1, 1, 0), + term(1.0, 2, 0, 1), + term(2.9656e-06, 1, 0, 2), + term(3.7746e-09, 1, 0, 3), + term(2.1886e-05, 1, 1, 1), + term(-1.6847e-07, 1, 1, 2), + term(-2.3863e-05, 1, 2, 0), + term(-8.561e-09, 1, 2, 1), + term(-1.4172e-07, 1, 3, 0), + term(2.31e-05, 2, 0, 2), + term(-1.6168e-07, 2, 0, 3), + term(-2.4386e-05, 2, 1, 1), + term(-5.7813e-09, 2, 1, 2), + term(2.1197e-06, 2, 2, 0), + term(-1.6583e-07, 2, 2, 1), + term(-2.0249e-08, 2, 3, 0)); + + /** The inverse SIP coefficients of {@code sip.head} with the identity terms. */ + private static final double[] SIP_INV = flat( + term(1.0, 1, 1, 0), + term(1.0, 2, 0, 1), + term(-6.4275e-07, 1, 0, 1), + term(-2.9425e-06, 1, 0, 2), + term(-3.582e-09, 1, 0, 3), + term(-1.4897e-05, 1, 1, 0), + term(-2.225e-05, 1, 1, 1), + term(1.7195e-07, 1, 1, 2), + term(2.4146e-05, 1, 2, 0), + term(6.709e-09, 1, 2, 1), + term(1.4492e-07, 1, 3, 0), + term(-1.6588e-05, 2, 0, 1), + term(-2.3424e-05, 2, 0, 2), + term(1.651e-07, 2, 0, 3), + term(-2.6783e-06, 2, 1, 0), + term(2.4753e-05, 2, 1, 1), + term(3.8917e-09, 2, 1, 2), + term(-2.151e-06, 2, 2, 0), + term(1.7e-07, 2, 2, 1), + term(2.0482e-08, 2, 3, 0)); + + private static final double[] CD = { + 0.000249756880272355, 0.000230177809743655, 0.000230428519265417, -0.000249965770576587 + }; + + /** C's SIP_A: every coefficient C stores that is not bad, as (i, j, value). */ + private static final double[][] SIP_A = { + {0, 2, 2.9656e-06}, + {0, 3, 3.7746e-09}, + {1, 1, 2.1886e-05}, + {1, 2, -1.6847e-07}, + {2, 0, -2.3863e-05}, + {2, 1, -8.561e-09}, + {3, 0, -1.4172e-07} + }; + + private static final double[][] SIP_B = { + {0, 2, 2.31e-05}, + {0, 3, -1.6168e-07}, + {1, 1, -2.4386e-05}, + {1, 2, -5.7813e-09}, + {2, 0, 2.1197e-06}, + {2, 1, -1.6583e-07}, + {3, 0, -2.0249e-08} + }; + + private static final double[][] SIP_AP = { + {0, 1, -6.4275e-07}, + {0, 2, -2.9425e-06}, + {0, 3, -3.582e-09}, + {1, 0, -1.4897000000013705e-05}, + {1, 1, -2.225e-05}, + {1, 2, 1.7195e-07}, + {2, 0, 2.4146e-05}, + {2, 1, 6.709e-09}, + {3, 0, 1.4492e-07} + }; + + private static final double[][] SIP_BP = { + {0, 1, -1.658800000003957e-05}, + {0, 2, -2.3424e-05}, + {0, 3, 1.651e-07}, + {1, 0, -2.6783e-06}, + {1, 1, 2.4753e-05}, + {1, 2, 3.8917e-09}, + {2, 0, -2.151e-06}, + {2, 1, 1.7e-07}, + {3, 0, 2.0482e-08} + }; + + /** C's SAMPLE_FORWARD: grid positions and the IWC the returned Mapping gives for them. */ + private static final double[][][] SAMPLE_FORWARD = { + {{1.0, 1.0}, {-0.060951705632033275, 0.002481230916518591}}, + {{64.0, 64.0}, {-0.030715820161024643, 0.0012503840839148805}}, + {{128.0, 128.0}, {0.0, 0.0}}, + {{200.0, 200.0}, {0.034555297681152716, -0.0014066820944042407}}, + {{256.0, 256.0}, {0.061431640322049286, -0.002500768167829761}} + }; + + /** The synthetic pixel to IWC chain: ShiftMap(-128, -128), the SIP PolyMap, the CD matrix. */ + private static Mapping sip2dChain() { + ShiftMap sm = new ShiftMap(new double[] {-128.0, -128.0}); + PolyMap pm = new PolyMap(2, 2, SIP_FWD.length / 4, SIP_FWD, SIP_INV.length / 4, SIP_INV); + MatrixMap mm = new MatrixMap(2, 2, MatrixMap.FULL, CD); + return new CmpMap(new CmpMap(sm, pm, true), mm, true); + } + + private static FitsStore storeWithCtypes(int naxis) { + FitsStore store = new FitsStore(naxis); + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + return store; + } + + /** Asserts that a store table holds C's values at the listed elements and is bad elsewhere. */ + private static void assertTable(double[][] want, double[][] table, String label) { + int n = 0; + for (double[] row : table) { + for (double v : row) { + if (v != BAD) { + n++; + } + } + } + assertEquals(want.length, n, label + ": number of good coefficients"); + for (double[] w : want) { + int i = (int) w[0]; + int j = (int) w[1]; + assertEquals(w[2], table[i][j], label + "[" + i + "][" + j + "]"); + } + } + + private static void assertSip2dTables(FitsStore store) { + assertTable(SIP_A, store.sipA, "SIP_A"); + assertTable(SIP_B, store.sipB, "SIP_B"); + assertTable(SIP_AP, store.sipAp, "SIP_AP"); + assertTable(SIP_BP, store.sipBp, "SIP_BP"); + } + + /** C's SIP_2D fixture. */ + @Test + void sip2dExtractsOracleValues() { + FitsStore store = storeWithCtypes(2); + int[] inaxes = new int[2]; + double[] crpix = new double[2]; + double[] cd = new double[4]; + Mapping result = FitsSipIntWorld.sipIntWorld( + sip2dChain(), + TOL, + 0, + 1, + ' ', + store, + new double[] {BAD, BAD}, + inaxes, + crpix, + cd, + "astWrite", + "FitsChan"); + assertNotNull(result); + assertArrayEquals(new int[] {0, 1}, inaxes); + assertArrayEquals(new double[] {128.0, 128.0}, crpix); + for (int k = 0; k < 4; k++) { + assertEquals(CD[k], cd[k], 1e-12 * Math.abs(CD[k]), "cd[" + k + "]"); + } + assertSip2dTables(store); + assertEquals("RA---TAN-SIP", store.ctype[0]); + assertEquals("DEC--TAN-SIP", store.ctype[1]); + + for (double[][] sample : SAMPLE_FORWARD) { + double[][] out = result.tran2(1, new double[] {sample[0][0]}, new double[] {sample[0][1]}, true); + assertEquals(sample[1][0], out[0][0], "x at " + sample[0][0]); + assertEquals(sample[1][1], out[1][0], "y at " + sample[0][1]); + } + } + + /** The same chain without its PolyMap: there is no SIP distortion, and the store is untouched. */ + @Test + void nonSipReturnsNull() { + ShiftMap sm = new ShiftMap(new double[] {-128.0, -128.0}); + MatrixMap mm = new MatrixMap(2, 2, MatrixMap.FULL, CD); + FitsStore store = storeWithCtypes(2); + Mapping result = FitsSipIntWorld.sipIntWorld( + new CmpMap(sm, mm, true), + TOL, + 0, + 1, + ' ', + store, + new double[] {256, 256}, + new int[2], + new double[2], + new double[4], + "astWrite", + "FitsChan"); + assertNull(result); + assertEquals(0, store.sipA.length); + assertEquals("RA---TAN", store.ctype[0]); + } + + /** + * The SIP_2D chain in parallel with a one-axis UnitMap, which takes C's branch for Mappings with + * more than two outputs. C's code gives the celestial values of SIP_2D, and a returned Mapping + * that passes the third axis through. + */ + @Test + void sip3dKeepsTheOtherAxis() { + Mapping chain = new CmpMap(sip2dChain(), new UnitMap(1), false); + FitsStore store = storeWithCtypes(3); + int[] inaxes = new int[2]; + double[] crpix = new double[2]; + double[] cd = new double[4]; + Mapping result = FitsSipIntWorld.sipIntWorld( + chain, TOL, 0, 1, ' ', store, new double[] {BAD, BAD, BAD}, inaxes, crpix, cd, "astWrite", "FitsChan"); + assertNotNull(result); + assertEquals(3, result.getNin()); + assertEquals(3, result.getNout()); + assertArrayEquals(new int[] {0, 1}, inaxes); + assertArrayEquals(new double[] {128.0, 128.0}, crpix); + assertSip2dTables(store); + for (double[][] sample : SAMPLE_FORWARD) { + double[][] out = result.transform(new double[][] {{sample[0][0]}, {sample[0][1]}, {1.0}}, 1, true); + assertEquals(sample[1][0], out[0][0]); + assertEquals(sample[1][1], out[1][0]); + assertEquals(1.0, out[2][0]); + } + } + + /** + * C copies a CTYPE into a buffer and writes {@code -SIP} at its ninth character, so a value of + * fewer than eight characters keeps its terminating null and is stored unchanged, and a longer + * one is cut to eight characters. + */ + @Test + void sipSuffixFollowsCsBuffer() { + FitsStore store = new FitsStore(2); + store.ctype[0] = "RA"; + store.ctype[1] = "DEC--TAN-XYZ"; + assertNotNull(FitsSipIntWorld.sipIntWorld( + sip2dChain(), + TOL, + 0, + 1, + ' ', + store, + new double[] {BAD, BAD}, + new int[2], + new double[2], + new double[4], + "astWrite", + "FitsChan")); + assertEquals("RA", store.ctype[0]); + assertEquals("DEC--TAN-SIP", store.ctype[1]); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsSkyPoleTest.java b/src/test/java/uk/ac/starlink/ast/FitsSkyPoleTest.java new file mode 100644 index 0000000..2ba4ba4 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsSkyPoleTest.java @@ -0,0 +1,178 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/sky_pole.rs} that test + * {@code sky_pole} (C {@code SkyPole}, fitschan.c), and the LONPOLE and LATPOLE C writes for the + * headers of {@code oracle/sky_pole.json} (made by {@code tools/oracle_fixtures/sky_pole_probe.c}), + * compared with what {@link FitsCelestialAxes#celestialAxes} stores. The {@code wcs_nat_pole} test + * is translated in {@link FitsNativePoleTest}. + */ +class FitsSkyPoleTest { + + private static final int[] WPERM = {0, 1}; + + private static void skyPole(WcsMap wm, Mapping map3, FitsStore store) { + FitsSkyPole.skyPole(wm, map3, 0, 1, WPERM, ' ', store, "astWrite", "FitsChan"); + } + + @Test + void tanWithNoPvOverridesEmitsNothing() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + FitsStore store = new FitsStore(2); + skyPole(wm, new UnitMap(2), store); + assertNull(store.lonpole); + assertNull(store.latpole); + assertNull(store.pv[0][3]); + assertNull(store.pv[0][4]); + } + + @Test + void tanWithPvOverridesEmitsLonpoleLatpole() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + wm.setPV(0, 3, 90.0); + wm.setPV(0, 4, 45.0); + FitsStore store = new FitsStore(2); + skyPole(wm, new UnitMap(2), store); + assertEquals(90.0, store.lonpole); + assertEquals(45.0, store.latpole); + assertEquals(90.0, store.pv[0][3]); + assertEquals(45.0, store.pv[0][4]); + } + + @Test + void tpnSkipsPvCopy() { + WcsMap wm = new WcsMap(2, WcsMap.AST__TPN, 1, 2); + wm.setPV(0, 3, Math.toRadians(99.0)); + wm.setPV(0, 4, Math.toRadians(99.0)); + FitsStore store = new FitsStore(2); + skyPole(wm, new UnitMap(2), store); + assertNull(store.lonpole); + assertNull(store.latpole); + assertNull(store.pv[0][3]); + } + + /** + * CAR with map3 a UnitMap and no CRVAL: the celestial pole is at native (0, pi/2); WcsNatPole, + * with LATPOLE 999, gives the solution pi/2 nearer to it, so LATPOLE takes its default, as does + * LONPOLE (0, the celestial latitude of the fiducial point, 0, being at least its native + * latitude, 0). The Rust test asserts nothing; these values are worked through C's code. + */ + @Test + void nonZenithalWithUnitMap3EmitsNoExplicitKeywords() { + WcsMap wm = new WcsMap(2, WcsMap.AST__CAR, 1, 2); + FitsStore store = new FitsStore(2); + skyPole(wm, new UnitMap(2), store); + assertNull(store.lonpole); + assertNull(store.latpole); + assertNull(store.pv[0][3]); + assertNull(store.pv[0][4]); + } + + /** C's {@code IsZenithal}, including its reading of SZP parameter 2 (a C quirk). */ + @Test + void isZenithalFollowsC() { + assertTrue(new WcsMap(2, WcsMap.AST__TAN, 1, 2).isZenithal()); + assertTrue(new WcsMap(2, WcsMap.AST__TPN, 1, 2).isZenithal()); + assertFalse(new WcsMap(2, WcsMap.AST__CAR, 1, 2).isZenithal()); + assertTrue(new WcsMap(2, WcsMap.AST__SIN, 1, 2).isZenithal()); + WcsMap slant = new WcsMap(2, WcsMap.AST__SIN, 1, 2); + slant.setPV(1, 1, 0.1); + assertFalse(slant.isZenithal()); + WcsMap azp = new WcsMap(2, WcsMap.AST__AZP, 1, 2); + azp.setPV(1, 1, 2.0); + assertTrue(azp.isZenithal()); + azp.setPV(1, 2, 10.0); + assertFalse(azp.isZenithal()); + // SZP parameter 2 defaults to 0, so a default SZP projection is not zenithal. + assertFalse(new WcsMap(2, WcsMap.AST__SZP, 1, 2).isZenithal()); + WcsMap szp = new WcsMap(2, WcsMap.AST__SZP, 1, 2); + szp.setPV(1, 2, 90.0); + assertTrue(szp.isZenithal()); + } + + /** The header of an oracle case, as the probe builds it. */ + private static List header(String proj, String extra) { + List cards = new ArrayList<>(); + cards.add("NAXIS = 2"); + cards.add("NAXIS1 = 100"); + cards.add("NAXIS2 = 100"); + cards.add("CRPIX1 = 50.0"); + cards.add("CRPIX2 = 50.0"); + cards.add("CRVAL1 = 30.0"); + cards.add("CRVAL2 = 40.0"); + cards.add("CDELT1 = -0.01"); + cards.add("CDELT2 = 0.01"); + cards.add("CTYPE1 = 'RA---" + proj + "'"); + cards.add("CTYPE2 = 'DEC--" + proj + "'"); + cards.add("RADESYS = 'ICRS'"); + for (String line : CValues.lines(extra)) { + if (!line.isEmpty()) { + cards.add(line); + } + } + return cards; + } + + private static void assertPole(String name, JsonNode want, Double got) { + if (want.isNull()) { + assertNull(got, name); + } else { + // C writes the value to 15 significant digits, and a pole angle is at most 180. + assertEquals(want.asDouble(), got, 1e-12, name); + } + } + + /** + * Each header C reads and writes, read here and its FrameSet's celestial axes described: the + * LONPOLE and LATPOLE stored are those C writes. A zenithal projection gives only the pole set + * in its WcsMap; any other has the pole worked out from its Mappings. + */ + @Test + void skyPoleMatchesTheCLibrary() { + int checked = 0; + for (JsonNode c : ProbeData.load("sky_pole").get("CASES")) { + if (!c.get(5).asBoolean()) { + continue; + } + String name = c.get(0).asText(); + FitsChan in = new FitsChan(); + in.setEncoding("FITS-WCS"); + for (String card : header(c.get(1).asText(), c.get(2).asText())) { + in.putFits(card, false); + } + in.clear("Card"); + FrameSet fs = (FrameSet) in.read(); + FitsStore store = new FitsStore(2); + FitsChan out = new FitsChan(); + out.setEncoding("FITS-WCS"); + FitsCelestialAxes.celestialAxes( + out, + fs, + new double[] {100, 100}, + new int[] {0, 1}, + ' ', + store, + new boolean[2], + 0, + "astWrite", + "FitsChan"); + assertPole(name + " LONPOLE", c.get(3), store.lonpole); + assertPole(name + " LATPOLE", c.get(4), store.latpole); + checked++; + } + assertNotEquals(0, checked); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsSkySysTest.java b/src/test/java/uk/ac/starlink/ast/FitsSkySysTest.java new file mode 100644 index 0000000..ac0c56b --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsSkySysTest.java @@ -0,0 +1,475 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/sky_sys.rs} (C {@code + * SkySys} and {@code IsSkyOff}, fitschan.c), with the values C's code gives where they differ from + * Rust's, and tests of branches the Rust tests do not reach, their expectations read from C's + * code. + */ +class FitsSkySysTest { + + private static SkyFrame sky(String system) { + SkyFrame sky = new SkyFrame(); + sky.setSystem(system); + return sky; + } + + /** C's {@code SkySys} for axes 0 and 1 of a two-axis store, with an empty FitsChan. */ + private static boolean skySys(SkyFrame sky, int wcstype, int proj, FitsStore store, char s, int isoff) { + return skySys(new FitsChan(), sky, wcstype, proj, store, s, isoff); + } + + private static boolean skySys( + FitsChan fc, SkyFrame sky, int wcstype, int proj, FitsStore store, char s, int isoff) { + return FitsSkySys.skySys(fc, sky, wcstype, proj, store, 0, 1, s, isoff, "astWrite", "FitsChan"); + } + + @Test + void fk5SkySysWritesCtypeRadesysEquinox() { + FitsStore s = new FitsStore(2); + s.cunit[0] = "deg"; + s.cunit[1] = "deg"; + assertTrue(skySys(sky("FK5"), 1, WcsMap.AST__TAN, s, ' ', 0)); + assertEquals("RA---TAN", s.ctype[0]); + assertEquals("DEC--TAN", s.ctype[1]); + assertEquals("FK5", s.radesys); + // The default equinox, J2000.0, as palEpj gives it. + assertEquals(Pal.epj(51544.5), s.equinox); + assertEquals(2000.0, s.equinox, 1e-12); + assertNull(s.cunit[0]); + assertNull(s.cunit[1]); + } + + @Test + void fk4SkySysUsesBesselianEquinox() { + FitsStore s = new FitsStore(2); + skySys(sky("FK4"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals(1950.0, s.equinox, 1e-9); + assertEquals("FK4", s.radesys); + } + + @Test + void icrsNoEquinox() { + FitsStore s = new FitsStore(2); + skySys(sky("ICRS"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertNull(s.equinox); + assertEquals("ICRS", s.radesys); + assertEquals("RA---TAN", s.ctype[0]); + assertEquals("DEC--TAN", s.ctype[1]); + } + + @Test + void galacticUsesGlonGlatNoEquinoxNoRadesys() { + FitsStore s = new FitsStore(2); + skySys(sky("GALACTIC"), 1, WcsMap.AST__SIN, s, ' ', 0); + assertEquals("GLON-SIN", s.ctype[0]); + assertEquals("GLAT-SIN", s.ctype[1]); + assertNull(s.radesys); + assertNull(s.equinox); + } + + @Test + void eclipticUsesElonElatJulianEquinox() { + FitsStore s = new FitsStore(2); + skySys(sky("ECLIPTIC"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("ELON-TAN", s.ctype[0]); + assertEquals("ELAT-TAN", s.ctype[1]); + assertEquals(2000.0, s.equinox); + } + + @Test + void supergalacticSlatSlon() { + FitsStore s = new FitsStore(2); + skySys(sky("SUPERGALACTIC"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("SLON-TAN", s.ctype[0]); + assertEquals("SLAT-TAN", s.ctype[1]); + } + + @Test + void azelWritesAzElPrefixes() { + FitsStore s = new FitsStore(2); + skySys(sky("AZEL"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("AZ---TAN", s.ctype[0]); + assertEquals("EL---TAN", s.ctype[1]); + } + + @Test + void isoffPositiveWritesOflnOflt() { + SkyFrame sky = sky("FK5"); + sky.setSkyRefIs("Origin"); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 1); + assertEquals("OFLN-TAN", s.ctype[0]); + assertEquals("OFLT-TAN", s.ctype[1]); + } + + /** + * The CTYPE comments of offset coordinates: each axis Symbol without its first character + * (the "D" of an offset Symbol) and the formatted SkyRef. + */ + @Test + void isoffPositiveWritesCtypeCommentOffsetFrom() { + SkyFrame sky = sky("FK5"); + sky.setSkyRefIs("Origin"); + sky.setSkyRef(1, 0.5); + sky.setSkyRef(2, -0.25); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 1); + assertTrue(s.ctypeCom[0].startsWith("RA offset from "), s.ctypeCom[0]); + assertTrue(s.ctypeCom[1].startsWith("Dec offset from "), s.ctypeCom[1]); + assertEquals("RA offset from " + sky.getC("SkyRef"), s.ctypeCom[0]); + } + + @Test + void isoffNegativeWritesSkyrefisSkyrefSkyrefp() { + SkyFrame sky = sky("FK5"); + sky.setSkyRefIs("Pole"); + sky.setSkyRef(1, 0.5); + sky.setSkyRef(2, -0.25); + sky.setSkyRefP(1, 1.0); + sky.setSkyRefP(2, 0.5); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', -1); + assertEquals("POLE", s.skyrefis); + assertEquals(0.5, s.skyref[0]); + assertEquals(-0.25, s.skyref[1]); + assertEquals(1.0, s.skyrefp[0]); + assertEquals(0.5, s.skyrefp[1]); + // Only a positive isoff gives the offset CTYPE. + assertEquals("RA---TAN", s.ctype[0]); + } + + @Test + void isoffNegative2WritesOrigin() { + SkyFrame sky = sky("FK5"); + sky.setSkyRefIs("Origin"); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', -2); + assertEquals("ORIGIN", s.skyrefis); + assertNull(s.skyref[0]); + assertNull(s.skyrefp[0]); + } + + @Test + void isoffNegative3WritesIgnored() { + FitsStore s = new FitsStore(2); + skySys(sky("FK5"), 1, WcsMap.AST__TAN, s, ' ', -3); + assertEquals("IGNORED", s.skyrefis); + } + + @Test + void isoffZeroDoesNotEmitSkyrefMetadata() { + SkyFrame sky = sky("FK5"); + sky.setSkyRef(1, 1.0); + sky.setSkyRef(2, 1.0); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertNull(s.skyrefis); + assertNull(s.skyref[0]); + assertNull(s.skyref[1]); + } + + /** The observer's geocentric position, by eraGd2gc on the WGS84 ellipsoid. */ + @Test + void obsgeoEmittedWhenObserverPositionSet() { + SkyFrame sky = sky("FK5"); + double lat = Math.toRadians(51.4778); + sky.setObsLonValue(0.0); + sky.setObsLatValue(lat); + sky.setObsAlt(0.0); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + double[] xyz = Pal.gd2gc(0.0, lat, 0.0); + assertEquals(xyz[0], s.obsgeox); + assertEquals(xyz[1], s.obsgeoy); + assertEquals(xyz[2], s.obsgeoz); + double r = Math.sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1] + xyz[2] * xyz[2]); + assertEquals(6_371_000.0, r, 50_000.0); + assertEquals(0.0, s.obsgeoy, 1e-3); + } + + @Test + void obsgeoSkippedForNonPrimaryVersion() { + SkyFrame sky = sky("FK5"); + sky.setObsLonValue(0.0); + sky.setObsLatValue(0.0); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, 'A', 0); + assertNull(s.obsgeox); + } + + @Test + void obsgeoSkippedWhenObserverUnset() { + FitsStore s = new FitsStore(2); + skySys(sky("FK5"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertNull(s.obsgeox); + } + + /** + * Rust stores a Domain other than SKY as WCSNAME; C's {@code SkySys} begins with the {@code + * IsASkyFrame} test, which needs the Domain SKY, so it stores nothing and returns 0. + */ + @Test + void nonSkyDomainIsNotDescribed() { + SkyFrame sky = sky("FK5"); + sky.setDomain("MY-DOMAIN"); + FitsStore s = new FitsStore(2); + assertFalse(skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0)); + assertNull(s.wcsname); + assertNull(s.ctype[0]); + assertNull(s.radesys); + } + + /** A Domain set, which can only be SKY, is stored as WCSNAME (C's {@code astTestDomain}). */ + @Test + void wcsnameEmittedWhenDomainSet() { + SkyFrame sky = sky("FK5"); + sky.setDomain("SKY"); + FitsStore s = new FitsStore(2); + assertTrue(skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0)); + assertEquals("SKY", s.wcsname); + } + + @Test + void wcsnameSkippedForDefaultDomain() { + FitsStore s = new FitsStore(2); + skySys(sky("FK5"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertNull(s.wcsname); + } + + @Test + void axisLabelEmitsCtypeCommentAndCname() { + SkyFrame sky = sky("FK5"); + sky.setLabel(1, "MyRA"); + sky.setLabel(2, "MyDec"); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("MyRA", s.ctypeCom[0]); + assertEquals("MyRA", s.cname[0]); + assertEquals("MyDec", s.ctypeCom[1]); + assertEquals("MyDec", s.cname[1]); + } + + @Test + void axisLabelUnsetLeavesCtypeComDefault() { + FitsStore s = new FitsStore(2); + skySys(sky("FK5"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertNull(s.ctypeCom[0]); + assertNull(s.ctypeCom[1]); + assertNull(s.cname[0]); + } + + @Test + void unknownSystemSymbolXxlnXxltPassesThrough() { + SkyFrame sky = sky("UNKNOWN"); + sky.setSymbol(1, "QQLN"); + sky.setSymbol(2, "QQLT"); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("QQLN-TAN", s.ctype[0]); + assertEquals("QQLT-TAN", s.ctype[1]); + } + + @Test + void unknownSystemSymbolXlonXlatPassesThrough() { + SkyFrame sky = sky("UNKNOWN"); + sky.setSymbol(1, "ZLON"); + sky.setSymbol(2, "ZLAT"); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("ZLON-TAN", s.ctype[0]); + assertEquals("ZLAT-TAN", s.ctype[1]); + } + + /** MJD-OBS is the Epoch converted from TDB to UTC, as C's {@code TDBConv} gives it. */ + @Test + void epochConvertsTdbToUtcForMjdobs() { + SkyFrame sky = sky("FK5"); + double tdb = 60000.0; + sky.setEpochMjd(tdb); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertNotNull(s.mjdobs); + assertEquals(FitsEpoch.tdbConv(tdb, TimeFrame.AST__UTC, true), s.mjdobs); + double deltaS = (tdb - s.mjdobs) * 86_400.0; + assertTrue(deltaS > 60.0 && deltaS < 80.0, "TDB-UTC " + deltaS); + assertNull(s.timesys); + } + + @Test + void unknownSystemNonConformingFallsBackToUnlnUnlt() { + SkyFrame sky = sky("UNKNOWN"); + sky.setSymbol(1, "WEIRD"); + sky.setSymbol(2, "ALSOWEIRD"); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("UNLN-TAN", s.ctype[0]); + assertEquals("UNLT-TAN", s.ctype[1]); + } + + @Test + void wcstypeZeroUsesTabSuffix() { + FitsStore s = new FitsStore(2); + skySys(sky("FK5"), 0, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("RA---TAB", s.ctype[0]); + assertEquals("DEC--TAB", s.ctype[1]); + } + + /** A two-Frame FrameSet: a base Frame and a SkyFrame with SkyRefIs {@code skyRefIs}. */ + private static FrameSet skyOnlyFrameSet(String skyRefIs) { + SkyFrame sky = sky("FK5"); + sky.setSkyRefIs(skyRefIs); + FrameSet fs = new FrameSet(new Frame(2)); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(2), sky); + return fs; + } + + @Test + void isSkyOffOriginReturnsOne() { + assertEquals(1, FitsSkySys.isSkyOff(skyOnlyFrameSet("Origin"), 2)); + } + + @Test + void isSkyOffPoleReturnsOne() { + assertEquals(1, FitsSkySys.isSkyOff(skyOnlyFrameSet("Pole"), 2)); + } + + @Test + void isSkyOffIgnoredReturnsZero() { + assertEquals(0, FitsSkySys.isSkyOff(skyOnlyFrameSet("Ignored"), 2)); + } + + @Test + void isSkyOffBasicFrameReturnsZero() { + assertEquals(0, FitsSkySys.isSkyOff(skyOnlyFrameSet("Origin"), 1)); + } + + // ------------------------------------------------------------------ + // Branches read from C's code + // ------------------------------------------------------------------ + + /** A CmpFrame holding an offset SkyFrame is offset: its SkyRefIs is read from the SkyFrame. */ + @Test + void isSkyOffSeesASkyFrameInACmpFrame() { + SkyFrame sky = sky("FK5"); + sky.setSkyRefIs("Pole"); + FrameSet fs = new FrameSet(new Frame(3)); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(3), new CmpFrame(new Frame(1), sky)); + assertEquals(1, FitsSkySys.isSkyOff(fs, FrameSet.AST__CURRENT)); + } + + /** J2000 is none of the systems C names, so it is described as an unknown system. */ + @Test + void j2000IsAnUnknownSystem() { + FitsStore s = new FitsStore(2); + skySys(sky("J2000"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("UNLN-TAN", s.ctype[0]); + assertEquals("UNLT-TAN", s.ctype[1]); + assertNull(s.radesys); + assertNull(s.equinox); + } + + @Test + void fk4NoEAndGapptAndHelioecliptic() { + FitsStore s = new FitsStore(2); + skySys(sky("FK4-NO-E"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("FK4-NO-E", s.radesys); + assertEquals(1950.0, s.equinox, 1e-9); + + s = new FitsStore(2); + skySys(sky("GAPPT"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("GAPPT", s.radesys); + assertEquals("RA---TAN", s.ctype[0]); + assertNull(s.equinox); + + s = new FitsStore(2); + skySys(sky("HELIOECLIPTIC"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("HLON-TAN", s.ctype[0]); + assertEquals("HLAT-TAN", s.ctype[1]); + assertNull(s.equinox); + } + + /** An equinox that is not stored overwrites one already in the store, as C's SetItem of AST__BAD. */ + @Test + void anUnstoredEquinoxClearsTheStore() { + FitsStore s = new FitsStore(2); + s.equinox = 1950.0; + skySys(sky("ICRS"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertNull(s.equinox); + } + + /** FITS has one MJD-OBS, which an alternate description does not store. */ + @Test + void mjdobsOnlyForThePrimaryDescription() { + SkyFrame sky = sky("FK5"); + sky.setEpochMjd(60000.0); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, 'A', 0); + assertNull(s.mjdobs); + } + + /** + * The longitude and latitude axes are those of the SkyFrame, whatever its axis order: with + * latitude first, the latitude axis's Label is still stored for the latitude FITS axis. + */ + @Test + void permutedSkyFrameAxes() { + SkyFrame sky = sky("FK5"); + sky.permAxes(new int[] {2, 1}); + sky.setLabel(1, "First"); + FitsStore s = new FitsStore(2); + skySys(sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("First", s.cname[1]); + assertNull(s.cname[0]); + } + + /** + * Under a TIMESYS card naming another time scale, MJD-OBS is in that scale and TIMESYS is + * stored, its padding removed; the card is found even when a read has used it. + */ + @Test + void timesysCardGivesTheTimeScale() { + SkyFrame sky = sky("FK5"); + double tdb = 60000.0; + sky.setEpochMjd(tdb); + FitsChan fc = new FitsChan(); + fc.putFits("TIMESYS = 'TAI '", false); + fc.cards().cards().get(0).flags.consumption = FitsCard.Consumption.USED; + FitsStore s = new FitsStore(2); + skySys(fc, sky, 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("TAI", s.timesys); + assertEquals(FitsEpoch.tdbConv(tdb, TimeFrame.AST__TAI, true), s.mjdobs); + } + + /** A TIMESYS of UTC is the default, and is not stored. */ + @Test + void utcTimesysIsNotStored() { + FitsChan fc = new FitsChan(); + fc.putFits("TIMESYS = 'UTC'", false); + FitsStore s = new FitsStore(2); + skySys(fc, sky("FK5"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertNull(s.timesys); + } + + /** An unsupported TIMESYS raises C's {@code badval} warning, as an ASTWARN card. */ + @Test + void unsupportedTimesysWarns() { + FitsChan fc = new FitsChan(); + fc.setWarnings("BadVal"); + fc.putFits("TIMESYS = 'XYZ'", false); + FitsStore s = new FitsStore(2); + skySys(fc, sky("FK5"), 1, WcsMap.AST__TAN, s, ' ', 0); + assertEquals("XYZ", s.timesys); + fc.clear("Card"); + assertNotNull(fc.findFits("ASTWARN", false)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java b/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java index 67490bd..3f85dfe 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java @@ -19,11 +19,13 @@ * non-standard FITS-WCS keywords (fitschan.c {@code SpecTrans}). * *

Many Rust tests run under FITS-PC although the translation they test is not gated on the - * encoding; those run here under FITS-WCS, which C translates the same way. The tests of the - * translations only FITS-PC, FITS-IRAF and FITS-CLASS make are deferred, since those encodings are - * not read. C marks the cards a translation reads as used rather than deleting them, so where Rust - * asserts a card has gone, these tests assert it was consumed. The tests after the translated ones - * check behaviour of C that the Rust port does not share, each citing the C it follows. + * encoding; those run here under FITS-WCS, which C translates the same way, and those of the + * translations only FITS-PC and FITS-IRAF make run under that encoding. The test of C's {@code + * ClassTrans} is deferred, since FITS-CLASS is not read. C marks the cards a translation reads as + * used rather than deleting them, so where Rust asserts a card has gone, these tests assert it was + * consumed. Rust's {@code rename_keyword} tests run as the RADECSYS and LONGPOLE translations C + * makes in its place. The tests after the translated ones check behaviour of C that the Rust port + * does not share, each citing the C it follows. */ class FitsSpecTransTest { @@ -37,6 +39,22 @@ private static FitsCardList wcs(String header) { return run(header, new FitsSpecTrans.TransAttrs(), new FitsSpecTrans.TransWarnings()); } + /** The cards of {@code header} translated under {@code encoding}. */ + private static FitsCardList under(FitsChan.Encoding encoding, String header) { + FitsCardList cards = FitsCardList.fromHeader(header); + FitsSpecTrans.specTransInplace( + cards, encoding, new FitsSpecTrans.TransAttrs(), new FitsSpecTrans.TransWarnings()); + return cards; + } + + private static FitsCardList pc(String header) { + return under(FitsChan.Encoding.FITS_PC, header); + } + + private static FitsCardList iraf(String header) { + return under(FitsChan.Encoding.FITS_IRAF, header); + } + private static boolean consumed(FitsCardList cards, String keyword) { return cards.takeConsumedNames().contains(keyword); } @@ -54,7 +72,7 @@ void specTransIsANoOpWhenAllKeywordsAreAlreadyStandard() { FitsSpecTrans.specTransInplace( cards, FitsChan.Encoding.FITS_WCS, new FitsSpecTrans.TransAttrs(), new FitsSpecTrans.TransWarnings()); assertEquals(before, cards.len()); - assertEquals("FK5 ", cards.getString("RADESYS")); + assertEquals("FK5 ", cards.getStoredString("RADESYS", 10)); } @Test @@ -68,16 +86,16 @@ void zeroCdeltIsReplacedWithOne() { + "END"); // A zero CDELT becomes 1.0, since 1.0E-6 times the zero CDELT is still zero // (fitschan.c:31700-31706). - assertEquals(1.0e-10, cards.getFloat("CDELT1")); - assertEquals(1.0, cards.getFloat("CDELT2")); - assertEquals(1.0, cards.getFloat("CDELT3")); + assertEquals(1.0e-10, cards.getStoredFloat("CDELT1")); + assertEquals(1.0, cards.getStoredFloat("CDELT2")); + assertEquals(1.0, cards.getStoredFloat("CDELT3")); } @Test void zeroCdeltHandlesAlternateVersions() { FitsCardList cards = wcs("CDELT1A = 0.0\nCDELT2A = 2.5\nEND"); - assertEquals(1.0, cards.getFloat("CDELT1A")); - assertEquals(2.5, cards.getFloat("CDELT2A")); + assertEquals(1.0, cards.getStoredFloat("CDELT1A")); + assertEquals(2.5, cards.getStoredFloat("CDELT2A")); } @Test @@ -106,10 +124,10 @@ void translatesCrotaToPcMatrix() { + "END"); assertTrue(consumed(cards, "CROTA2")); double cos30 = Math.cos(Math.toRadians(30.0)); - assertTrue(Math.abs(cards.getFloat("PC1_1") - cos30) < 1e-10); - assertTrue(Math.abs(cards.getFloat("PC2_2") - cos30) < 1e-10); - assertEquals(-1.0, cards.getFloat("CDELT1")); - assertEquals(1.0, cards.getFloat("CDELT2")); + assertTrue(Math.abs(cards.getStoredFloat("PC1_1") - cos30) < 1e-10); + assertTrue(Math.abs(cards.getStoredFloat("PC2_2") - cos30) < 1e-10); + assertEquals(-1.0, cards.getStoredFloat("CDELT1")); + assertEquals(1.0, cards.getStoredFloat("CDELT2")); } @Test @@ -123,9 +141,9 @@ void crotaSurvivesWhenPcAlreadyPresent() { + "PC2_2 = 1.0\n" + "CROTA2 = 30.0\n" + "END"); - assertEquals(30.0, cards.getFloat("CROTA2")); + assertEquals(30.0, cards.getStoredFloat("CROTA2")); assertFalse(consumed(cards, "CROTA2")); - assertEquals(1.0, cards.getFloat("PC1_1")); + assertEquals(1.0, cards.getStoredFloat("PC1_1")); } @Test @@ -141,12 +159,12 @@ void crotaSuppressedByPcOnANonCelestialAxis() { + "PC3_3 = 1.0\n" + "CROTA2 = 30.0\n" + "END"); - assertEquals(30.0, cards.getFloat("CROTA2")); + assertEquals(30.0, cards.getStoredFloat("CROTA2")); assertNull(cards.find("PC1_1")); assertNull(cards.find("PC1_2")); assertNull(cards.find("PC2_1")); assertNull(cards.find("PC2_2")); - assertEquals(1.0, cards.getFloat("PC3_3")); + assertEquals(1.0, cards.getStoredFloat("PC3_3")); } @Test @@ -179,52 +197,52 @@ void cnxxxTranslationSkippedForFitsWcs() { void translatesEpochToEquinox() { FitsCardList cards = wcs("EPOCH = 1995.0\nEND"); assertTrue(consumed(cards, "EPOCH")); - assertEquals(1995.0, cards.getFloat("EQUINOX")); + assertEquals(1995.0, cards.getStoredFloat("EQUINOX")); } @Test void epochZeroBecomesB1950Equinox() { FitsCardList cards = wcs("EPOCH = 0.0\nEND"); - assertEquals(1950.0, cards.getFloat("EQUINOX")); + assertEquals(1950.0, cards.getStoredFloat("EQUINOX")); } @Test void epochConsumedWhenEquinoxPresent() { FitsCardList cards = wcs("EPOCH = 1995.0\nEQUINOX = 2000.0\nEND"); assertTrue(consumed(cards, "EPOCH")); - assertEquals(2000.0, cards.getFloat("EQUINOX")); + assertEquals(2000.0, cards.getStoredFloat("EQUINOX")); } @Test void equinoxZeroBecomesB1950() { FitsCardList cards = wcs("EQUINOX = 0.0\nEND"); - assertEquals(1950.0, cards.getFloat("EQUINOX")); + assertEquals(1950.0, cards.getStoredFloat("EQUINOX")); } @Test void translatesEquinoxB1995StringToJulianNumber() { FitsCardList cards = wcs("EQUINOX = 'B1995.0'\nEND"); // C: dval = palEpj( palEpb2d( dval ) ) (fitschan.c:32136). - assertEquals(Pal.epj(Pal.epb2d(1995.0)), cards.getFloat("EQUINOX")); + assertEquals(Pal.epj(Pal.epb2d(1995.0)), cards.getStoredFloat("EQUINOX")); } @Test void translatesEquinoxJ2000StringToPlainNumber() { FitsCardList cards = wcs("EQUINOX = 'J2000.0'\nEND"); - assertEquals(2000.0, cards.getFloat("EQUINOX")); + assertEquals(2000.0, cards.getStoredFloat("EQUINOX")); } @Test void translatesDateObsToMjdObs() { FitsCardList cards = wcs("DATE-OBS= '2000-01-15T12:00:00'\nEND"); - assertTrue(Math.abs(cards.getFloat("MJD-OBS") - 51558.5) < 1e-6); + assertTrue(Math.abs(cards.getStoredFloat("MJD-OBS") - 51558.5) < 1e-6); assertNotNull(cards.find("DATE-OBS")); } @Test void dateObsSkippedWhenMjdObsPresent() { FitsCardList cards = wcs("DATE-OBS= '2000-01-15T12:00:00'\nMJD-OBS = 50000.0\nEND"); - assertEquals(50000.0, cards.getFloat("MJD-OBS")); + assertEquals(50000.0, cards.getStoredFloat("MJD-OBS")); // MJD-OBS is read only as a test for its presence (fitschan.c:32170-32175). List names = cards.takeConsumedNames(); assertTrue(names.contains("DATE-OBS")); @@ -234,34 +252,34 @@ void dateObsSkippedWhenMjdObsPresent() { @Test void translatesNcpToSinWithPv22() { FitsCardList cards = wcs("CTYPE1 = 'RA---NCP'\nCTYPE2 = 'DEC--NCP'\nCRVAL2 = 30.0\nEND"); - assertEquals("RA---SIN", cards.getString("CTYPE1")); - assertEquals("DEC--SIN", cards.getString("CTYPE2")); + assertEquals("RA---SIN", cards.getStoredString("CTYPE1", 10)); + assertEquals("DEC--SIN", cards.getStoredString("CTYPE2", 10)); double cot30 = 1.0 / Math.tan(Math.toRadians(30.0)); - assertTrue(Math.abs(cards.getFloat("PV2_2") - cot30) < 1e-10); - assertEquals(0.0, cards.getFloat("PV2_1")); + assertTrue(Math.abs(cards.getStoredFloat("PV2_2") - cot30) < 1e-10); + assertEquals(0.0, cards.getStoredFloat("PV2_1")); } @Test void translatesGlsToSfl() { FitsCardList cards = wcs("CTYPE1 = 'RA---GLS'\nCTYPE2 = 'DEC--GLS'\nEND"); - assertEquals("RA---SFL", cards.getString("CTYPE1")); - assertEquals("DEC--SFL", cards.getString("CTYPE2")); + assertEquals("RA---SFL", cards.getStoredString("CTYPE1", 10)); + assertEquals("DEC--SFL", cards.getStoredString("CTYPE2", 10)); } @Test void ncpAtEquatorLeftAlone() { FitsCardList cards = wcs("CTYPE1 = 'RA---NCP'\nCTYPE2 = 'DEC--NCP'\nCRVAL2 = 0.0\nEND"); - assertEquals("DEC--NCP", cards.getString("CTYPE2")); + assertEquals("DEC--NCP", cards.getStoredString("CTYPE2", 10)); } @Test void earlyPaperIiiWaveFrqBecomesWaveF2w() { - assertEquals("WAVE-F2W", wcs("CTYPE3 = 'WAVE-FRQ'\nEND").getString("CTYPE3")); + assertEquals("WAVE-F2W", wcs("CTYPE3 = 'WAVE-FRQ'\nEND").getStoredString("CTYPE3", 10)); } @Test void earlyPaperIiiVeloVelRedundantBlanks() { - assertEquals("VELO ", wcs("CTYPE3 = 'VELO-VEL'\nEND").getString("CTYPE3")); + assertEquals("VELO ", wcs("CTYPE3 = 'VELO-VEL'\nEND").getStoredString("CTYPE3", 10)); } @Test @@ -277,20 +295,20 @@ void translatesSaoCoToPvAndTpv() { + "CO2_3 = 0.0\n" + "CO2_5 = 0.7\n" + "END"); - assertEquals("RA---TPN", cards.getString("CTYPE1")); - assertEquals("DEC--TPN", cards.getString("CTYPE2")); - assertEquals(1.0, cards.getFloat("PV1_1")); - assertEquals(1.0, cards.getFloat("PV2_2")); - assertEquals(1.0, cards.getFloat("PC1_1")); - assertEquals(1.0, cards.getFloat("CDELT1")); + assertEquals("RA---TPN", cards.getStoredString("CTYPE1", 10)); + assertEquals("DEC--TPN", cards.getStoredString("CTYPE2", 10)); + assertEquals(1.0, cards.getStoredFloat("PV1_1")); + assertEquals(1.0, cards.getStoredFloat("PV2_2")); + assertEquals(1.0, cards.getStoredFloat("PC1_1")); + assertEquals(1.0, cards.getStoredFloat("CDELT1")); } @Test void translatesAtfToAit() { // The ATF translation has no encoding test (fitschan.c:32245-32257). FitsCardList cards = wcs("CTYPE1 = 'RA---ATF'\nCTYPE2 = 'DEC--ATF'\nEND"); - assertEquals("RA---AIT", cards.getString("CTYPE1")); - assertEquals("DEC--AIT", cards.getString("CTYPE2")); + assertEquals("RA---AIT", cards.getStoredString("CTYPE1", 10)); + assertEquals("DEC--AIT", cards.getStoredString("CTYPE2", 10)); } @Test @@ -300,34 +318,34 @@ void translatesQvToPvAndTanToTpn() { + "QV2_1 = 0.5\n" + "QV2_2 = 0.7\n" + "END"); - assertEquals("RA---TPN", cards.getString("CTYPE1")); - assertEquals("DEC--TPN", cards.getString("CTYPE2")); - assertEquals(0.5, cards.getFloat("PV2_1")); - assertEquals(0.7, cards.getFloat("PV2_2")); + assertEquals("RA---TPN", cards.getStoredString("CTYPE1", 10)); + assertEquals("DEC--TPN", cards.getStoredString("CTYPE2", 10)); + assertEquals(0.5, cards.getStoredFloat("PV2_1")); + assertEquals(0.7, cards.getStoredFloat("PV2_2")); assertTrue(consumed(cards, "QV2_1")); } @Test void translatesTpvToTpn() { FitsCardList cards = wcs("CTYPE1 = 'RA---TPV'\nCTYPE2 = 'DEC--TPV'\nEND"); - assertEquals("RA---TPN", cards.getString("CTYPE1")); - assertEquals("DEC--TPN", cards.getString("CTYPE2")); + assertEquals("RA---TPN", cards.getStoredString("CTYPE1", 10)); + assertEquals("DEC--TPN", cards.getStoredString("CTYPE2", 10)); } @Test void translatesZpxToZpnAndExtractsProjp() { FitsCardList cards = wcs( "CTYPE1 = 'RA---ZPX'\n" + "CTYPE2 = 'DEC--ZPX'\n" + "WAT2_001= 'projp1=1.0 projp2=-0.4'\n" + "END"); - assertEquals("RA---ZPN-ZPX", cards.getString("CTYPE1")); - assertEquals(1.0, cards.getFloat("PV2_1")); - assertEquals(-0.4, cards.getFloat("PV2_2")); + assertEquals("RA---ZPN-ZPX", cards.getStoredString("CTYPE1", 10)); + assertEquals(1.0, cards.getStoredFloat("PV2_1")); + assertEquals(-0.4, cards.getStoredFloat("PV2_2")); } @Test void translatesTnxToTpn() { FitsCardList cards = wcs("CTYPE1 = 'RA---TNX'\nCTYPE2 = 'DEC--TNX'\nEND"); - assertEquals("RA---TPN", cards.getString("CTYPE1")); - assertEquals("DEC--TPN", cards.getString("CTYPE2")); + assertEquals("RA---TPN", cards.getStoredString("CTYPE1", 10)); + assertEquals("DEC--TPN", cards.getStoredString("CTYPE2", 10)); } @Test @@ -338,7 +356,7 @@ void translatesMsxCarWrapsCrpix() { + "CRPIX1 = 1000.0\n" + "CDELT1 = -1.0\n" + "END"); - double crpix1 = cards.getFloat("CRPIX1"); + double crpix1 = cards.getStoredFloat("CRPIX1"); assertTrue(Math.abs(crpix1) < 250.0, "CRPIX1 not wrapped: " + crpix1); } @@ -348,30 +366,30 @@ void carlinSuppressesTheMsxCarWrap() { // translation of the CD matrix and gates the wrap on !CarLin (fitschan.c:32473). String text = Fixtures.read("wcsconv/inputs/car4.head"); FitsCardList wrapped = run(text, new FitsSpecTrans.TransAttrs(), new FitsSpecTrans.TransWarnings()); - assertNotEquals(211076.0, wrapped.getFloat("CRPIX1")); + assertNotEquals(211076.0, wrapped.getStoredFloat("CRPIX1")); FitsSpecTrans.TransAttrs carLin = new FitsSpecTrans.TransAttrs(); carLin.carLin = true; FitsCardList kept = run(text, carLin, new FitsSpecTrans.TransWarnings()); - assertEquals(211076.0, kept.getFloat("CRPIX1")); + assertEquals(211076.0, kept.getStoredFloat("CRPIX1")); } @Test void translatesRestfreqToRestfrqWithGhzScale() { FitsCardList cards = wcs("RESTFREQ= 1.42 / Rest frequency in GHz\nEND"); assertTrue(consumed(cards, "RESTFREQ")); - assertTrue(Math.abs(cards.getFloat("RESTFRQ") - 1.42e9) < 1.0); + assertTrue(Math.abs(cards.getStoredFloat("RESTFRQ") - 1.42e9) < 1.0); } @Test void translatesVeloLsrToVradPlusSpecsys() { FitsCardList cards = wcs("CTYPE3 = 'VELO-LSR'\nEND"); - assertEquals("VRAD ", cards.getString("CTYPE3")); - assertEquals("LSRK", cards.getString("SPECSYS")); + assertEquals("VRAD ", cards.getStoredString("CTYPE3", 10)); + assertEquals("LSRK", cards.getStoredString("SPECSYS", 10)); } @Test void translatesLambdaToWave() { - assertEquals("WAVE", wcs("CTYPE3 = 'LAMBDA '\nEND").getString("CTYPE3")); + assertEquals("WAVE", wcs("CTYPE3 = 'LAMBDA '\nEND").getStoredString("CTYPE3", 10)); } @Test @@ -380,10 +398,10 @@ void translatesCunitCaseInsensitively() { // (Ustrcmp, fitschan.c:32597-32604), so only an unpadded value is translated. FitsCardList cards = wcs("CUNIT1 = 'HZ'\n" + "CUNIT2 = 'M/S'\n" + "CUNIT3 = 'KM/S'\n" + "CUNIT4 = 'HZ '\n" + "END"); - assertEquals("Hz", cards.getString("CUNIT1")); - assertEquals("m/s", cards.getString("CUNIT2")); - assertEquals("km/s", cards.getString("CUNIT3")); - assertEquals("HZ ", cards.getString("CUNIT4")); + assertEquals("Hz", cards.getStoredString("CUNIT1", 10)); + assertEquals("m/s", cards.getStoredString("CUNIT2", 10)); + assertEquals("km/s", cards.getStoredString("CUNIT3", 10)); + assertEquals("HZ ", cards.getStoredString("CUNIT4", 10)); } @Test @@ -403,24 +421,236 @@ void irafMiniWcsKeywordsStripped() { assertFalse(names.contains("MWCS1")); } + // ------------------------------------------------------------------ + // The translations of FITS-PC and FITS-IRAF + // ------------------------------------------------------------------ + + @Test + void renameKeywordMovesValueAndCommentToNewName() { + // C writes RADESYS with the comment of the FitsChan's current card, the first card at the + // start of a read (CardComm( this ), fitschan.c:31663), which here is RADECSYS itself. + FitsCardList cards = pc("RADECSYS= 'FK5 ' / Reference frame\nEND"); + assertTrue(consumed(cards, "RADECSYS")); + assertEquals("FK5 ", cards.getStoredString("RADESYS", 10)); + assertEquals("Reference frame", cards.find("RADESYS").comment); + } + + @Test + void renameKeywordNoOpWhenSourceAbsent() { + FitsCardList cards = pc("END"); + assertNull(cards.find("RADECSYS")); + assertNull(cards.find("RADESYS")); + } + + @Test + void renameKeywordReplacesTheDestinationWhenAlreadyPresent() { + // Rust keeps RADESYS; C writes the RADECSYS value as RADESYS into the FitsChan of + // translations, whose values replace those of the header (WcsToStore), so RADECSYS wins + // (C probe p2 (a): the SkyFrame's System is FK4). + FitsCardList cards = + pc("RADECSYS= 'FK4 ' / Old\n" + "RADESYS = 'FK5 ' / New\n" + "END"); + assertTrue(consumed(cards, "RADECSYS")); + assertEquals("FK4 ", cards.getStoredString("RADESYS", 10)); + } + + @Test + void renameKeywordHandlesFloatValues() { + FitsCardList cards = pc("LONGPOLE= 180.0 / Old name\nEND"); + assertEquals(180.0, cards.getStoredFloat("LONPOLE")); + assertTrue(consumed(cards, "LONGPOLE")); + } + + @Test + void translatesRadecsysToRadesys() { + FitsCardList cards = pc("RADECSYS= 'FK5 ' / Old-style frame\nEND"); + assertTrue(consumed(cards, "RADECSYS")); + assertEquals("FK5 ", cards.getStoredString("RADESYS", 10)); + } + + @Test + void radecsysReplacesRadesysWhenBothPresent() { + // Rust's keeps_radesys_when_both_present; C gives the RADECSYS value (C probe p2 (a)). + FitsCardList cards = pc("RADECSYS= 'FK4 '\nRADESYS = 'FK5 '\nEND"); + assertEquals("FK4 ", cards.getStoredString("RADESYS", 10)); + } + + @Test + void translatesLongpoleToLonpole() { + FitsCardList cards = pc("LONGPOLE= 180.0 / Old name\nEND"); + assertTrue(consumed(cards, "LONGPOLE")); + assertEquals(180.0, cards.getStoredFloat("LONPOLE")); + } + + @Test + void translatesCdjjjiiiToPcWithUnitCdeltForFitsIraf() { + FitsCardList cards = iraf("CD001001= -2.0\n" + + "CD001002= 0.0\n" + + "CD002001= 0.0\n" + + "CD002002= 3.0\n" + + "END"); + assertTrue(consumed(cards, "CD001001")); + assertEquals(-2.0, cards.getStoredFloat("PC1_1")); + assertEquals(3.0, cards.getStoredFloat("PC2_2")); + // CDELT is 1.0 for every row that had a CDjjjiii. + assertEquals(1.0, cards.getStoredFloat("CDELT1")); + assertEquals(1.0, cards.getStoredFloat("CDELT2")); + } + + @Test + void cdjjjiiiTranslatedAndConsumedUnderFitsIraf() { + FitsCardList cards = iraf("CD001001= 1.0\nCD002002= 1.0\nEND"); + List names = cards.takeConsumedNames(); + assertTrue(names.contains("CD001001")); + assertTrue(names.contains("CD002002")); + assertEquals(1.0, cards.getStoredFloat("PC1_1")); + assertEquals(1.0, cards.getStoredFloat("PC2_2")); + } + + @Test + void translatesProjpToPvOnLatitudeAxis() { + // C reads PROJP with GetValue2, which marks the card used but does not delete it. + FitsCardList cards = pc("CTYPE1 = 'RA---ZPN'\n" + + "CTYPE2 = 'DEC--ZPN'\n" + + "PROJP0 = 0.0\n" + + "PROJP1 = 1.0\n" + + "PROJP2 = -0.4\n" + + "END"); + assertNotNull(cards.find("PROJP0")); + assertNotNull(cards.find("PROJP1")); + assertTrue(consumed(cards, "PROJP1")); + assertEquals(0.0, cards.getStoredFloat("PV2_0")); + assertEquals(1.0, cards.getStoredFloat("PV2_1")); + assertEquals(-0.4, cards.getStoredFloat("PV2_2")); + } + + @Test + void projpUsedWhenPvSetIsIncomplete() { + // PV1_1 and PV1_2 without PV1_0: the PV values are not trusted (fitschan.c:31929-31935). + FitsCardList cards = pc("CTYPE1 = 'RA---ZPN'\n" + + "CTYPE2 = 'DEC--ZPN'\n" + + "PROJP0 = 0.0\n" + + "PV1_1 = 1.0\n" + + "PV1_2 = -0.4\n" + + "END"); + assertEquals(0.0, cards.getStoredFloat("PV2_0")); + } + + @Test + void translatesCnxxxToAltLetterFormForFitsPc() { + FitsCardList cards = pc("C1YPE1 = 'GLON-TAN'\n" + + "C1YPE2 = 'GLAT-TAN'\n" + + "C1VAL1 = 101.255\n" + + "C1VAL2 = 16.177\n" + + "C1PIX1 = 50.5\n" + + "C1PIX2 = 50.5\n" + + "C1ELT1 = -0.01\n" + + "C1ELT2 = 0.01\n" + + "END"); + List names = cards.takeConsumedNames(); + assertTrue(names.contains("C1YPE1")); + assertTrue(names.contains("C1ELT1")); + assertEquals("GLON-TAN", cards.getStoredString("CTYPE1A", 10)); + assertEquals("GLAT-TAN", cards.getStoredString("CTYPE2A", 10)); + assertEquals(101.255, cards.getStoredFloat("CRVAL1A")); + assertEquals(50.5, cards.getStoredFloat("CRPIX1A")); + assertEquals(-0.01, cards.getStoredFloat("CDELT1A")); + // The unit PC matrix, there being no PCjjjiii. + assertEquals(1.0, cards.getStoredFloat("PC1_1A")); + assertEquals(0.0, cards.getStoredFloat("PC1_2A")); + assertEquals(1.0, cards.getStoredFloat("PC2_2A")); + } + + @Test + void cnxxxZeroCdeltFallsBackToCrvalOrOne() { + // A zero CmELTi becomes 0.01 times CRVALiA, the translated C1VAL1 (fitschan.c:32063-32068). + FitsCardList cards = pc("C1YPE1 = 'GLON-TAN'\n" + + "C1VAL1 = 100.0\n" + + "C1ELT1 = 0.0\n" + + "END"); + assertEquals(1.0, cards.getStoredFloat("CDELT1A")); + } + // ------------------------------------------------------------------ // C behaviour beyond the Rust tests // ------------------------------------------------------------------ @Test - void encodingsThatAreNotReadThrow() { - for (FitsChan.Encoding e : new FitsChan.Encoding[] { - FitsChan.Encoding.FITS_PC, FitsChan.Encoding.FITS_IRAF, FitsChan.Encoding.FITS_CLASS - }) { - UnsupportedOperationException ex = assertThrows( - UnsupportedOperationException.class, - () -> FitsSpecTrans.specTransInplace( - FitsCardList.fromHeader("END"), - e, - new FitsSpecTrans.TransAttrs(), - new FitsSpecTrans.TransWarnings())); - assertEquals("FitsChan: reading the " + e.cName() + " encoding is not available", ex.getMessage()); + void fitsClassIsNotRead() { + UnsupportedOperationException ex = assertThrows( + UnsupportedOperationException.class, + () -> FitsSpecTrans.specTransInplace( + FitsCardList.fromHeader("END"), + FitsChan.Encoding.FITS_CLASS, + new FitsSpecTrans.TransAttrs(), + new FitsSpecTrans.TransWarnings())); + assertEquals("FitsChan: reading the FITS-CLASS encoding is not available", ex.getMessage()); + } + + @Test + void translatedCardsTakeTheCommentOfTheFirstCard() { + // C gives the cards it translates from RADECSYS, LONGPOLE, PROJPm and CmXXXi the comment of + // the current card of the FitsChan read (CardComm( this ), fitschan.c:31663-31673, + // 31956-32034), which is the first card when a read starts. + FitsCardList cards = pc("NAXIS = 2 / first card\n" + + "LONGPOLE= 180.0 / Old name\n" + + "C1VAL1 = 10.0 / CRVAL1 of A\n" + + "END"); + assertEquals("first card", cards.find("LONPOLE").comment); + assertEquals("first card", cards.find("CRVAL1A").comment); + } + + @Test + void radecsysWinsOverRadesysInARead() { + // C probe p2 (a): with both, the FITS-PC read's SkyFrame takes the RADECSYS system. + FitsChan fc = FitsHeaders.chan( + "NAXIS = 2 / first card comment", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 20", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "RADECSYS= 'FK4'", + "RADESYS = 'FK5'", + "EQUINOX = 1950.0"); + fc.setEncoding("FITS-PC"); + assertEquals("FK4", FitsHeaders.readFrameSet(fc).getC("System")); + } + + @Test + void projpParametersReachTheProjectionOnlyUnderPcAndIraf() { + // C probe p2 (c): a ZPN projection whose parameters are PROJPm. Under FITS-PC and FITS-IRAF + // they become PV2_m; under FITS-WCS they are only read, and the projection has none. + String[] header = { + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'RA---ZPN'", + "CTYPE2 = 'DEC--ZPN'", + "CRPIX1 = 50", + "CRPIX2 = 50", + "CRVAL1 = 10", + "CRVAL2 = 80", + "CDELT1 = -0.01", + "CDELT2 = 0.01", + "PROJP1 = 1.0", + "PROJP3 = 0.5" + }; + for (String enc : new String[] {"FITS-PC", "FITS-IRAF"}) { + FitsChan fc = FitsHeaders.chan(header); + fc.setEncoding(enc); + double[] out = FitsHeaders.tran(FitsHeaders.readFrameSet(fc), new double[] {10.0, 90.0}, true); + assertEquals(0.21636900620530422, out[0], 1e-15, enc); + assertEquals(1.4031004897573576, out[1], 1e-15, enc); } + FitsChan fc = FitsHeaders.chan(header); + fc.setEncoding("FITS-WCS"); + FrameSet fs = FitsHeaders.readFrameSet(fc); + assertThrows(AstException.class, () -> FitsHeaders.tran(fs, new double[] {10.0, 90.0}, true)); } @Test @@ -441,8 +671,8 @@ void cdMatrixSizeIsTheHighestColumnIndex() { // C's Match stores the fields from the last (fitschan.c:22790), so naxis is the highest // column index: a matrix with one column is a 1x1 matrix. FitsCardList cards = wcs("CD1_1 = 2.0\nCD2_1 = 1.0\nEND"); - assertEquals(2.0, cards.getFloat("CDELT1")); - assertEquals(1.0, cards.getFloat("PC1_1")); + assertEquals(2.0, cards.getStoredFloat("CDELT1")); + assertEquals(1.0, cards.getStoredFloat("PC1_1")); assertNull(cards.find("CDELT2")); assertNull(cards.find("PC2_1")); assertFalse(consumed(cards, "CD2_1")); @@ -483,10 +713,10 @@ void cmeltIsTranslatedUnderEveryEncoding() { + "C1ELT1 = 2.0\n" + "C1ELT2 = 3.0\n" + "END"); - assertEquals(2.0, cards.getFloat("CDELT1A")); - assertEquals(3.0, cards.getFloat("CDELT2A")); - assertEquals(1.0, cards.getFloat("PC1_1A")); - assertEquals(0.0, cards.getFloat("PC1_2A")); + assertEquals(2.0, cards.getStoredFloat("CDELT1A")); + assertEquals(3.0, cards.getStoredFloat("CDELT2A")); + assertEquals(1.0, cards.getStoredFloat("PC1_1A")); + assertEquals(0.0, cards.getStoredFloat("PC1_2A")); assertNull(cards.find("CRVAL1A")); assertTrue(consumed(cards, "C1VAL1")); } @@ -504,7 +734,7 @@ void zeroPolyTanCoefficientsWarnAndAreDeleted() { + "END", new FitsSpecTrans.TransAttrs(), w); - assertEquals("RA---TAN", cards.getString("CTYPE1")); + assertEquals("RA---TAN", cards.getStoredString("CTYPE1", 10)); assertNull(cards.find("PV2_1")); assertNull(cards.find("PV2_2")); assertTrue(w.entry.isEmpty()); @@ -536,8 +766,8 @@ void specTransLeavesTheSuppliedCardsAndRecordsWhatItWrites() { new FitsSpecTrans.TransAttrs(), new FitsSpecTrans.TransWarnings(), new FitsWarnings()); - assertEquals("RA---TPV", cards.getString("CTYPE1")); - assertEquals("RA---TPN", trans.getString("CTYPE1")); + assertEquals("RA---TPV", cards.getStoredString("CTYPE1", 10)); + assertEquals("RA---TPN", trans.getStoredString("CTYPE1", 10)); List written = trans.takeWrittenNames(); assertTrue(written.contains("CTYPE1")); assertTrue(written.contains("CTYPE2")); diff --git a/src/test/java/uk/ac/starlink/ast/FitsWcsDecomposeTest.java b/src/test/java/uk/ac/starlink/ast/FitsWcsDecomposeTest.java new file mode 100644 index 0000000..2239d37 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsWcsDecomposeTest.java @@ -0,0 +1,138 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Tests of {@link FitsWcsDecompose}: the unit tests of Rust {@code fitschan/wcs_decompose.rs} + * ({@code split_cd}, C's {@code SplitMat}), and tests of C's {@code FindBasisVectors}, {@code + * FitLine} and {@code FitOK} whose expectations follow from those functions in fitschan.c. + */ +class FitsWcsDecomposeTest { + + private static final double BAD = AstObject.AST__BAD; + + @Test + void splitCdDiagonal() { + double[] m = {-0.001, 0.0, 0.0, 0.001}; + double[] cdelt = new double[2]; + assertTrue(FitsWcsDecompose.splitMat(2, m, cdelt)); + assertEquals(-0.001, cdelt[0], 1e-15); + assertEquals(0.001, cdelt[1], 1e-15); + assertEquals(1.0, m[0], 1e-15); + assertEquals(1.0, m[3], 1e-15); + } + + @Test + void splitCdRotated() { + double s = 0.001; + double cos45 = Math.sqrt(0.5); + double[] m = {s * cos45, -s * cos45, s * cos45, s * cos45}; + double[] cdelt = new double[2]; + assertTrue(FitsWcsDecompose.splitMat(2, m, cdelt)); + assertEquals(s, Math.abs(cdelt[0]), 1e-12); + assertEquals(s, Math.abs(cdelt[1]), 1e-12); + assertEquals(1.0, Math.sqrt(m[0] * m[0] + m[1] * m[1]), 1e-12); + assertEquals(1.0, Math.sqrt(m[2] * m[2] + m[3] * m[3]), 1e-12); + } + + /** SplitMat (fitschan.c) stops at the first bad element and returns zero. */ + @Test + void splitMatStopsAtABadElement() { + double[] m = {BAD, 0.0, 0.0, 1.0}; + double[] cdelt = {7.0, 7.0}; + assertFalse(FitsWcsDecompose.splitMat(2, m, cdelt)); + assertArrayEquals(new double[] {BAD, 0.0, 0.0, 1.0}, m); + assertArrayEquals(new double[] {7.0, 7.0}, cdelt); + } + + /** FitOK accepts a mean squared residual strictly below the squared tolerance. */ + @Test + void fitOkIsStrict() { + assertFalse(FitsWcsDecompose.fitOK(2, new double[] {0.5, 0.5}, new double[] {0.0, 0.0}, 0.5)); + assertTrue(FitsWcsDecompose.fitOK(2, new double[] {0.5, 0.0}, new double[] {0.0, 0.0}, 0.5)); + } + + /** FitOK skips pairs with a bad value, and fails when none is left. */ + @Test + void fitOkSkipsBadValues() { + assertTrue(FitsWcsDecompose.fitOK(2, new double[] {BAD, 1.0}, new double[] {0.0, 1.0}, 1e-10)); + assertFalse(FitsWcsDecompose.fitOK(2, new double[] {BAD, 1.0}, new double[] {0.0, BAD}, 1.0)); + } + + /** With every dimension known, the first root position tried is the grid centre. */ + @Test + void basisVectorsStartAtTheGridCentre() { + ShiftMap map = new ShiftMap(new double[] {10.0, -20.0}); + double[][] ptrg = new double[2][3]; + double[][] ptrw = new double[2][3]; + assertTrue(FitsWcsDecompose.findBasisVectors(map, 2, 2, new double[] {100.0, 50.0}, ptrg, ptrw)); + assertArrayEquals(new double[] {50.5, 51.5, 50.5}, ptrg[0]); + assertArrayEquals(new double[] {25.5, 25.5, 26.5}, ptrg[1]); + assertArrayEquals(new double[] {60.5, 61.5, 60.5}, ptrw[0]); + assertArrayEquals(new double[] {5.5, 5.5, 6.5}, ptrw[1]); + } + + /** With a dimension unknown, the first root position tried is (1, 1, ...). */ + @Test + void basisVectorsStartAtOneWithoutDimensions() { + ShiftMap map = new ShiftMap(new double[] {10.0, -20.0}); + double[][] ptrg = new double[2][3]; + double[][] ptrw = new double[2][3]; + assertTrue(FitsWcsDecompose.findBasisVectors(map, 2, 2, new double[] {100.0, BAD}, ptrg, ptrw)); + assertArrayEquals(new double[] {1.0, 2.0, 1.0}, ptrg[0]); + assertArrayEquals(new double[] {1.0, 1.0, 2.0}, ptrg[1]); + assertTrue(FitsWcsDecompose.findBasisVectors(map, 2, 2, null, ptrg, ptrw)); + assertArrayEquals(new double[] {1.0, 2.0, 1.0}, ptrg[0]); + } + + /** FitLine gives the vector in the output space of a unit step along the input line. */ + @Test + void fitLineOfALinearMapping() { + MatrixMap map = new MatrixMap(2, 2, new double[][] {{3.0, 1.0}, {-2.0, 0.5}}); + double[] g0 = {50.5, 50.5}; + double[] w0 = {3.0 * 50.5 + 50.5, -2.0 * 50.5 + 0.5 * 50.5}; + double[] tol = {3.0e-3, 2.0e-3}; + double[] col = FitsWcsDecompose.fitLine(map, new double[] {1.0, 0.0}, g0, w0, 100.0, tol); + assertNotNull(col); + assertEquals(3.0, col[0], 1e-12); + assertEquals(-2.0, col[1], 1e-12); + col = FitsWcsDecompose.fitLine(map, new double[] {0.0, 1.0}, g0, w0, BAD, tol); + assertNotNull(col); + assertEquals(1.0, col[0], 1e-12); + assertEquals(0.5, col[1], 1e-12); + } + + /** A constant output gives a zero component. */ + @Test + void fitLineOfAConstantOutputIsZero() { + PermMap map = new PermMap(1, new int[] {1}, 2, new int[] {1, -1}, new double[] {7.0}); + double[] col = FitsWcsDecompose.fitLine( + map, new double[] {1.0}, new double[] {5.0}, new double[] {5.0, 7.0}, 10.0, new double[] {1e-3, 1e-3}); + assertNotNull(col); + assertEquals(1.0, col[0], 1e-12); + assertEquals(0.0, col[1]); + } + + /** FitLine returns no vector for a zero dimension, a bad root value, or a non-linear Mapping. */ + @Test + void fitLineFailures() { + ZoomMap zoom = new ZoomMap(1, 2.0); + double[] g = {1.0}; + double[] tol = {1e-3}; + assertNull(FitsWcsDecompose.fitLine(zoom, g, new double[] {5.0}, new double[] {10.0}, 0.0, tol)); + assertNull(FitsWcsDecompose.fitLine(zoom, g, new double[] {5.0}, new double[] {BAD}, 10.0, tol)); + WcsMap tan = new WcsMap(2, WcsMap.AST__TAN, 1, 2); + tan.invert(); + double[] g0 = {0.0, 0.0}; + double[][] w0 = tan.transform(new double[][] {{0.0}, {0.0}}, 1, true); + assertNull(FitsWcsDecompose.fitLine( + tan, new double[] {1.0, 0.0}, g0, new double[] {w0[0][0], w0[1][0]}, BAD, new double[] {1e-3, 1e-3})); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsWcsWriteTest.java b/src/test/java/uk/ac/starlink/ast/FitsWcsWriteTest.java new file mode 100644 index 0000000..4d841d7 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsWcsWriteTest.java @@ -0,0 +1,342 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * {@link FitsWcsWrite}, C's {@code WcsFromStore}, and the comment rules of C's {@code SetValue} + * and {@code SetFits} it writes its cards with ({@link FitsCardList#setValueAsWriter}). The cards + * expected are those a C probe of the pinned library wrote ({@code p1.c} beside the task report), + * or are worked from {@code WcsFromStore}'s code where a store is written directly. + */ +class FitsWcsWriteTest { + + /** A card as C lists it: 80 characters, blank-padded. */ + private static String pad(String card) { + StringBuilder b = new StringBuilder(card); + while (b.length() < 80) { + b.append(' '); + } + return b.toString(); + } + + private static List padded(String... cards) { + List out = new ArrayList<>(); + for (String c : cards) { + out.add(pad(c)); + } + return out; + } + + /** The probe's FrameSet: {@code n} GRID axes shifted by 5, 6 and 7 to a Frame with {@code attrs}. */ + private static FrameSet plain(int n, String attrs) { + Frame grid = new Frame(n); + grid.setDomain("GRID"); + Frame wcs = new Frame(n); + wcs.set(attrs); + FrameSet fs = new FrameSet(grid); + fs.addFrame(FrameSet.AST__BASE, new ShiftMap(Arrays.copyOf(new double[] {5, 6, 7}, n)), wcs); + return fs; + } + + /** The cards of {@code fs} written FITS-WCS into a FitsChan holding {@code cards}. */ + private static List written(FrameSet fs, String... cards) { + FitsChan fc = FitsHeaders.chan(cards); + fc.setEncoding("FITS-WCS"); + assertEquals(1, fc.write(fs)); + return FitsHeaders.foundCards(fc); + } + + /** + * A card replaced keeps its comment when C's {@code Similar} finds the values alike, and + * {@code Similar} does not compare the last character that is not blank (C-library quirk). + */ + @Test + void similarIgnoresTheLastCharacter() { + List rest = padded( + "WCSAXES = 2 / Number of WCS axes", + "CRPIX1 = 1.0 / Reference pixel on axis 1", + "CRPIX2 = 1.0 / Reference pixel on axis 2", + "CRVAL1 = 6.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 7.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'ABCD1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'ABCD2 ' / Type of co-ordinate on axis 2", // codespell:ignore + "CDELT1 = 1.0 / Pixel size on axis 1", + "CDELT2 = 1.0 / Pixel size on axis 2"); + List want = new ArrayList<>(); + want.add(pad("WCSNAME = 'ABCD ' / old comment")); + want.addAll(rest); + assertEquals(want, written(plain(2, "Domain=ABCD"), "WCSNAME = 'ABCX' / old comment")); + want.set(0, pad("WCSNAME = 'ABCD ' / Reference name for the coord. frame")); + assertEquals(want, written(plain(2, "Domain=ABCD"), "WCSNAME = 'ABXD' / old comment")); + + assertTrue(FitsCardList.similar("RA---TAN", "ra---tab")); + assertTrue(FitsCardList.similar(" A B ", "A B")); + assertFalse(FitsCardList.similar("ABCD", "ABC")); + assertFalse(FitsCardList.similar("ABCD", "")); + assertTrue(FitsCardList.similar(" ", "")); + } + + /** For one axis, WCSNAME is left out when {@code Similar} finds it like CTYPE1. */ + @Test + void oneAxisWcsnameLeftOutWhenLikeCtype() { + assertEquals( + padded( + "WCSAXES = 1 / Number of WCS axes", + "CRPIX1 = 1.0 / Reference pixel on axis 1", + "CRVAL1 = 6.0 / Value at ref. pixel on axis 1", + "CTYPE1 = 'ABCD ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 1.0 / Pixel size on axis 1"), + written(plain(1, "Domain=ABCX,Symbol(1)=ABCD"))); + assertEquals( + padded( + "WCSAXES = 1 / Number of WCS axes", + "WCSNAME = 'ABXD ' / Reference name for the coord. frame", + "CRPIX1 = 1.0 / Reference pixel on axis 1", + "CRVAL1 = 6.0 / Value at ref. pixel on axis 1", + "CTYPE1 = 'ABCD ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 1.0 / Pixel size on axis 1"), + written(plain(1, "Domain=ABXD,Symbol(1)=ABCD"))); + } + + /** + * A card replaced keeps its comment when its value, converted to the type of the new value as + * C's {@code CnvValue} converts it, is the same; a value that cannot be converted does not. + * The new cards go after the last card describing WCS. + */ + @Test + void aReplacedCardKeepsItsCommentWhenTheConvertedValueIsTheSame() { + assertEquals( + padded( + "CRPIX1 = 1.0 / old int comment", + "CRVAL1 = 6.0 / old crval comment", + "CDELT1 = 1.0 / Pixel size on axis 1", + "WCSAXES = 1 / Number of WCS axes", + "WCSNAME = 'ABCD ' / Reference name for the coord. frame", + "CTYPE1 = 'ABCD1 ' / Type of co-ordinate on axis 1"), // codespell:ignore + written( + plain(1, "Domain=ABCD"), + "CRPIX1 = 1 / old int comment", + "CRVAL1 = 6 / old crval comment", + "CDELT1 = 'X' / old string comment")); + } + + /** A store with the keywords common to every axis type, for two axes. */ + private static FitsStore store() { + FitsStore st = new FitsStore(2); + st.crpix[0] = 100.0; + st.crpix[1] = 100.0; + st.crval[0] = 180.0; + st.crval[1] = 0.0; + st.ctype[0] = "RA---TAN"; + st.ctype[1] = "DEC--TAN"; + st.cdelt[0] = -0.001; + st.cdelt[1] = 0.001; + return st; + } + + private static List keywords(FitsChan fc) { + List out = new ArrayList<>(); + for (String card : FitsHeaders.foundCards(fc)) { + out.add(card.substring(0, 8).trim()); + } + return out; + } + + /** + * The AST extension keywords and the observation-wide keywords, in C's order: the alternate + * description has the version letter on each keyword but IMAGFREQ, and no OBSGEO or date of + * observation. (Rust {@code primary_plane_emits_ast_extension_keywords} and {@code + * alt_plane_emits_suffixed_versions_and_no_obsgeo}, whose IMAGFREQ follows C here.) + */ + @Test + void extensionKeywordsAndVersionLetters() { + FitsPlaneStores stores = new FitsPlaneStores(2); + for (char s : new char[] {' ', 'A'}) { + FitsStore st = stores.version(s, 2); + FitsStore src = store(); + st.crpix = src.crpix; + st.crval = src.crval; + st.ctype = src.ctype; + st.cdelt = src.cdelt; + st.wcsname = "MYDOMAIN"; + st.obsgeox = 1234567.0; + st.obsgeoy = 2345678.0; + st.obsgeoz = 3456789.0; + st.ssyssrc = "LSRK"; + st.zsource = 0.025; + st.imagfreq = 2.3e11; + st.skyrefis = "ORIGIN"; + st.skyref[0] = 1.5; + st.skyref[1] = 0.25; + st.skyrefp[0] = 1.6; + st.skyrefp[1] = 0.5; + st.mjdobs = 51544.5; + } + FitsChan fc = new FitsChan(); + assertTrue(fromStore(fc, stores, "astWrite", "FrameSet")); + assertEquals( + Arrays.asList( + "WCSAXES", + "WCSNAME", + "CRPIX1", + "CRPIX2", + "CRVAL1", + "CRVAL2", + "CTYPE1", + "CTYPE2", + "CDELT1", + "CDELT2", + "SREFIS", + "SREF1", + "SREF2", + "SREFP1", + "SREFP2", + "MJD-OBS", + "DATE-OBS", + "SSYSSRC", + "ZSOURCE", + "IMAGFREQ", + "OBSGEO-X", + "OBSGEO-Y", + "OBSGEO-Z", + "WCSAXESA", + "WCSNAMEA", + "CRPIX1A", + "CRPIX2A", + "CRVAL1A", + "CRVAL2A", + "CTYPE1A", + "CTYPE2A", + "CDELT1A", + "CDELT2A", + "SREFISA", + "SREF1A", + "SREF2A", + "SREFP1A", + "SREFP2A", + "SSYSSRCA", + "ZSOURCEA"), + keywords(fc)); + assertEquals("2000-01-01T12:00:00.000", fc.getFitsS("DATE-OBS")); + } + + /** + * A version without CRPIX1 is not written, and the versions after it still are; one lacking + * a CTYPE on an axis is removed whole; and none is written if the primary one is not. + */ + @Test + void incompleteVersionsAreNotWritten() { + FitsPlaneStores stores = new FitsPlaneStores(2); + stores.version(' ', 2); + copyInto(stores.get(' '), store()); + FitsStore a = stores.version('A', 2); + copyInto(a, store()); + a.crpix[0] = null; + FitsStore b = stores.version('B', 2); + copyInto(b, store()); + b.ctype[1] = null; + FitsStore c = stores.version('C', 2); + copyInto(c, store()); + FitsChan fc = new FitsChan(); + assertTrue(fromStore(fc, stores, "astWrite", "FrameSet")); + List kw = keywords(fc); + assertTrue(kw.contains("CRPIX1C"), kw.toString()); + for (String k : kw) { + assertFalse(k.endsWith("A") || k.endsWith("B"), k); + } + + stores.get(' ').crval[0] = null; + FitsChan none = new FitsChan(); + assertFalse(fromStore(none, stores, "astWrite", "FrameSet")); + assertEquals(0, none.getNcard()); + } + + /** + * {@link FitsWcsWrite#wcsFromStore} with the cards it adds marked new, as C's {@code Write} + * marks them while it runs; the marks are then cleared. + */ + private static boolean fromStore(FitsChan fc, FitsPlaneStores stores, String method, String cls) { + fc.cards().beginMarkingNew(); + try { + return FitsWcsWrite.wcsFromStore(fc, stores, method, cls); + } finally { + fc.cards().fixNew(FitsCardList.NewScope.WRITE, false); + fc.cards().endMarkingNew(); + } + } + + private static void copyInto(FitsStore st, FitsStore src) { + st.crpix = src.crpix; + st.crval = src.crval; + st.ctype = src.ctype; + st.cdelt = src.cdelt; + } + + /** + * With CDMatrix the CD matrix is written, each PC row times its CDELT and zero elements left + * out; without it, CDELT and the PC elements other than the unit matrix's. A TPN projection is + * written TAN, its parameters (and every other axis's) as QV. + */ + @Test + void matrixFormsAndTpn() { + FitsPlaneStores stores = new FitsPlaneStores(2); + FitsStore st = stores.version(' ', 2); + copyInto(st, store()); + st.ctype[0] = "RA---TPN"; + st.ctype[1] = "DEC--TPN"; + st.pc[0][0] = 1.0; + st.pc[0][1] = 0.5; + st.pc[1][0] = 0.0; + st.pv[1][1] = 0.25; + FitsChan fc = new FitsChan(); + fc.setCDMatrix(true); + assertTrue(fromStore(fc, stores, "astWrite", "FrameSet")); + assertEquals( + Arrays.asList( + "WCSAXES", "CRPIX1", "CRPIX2", "CRVAL1", "CRVAL2", "CTYPE1", "CTYPE2", "CD1_1", "CD1_2", + "CD2_2", "QV2_1"), + keywords(fc)); + assertEquals("RA---TAN", fc.getFitsS("CTYPE1")); + assertEquals(-0.0005, fc.getFitsF("CD1_2"), 0.0); + + FitsChan pc = new FitsChan(); + pc.setCDMatrix(false); + assertTrue(fromStore(pc, stores, "astWrite", "FrameSet")); + assertEquals( + Arrays.asList( + "WCSAXES", "CRPIX1", "CRPIX2", "CRVAL1", "CRVAL2", "CTYPE1", "CTYPE2", "CDELT1", "CDELT2", + "PC1_2", "QV2_1"), + keywords(pc)); + } + + /** + * The SIP coefficients, in order of the powers, each table followed by its order, the highest + * sum of the powers; the coefficients of an alternate version carry its letter, but the order + * keyword does not (C-library quirk). + */ + @Test + void sipCoefficientsAndOrders() { + FitsPlaneStores stores = new FitsPlaneStores(2); + FitsStore st = stores.version(' ', 2); + copyInto(st, store()); + FitsStore a = stores.version('A', 2); + copyInto(a, store()); + a.sipA = FitsStore.setItem(a.sipA, 0, 2, 1e-6); + a.sipA = FitsStore.setItem(a.sipA, 2, 1, 2e-7); + a.sipBp = FitsStore.setItem(a.sipBp, 1, 0, 3e-5); + FitsChan fc = new FitsChan(); + assertTrue(fromStore(fc, stores, "astWrite", "FrameSet")); + List kw = keywords(fc); + int i = kw.indexOf("A_0_2A"); + assertEquals(Arrays.asList("A_0_2A", "A_2_1A", "A_ORDER", "BP_1_0A", "BP_ORDER"), kw.subList(i, i + 5)); + assertEquals(3, fc.getFitsI("A_ORDER")); + assertEquals(1, fc.getFitsI("BP_ORDER")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsWorldAxesTest.java b/src/test/java/uk/ac/starlink/ast/FitsWorldAxesTest.java new file mode 100644 index 0000000..d5e35df --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsWorldAxesTest.java @@ -0,0 +1,83 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** Translation of the unit tests of Rust {@code fitschan/fset_to_store/world_axes.rs} (C {@code WorldAxes}). */ +class FitsWorldAxesTest { + + private static int[] worldAxes(Mapping map, double[] dim) { + int[] perm = new int[map.getNout()]; + assertTrue(FitsWorldAxes.worldAxes(new FitsChan(), map, dim, perm)); + return perm; + } + + @Test + void unitMap2dReturnsIdentityPerm() { + assertArrayEquals(new int[] {0, 1}, worldAxes(new UnitMap(2), new double[] {100, 100})); + } + + /** A PermMap swapping the axes associates each output with the other input. */ + @Test + void permMapSwapsAxes() { + PermMap pm = new PermMap(2, new int[] {2, 1}, 2, new int[] {2, 1}, null); + assertArrayEquals(new int[] {1, 0}, worldAxes(pm, new double[] {100, 100})); + } + + @Test + void shiftMapKeepsIdentity() { + ShiftMap s = new ShiftMap(new double[] {10.0, 20.0}); + assertArrayEquals(new int[] {0, 1}, worldAxes(s, new double[] {50, 50})); + } + + @Test + void matrixSwapViaOffDiagonal() { + MatrixMap mm = new MatrixMap(2, 2, new double[][] {{0.0, 1.0}, {1.0, 0.0}}); + assertArrayEquals(new int[] {1, 0}, worldAxes(mm, new double[] {100, 100})); + } + + /** Output 0 follows pixel axis 1, output 1 pixel axis 2 and output 2 pixel axis 0. */ + @Test + void threeAxisPartialSwap() { + PermMap pm = new PermMap(3, new int[] {3, 1, 2}, 3, new int[] {2, 3, 1}, null); + assertArrayEquals(new int[] {1, 2, 0}, worldAxes(pm, new double[] {100, 100, 100})); + } + + @Test + void seriesChainOfShiftAndSwap() { + ShiftMap shift = new ShiftMap(new double[] {3.0, 7.0}); + MatrixMap swap = new MatrixMap(2, 2, new double[][] {{0.0, 1.0}, {1.0, 0.0}}); + CmpMap chain = new CmpMap(shift, swap, true); + assertArrayEquals(new int[] {1, 0}, worldAxes(chain, new double[] {100, 100})); + } + + /** + * A Mapping with only a forward transformation is analysed only when TabOK is positive, each + * output taking the input that alone feeds it. + */ + @Test + void aForwardOnlyMappingNeedsTabOk() { + PolyMap square = new PolyMap(1, 1, 1, new double[] {1.0, 1, 2}, 0, null); + square.set("IterInverse=0"); + CmpMap map = new CmpMap(new UnitMap(1), square, false); + int[] perm = new int[2]; + FitsChan fc = new FitsChan(); + assertFalse(FitsWorldAxes.worldAxes(fc, map, new double[] {10, 10}, perm)); + fc.set("TabOK=1"); + assertTrue(FitsWorldAxes.worldAxes(fc, map, new double[] {10, 10}, perm)); + assertArrayEquals(new int[] {0, 1}, perm); + } + + /** + * A WCS axis no pixel axis is aligned with takes the lowest unused pixel axis, numbering past + * the pixel axes when they run out (fitschan.c {@code WorldAxes}). + */ + @Test + void aDegenerateWcsAxisIsNumberedPastThePixelAxes() { + PermMap pm = new PermMap(1, new int[] {2}, 2, new int[] {-1, 1}, new double[] {4.0}); + assertArrayEquals(new int[] {1, 0}, worldAxes(pm, new double[] {100})); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsWriteUnsupportedTest.java b/src/test/java/uk/ac/starlink/ast/FitsWriteUnsupportedTest.java new file mode 100644 index 0000000..4246488 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsWriteUnsupportedTest.java @@ -0,0 +1,110 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * A FrameSet whose description in FITS-WCS needs a class this library lacks makes {@link + * FitsChan#write} throw an {@link UnsupportedOperationException} naming the class, at the point C + * reaches it, and leaves the cards as they were. Each FrameSet is one a C-oracle probe linked + * against the pinned C library wrote, with the outcome noted beside it. + */ +class FitsWriteUnsupportedTest { + + /** A 1-D FrameSet whose world axis is {@code c0 + c1 p + c2 p^2} of the pixel axis. */ + private static FrameSet quadratic(double c0, double c1, double c2) { + PolyMap pm = new PolyMap(1, 1, 3, new double[] {c0, 1, 0, c1, 1, 1, c2, 1, 2}, 0, new double[0]); + pm.set("IterInverse=1"); + Frame pixel = new Frame(1); + pixel.setDomain("GRID"); + Frame wcs = new Frame(1); + wcs.setDomain("WORLD"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, pm, wcs); + return fs; + } + + private static FitsChan chan(String attrs) { + FitsChan fc = FitsChan.fromHeader(String.join("\n", "NAXIS = 1", "NAXIS1 = 100")); + fc.setEncoding("FITS-WCS"); + if (!attrs.isEmpty()) { + fc.set(attrs); + } + return fc; + } + + private static void assertNeeds(String cls, FitsChan fc, FrameSet fs) { + String before = fc.toHeader(); + UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, () -> fc.write(fs)); + assertTrue(e.getMessage().endsWith("needs " + cls), e.getMessage()); + assertEquals(before, fc.toHeader()); + } + + /** A 1-D FrameSet whose world axis is the Taylor series to degree 20 of {@code 10 exp(0.01 p)}. */ + private static FrameSet exponential() { + double[] coeffs = new double[21 * 3]; + double term = 10.0; + for (int k = 0; k <= 20; k++) { + coeffs[3 * k] = term; + coeffs[3 * k + 1] = 1; + coeffs[3 * k + 2] = k; + term = term * 0.01 / (k + 1); + } + PolyMap pm = new PolyMap(1, 1, 21, coeffs, 0, new double[0]); + pm.set("IterInverse=1"); + Frame pixel = new Frame(1); + pixel.setDomain("GRID"); + Frame wcs = new Frame(1); + wcs.setDomain("WORLD"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, pm, wcs); + return fs; + } + + @Test + void aLogarithmicAxisIsUnsupported() { + // C's LogAxis finds the logarithm of the axis linear and describes it with the -LOG + // algorithm, whose Mapping holds a MathMap (C probe loglin.c: written as WORL-LOG). + assertNeeds("MathMap", chan(""), exponential()); + } + + @Test + void aNonLinearAxisThatIsNotLogarithmicIsNotWritten() { + // C's LogAxis finds the logarithm of this quadratic not linear, and the axis described as + // linear is too far from linear for MakeIntWorld (C probe loglin.c: the write returns 0). + FitsChan fc = chan(""); + String before = fc.toHeader(); + assertEquals(0, fc.write(quadratic(10, 1, 0.01))); + assertEquals(before, fc.toHeader()); + // With TabOK set, -TAB comes after LogAxis (C probe loglin.c: written as WORL-TAB). + assertNeeds("FitsTable", chan("TabOK=1"), quadratic(10, 1, 0.01)); + } + + @Test + void aNonLinearAxisWithZeroCrvalIsNotWritten() { + // LogAxis returns at once for a zero CRVAL, and with TabOK zero the axis is described as + // linear, which MakeIntWorld rejects (C probe: the write returns 0). + FitsChan fc = chan(""); + String before = fc.toHeader(); + assertEquals(0, fc.write(quadratic(-25, 0, 0.01))); + assertEquals(before, fc.toHeader()); + } + + @Test + void aTableWithTabOkIsUnsupported() { + // C probe tab_zero_crval: TabOK=1 and a non-linear axis whose CRVAL is zero, written as + // WORL-TAB; IsMapTab1D samples the axis and stores it in a FitsTable, reached before any + // LutMap. + assertNeeds("FitsTable", chan("TabOK=1"), quadratic(-25, 0, 0.01)); + // C probe tab_force: ForceTab describes even a linear axis with -TAB. + Frame pixel = new Frame(1); + Frame wcs = new Frame(1); + wcs.setDomain("WORLD"); + FrameSet linear = new FrameSet(pixel); + linear.addFrame(FrameSet.AST__BASE, new ShiftMap(new double[] {5}), wcs); + assertNeeds("FitsTable", chan("TabOK=1,ForceTab=1"), linear); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/ScalePolyInputsTest.java b/src/test/java/uk/ac/starlink/ast/ScalePolyInputsTest.java new file mode 100644 index 0000000..d6d7114 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/ScalePolyInputsTest.java @@ -0,0 +1,96 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code mappings/helpers/scale_poly_inputs.rs} (C {@code + * ScalePolyInputs}, fitschan.c). The expected coefficients were captured from C by the Rust + * repository's {@code tools/oracle_fixtures/scale_poly_inputs.c}; C gives them in the order + * {@code astPolyCoeffs} returns them, which is the order compared here. + */ +class ScalePolyInputsTest { + + /** {@code y0 = x0 + 0.001*x0*x1}, {@code y1 = x1 + 0.002*x0^2}, with no inverse. */ + private static PolyMap sipShape() { + return new PolyMap(2, 2, 4, new double[] {1.0, 1, 1, 0, 0.001, 1, 1, 1, 1.0, 2, 0, 1, 0.002, 2, 2, 0}, 0, null); + } + + /** C's SCALE_POLY_INPUTS_SIP_UNIFORM fixture: scales (2, 2). */ + @Test + void sipUniformScaling() { + PolyMap result = ScalePolyInputs.scalePolyInputs(sipShape(), new double[] {2.0, 2.0}); + assertArrayEquals( + new double[] {2.0, 1, 1, 0, 0.004, 1, 1, 1, 2.0, 2, 0, 1, 0.008, 2, 2, 0}, result.polyCoeffs(true)); + } + + /** C's SCALE_POLY_INPUTS_SIP_NONUNIFORM fixture: scales (3, 5). */ + @Test + void sipNonuniformScaling() { + PolyMap result = ScalePolyInputs.scalePolyInputs(sipShape(), new double[] {3.0, 5.0}); + assertArrayEquals( + new double[] {3.0, 1, 1, 0, 0.015, 1, 1, 1, 5.0, 2, 0, 1, 0.018000000000000002, 2, 2, 0}, + result.polyCoeffs(true)); + } + + /** + * C's SCALE_POLY_INPUTS_3D_MIXED fixture: scales (2, 3, 5) on a 3-input PolyMap. C's fixture + * records only the first two powers of each term; the third is the one supplied. + */ + @Test + void threeDMixed() { + PolyMap pm = new PolyMap(3, 1, 3, new double[] {2.0, 1, 1, 0, 0, 3.0, 1, 0, 2, 1, 7.0, 1, 1, 1, 1}, 0, null); + PolyMap result = ScalePolyInputs.scalePolyInputs(pm, new double[] {2.0, 3.0, 5.0}); + assertArrayEquals( + new double[] {4.0, 1, 1, 0, 0, 135.0, 1, 0, 2, 1, 210.0, 1, 1, 1, 1}, result.polyCoeffs(true)); + } + + /** A zero scale factor is an internal programming error in C, which reports AST__INTER. */ + @Test + void zeroScaleIsAnInternalError() { + PolyMap pm = new PolyMap(2, 2, 2, new double[] {1.0, 1, 1, 0, 1.0, 2, 0, 1}, 0, null); + AstException e = + assertThrows(AstException.class, () -> ScalePolyInputs.scalePolyInputs(pm, new double[] {0.0, 1.0})); + assertEquals(AstException.AST__INTER, e.getStatus()); + assertTrue(e.getMessage().contains("Scale factor for input 0 is zero or bad"), e.getMessage()); + } + + /** The IterInverse, NiterInverse and TolInverse values set on the PolyMap are copied. */ + @Test + void iterInverseAttributesArePropagated() { + PolyMap pm = sipShape(); + pm.setIterInverse(true); + pm.setNiterInverse(7); + pm.setTolInverse(1.0e-9); + PolyMap result = ScalePolyInputs.scalePolyInputs(pm, new double[] {2.0, 2.0}); + assertTrue(result.testIterInverse()); + assertTrue(result.getIterInverse()); + assertEquals(7, result.getNiterInverse()); + assertEquals(1.0e-9, result.getTolInverse()); + } + + /** + * An inverted PolyMap is rebuilt uninverted and then inverted, and the coefficients of an + * explicit inverse are divided by the scale of the input they give, as C's {@code + * ScalePolyInputs} does. + */ + @Test + void invertedPolyMapKeepsItsOrientation() { + PolyMap pm = new PolyMap( + 2, 2, 2, new double[] {2.0, 1, 1, 0, 3.0, 2, 0, 1}, 2, new double[] {0.5, 1, 1, 0, 1.0 / 3.0, 2, 0, 1}); + pm.invert(); + PolyMap result = ScalePolyInputs.scalePolyInputs(pm, new double[] {4.0, 8.0}); + assertTrue(result.getInvert()); + // The forward transformation of the inverted PolyMap: its original inverse, scaled by the + // powers of the scales. + assertArrayEquals(new double[] {0.5 * 4.0, 1, 1, 0, 1.0 / 3.0 * 8.0, 2, 0, 1}, result.polyCoeffs(true)); + // Its inverse: the original forward coefficients, times the reciprocal of the scale of the + // output each gives. + assertArrayEquals( + new double[] {2.0 * (1.0 / 4.0), 1, 1, 0, 3.0 * (1.0 / 8.0), 2, 0, 1}, result.polyCoeffs(false)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SkyPoleOracleTest.java b/src/test/java/uk/ac/starlink/ast/SkyPoleOracleTest.java index 272402b..f374e85 100644 --- a/src/test/java/uk/ac/starlink/ast/SkyPoleOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/SkyPoleOracleTest.java @@ -3,10 +3,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import org.junit.jupiter.api.Test; import uk.ac.starlink.ast.testsupport.CValues; import uk.ac.starlink.ast.testsupport.ProbeData; @@ -17,8 +19,9 @@ * tools/oracle_fixtures/sky_pole_probe.c}), each read and written again by C with the FITS-WCS * encoding. * - *

{@code sky_pole_matches_the_c_library} compares the LONPOLE and LATPOLE C writes, and needs - * {@code FitsChan.write}, which is out of scope; it is listed in {@code deferred/rust-tests.txt}. + *

{@code sky_pole_matches_the_c_library} compares the LONPOLE and LATPOLE C writes: a + * projection wcsmap.c {@code IsZenithal} counts as zenithal writes only the pole its WcsMap was + * given, and any other has the pole worked out from its Mappings (fitschan.c {@code SkyPole}). */ class SkyPoleOracleTest { @@ -70,4 +73,55 @@ void refusedCasesAreIllConditioned() { } assertNotEquals(0, refused, "C refuses some cases"); } + + /** + * The LONPOLE and LATPOLE written for a case, each null if not written; null if the header + * is not read or the FrameSet not written. + */ + private static Double[] written(String proj, String extra) { + FitsChan fc = new FitsChan(); + fc.setEncoding("FITS-WCS"); + for (String card : header(proj, extra)) { + fc.putFits(card, false); + } + fc.clear("Card"); + AstObject obj; + try { + obj = fc.read(); + } catch (AstException e) { + return null; + } + if (obj == null) { + return null; + } + FitsChan out = new FitsChan(); + out.setEncoding("FITS-WCS"); + if (out.write(obj) != 1) { + return null; + } + return new Double[] {out.getFitsF("LONPOLE"), out.getFitsF("LATPOLE")}; + } + + private static Double optional(JsonNode n) { + return n.isNull() ? null : ProbeData.toDouble(n); + } + + @Test + void skyPoleMatchesTheCLibrary() { + List failures = new ArrayList<>(); + for (JsonNode c : ProbeData.load("sky_pole").get("CASES")) { + String name = c.get(0).asText(); + Double lonpole = optional(c.get(3)); + Double latpole = optional(c.get(4)); + boolean ok = c.get(5).asBoolean(); + Double[] got = written(c.get(1).asText(), c.get(2).asText()); + boolean matches = + got == null ? !ok : ok && Objects.equals(got[0], lonpole) && Objects.equals(got[1], latpole); + if (!matches) { + failures.add(name + ": " + (got == null ? "not written" : got[0] + " " + got[1]) + ", C gives LONPOLE " + + lonpole + " LATPOLE " + latpole + " (ok " + ok + ")"); + } + } + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } } diff --git a/src/test/java/uk/ac/starlink/ast/TranGridOracleTest.java b/src/test/java/uk/ac/starlink/ast/TranGridOracleTest.java index d520eb5..2735f84 100644 --- a/src/test/java/uk/ac/starlink/ast/TranGridOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/TranGridOracleTest.java @@ -2,10 +2,13 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; +import java.util.Collections; import java.util.List; +import java.util.Set; import org.junit.jupiter.api.Test; import uk.ac.starlink.ast.testsupport.CValues; import uk.ac.starlink.ast.testsupport.ProbeData; @@ -16,14 +19,16 @@ * through C's FNV-1a hash of every output, and through a sample of positions so that a mismatch * shows where it is. The grids cover the linear-fit paths C keeps separate (1-D, 2-D and general), * sections divided by the initial scale size, grids large enough to be transformed in blocks, and - * the inverse transformation. The Mappings here do only arithmetic, which Java and C carry out - * alike, so every value must equal C's. + * the inverse transformation. The Mappings here but {@code tan} do only arithmetic, which Java and + * C carry out alike, so every value must equal C's. * - *

{@code grids_match_c} runs the grids of the Mappings in the first phase. The grids of the - * FrameSet of a TAN header ({@code tan}) are not run: the header has a {@code CROTA1} card, which - * C's FitsChan guesses to be FITS-AIPS (fitschan.c:12880), an encoding whose read is out of scope; - * the MathMap grids ({@code cubic}) are outside the first phase. In {@code grid_errors_match_c}, a - * Mapping with no inverse stands in for the MathMap whose inverse is undefined. {@code + *

{@code grids_match_c} runs the grids of the Mappings in the first phase, and those of the + * FrameSet of a TAN header with a {@code CROTA1} card ({@code tan}), which the FitsChan guesses to + * be FITS-AIPS. The {@code tan} grids hold values that java.lang.Math's elementary functions give + * one unit in the last place away from C's libm, so they are compared as {@link #RUNTIME_MATH} + * says. The MathMap grids ({@code cubic}) are outside the first phase. In {@code + * grid_errors_match_c}, a Mapping with no inverse stands in for the MathMap whose inverse is + * undefined. {@code * quadratic_fits_match_c} and {@code quadratic_fit_needs_two_inputs} test {@code astQuadApprox}, * which jniast does not have. */ @@ -50,6 +55,7 @@ private static Mapping mapping(String name) { 0, null); case "tan": + return tan(); case "cubic": case "sqrt_part": case "second_bad": @@ -59,6 +65,47 @@ private static Mapping mapping(String name) { } } + /** + * The Mappings whose grids are compared position by position, at the sampled positions only, to + * within {@link #TAN_ATOL}, rather than bit for bit through the hash. + * + *

{@code tan}: traced with the probes {@code tr.c}, {@code rep.c} and {@code tg.c} beside the + * phase 3 task 8 report. Followed point by point through the components of the simplified + * Mapping, 472 of the 682 pixels of {@code tan_small} differ from C at some component (451 in + * the final output). At each of them the first component whose result differs + * (the inverse TAN WcsMap at 132, the inverse SphMap at 184, the forward SphMap at 156) has the + * same input bits in Java and C; replaying its arithmetic gives each side's result bit for bit, + * every argument of {@code atan2}, {@code sin} and {@code cos} is the same, and only their results + * differ, each by one unit in the last place (atan2 308 times, sin 169, cos 31). For pixel (-1, 7) + * {@code atan2(57.29577951308232, 0.024698178070456944)} is 0x3ff9203753454e2d in libm and + * 0x3ff9203753454e2c in java.lang.Math, the exact value lying 0.49984 units from the first. One + * unit in a native latitude near pi/2 is 2.2E-16 radians, which the rotation to celestial + * coordinates carries into outputs of about 4E-4 radians: the largest difference over all five + * grids, the linear-fit grids included, is 2.2194E-16 radians (relative 5.2E-13). + */ + private static final Set RUNTIME_MATH = Collections.singleton("tan"); + + /** The absolute tolerance of a {@link #RUNTIME_MATH} grid: one unit in the last place of pi/2 radians. */ + private static final double TAN_ATOL = Math.ulp(Math.PI / 2); + + /** + * The FrameSet the probe reads from a TAN header with a {@code CROTA1} card, which the FitsChan + * guesses to be FITS-AIPS. + */ + private static Mapping tan() { + return FitsHeaders.readFrameSet(FitsHeaders.chan( + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRPIX1 = 20", + "CRPIX2 = 20", + "CRVAL1 = 0.0", + "CRVAL2 = 0.0", + "CROTA1 = 30.0", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "NAXIS = 2")); + } + /** The 3-D CmpMap of {@code testtrangrid.c}. */ private static Mapping cmp3() { CmpMap c3 = new CmpMap( @@ -125,11 +172,20 @@ void gridsMatchC() { for (int i = 0; i < want.length; i++) { want[i] = ProbeData.toDouble(sample.get(i)); } - CValues.assertCValues(gotArr, want, name + ": sampled positions"); - assertEquals(wantHash, hash(out), name + ": every position"); + if (RUNTIME_MATH.contains(c.get(1).asText())) { + assertEquals(want.length, gotArr.length, name + ": sampled positions"); + for (int i = 0; i < want.length; i++) { + assertTrue( + Math.abs(gotArr[i] - want[i]) <= TAN_ATOL, + name + ": sampled value " + i + " is " + gotArr[i] + ", C gives " + want[i]); + } + } else { + CValues.assertCValues(gotArr, want, name + ": sampled positions"); + assertEquals(wantHash, hash(out), name + ": every position"); + } ran++; } - assertEquals(14, ran, "grids run"); + assertEquals(19, ran, "grids run"); } @Test diff --git a/src/test/java/uk/ac/starlink/ast/TranGridTest.java b/src/test/java/uk/ac/starlink/ast/TranGridTest.java index b72f82f..560b010 100644 --- a/src/test/java/uk/ac/starlink/ast/TranGridTest.java +++ b/src/test/java/uk/ac/starlink/ast/TranGridTest.java @@ -15,7 +15,7 @@ * *

{@code tranmap} needs a TranMap and {@code nonlinear_mathmap_1d} a MathMap, which are outside * the first phase. {@code fits_wcs_pixel_to_sky} reads a header with a {@code CROTA1} card, which - * C's FitsChan guesses to be FITS-AIPS (fitschan.c:12880), an encoding whose read is out of scope. + * C's FitsChan guesses to be FITS-AIPS (fitschan.c:12880). */ class TranGridTest { @@ -122,6 +122,21 @@ void cmpmap3d() { assertGridsRoundTrip(new CmpMap(c3, c4, true), 6, 0.5); } + @Test + void fitsWcsPixelToSky() { + FitsChan fc = FitsHeaders.chan( + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CRPIX1 = 20", + "CRPIX2 = 20", + "CRVAL1 = 0.0", + "CRVAL2 = 0.0", + "CROTA1 = 30.0", + "CDELT1 = -0.001", + "CDELT2 = 0.001"); + assertGridsRoundTrip(FitsHeaders.readFrameSet(fc), 8, 0.0001); + } + /** The results hold one value per grid position for each output, the first axis varying fastest. */ @Test void gridRoundTripUsesPointset() { diff --git a/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java b/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java index 943f76a..f7165ee 100644 --- a/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java @@ -66,10 +66,6 @@ * that are not ported. Any other read that gives no FrameSet, or throws {@code AstException}, is a * failure the gate reports unless a measured cause is written for it by hand. * - *

{@code loads_head_frameset_with_frames} and {@code skyframe_longitude_is_cyclic_pixel_is_not} - * read {@code wcsconv/inputs/galactic-tan.head} rather than Rust's {@code cobe.head}, which is - * guessed to be FITS-AIPS, an encoding whose read is out of scope. - * *

Single rows may be excused by {@code deferred/oracle-rows.txt}, one line per section, {@code * | }, for rows that differ from C only because * C's oracle was computed with a multiply and an add fused (BAD on one side and finite on the @@ -1309,12 +1305,8 @@ void loadsNativeMapping() { assertNotEquals("FrameSet", l.map.astClass(), "a bare Mapping has no Frame"); } - /** - * A celestial header the FitsChan reads as FITS-WCS, used instead of Rust's {@code - * wcsconv/inputs/cobe.head}, which the FitsChan guesses to be FITS-AIPS, an encoding whose read - * is out of scope. - */ - private static final String CELESTIAL_HEAD = "wcsconv/inputs/galactic-tan.head"; + /** A celestial header, which the FitsChan guesses to be FITS-AIPS. */ + private static final String CELESTIAL_HEAD = "wcsconv/inputs/cobe.head"; /** * A {@code .head} fixture reads as a FrameSet, whose base-to-current Mapping is transformed and @@ -1578,12 +1570,12 @@ void skyframeLongitudeIsCyclicPixelIsNot() { assertNull(l.failure); boolean[] fwd = angularFlags( l, - OracleFile.parseText(TOL_LINE + "[galactic-tan.head nin=2 nout=2 dir=forward]\n", "test") + OracleFile.parseText(TOL_LINE + "[cobe.head nin=2 nout=2 dir=forward]\n", "test") .get(0)); assertTrue(fwd[0] || fwd[1], "at least one axis cyclic (sky longitude)"); boolean[] inv = angularFlags( l, - OracleFile.parseText(TOL_LINE + "[galactic-tan.head nin=2 nout=2 dir=inverse]\n", "test") + OracleFile.parseText(TOL_LINE + "[cobe.head nin=2 nout=2 dir=inverse]\n", "test") .get(0)); assertFalse(inv[0] || inv[1], "pixel axes are not cyclic"); } diff --git a/src/test/java/uk/ac/starlink/ast/WcsconvTest.java b/src/test/java/uk/ac/starlink/ast/WcsconvTest.java index eddd26e..cae22ca 100644 --- a/src/test/java/uk/ac/starlink/ast/WcsconvTest.java +++ b/src/test/java/uk/ac/starlink/ast/WcsconvTest.java @@ -1,6 +1,5 @@ package uk.ac.starlink.ast; -import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; @@ -26,27 +25,23 @@ * -Dast.writeDeferred=true} to rewrite the list from what the rows give. * *

    - *
  • A row whose output is written with a FITS encoding or DSS needs {@code FitsChan.write} and - * cannot run at all; there are {@value #WRITE_ROWS} of them, each listed as {@value #WRITE}. - *
  • A {@code native} row's output is the cards {@code FitsChan.write} gives with the NATIVE - * encoding, so no {@code native} row can be compared with C's output. Its input is still read - * as C reads it: a read that stops at an out-of-scope class or encoding gives that reason - * ({@code needs } or {@code encoding }), and a read that fails otherwise fails the - * test, since C reads every input. A row whose read succeeds is listed as {@value #WRITE}. - * Reading C's output back instead does not give C's Object: the cards hold numbers rounded to - * FitsDigits (the {@code timj} Epoch is 2002.3822 in them, 2002.3821786502001 in the Object). - *
  • An {@code ast} row's output is the Object's native text, compared with C's as the Rust test - * compares it (numbers to 4 ULP, or to {@code astEQUAL} for an {@code astequal} row). + *
  • A row written with a FITS encoding (any encoding but {@code ast}) has as output the cards + * {@code FitsChan.write} gives with that encoding, written as {@code wcsconverter.c} writes them: to the FitsChan + * the input was read from (or, if the input was read as a native dump, to a new FitsChan + * with the row's attributes), from its first card, the cards then listed from the first by + * {@code astFindFits} with the template {@code %f}. A write that stops at an out-of-scope + * class gives that reason ({@code needs }). + *
  • An {@code ast} row's output is the Object's native text. *
+ * + *

Either output is compared with C's as the Rust test compares it (numbers to 4 ULP, or to + * {@code astEQUAL} for an {@code astequal} row). Before that the input is read as C reads it: a + * read that stops at an out-of-scope class or encoding gives that reason ({@code needs } or + * {@code encoding }), and a read that fails otherwise fails the test, since C reads every + * input. */ class WcsconvTest { - /** The reason of a row whose output needs {@code FitsChan.write}. */ - static final String WRITE = "out-of-scope method FitsChan.write"; - - /** The number of rows whose output is written with a FITS encoding or DSS. */ - static final int WRITE_ROWS = 85; - /** One row of the manifest. */ private static final class Row { final String name; @@ -78,10 +73,6 @@ private static final class Row { throw new IllegalArgumentException("wcsconv/cases.txt: unknown compare mode " + mode); } } - - boolean needsWrite() { - return !"native".equalsIgnoreCase(encoding) && !"ast".equalsIgnoreCase(encoding); - } } /** The rows of {@code wcsconv/cases.txt}, fields separated by '|'. */ @@ -107,15 +98,26 @@ private static List manifest() { return rows; } + /** The Object read from a row's input, and the FitsChan it was read from, if any. */ + private static final class Input { + final AstObject obj; + final FitsChan fc; + + Input(AstObject obj, FitsChan fc) { + this.obj = obj; + this.fc = fc; + } + } + /** * The Object {@code wcsconverter.c} reads from the input of {@code row}: a FITS header through a * FitsChan with the row's attributes set first and CDMatrix set to its value, or, if that gives * nothing, the file read as a native dump. */ - private static AstObject readInput(Row row) { + private static Input readInput(Row row) { String text = Fixtures.read(row.input); if (row.input.endsWith(".ast")) { - return ChannelText.read(text); + return new Input(ChannelText.read(text), null); } FitsChan fc = new FitsChan(); if (!row.attrs.isEmpty()) { @@ -129,7 +131,38 @@ private static AstObject readInput(Row row) { } fc.clear("Card"); AstObject obj = fc.read(); - return obj != null ? obj : ChannelText.read(text); + return obj != null ? new Input(obj, fc) : new Input(ChannelText.read(text), null); + } + + /** + * The cards {@code wcsconverter.c} writes for a row written with a FITS encoding: the + * Object written with the row's encoding from the first card of the FitsChan it was read from, + * or of a new FitsChan with the row's attributes, and then every card from the first, as {@code + * astFindFits} with the template {@code %f} gives them, one per line. + * + * @throws AssertionError if the write fails, since C's succeeds + * @throws UnsupportedOperationException if the write needs a class this library lacks + */ + private static String writtenCards(Row row, Input in) { + FitsChan fc = in.fc; + if (fc == null) { + fc = new FitsChan(); + if (!row.attrs.isEmpty()) { + fc.set(row.attrs); + } + } + fc.setEncoding(row.encoding); + fc.clear("Card"); + if (fc.write(in.obj) != 1) { + throw new AssertionError("C writes the Object read from " + row.input + ", but here the write fails"); + } + fc.clear("Card"); + StringBuilder out = new StringBuilder(); + String card; + while ((card = fc.findFits("%f", true)) != null) { + out.append(card).append('\n'); + } + return out.toString(); } /** @@ -158,17 +191,13 @@ private static boolean equivalent(Row row, String got, String want) { /** * What {@code row} gives: null if its output matches C's, otherwise the reason it cannot. * - * @throws AssertionError if the read fails where C's succeeds, or an {@code ast} row's output + * @throws AssertionError if the read or the write fails where C's succeeds, or the output * differs from C's */ private static String outcome(Row row) { - boolean ast = "ast".equalsIgnoreCase(row.encoding); - if (row.needsWrite() || (!ast && row.input.endsWith(".ast"))) { - return WRITE; - } - AstObject obj; + Input in; try { - obj = readInput(row); + in = readInput(row); } catch (UnsupportedOperationException e) { return FitsHeaders.outOfScope(e); } catch (AstException e) { @@ -178,10 +207,12 @@ private static String outcome(Row row) { } throw new AssertionError("C reads " + row.input + ", but here the read fails: " + e.getMessage(), e); } - if (!ast) { - return WRITE; + String got; + try { + got = "ast".equalsIgnoreCase(row.encoding) ? ChannelText.dump(in.obj) : writtenCards(row, in); + } catch (UnsupportedOperationException e) { + return FitsHeaders.outOfScope(e); } - String got = ChannelText.dump(obj); String want = Fixtures.read(row.expected); if (!equivalent(row, got, want)) { throw new AssertionError("the texts differ:\n--- Java\n" + got + "--- C\n" + want); @@ -255,17 +286,4 @@ void listedRowsStillFail() { } assertTrue(stale.isEmpty(), String.join("\n", stale)); } - - @Test - void writeRowsCannotRunAndArePinned() { - Map listed = Deferred.load("wcsconv"); - int n = 0; - for (Row row : manifest()) { - if (row.needsWrite()) { - n++; - assertEquals(WRITE, listed.get(row.name), row.name); - } - } - assertEquals(WRITE_ROWS, n, "rows whose output needs FitsChan.write"); - } } diff --git a/src/test/java/uk/ac/starlink/ast/testsupport/CValues.java b/src/test/java/uk/ac/starlink/ast/testsupport/CValues.java index 6ed5d1a..22193b1 100644 --- a/src/test/java/uk/ac/starlink/ast/testsupport/CValues.java +++ b/src/test/java/uk/ac/starlink/ast/testsupport/CValues.java @@ -166,6 +166,16 @@ public static boolean nativeStringsEquivalent(String got, String want, long maxU return linesMatch(got, want, (a, b) -> ulpClose(a, b, maxUlps)); } + /** {@link #nativeStringsEquivalent} with {@link #withinLibmRounding} as the tolerance on numbers. */ + public static boolean nativeStringsWithinLibmRounding(String got, String want) { + return linesMatch(got, want, CValues::withinLibmRounding); + } + + /** {@link #nativeStringsEquivalent} with an absolute tolerance {@code atol} on numbers. */ + public static boolean nativeStringsWithin(String got, String want, double atol) { + return linesMatch(got, want, (a, b) -> Math.abs(a - b) <= atol); + } + /** {@link #nativeStringsEquivalent} with C's {@code astEQUAL} tolerance on numbers. */ public static boolean nativeStringsAstEqual(String got, String want) { return linesMatch(got, want, CValues::astEqualClose); diff --git a/src/test/resources/deferred/headers.txt b/src/test/resources/deferred/headers.txt index b7b642d..2dc5d98 100644 --- a/src/test/resources/deferred/headers.txt +++ b/src/test/resources/deferred/headers.txt @@ -1,14 +1,11 @@ # Fixtures of fixtures/oracle/headers.oracle whose sections do not all match C: # | # Rewritten by TransformOracleTest with -Dast.writeDeferred=true. -programs/joye_car_headers/CAR_model.head | encoding FITS-AIPS -programs/joye_car_headers/cmap_3years_GP_D2.head | encoding FITS-AIPS wcsconv/inputs/alt-spectral.head | needs SpecFrame wcsconv/inputs/awav-a2f.head | needs SpecFrame wcsconv/inputs/axes-swap.head | needs SpecFrame wcsconv/inputs/beta-frq.head | needs SpecFrame wcsconv/inputs/cd-cross.head | needs SpecFrame -wcsconv/inputs/cd-old.head | encoding FITS-IRAF wcsconv/inputs/class-ait.head | needs SpecFrame wcsconv/inputs/class-arc.head | needs SpecFrame wcsconv/inputs/class-gal.head | needs SpecFrame @@ -19,44 +16,29 @@ wcsconv/inputs/class-sin.head | needs SpecFrame wcsconv/inputs/class-spec-hel.head | encoding FITS-CLASS wcsconv/inputs/class-spec.head | encoding FITS-CLASS wcsconv/inputs/class-write.head | encoding FITS-CLASS -wcsconv/inputs/cobe.head | encoding FITS-AIPS -wcsconv/inputs/crota-3d.head | encoding FITS-AIPS +wcsconv/inputs/crota-3d.head | needs SpecFrame wcsconv/inputs/cube-reorder.head | needs SpecFrame wcsconv/inputs/degen-wcsaxes.head | needs SpecFrame wcsconv/inputs/ener-vel.head | needs SpecFrame -wcsconv/inputs/fits-pc-alt.head | encoding FITS-PC -wcsconv/inputs/fits-pc-altgal.head | encoding FITS-PC -wcsconv/inputs/fits-pc-full.head | encoding FITS-PC -wcsconv/inputs/fits-pc-gal.head | encoding FITS-PC -wcsconv/inputs/fits-pc-unit.head | encoding FITS-PC +wcsconv/inputs/fits-pc-alt.head | needs SpecFrame +wcsconv/inputs/fits-pc-unit.head | needs SpecFrame wcsconv/inputs/freq-f2w.head | needs SpecFrame wcsconv/inputs/freq-ghz-bary.head | needs SpecFrame wcsconv/inputs/freq-log.head | needs SpecFrame wcsconv/inputs/freq-pixel3d.head | needs SpecFrame wcsconv/inputs/freq-wav.head | needs SpecFrame wcsconv/inputs/grism.head | needs SpecFrame -wcsconv/inputs/iraf-longpole.head | encoding FITS-IRAF wcsconv/inputs/multi-wcs-spec.head | needs SpecFrame -wcsconv/inputs/origin.head | encoding FITS-PC -wcsconv/inputs/pc-sparse.head | encoding FITS-PC wcsconv/inputs/polco.head | needs MathMap wcsconv/inputs/polco2.head | needs MathMap -wcsconv/inputs/projp-nopv0.head | encoding FITS-IRAF -wcsconv/inputs/projp-pv.head | encoding FITS-IRAF -wcsconv/inputs/projp-pv0only.head | encoding FITS-IRAF -wcsconv/inputs/projp.head | encoding FITS-IRAF -wcsconv/inputs/restfreq-ghz.head | encoding FITS-AIPS -wcsconv/inputs/restfreq-mhz.head | encoding FITS-AIPS -wcsconv/inputs/scp.head | encoding FITS-PC -wcsconv/inputs/serpens.head | encoding FITS-IRAF +wcsconv/inputs/restfreq-ghz.head | needs SpecFrame +wcsconv/inputs/restfreq-mhz.head | needs SpecFrame wcsconv/inputs/sip-3d-swap.head | needs SpecFrame wcsconv/inputs/sip-3d.head | needs SpecFrame wcsconv/inputs/skyspec3d-class.head | needs SpecFrame wcsconv/inputs/skyspec3d.head | needs SpecFrame wcsconv/inputs/ssysobs.head | needs SpecFrame -wcsconv/inputs/tnx-cheb.head | encoding FITS-IRAF -wcsconv/inputs/tnx.head | encoding FITS-IRAF -wcsconv/inputs/velo-aips.head | encoding FITS-AIPS +wcsconv/inputs/velo-aips.head | needs SpecFrame wcsconv/inputs/velo-vel.head | needs SpecFrame wcsconv/inputs/vopt-f2w.head | needs SpecFrame wcsconv/inputs/vopt-geo.head | needs SpecFrame @@ -70,4 +52,3 @@ wcsconv/inputs/wave-w2f.head | needs SpecFrame wcsconv/inputs/wavn-frq.head | needs SpecFrame wcsconv/inputs/zero-cdelt.head | needs SpecFrame wcsconv/inputs/zopt-frq.head | needs SpecFrame -wcsconv/inputs/zpx.head | encoding FITS-IRAF diff --git a/src/test/resources/deferred/rust-tests.txt b/src/test/resources/deferred/rust-tests.txt index 108f987..0fea2e2 100644 --- a/src/test/resources/deferred/rust-tests.txt +++ b/src/test/resources/deferred/rust-tests.txt @@ -154,7 +154,6 @@ tests/test_equal_oracle.rs::equality_matches_the_c_library | astEqual (out-of-sc tests/test_equal_oracle.rs::wcsmap_equality_is_symmetric_where_c_checks_it | astEqual (out-of-scope method) tests/test_trangrid.rs::tranmap | TranMap (out of scope) tests/test_trangrid.rs::nonlinear_mathmap_1d | MathMap (out of scope) -tests/test_trangrid.rs::fits_wcs_pixel_to_sky | out-of-scope method FitsChan.read of the FITS-AIPS encoding tests/test_tran_grid_oracle.rs::quadratic_fits_match_c | astQuadApprox (out-of-scope method) tests/test_tran_grid_oracle.rs::quadratic_fit_needs_two_inputs | astQuadApprox (out-of-scope method) tests/test_map_split.rs::normmap_split_picks_axes | NormMap (out of scope) @@ -276,7 +275,6 @@ tests/test_skyframe.rs::skyframe_is_send | Rust-only API (Send) tests/test_skyframe.rs::debug_formatting | Rust-only API (Debug formatting) tests/test_skyframe.rs::serialise_skyframe_not_a_mapping | Rust-only API (AnyObject::as_mapping; in AST every Frame is a Mapping) tests/test_sky_convert.rs::fk_licences_name_existing_cases | hardware SIMD -tests/test_sky_pole_oracle.rs::sky_pole_matches_the_c_library | out-of-scope method FitsChan.write tests/test_timeframe.rs::test_equal | astEqual (out-of-scope method) tests/test_timeframe.rs::test_map_from_timescale_change | Rust-only API (Frame::map_from) tests/test_spec_use_defs.rs::titles_match_the_c_library | SpecFrame (out of scope) @@ -341,63 +339,42 @@ tests/test_serialisation.rs::round_trip_pointlist | PointList (Region, out of sc tests/test_serialisation.rs::round_trip_cmpregion | CmpRegion and Circle (Region, out of scope) tests/test_serialisation.rs::round_trip_prism | Prism, Circle and Interval (Region, out of scope) tests/test_serialisation.rs::round_trip_negated_circle | Circle (Region, out of scope) -tests/test_fitschan.rs::native_round_trip_zoommap | out-of-scope method FitsChan.write -tests/test_fitschan.rs::native_round_trip_skyframe | out-of-scope method FitsChan.write -tests/test_fitschan.rs::native_rewind_and_reread | out-of-scope method FitsChan.write -tests/test_fitschan.rs::translate_projp_retains_source_cards | out-of-scope method FitsChan.write tests/test_fitschan_native_keyword.rs::polco_loads | MathMap (out of scope) tests/test_fitschan_native_keyword.rs::polco2_loads | MathMap (out of scope) tests/test_fitschan_native_keyword.rs::specflux_loads | SpecFrame (out of scope) -src/fitschan/mod.rs::native_round_trip | out-of-scope method FitsChan.write -src/fitschan/mod.rs::rewrite_after_read_re_emits_wcs_cards | out-of-scope method FitsChan.write -tests/test_fitschan_cursor_oracle.rs::excluded_cases_still_differ | out-of-scope method FitsChan.write -tests/test_fitschan_cursor_oracle.rs::native_full_1_matches_c_but_for_process_counts | out-of-scope method FitsChan.write src/fitschan/wcs_read.rs::decode_1d_spectral | SpecFrame (out of scope) src/fitschan/wcs_read.rs::decode_3d_mixed | SpecFrame (out of scope) src/fitschan/wcs_read.rs::build_pixel_to_world_handles_non_adjacent_celestial_axes | SpecFrame (out of scope) -src/fitschan/spec_trans.rs::rename_keyword_moves_value_and_comment_to_new_name | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::rename_keyword_no_op_when_source_absent | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::rename_keyword_no_op_when_destination_already_present | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::translates_radecsys_to_radesys | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::keeps_radesys_when_both_present | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::translates_longpole_to_lonpole | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::translates_cdjjjiii_to_pc_with_unit_cdelt_for_fits_iraf | out-of-scope method FitsChan.read(FITS-IRAF) -src/fitschan/spec_trans.rs::cdjjjiii_translated_and_consumed_under_fits_iraf | out-of-scope method FitsChan.read(FITS-IRAF) -src/fitschan/spec_trans.rs::translates_projp_to_pv_on_latitude_axis | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::projp_used_when_pv_set_is_incomplete | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::translates_cnxxx_to_alt_letter_form_for_fits_pc | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/spec_trans.rs::cnxxx_zero_cdelt_falls_back_to_crval_or_one | out-of-scope method FitsChan.read(FITS-PC) src/fitschan/spec_trans.rs::translates_class_spectral_crval_and_specsys | out-of-scope method FitsChan.read(FITS-CLASS) -src/fitschan/spec_trans.rs::rename_keyword_handles_float_values | out-of-scope method FitsChan.read(FITS-PC) -src/fitschan/wcs_write/mod.rs::date_str_to_mjd_roundtrip_modern | out-of-scope method FitsChan.write -src/fitschan/wcs_write/mod.rs::date_str_to_mjd_roundtrip_legacy | out-of-scope method FitsChan.write tests/test_fitschan_wcs.rs::read_spectral_header | SpecFrame (out of scope) tests/test_fitschan_wcs.rs::axes_swap_non_adjacent_celestial_axes | SpecFrame (out of scope) tests/test_fitschan_wcs.rs::jan_class_no_naxis_keyword | FITS-CLASS encoding (out-of-scope method FitsChan.read) -tests/test_fitschan_wcs.rs::serpens_dut1_is_seconds | FITS-IRAF encoding (out-of-scope method FitsChan.read) -tests/test_fitschan_wcs.rs::serpens_swapped_axis_transform | FITS-IRAF encoding (out-of-scope method FitsChan.read) tests/test_fitschan_wcs.rs::class_noproj_builds_sfl | FITS-CLASS encoding (out-of-scope method FitsChan.read) tests/test_fitschan_wcs.rs::crota_3d_forward_matches_oracle_inverse_undefined | SpecFrame (out of scope) tests/test_fitschan_read.rs::log_suffix_is_stripped_from_the_domain_and_symbol | MathMap (out of scope) tests/test_fitschan_read.rs::unset_system_still_leaves_system_unset | Rust-only API (SkyFrame::unset_system) tests/test_fitschan_read.rs::dsb_centre_prefers_axref_over_crval | DSBSpecFrame (out of scope) -tests/test_fitschan_astwarn.rs::badpv_warning_names_each_unusable_parameter_in_ascending_order | FITS-IRAF encoding (out-of-scope method FitsChan.read) tests/test_fitschan_astwarn.rs::badctype_warning_names_the_legal_ctype_and_precedes_naxis1 | SpecFrame (out of scope) -tests/test_fitschan_astwarn.rs::strict_write_warning_is_an_error | out-of-scope method FitsChan.write -tests/test_fitschan_astwarn.rs::strict_read_warning_is_an_error | FITS-PC encoding (out-of-scope method FitsChan.read) -tests/test_fitschan_astwarn.rs::strict_sweep_warning_is_an_error | FITS-PC encoding (out-of-scope method FitsChan.read) tests/test_fitschan_time.rs::dtai_set_on_world_frame_for_jcmt | SpecFrame (out of scope) tests/test_fitschan_time.rs::dtai_set_on_world_frame_for_ukirt | SpecFrame (out of scope) tests/test_fitschan_time.rs::dtai_ignored_for_other_telescope | SpecFrame (out of scope) tests/test_fitschan_time.rs::dtai_ignored_when_telescop_absent | SpecFrame (out of scope) tests/test_fitschan_time.rs::dut1_set_on_world_frame_regardless_of_telescop | SpecFrame (out of scope) -tests/test_fitschan_c_inline.rs::sip_header_does_not_write_as_fits_wcs | out-of-scope method FitsChan.write tests/test_fitschan_c_inline.rs::alternate_axes_with_a_bad_set | SpecFrame (out of scope) tests/test_fitschan_c_inline.rs::show_fits_succeeds | astShowFits (out-of-scope method; jniast has no showFits) -tests/test_fitschan_c_inline.rs::azel_writes_as_fits_wcs | out-of-scope method FitsChan.write tests/test_fitschan_c_inline.rs::non_linear_spectral_writes | SpecFrame (out of scope) -tests/test_fitschan_c_inline.rs::supergalactic_writes_slon | out-of-scope method FitsChan.write -tests/test_fitschan_c_inline.rs::sky_systems_through_five_encodings | out-of-scope method FitsChan.write tests/test_fitschan_c_inline.rs::spectral_systems_through_fits_wcs | SpecFrame (out of scope) tests/test_fitschan_c_inline.rs::log_spectral_axis_writes_freq_log | MathMap and SpecFrame (out of scope) -tests/test_fitschan_c_inline.rs::date_and_observatory_write_back | out-of-scope method FitsChan.write +tests/test_fitschan_wcs_write.rs::write_spectral_frameset | SpecFrame (out of scope) +tests/test_fitschan_wcs_write.rs::write_spectral_round_trip | SpecFrame (out of scope) +tests/test_fitschan_wcs_write.rs::grism_interference_order_survives_a_round_trip | SpecFrame and GrismMap (out of scope) +tests/test_fitschan_wcs_write.rs::a_non_linear_grism_axis_writes_a_header_that_reads_back | SpecFrame and GrismMap (out of scope) +tests/test_fitschan_wcs_write.rs::a_splinemap_frameset_writes_nothing_at_a_tight_fits_tol | SplineMap (out of scope) +tests/test_fitschan_wcs_write.rs::the_as_fits_wcs_wrapping_of_a_splinemap_frameset_also_writes_nothing | SplineMap (out of scope) +tests/test_fitschan_wcs_write.rs::alternate_descriptions_are_withheld_when_the_primary_cannot_be_written | SplineMap (out of scope) +tests/test_fitschan_wcs_write.rs::a_splinemap_frameset_writes_a_complete_header_at_the_default_fits_tol | SplineMap (out of scope) +tests/test_fitschan_wcs_write.rs::a_sip_description_is_rejected_when_it_is_not_linear_over_the_image | MathMap (out of scope) +tests/test_fitschan_encodings.rs::read_aips_spectral | SpecFrame (out of scope) +tests/test_fitschan_encodings.rs::read_class_produces_frameset | FITS-CLASS encoding (out-of-scope method FitsChan.read) +tests/test_fitschan_encodings.rs::freq_log_builds_log_mapping | MathMap and SpecFrame (out of scope) +tests/test_fitschan_encodings.rs::grism_builds_grism_mapping | SpecFrame and GrismMap (out of scope) diff --git a/src/test/resources/deferred/wcsconv.txt b/src/test/resources/deferred/wcsconv.txt index 43883e1..9a9dd86 100644 --- a/src/test/resources/deferred/wcsconv.txt +++ b/src/test/resources/deferred/wcsconv.txt @@ -1,197 +1,79 @@ # Rows of fixtures/wcsconv/cases.txt that do not match C: # | # Rewritten by WcsconvTest with -Dast.writeDeferred=true. -timj_fits-wcs | out-of-scope method FitsChan.write -timj_fits-iraf | out-of-scope method FitsChan.write -timj_fits-aips | out-of-scope method FitsChan.write -timj_fits-pc | out-of-scope method FitsChan.write -timj_native | out-of-scope method FitsChan.write -a20070718_fits-wcs | out-of-scope method FitsChan.write -dss_fits-dss_ast | encoding DSS -dss_ast_dss | out-of-scope method FitsChan.write -dss_ast_fits-wcs | out-of-scope method FitsChan.write -degen1_fits-wcs | out-of-scope method FitsChan.write -sip_fits-wcs | out-of-scope method FitsChan.write -sip2_fits-wcs | out-of-scope method FitsChan.write -sip-3d_fits-wcs | out-of-scope method FitsChan.write -sip-3d-swap_fits-wcs | out-of-scope method FitsChan.write -lsst_fits-wcs | out-of-scope method FitsChan.write -lsst2_fits-wcs | out-of-scope method FitsChan.write -longslit_fits-wcs | out-of-scope method FitsChan.write +a20070718_fits-wcs | needs DSBSpecFrame +sip-3d_fits-wcs | needs SpecFrame +sip-3d-swap_fits-wcs | needs SpecFrame +lsst2_fits-wcs | needs SplineMap +longslit_fits-wcs | needs SpecFrame jan_fits-class_ast | encoding FITS-CLASS -aitoff_native | out-of-scope method FitsChan.write -car1_native | out-of-scope method FitsChan.write -car2_native | out-of-scope method FitsChan.write -car3_native | out-of-scope method FitsChan.write -car4_native | out-of-scope method FitsChan.write -car5_native | out-of-scope method FitsChan.write -car6_native | out-of-scope method FitsChan.write -cobe_native | encoding FITS-AIPS -hpx_native | out-of-scope method FitsChan.write -origin_native | encoding FITS-PC polco_native | needs MathMap polco2_native | needs MathMap -scp_native | encoding FITS-PC -serpens_native | encoding FITS-IRAF specflux_native | needs SpecFrame -timeplot_native | out-of-scope method FitsChan.write -tnx_native | encoding FITS-IRAF -tsc_native | out-of-scope method FitsChan.write -zpn_native | out-of-scope method FitsChan.write -zpx_native | encoding FITS-IRAF freq-log_native | needs SpecFrame freq-f2w_native | needs SpecFrame -tan-pv0_native | out-of-scope method FitsChan.write -tnx-cheb_native | encoding FITS-IRAF grism_native | needs SpecFrame -grism_fits-wcs | out-of-scope method FitsChan.write +grism_fits-wcs | needs SpecFrame class-spec_native | encoding FITS-CLASS class-hel_native | encoding FITS-CLASS -multi-wcs_native | out-of-scope method FitsChan.write -multi-wcs_fits-wcs | out-of-scope method FitsChan.write degen-wcsaxes_native | needs SpecFrame wave-w2f_native | needs SpecFrame vrad-v2f_native | needs SpecFrame -tan-polytan_native | out-of-scope method FitsChan.write -sao-tan_native | out-of-scope method FitsChan.write -fits-pc-alt_native | encoding FITS-PC -velo-aips_native | encoding FITS-AIPS +fits-pc-alt_native | needs SpecFrame +velo-aips_native | needs SpecFrame awav-a2f_native | needs SpecFrame -tan-zeropv_native | out-of-scope method FitsChan.write cube-reorder_native | needs SpecFrame -ncp_native | out-of-scope method FitsChan.write velo-vel_native | needs SpecFrame vopt-wav_native | needs SpecFrame zopt-frq_native | needs SpecFrame -cname_native | out-of-scope method FitsChan.write -cname_fits-wcs | out-of-scope method FitsChan.write -skyref_native | out-of-scope method FitsChan.write -fits-pc-unit_native | encoding FITS-PC -gls_native | out-of-scope method FitsChan.write -iraf-longpole_native | encoding FITS-IRAF +fits-pc-unit_native | needs SpecFrame multi-wcs-spec_native | needs SpecFrame -multi-wcs-dup_native | out-of-scope method FitsChan.write -multi-wcs-dup_fits-wcs | out-of-scope method FitsChan.write freq-wav_native | needs SpecFrame wavn-frq_native | needs SpecFrame -mercator_native | out-of-scope method FitsChan.write -gappt_native | out-of-scope method FitsChan.write -gappt_fits-wcs | out-of-scope method FitsChan.write -atf_native | out-of-scope method FitsChan.write -equinox-bj_native | out-of-scope method FitsChan.write -timesys-tdb_native | out-of-scope method FitsChan.write zero-cdelt_native | needs SpecFrame alt-spectral_native | needs SpecFrame -helioecl_native | out-of-scope method FitsChan.write -fits-pc-full_native | encoding FITS-PC -fits-pc-gal_native | encoding FITS-PC -fits-pc-gal_fits-pc | out-of-scope method FitsChan.write -sfl-pc_fits-pc | out-of-scope method FitsChan.write -zpn_fits-pc | out-of-scope method FitsChan.write -projp_native | encoding FITS-IRAF -fk5-noeq_native | out-of-scope method FitsChan.write -timesys-tt_native | out-of-scope method FitsChan.write -skyref-alt_native | out-of-scope method FitsChan.write -axref_native | out-of-scope method FitsChan.write -unknown-cel_native | out-of-scope method FitsChan.write -projp-pv_native | encoding FITS-IRAF -cd-old_native | encoding FITS-IRAF -fk4-noeq_native | out-of-scope method FitsChan.write -unknown-cel2_native | out-of-scope method FitsChan.write -tidy-offsets_native | out-of-scope method FitsChan.write -tidy-pole_native | out-of-scope method FitsChan.write -date-short_native | out-of-scope method FitsChan.write -date-frac_native | out-of-scope method FitsChan.write -equinox-zero_native | out-of-scope method FitsChan.write ssysobs_native | needs SpecFrame ener-vel_native | needs SpecFrame beta-frq_native | needs SpecFrame -sip-alt_native | out-of-scope method FitsChan.write -ukirt-dtai_native | out-of-scope method FitsChan.write -ukirt-dtai_fits-wcs | out-of-scope method FitsChan.write -rfval_native | out-of-scope method FitsChan.write vrad-wav_native | needs SpecFrame -projp-nopv0_native | encoding FITS-IRAF -projp-pv0only_native | encoding FITS-IRAF -restfreq-ghz_native | encoding FITS-AIPS -pc-sparse_native | encoding FITS-PC -restfreq-mhz_native | encoding FITS-AIPS -unknown-spec_native | out-of-scope method FitsChan.write -crota-3d_native | encoding FITS-AIPS +restfreq-ghz_native | needs SpecFrame +restfreq-mhz_native | needs SpecFrame +crota-3d_native | needs SpecFrame axes-swap_native | needs SpecFrame cd-cross_native | needs SpecFrame class-noproj_native | encoding FITS-CLASS -ait-highlatpole_native | out-of-scope method FitsChan.write -timj_fits-aips++ | out-of-scope method FitsChan.write -a20070718_fits-aips | out-of-scope method FitsChan.write -a20070718_fits-aips++ | out-of-scope method FitsChan.write -freq-ghz-bary_fits-aips | out-of-scope method FitsChan.write -freq-ghz-bary_fits-aips++ | out-of-scope method FitsChan.write -vopt-geo_fits-aips | out-of-scope method FitsChan.write -vopt-geo_fits-aips++ | out-of-scope method FitsChan.write -ncp_fits-aips | out-of-scope method FitsChan.write -ncp_fits-aips++ | out-of-scope method FitsChan.write -fk4-aips_fits-aips | out-of-scope method FitsChan.write -fk4-aips_fits-aips++ | out-of-scope method FitsChan.write -sfl-origin_fits-aips | out-of-scope method FitsChan.write -sfl-origin_fits-aips++ | out-of-scope method FitsChan.write -sin-plain_fits-aips | out-of-scope method FitsChan.write -sin-plain_fits-aips++ | out-of-scope method FitsChan.write -tan-rotated_fits-aips | out-of-scope method FitsChan.write -tan-rotated_fits-aips++ | out-of-scope method FitsChan.write -tan-cdmatrix_fits-aips++ | out-of-scope method FitsChan.write -pixel-2d_fits-aips | out-of-scope method FitsChan.write -pixel-2d_fits-aips++ | out-of-scope method FitsChan.write -vrad-lsrd_fits-aips | out-of-scope method FitsChan.write -vrad-lsrd_fits-aips++ | out-of-scope method FitsChan.write -freq-pixel3d_fits-aips | out-of-scope method FitsChan.write -freq-pixel3d_fits-aips++ | out-of-scope method FitsChan.write -pixel-1d_fits-aips | out-of-scope method FitsChan.write -pixel-1d_fits-aips++ | out-of-scope method FitsChan.write -pixel-rotated_fits-aips | out-of-scope method FitsChan.write -pixel-rotated_fits-aips++ | out-of-scope method FitsChan.write -pixel-shear_fits-aips++ | out-of-scope method FitsChan.write -class-write_fits-class | out-of-scope method FitsChan.write -class-gal_fits-class | out-of-scope method FitsChan.write -jan_fits-class-rt | out-of-scope method FitsChan.write +a20070718_fits-aips | needs DSBSpecFrame +a20070718_fits-aips++ | needs DSBSpecFrame +freq-ghz-bary_fits-aips | needs SpecFrame +freq-ghz-bary_fits-aips++ | needs SpecFrame +vopt-geo_fits-aips | needs SpecFrame +vopt-geo_fits-aips++ | needs SpecFrame +vrad-lsrd_fits-aips | needs SpecFrame +vrad-lsrd_fits-aips++ | needs SpecFrame +freq-pixel3d_fits-aips | needs SpecFrame +freq-pixel3d_fits-aips++ | needs SpecFrame +class-write_fits-class | encoding FITS-CLASS +class-gal_fits-class | needs SpecFrame +jan_fits-class-rt | encoding FITS-CLASS class-arc_native | needs SpecFrame -class-arc_fits-class | out-of-scope method FitsChan.write +class-arc_fits-class | needs SpecFrame class-ait_native | needs SpecFrame -class-ait_fits-class | out-of-scope method FitsChan.write +class-ait_fits-class | needs SpecFrame class-sin_native | needs SpecFrame -class-sin_fits-class | out-of-scope method FitsChan.write -class-sfl_fits-class | out-of-scope method FitsChan.write -class-olddate_fits-class | out-of-scope method FitsChan.write -ncp_fits-iraf | out-of-scope method FitsChan.write -fk4-aips_fits-iraf | out-of-scope method FitsChan.write -a20070718_fits-iraf | out-of-scope method FitsChan.write -sfl-origin_fits-iraf | out-of-scope method FitsChan.write +class-sin_fits-class | needs SpecFrame +class-sfl_fits-class | needs SpecFrame +class-olddate_fits-class | needs SpecFrame +a20070718_fits-iraf | needs DSBSpecFrame skyspec3d_native | needs SpecFrame -skyspec3d_fits-wcs | out-of-scope method FitsChan.write -skyspec3d_fits-aips | out-of-scope method FitsChan.write -skyspec3d_fits-aips++ | out-of-scope method FitsChan.write -skyspec3d_fits-iraf | out-of-scope method FitsChan.write -sin-plain_fits-iraf | out-of-scope method FitsChan.write -wave-1d_fits-iraf | out-of-scope method FitsChan.write -skyspec3d_fits-pc | out-of-scope method FitsChan.write +skyspec3d_fits-wcs | needs SpecFrame +skyspec3d_fits-aips | needs SpecFrame +skyspec3d_fits-aips++ | needs SpecFrame +skyspec3d_fits-iraf | needs SpecFrame +wave-1d_fits-iraf | needs SpecFrame +skyspec3d_fits-pc | needs SpecFrame skyspec3d-class_native | needs SpecFrame -skyspec3d-class_fits-class | out-of-scope method FitsChan.write -offset-sky_native | out-of-scope method FitsChan.write -offset-sky_fits-wcs | out-of-scope method FitsChan.write -offset-sky-pole_native | out-of-scope method FitsChan.write -offset-sky-pole_fits-wcs | out-of-scope method FitsChan.write -azel_native | out-of-scope method FitsChan.write -azel_fits-wcs | out-of-scope method FitsChan.write +skyspec3d-class_fits-class | needs SpecFrame vopt-f2w_native | needs SpecFrame -vopt-f2w_fits-wcs | out-of-scope method FitsChan.write +vopt-f2w_fits-wcs | needs SpecFrame wave-f2w_native | needs SpecFrame -wave-f2w_fits-wcs | out-of-scope method FitsChan.write -galactic-tan_fits-aips | out-of-scope method FitsChan.write -galactic-tan_fits-aips++ | out-of-scope method FitsChan.write -galactic-tan_fits-iraf | out-of-scope method FitsChan.write -ecliptic-tan_fits-aips | out-of-scope method FitsChan.write -tan-pv0_fits-wcs | out-of-scope method FitsChan.write -date-z_fits-wcs | out-of-scope method FitsChan.write -fits-pc-altgal_native | encoding FITS-PC -fits-pc-altgal_fits-wcs | out-of-scope method FitsChan.write -offset-sref_native | out-of-scope method FitsChan.write +wave-f2w_fits-wcs | needs SpecFrame diff --git a/src/test/resources/oracle/fitschan_alt_epoch.json b/src/test/resources/oracle/fitschan_alt_epoch.json new file mode 100644 index 0000000..2ebf253 --- /dev/null +++ b/src/test/resources/oracle/fitschan_alt_epoch.json @@ -0,0 +1,8 @@ +{ + "source": "crates/starlink-ast/tests/fitschan_alt_epoch_oracle/cases.rs", + "generator": "tools/oracle_fixtures/fitschan_alt_epoch_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["no_dates","",0.0,0.0,false,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","WCSAXESA= 2 / Number of WCS axes ","CRPIX1A = 50.0 / Reference pixel on axis 1 ","CRPIX2A = 50.0 / Reference pixel on axis 2 ","CRVAL1A = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 30.0 / Value at ref. pixel on axis 2 ","CTYPE1A = 'GLON-TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'GLAT-TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 "]],["read_date","MJD-OBS = 51000.0",0.0,0.0,false,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51000.0 / Modified Julian Date of observation ","DATE-OBS= '06/07/98' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","WCSAXESA= 2 / Number of WCS axes ","CRPIX1A = 50.0 / Reference pixel on axis 1 ","CRPIX2A = 50.0 / Reference pixel on axis 2 ","CRVAL1A = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 30.0 / Value at ref. pixel on axis 2 ","CTYPE1A = 'GLON-TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'GLAT-TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 "]],["alt_differs","MJD-OBS = 51000.0",0.0,55000.0,false,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51000.0 / Modified Julian Date of observation ","DATE-OBS= '06/07/98' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","WCSAXESA= 2 / Number of WCS axes ","CRPIX1A = 50.0 / Reference pixel on axis 1 ","CRPIX2A = 50.0 / Reference pixel on axis 2 ","CRVAL1A = 100.00000095520664 / Value at ref. pixel on axis 1 ","CRVAL2A = 29.9999975206429 / Value at ref. pixel on axis 2 ","CTYPE1A = 'GLON-TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'GLAT-TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 "]],["alt_only","",0.0,55000.0,false,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","WCSAXESA= 2 / Number of WCS axes ","CRPIX1A = 50.0 / Reference pixel on axis 1 ","CRPIX2A = 50.0 / Reference pixel on axis 2 ","CRVAL1A = 100.00000082496021 / Value at ref. pixel on axis 1 ","CRVAL2A = 29.999997858016009 / Value at ref. pixel on axis 2 ","CTYPE1A = 'GLON-TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'GLAT-TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 "]],["primary_only","",52000.0,0.0,false,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000000266603987 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999999777262929 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51999.999257110736 / Modified Julian Date of observation ","DATE-OBS= '2001-03-31T23:58:55.814' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","WCSAXESA= 2 / Number of WCS axes ","CRPIX1A = 50.0 / Reference pixel on axis 1 ","CRPIX2A = 50.0 / Reference pixel on axis 2 ","CRVAL1A = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 30.0 / Value at ref. pixel on axis 2 ","CTYPE1A = 'GLON-TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'GLAT-TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 "]],["both_set","",52000.0,55000.0,false,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000000266603987 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999999777262929 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51999.999257110736 / Modified Julian Date of observation ","DATE-OBS= '2001-03-31T23:58:55.814' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","WCSAXESA= 2 / Number of WCS axes ","CRPIX1A = 50.0 / Reference pixel on axis 1 ","CRPIX2A = 50.0 / Reference pixel on axis 2 ","CRVAL1A = 100.00000082496021 / Value at ref. pixel on axis 1 ","CRVAL2A = 29.999997858016009 / Value at ref. pixel on axis 2 ","CTYPE1A = 'GLON-TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'GLAT-TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 "]],["alt_differs_fails","MJD-OBS = 51000.0",0.0,55000.0,true,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51000.0 / Modified Julian Date of observation ","DATE-OBS= '06/07/98' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox "]],["alt_only_fails","",0.0,55000.0,true,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox "]],["both_set_fails","",52000.0,55000.0,true,1,["NAXIS1 = 100 ","NAXIS2 = 100 ","WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 50.0 / Reference pixel on axis 1 ","CRPIX2 = 50.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000000266603987 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999999777262929 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","MJD-OBS = 51999.999257110736 / Modified Julian Date of observation ","DATE-OBS= '2001-03-31T23:58:55.814' / Date of observation ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox "]]] + } +} diff --git a/src/test/resources/oracle/fitschan_alt_naxes.json b/src/test/resources/oracle/fitschan_alt_naxes.json new file mode 100644 index 0000000..d7dbacd --- /dev/null +++ b/src/test/resources/oracle/fitschan_alt_naxes.json @@ -0,0 +1,8 @@ +{ + "source": "crates/starlink-ast/tests/fitschan_alt_naxes_oracle/cases.rs", + "generator": "tools/oracle_fixtures/fitschan_alt_naxes_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["same",3,3,1,["NAXIS = 3 ","WCSNAME = 'PRI ' / Reference name for the coord. frame ","CRPIX1 = 1.0 / Reference pixel on axis 1 ","CRPIX2 = 1.0 / Reference pixel on axis 2 ","CRPIX3 = 1.0 / Reference pixel on axis 3 ","CRVAL1 = 11.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 12.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 13.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'PRI1 ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'PRI2 ' / Type of co-ordinate on axis 2 ","CTYPE3 = 'PRI3 ' / Type of co-ordinate on axis 3 ","CDELT1 = 1.0 / Pixel size on axis 1 ","CDELT2 = 1.0 / Pixel size on axis 2 ","CDELT3 = 1.0 / Pixel size on axis 3 ","WCSNAMEA= 'ALT ' / Reference name for the coord. frame ","CRPIX1A = 1.0 / Reference pixel on axis 1 ","CRPIX2A = 1.0 / Reference pixel on axis 2 ","CRPIX3A = 1.0 / Reference pixel on axis 3 ","CRVAL1A = 101.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 102.0 / Value at ref. pixel on axis 2 ","CRVAL3A = 103.0 / Value at ref. pixel on axis 3 ","CTYPE1A = 'ALT1 ' / Type of co-ordinate on axis 1 ","CTYPE2A = 'ALT2 ' / Type of co-ordinate on axis 2 ","CTYPE3A = 'ALT3 ' / Type of co-ordinate on axis 3 ","CDELT1A = 1.0 / Pixel size on axis 1 ","CDELT2A = 1.0 / Pixel size on axis 2 ","CDELT3A = 1.0 / Pixel size on axis 3 "]],["alt_fewer",3,2,1,["NAXIS = 3 ","WCSNAME = 'PRI ' / Reference name for the coord. frame ","CRPIX1 = 1.0 / Reference pixel on axis 1 ","CRPIX2 = 1.0 / Reference pixel on axis 2 ","CRPIX3 = 1.0 / Reference pixel on axis 3 ","CRVAL1 = 11.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 12.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 13.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'PRI1 ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'PRI2 ' / Type of co-ordinate on axis 2 ","CTYPE3 = 'PRI3 ' / Type of co-ordinate on axis 3 ","CDELT1 = 1.0 / Pixel size on axis 1 ","CDELT2 = 1.0 / Pixel size on axis 2 ","CDELT3 = 1.0 / Pixel size on axis 3 "]],["alt_one",3,1,1,["NAXIS = 3 ","WCSNAME = 'PRI ' / Reference name for the coord. frame ","CRPIX1 = 1.0 / Reference pixel on axis 1 ","CRPIX2 = 1.0 / Reference pixel on axis 2 ","CRPIX3 = 1.0 / Reference pixel on axis 3 ","CRVAL1 = 11.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 12.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 13.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'PRI1 ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'PRI2 ' / Type of co-ordinate on axis 2 ","CTYPE3 = 'PRI3 ' / Type of co-ordinate on axis 3 ","CDELT1 = 1.0 / Pixel size on axis 1 ","CDELT2 = 1.0 / Pixel size on axis 2 ","CDELT3 = 1.0 / Pixel size on axis 3 "]],["alt_more",3,4,1,["NAXIS = 3 ","WCSNAME = 'PRI ' / Reference name for the coord. frame ","CRPIX1 = 1.0 / Reference pixel on axis 1 ","CRPIX2 = 1.0 / Reference pixel on axis 2 ","CRPIX3 = 1.0 / Reference pixel on axis 3 ","CRVAL1 = 11.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 12.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 13.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'PRI1 ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'PRI2 ' / Type of co-ordinate on axis 2 ","CTYPE3 = 'PRI3 ' / Type of co-ordinate on axis 3 ","CDELT1 = 1.0 / Pixel size on axis 1 ","CDELT2 = 1.0 / Pixel size on axis 2 ","CDELT3 = 1.0 / Pixel size on axis 3 ","WCSAXESA= 4 / Number of WCS axes ","WCSNAMEA= 'ALT ' / Reference name for the coord. frame ","CRPIX1A = 1.0 / Reference pixel on axis 1 ","CRPIX2A = 1.0 / Reference pixel on axis 2 ","CRPIX3A = 1.0 / Reference pixel on axis 3 ","CRPIX4A = 1.0 / Reference pixel on axis 4 ","CRVAL1A = 101.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 102.0 / Value at ref. pixel on axis 2 ","CRVAL3A = 103.0 / Value at ref. pixel on axis 3 ","CRVAL4A = 108.0 / Value at ref. pixel on axis 4 ","CTYPE1A = 'ALT1 ' / Type of co-ordinate on axis 1 ","CTYPE2A = 'ALT2 ' / Type of co-ordinate on axis 2 ","CTYPE3A = 'ALT3 ' / Type of co-ordinate on axis 3 ","CTYPE4A = 'ALT4 ' / Type of co-ordinate on axis 4 ","CDELT1A = 1.0 / Pixel size on axis 1 ","CDELT2A = 1.0 / Pixel size on axis 2 ","CDELT3A = 1.0 / Pixel size on axis 3 ","CDELT4A = 1.0 / Pixel size on axis 4 "]],["primary_fewer",2,3,0,["NAXIS = 3 "]],["primary_more",4,3,1,["NAXIS = 3 ","WCSAXES = 4 / Number of WCS axes ","WCSNAME = 'PRI ' / Reference name for the coord. frame ","CRPIX1 = 1.0 / Reference pixel on axis 1 ","CRPIX2 = 1.0 / Reference pixel on axis 2 ","CRPIX3 = 1.0 / Reference pixel on axis 3 ","CRPIX4 = 1.0 / Reference pixel on axis 4 ","CRVAL1 = 11.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 12.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 13.0 / Value at ref. pixel on axis 3 ","CRVAL4 = 18.0 / Value at ref. pixel on axis 4 ","CTYPE1 = 'PRI1 ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'PRI2 ' / Type of co-ordinate on axis 2 ","CTYPE3 = 'PRI3 ' / Type of co-ordinate on axis 3 ","CTYPE4 = 'PRI4 ' / Type of co-ordinate on axis 4 ","CDELT1 = 1.0 / Pixel size on axis 1 ","CDELT2 = 1.0 / Pixel size on axis 2 ","CDELT3 = 1.0 / Pixel size on axis 3 ","CDELT4 = 1.0 / Pixel size on axis 4 ","WCSNAMEA= 'ALT ' / Reference name for the coord. frame ","CRPIX1A = 1.0 / Reference pixel on axis 1 ","CRPIX2A = 1.0 / Reference pixel on axis 2 ","CRPIX3A = 1.0 / Reference pixel on axis 3 ","CRVAL1A = 101.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 102.0 / Value at ref. pixel on axis 2 ","CRVAL3A = 103.0 / Value at ref. pixel on axis 3 ","CTYPE1A = 'ALT1 ' / Type of co-ordinate on axis 1 ","CTYPE2A = 'ALT2 ' / Type of co-ordinate on axis 2 ","CTYPE3A = 'ALT3 ' / Type of co-ordinate on axis 3 ","CDELT1A = 1.0 / Pixel size on axis 1 ","CDELT2A = 1.0 / Pixel size on axis 2 ","CDELT3A = 1.0 / Pixel size on axis 3 "]]] + } +} diff --git a/src/test/resources/oracle/fitschan_encodings.json b/src/test/resources/oracle/fitschan_encodings.json new file mode 100644 index 0000000..c48e16b --- /dev/null +++ b/src/test/resources/oracle/fitschan_encodings.json @@ -0,0 +1,8 @@ +{ + "source": "crates/starlink-ast/tests/fitschan_encodings_oracle/cases.rs", + "generator": "tools/oracle_fixtures/fitschan_encodings_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["tan_icrs",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'ICRS'","MJD-OBS = 51000","EXTRA = 1"],"",[["FITS-WCS",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'ICRS ' / Reference frame for RA/DEC values ","MJD-OBS = 51000.0 / Modified Julian Date of observation ","DATE-OBS= '06/07/98' / Date of observation ","EXTRA = 1 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","MJD-OBS","DATE-OBS","EXTRA"]],["FITS-PC",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","MJD-OBS = 51000.0 / Modified Julian Date of observation ","RADECSYS= 'ICRS ' / Reference frame for RA/DEC values ","DATE-OBS= '06/07/98' / Date of observation ","EXTRA = 1 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","MJD-OBS","RADECSYS","DATE-OBS","EXTRA"]],["FITS-IRAF",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","MJD-OBS = 51000.0 / Modified Julian Date of observation ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'ICRS ' / Reference frame for RA/DEC values ","DATE-OBS= '06/07/98' / Date of observation ","EXTRA = 1 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","MJD-OBS","CD1_1","CD2_2","RADECSYS","DATE-OBS","EXTRA"]],["FITS-AIPS",0,5,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 51000 ","EXTRA = 1 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","MJD-OBS","EXTRA"]],["FITS-AIPS++",0,5,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 51000 ","EXTRA = 1 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","MJD-OBS","EXTRA"]],["FITS-CLASS",0,5,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 51000 ","EXTRA = 1 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","MJD-OBS","EXTRA"]],["DSS",0,5,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 51000 ","EXTRA = 1 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","MJD-OBS","EXTRA"]]]],["tan_fk5",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0"],"",[["FITS-WCS",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS","DATE-OBS"]],["FITS-PC",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","RADECSYS","MJD-OBS","DATE-OBS"]],["FITS-IRAF",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CD1_1","CD2_2","RADECSYS","DATE-OBS"]],["FITS-AIPS",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CROTA2","EPOCH","DATE-OBS"]],["FITS-AIPS++",1,13,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","EPOCH","DATE-OBS"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX"]],["DSS",1,61,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CNPIX1 = 1.0 / X corner (pixels) ","CNPIX2 = 1.0 / Y corner (pixels) ","PPO1 = 0.0 / Orientation co-efficients ","PPO2 = 0.0 ","PPO3 = 5.5 ","PPO4 = 0.0 ","PPO5 = 0.0 ","PPO6 = 5.5 ","XPIXELSZ= 1.0 / X pixel size (microns) ","YPIXELSZ= 1.0 / Y pixel size (microns) ","PLTRAH = 0.0 / RA at plate centre ","PLTRAM = 39.0 ","PLTRAS = 60.0 ","PLTDECD = 20.0 / DEC at plate centre ","PLTDECM = 0.0 ","PLTDECS = 1.2789769243681803E-11 ","PLTDECSN= '+ ' ","PLTSCALE= 3600.0 / Plate scale (arcsec/mm) ","AMDX1 = 3600.0 / Plate solution x co-efficients ","AMDX2 = 0.0 ","AMDX3 = 0.0 ","AMDX4 = 0.0 ","AMDX5 = 0.0 ","AMDX6 = 0.0 ","AMDX7 = 0.0 ","AMDX8 = 0.0 ","AMDX9 = 0.0 ","AMDX10 = 0.0 ","AMDX11 = 0.0 ","AMDX12 = 0.0 ","AMDX13 = 0.0 ","AMDX14 = 0.0 ","AMDX15 = 0.0 ","AMDX16 = 0.0 ","AMDX17 = 0.0 ","AMDX18 = 0.0 ","AMDX19 = 0.0 ","AMDX20 = 0.0 ","AMDY1 = 3600.0 / Plate solution y co-efficients ","AMDY2 = 0.0 ","AMDY3 = 0.0 ","AMDY4 = 0.0 ","AMDY5 = 0.0 ","AMDY6 = 0.0 ","AMDY7 = 0.0 ","AMDY8 = 0.0 ","AMDY9 = 0.0 ","AMDY10 = 0.0 ","AMDY11 = 0.0 ","AMDY12 = 0.0 ","AMDY13 = 0.0 ","AMDY14 = 0.0 ","AMDY15 = 0.0 ","AMDY16 = 0.0 ","AMDY17 = 0.0 ","AMDY18 = 0.0 ","AMDY19 = 0.0 ","AMDY20 = 0.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CNPIX1","CNPIX2","PPO1","PPO2","PPO3","PPO4","PPO5","PPO6","XPIXELSZ","YPIXELSZ","PLTRAH","PLTRAM","PLTRAS","PLTDECD","PLTDECM","PLTDECS","PLTDECSN","PLTSCALE","AMDX1","AMDX2","AMDX3","AMDX4","AMDX5","AMDX6","AMDX7","AMDX8","AMDX9","AMDX10","AMDX11","AMDX12","AMDX13","AMDX14","AMDX15","AMDX16","AMDX17","AMDX18","AMDX19","AMDX20","AMDY1","AMDY2","AMDY3","AMDY4","AMDY5","AMDY6","AMDY7","AMDY8","AMDY9","AMDY10","AMDY11","AMDY12","AMDY13","AMDY14","AMDY15","AMDY16","AMDY17","AMDY18","AMDY19","AMDY20"]]]],["tan_rotated",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","PC1_1 = 0.8660254037844387","PC1_2 = -0.5","PC2_1 = 0.5","PC2_2 = 0.8660254037844387","RADESYS = 'FK5'","EQUINOX = 2000.0"],"",[["FITS-WCS",1,19,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","PC1_1 = 0.8660254037844386 / Transformation matrix element ","PC1_2 = -0.5 / Transformation matrix element ","PC2_1 = 0.5 / Transformation matrix element ","PC2_2 = 0.86602540378443871 / Transformation matrix element ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","MJD-OBS","DATE-OBS"]],["FITS-PC",1,19,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","PC001001= 0.8660254037844386 ","PC001002= -0.5 ","PC002001= 0.5 ","PC002002= 0.86602540378443871 ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","PC001001","PC001002","PC002001","PC002002","RADECSYS","MJD-OBS","DATE-OBS"]],["FITS-IRAF",1,16,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","CD1_1 = -8.660254037844388E-4 / Transformation matrix element ","CD1_2 = 0.0005 / Transformation matrix element ","CD2_1 = 0.0005 / Transformation matrix element ","CD2_2 = 0.00086602540378443891 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","CD1_1","CD1_2","CD2_1","CD2_2","RADECSYS","DATE-OBS"]],["FITS-AIPS",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = 0.001 / Pixel size ","CDELT2 = -0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CROTA2 = 150.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","CROTA2","EPOCH","DATE-OBS"]],["FITS-AIPS++",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = 0.001 / Pixel size ","CDELT2 = -0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CROTA2 = 150.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","CROTA2","EPOCH","DATE-OBS"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX"]],["DSS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX"]]]],["tan_sheared",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","PC1_1 = 1.0","PC1_2 = 0.3","PC2_1 = 0.0","PC2_2 = 1.0","RADESYS = 'FK5'","EQUINOX = 2000.0"],"",[["FITS-WCS",1,17,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.0010440306508910551 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","PC1_1 = 0.95782628522115132 / Transformation matrix element ","PC1_2 = 0.2873478855663455 / Transformation matrix element ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","MJD-OBS","DATE-OBS"]],["FITS-PC",1,17,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.0010440306508910551 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","PC001001= 0.95782628522115132 ","PC001002= 0.2873478855663455 ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","PC001001","PC001002","RADECSYS","MJD-OBS","DATE-OBS"]],["FITS-IRAF",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","CD1_1 = -0.001 / Transformation matrix element ","CD1_2 = -3.0E-4 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","CD1_1","CD1_2","CD2_2","RADECSYS","DATE-OBS"]],["FITS-AIPS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX"]],["FITS-AIPS++",1,16,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CD1_1 = -0.001 / Transformation matrix element ","CD1_2 = -3.0E-4 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX","CD1_1","CD1_2","CD2_2","EPOCH","DATE-OBS"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX"]],["DSS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PC1_1","PC1_2","PC2_1","PC2_2","RADESYS","EQUINOX"]]]],["sin_ncp",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 30","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---SIN'","CTYPE2 = 'DEC--SIN'","PV2_1 = 0.0","PV2_2 = 1.7320508075688772","RADESYS = 'FK4'","EQUINOX = 1950.0"],"",[["FITS-WCS",1,17,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 30.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---SIN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--SIN' / Type of co-ordinate on axis 2 ","PV2_1 = 0.0 / Projection parameter ","PV2_2 = 1.7320508075688772 / Projection parameter ","RADESYS = 'FK4 ' / Reference frame for RA/DEC values ","EQUINOX = 1950.0 / [yr] Epoch of reference equinox ","MJD-OBS = 33281.923130412084 / Modified Julian Date of observation ","DATE-OBS= '31/12/49' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV2_1","PV2_2","RADESYS","EQUINOX","MJD-OBS","DATE-OBS"]],["FITS-PC",1,17,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 30.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---SIN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--SIN' / Type of co-ordinate on axis 2 ","EQUINOX = 1950.0 / Epoch of reference equinox ","RADECSYS= 'FK4 ' / Reference frame for RA/DEC values ","MJD-OBS = 33281.923130412084 / Modified Julian Date of observation ","DATE-OBS= '31/12/49' / Date of observation ","PROJP1 = 0.0 / Projection parameter ","PROJP2 = 1.7320508075688772 / Projection parameter "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV2_1","PV2_2","RADESYS","EQUINOX","RADECSYS","MJD-OBS","DATE-OBS","PROJP1","PROJP2"]],["FITS-IRAF",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 30.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---NCP' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--NCP' / Type of co-ordinate on axis 2 ","EQUINOX = 1950.0 / Epoch of reference equinox ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK4 ' / Reference frame for RA/DEC values ","DATE-OBS= '31/12/49' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV2_1","PV2_2","RADESYS","EQUINOX","CD1_1","CD2_2","RADECSYS","DATE-OBS"]],["FITS-AIPS",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 30.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---NCP' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--NCP' / Type of co-ordinate on axis 2 ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 1950.0 / Epoch of reference equinox ","DATE-OBS= '31/12/49' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV2_1","PV2_2","RADESYS","EQUINOX","CROTA2","EPOCH","DATE-OBS"]],["FITS-AIPS++",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 30.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---SIN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--SIN' / Type of co-ordinate on axis 2 ","EPOCH = 1950.0 / Epoch of reference equinox ","DATE-OBS= '31/12/49' / Date of observation ","PROJP1 = 0.0 / Projection parameter ","PROJP2 = 1.7320508075688772 / Projection parameter "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV2_1","PV2_2","RADESYS","EQUINOX","EPOCH","DATE-OBS","PROJP1","PROJP2"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV2_1","PV2_2","RADESYS","EQUINOX"]],["DSS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV2_1","PV2_2","RADESYS","EQUINOX"]]]],["galactic_car",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 0","CRVAL2 = 0","CDELT1 = -0.1","CDELT2 = 0.1","CTYPE1 = 'GLON-CAR'","CTYPE2 = 'GLAT-CAR'"],"",[["FITS-WCS",1,11,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 0.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 0.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.1 / Pixel size on axis 1 ","CDELT2 = 0.1 / Pixel size on axis 2 ","CTYPE1 = 'GLON-CAR' / Type of co-ordinate on axis 1 ","CTYPE2 = 'GLAT-CAR' / Type of co-ordinate on axis 2 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]],["FITS-PC",1,11,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 0.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 0.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.1 / Pixel scale on axis 1 ","CDELT2 = 0.1 / Pixel scale on axis 2 ","CTYPE1 = 'GLON-CAR' / Type of co-ordinate on axis 1 ","CTYPE2 = 'GLAT-CAR' / Type of co-ordinate on axis 2 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]],["FITS-IRAF",1,11,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 0.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 0.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'GLON-CAR' / Type of co-ordinate on axis 1 ","CTYPE2 = 'GLAT-CAR' / Type of co-ordinate on axis 2 ","CD1_1 = -0.1 / Transformation matrix element ","CD2_2 = 0.1 / Transformation matrix element "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CD1_1","CD2_2"]],["FITS-AIPS",1,12,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 0.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 0.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.1 / Pixel size ","CDELT2 = 0.1 / Pixel size ","CTYPE1 = 'GLON-CAR' / Type of co-ordinate on axis 1 ","CTYPE2 = 'GLAT-CAR' / Type of co-ordinate on axis 2 ","CROTA2 = 0.0 / Axis rotation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CROTA2"]],["FITS-AIPS++",1,11,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 0.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 0.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.1 / Pixel size ","CDELT2 = 0.1 / Pixel size ","CTYPE1 = 'GLON-CAR' / Type of co-ordinate on axis 1 ","CTYPE2 = 'GLAT-CAR' / Type of co-ordinate on axis 2 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]],["DSS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]]]],["freq_cube",["NAXIS = 3","NAXIS1 = 10","NAXIS2 = 10","NAXIS3 = 20","CRPIX1 = 5","CRPIX2 = 5","CRPIX3 = 10","CRVAL1 = 10","CRVAL2 = 20","CRVAL3 = 1.4E9","CDELT1 = -0.001","CDELT2 = 0.001","CDELT3 = 1.0E6","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","CTYPE3 = 'FREQ'","CUNIT3 = 'Hz'","SPECSYS = 'LSRK'","RESTFRQ = 1.420405752E9","RADESYS = 'FK5'","EQUINOX = 2000.0"],"",[["FITS-WCS",1,24,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1000000.0 / Pixel size on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","VELOSYS"]],["FITS-PC",1,21,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CDELT3 = 1000000.0 / Pixel scale on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","RADECSYS","MJD-OBS","DATE-OBS"]],["FITS-IRAF",1,20,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","CD3_3 = 1000000.0 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","CD1_1","CD2_2","CD3_3","RADECSYS","DATE-OBS"]],["FITS-AIPS",1,21,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CDELT3 = 1000000.0 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ-LSR' / Type of co-ordinate on axis 3 ","CUNIT3 = 'HZ ' / Units for axis 3 ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","RESTFREQ= 1420405752.0 / [Hz] Rest frequency "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","CROTA2","EPOCH","DATE-OBS","RESTFREQ"]],["FITS-AIPS++",1,20,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CDELT3 = 1000000.0 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ-LSR' / Type of co-ordinate on axis 3 ","CUNIT3 = 'HZ ' / Units for axis 3 ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","RESTFREQ= 1420405752.0 / [Hz] Rest frequency "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","EPOCH","DATE-OBS","RESTFREQ"]],["FITS-CLASS",1,26,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = -20401720.496064663 / Value at ref. pixel on axis 3 ","CDELT1 = -10.0E-4 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CDELT3 = 1000002.8796456693 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","RESTFREQ= 1420405752.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VELO-LSR= 4306861.2900254978 / [m/s] Reference velocity ","VLSR = 4306861.2900254978 / [m/s] Reference velocity ","DELTAV = -211061.14050704753 / [m/s] Velocity resolution ","AZIMUTH = 70.000142900751996 / [Deg] Telescope azimuth ","ELEVATIO= 0.18035206979989882 / [Deg] Telescope elevation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","DATE-OBS","RESTFREQ","OBJECT","LINE","VELO-LSR","VLSR","DELTAV","AZIMUTH","ELEVATIO"]],["DSS",0,4,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX"]]]],["class_cube",["NAXIS = 3","NAXIS1 = 20","NAXIS2 = 10","NAXIS3 = 10","CRPIX1 = 10","CRPIX2 = 5","CRPIX3 = 5","CRVAL1 = 1.102E11","CRVAL2 = 40.738","CRVAL3 = 62.933","CDELT1 = 39062.5","CDELT2 = -0.01","CDELT3 = 0.01","CTYPE1 = 'FREQ'","CTYPE2 = 'RA---TAN'","CTYPE3 = 'DEC--TAN'","CUNIT1 = 'Hz'","SPECSYS = 'SOURCE'","RESTFRQ = 1.10201354E11","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 52413.59"],"",[["FITS-WCS",1,24,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size on axis 1 ","CDELT2 = -0.01 / Pixel size on axis 2 ","CDELT3 = 0.01 / Pixel size on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","SPECSYS = 'SOURCE ' / Standard of rest for spectral axis ","RESTFRQ = 110201354000.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","VELOSYS = 0.0 / [m/s] Topo. apparent velocity of rest frame "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","VELOSYS"]],["FITS-PC",1,21,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel scale on axis 1 ","CDELT2 = -0.01 / Pixel scale on axis 2 ","CDELT3 = 0.01 / Pixel scale on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","RADECSYS","DATE-OBS"]],["FITS-IRAF",1,21,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","CD1_1 = 39062.5 / Transformation matrix element ","CD2_2 = -0.01 / Transformation matrix element ","CD3_3 = 0.01 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","CD1_1","CD2_2","CD3_3","RADECSYS","DATE-OBS"]],["FITS-AIPS",0,5,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS++",0,5,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-CLASS",1,27,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = -1354000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size ","CDELT2 = -0.01 / Pixel size ","CDELT3 = 0.01 / Pixel size ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","RESTFREQ= 110201354000.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VELO-LSR= 7546.9121858340259 / [m/s] Reference velocity ","VLSR = 7546.9121858340259 / [m/s] Reference velocity ","DELTAV = -106.2645018012754 / [m/s] Velocity resolution ","AZIMUTH = 339.00226537612787 / [Deg] Telescope azimuth ","ELEVATIO= 17.470663568419475 / [Deg] Telescope elevation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","RESTFREQ","OBJECT","LINE","VELO-LSR","VLSR","DELTAV","AZIMUTH","ELEVATIO"]],["DSS",0,5,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]]]],["linear",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 100","CRVAL2 = 200","CDELT1 = 2","CDELT2 = 3","CTYPE1 = 'X'","CTYPE2 = 'Y'"],"",[["FITS-WCS",1,12,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 200.0 / Value at ref. pixel on axis 2 ","CDELT1 = 2.0 / Pixel size on axis 1 ","CDELT2 = 3.0 / Pixel size on axis 2 ","CTYPE1 = 'X ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'Y ' / Type of co-ordinate on axis 2 ","WCSNAME = 'X-Y ' / Reference name for the coord. frame "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","WCSNAME"]],["FITS-PC",1,11,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 200.0 / Value at ref. pixel on axis 2 ","CDELT1 = 2.0 / Pixel scale on axis 1 ","CDELT2 = 3.0 / Pixel scale on axis 2 ","CTYPE1 = 'X ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'Y ' / Type of co-ordinate on axis 2 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]],["FITS-IRAF",1,11,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 200.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'X ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'Y ' / Type of co-ordinate on axis 2 ","CD1_1 = 2.0 / Transformation matrix element ","CD2_2 = 3.0 / Transformation matrix element "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CD1_1","CD2_2"]],["FITS-AIPS",1,12,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 200.0 / Value at ref. pixel on axis 2 ","CDELT1 = 2.0 / Pixel size ","CDELT2 = 3.0 / Pixel size ","CTYPE1 = 'X ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'Y ' / Type of co-ordinate on axis 2 ","CROTA1 = 0.0 / Axis rotation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CROTA1"]],["FITS-AIPS++",1,11,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 100.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 200.0 / Value at ref. pixel on axis 2 ","CDELT1 = 2.0 / Pixel size ","CDELT2 = 3.0 / Pixel size ","CTYPE1 = 'X ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'Y ' / Type of co-ordinate on axis 2 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]],["DSS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2"]]]],["tpn",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TPN'","CTYPE2 = 'DEC--TPN'","PV1_0 = 0.0","PV1_1 = 1.0","PV1_2 = 0.0","PV2_0 = 0.0","PV2_1 = 1.0","PV2_2 = 0.0","PV1_4 = 0.001","RADESYS = 'FK5'","EQUINOX = 2000.0"],"",[["FITS-WCS",1,22,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","QV1_0 = 0.0 / Projection parameter ","QV1_1 = 1.0 / Projection parameter ","QV1_2 = 0.0 / Projection parameter ","QV1_4 = 0.001 / Projection parameter ","QV2_0 = 0.0 / Projection parameter ","QV2_1 = 1.0 / Projection parameter ","QV2_2 = 0.0 / Projection parameter "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV1_0","PV1_1","PV1_2","PV2_0","PV2_1","PV2_2","PV1_4","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","QV1_0","QV1_1","QV1_2","QV1_4","QV2_0","QV2_1","QV2_2"]],["FITS-PC",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CTYPE1","CTYPE2","PV1_0","PV1_1","PV1_2","PV2_0","PV2_1","PV2_2","PV1_4","RADESYS","EQUINOX"]],["FITS-IRAF",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV1_0","PV1_1","PV1_2","PV2_0","PV2_1","PV2_2","PV1_4","RADESYS","EQUINOX"]],["FITS-AIPS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV1_0","PV1_1","PV1_2","PV2_0","PV2_1","PV2_2","PV1_4","RADESYS","EQUINOX"]],["FITS-AIPS++",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV1_0","PV1_1","PV1_2","PV2_0","PV2_1","PV2_2","PV1_4","RADESYS","EQUINOX"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV1_0","PV1_1","PV1_2","PV2_0","PV2_1","PV2_2","PV1_4","RADESYS","EQUINOX"]],["DSS",1,61,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CNPIX1 = 1.0 / X corner (pixels) ","CNPIX2 = 1.0 / Y corner (pixels) ","PPO1 = 0.0 / Orientation co-efficients ","PPO2 = 0.0 ","PPO3 = 5.5 ","PPO4 = 0.0 ","PPO5 = 0.0 ","PPO6 = 5.5 ","XPIXELSZ= 1.0 / X pixel size (microns) ","YPIXELSZ= 1.0 / Y pixel size (microns) ","PLTRAH = 0.0 / RA at plate centre ","PLTRAM = 39.0 ","PLTRAS = 60.0 ","PLTDECD = 20.0 / DEC at plate centre ","PLTDECM = 0.0 ","PLTDECS = 1.2789769243681803E-11 ","PLTDECSN= '+ ' ","PLTSCALE= 3600.0 / Plate scale (arcsec/mm) ","AMDX1 = 3600.0 / Plate solution x co-efficients ","AMDX2 = 0.0 ","AMDX3 = 0.0 ","AMDX4 = 3.6 ","AMDX5 = 0.0 ","AMDX6 = 0.0 ","AMDX7 = 0.0 ","AMDX8 = 0.0 ","AMDX9 = 0.0 ","AMDX10 = 0.0 ","AMDX11 = 0.0 ","AMDX12 = 0.0 ","AMDX13 = 0.0 ","AMDX14 = 0.0 ","AMDX15 = 0.0 ","AMDX16 = 0.0 ","AMDX17 = 0.0 ","AMDX18 = 0.0 ","AMDX19 = 0.0 ","AMDX20 = 0.0 ","AMDY1 = 3600.0 / Plate solution y co-efficients ","AMDY2 = 0.0 ","AMDY3 = 0.0 ","AMDY4 = 0.0 ","AMDY5 = 0.0 ","AMDY6 = 0.0 ","AMDY7 = 0.0 ","AMDY8 = 0.0 ","AMDY9 = 0.0 ","AMDY10 = 0.0 ","AMDY11 = 0.0 ","AMDY12 = 0.0 ","AMDY13 = 0.0 ","AMDY14 = 0.0 ","AMDY15 = 0.0 ","AMDY16 = 0.0 ","AMDY17 = 0.0 ","AMDY18 = 0.0 ","AMDY19 = 0.0 ","AMDY20 = 0.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","PV1_0","PV1_1","PV1_2","PV2_0","PV2_1","PV2_2","PV1_4","RADESYS","EQUINOX","CNPIX1","CNPIX2","PPO1","PPO2","PPO3","PPO4","PPO5","PPO6","XPIXELSZ","YPIXELSZ","PLTRAH","PLTRAM","PLTRAS","PLTDECD","PLTDECM","PLTDECS","PLTDECSN","PLTSCALE","AMDX1","AMDX2","AMDX3","AMDX4","AMDX5","AMDX6","AMDX7","AMDX8","AMDX9","AMDX10","AMDX11","AMDX12","AMDX13","AMDX14","AMDX15","AMDX16","AMDX17","AMDX18","AMDX19","AMDX20","AMDY1","AMDY2","AMDY3","AMDY4","AMDY5","AMDY6","AMDY7","AMDY8","AMDY9","AMDY10","AMDY11","AMDY12","AMDY13","AMDY14","AMDY15","AMDY16","AMDY17","AMDY18","AMDY19","AMDY20"]]]],["alt_pc",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0","CRPIX1A = 5","CRPIX2A = 5","CRVAL1A = 10","CRVAL2A = 20","CDELT1A = -0.002","CDELT2A = 0.002","CTYPE1A = 'RA---TAN'","CTYPE2A = 'DEC--TAN'","RADESYSA= 'FK5'","EQUINOXA= 2000.0","CRPIX1B = 5","CRPIX2B = 5","CRVAL1B = 10","CRVAL2B = 20","CDELT1B = -0.001","CDELT2B = 0.001","CTYPE1B = 'RA---TAN'","CTYPE2B = 'DEC--TAN'","PC1_1B = 0.8660254037844387","PC1_2B = -0.5","PC2_1B = 0.5","PC2_2B = 0.8660254037844387","RADESYSB= 'FK5'","EQUINOXB= 2000.0"],"",[["FITS-WCS",1,39,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","CRPIX1A = 5.0 / Reference pixel on axis 1 ","CRPIX2A = 5.0 / Reference pixel on axis 2 ","CRVAL1A = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 20.0 / Value at ref. pixel on axis 2 ","CDELT1A = -0.002 / Pixel size on axis 1 ","CDELT2A = 0.002 / Pixel size on axis 2 ","CTYPE1A = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYSA= 'FK5 ' / Reference frame for RA/DEC values ","EQUINOXA= 2000.0 / [yr] Epoch of reference equinox ","CRPIX1B = 5.0 / Reference pixel on axis 1 ","CRPIX2B = 5.0 / Reference pixel on axis 2 ","CRVAL1B = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2B = 20.0 / Value at ref. pixel on axis 2 ","CDELT1B = -0.001 / Pixel size on axis 1 ","CDELT2B = 0.001 / Pixel size on axis 2 ","CTYPE1B = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2B = 'DEC--TAN' / Type of co-ordinate on axis 2 ","PC1_1B = 0.8660254037844386 / Transformation matrix element ","PC1_2B = -0.5 / Transformation matrix element ","PC2_1B = 0.5 / Transformation matrix element ","PC2_2B = 0.86602540378443871 / Transformation matrix element ","RADESYSB= 'FK5 ' / Reference frame for RA/DEC values ","EQUINOXB= 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","CRPIX1B","CRPIX2B","CRVAL1B","CRVAL2B","CDELT1B","CDELT2B","CTYPE1B","CTYPE2B","PC1_1B","PC1_2B","PC2_1B","PC2_2B","RADESYSB","EQUINOXB","MJD-OBS","DATE-OBS"]],["FITS-PC",1,23,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","C1ELT1 = -0.002 / Pixel scale on axis 1 ","C1ELT2 = 0.002 / Pixel scale on axis 2 ","C1PIX1 = 5.0 / Reference pixel on axis 1 ","C1PIX2 = 5.0 / Reference pixel on axis 2 ","C1VAL1 = 10.0 / Value at ref. pixel on axis 1 ","C1VAL2 = 20.0 / Value at ref. pixel on axis 2 ","C1YPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","C1YPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","CRPIX1B","CRPIX2B","CRVAL1B","CRVAL2B","CDELT1B","CDELT2B","CTYPE1B","CTYPE2B","PC1_1B","PC1_2B","PC2_1B","PC2_2B","RADESYSB","EQUINOXB","RADECSYS","MJD-OBS","DATE-OBS","C1ELT1","C1ELT2","C1PIX1","C1PIX2","C1VAL1","C1VAL2","C1YPE1","C1YPE2"]],["FITS-IRAF",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","CRPIX1B","CRPIX2B","CRVAL1B","CRVAL2B","CDELT1B","CDELT2B","CTYPE1B","CTYPE2B","PC1_1B","PC1_2B","PC2_1B","PC2_2B","RADESYSB","EQUINOXB","CD1_1","CD2_2","RADECSYS","DATE-OBS"]],["FITS-AIPS",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","CRPIX1B","CRPIX2B","CRVAL1B","CRVAL2B","CDELT1B","CDELT2B","CTYPE1B","CTYPE2B","PC1_1B","PC1_2B","PC2_1B","PC2_2B","RADESYSB","EQUINOXB","CROTA2","EPOCH","DATE-OBS"]],["FITS-AIPS++",1,13,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","CRPIX1B","CRPIX2B","CRVAL1B","CRVAL2B","CDELT1B","CDELT2B","CTYPE1B","CTYPE2B","PC1_1B","PC1_2B","PC2_1B","PC2_2B","RADESYSB","EQUINOXB","EPOCH","DATE-OBS"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","CRPIX1B","CRPIX2B","CRVAL1B","CRVAL2B","CDELT1B","CDELT2B","CTYPE1B","CTYPE2B","PC1_1B","PC1_2B","PC2_1B","PC2_2B","RADESYSB","EQUINOXB"]],["DSS",1,61,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CNPIX1 = 1.0 / X corner (pixels) ","CNPIX2 = 1.0 / Y corner (pixels) ","PPO1 = 0.0 / Orientation co-efficients ","PPO2 = 0.0 ","PPO3 = 5.5 ","PPO4 = 0.0 ","PPO5 = 0.0 ","PPO6 = 5.5 ","XPIXELSZ= 1.0 / X pixel size (microns) ","YPIXELSZ= 1.0 / Y pixel size (microns) ","PLTRAH = 0.0 / RA at plate centre ","PLTRAM = 39.0 ","PLTRAS = 60.0 ","PLTDECD = 20.0 / DEC at plate centre ","PLTDECM = 0.0 ","PLTDECS = 1.2789769243681803E-11 ","PLTDECSN= '+ ' ","PLTSCALE= 3600.0 / Plate scale (arcsec/mm) ","AMDX1 = 3600.0 / Plate solution x co-efficients ","AMDX2 = 0.0 ","AMDX3 = 0.0 ","AMDX4 = 0.0 ","AMDX5 = 0.0 ","AMDX6 = 0.0 ","AMDX7 = 0.0 ","AMDX8 = 0.0 ","AMDX9 = 0.0 ","AMDX10 = 0.0 ","AMDX11 = 0.0 ","AMDX12 = 0.0 ","AMDX13 = 0.0 ","AMDX14 = 0.0 ","AMDX15 = 0.0 ","AMDX16 = 0.0 ","AMDX17 = 0.0 ","AMDX18 = 0.0 ","AMDX19 = 0.0 ","AMDX20 = 0.0 ","AMDY1 = 3600.0 / Plate solution y co-efficients ","AMDY2 = 0.0 ","AMDY3 = 0.0 ","AMDY4 = 0.0 ","AMDY5 = 0.0 ","AMDY6 = 0.0 ","AMDY7 = 0.0 ","AMDY8 = 0.0 ","AMDY9 = 0.0 ","AMDY10 = 0.0 ","AMDY11 = 0.0 ","AMDY12 = 0.0 ","AMDY13 = 0.0 ","AMDY14 = 0.0 ","AMDY15 = 0.0 ","AMDY16 = 0.0 ","AMDY17 = 0.0 ","AMDY18 = 0.0 ","AMDY19 = 0.0 ","AMDY20 = 0.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","CRPIX1B","CRPIX2B","CRVAL1B","CRVAL2B","CDELT1B","CDELT2B","CTYPE1B","CTYPE2B","PC1_1B","PC1_2B","PC2_1B","PC2_2B","RADESYSB","EQUINOXB","CNPIX1","CNPIX2","PPO1","PPO2","PPO3","PPO4","PPO5","PPO6","XPIXELSZ","YPIXELSZ","PLTRAH","PLTRAM","PLTRAS","PLTDECD","PLTDECM","PLTDECS","PLTDECSN","PLTSCALE","AMDX1","AMDX2","AMDX3","AMDX4","AMDX5","AMDX6","AMDX7","AMDX8","AMDX9","AMDX10","AMDX11","AMDX12","AMDX13","AMDX14","AMDX15","AMDX16","AMDX17","AMDX18","AMDX19","AMDX20","AMDY1","AMDY2","AMDY3","AMDY4","AMDY5","AMDY6","AMDY7","AMDY8","AMDY9","AMDY10","AMDY11","AMDY12","AMDY13","AMDY14","AMDY15","AMDY16","AMDY17","AMDY18","AMDY19","AMDY20"]]]],["alt_j",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0","CRPIX1J = 5","CRPIX2J = 5","CRVAL1J = 10","CRVAL2J = 20","CDELT1J = -0.002","CDELT2J = 0.002","CTYPE1J = 'RA---TAN'","CTYPE2J = 'DEC--TAN'","RADESYSJ= 'FK5'","EQUINOXJ= 2000.0"],"",[["FITS-WCS",1,25,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","CRPIX1J = 5.0 / Reference pixel on axis 1 ","CRPIX2J = 5.0 / Reference pixel on axis 2 ","CRVAL1J = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2J = 20.0 / Value at ref. pixel on axis 2 ","CDELT1J = -0.002 / Pixel size on axis 1 ","CDELT2J = 0.002 / Pixel size on axis 2 ","CTYPE1J = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2J = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYSJ= 'FK5 ' / Reference frame for RA/DEC values ","EQUINOXJ= 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1J","CRPIX2J","CRVAL1J","CRVAL2J","CDELT1J","CDELT2J","CTYPE1J","CTYPE2J","RADESYSJ","EQUINOXJ","MJD-OBS","DATE-OBS"]],["FITS-PC",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1J","CRPIX2J","CRVAL1J","CRVAL2J","CDELT1J","CDELT2J","CTYPE1J","CTYPE2J","RADESYSJ","EQUINOXJ"]],["FITS-IRAF",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1J","CRPIX2J","CRVAL1J","CRVAL2J","CDELT1J","CDELT2J","CTYPE1J","CTYPE2J","RADESYSJ","EQUINOXJ","CD1_1","CD2_2","RADECSYS","DATE-OBS"]],["FITS-AIPS",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1J","CRPIX2J","CRVAL1J","CRVAL2J","CDELT1J","CDELT2J","CTYPE1J","CTYPE2J","RADESYSJ","EQUINOXJ","CROTA2","EPOCH","DATE-OBS"]],["FITS-AIPS++",1,13,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1J","CRPIX2J","CRVAL1J","CRVAL2J","CDELT1J","CDELT2J","CTYPE1J","CTYPE2J","RADESYSJ","EQUINOXJ","EPOCH","DATE-OBS"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1J","CRPIX2J","CRVAL1J","CRVAL2J","CDELT1J","CDELT2J","CTYPE1J","CTYPE2J","RADESYSJ","EQUINOXJ"]],["DSS",1,61,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CNPIX1 = 1.0 / X corner (pixels) ","CNPIX2 = 1.0 / Y corner (pixels) ","PPO1 = 0.0 / Orientation co-efficients ","PPO2 = 0.0 ","PPO3 = 5.5 ","PPO4 = 0.0 ","PPO5 = 0.0 ","PPO6 = 5.5 ","XPIXELSZ= 1.0 / X pixel size (microns) ","YPIXELSZ= 1.0 / Y pixel size (microns) ","PLTRAH = 0.0 / RA at plate centre ","PLTRAM = 39.0 ","PLTRAS = 60.0 ","PLTDECD = 20.0 / DEC at plate centre ","PLTDECM = 0.0 ","PLTDECS = 1.2789769243681803E-11 ","PLTDECSN= '+ ' ","PLTSCALE= 3600.0 / Plate scale (arcsec/mm) ","AMDX1 = 3600.0 / Plate solution x co-efficients ","AMDX2 = 0.0 ","AMDX3 = 0.0 ","AMDX4 = 0.0 ","AMDX5 = 0.0 ","AMDX6 = 0.0 ","AMDX7 = 0.0 ","AMDX8 = 0.0 ","AMDX9 = 0.0 ","AMDX10 = 0.0 ","AMDX11 = 0.0 ","AMDX12 = 0.0 ","AMDX13 = 0.0 ","AMDX14 = 0.0 ","AMDX15 = 0.0 ","AMDX16 = 0.0 ","AMDX17 = 0.0 ","AMDX18 = 0.0 ","AMDX19 = 0.0 ","AMDX20 = 0.0 ","AMDY1 = 3600.0 / Plate solution y co-efficients ","AMDY2 = 0.0 ","AMDY3 = 0.0 ","AMDY4 = 0.0 ","AMDY5 = 0.0 ","AMDY6 = 0.0 ","AMDY7 = 0.0 ","AMDY8 = 0.0 ","AMDY9 = 0.0 ","AMDY10 = 0.0 ","AMDY11 = 0.0 ","AMDY12 = 0.0 ","AMDY13 = 0.0 ","AMDY14 = 0.0 ","AMDY15 = 0.0 ","AMDY16 = 0.0 ","AMDY17 = 0.0 ","AMDY18 = 0.0 ","AMDY19 = 0.0 ","AMDY20 = 0.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","CRPIX1J","CRPIX2J","CRVAL1J","CRVAL2J","CDELT1J","CDELT2J","CTYPE1J","CTYPE2J","RADESYSJ","EQUINOXJ","CNPIX1","CNPIX2","PPO1","PPO2","PPO3","PPO4","PPO5","PPO6","XPIXELSZ","YPIXELSZ","PLTRAH","PLTRAM","PLTRAS","PLTDECD","PLTDECM","PLTDECS","PLTDECSN","PLTSCALE","AMDX1","AMDX2","AMDX3","AMDX4","AMDX5","AMDX6","AMDX7","AMDX8","AMDX9","AMDX10","AMDX11","AMDX12","AMDX13","AMDX14","AMDX15","AMDX16","AMDX17","AMDX18","AMDX19","AMDX20","AMDY1","AMDY2","AMDY3","AMDY4","AMDY5","AMDY6","AMDY7","AMDY8","AMDY9","AMDY10","AMDY11","AMDY12","AMDY13","AMDY14","AMDY15","AMDY16","AMDY17","AMDY18","AMDY19","AMDY20"]]]],["alt_lonpole",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0","LONPOLE = 179.95","CRPIX1A = 5","CRPIX2A = 5","CRVAL1A = 10","CRVAL2A = 20","CDELT1A = -0.002","CDELT2A = 0.002","CTYPE1A = 'RA---TAN'","CTYPE2A = 'DEC--TAN'","RADESYSA= 'FK5'","EQUINOXA= 2000.0","LONPOLEA= 179.97"],"",[["FITS-WCS",1,29,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","LONPOLE = 179.95 / [deg] Longitude of native north pole ","CRPIX1A = 5.0 / Reference pixel on axis 1 ","CRPIX2A = 5.0 / Reference pixel on axis 2 ","CRVAL1A = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 20.0 / Value at ref. pixel on axis 2 ","CDELT1A = -0.002 / Pixel size on axis 1 ","CDELT2A = 0.002 / Pixel size on axis 2 ","CTYPE1A = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYSA= 'FK5 ' / Reference frame for RA/DEC values ","EQUINOXA= 2000.0 / [yr] Epoch of reference equinox ","LONPOLEA= 179.97 / [deg] Longitude of native north pole ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","PV1_3 = 179.95 / Projection parameter ","PV1_3A = 179.97 / Projection parameter "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","LONPOLE","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","LONPOLEA","MJD-OBS","DATE-OBS","PV1_3","PV1_3A"]],["FITS-PC",1,16,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","LONGPOLE= 179.95 / Longitude of native north pole ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","LONPOLE","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","LONPOLEA","RADECSYS","LONGPOLE","MJD-OBS","DATE-OBS"]],["FITS-IRAF",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","LONPOLE","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","LONPOLEA"]],["FITS-AIPS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","LONPOLE","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","LONPOLEA"]],["FITS-AIPS++",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","LONPOLE = 179.95 / Longitude of native north pole ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","LONPOLE","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","LONPOLEA","EPOCH","DATE-OBS"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","LONPOLE","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","LONPOLEA"]],["DSS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","LONPOLE","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CDELT1A","CDELT2A","CTYPE1A","CTYPE2A","RADESYSA","EQUINOXA","LONPOLEA"]]]],["class_lonpole_180",["NAXIS = 3","NAXIS1 = 20","NAXIS2 = 10","NAXIS3 = 10","CRPIX1 = 10","CRPIX2 = 5","CRPIX3 = 5","CRVAL1 = 1.102E11","CRVAL2 = 40.738","CRVAL3 = 62.933","CDELT1 = 39062.5","CDELT2 = -0.01","CDELT3 = 0.01","CTYPE1 = 'FREQ'","CTYPE2 = 'RA---TAN'","CTYPE3 = 'DEC--TAN'","CUNIT1 = 'Hz'","SPECSYS = 'SOURCE'","RESTFRQ = 1.10201354E11","RADESYS = 'FK5'","EQUINOX = 2000.0","LONPOLE = 180"],"",[["FITS-WCS",1,26,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size on axis 1 ","CDELT2 = -0.01 / Pixel size on axis 2 ","CDELT3 = 0.01 / Pixel size on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","SPECSYS = 'SOURCE ' / Standard of rest for spectral axis ","RESTFRQ = 110201354000.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","LONPOLE = 180.0 / [deg] Longitude of native north pole ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","PV2_3 = 180.0 / Projection parameter ","VELOSYS = 0.0 / [m/s] Topo. apparent velocity of rest frame "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE","MJD-OBS","DATE-OBS","PV2_3","VELOSYS"]],["FITS-PC",1,22,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel scale on axis 1 ","CDELT2 = -0.01 / Pixel scale on axis 2 ","CDELT3 = 0.01 / Pixel scale on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","LONGPOLE= 180.0 / Longitude of native north pole ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE","RADECSYS","LONGPOLE","MJD-OBS","DATE-OBS"]],["FITS-IRAF",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]],["FITS-AIPS",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]],["FITS-AIPS++",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]],["FITS-CLASS",1,26,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = -1354000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size ","CDELT2 = -0.01 / Pixel size ","CDELT3 = 0.01 / Pixel size ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","RESTFREQ= 110201354000.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VELO-LSR= 7546.9121858340259 / [m/s] Reference velocity ","VLSR = 7546.9121858340259 / [m/s] Reference velocity ","DELTAV = -106.2645018012754 / [m/s] Velocity resolution ","AZIMUTH = 23.750355091264087 / [Deg] Telescope azimuth ","ELEVATIO= -13.373012460218291 / [Deg] Telescope elevation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE","DATE-OBS","RESTFREQ","OBJECT","LINE","VELO-LSR","VLSR","DELTAV","AZIMUTH","ELEVATIO"]],["DSS",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]]]],["class_lonpole_90",["NAXIS = 3","NAXIS1 = 20","NAXIS2 = 10","NAXIS3 = 10","CRPIX1 = 10","CRPIX2 = 5","CRPIX3 = 5","CRVAL1 = 1.102E11","CRVAL2 = 40.738","CRVAL3 = 62.933","CDELT1 = 39062.5","CDELT2 = -0.01","CDELT3 = 0.01","CTYPE1 = 'FREQ'","CTYPE2 = 'RA---TAN'","CTYPE3 = 'DEC--TAN'","CUNIT1 = 'Hz'","SPECSYS = 'SOURCE'","RESTFRQ = 1.10201354E11","RADESYS = 'FK5'","EQUINOX = 2000.0","LONPOLE = 90"],"",[["FITS-WCS",1,26,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size on axis 1 ","CDELT2 = -0.01 / Pixel size on axis 2 ","CDELT3 = 0.01 / Pixel size on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","SPECSYS = 'SOURCE ' / Standard of rest for spectral axis ","RESTFRQ = 110201354000.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","LONPOLE = 90.0 / [deg] Longitude of native north pole ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation ","PV2_3 = 90.0 / Projection parameter ","VELOSYS = 0.0 / [m/s] Topo. apparent velocity of rest frame "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE","MJD-OBS","DATE-OBS","PV2_3","VELOSYS"]],["FITS-PC",1,22,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel scale on axis 1 ","CDELT2 = -0.01 / Pixel scale on axis 2 ","CDELT3 = 0.01 / Pixel scale on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","LONGPOLE= 90.0 / Longitude of native north pole ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE","RADECSYS","LONGPOLE","MJD-OBS","DATE-OBS"]],["FITS-IRAF",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]],["FITS-AIPS",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]],["FITS-AIPS++",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]],["FITS-CLASS",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]],["DSS",0,4,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","LONPOLE"]]]],["tan_new_epoch",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0","DATE-OBS= '2002-05-19T14:09:36.000'","MJD-OBS = 52413.59"],"MJD 55000",[["FITS-WCS",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS"]],["FITS-PC",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS","RADECSYS"]],["FITS-IRAF",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","CD1_1 = -10.0E-4 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS","CD1_1","CD2_2","RADECSYS"]],["FITS-AIPS",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS","CROTA2","EPOCH"]],["FITS-AIPS++",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","EPOCH = 2000.0 / Epoch of reference equinox "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS","EPOCH"]],["FITS-CLASS",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS"]],["DSS",1,62,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 52413.59 ","CNPIX1 = 1.0 / X corner (pixels) ","CNPIX2 = 1.0 / Y corner (pixels) ","PPO1 = 0.0 / Orientation co-efficients ","PPO2 = 0.0 ","PPO3 = 5.5 ","PPO4 = 0.0 ","PPO5 = 0.0 ","PPO6 = 5.5 ","XPIXELSZ= 1.0 / X pixel size (microns) ","YPIXELSZ= 1.0 / Y pixel size (microns) ","PLTRAH = 0.0 / RA at plate centre ","PLTRAM = 40.0 ","PLTRAS = 0.0003633178766904166 ","PLTDECD = 19.0 / DEC at plate centre ","PLTDECM = 59.0 ","PLTDECS = 59.99544693467044 ","PLTDECSN= '+ ' ","PLTSCALE= 3600.0 / Plate scale (arcsec/mm) ","AMDX1 = 3600.0 / Plate solution x co-efficients ","AMDX2 = 0.0 ","AMDX3 = 0.0 ","AMDX4 = 0.0 ","AMDX5 = 0.0 ","AMDX6 = 0.0 ","AMDX7 = 0.0 ","AMDX8 = 0.0 ","AMDX9 = 0.0 ","AMDX10 = 0.0 ","AMDX11 = 0.0 ","AMDX12 = 0.0 ","AMDX13 = 0.0 ","AMDX14 = 0.0 ","AMDX15 = 0.0 ","AMDX16 = 0.0 ","AMDX17 = 0.0 ","AMDX18 = 0.0 ","AMDX19 = 0.0 ","AMDX20 = 0.0 ","AMDY1 = 3600.0 / Plate solution y co-efficients ","AMDY2 = 0.0 ","AMDY3 = 0.0 ","AMDY4 = 0.0 ","AMDY5 = 0.0 ","AMDY6 = 0.0 ","AMDY7 = 0.0 ","AMDY8 = 0.0 ","AMDY9 = 0.0 ","AMDY10 = 0.0 ","AMDY11 = 0.0 ","AMDY12 = 0.0 ","AMDY13 = 0.0 ","AMDY14 = 0.0 ","AMDY15 = 0.0 ","AMDY16 = 0.0 ","AMDY17 = 0.0 ","AMDY18 = 0.0 ","AMDY19 = 0.0 ","AMDY20 = 0.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS","CNPIX1","CNPIX2","PPO1","PPO2","PPO3","PPO4","PPO5","PPO6","XPIXELSZ","YPIXELSZ","PLTRAH","PLTRAM","PLTRAS","PLTDECD","PLTDECM","PLTDECS","PLTDECSN","PLTSCALE","AMDX1","AMDX2","AMDX3","AMDX4","AMDX5","AMDX6","AMDX7","AMDX8","AMDX9","AMDX10","AMDX11","AMDX12","AMDX13","AMDX14","AMDX15","AMDX16","AMDX17","AMDX18","AMDX19","AMDX20","AMDY1","AMDY2","AMDY3","AMDY4","AMDY5","AMDY6","AMDY7","AMDY8","AMDY9","AMDY10","AMDY11","AMDY12","AMDY13","AMDY14","AMDY15","AMDY16","AMDY17","AMDY18","AMDY19","AMDY20"]]]],["tan_offset_origin",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 55000.0"],"SKYREF 0.17 0.35 Origin",[["FITS-WCS",1,32,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 0.24405461001771456 / Value at ref. pixel on axis 1 ","CRVAL2 = -0.053333159112612105 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'OFLN-TAN' / RA offset from 0:38:57.7, 20:03:13 ","CTYPE2 = 'OFLT-TAN' / Dec offset from 0:38:57.7, 20:03:13 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 55000.0 / Modified Julian Date of observation ","PC1_1 = 0.9999987920354485 / Transformation matrix element ","PC1_2 = 0.0015543254626795831 / Transformation matrix element ","PC2_1 = -0.0015543254627649512 / Transformation matrix element ","PC2_2 = 0.99999879203544828 / Transformation matrix element ","DATE-OBS= '2009-06-18T00:00:00.000' / Date of observation ","CRPIX1A = 5.0 / Reference pixel on axis 1 ","CRPIX2A = 5.0 / Reference pixel on axis 2 ","CRVAL1A = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1A = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 ","SREFISA = 'ORIGIN ' / Is SkyRef used as pole or origin? ","SREF1A = 0.17 / Sky reference position on axis 1 ","SREF2A = 0.35 / Sky reference position on axis 2 ","RADESYSA= 'FK5 ' / Reference frame for RA/DEC values ","EQUINOXA= 2000.0 / [yr] Epoch of reference equinox "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS","PC1_1","PC1_2","PC2_1","PC2_2","DATE-OBS","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CTYPE1A","CTYPE2A","CDELT1A","CDELT2A","SREFISA","SREF1A","SREF2A","RADESYSA","EQUINOXA"]],["FITS-PC",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-IRAF",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS++",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-CLASS",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["DSS",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]]]],["tan_offset_pole",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 55000.0"],"SKYREF 0.17 0.35 Pole",[["FITS-WCS",1,32,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 89.750185946494426 / Value at ref. pixel on axis 1 ","CRVAL2 = 257.67292437411567 / Value at ref. pixel on axis 2 ","CDELT1 = 0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'OFLT-TAN' / Dec offset from 0:38:57.7, 20:03:13 ","CTYPE2 = 'OFLN-TAN' / RA offset from 0:38:57.7, 20:03:13 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 55000.0 / Modified Julian Date of observation ","PC1_1 = 0.97661220592969344 / Transformation matrix element ","PC1_2 = 0.21500837013739305 / Transformation matrix element ","PC2_1 = -0.21500837013746846 / Transformation matrix element ","PC2_2 = 0.97661220592967668 / Transformation matrix element ","DATE-OBS= '2009-06-18T00:00:00.000' / Date of observation ","CRPIX1A = 5.0 / Reference pixel on axis 1 ","CRPIX2A = 5.0 / Reference pixel on axis 2 ","CRVAL1A = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2A = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1A = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2A = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1A = -0.001 / Pixel size on axis 1 ","CDELT2A = 0.001 / Pixel size on axis 2 ","SREFISA = 'POLE ' / Is SkyRef used as pole or origin? ","SREF1A = 0.17 / Sky reference position on axis 1 ","SREF2A = 0.35 / Sky reference position on axis 2 ","RADESYSA= 'FK5 ' / Reference frame for RA/DEC values ","EQUINOXA= 2000.0 / [yr] Epoch of reference equinox "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS","PC1_1","PC1_2","PC2_1","PC2_2","DATE-OBS","CRPIX1A","CRPIX2A","CRVAL1A","CRVAL2A","CTYPE1A","CTYPE2A","CDELT1A","CDELT2A","SREFISA","SREF1A","SREF2A","RADESYSA","EQUINOXA"]],["FITS-PC",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-IRAF",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS++",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["FITS-CLASS",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]],["DSS",0,4,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","MJD-OBS = 55000.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","MJD-OBS"]]]],["tan_new_epoch_no_mjd",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","RADESYS = 'FK5'","EQUINOX = 2000.0","DATE-OBS= '2002-05-19T14:09:36.000'"],"MJD 55000",[["FITS-WCS",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","MJD-OBS"]],["FITS-PC",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","RADECSYS","MJD-OBS"]],["FITS-IRAF",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","CD1_1 = -10.0E-4 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","CD1_1","CD2_2","RADECSYS"]],["FITS-AIPS",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","CROTA2","EPOCH"]],["FITS-AIPS++",1,13,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.000001513824486 / Value at ref. pixel on axis 1 ","CRVAL2 = 19.999998735259631 / Value at ref. pixel on axis 2 ","CDELT1 = -10.0E-4 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","EPOCH = 2000.0 / Epoch of reference equinox "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","EPOCH"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS"]],["DSS",1,61,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CNPIX1 = 1.0 / X corner (pixels) ","CNPIX2 = 1.0 / Y corner (pixels) ","PPO1 = 0.0 / Orientation co-efficients ","PPO2 = 0.0 ","PPO3 = 5.5 ","PPO4 = 0.0 ","PPO5 = 0.0 ","PPO6 = 5.5 ","XPIXELSZ= 1.0 / X pixel size (microns) ","YPIXELSZ= 1.0 / Y pixel size (microns) ","PLTRAH = 0.0 / RA at plate centre ","PLTRAM = 40.0 ","PLTRAS = 0.0003633178766904166 ","PLTDECD = 19.0 / DEC at plate centre ","PLTDECM = 59.0 ","PLTDECS = 59.99544693467044 ","PLTDECSN= '+ ' ","PLTSCALE= 3600.0 / Plate scale (arcsec/mm) ","AMDX1 = 3600.0 / Plate solution x co-efficients ","AMDX2 = 0.0 ","AMDX3 = 0.0 ","AMDX4 = 0.0 ","AMDX5 = 0.0 ","AMDX6 = 0.0 ","AMDX7 = 0.0 ","AMDX8 = 0.0 ","AMDX9 = 0.0 ","AMDX10 = 0.0 ","AMDX11 = 0.0 ","AMDX12 = 0.0 ","AMDX13 = 0.0 ","AMDX14 = 0.0 ","AMDX15 = 0.0 ","AMDX16 = 0.0 ","AMDX17 = 0.0 ","AMDX18 = 0.0 ","AMDX19 = 0.0 ","AMDX20 = 0.0 ","AMDY1 = 3600.0 / Plate solution y co-efficients ","AMDY2 = 0.0 ","AMDY3 = 0.0 ","AMDY4 = 0.0 ","AMDY5 = 0.0 ","AMDY6 = 0.0 ","AMDY7 = 0.0 ","AMDY8 = 0.0 ","AMDY9 = 0.0 ","AMDY10 = 0.0 ","AMDY11 = 0.0 ","AMDY12 = 0.0 ","AMDY13 = 0.0 ","AMDY14 = 0.0 ","AMDY15 = 0.0 ","AMDY16 = 0.0 ","AMDY17 = 0.0 ","AMDY18 = 0.0 ","AMDY19 = 0.0 ","AMDY20 = 0.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","RADESYS","EQUINOX","DATE-OBS","CNPIX1","CNPIX2","PPO1","PPO2","PPO3","PPO4","PPO5","PPO6","XPIXELSZ","YPIXELSZ","PLTRAH","PLTRAM","PLTRAS","PLTDECD","PLTDECM","PLTDECS","PLTDECSN","PLTSCALE","AMDX1","AMDX2","AMDX3","AMDX4","AMDX5","AMDX6","AMDX7","AMDX8","AMDX9","AMDX10","AMDX11","AMDX12","AMDX13","AMDX14","AMDX15","AMDX16","AMDX17","AMDX18","AMDX19","AMDX20","AMDY1","AMDY2","AMDY3","AMDY4","AMDY5","AMDY6","AMDY7","AMDY8","AMDY9","AMDY10","AMDY11","AMDY12","AMDY13","AMDY14","AMDY15","AMDY16","AMDY17","AMDY18","AMDY19","AMDY20"]]]],["class_new_epoch",["NAXIS = 3","NAXIS1 = 20","NAXIS2 = 10","NAXIS3 = 10","CRPIX1 = 10","CRPIX2 = 5","CRPIX3 = 5","CRVAL1 = 1.102E11","CRVAL2 = 40.738","CRVAL3 = 62.933","CDELT1 = 39062.5","CDELT2 = -0.01","CDELT3 = 0.01","CTYPE1 = 'FREQ'","CTYPE2 = 'RA---TAN'","CTYPE3 = 'DEC--TAN'","CUNIT1 = 'Hz'","SPECSYS = 'SOURCE'","RESTFRQ = 1.10201354E11","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 52413.59"],"MJD 55000",[["FITS-WCS",1,24,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738000744648858 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.932998720660109 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size on axis 1 ","CDELT2 = -0.01 / Pixel size on axis 2 ","CDELT3 = 0.01 / Pixel size on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","SPECSYS = 'SOURCE ' / Standard of rest for spectral axis ","RESTFRQ = 110201354000.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","VELOSYS = 0.0 / [m/s] Topo. apparent velocity of rest frame "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","VELOSYS"]],["FITS-PC",1,21,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738000744648858 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.932998720660109 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel scale on axis 1 ","CDELT2 = -0.01 / Pixel scale on axis 2 ","CDELT3 = 0.01 / Pixel scale on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","RADECSYS","DATE-OBS"]],["FITS-IRAF",1,21,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738000744648858 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.932998720660109 / Value at ref. pixel on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","CD1_1 = 39062.5 / Transformation matrix element ","CD2_2 = -0.01 / Transformation matrix element ","CD3_3 = 0.01 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","CD1_1","CD2_2","CD3_3","RADECSYS","DATE-OBS"]],["FITS-AIPS",0,5,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS++",0,5,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-CLASS",1,27,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = -1354000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738000744648858 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.932998720660109 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size ","CDELT2 = -0.01 / Pixel size ","CDELT3 = 0.01 / Pixel size ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 54999.999233975963 / Modified Julian Date of observation ","DATE-OBS= '2009-06-17T23:58:53.816' / Date of observation ","RESTFREQ= 110201354000.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VELO-LSR= 7546.9121858340259 / [m/s] Reference velocity ","VLSR = 7546.9121858340259 / [m/s] Reference velocity ","DELTAV = -106.2645018012754 / [m/s] Velocity resolution ","AZIMUTH = 19.89061266963898 / [Deg] Telescope azimuth ","ELEVATIO= -18.685900717733542 / [Deg] Telescope elevation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","RESTFREQ","OBJECT","LINE","VELO-LSR","VLSR","DELTAV","AZIMUTH","ELEVATIO"]],["DSS",0,5,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]]]],["source_zsource",["NAXIS = 3","NAXIS1 = 10","NAXIS2 = 10","NAXIS3 = 20","CRPIX1 = 5","CRPIX2 = 5","CRPIX3 = 10","CRVAL1 = 10","CRVAL2 = 20","CRVAL3 = 1.4E9","CDELT1 = -0.001","CDELT2 = 0.001","CDELT3 = 1.0E6","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","CTYPE3 = 'FREQ'","CUNIT3 = 'Hz'","SPECSYS = 'SOURCE'","SSYSSRC = 'LSRK'","ZSOURCE = 8.0E-5","RESTFRQ = 1.420405752E9","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 52413.59"],"",[["FITS-WCS",1,26,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1000000.0 / Pixel size on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","SPECSYS = 'SOURCE ' / Standard of rest for spectral axis ","SSYSSRC = 'LSRK ' / Standard of rest for source redshift ","ZSOURCE = 8.0E-5 / [] Redshift of source ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","VELOSYS = 5000.6434165736428 / [m/s] Topo. apparent velocity of rest frame "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","SSYSSRC","ZSOURCE","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","VELOSYS"]],["FITS-PC",1,21,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CDELT3 = 1000000.0 / Pixel scale on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","SSYSSRC","ZSOURCE","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","RADECSYS","DATE-OBS"]],["FITS-IRAF",1,21,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","CD3_3 = 1000000.0 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","SSYSSRC","ZSOURCE","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","CD1_1","CD2_2","CD3_3","RADECSYS","DATE-OBS"]],["FITS-AIPS",0,5,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","SSYSSRC","ZSOURCE","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS++",0,5,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","SSYSSRC","ZSOURCE","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-CLASS",1,27,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = -20405752.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CDELT3 = 1000000.0 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","RESTFREQ= 1420405752.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VELO-LSR= 4330498.2468057619 / [m/s] Reference velocity ","VLSR = 4330498.2468057619 / [m/s] Reference velocity ","DELTAV = -211044.25696653035 / [m/s] Velocity resolution ","AZIMUTH = 290.32480248483148 / [Deg] Telescope azimuth ","ELEVATIO= 9.9069547263116213 / [Deg] Telescope elevation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","SSYSSRC","ZSOURCE","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","RESTFREQ","OBJECT","LINE","VELO-LSR","VLSR","DELTAV","AZIMUTH","ELEVATIO"]],["DSS",0,5,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","SSYSSRC","ZSOURCE","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]]]],["topocent",["NAXIS = 3","NAXIS1 = 10","NAXIS2 = 10","NAXIS3 = 20","CRPIX1 = 5","CRPIX2 = 5","CRPIX3 = 10","CRVAL1 = 10","CRVAL2 = 20","CRVAL3 = 1.4E9","CDELT1 = -0.001","CDELT2 = 0.001","CDELT3 = 1.0E6","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","CTYPE3 = 'FREQ'","CUNIT3 = 'Hz'","SPECSYS = 'TOPOCENT'","RESTFRQ = 1.420405752E9","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 52413.59"],"",[["FITS-WCS",1,24,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1000000.0 / Pixel size on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","SPECSYS = 'TOPOCENT' / Standard of rest for spectral axis ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","VELOSYS = 0.0 / [m/s] Topo. apparent velocity of rest frame "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","VELOSYS"]],["FITS-PC",1,21,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CDELT3 = 1000000.0 / Pixel scale on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","RADECSYS","DATE-OBS"]],["FITS-IRAF",1,21,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 1400000000.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","CD3_3 = 1000000.0 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","CD1_1","CD2_2","CD3_3","RADECSYS","DATE-OBS"]],["FITS-AIPS",0,5,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-AIPS++",0,5,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]],["FITS-CLASS",1,27,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 10.0 / Reference pixel on axis 3 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CRVAL3 = -20490360.973978996 / Value at ref. pixel on axis 3 ","CDELT1 = -10.0E-4 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CDELT3 = 999939.56501858868 / Pixel size ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","RESTFREQ= 1420405752.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VELO-LSR= 4325569.7965153586 / [m/s] Reference velocity ","VLSR = 4325569.7965153586 / [m/s] Reference velocity ","DELTAV = -211047.77728821337 / [m/s] Velocity resolution ","AZIMUTH = 290.32480248483148 / [Deg] Telescope azimuth ","ELEVATIO= 9.9069547263116213 / [Deg] Telescope elevation "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","RESTFREQ","OBJECT","LINE","VELO-LSR","VLSR","DELTAV","AZIMUTH","ELEVATIO"]],["DSS",0,5,["NAXIS = 3 ","NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","MJD-OBS = 52413.59 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT3","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS"]]]],["velolsr_late",["NAXIS = 3","NAXIS1 = 20","NAXIS2 = 10","NAXIS3 = 10","CRPIX1 = 10","CRPIX2 = 5","CRPIX3 = 5","CRVAL1 = 1.102E11","CRVAL2 = 40.738","CRVAL3 = 62.933","CDELT1 = 39062.5","CDELT2 = -0.01","CDELT3 = 0.01","CTYPE1 = 'FREQ'","CTYPE2 = 'RA---TAN'","CTYPE3 = 'DEC--TAN'","CUNIT1 = 'Hz'","SPECSYS = 'SOURCE'","RESTFRQ = 1.10201354E11","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 52413.59","FOO = 1","BAR = 2","VELO-LSR= 0.0","BAZ = 3"],"",[["FITS-WCS",1,28,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size on axis 1 ","CDELT2 = -0.01 / Pixel size on axis 2 ","CDELT3 = 0.01 / Pixel size on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","SPECSYS = 'SOURCE ' / Standard of rest for spectral axis ","RESTFRQ = 110201354000.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","VELOSYS = 0.0 / [m/s] Topo. apparent velocity of rest frame ","FOO = 1 ","BAR = 2 ","VELO-LSR= 0.0 ","BAZ = 3 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","VELOSYS","FOO","BAR","VELO-LSR","BAZ"]],["FITS-PC",1,25,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel scale on axis 1 ","CDELT2 = -0.01 / Pixel scale on axis 2 ","CDELT3 = 0.01 / Pixel scale on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","FOO = 1 ","BAR = 2 ","VELO-LSR= 0.0 ","BAZ = 3 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","RADECSYS","DATE-OBS","FOO","BAR","VELO-LSR","BAZ"]],["FITS-IRAF",1,25,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","CD1_1 = 39062.5 / Transformation matrix element ","CD2_2 = -0.01 / Transformation matrix element ","CD3_3 = 0.01 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","FOO = 1 ","BAR = 2 ","VELO-LSR= 0.0 ","BAZ = 3 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","CD1_1","CD2_2","CD3_3","RADECSYS","DATE-OBS","FOO","BAR","VELO-LSR","BAZ"]],["FITS-AIPS",0,9,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 ","FOO = 1 ","BAR = 2 ","VELO-LSR= 0.0 ","BAZ = 3 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","FOO","BAR","VELO-LSR","BAZ"]],["FITS-AIPS++",0,9,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 ","FOO = 1 ","BAR = 2 ","VELO-LSR= 0.0 ","BAZ = 3 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","FOO","BAR","VELO-LSR","BAZ"]],["FITS-CLASS",1,30,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = -1354000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size ","CDELT2 = -0.01 / Pixel size ","CDELT3 = 0.01 / Pixel size ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","RESTFREQ= 110201354000.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VLSR = 7546.9121858340259 / [m/s] Reference velocity ","DELTAV = -106.2645018012754 / [m/s] Velocity resolution ","AZIMUTH = 339.00226537612787 / [Deg] Telescope azimuth ","ELEVATIO= 17.470663568419475 / [Deg] Telescope elevation ","FOO = 1 ","BAR = 2 ","VELO-LSR= 7546.9121858340259 / [m/s] Reference velocity ","BAZ = 3 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","RESTFREQ","OBJECT","LINE","VLSR","DELTAV","AZIMUTH","ELEVATIO","FOO","BAR","VELO-LSR","BAZ"]],["DSS",0,9,["NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 ","FOO = 1 ","BAR = 2 ","VELO-LSR= 0.0 ","BAZ = 3 "],["NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","FOO","BAR","VELO-LSR","BAZ"]]]],["velolsr_dup",["VELO-LSR= 0.0","NAXIS = 3","NAXIS1 = 20","NAXIS2 = 10","NAXIS3 = 10","CRPIX1 = 10","CRPIX2 = 5","CRPIX3 = 5","CRVAL1 = 1.102E11","CRVAL2 = 40.738","CRVAL3 = 62.933","CDELT1 = 39062.5","CDELT2 = -0.01","CDELT3 = 0.01","CTYPE1 = 'FREQ'","CTYPE2 = 'RA---TAN'","CTYPE3 = 'DEC--TAN'","CUNIT1 = 'Hz'","SPECSYS = 'SOURCE'","RESTFRQ = 1.10201354E11","RADESYS = 'FK5'","EQUINOX = 2000.0","MJD-OBS = 52413.59","FOO = 1","VELO-LSR= 0.0","BAZ = 3"],"",[["FITS-WCS",1,28,["VELO-LSR= 0.0 ","NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size on axis 1 ","CDELT2 = -0.01 / Pixel size on axis 2 ","CDELT3 = 0.01 / Pixel size on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","SPECSYS = 'SOURCE ' / Standard of rest for spectral axis ","RESTFRQ = 110201354000.0 / [Hz] Rest frequency ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","VELOSYS = 0.0 / [m/s] Topo. apparent velocity of rest frame ","FOO = 1 ","VELO-LSR= 0.0 ","BAZ = 3 "],["VELO-LSR","NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","VELOSYS","FOO","VELO-LSR","BAZ"]],["FITS-PC",1,25,["VELO-LSR= 0.0 ","NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel scale on axis 1 ","CDELT2 = -0.01 / Pixel scale on axis 2 ","CDELT3 = 0.01 / Pixel scale on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","FOO = 1 ","VELO-LSR= 0.0 ","BAZ = 3 "],["VELO-LSR","NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","RADECSYS","DATE-OBS","FOO","VELO-LSR","BAZ"]],["FITS-IRAF",1,25,["VELO-LSR= 0.0 ","NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = 110200000000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","CUNIT1 = 'Hz ' / Units for axis 1 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","CD1_1 = 39062.5 / Transformation matrix element ","CD2_2 = -0.01 / Transformation matrix element ","CD3_3 = 0.01 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","FOO = 1 ","VELO-LSR= 0.0 ","BAZ = 3 "],["VELO-LSR","NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","CD1_1","CD2_2","CD3_3","RADECSYS","DATE-OBS","FOO","VELO-LSR","BAZ"]],["FITS-AIPS",0,9,["VELO-LSR= 0.0 ","NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 ","FOO = 1 ","VELO-LSR= 0.0 ","BAZ = 3 "],["VELO-LSR","NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","FOO","VELO-LSR","BAZ"]],["FITS-AIPS++",0,9,["VELO-LSR= 0.0 ","NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 ","FOO = 1 ","VELO-LSR= 0.0 ","BAZ = 3 "],["VELO-LSR","NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","FOO","VELO-LSR","BAZ"]],["FITS-CLASS",1,30,["VELO-LSR= 0.0 ","NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","CRPIX1 = 10.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 5.0 / Reference pixel on axis 3 ","CRVAL1 = -1354000.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 40.738 / Value at ref. pixel on axis 2 ","CRVAL3 = 62.933 / Value at ref. pixel on axis 3 ","CDELT1 = 39062.5 / Pixel size ","CDELT2 = -0.01 / Pixel size ","CDELT3 = 0.01 / Pixel size ","CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1 ","CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2 ","CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3 ","EQUINOX = 2000.0 / Epoch of reference equinox ","MJD-OBS = 52413.59 / Modified Julian Date of observation ","DATE-OBS= '2002-05-19T14:09:36.000' / Date of observation ","RESTFREQ= 110201354000.0 / [Hz] Rest frequency ","OBJECT = ' ' ","LINE = ' ' ","VLSR = 7546.9121858340259 / [m/s] Reference velocity ","DELTAV = -106.2645018012754 / [m/s] Velocity resolution ","AZIMUTH = 339.00226537612787 / [Deg] Telescope azimuth ","ELEVATIO= 17.470663568419475 / [Deg] Telescope elevation ","FOO = 1 ","VELO-LSR= 7546.9121858340259 / [m/s] Reference velocity ","BAZ = 3 "],["VELO-LSR","NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","DATE-OBS","RESTFREQ","OBJECT","LINE","VLSR","DELTAV","AZIMUTH","ELEVATIO","FOO","VELO-LSR","BAZ"]],["DSS",0,9,["VELO-LSR= 0.0 ","NAXIS = 3 ","NAXIS1 = 20 ","NAXIS2 = 10 ","NAXIS3 = 10 ","MJD-OBS = 52413.59 ","FOO = 1 ","VELO-LSR= 0.0 ","BAZ = 3 "],["VELO-LSR","NAXIS","NAXIS1","NAXIS2","NAXIS3","CRPIX1","CRPIX2","CRPIX3","CRVAL1","CRVAL2","CRVAL3","CDELT1","CDELT2","CDELT3","CTYPE1","CTYPE2","CTYPE3","CUNIT1","SPECSYS","RESTFRQ","RADESYS","EQUINOX","MJD-OBS","FOO","VELO-LSR","BAZ"]]]],["cname",["NAXIS = 2","NAXIS1 = 10","NAXIS2 = 10","CRPIX1 = 5","CRPIX2 = 5","CRVAL1 = 10","CRVAL2 = 20","CDELT1 = -0.001","CDELT2 = 0.001","CTYPE1 = 'RA---TAN'","CTYPE2 = 'DEC--TAN'","CNAME1 = 'Sky X'","RADESYS = 'FK5'","EQUINOX = 2000.0"],"",[["FITS-WCS",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CTYPE1 = 'RA---TAN' / Sky X ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","RADESYS = 'FK5 ' / Reference frame for RA/DEC values ","EQUINOX = 2000.0 / [yr] Epoch of reference equinox ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CNAME1","RADESYS","EQUINOX","MJD-OBS","DATE-OBS"]],["FITS-PC",1,15,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel scale on axis 1 ","CDELT2 = 0.001 / Pixel scale on axis 2 ","CTYPE1 = 'RA---TAN' / Sky X ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","MJD-OBS = 51544.499257130781 / Modified Julian Date of observation ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CNAME1","RADESYS","EQUINOX","RADECSYS","MJD-OBS","DATE-OBS"]],["FITS-IRAF",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Sky X ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EQUINOX = 2000.0 / Epoch of reference equinox ","CD1_1 = -0.001 / Transformation matrix element ","CD2_2 = 0.001 / Transformation matrix element ","RADECSYS= 'FK5 ' / Reference frame for RA/DEC values ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CNAME1","RADESYS","EQUINOX","CD1_1","CD2_2","RADECSYS","DATE-OBS"]],["FITS-AIPS",1,14,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Sky X ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CROTA2 = 0.0 / Axis rotation ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CNAME1","RADESYS","EQUINOX","CROTA2","EPOCH","DATE-OBS"]],["FITS-AIPS++",1,13,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRVAL1 = 10.0 / Value at ref. pixel on axis 1 ","CRVAL2 = 20.0 / Value at ref. pixel on axis 2 ","CDELT1 = -0.001 / Pixel size ","CDELT2 = 0.001 / Pixel size ","CTYPE1 = 'RA---TAN' / Sky X ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","EPOCH = 2000.0 / Epoch of reference equinox ","DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CNAME1","RADESYS","EQUINOX","EPOCH","DATE-OBS"]],["FITS-CLASS",0,3,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CNAME1","RADESYS","EQUINOX"]],["DSS",1,61,["NAXIS = 2 ","NAXIS1 = 10 ","NAXIS2 = 10 ","CNPIX1 = 1.0 / X corner (pixels) ","CNPIX2 = 1.0 / Y corner (pixels) ","PPO1 = 0.0 / Orientation co-efficients ","PPO2 = 0.0 ","PPO3 = 5.5 ","PPO4 = 0.0 ","PPO5 = 0.0 ","PPO6 = 5.5 ","XPIXELSZ= 1.0 / X pixel size (microns) ","YPIXELSZ= 1.0 / Y pixel size (microns) ","PLTRAH = 0.0 / RA at plate centre ","PLTRAM = 39.0 ","PLTRAS = 60.0 ","PLTDECD = 20.0 / DEC at plate centre ","PLTDECM = 0.0 ","PLTDECS = 1.2789769243681803E-11 ","PLTDECSN= '+ ' ","PLTSCALE= 3600.0 / Plate scale (arcsec/mm) ","AMDX1 = 3600.0 / Plate solution x co-efficients ","AMDX2 = 0.0 ","AMDX3 = 0.0 ","AMDX4 = 0.0 ","AMDX5 = 0.0 ","AMDX6 = 0.0 ","AMDX7 = 0.0 ","AMDX8 = 0.0 ","AMDX9 = 0.0 ","AMDX10 = 0.0 ","AMDX11 = 0.0 ","AMDX12 = 0.0 ","AMDX13 = 0.0 ","AMDX14 = 0.0 ","AMDX15 = 0.0 ","AMDX16 = 0.0 ","AMDX17 = 0.0 ","AMDX18 = 0.0 ","AMDX19 = 0.0 ","AMDX20 = 0.0 ","AMDY1 = 3600.0 / Plate solution y co-efficients ","AMDY2 = 0.0 ","AMDY3 = 0.0 ","AMDY4 = 0.0 ","AMDY5 = 0.0 ","AMDY6 = 0.0 ","AMDY7 = 0.0 ","AMDY8 = 0.0 ","AMDY9 = 0.0 ","AMDY10 = 0.0 ","AMDY11 = 0.0 ","AMDY12 = 0.0 ","AMDY13 = 0.0 ","AMDY14 = 0.0 ","AMDY15 = 0.0 ","AMDY16 = 0.0 ","AMDY17 = 0.0 ","AMDY18 = 0.0 ","AMDY19 = 0.0 ","AMDY20 = 0.0 "],["NAXIS","NAXIS1","NAXIS2","CRPIX1","CRPIX2","CRVAL1","CRVAL2","CDELT1","CDELT2","CTYPE1","CTYPE2","CNAME1","RADESYS","EQUINOX","CNPIX1","CNPIX2","PPO1","PPO2","PPO3","PPO4","PPO5","PPO6","XPIXELSZ","YPIXELSZ","PLTRAH","PLTRAM","PLTRAS","PLTDECD","PLTDECM","PLTDECS","PLTDECSN","PLTSCALE","AMDX1","AMDX2","AMDX3","AMDX4","AMDX5","AMDX6","AMDX7","AMDX8","AMDX9","AMDX10","AMDX11","AMDX12","AMDX13","AMDX14","AMDX15","AMDX16","AMDX17","AMDX18","AMDX19","AMDX20","AMDY1","AMDY2","AMDY3","AMDY4","AMDY5","AMDY6","AMDY7","AMDY8","AMDY9","AMDY10","AMDY11","AMDY12","AMDY13","AMDY14","AMDY15","AMDY16","AMDY17","AMDY18","AMDY19","AMDY20"]]]]] + } +} diff --git a/src/test/resources/oracle/fitschan_sipok.json b/src/test/resources/oracle/fitschan_sipok.json new file mode 100644 index 0000000..ae86e7f --- /dev/null +++ b/src/test/resources/oracle/fitschan_sipok.json @@ -0,0 +1,8 @@ +{ + "source": "crates/starlink-ast/tests/fitschan_sipok_oracle/cases.rs", + "generator": "tools/oracle_fixtures/fitschan_sipok_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["FITS-WCS","unset","wrote 1\nWCSAXES = 2 / Number of WCS axes \nCRPIX1 = 128.0 / Reference pixel on axis 1 \nCRPIX2 = 128.0 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN-SIP' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN-SIP' / Type of co-ordinate on axis 2 \nCDELT1 = 0.00033964735144229486 / Pixel size on axis 1 \nCDELT2 = -3.3997086485579845E-4 / Pixel size on axis 2 \nPC1_1 = 0.73534175730143447 / Transformation matrix element \nPC1_2 = 0.67769646595569466 / Transformation matrix element \nPC2_1 = -0.67778901984190687 / Transformation matrix element \nPC2_2 = 0.73525644817420499 / Transformation matrix element \nMJD-OBS = 51544.499257130781 / Modified Julian Date of observation \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \nRADESYS = 'ICRS ' / Reference frame for RA/DEC values \nA_0_2 = 2.9656E-6 / SIP forward distortion coeff \nA_0_3 = 3.7746E-9 / SIP forward distortion coeff \nA_1_1 = 2.1886E-5 / SIP forward distortion coeff \nA_1_2 = -1.6847E-7 / SIP forward distortion coeff \nA_2_0 = -2.3863E-5 / SIP forward distortion coeff \nA_2_1 = -8.561E-9 / SIP forward distortion coeff \nA_3_0 = -1.4172E-7 / SIP forward distortion coeff \nA_ORDER = 3 / SIP max order \nB_0_2 = 2.31E-5 / SIP forward distortion coeff \nB_0_3 = -1.6168E-7 / SIP forward distortion coeff \nB_1_1 = -2.4386E-5 / SIP forward distortion coeff \nB_1_2 = -5.7813E-9 / SIP forward distortion coeff \nB_2_0 = 2.1197E-6 / SIP forward distortion coeff \nB_2_1 = -1.6583E-7 / SIP forward distortion coeff \nB_3_0 = -2.0249E-8 / SIP forward distortion coeff \nB_ORDER = 3 / SIP max order \nAP_0_1 = -6.4275E-7 / SIP inverse distortion coeff \nAP_0_2 = -2.9425E-6 / SIP inverse distortion coeff \nAP_0_3 = -3.582E-9 / SIP inverse distortion coeff \nAP_1_0 = -1.4897E-5 / SIP inverse distortion coeff \nAP_1_1 = -2.225E-5 / SIP inverse distortion coeff \nAP_1_2 = 1.7195E-7 / SIP inverse distortion coeff \nAP_2_0 = 2.4146E-5 / SIP inverse distortion coeff \nAP_2_1 = 6.709E-9 / SIP inverse distortion coeff \nAP_3_0 = 1.4492E-7 / SIP inverse distortion coeff \nAP_ORDER= 3 / SIP inverse max order \nBP_0_1 = -1.6588E-5 / SIP inverse distortion coeff \nBP_0_2 = -2.3424E-5 / SIP inverse distortion coeff \nBP_0_3 = 1.651E-7 / SIP inverse distortion coeff \nBP_1_0 = -2.6783E-6 / SIP inverse distortion coeff \nBP_1_1 = 2.4753E-5 / SIP inverse distortion coeff \nBP_1_2 = 3.8917E-9 / SIP inverse distortion coeff \nBP_2_0 = -2.151E-6 / SIP inverse distortion coeff \nBP_2_1 = 1.7E-7 / SIP inverse distortion coeff \nBP_3_0 = 2.0482E-8 / SIP inverse distortion coeff \nBP_ORDER= 3 / SIP inverse max order \n"],["FITS-WCS","0","wrote 1\nWCSAXES = 2 / Number of WCS axes \nCRPIX1 = 129.355915 / Reference pixel on axis 1 \nCRPIX2 = 129.523318 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 \nCDELT1 = 0.00033410241877235324 / Pixel size on axis 1 \nCDELT2 = -3.3856370093867668E-4 / Pixel size on axis 2 \nPC1_1 = 0.7397898021575291 / Transformation matrix element \nPC1_2 = 0.67283805527312723 / Transformation matrix element \nPC2_1 = -0.67886307698836412 / Transformation matrix element \nPC2_2 = 0.73426488592461681 / Transformation matrix element \nMJD-OBS = 51544.499257130781 / Modified Julian Date of observation \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \nRADESYS = 'ICRS ' / Reference frame for RA/DEC values \n"],["FITS-WCS","1","wrote 1\nWCSAXES = 2 / Number of WCS axes \nCRPIX1 = 128.0 / Reference pixel on axis 1 \nCRPIX2 = 128.0 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN-SIP' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN-SIP' / Type of co-ordinate on axis 2 \nCDELT1 = 0.00033964735144229486 / Pixel size on axis 1 \nCDELT2 = -3.3997086485579845E-4 / Pixel size on axis 2 \nPC1_1 = 0.73534175730143447 / Transformation matrix element \nPC1_2 = 0.67769646595569466 / Transformation matrix element \nPC2_1 = -0.67778901984190687 / Transformation matrix element \nPC2_2 = 0.73525644817420499 / Transformation matrix element \nMJD-OBS = 51544.499257130781 / Modified Julian Date of observation \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \nRADESYS = 'ICRS ' / Reference frame for RA/DEC values \nA_0_2 = 2.9656E-6 / SIP forward distortion coeff \nA_0_3 = 3.7746E-9 / SIP forward distortion coeff \nA_1_1 = 2.1886E-5 / SIP forward distortion coeff \nA_1_2 = -1.6847E-7 / SIP forward distortion coeff \nA_2_0 = -2.3863E-5 / SIP forward distortion coeff \nA_2_1 = -8.561E-9 / SIP forward distortion coeff \nA_3_0 = -1.4172E-7 / SIP forward distortion coeff \nA_ORDER = 3 / SIP max order \nB_0_2 = 2.31E-5 / SIP forward distortion coeff \nB_0_3 = -1.6168E-7 / SIP forward distortion coeff \nB_1_1 = -2.4386E-5 / SIP forward distortion coeff \nB_1_2 = -5.7813E-9 / SIP forward distortion coeff \nB_2_0 = 2.1197E-6 / SIP forward distortion coeff \nB_2_1 = -1.6583E-7 / SIP forward distortion coeff \nB_3_0 = -2.0249E-8 / SIP forward distortion coeff \nB_ORDER = 3 / SIP max order \nAP_0_1 = -6.4275E-7 / SIP inverse distortion coeff \nAP_0_2 = -2.9425E-6 / SIP inverse distortion coeff \nAP_0_3 = -3.582E-9 / SIP inverse distortion coeff \nAP_1_0 = -1.4897E-5 / SIP inverse distortion coeff \nAP_1_1 = -2.225E-5 / SIP inverse distortion coeff \nAP_1_2 = 1.7195E-7 / SIP inverse distortion coeff \nAP_2_0 = 2.4146E-5 / SIP inverse distortion coeff \nAP_2_1 = 6.709E-9 / SIP inverse distortion coeff \nAP_3_0 = 1.4492E-7 / SIP inverse distortion coeff \nAP_ORDER= 3 / SIP inverse max order \nBP_0_1 = -1.6588E-5 / SIP inverse distortion coeff \nBP_0_2 = -2.3424E-5 / SIP inverse distortion coeff \nBP_0_3 = 1.651E-7 / SIP inverse distortion coeff \nBP_1_0 = -2.6783E-6 / SIP inverse distortion coeff \nBP_1_1 = 2.4753E-5 / SIP inverse distortion coeff \nBP_1_2 = 3.8917E-9 / SIP inverse distortion coeff \nBP_2_0 = -2.151E-6 / SIP inverse distortion coeff \nBP_2_1 = 1.7E-7 / SIP inverse distortion coeff \nBP_3_0 = 2.0482E-8 / SIP inverse distortion coeff \nBP_ORDER= 3 / SIP inverse max order \n"],["FITS-PC","unset","wrote 1\nPC001001= 0.7397898021575291 \nPC001002= 0.67283805527312723 \nPC002001= -0.67886307698836412 \nPC002002= 0.73426488592461681 \nCDELT1 = 0.00033410241877235324 / Pixel scale on axis 1 \nCDELT2 = -3.3856370093867668E-4 / Pixel scale on axis 2 \nCRPIX1 = 129.355915 / Reference pixel on axis 1 \nCRPIX2 = 129.523318 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 \nRADECSYS= 'ICRS ' / Reference frame for RA/DEC values \nMJD-OBS = 51544.499257130781 / Modified Julian Date of observation \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \n"],["FITS-PC","0","wrote 1\nPC001001= 0.7397898021575291 \nPC001002= 0.67283805527312723 \nPC002001= -0.67886307698836412 \nPC002002= 0.73426488592461681 \nCDELT1 = 0.00033410241877235324 / Pixel scale on axis 1 \nCDELT2 = -3.3856370093867668E-4 / Pixel scale on axis 2 \nCRPIX1 = 129.355915 / Reference pixel on axis 1 \nCRPIX2 = 129.523318 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 \nRADECSYS= 'ICRS ' / Reference frame for RA/DEC values \nMJD-OBS = 51544.499257130781 / Modified Julian Date of observation \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \n"],["FITS-PC","1","wrote 1\nPC001001= 0.7397898021575291 \nPC001002= 0.67283805527312723 \nPC002001= -0.67886307698836412 \nPC002002= 0.73426488592461681 \nCDELT1 = 0.00033410241877235324 / Pixel scale on axis 1 \nCDELT2 = -3.3856370093867668E-4 / Pixel scale on axis 2 \nCRPIX1 = 129.355915 / Reference pixel on axis 1 \nCRPIX2 = 129.523318 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 \nRADECSYS= 'ICRS ' / Reference frame for RA/DEC values \nMJD-OBS = 51544.499257130781 / Modified Julian Date of observation \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \n"],["FITS-IRAF","unset","wrote 1\nCRPIX1 = 129.355915 / Reference pixel on axis 1 \nCRPIX2 = 129.523318 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 \nCD1_1 = 0.00024716556228395115 / Transformation matrix element \nCD1_2 = 0.00022479682170883811 / Transformation matrix element \nCD2_1 = 0.00022983839577579834 / Transformation matrix element \nCD2_2 = -2.485954372479535E-4 / Transformation matrix element \nRADECSYS= 'ICRS ' / Reference frame for RA/DEC values \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \n"],["FITS-IRAF","0","wrote 1\nCRPIX1 = 129.355915 / Reference pixel on axis 1 \nCRPIX2 = 129.523318 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 \nCD1_1 = 0.00024716556228395115 / Transformation matrix element \nCD1_2 = 0.00022479682170883811 / Transformation matrix element \nCD2_1 = 0.00022983839577579834 / Transformation matrix element \nCD2_2 = -2.485954372479535E-4 / Transformation matrix element \nRADECSYS= 'ICRS ' / Reference frame for RA/DEC values \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \n"],["FITS-IRAF","1","wrote 1\nCRPIX1 = 129.355915 / Reference pixel on axis 1 \nCRPIX2 = 129.523318 / Reference pixel on axis 2 \nCRVAL1 = 202.48232280542899 / Value at ref. pixel on axis 1 \nCRVAL2 = 47.175118930010107 / Value at ref. pixel on axis 2 \nCTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 \nCTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 \nCD1_1 = 0.00024716556228395115 / Transformation matrix element \nCD1_2 = 0.00022479682170883811 / Transformation matrix element \nCD2_1 = 0.00022983839577579834 / Transformation matrix element \nCD2_2 = -2.485954372479535E-4 / Transformation matrix element \nRADECSYS= 'ICRS ' / Reference frame for RA/DEC values \nDATE-OBS= '2000-01-01T11:58:55.816' / Date of observation \n"],["FITS-AIPS","unset","wrote 0\n"],["FITS-AIPS","0","wrote 0\n"],["FITS-AIPS","1","wrote 0\n"],["FITS-AIPS++","unset","wrote 0\n"],["FITS-AIPS++","0","wrote 0\n"],["FITS-AIPS++","1","wrote 0\n"],["FITS-CLASS","unset","wrote 0\n"],["FITS-CLASS","0","wrote 0\n"],["FITS-CLASS","1","wrote 0\n"],["DSS","unset","wrote 0\n"],["DSS","0","wrote 0\n"],["DSS","1","wrote 0\n"]] + } +} diff --git a/src/test/resources/oracle/fitschan_splitmap.json b/src/test/resources/oracle/fitschan_splitmap.json new file mode 100644 index 0000000..2131021 --- /dev/null +++ b/src/test/resources/oracle/fitschan_splitmap.json @@ -0,0 +1,8 @@ +{ + "source": "crates/starlink-ast/tests/fitschan_splitmap_oracle/cases.rs", + "generator": "tools/oracle_fixtures/fitschan_splitmap_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["linear",1,["WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 0.0 / Reference pixel on axis 1 ","CRPIX2 = -150.0 / Reference pixel on axis 2 ","CRVAL1 = 11.459155902616466 / Value at ref. pixel on axis 1 ","CRVAL2 = 0.0 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---CAR' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--CAR' / Type of co-ordinate on axis 2 ","CDELT1 = -0.057295779513082325 / Pixel size on axis 1 ","CDELT2 = 0.11459155902616472 / Pixel size on axis 2 ","PV1_3 = 348.54084409738351 / Projection parameter ","RADESYS = 'ICRS ' / Reference frame for RA/DEC values ","LONPOLE = 348.54084409738351 / [deg] Longitude of native north pole "]],["linear_3d",1,["WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 0.0 / Reference pixel on axis 1 ","CRPIX2 = -150.0 / Reference pixel on axis 2 ","CRPIX3 = 1.0 / Reference pixel on axis 3 ","CRVAL1 = 11.459155902616466 / Value at ref. pixel on axis 1 ","CRVAL2 = 0.0 / Value at ref. pixel on axis 2 ","CRVAL3 = 7.0 / Value at ref. pixel on axis 3 ","CTYPE1 = 'RA---CAR' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--CAR' / Type of co-ordinate on axis 2 ","CTYPE3 = 'x3 ' / Type of co-ordinate on axis 3 ","CDELT1 = -0.057295779513082325 / Pixel size on axis 1 ","CDELT2 = 0.11459155902616472 / Pixel size on axis 2 ","CDELT3 = 3.0 / Pixel size on axis 3 ","PV1_3 = 348.54084409738351 / Projection parameter ","RADESYS = 'ICRS ' / Reference frame for RA/DEC values ","LONPOLE = 348.54084409738351 / [deg] Longitude of native north pole "]],["constant",1,["WCSAXES = 2 / Number of WCS axes ","CRPIX1 = 1.0 / Reference pixel on axis 1 ","CRPIX2 = 1.0 / Reference pixel on axis 2 ","CRVAL1 = 28.647889756541154 / Value at ref. pixel on axis 1 ","CRVAL2 = -14.323944878270581 / Value at ref. pixel on axis 2 ","CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1 ","CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2 ","CDELT1 = 0.0 / Pixel size on axis 1 ","CDELT2 = 0.0 / Pixel size on axis 2 ","PC1_1 = 0.0 / Transformation matrix element ","PC2_2 = 0.0 / Transformation matrix element ","RADESYS = 'ICRS ' / Reference frame for RA/DEC values "]]] + } +}