diff --git a/docs/reports/2026-11-16-phase4-report.md b/docs/reports/2026-11-16-phase4-report.md new file mode 100644 index 0000000..273dbd6 --- /dev/null +++ b/docs/reports/2026-11-16-phase4-report.md @@ -0,0 +1,187 @@ +# Pure-Java AST: phase 4 report + +## Summary + +Phase 4 ported the spectral and flux classes on 16 November 2026, following the plan [`2026-11-16-pure-java-ast-phase4-spectral.md`](../superpowers/plans/2026-11-16-pure-java-ast-phase4-spectral.md). +SpecMap, SpecFrame, DSBSpecFrame, FluxFrame and SpecFluxFrame now exist with jniast's public API, and `JniastApiTest` passes for all five with no exclusions. +`FitsChan.read()` now reads spectral axes from FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and FITS-CLASS headers, and `FitsChan.write()` writes them in each of those encodings. +Of the 194 rows of C's FITS conversion regression table (`ast_tester/fixtures/wcsconv/cases.txt`), 188 now give C's cards, against 118 at the start of the phase; the other six need MathMap (3), GrismMap (2) or SplineMap (1). +47 more headers of the transform oracle now read and transform as C's do, leaving 4, and nine C-probe oracle suites of the Rust port were converted and pass. +SpecFluxFrame converts only between equal components: pinned C builds a RateMap, a MathMap and a TranMap for every other conversion, unit changes included, and for a FluxFrame or SpecFrame that does not match a SpecFluxFrame directly, so those throw `needs RateMap`, and SPLAT's flux-axis conversions wait for the phase that ports those Mappings. +Porting found five places where C writes past a buffer or reads memory it never set, and a new route to the null dereference phase 3 found in `MakeFitsFrameSet`; the final review found a buffer overflow in SpecFrame's `GetSymbol` and a null dereference in CmpFrame's `Cast`; they are recorded in [`docs/rust-c-differences.md`](../rust-c-differences.md) and listed below. +Against the branch base the work adds 7,313 lines of main code and 9,118 lines of tests, and removes 265 and 1,237; `mvn verify` passes with 3,229 tests on JDK 21, and the tests pass on the JDK 27 runtime. + +## What was ported + +| Task | What | Main lines | Test lines | +| --- | --- | ---: | ---: | +| 1 | `SpecMap`: every conversion of C's `specmap.c`, its `MapMerge`, rate and dump, 1-D and 3-D | 1,106 | 769 | +| 2 | `SpecFrame` attributes, defaults, the Unit used with each System, Label, Symbol, Title, `Overlay`, dump and loader | 2,059 | 1,193 | +| 3 | `SpecFrame` conversions (`Match`, `SubFrame`, `MakeSpecMapping`), SpecOrigin and AlignSpecOffset | 347 | 1,250 | +| 4 | `DSBSpecFrame`, with the cast of a DSBSpecFrame template into a SpecFrame | 851 | 1,079 | +| 5 | `FluxFrame`, with `MakeFluxMapping` | 913 | 1,250 | +| 6 | `SpecFluxFrame`, as far as C goes without RateMap, MathMap and TranMap | 348 | 922 | +| 7 | Reading spectral axes (`FitsWcsSpectral`, C's `WcsSpectral` and its helpers) | 542 | 1,195 | +| 8 | Writing spectral axes (`FitsSpectralAxes`, C's `SpectralAxes`; the SpecFrame parts of `MakeFitsFrameSet` and `AddEncodingFrame`) | 635 | 1,024 | +| 9 | FITS-CLASS: C's `ClassTrans` on reading and the whole of `CLASSFromStore` on writing (`FitsEncClass`) | 430 | 541 | +| 10 | The remaining Rust tests, and a guard on `CLASSFromStore`'s array over-run | 9 | 65 | +| 11 | Sweep of the deferred lists: nothing left to change | 0 | 0 | +| 12 | This report | | | + +Lines are those each task's commits add, the controller's fix commits included; summed, they exceed the branch totals by the lines a later task changed again. +Each of Tasks 1 to 10 was done by one implementer subagent, reviewed by a second, 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). +The reviews found no Critical problem and one Important one (Task 3: the velocity chains of `MakeSpecMapping` lacked a final `else` throwing `AST__INTER`); it and the minor findings taken up were fixed by the controller. +Expected values that no fixture or oracle held were taken from probes run against the pinned C library; the probe sources were kept with the execution record. +The probes behind the oracles converted in Tasks 3 to 6 were rebuilt against the pinned library and gave the committed values. +The tasks were committed between 08:29 and 13:06 on 16 November. + +## Departures from the plan + +The [rulings](2026-11-16-phase4-rulings.md) give each with its reason and cost; these change what later work builds on. + +- **A Unit of another kind leaves the System alone.** + Review Focus 2 says that setting a SpecFrame's Unit to a unit of another kind changes its System; C's SpecFrame `SetUnit` records the Unit for the current System and never changes the System, so the tests follow C. + (A FluxFrame with no System set does take its System from its Unit, as C's `GetSystem` does.) +- **SpecFluxFrame needs RateMap, for nearly every conversion.** + The plan has `MakeMapF` and `MakeMapI` throw `needs MathMap`; both build a RateMap before the MathMap, so they throw `needs RateMap`, the first absent class C builds. + The plan expected unit changes to convert without them, but pinned C's `MakeSFMapping` short-circuits only when both components are equal, and every other conversion whose standardised SpecFrames convert (Jy to mJy, GHz to MHz, FREQ to WAVE) reaches `MakeMapF`. + What works is what works in C without those classes: equal or swapped components, picking axes, FrameSet searches through CmpFrame's `Match`, and dumps. + The part of `MakeSFMapping` after `MakeMap3` cannot be reached and is not ported. +- **Upstream fixes already in the pin.** + The plan treated the FluxFrame `SFCBRW` name and the default reference value of `SpectralAxes` as fixed after the pin, to be recorded and not followed, and the Rust port's quirk file marks FITS-CLASS's LONPOLE of ±180° and its spectral CDELT scaling the same way. + The pinned C has all four, under other commit names where the Rust file's are not in its history: `3b1f3f5a` (Rust's `b4457da9`), `0dfd0f74` (`e09bc221`), `a66a0cb5` (`aea3090b`) and `17416d33`; so do the AlignSpecOffset fix of `MakeSpecMapping` (`58ba2441`, Rust's `65bd5b6e`) and two `IsMapLinear` and `AddVersion` fixes (`d2c047eb`, `12e9ed4a`). + C, Rust and Java agree on each, and `docs/rust-c-differences.md` says so. +- **`AddEncodingFrame` came with the spectral write.** + Task 8 ported it with `MakeFitsFrameSet`'s SpecFrame parts rather than leaving it to Task 9, since without it a FITS-CLASS write fails `CLASSFromStore`'s SPECSYS check where C writes. +- **The grism write builds nothing.** + Reading a `-GRI` or `-GRA` axis throws `needs GrismMap`, as planned, but C's write extracts a GrismMap already in the FrameSet and builds none; a FrameSet of this library's classes holds none, so the write makes C's System and Unit trials through the FrameSet and falls through to the next algorithm. +- **The SpecMap correction factor is part of the dump.** + C's 1-D SpecMap works out its frequency correction factor when it first transforms, stores it among the step's arguments and dumps it, so `SimplifyRegressionTest` now takes its dumps before it transforms anything. + +## Gates + +| Gate | Before | After | +| --- | --- | --- | +| `wcsconv/cases.txt` rows giving C's cards | 118 of 194 | 188 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 | NATIVE 103/107, FITS-WCS 24/26, FITS-AIPS 17/17, FITS-AIPS++ 18/18, FITS-IRAF 9/9, FITS-PC 5/5, DSS 1/1, AST 2/2, FITS-CLASS 9/9 | +| `wcsconv.txt` entries | 76: SpecFrame 63, FITS-CLASS 6, DSBSpecFrame 4, MathMap 2, SplineMap 1 | 6: MathMap 3 (`freq-log_native`, `polco_native`, `polco2_native`), GrismMap 2 (`grism_native`, `grism_fits-wcs`), SplineMap 1 (`lsst2_fits-wcs`) | +| `headers.txt` entries (transform oracle) | 51: SpecFrame 45, FITS-CLASS 4, MathMap 2 | 4: MathMap 3 (`freq-log`, `polco`, `polco2`), GrismMap 1 (`grism`) | +| `framesets.txt` entries | 69 | 10 | +| `full-dumps.txt` entries | 476 | 365 | +| `read-warnings.txt` entries | 495 | 384 | +| `serialisation.txt` entries | 490 | 383 | +| `simplify-cases.txt` entries | 288 | 255 | +| `simplify.txt` entries | 407 | 356 | +| `rust-tests.txt` entries | 376 | 336, after adding 11: seven `astEqual` tests of SpecMap, SpecFrame and FluxFrame, three of a Rust-only DSBSpecFrame function, one Rust unit test that builds a GrismMap | +| `FitsChanCursorOracleTest` cases run | 247 | 257 | +| `FitsChanErrorsTest` cases run | 27 | 34 | +| `FitsChanEncodingsOracleTest` cases excluded | 9 | 0 | +| Tests | 2,829 | 3,229 | + +No deferred entry names a class this phase adds or the FITS-CLASS encoding, and rewriting the lists with `-Dast.writeDeferred=true` changes nothing. +New C-probe oracle suites, converted from the Rust port's `cases.rs` with `CasesToJson`: `SpecMap3dOracleTest`, `SpecConvertOracleTest` (208 cases), `SpecOriginSorOracleTest` (16), `DsbTopoOracleTest`, `FluxBadunOracleTest`, `FluxUnitSystemOracleTest`, `SpecFluxCmpOracleTest`, `SpecFluxPrimaryOracleTest` and `FitsChanSpecUnitOracleTest` (two cases need MathMap, listed and checked both ways). +Cases of earlier oracles that waited for these classes now run: 646 values and 46 dumps of `ClassAttrsTest` (the dumps byte for byte, and read back), 1,280 of `FrameClassAttrsTest`, 1,104 of `FrameAxisAttrsTest`, and `MatchAxesTest` 36 to 144, `OverlayTest` 6 to 13, `FrameSetIntegrityTest` 13 to 21, the conversions of `SpecUseDefsTest` 4 to 28. + +The Review Focus tests: + +1. `SpecFrameTest` converts with each attribute a standard of rest needs left unset (RefRA, RefDec, Epoch, the observer, SourceVel, StdOfRest, RestFreq): with UseDefs set, 11 cases give C's values; with it cleared, 12 give `AST__NOVAL` with C's message. +2. `SpecFrameTest` sets Units of another kind as C's `SetUnit` takes them, and checks C's `AST__BADUN` errors for a SpecOrigin that cannot be expressed in them. +3. `SpecFrameTest` dumps three SpecFrames before and after conversions and `findFrame` both ways, failing ones included, and after FrameSet searches; two threads converting their own copies 50 times get the single-thread Mapping. +4. Each class's Channel dump is compared with C's byte for byte (the `class_attrs` dumps, `serialisation/specframe.ast`, `jan-dsb.ast`, `specfluxframe_swapped.native`) and read back; NATIVE FitsChan cards of SpecFrames and DSBSpecFrames are compared with C's through the `wcsconv` NATIVE rows of the spectral headers. +5. `FitsWcsSpectralTest` reads `-LOG`, `-GRI`, `-GRA` and `-TAB` axes and gets `needs MathMap`, `needs GrismMap` and `needs LutMap`; `FitsChanWriteTest` writes a spectral cube in FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS and FITS-AIPS++ and reads it back to C's values, and round-trips every in-scope spectral and FITS-CLASS header, expecting C's outcome where C's own round trip fails or differs. + +## Tolerances and excuses + +Removed: none. +Added: + +| Where | What | Measured size and cause | +| --- | --- | --- | +| `SpecConvertOracleTest`, `SpecOriginSorOracleTest`, `DsbTopoOracleTest`; the probe values of `SpecFrameTest` and `DSBSpecFrameTest` | Within libm rounding (`CValues.cValueEq`: 1e-13 relative plus 1e-14), the rule the library has used for C values since phase 1 | Not measured per value; the 3-D SpecMap oracle, the SpecFrame unit-mapper cases and the flux and SpecFluxFrame oracles are compared exactly and match bit for bit | +| `SpecMapTest` correction factor | The factor C dumps in fixture `cap_specmap_06.map`, within libm rounding | Computed through PAL's velocity routines with runtime Math; not traced further | +| `SpecMapTest` translated Rust tests | Round trips and textbook formulae within the Rust tests' 1e-10 to 1e-12 relative | These are the Rust tests' own property checks, not C values; C's values for the same conversions are checked by the oracle suites | +| `SpecFrameTest` testspecframe.c errors | testspecframe.c's own tolerances (Error 13 within 1e-6), with C's value within libm rounding where the probe gives one | C's test | +| `FitsChanWcsTest` rows of `class-noproj`, `crota-3d`, `axes-swap` | The Rust tests' tolerances (1e-12 relative; for `class-noproj` 1e-3 Hz and 1e-9 rad forward, 1e-6 pixels inverse) | The same headers pass the transform-oracle gate | +| `FitsSpectralAxesTest` galactic reference position | CDELT2 within 1e-16 and PC within 1e-12 absolute; VELOSYS, CRVAL and the spectral cards exact | Up to 7e-17 and 6e-13: the same differences as C and Java give writing the same celestial axes without the spectral axis (C probe), from `FitLine` over SphMap and SlaMap transforms whose sines and arctangents are 1 ULP from libm, phase 3's cause | +| `FitsChanWriteTest.spectralCubeRoundTripsInEachEncoding` | Read-back values within 4 ULP of C's, as the `wcsconv` gate | Runtime Math; not traced per value | +| `FitsChanEncodingsOracleTest` FITS-CLASS `source_zsource`, `topocent` | ELEVATIO within the existing 4-ULP card gate | 1 ULP: the reference pixel's declination is 1 ULP from C's through `Math.atan2`; the AZEL conversion from it is bit-identical (traced with a C probe and Java on the same chain) | +| `FitsChanCInlineTest.azelWritesAsFitsWcs`, `FitsChanEncodingsOracleTest.writesMatchC` | Run on a fresh thread (`testsupport/FreshThread`) | C's table of local apparent sidereal times, ported per thread, is filled by earlier conversions with an observer, which reading spectral headers now makes; on the test runner's thread CRVAL moved by about 1e-6° and ELEVATIO by 14 ULP, where C's probes start with empty tables | + +## Defects found in the C library + +All are in the pinned library (`3d3f255f`); "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 writes the whole text where C overruns a buffer, uses 0 where C reads a value it never set, throws `AstException` with `AST__INTER` where C writes past an array, and makes no FrameSet where C dereferences the null one. + +| Where | Defect | Confirmed | +| --- | --- | --- | +| `fluxframe.c` `Dump` | Formats "Preferred units for" and the System's label into `comm[50]`; for SFCBRW that is 55 characters, a stack-buffer overflow | Probe (AddressSanitizer); still present at the tip of PR #104 (`1be1c664`) | +| `specfluxframe.c` `GetTitle` | Formats " versus " into a static 101-character buffer, so Labels longer than 92 characters between them overrun it | Reading | +| `ClassTrans` | Computes the source velocity from `crval` when the spectral CRVAL was never read (one-axis headers such as `class-spec.head`) | Reading; C's recorded `wcsconv` outputs encode 0 | +| `CLASSFromStore` | Scales `cdelt[axspec]` past its array when the spectral axis is not among the axes with a CRPIX (latent: every axis of a FrameSet written has one) | Reading | +| `CLASSFromStore` | Reads the `crval` elements of axes its CRVAL loop did not reach, for the velocity, AZIMUTH and ELEVATIO cards (latent: the write has already failed) | Reading | +| `MakeFitsFrameSet`, `AddEncodingFrame` | A world Frame holding two SpecFrames, or a SpecFrame whose reference position gives no celestial FrameSet, makes no FrameSet, and the null FrameSet is then dereferenced (phase 3 found the two-SkyFrame route) | Probe (crash in `astGetFrame_`); fixed in PR #104 by `5a3e23e3`, where the probe's write returns 0 | +| `specframe.c` `GetSymbol` | Copies a Symbol modified by the Unit into a static 21-character buffer with `strcpy`; System `WAVN` with Unit `nm` overflows it, as does a NATIVE write of a header with `CTYPE1 = 'WAVN'` and `CUNIT1 = 'nm'`; `fluxframe.c` `GetSymbol` has the same pattern | Probe (SIGTRAP from the fortified `strcpy`) for SpecFrame; reading for FluxFrame | +| `cmpframe.c` `Cast` | Compares classes through CmpFrame's `class_vtab`, set only when a plain CmpFrame is first made, so in a process with SpecFluxFrames but no CmpFrame a failed SpecFluxFrame match dereferences null in `astClassCompare` | Probe (SIGSEGV converting a SpecFluxFrame whose SpecFrame has Domain `FOO`; with one CmpFrame made first, C finds no conversion, as Java does) | + +`SpectralAxes` shares `OtherAxes`'s use of a FitsTable that was never made, for a `-TAB` Mapping without table columns (phase 3); Java throws `needs FitsTable` there as it does for `OtherAxes`, though the entry in `docs/rust-c-differences.md` names only `OtherAxes`. + +Kept as C has them, since they are defined: SpecMap's axis-count message saying "1 or 2"; an overflow in six SpecMap conversions giving an infinity where the others give a bad value; SpecFrame's `Overlay` onto another class clearing the Title, Label, Symbol and, usually, the Unit with the System, and its `SubFrame` clearing the System after setting them; an aligned DSBSpecFrame conversion leaving the target's SideBand set; any setting containing `dsbcentre=` taken for DSBCentre; `GetLO`'s message always giving a DSBCentre of 3e+10 Hz and naming `astGetImagFreq`; FluxFrame's `Overlay` changing the template it is given; the Unit a FluxFrame records keeping its trailing spaces; the `-GLS` code of `ClassTrans` not seen by the later GLS translation. + +## Final review + +A fresh reviewer read the whole branch against the plan, the spec's phase rules, the rulings and C, and ran a differential fuzz of the branch against the pinned C build. + +- Frames: 11,900 random cases of SpecFrame, DSBSpecFrame, FluxFrame and SpecFluxFrame, alone and mixed, each with up to 11 settings, valid and invalid, in random order, with UseDefs set and cleared. + Each compared the status of every setting, 23 to 28 attribute values, the Channel dump, NATIVE FitsChan cards and their read-back, `convert` both ways and `findFrame` with 8 points transformed both ways, the dumps of both Frames given after each call, and FrameSet integrity after settings made through a FrameSet. +- FITS: 5,252 headers mutated from the 63 spectral `wcsconv` inputs (every algorithm code, the standard-of-rest, source, rest-frequency, unit, reference, date, observer and FITS-CLASS keywords, deleted cards), read with AUTO or a random encoding, transformed both ways, written in FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++, FITS-CLASS and NATIVE, the cards compared to 1e-9 relative, and each written header read back. + +Statuses, cards, dumps and values agreed with C apart from the findings below, the `needs ` refusals the phase rules require, and the state an object is left in after an error. +The Review Focus checks: + +1. Unset RefRA, RefDec, Epoch, observer and SourceVel, with UseDefs set and cleared: every fuzz conversion gave C's values or C's status; the one silent velocity difference was on FITS reading (I2). +2. Unit on a SpecFrame axis: C's behaviour (no System change, C's AST__BADUN errors) throughout. +3. The dumps of the Frames given to `convert` and `findFrame` matched C's after every successful call, and 8 threads converting copies of a topocentric DSBSpecFrame pair and a FluxFrame pair 64 times got identical Mappings, values and dumps. +4. Channel dumps and NATIVE cards of all five classes matched C's byte for byte, white space aside, and read back to the same dump. +5. Every header needing an absent class gave `needs MathMap` or `needs GrismMap`, reading or writing, and `-TAB` gave C's AST__BDFTS with TabOK 0. + +Findings, and what the fix pass did: + +- **I1** (important): CmpFrame's `cast` did not follow cmpframe.c's `Cast`, which copies a CmpFrame into any class of the CmpFrame family (`astCastCopy`), a subclass included. + A SpecFluxFrame that matched no CmpFrame threw AST__INTER where C finds no conversion, and a FluxFrame or SpecFrame that did not match a SpecFluxFrame directly (13 fuzz cases) found no conversion where C casts the CmpFrame of its match into a SpecFluxFrame and reaches `MakeSFMapping`. + Fixed in "Cast SpecFluxFrames as C's CmpFrame Cast does": those cases now give C's null, `needs RateMap` (C builds its RateMap) or C's AST__ATSER, and the 13 fuzz cases give C's outcome; `SpecFluxFrameTest` checks them against C probes. +- **I2** (important): reading a header with one celestial CRVAL dropped the other reference coordinate as well, so the SpecFrame had neither RefRA nor RefDec, its standard-of-rest conversions differed from C's, and a FITS-WCS write gave VELOSYS -24443.52 m/s where C writes 28372.57 m/s (11 fuzz headers). + Fixed in "Keep a SpecFrame's reference coordinates separate on read": `WcsCelestial` returns the two coordinates separately, as C does, and only SkyRef needs both; `FitsWcsSpectralTest` checks C's RefRA, conversion and VELOSYS, and the 11 headers now give C's cards. +- **M1** (minor): when re-expressing the SpecOrigin or SourceVel fails, setting or clearing StdOfRest, SourceVRF or SourceSys throws in both, but C stores the new value and Java keeps the old one. + Ruled: Java keeps the old value; C's behaviour is recorded as a C quirk in `docs/rust-c-differences.md`. +- **M2** (minor): SpecFluxFrame's Javadoc and the gap below now say that FluxFrame and SpecFrame to SpecFluxFrame conversions need RateMap too. +- **M3** (minor, deferred): one FITS-CLASS write differs at the edge of `IsMapLinear`'s tolerance: header `h00886` of the fuzz (VOPT-F2W at 0.001 m/s per channel) has a residual of 5.63e-5 pixels against a tolerance of 4.99e-5, so Java rejects the linear fit and writes nothing where C writes the header; this is rounding in an ill-conditioned fit, the runtime-Math margin listed below. + +The review also found the two C defects added to the table above, and three C quirks of the state left after an error, which Java does not copy: `astFindFrame` leaves PreserveAxes set on a component of the template after an error, a Channel write that fails part way leaves its indentation raised for later writes, and `ClassTrans`'s uninitialised `crval` (already ruled) shows as SRCVEL_A = -299792458 m/s in C for one-axis WAVE headers with RESTFRQ 0. +After the fix pass the fuzz cases of I1 and I2 agree with C, and the full suite passes with 3,229 tests. + +## Gaps and risks + +- **SpecFluxFrame converts only equal components.** + Every other SpecFluxFrame conversion, every conversion between a SpecFluxFrame and a FluxFrame or SpecFrame that do not match directly (a FluxFrame in another flux System, say), and the integrity of a FrameSet whose current Frame is a SpecFluxFrame after its Unit or System changes, throws `needs RateMap` where C converts; SPLAT's flux-axis conversions wait for RateMap, MathMap and TranMap, and the rest of `MakeSFMapping` must then be ported from C. + Review Focus 3's two-thread check covers SpecFrame only. +- **Spectral axes that need absent Mappings.** + A `-LOG` spectral axis with a non-zero CRVAL needs MathMap to read and to write, as do logarithmic units (`log(Hz)`, `log(Jy)`); a `-GRI` or `-GRA` axis needs GrismMap to read, and C's `ExtractGrismMap` is to be ported with it; a `-TAB` axis needs LutMap to read with TabOK set and FitsTable to write. + These, with the MathMap of `polco` and the SplineMap of `lsst2`, are the six `wcsconv` rows and four headers still deferred. +- **No `astEqual`.** + 108 Rust tests wait for it, seven of them added this phase; SpecFluxFrame carries a private port of the comparison `MakeSFMapping` makes. +- **Order-dependent AZEL values.** + C's per-observer table of local apparent sidereal times is ported as C has it, per thread, so AZEL results depend on what the thread converted before; reading spectral headers with an observer now fills it, and tests comparing AZEL values with C's run on a fresh thread. +- **Runtime-Math margins.** + The galactic PC elements of `FitsSpectralAxesTest` differ by 6e-13 against a limit of 1e-12, a margin of under two; another JDK or libm could use it up. + A FITS-CLASS write near `IsMapLinear`'s tolerance can succeed in C and fail here (M3 above). +- **FITS-CLASS headers that do not write back.** + `class-noproj`, `class-spec` and `class-spec-hel` write nothing into a new FitsChan, as in C; why was not investigated. +- **Probe sources outside the repository.** + The test Javadocs of Tasks 2 to 4 cite C probes kept in the git-ignored execution workspace (`.superpowers/sdd/.../task-N-probes`; `DSBSpecFrameTest` names `task-4-probes/dsb_cases.c`, `SpecFrameTest` `spec_convert_cases.c`), so those expected values cannot be regenerated from the repository; from Task 5 on the tests name the C function or fixture instead. +- **Runtimes.** + The tests were run on JDK 21 and on the JDK 27 runtime, not on a Java 8 runtime. + +## Rulings + +Every decision made while executing the plan where it was wrong, unclear or silent, every departure from Rust or C and every C quirk kept is in [`2026-11-16-phase4-rulings.md`](2026-11-16-phase4-rulings.md), with its reason and its cost if wrong: 104 rulings, 96 by the implementers and 8 by the controller. diff --git a/docs/reports/2026-11-16-phase4-rulings.md b/docs/reports/2026-11-16-phase4-rulings.md new file mode 100644 index 0000000..6ea7c3d --- /dev/null +++ b/docs/reports/2026-11-16-phase4-rulings.md @@ -0,0 +1,173 @@ +# Phase 4: rulings + +These are the decisions made while executing the phase 4 plan ([`2026-11-16-pure-java-ast-phase4-spectral.md`](../superpowers/plans/2026-11-16-pure-java-ast-phase4-spectral.md)) where the plan was wrong, unclear or silent, or where the port departs from Rust or C or keeps a C quirk. +They are copied from the execution ledger (the controller's rulings) and from each task's report (the implementer's rulings), grouped by task; within a task the implementer's come first, in the order of the report, then the controller's, in the order they were made. +Each gives what was decided, why, and what it costs if wrong. +A later ruling can reverse an earlier one. +There are 104 rulings. +The phase report is [`2026-11-16-phase4-report.md`](2026-11-16-phase4-report.md). + +## Plan review + +- Ruling: execute without a separate plan review — the user asked to "do the next phase" after approving phase 3's identical process — cost if wrong: the user redirects the plan mid-phase. + +## Task 1 + +- Ruling: the 1-D frequency correction factor is stored in the step's argument slot during `transformInto` and written by Dump, as C's `FrameChange` does (Rust keeps a separate unwritten cache) — C fixtures carry these cards and SpecFrame/FitsChan dumps must match C — cost if wrong: dumps after a transform gain cards Rust's lack; recorded in `docs/rust-c-differences.md`. +- Ruling: `SimplifyRegressionTest` takes its dumps before transforming (second read of the input for the "computes the same" check) — the old ordering asserted an invariant C itself does not satisfy for SpecMaps — cost if wrong: a simplify that mutates the input only through a transform-time cache would go unnoticed (the dump-unchanged and computes-unchanged checks are otherwise intact). +- Ruling: `tests/test_specmap.rs::equality` deferred as `astEqual (out-of-scope method)` — C's `Equal` has no Java consumer and TimeMap's `equality` is deferred the same way — cost if wrong: SpecMap `Equal` must be added when something (e.g. a later CmpMap/FrameSet comparison) needs it. +- Ruling: inputs that are not finite (NaN, infinities, on all three axes of a 3-D map) become AST__BAD when copied, while each step otherwise tests `!= AST__BAD` exactly as C — project rule "Infinite input coordinates" and the no-NaN-output tests — cost if wrong: differs from C only for non-finite inputs. +- Ruling: no final non-finite-to-bad pass (Rust's SP-4), so an ENTOFR/FRTOEN/WNTOFR/FRTOWN/BTTOVL/VLTOBT overflow gives an infinity as in C — follow C — cost if wrong: an infinity reaches callers where Rust gives AST__BAD; recorded in `docs/rust-c-differences.md`. +- Ruling: C quirk kept: `astInitSpecMap`'s AST__BADNI message says "it should be 1 or 2" (trailing space included) — keep C's text — cost if wrong: message text only; recorded as a C quirk. +- Ruling: load errors are AST__BADIN with C's messages (Rust: AST__SPCIN) — follow C — recorded. +- Ruling: `MapMerge` cancels a pair when the second code is the first's inverse and the first `nargs` arguments are astEQUAL — this is exactly the union of C's five `PAIR_CVT2` groups (0, 1, 2, 3 and 6 user arguments, 17 pairs) — cost if wrong: none found; every simplify fixture with SpecMaps now matches C. +- Ruling: `Rate` tests `at[0] != AST__BAD` exactly as C, not `isBad` — follow C. +- Ruling: `Cvt.inverse()` pairs each odd C code with the next even one, the pairing C's SWAP macros spell out; the change-of-rest-frame sign is likewise taken from the code's parity (odd = to heliocentric = -1), matching each `case` of C's `FrameChange`. + +## Task 2 + +### Implementer + +- Ruling: jniast's `getSourceVRF()` and `setSourceVRF(double)` kept with jniast's signatures and bodies (`getD`/`setD` of a string attribute, so they always fail, AST__ATGER and AST__ATTIN) — the public API must be exactly jniast's — cost if wrong: none beyond jniast's own; callers use `getC`/`setC("SourceVRF", ...)` as with jniast. +- Ruling: SpecFrame `Overlay` onto a non-SpecFrame result follows C: a copy with System and AlignSystem cleared is overlaid, and when that changes the copy's System its Title, Label, Symbol (and Unit unless one was used with WAVE) are cleared and not overlaid; Rust overlays them; recorded in `docs/rust-c-differences.md` as a C quirk — cost if wrong: a plain Frame made from a SpecFrame template keeps C's lost Title where a reader might expect it. +- Ruling: Review Focus 2 is tested as specframe.c's code gives it: `SetUnit` stores a Unit of another kind and leaves the System alone (C has no System change on SetUnit; the plan's "changes System" wording does not match C), the Label/Symbol keep their defaults, and a SpecOrigin cannot be set (`ToUnits`) or read (`GetSpecOriginCur`) with AST__BADUN and C's messages; these expectations are read from the C source, not a probe run, while the C-oracle cases NewUnitTest spec_* and SystemChangeTest spec_* cover unit changes and restoration — cost if wrong: two SpecFrameTest tests would encode a misreading of C. +- Ruling: `OriginSystem`, `OriginStdOfRest`, `ConvertSourceVel`, `SorConvert` and `EqualSor` are ported in Task 2 because C's attribute setters call them; `OriginSystem`/`OriginStdOfRest` go through `convert`, whose SpecFrame `match`/`subFrame` are Task 3's, so no Task 2 test changes System or StdOfRest with a SpecOrigin set — cost if wrong: until Task 3 such a change re-expresses the SpecOrigin through Frame's matching (wrong value or AST__ATSER). +- Ruling: the used-units record is a fixed `String[11]` indexed by System code where C grows an array to `nuunits`; dumps, copies and restores are the same — cost if wrong: none visible. +- Ruling: the FK5 J2000 SkyFrame C keeps in a static for RefRA/RefDec and `astGetRefPos`/`astSetRefPos` is made per call, as `Frame.obsSkyFrame` does (no mutable static state) — cost if wrong: speed only. +- Ruling: `tests/test_specframe.rs::test_equal_same`, `test_not_equal_different_system`, `test_not_equal_different_sor` added to rust-tests.txt as `astEqual (out-of-scope method)`, as Task 1 listed `test_specmap.rs::equality` — cost if wrong: three tests untranslated until astEqual exists. +- Ruling: tests outside the brief's list were brought in where SpecFrame alone makes them runnable (KeyMap, CmpFrame overlay, FrameLoad, SectionLoad, UseDefs, NewUnit, SystemChange, FrameAxisAttrs, FrameClassAttrs CmpFrame, SkyGeometry kind 0, FrameTest NormUnit); FrameLoadTest and SectionLoadTest gate their skips and would have failed — cost if wrong: none. +- Ruling: `CScan.hasWord`/`numberThenWord` replace private copies in Frame and TimeFrame, and SpecMap's `AST__C`/`AST__H` become package-private, to share them with SpecFrame — cost if wrong: none (full suite passes). +- Ruling: `NativeClassesTest`'s example of an absent class changed from SpecFrame to FluxFrame — the test is of the helper — cost if wrong: none. + +### Controller + +- Ruling: Review Focus 2 wording (a Unit of another kind changes System) is wrong; C's SpecFrame SetUnit (specframe.c SetUnit) only records the unit for the current System — tests follow C — cost if wrong: none, C is the reference + +## Task 3 + +- Ruling: the Rust conversion tests of `test_specframe.rs` that compare with formulae (frequency to wavelength, energy, wave-number, velocities, LSRK shift, unit changes) assert C's values from the task-3 probe (within `CValues.cValueEq`) and the class of C's simplified Mapping, instead of the formulae and tolerances — expected values must come from C — cost if wrong: none; C's values satisfy the Rust tolerances. +- Ruling: the DSBSpecFrame rows of `spec_convert` (6 named cases) and `spec_origin_sor` (8 rows) and of `spec_use_defs` CONVERSIONS (5 rows) are skipped by name/class with exact count assertions, left to Task 4 (whose plan step names "the DSBSpecFrame cases of the oracles already converted"); not added to rust-tests.txt, as the Rust tests themselves are translated — cost if wrong: Task 4 must enable them (the counts 202, 8 and 23 will need raising). +- Ruling: Review Focus 3 compares the Frames inside a FrameSet, not the FrameSet's own dump, because C's `astConvert` deliberately sets the Base of a FrameSet argument (frameset.c `ConvertX`, as AST documents); Java does the same — cost if wrong: none for Frames; a reader expecting a FrameSet's Base to stay unset would be surprised, as with C. +- Ruling: `MakeSpecMapping` throws `AST__BADUN` at the point C calls `astError` (C continues with steps 0 and 9 under bad status, which do nothing) — cost if wrong: none observable. +- Ruling: the pinned C (3d3f255f) already contains the AlignSpecOffset fix the Rust repo lists as "RESOLVED (upstream 65bd5b6e)" (the `result_origin == AST__BAD` fallback in `MakeSpecMapping`); it is followed, so there is no pinned-C/Rust difference to record and `docs/rust-c-differences.md` is unchanged — cost if wrong: none; the spec_origin_sor oracle and testspecframe.c Error 13 confirm it. +- Ruling: SubFrame's plain-Frame branch keeps C's quirk of clearing System after setting Label, Symbol and Unit explicitly (a System change clears them again); Rust follows it too (audit SP-5), so it is not recorded as a difference — cost if wrong: none; OverlayTest `spec_pick_padded`/`spec_wave_pick_padded` match C. + +## Task 4 + +### Implementer + +- Ruling: `Match` calls the target's SubFrame a second time when the target axis is a DSBSpecFrame, and SubFrame finds each observed sideband by setting SideBand to `observed` and setting it back, leaving the target's SideBand set — both as C, where Rust does neither — because the target mutation is visible (probe `sideband_left_set`: `astTest(from, "SideBand")` is 1 after an aligned conversion) and the second call's result copies that state — cost if wrong: none, C is the reference; recorded in rust-c-differences.md. +- Ruling: C quirks kept: any setting holding `dsbcentre=` is taken for DSBCentre (`Title=dsbcentre=3` fails with AST__ATTIN, probed); GetLO's second message line reports the DSBCentre as 3e+10 Hz (C reads it under error status, probed); GetLO messages name `astGetImagFreq` and ToLSB/ToUSBMapping get TopoMap before checking IF/DSBCentre — cost if wrong: messages differ from what a reader expects, as C's do. +- Ruling: `observed_sideband_usb/lsb/lo` added to rust-tests.txt as `Rust-only API (DSBSpecFrame::observed_freq)` — C has no such function — cost if wrong: three tests untranslated. +- Ruling: C's `ToLOMapping` is not ported (C marks it unused and never calls it); Rust's `lo_offset_mapping` is translated as the C-reachable conversion to and from SideBand=LO through ToLSB/ToUSBMapping's LO branches (`loOffsetMappings`, probed) — cost if wrong: none observable. +- Ruling: Rust tests that set the internal topocentric DSBCentre/IF directly are translated with attribute settings in a topocentric FREQ Hz frame (DSBCentre exact) and the IF in GHz, applied identically in Java and the C probe; the direct sideband-Mapping tests call the package-private `toLsbMapping`/`toUsbMapping` and compare with the C value of the equivalent aligned conversion, whose simplified Mapping is the same WinMap — cost if wrong: none; the conversions themselves are also asserted. +- Ruling: `SpecFrame.castCopy` added so that FrameFinder's matchSub cast of a DSBSpecFrame template into a SpecFrame gives a SpecFrame as C's `astCastCopy` does (probe `cast_domain`: findFrame returns NULL, where Java threw AST__INTER) — cost if wrong: none; plain-Frame casts unchanged. +- Ruling: `FitsFsetToStore.makeFitsFrameSet` refuses a world Frame with a SpecFrame axis (`UnsupportedOperationException ... needs SpecFrame`), and the four `a20070718_*` wcsconv rows move from `needs DSBSpecFrame` to `needs SpecFrame` — once DSBSpecFrame loads, the writer (whose `spectralAxes` assumes no SpecFrame) wrote spectral axes as generic axes, giving wrong headers (fits-wcs: no CUNIT3/SPECSYS/RESTFRQ/IMAGFREQ, CRVAL3 off) or failures (fits-aips, fits-aips++), which the wcsconv gate cannot list; the refusal mirrors Task 2's read-side `needs SpecFrame` refusal and leaves Task 8 to replace it — cost if wrong: the reason names a class that exists (as the 66 Task 2 rows already do), and Task 8 must remove the refusal. +- Ruling: `test_dsbspecframe_read.rs` left untranslated and unlisted for Task 7 (needs the FitsChan spectral read), as the dispatch says — cost if wrong: none. + +### Controller + +- Ruling: accept the interim FitsFsetToStore.makeFitsFrameSet refusal of a world Frame with a SpecFrame axis (`needs SpecFrame`) — since Task 2 such FrameSets were written with the spectral axis as a plain axis, giving wrong headers — cost if wrong: Task 8 must remove it (carried into Task 8's dispatch). + +## Task 5 + +- Ruling: SFCBRW read and write follow the pinned C, which already reads `SFCBRW` and `SRCBR` and writes `SFCBRW` (fix 3b1f3f5a is in the pin; the Rust quirk file dates it after the pin as b4457da9); recorded in rust-c-differences.md — cost if wrong: none, both names read either way. +- Ruling: C quirk kept: Overlay onto a non-FluxFrame clears and re-sets the template's own System and AlignSystem, leaving its AlignSystem set and, when the System changes on clearing, clearing its Label/Symbol/Title and resetting its Unit (probed with `astOverlay_`) — cost if wrong: a template mutated as C mutates it. +- Ruling: C behaviour kept: `SetUnit` records the Unit as given, trailing spaces included, in the per-System record (probed: `UFlxdn = "Jy "`), where Rust trims — cost if wrong: none observable but in dumps. +- Ruling: existence checks C makes with `astUnitMapper` (GetSystem, SetUnit's `UnitsOK`) use `Units.relabel(from, to, null)`, which finds the conversion without building the Mapping, as `NewUnit` already does; building it would throw "needs a MathMap" for logarithmic units that C accepts (probed: `Unit=log(Jy)` gives System FLXDN, Label `log( Flux density )`) — cost if wrong: none; the conversion found is the same. +- Ruling: C's `astFluxFrame` units check after applying the options string is not ported; jniast's constructors take no options, so the defaults always pass (comment at the constructor) — cost if wrong: none reachable. +- Ruling: C's `SubFrame` alignment System (`align_sys`, and `report`) are not computed, since `MakeFluxMapping` does not use them (comment at `subFrame`) — cost if wrong: none; the getters have no side effects and `GetSystem`'s error is raised by `MakeFluxMapping` first anyway. +- Ruling: the loader refuses a `SpcFr` that is not a SpecFrame with AST__LDERR; C stores any Object (no C counterpart, like `checkLoadedPerm`); recorded in rust-c-differences.md — cost if wrong: a corrupt dump C would load fails here. +- Ruling: a missing `smap_in`/`smap_out` in `MakeFluxMapping`, which C would pass to `astTran1` as NULL, throws AST__INTER; with a SpecFrame template `astConvert` either succeeds or reports an error, so it is not reachable — cost if wrong: a different error status in an unreachable case. +- Ruling: `test_fluxframe.rs`'s three `astEqual` tests listed as `astEqual (out-of-scope method)` (as SpecFrameTest's), and its 16 SpecFluxFrame tests as `SpecFluxFrame (not yet ported)`; the round-trip tests that end in `equal` compare C's dump byte for byte and `equals` instead — cost if wrong: Task 6 must translate and unlist the 16. +- Ruling: Rust's `FluxSystem::parse(" SFCBR")` (Rust-only API) is tested through the package-private `systemCode`, the C function it mirrors; the other parse cases go through `System=` settings checked against C — cost if wrong: none. +- Ruling: Rust tests that build a FluxFrame with `set_spec_frame` + `set_spec_val` give the SpecFrame to the constructor (default SpecVal bad) and set SpecVal, as C's only way to give a SpecFrame; `make_flux_mapping` tests call the package-private `makeFluxMapping` and also check `convert` — cost if wrong: none. +- Ruling: `NativeClassesTest`'s synthetic dump now names GrismMap instead of FluxFrame as its missing class — cost if wrong: none. + +## Task 6 + +### Implementer + +- Ruling: `MakeMapF`/`MakeMapI` throw `needs RateMap`, not the brief's `needs MathMap` — both C functions build `astRateMap( m, 0, 0, ... )` before `astMathMap`, and the brief's own rule is "the first absent class C builds" — cost if wrong: a one-word change in two messages and in the tests' `assertNeeds("RateMap", ...)`. +- Ruling: the dispatch's premise that unit-only or same-system conversions avoid the TranMap does not hold in pinned C — `MakeSFMapping` short-circuits only for equal components, and every other conversion whose standardised SpecFrames convert reaches `MakeMapF` (probed: Jy to mJy, GHz to MHz, FREQ to WAVE all give CmpMaps); these throw here, and only equal components and no-conversion cases work — cost if wrong: none, C is the reference. +- Ruling: conversions involving logarithmic flux units throw `needs MathMap` from `UnitsMapper`, because C's `astEqual` of the FluxFrames builds that unit MathMap (fluxframe.c `MakeFluxMapping`'s `astUnitMapper`) before `MakeMapF` (testspecflux.c Errors 18 and 25) — cost if wrong: a different absent class named. +- Ruling: `UnitsMapper`'s message now ends `needs MathMap` (reached by this task's log-unit conversions); the full `writeDeferred` run changed no entry — cost if wrong: none. +- Ruling: the part of `MakeSFMapping` after `MakeMap3` (map1, map4 = inverted `MakeMap2(result)`, map5, the series CmpMaps, `astSimplify`) is not ported, nor `MakeMap3`'s TranMap/CmpMap: `MakeMap3` can only throw or make no Mapping here, so they are unreachable; `makeMap3` keeps the calls C makes (standardised Frames, MakeMapF, MakeMapI, the SpecFrame conversion) — cost if wrong: when RateMap, MathMap and TranMap are ported, that remainder must be ported from C. +- Ruling: C's `astEqual` is ported as a private helper of SpecFluxFrame (object.c `astEqual_` pointer test, frame.c `Equal`), since no public astEqual exists and only Frame's `Equal` applies to SpecFrame/FluxFrame — cost if wrong: none. +- Ruling: the loader refuses components that are not a SpecFrame and a FluxFrame with AST__LDERR (C keeps them and casts later; Rust refuses); recorded in rust-c-differences.md — cost if wrong: a corrupt dump C would load fails here. +- Ruling: C quirk not kept: `GetTitle` formats into a 101-character static buffer; Java returns the whole Title (as Rust); recorded in rust-c-differences.md from reading the code, not probed — cost if wrong: none for Labels under 93 characters. +- Ruling: Rust tests that assert converted values C produces through RateMap/MathMap/TranMap (test_specflux.rs Errors 8-29, `test_specflux_jy_to_fluxdenw`, `_inverse`, `_log_units`, `_surface_brightness`, `test_specfluxframe_convert_different_spec_system_converts`, `test_specfluxframe_not_equal_different_spec`) are translated as assertions that the conversion throws, with C's values in the Javadoc — cost if wrong: none; the values return when the classes do. +- Ruling: `astEqual` tests (testspecflux.c Errors 30-32, `test_specfluxframe_equal`, the two serialisation round trips) check the conversion C's `Equal` makes (simplifies to a UnitMap), plus dump text and `equals` for the round trips; Error 32's conversion throws `needs RateMap` (C: a CmpMap, `astEqual` 0, probed) — cost if wrong: none. +- Ruling: Rust's `pick_axes_snapshot_full_returns_specflux` and `pick_axes_snapshot_partial_returns_basicframe` (Rust-only API) are tested through `pickAxes` with C's classes: CmpFrame for both axes in either order, SpecFrame for axis 1 (probed) — cost if wrong: none. +- Ruling: Rust's `set_rest_freq(4.57e14)` is given as C's attribute string `RestFreq=4.57e14` (GHz), with C's dump (`RstFrq = 4.5700000000000001e+23`) — cost if wrong: none. +- Ruling: Rust tests that set a FluxFrame's SpecFrame and SpecVal give the SpecFrame to the constructor and set SpecVal (as Task 5) — cost if wrong: none. + +### Controller + +- Ruling: MakeMapF/MakeMapI throw `needs RateMap`, not the plan's `needs MathMap` — specfluxframe.c builds astRateMap (839/985) before astMathMap (846/998), and the rule is the first absent class C builds — cost if wrong: one word in two messages. +- Ruling: accept that in pinned C MakeSFMapping short-circuits only when both components are astEqual, so every other SpecFluxFrame conversion (Jy->mJy, GHz->MHz, FREQ->WAVE) needs RateMap/MathMap/TranMap and throws here; SpecFluxFrame is usable for equal/swapped components, picks and dumps until those Mappings (spec item 4) arrive — cost if wrong: SPLAT's flux-axis conversions wait for phase 5; reported to the user. + +## Task 7 + +### Implementer + +- Ruling: `test_fitschan_spec_unit_oracle.rs` tests C's `SpectralAxes` (a write), not the read; it is converted and translated now as `FitsChanSpecUnitOracleTest`, which checks the read of the cube for every case and compares each write with C, with the cases that stop listed in the test with their measured reason, checked both ways: 5 `needs SpecFrame` (the interim `makeFitsFrameSet` refusal) and `unit_log`/`unit_log_no_dims` `needs MathMap` (setting `log(Hz)` through the FrameSet builds the MathMap C builds) — cost if wrong: Task 8 empties the SpecFrame entries; the MathMap ones stay until MathMap. +- Ruling: `test_dsbspecframe_read.rs` reads FITS-CLASS headers, whose read is not available here (`encoding FITS-CLASS`, raised before FitsEncClass's VELO-LSR refusal); translated as `DSBSpecFrameReadTest` with C's values and both fixtures listed in the test with that reason, checked both ways; the DSBSetUp path itself is covered through FITS-WCS by `dsbCentrePrefersAxrefOverCrval` and `FitsWcsSpectralTest.dsbSpecFrameTakesEveryKeywordAsC` (C probe, IF/DSBCentre/SideBand exact) — cost if wrong: Task 9 removes the two entries. +- Ruling: `FitsChanCInlineTest.azelWritesAsFitsWcs` now runs on a fresh thread (the `SkyLastTest` pattern): reading `alt.header` (now possible, a DSBSpecFrame with the same OBSGEO and date) fills C's LAST table for that observer, and the AZEL write then interpolates from it, moving CRVAL by ~1e-6 deg; the expected values come from a C probe with empty tables, and C's LAST cache is ported faithfully (per thread) — cost if wrong: none to behaviour; other order-dependent AZEL tests could appear as more spectral headers are read in one thread. +- Ruling: the exclusion lists of `FitsChanErrorsTest`, `FitsChanCursorOracleTest`, `FitsChanEncodingsOracleTest` and `FitsChanWriteTest` keep or gain `needs SpecFrame` entries measured from the write (the interim refusal Task 4 added), and `FitsChanErrorsTest.check` and `FitsChanEncodingsOracleTest` now measure write refusals as they measured read ones — cost if wrong: Task 8 must empty them. +- Ruling: a `-TAB` spectral axis with TabOK above zero keeps phase 1's `needs LutMap` (TabMapping); with TabOK at most zero it now reaches `WcsSpectral` and gives C's AST__BDFTS (probe `tab_tabok0`) — cost if wrong: none; C confirms. +- Ruling: a `-LOG` spectral axis with CRVAL zero is AST__BDFTS (C's `LogWcs` returns NULL and `WcsSpectral`, unlike `WcsOthers`, has no UnitMap fallback; probe `log_zero`) — cost if wrong: none. +- Ruling: Rust's order of SpecFrame settings, its skipping of a blank Unit, its case-insensitive system parse and its 0 observation centre are not followed (recorded in `docs/rust-c-differences.md`) — cost if wrong: none; C is the reference and the wcsconv native dumps match C byte for byte. +- Ruling: `Pal.gc2gd` returning null (never for WGS84) skips the observer settings, as `FitsWcsCelestial` already does; C ignores `eraGc2gd`'s status — cost if wrong: none (unreachable). + +### Controller + +- Ruling: keep phase 1's `needs LutMap` for a -TAB axis with TabOK 1 — C reports AST__NOTAB from GetNamedTable when no table is supplied, but supplying tables needs FitsTable support this library lacks; revisit with the -TAB phase — cost if wrong: one reason string. + +## Task 8 + +- Ruling: the write's grism branch throws nothing — C's grism branch extracts an existing GrismMap (`ExtractGrismMap`) and builds none, and a FrameSet of this library's classes holds none (reading a `-GRI`/`-GRA` header already throws `needs GrismMap`, Task 7), so the branch makes only C's System/Unit changes through the FrameSet and falls through, per the common rule "where C finds no such object in a FrameSet of this library's classes, port C's behaviour"; the brief's "`-GRI`/`-GRA` throws `needs GrismMap`" holds for every header that has one — cost if wrong: none observable until GrismMap arrives, when `ExtractGrismMap` must be ported. +- Ruling: `AddEncodingFrame` is ported here as part of `MakeFitsFrameSet` (Task 9's files are FitsEncClass, FitsSpecTrans, FitsChan) — without it a FITS-CLASS write of a spectral cube would fail `CLASSFromStore`'s SPECSYS SOURCE check and return 0 where C writes, instead of reaching the kept refusal — cost if wrong: none; Task 9 builds on it. +- Ruling: `FitsChanEncodingsOracleTest` exclusions are keyed by header and encoding, so the other six encodings of the 8 headers whose FITS-CLASS write stops are compared with C (they match) — cost if wrong: none; the gate is stricter. +- Ruling: `crota-3d.head` is added to `NOT_ROUND_TRIPPED` as WRITE_FAILS — C's write into a new FitsChan also returns 0 (`write_probe`) — cost if wrong: none. +- Ruling: vopt-f2w, vopt-geo, vrad-v2f and vrad-wav are added as DIFFERS — their `-X2P` axes written into a new FitsChan have the reference at pixel 1 and CDELT from the numerical rate there, and read back differ from the header by up to 1e-3 m/s; C's cards and C's read-back values are identical to Java's to the last digit (`roundtrip_probe`) — cost if wrong: none. +- Ruling: the galactic case of `referencePositionIsTheCelestialReferencePoint` compares CDELT2 to 1e-16 and PC to 1e-12 absolute — traced: the same keys differ by the same amounts in the 2-D galactic write without a spectral axis (`gal_probe` vs Java), the phase 3 FitLine/libm cause; VELOSYS, CRVAL1/3 and the spectral cards are exact — cost if wrong: hides a 1e-12 PC error in that one test. +- Ruling: a `-TAB` spectral axis throws `needs FitsTable` for any Mapping `IsMapTab1D` returns, as phase 3 ruled for `OtherAxes` (C dereferences a null FitsTable when the Mapping comes without table columns) — cost if wrong: one reason string. +- Ruling: two SpecFrames, or celestial axes for a SpecFrame's reference position that give no FrameSet or fiducial point, make no FrameSet, as phase 3 ruled for two SkyFrames (C passes NULL to `AddEncodingFrame`, which dereferences it) — cost if wrong: none observable (C crashes). +- Ruling: a bad CRVAL is stored as not set — C's `SetItem` stores `AST__BAD` and `GetItem` gives the same `AST__BAD` for an item not set — cost if wrong: none. +- Ruling: the RESOLVED (upstream e09bc221) quirk is already in the pinned C (as 0dfd0f74), so there is no difference to follow or record beyond noting it (likewise 85e75a4e and 7f4ba71d) — cost if wrong: none; C, Rust and Java agree. +- Ruling: `spectral_axes.rs::try_grism_cascade_emits_gri_pv_and_chain` (a Rust unit test never listed) is added to `rust-tests.txt` with `GrismMap (out of scope)`: it builds a GrismMap and tests a Rust-only helper — cost if wrong: one entry. +- Ruling: `x2p_cascade_picks_freq_for_wavelength_axis` builds its axis by setting a frequency axis to WAVE through the FrameSet (testfitschan.c's construction) instead of a MathMap; `nonlinear_unit_is_cleared` expects `needs MathMap`, since the `log(Hz)` conversion is the MathMap C builds — cost if wrong: none. +- Ruling: Rust's clones in the `-X2P`/grism trials, its `LOCAL` for Local_group, its first-axis-only description, its early return on a bad reference value, its blank-Label skip, its VELOSYS on a clone, and its unformatted RefRA/RefDec are not followed (recorded in `docs/rust-c-differences.md`) — cost if wrong: none; C is the reference and the wcsconv rows match C. + +## Task 9 + +- Ruling: C's `ClassTrans` reads an uninitialised `crval` when the spectral axis has no CTYPE (one-axis headers such as class-spec.head); Java uses 0, the value C's recorded wcsconv outputs (class-spec, class-spec-hel) encode and Rust uses — C has no defined value to follow — cost if wrong: a different source velocity for such headers, which the wcsconv gate would show. +- Ruling: in `CLASSFromStore`, C's `crval[]` elements for axes the CRVAL loop did not reach are uninitialised; Java uses 0 — they are read only in a write that returns 0 and whose cards are removed — cost if wrong: none observable unless C's garbage made `SetValue` fail. +- Ruling: `FitsChanEncodingsOracleTest.writesMatchC` runs on a fresh thread — C's probe runs the cases in order in one process with empty LAST tables at the start; on the surefire thread earlier tests' LAST values changed ELEVATIO by 14 ULP — cost if wrong: none; the test is stricter about order, not looser. +- Ruling: the remaining 1-ULP ELEVATIO difference of `source_zsource`/`topocent` is accepted by the existing 4-ULP card gate — traced to `Math.atan2` in the reference pixel's declination; the AZEL chain itself is bit-identical — cost if wrong: hides a 1-ULP error in that card. +- Ruling: the fresh-thread helper moved to `testsupport/FreshThread` (it was duplicated in `SkyLastTest` and `FitsChanCInlineTest`), rather than adding a third copy — cost if wrong: none. +- Ruling: `FitsChanCursorOracleTest`'s "waiting for another encoding" mechanism is removed, since no encoding is unread; any read stopping now must be listed in `EXCLUDED` — cost if wrong: none. +- Ruling: `writeClassSubtractsRestfreq`, `writeClassSflToGls` and `roundTripClass` pass `CLASSFromStore` a FrameSet with a plain 3-axis Frame (in which C's templates find no SpecFrame or SkyFrame, so no velocity or azimuth cards), since C's writer, unlike Rust's `write_to_cards`, needs a FrameSet — cost if wrong: none. +- Ruling: `spectralCdeltIsScaledToHertzOnce` checks a property (kHz and Hz descriptions write identical cards) rather than C numbers, as `CLASSFromStore` cannot be called on a hand-made store in C, and `AddEncodingFrame` forces Hz on every C write — cost if wrong: none; it pins the fix the pinned C has. +- Ruling: Rust's `translate_class` (runs last, skips what C reports, comments its cards) and `write_to_cards`/`write_velocities_from_frameset`/`write_azel_from_frameset` (pre-checks, default comments, no default EQUINOX, no NAXIS rewrite, CTYPE scans, matched-Frame normalisation) are not followed; recorded in `docs/rust-c-differences.md` — cost if wrong: none; every FITS-CLASS gate matches C. + +## Task 10 + +- Ruling: the over-run guard sits just before the CDELT scaling, where C writes past its array — earlier writes of CRPIX/CRVAL/CTYPE are unchanged — a FrameSet never reaches it, so no cost. +- Ruling: uninitialised crval reads in C are replaced by 0 (as the existing code comment says) — unreachable from a FrameSet — none. +- Ruling: causes of the three FITS-CLASS write failures not investigated beyond C's identical outcome — the test only needs the outcome — none. + +## Final review fix pass + +### Implementer + +- Ruling: a CmpFrame cast into a SpecFluxFrame keeps copies of the CmpFrame's components whatever their classes, as C's `astCastCopy` does, rather than giving null for components other than a SpecFrame and a FluxFrame — the cast SpecFluxFrame is only ever the template of a match against a SpecFluxFrame, whose `Match` and `SubFrame` read its axes and attributes and overlay it, never its SpecFrame and FluxFrame, so C's behaviour is defined there — cost if wrong: a `ClassCastException` if a later path reads the components of such a SpecFluxFrame as a SpecFrame and a FluxFrame. +- Ruling: SpecFluxFrame's default Title reads the components' Labels as Frames, as C's `GetTitle` does through `astGetLabel`, so it works for a SpecFluxFrame made by that cast — cost if wrong: none. +- Ruling: a CmpFrame cast into its own class is a copy, not `castCopy` — C's `astCastCopy` into the same class is `astCopy` followed by `astCleanAttribs`, which changes nothing in a valid object — cost if wrong: none. +- Ruling: C's crash in `Cast` when no plain CmpFrame has been made is not copied; Java gives what C gives once one has been — cost if wrong: none. + +### Controller + +- Ruling: when re-expressing the SpecOrigin or SourceVel fails, a StdOfRest, SourceVRF or SourceSys setting or clearing throws and keeps the old value, where C throws and stores the new one; recorded as a C quirk in `docs/rust-c-differences.md` — C's state is inconsistent (a new rest frame with the SourceVel of the old one) — cost if wrong: after such a failed setting, later attribute values, the default Title and the dump differ from C's. +- Ruling: the FITS-CLASS write at the edge of `IsMapLinear`'s tolerance (fuzz header `h00886`, residual 5.63e-5 pixels against 4.99e-5; C writes, Java returns 0) is recorded, not fixed — rounding in an ill-conditioned linear fit, not a porting error — cost if wrong: an occasional FITS-CLASS header near the tolerance that C writes and Java does not. diff --git a/docs/rust-c-differences.md b/docs/rust-c-differences.md index c1de275..07f886f 100644 --- a/docs/rust-c-differences.md +++ b/docs/rust-c-differences.md @@ -279,6 +279,30 @@ The entries are grouped by area, in the order the Java classes were ported. - Rust: makes the point bad. - Java: as Rust. +### The frequency correction factor of a SpecMap's change of rest frame + +- C: a 1-dimensional SpecMap works out the factor the first time it transforms points and keeps it in the conversion's last argument slot (`specmap.c` `FrameChange`), so a SpecMap written after it has transformed points carries a `Spec` card for it, as the fixtures `simplify/cap_specmap_06.map` and `cap_winmap_01.map` do. +- Rust: keeps the factor in a separate cache (`fcorr`), which is not written. +- Java: as C. + +### SpecMap values that are not finite + +- C: each conversion that can make a value that is not finite tests for it and writes AST__BAD; ENTOFR, FRTOEN, WNTOFR, FRTOWN, BTTOVL and VLTOBT do not, so an overflow gives an infinity (`specmap.c` `SystemChange`). +- Rust: also replaces every value that is not finite with AST__BAD after the last conversion. +- Java: as C, apart from inputs that are not finite, which are bad (see "Infinite input coordinates"). + +### SpecMap load errors + +- C: a missing or unknown conversion is AST__BADIN with C's messages (`astLoadSpecMap`). +- Rust: AST__SPCIN. +- Java: as C. + +### The SpecMap axis-count message + +- **C quirk**: `astInitSpecMap` refuses a number of axes other than 1 or 3 with a message saying "it should be 1 or 2". +- Rust: gives its own message. +- Java: keeps C's message. + ## Units Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follows C in each. @@ -343,6 +367,99 @@ Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follow - Rust: raises an error. - Java: as C. +### SpecFrame Overlay onto a Frame of another class + +- **C quirk**: when the template has its System set, `Overlay` (specframe.c) clears the System and AlignSystem of a copy of the template and overlays the copy; when that changes the copy's System, `ClearSystem` also clears the copy's Title, Label and Symbol, and its Unit unless one was used with the default System, so none of those is overlaid either. +- Rust: `specframe_overlay` overlays the template itself through `frame_overlay`, which transfers the System only to a result of the template's class, so the Title, Label, Symbol and Unit are overlaid. +- Java: as C. + +### A SpecFrame Symbol changed by its Unit + +- **C quirk**: `GetSymbol` (specframe.c) copies the default Symbol, modified for a Unit other than the System's default, into a static 21-character buffer with `strcpy`, so a longer one overflows it: System `WAVN` with Unit `nm` gives a Symbol beginning `999999999.99999988/ WAVN`, and the fortified `strcpy` traps (probed: SIGTRAP from `astGetC( f, "Symbol(1)" )`, and from a NATIVE write of a header with `CTYPE1 = 'WAVN'`, `CUNIT1 = 'nm'`, through `Dump`). + `GetSymbol` in fluxframe.c has the same pattern (read from the code, not triggered by the units tried). +- Rust: gives the whole Symbol. +- Java: as Rust. + +### A failed StdOfRest, SourceVRF or SourceSys setting + +- **C quirk**: when re-expressing a set SpecOrigin or SourceVel in the new standard of rest or source System fails (AST__ATSER, AST__NOVAL, AST__BADUN), setting or clearing StdOfRest, SourceVRF or SourceSys reports the error but stores the new value anyway: `SetStdOfRest` and `ClearStdOfRest` (specframe.c) store it after `OriginStdOfRest` has cleared the SpecOrigin and failed, and the `astMAKE_SET` and `astMAKE_CLEAR` macros for SourceVRF and SourceSys store it after `ConvertSourceVel` has failed, leaving the SourceVel expressed in the old rest frame or System. + Later attribute values, the default Title (`Wavelength (LSRK)`, say) and the dump then describe the new value. +- Rust: `set_std_of_rest`, `clear_std_of_rest`, `set_source_vrf`, `clear_source_vrf`, `set_source_sys` and `clear_source_sys` in `frames/specframe.rs` return the error before storing the value. +- Java: as Rust: the setter throws and the attribute keeps its old value (a SpecOrigin already cleared by the failed re-expression stays cleared, as in C). + +### Aligning DSBSpecFrames in sidebands sets the target's SideBand + +- **C quirk**: to find the observed sideband of the target and of the result, `SubFrame` (dsbspecframe.c) reads the SideBand, sets it to `observed` and sets it back with `astSetSideBand`, so after a conversion with AlignSideBand set on both DSBSpecFrames (or one restoring a FrameSet's integrity) the target's SideBand is set, to the value it had. + `Match` then calls the target's `SubFrame` a second time when the target axis belongs to a DSBSpecFrame, although the parent `Match` has made the same call, so the result of the second call is a copy of a target whose SideBand is set. +- Rust: `DSBSpecFrame::sub_frame` takes the observed sidebands from the sign of the IF without changing either Frame, and `match_template` makes the call once. +- Java: as C. + +### DSBSpecFrame settings and errors + +- **C quirk**: `SetAttrib` (dsbspecframe.c) takes any setting that holds the text `dsbcentre=` for a DSBCentre setting, so `Title=dsbcentre=3` fails with AST__ATTIN. + `GetLO` reads the DSBCentre for the second line of its AST__ATTIN message after reporting the first, when the getter gives its default, so the message always says the DSBCentre is 3e+10 Hz. + Its AST__NOVAL and AST__ATTIN messages name `astGetImagFreq` whichever method calls it, and `ToLSBMapping` and `ToUSBMapping` find the Mapping to topocentric frequency before checking the IF and DSBCentre. + The loader refuses a SideBand other than `USB`, `LSB` or `LO`, in that case, with AST__ATTIN. +- Rust: has no string attribute layer for a DSBSpecFrame; its `lo_freq` message gives the DSBCentre held, `verify_attrs` names `astMatch`, the sideband Mappings check the attributes first, and `from_node` reads the SideBand in any case and ignores one it does not know. +- Java: as C. + +### FluxFrame System names + +- C: at the pin, `SystemCode` (fluxframe.c) reads both `SFCBRW` and `SRCBR` as `AST__SBRIGHTW`, and `FluxSystemString` writes `SFCBRW`, so a FluxFrame in that System reads its own dump back. + The Rust repository's `c-library-quirks.md` lists this as resolved upstream in b4457da9, after the pin, but the pinned C already holds the fix (3b1f3f5a, "fluxframe: read the System name it writes for per-wavelength surface brightness"). +- Rust: `FluxSystem::parse` reads both names and writes `SFCBRW`, as C at the pin does. +- Java: as C. + +### The SpecVal comparison of `MakeFluxMapping` + +- C: the two SpecVals, each converted to the result's density system, must satisfy `astEQUALS( specval_in, specval_out, 1.0E8 )`: a difference of no more than the larger of 1e8 times DBL_EPSILON times the sum of their magnitudes, and 1e-12. +- Rust: allows 1e8 times DBL_EPSILON times the larger of their magnitudes and 1, which is about half C's width for large values and wider than C's for values below 1. +- Java: as C. + +### FluxFrame Overlay onto a Frame of another class + +- **C quirk**: when the template has its System set, `Overlay` (fluxframe.c) clears the System and AlignSystem of the template itself, overlays the Frame attributes, and sets the System and AlignSystem again with the values they had. + The template's AlignSystem is left set, to its default if it was not set, and when clearing the System changes it, FluxFrame's `ClearSystem` and `SetSystem` clear the template's Label, Symbol and Title and reset its Unit to the one last used with each System, or clear it (probed through `astOverlay`). +- Rust: `fluxframe_overlay` leaves the template unchanged; `frame_overlay` transfers the System only to a result of the template's class. +- Java: as C. + +### The Unit a FluxFrame records for its System + +- C: `SetUnit` (fluxframe.c) records the Unit as given, trailing spaces included, as the one used with the System, while the Frame class stores the Unit without them (probed: `Unit(1)=Jy ` dumps `UFlxdn = "Jy "`). +- Rust: records the Unit without trailing spaces. +- Java: as C. + +### A FluxFrame dump whose `SpcFr` is not a SpecFrame + +- C: `astLoadFluxFrame` keeps whatever Object `SpcFr` holds. +- Rust: keeps it only if it is a SpecFrame, and ignores any other. +- Java: refuses it with AST__LDERR, since a FluxFrame here holds only a SpecFrame. + +### The comment of a FluxFrame's SFCBRW units in a dump + +- C: `Dump` formats "Preferred units for " into a 50-character buffer (`fluxframe.c` `Dump`); for SFCBRW the comment is 55 characters, so it writes past the buffer (an AddressSanitizer stack-buffer-overflow, C probe). **C quirk.** +- Rust: writes the whole comment. +- Java: as Rust. + +### A SpecFluxFrame dump whose components are not a SpecFrame and a FluxFrame + +- C: `astLoadSpecFluxFrame` loads the CmpFrame and keeps whatever Frames `FrameA` and `FrameB` hold, which `GetSpecFrame` and `GetFluxFrame` (specfluxframe.c) later cast to a SpecFrame and a FluxFrame. +- Rust: refuses them with AST__LDERR. +- Java: as Rust. + +### The default Title of a SpecFluxFrame + +- C: `GetTitle` (specfluxframe.c) formats " versus " with `sprintf` into a static 101-character buffer, so Labels longer than 92 characters between them write past it (read from the code, not probed). **C quirk.** +- Rust: gives the whole Title. +- Java: as Rust. + +### Casting between a CmpFrame and a SpecFluxFrame + +- C: `Cast` (cmpframe.c) copies a CmpFrame or SpecFluxFrame as an instance of any class of the CmpFrame family, a subclass included (`astCastCopy`), so a SpecFluxFrame template that matches no CmpFrame is cast into a plain CmpFrame and matched again, and a plain CmpFrame template that matches no SpecFluxFrame (the CmpFrame `ConvertX` gets from matching a SpecFluxFrame against a FluxFrame or SpecFrame) is cast into a SpecFluxFrame holding copies of its components, whose `Match` reaches `MakeSFMapping`. + **C quirk**: `Cast` compares the classes through CmpFrame's own `class_vtab`, which is initialised only when a plain CmpFrame is first made, so in a process that has made SpecFluxFrames but no CmpFrame a SpecFluxFrame match that fails dereferences null in `astClassCompare` (probed: SIGSEGV converting a SpecFluxFrame whose SpecFrame has Domain `FOO` to a default one). +- Rust: SpecFluxFrame has no `cast`, and `CmpFrame::cast` in `frames/cmpframe.rs` copies a CmpFrame only into a CmpFrame, so neither becomes the other and these conversions find nothing. +- Java: as C once a CmpFrame has been made: a FluxFrame or SpecFrame that does not match a SpecFluxFrame directly converts through `MakeSFMapping`, so it throws `needs RateMap` (or C's error, such as AST__ATSER from `GetSpecFrame`). + ## FitsChan ### An equals sign in a keyword name is reported as an `astPutFits` error from every method @@ -656,12 +773,18 @@ Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follow - 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` +### Two SkyFrames or two SpecFrames 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. +- C: `MakeFitsFrameSet` marks a world Frame with axes of two SkyFrames (of Domain `SKY`), or of two SpecFrames, 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_`); so it does when the celestial axes it makes or finds for a SpecFrame's reference position give no FrameSet or no fiducial point (`fitschan.c` `MakeFitsFrameSet`, `AddEncodingFrame`). **C quirk.** +- Rust: `make_fits_frameset` in `fitschan/fset_to_store/mod.rs` looks for neither a second SkyFrame nor a second SpecFrame. - Java: makes no FrameSet, so that the description cannot be made, which is what `AddVersion` does with the null FrameSet C means to return. +### A SpecFrame's reference position in `MakeFitsFrameSet` + +- C: when the SpecFrame of the world Frame has RefRA and RefDec set, and the world Frame has no SkyFrame and at most two axes, `MakeFitsFrameSet` adds FK5 J2000 celestial axes, read by a FitsChan from a TAN header with the reference position at pixel (0, 0) and the SpecFrame's Epoch as MJD-OBS, the two new pixel axes being given the constant 0; when the world Frame has a SkyFrame, it sets the SkyFrame to FK5 J2000 and sets RefRA and RefDec through the FrameSet to the fiducial point of the projection, formatted by the SkyFrame with Digits 20, then sets back the SkyFrame's System and Equinox if they were set (`fitschan.c` `MakeFitsFrameSet`). +- Rust: `make_fits_frameset` in `fitschan/fset_to_store/mod.rs` adds no celestial axes, and sets RefRA and RefDec on the SpecFrame to the fiducial point, normalised, without formatting it. +- Java: as C (`FitsFsetToStore.makeFitsFrameSet`). + ### 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`). @@ -779,7 +902,64 @@ Rust's `src/units/` departs from C's `unit.c` in the following ways; Java follow - 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. +- Java: as C (`FitsEncClass`). + +### The cards `CLASSFromStore` writes + +- C: `CLASSFromStore` writes CRPIX, CRVAL and CTYPE of the first three axes, each loop stopping at a missing value or a `-TAB` axis, and then still writes CDELT, EQUINOX, DATE-OBS (and MJD-OBS over a card the header has), RESTFREQ, IMAGFREQ, OBJECT, LINE, the velocities and the azimuth and elevation before returning 0, leaving the cards for `Write` to remove. + Each CTYPE comment is the description's, if it has one. + EQUINOX is 1950 for FK4 and 2000 for FK5 when the description has a RADESYS and no equinox. + A description of one pixel axis, to which `MakeFitsFrameSet` added celestial axes, is written with NAXIS 3 and NAXIS2 and NAXIS3 of 1. + VELO-LSR, VLSR and DELTAV convert the spectral CRVAL and CRVAL plus CDELT, both in Hz, with a SpecFrame matched in the current Frame of the FrameSet written; AZIMUTH and ELEVATIO convert the celestial CRVAL with SkyFrames matched there, and are normalised with the AZEL template SkyFrame (`fitschan.c` `CLASSFromStore`). + When the description has fewer than three axes with a CRPIX and the spectral axis is not among them, C scales and writes `cdelt[axspec]` past the end of its array of one element per axis written (`fitschan.c:7015`). + C also reads uninitialised elements of its `crval` array, those of axes its CRVAL loop did not reach, when it computes VELO-LSR and DELTAV (the spectral axis) and AZIMUTH and ELEVATIO (the celestial axes). + **C quirk** (an over-run and uninitialised reads), neither reachable from a FrameSet, since every WCS axis has a CRPIX. + The pinned C has the fixes the Rust repository's `docs/issues/c-library-quirks.md` lists as upstream aea3090b (a LONPOLE of +180 or -180 degrees is allowed and any other refused, as a66a0cb5) and 17416d33 (the spectral CDELT is scaled to Hz once). +- Rust: `class_store_ok` in `fitschan/enc_class.rs` checks every value before `write_to_cards` writes any; `write_to_cards` gives every CTYPE the default comment, writes EQUINOX only when the description has one, and leaves NAXIS alone; `write_velocities_from_frameset` takes the frequencies from the cards written, finding the spectral axis by its CTYPE; `write_azel_from_frameset` finds the celestial axes by their CTYPE and normalises with the matched AZEL Frame. +- Java: as C (`FitsEncClass`), except that the over-run throws `AstException` with status `AST__INTER` and an unreached `crval` element reads as 0. + +### `ClassTrans` + +- C: `SpecTrans` calls `ClassTrans` for the primary description of a FITS-CLASS header after translating DATE-OBS and before the SAO, NCP, ATF and GLS translations. + It reports `AST__BDFTS` when there is neither RESTFRQ nor RESTFREQ, when the spectral CTYPE (of the one of the first three axes that is not celestial, axis 2 when there are none) is not FREQ, ignoring case and trailing spaces, and when that axis has no CRVAL. + It writes the CRVAL plus the rest frequency, SPECSYS `SOURCE`, SSYSSRC and ZSOURCE with no comment, and warns (`badval`) when there is no VELO-xxx keyword, assuming LSRK and a velocity of zero. + A blank projection code becomes `-GLS`, which the GLS translation does not change to `-SFL`, since it tests the projection code `SpecTrans` took before `ClassTrans` ran. + The reference frequency of the radio velocity is a variable set only when the spectral axis has a CTYPE; otherwise it is not initialised, and the recorded outputs of the wcsconv fixtures `class-spec.head` and `class-spec-hel.head`, whose one axis is not axis 2, encode 0 (`fitschan.c` `ClassTrans`). **C quirk** (an uninitialised variable). +- Rust: `translate_class` in `fitschan/spec_trans.rs` runs after every other translation, and skips what C reports: no rest frequency, a spectral CTYPE other than FREQ (compared after trimming spaces at both ends) and a missing CRVAL; it gives the cards it writes comments. +- Java: as C (`FitsSpecTrans`); the uninitialised value is 0, as Rust's. + +### Which CTYPE values `WcsSpectral` takes as spectral + +- C: `IsSpectral` compares the first four characters of the CTYPE, without trailing spaces, with the ten FITS-WCS paper III codes case by case, and accepts the axis only when the algorithm code after them is blank or starts with `-`; any other axis is left to `WcsOthers` as a linear axis (`fitschan.c` `IsSpectral`), so `freq` gives a plain Frame axis with Domain `FREQ`. +- Rust: `parse_spectral_ctype` in `fitschan/wcs_spectral.rs` takes the first four characters through `SpecSystem::parse`, which ignores case and accepts the long System names, and does not check the algorithm code, so `freq` makes a SpecFrame and `FREQXYZW` fails with an unknown algorithm code. +- Java: as C (`FitsWcsSpectral.spectralAxes`, `FitsStore.isSpectral`). + +### The order of the SpecFrame settings in `WcsSpectral` + +- C: sets System, the reference position, Unit (CUNIT, or the system's default unit, which is blank for ZOPT and BETA), Epoch, RestFreq (set to `AST__BAD` when there is neither RESTFRQ nor RESTWAV), ObsLat/ObsLon/ObsAlt, SourceVRF, SourceVel, StdOfRest and Label, in that order, and then calls `DSBSetUp` with the AXREF value, else the CRVAL value, which is `AST__BAD` when there is neither (`fitschan.c` `WcsSpectral`). +- Rust: `build_spectral_axis` sets StdOfRest second, skips the Unit when it is blank, so a ZOPT or BETA axis with no CUNIT has no Unit set, and gives `dsb_set_up` an observation centre of 0 when there is neither AXREF nor CRVAL. +- Java: as C (`FitsWcsSpectral`); C's blank Unit is set and recorded as the Unit used with the System. + +### How `SpectralAxes` tries the non-linear and grism algorithms + +- C: `SpectralAxes` tries each System of the `-X2P` algorithm (FREQ, WAVE, AWAV and VELO, the axis's own System among them) and of the grism algorithm (WAVE and AWAV in m) by setting it, and clearing or setting the Unit, through the FrameSet being written, which remaps its current Frame, and sets the original System and the linear Unit back after each, so the FrameSet's Mapping goes through each conversion and back, and a Unit that was not set is left set; it gives `IsMapTab1D` no unit (`fitschan.c` `SpectralAxes`). +- Rust: `try_x2p_cascade` and `try_grism_cascade` in `fitschan/fset_to_store/spectral_axes.rs` convert clones of the SpecFrame and join the conversion to the pixel to world Mapping themselves, leaving the FrameSet unchanged; they skip the axis's own System, and pass to the next System when the reference value or the rate does not convert; `is_map_tab_1d` is given the linear Unit. +- Java: as C (`FitsSpectralAxes`). + A FrameSet of this library's classes holds no GrismMap, so C's grism algorithm finds none, and only the attribute changes are made. + +### The keywords `SpectralAxes` stores + +- C: `SpectralAxes` describes every SpecFrame axis of the world Frame; uses the reference value it has even when it is bad; takes a set Label, blank or not, as the CTYPE comment and CNAME; gives the Local_group standard of rest as `LOCALGRP` (`GetFitsSor`); and finds VELOSYS by setting SourceVRF and SourceVel on the SpecFrame in the FrameSet, setting them back only when SourceVel was set, so that SourceVRF is left set (`fitschan.c` `SpectralAxes`). +- Rust: `spectral_axes` in `fitschan/fset_to_store/spectral_axes.rs` describes the first spectral axis only; describes none when the reference value is bad; skips a blank Label; gives `LOCAL` for the Local_group standard of rest; and finds VELOSYS on a clone of the SpecFrame. +- Java: as C (`FitsSpectralAxes`). + +### The default reference value of `SpectralAxes` + +- C: the default reference value is the middle of the spectral range when the size of the one pixel axis that feeds the spectral axis is known, found by splitting the inverted pixel to world Mapping, and the value at pixel 1 otherwise (`fitschan.c` `SpectralAxes`). + The Rust repository's `docs/issues/c-library-quirks.md` lists this as a fix made after the pin (upstream e09bc221), but the pinned C has it, as commit 0dfd0f74. + It also has the fixes the same file lists as upstream 85e75a4e (`IsMapLinear` centres the values it fits, as d2c047eb) and 7f4ba71d (`AddVersion` takes the pixel to world Mapping again after the axes are described, as 12e9ed4a). +- Rust: as C. +- Java: as C (`FitsSpectralAxes`, `FitsIsMapLinear`, `FitsFsetToStore.addVersion`). ## Test harness diff --git a/docs/superpowers/plans/2026-11-16-pure-java-ast-phase4-spectral.md b/docs/superpowers/plans/2026-11-16-pure-java-ast-phase4-spectral.md new file mode 100644 index 0000000..6aed807 --- /dev/null +++ b/docs/superpowers/plans/2026-11-16-pure-java-ast-phase4-spectral.md @@ -0,0 +1,231 @@ +# Pure-Java AST Phase 4 (Spectral and Flux Frames) 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:** SpecMap, SpecFrame, DSBSpecFrame, FluxFrame and SpecFluxFrame work as C's do, with jniast's public API, and FitsChan reads and writes spectral axes in every encoding, FITS-CLASS included. + +**Architecture:** Port the Rust port's `mappings/specmap.rs`, `frames/{specframe,dsbspecframe,fluxframe,specfluxframe}.rs`, `fitschan/wcs_spectral.rs`, `fitschan/fset_to_store/spectral_axes.rs` and `fitschan/enc_class.rs` onto the phase 1 to 3 classes, with TimeFrame and TimeMap as the Java pattern for a Frame class and its Mapping. +Take from C (`reference/starlink-ast/src/{specmap,specframe,dsbspecframe,fluxframe,specfluxframe,fitschan}.c`) every part whose Rust structure follows from Rust's ownership rules (Shared Design). +The gates are the C test programs (`testspecmap.c`, `testspecframe.c`, `testflux.c`, `testspecflux.c`, through their Rust translations), the Rust repo's C-probe oracles, C's `wcsconv` rows and the deferred lists, each checked both ways. + +**Tech Stack:** as phases 1 to 3: 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 3). +The earlier plans' Shared Design sections and the rulings in `docs/reports/2026-11-1*-phase*-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). +- Public API: exactly jniast's constructors and methods for the five classes (`SpecFrame()`, `getRefPos(SkyFrame)`, `setRefPos(SkyFrame, double, double)`, the attribute getters and setters of `SpecFrame.java`, `DSBSpecFrame.java`, `FluxFrame.java`; `FluxFrame(double, SpecFrame)`, `FluxFrame()`; `SpecFluxFrame(SpecFrame, FluxFrame)`; `SpecMap(int, int)`, `specAdd(String, double[])`); every other attribute C has (SpecOrigin, AlignSpecOffset, ImagFreq, and so on) is reached through the generic `AstObject` attribute methods, as in jniast. + Nothing else public is added. +- Before porting, read Rust `docs/porting-hazards.md` (H7 and H8 above all), `docs/audits/frame-family-c-parity.md`, `docs/audits/mapping-c-parity.md` (SpecMap), `docs/audits/fitschan-c-parity.md` (spectral and CLASS parts), and in `docs/issues/c-library-quirks.md` every entry naming SpecFrame, SpecMap, DSBSpecFrame, FluxFrame, SpecFluxFrame, SpectralAxes, WcsSpectral or CLASS (search by name). + An entry marked RESOLVED upstream describes a fix made after the pin: follow the pinned C, and record the difference in `docs/rust-c-differences.md`. +- Rust comments cite older C line numbers; find each C function by name in the pinned source. +- Classes still absent after this phase: GrismMap, MathMap, TranMap, LutMap, RateMap, FitsTable and the rest of spec item 4. + Each place C or Rust reaches one throws `UnsupportedOperationException` whose message ends `needs `, naming the first absent class C would build (the convention `Deferred.unavailableReason` reads); where C finds no such object in a FrameSet of this library's classes, port C's behaviour. +- Spectral values must match C to the oracle tolerances; when one does not, find the C function that computes it before touching the arithmetic (H7). + +## Review Focus + +1. Converting between SpecFrames whose standards of rest need a source position, epoch or observer (RefRA/RefDec unset, Epoch unset, ObsLon/ObsLat unset) gives C's result or C's error, never a silently wrong velocity (test in Task 3). +2. Setting Unit on a SpecFrame axis to a unit of another kind (Angstrom on a frequency axis, km/s on a wavelength axis) changes System as C's ActiveUnit rules do, and an impossible unit gives C's error (test in Task 2). +3. `astConvert`, `findFrame` and FrameSet integrity never change the attributes of the Frames given, and two threads converting copies of one SpecFrame or SpecFluxFrame get identical Mappings (test in Task 3). +4. Every new class survives a NATIVE dump and read, through Channel and FitsChan, with each attribute set and unset, giving C's cards (test in Task 2, extended in Tasks 4 to 6). +5. A spectral FITS header read and written back in each encoding that accepts it gives a FrameSet that transforms as the original, and a header whose spectral axis needs an absent class (`-GRI`, `-LOG` through MathMap, `-TAB`) fails with `needs `, never another exception (test in Task 7, extended in Tasks 8 and 9). + +--- + +## Shared Design + +### Where the code goes + +- One public class per AST class: `SpecMap` (extends `Mapping`), `SpecFrame` (extends `Frame`), `DSBSpecFrame` (extends `SpecFrame`), `FluxFrame` (extends `Frame`), `SpecFluxFrame` (extends `CmpFrame`), each built as `TimeFrame` and `TimeMap` are: attribute values, `getAttrib`/`setAttrib`/`testAttrib`/`clearAttrib`, `systemCode`/`systemString`/`validateSystem`, `match`/`subFrame`/`overlay`, `dump`/`dumpComment`, and a loader in `ObjectRegistry`. +- Package-private helpers beside them when a class passes about 2,500 lines, named for the Rust module they port. +- FITS code follows the phase 3 naming: `FitsWcsSpectral` (`wcs_spectral.rs`, C `WcsSpectral` and its helpers), `FitsSpectralAxes` (`fset_to_store/spectral_axes.rs`, C `SpectralAxes`), `FitsEncClass` (`enc_class.rs`, C `ClassTrans` and `CLASSFromStore`, replacing the phase 3 refusal). +- PAL's velocity routines (`rvgalc`, `rvlg`, `rvlsrd`, `rvlsrk`, `evp`, `geoc`, `pvobs`) are already in `internal.pal`. + +### Taken from C rather than Rust + +1. C's `Match` and `SubFrame` work on copies of the template where C copies, and on the caller's Frame where C does; Rust's extra clones for borrowing are not reproduced (phase 2 ruling: Java objects are shared references as C's are). +2. SpecFluxFrame is a CmpFrame of the two Frames given, shared where C clones them, as C's `astSpecFluxFrame` builds it. +3. SpecMap's conversion steps are kept in C's list form (`cvttype` and `cvtargs` per step) so `MapMerge` and the native dump follow C's merge and card order. +4. The FitsChan spectral reader and writer receive the FitsChan, store and FrameSet as C's functions do, as phase 3's writers do. + +### Gates and deferred lists + +- The Rust test files `test_specmap.rs`, `test_specframe.rs`, `test_dsbspecframe.rs`, `test_fluxframe.rs`, `test_flux.rs`, `test_specflux.rs` and their siblings are not in `deferred/rust-tests.txt`, since phase 1 never listed them; each task translates its files and adds to `rust-tests.txt` only the tests that still need an absent class, with that reason. +- C-probe oracles: `class_attrs`, `frame_class` and `spec_use_defs` are converted already (their deferred cases come back as each class arrives); `specmap_3d`, `spec_convert`, `spec_origin_sor`, `dsb_topo`, `flux_badun`, `flux_unit_system`, `specflux_cmp`, `specflux_primary` and `fitschan_spec_unit` are converted by the task that needs them, from `tests/_oracle/cases.rs` with the existing `CasesToJson`, as phases 1 and 3 did. +- `WcsconvTest`, `TransformOracleTest` (`headers.txt`), `SerialisationCorpusTest` (`serialisation.txt`, `full-dumps.txt`), `framesets.txt`, `simplify.txt`, `simplify-cases.txt` and `read-warnings.txt`: an entry whose only missing class arrives in a task passes in that task, or carries the next absent class as its reason; the lists stay stable on a rewrite (`-Dast.writeDeferred=true` makes no change). + +--- + +### Task 1: SpecMap + +**Files:** +- Create: `SpecMap.java` (Rust `mappings/specmap.rs`; C `specmap.c`) +- Modify: `ObjectRegistry.java`, the simplifier's merge dispatch for C's `SpecMap` `MapMerge` +- Test: `SpecMapTest` (translates `test_specmap.rs`), `SpecMap3dOracleTest` (new, `specmap_3d_oracle`), the deferred-list gates + +**Interfaces:** +- Produces: `public SpecMap(int nin, int flags)`, `public void specAdd(String cvt, double[] args)`; package-private access to the step list for `MapMerge` and dumps. + +- [ ] **Step 1: Write the failing tests:** the 36 tests of `test_specmap.rs` and the 4 of `test_specmap_3d.rs` (from C's `testspecmap.c` and the oracle), the native round trip of a SpecMap with every conversion type, and the simplification cases in `deferred/simplify*.txt` whose only reason is `needs SpecMap`. +- [ ] **Step 2: Run** `mvn test -Dtest='SpecMapTest,SpecMap3dOracleTest'` — Expected: FAIL (no SpecMap). +- [ ] **Step 3: Implement** every conversion C's `specmap.c` has (frequency, energy, wavenumber, wavelength, air wavelength, the velocity definitions, and the rest-frame shifts through PAL), its argument checks and errors, its `MapMerge` (merging and cancelling adjacent steps as C's `MergeSpecMaps` does), and its dump. +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS; deferred lists rewritten with only `needs SpecMap` entries gone. +- [ ] **Step 5: Commit** `Port SpecMap`. + +### Task 2: SpecFrame attributes, formatting and dumps + +**Files:** +- Create: `SpecFrame.java` (Rust `frames/specframe.rs`; C `specframe.c`) +- Modify: `ObjectRegistry.java`, `NativeStream.java` if needed +- Test: `SpecFrameTest` (the attribute, label, unit and dump tests of `test_specframe.rs` and the unit tests of `specframe.rs`), `ClassAttrsTest`, `FrameClassAttrsTest`, `SpecUseDefsOracleTest` (existing deferred cases) + +**Interfaces:** +- Produces: the jniast SpecFrame API; System values FREQ, ENER, WAVN, WAVE, AWAV, VRAD, VOPT, ZOPT, BETA, VELO and their default units; StdOfRest, AlignStdOfRest, RestFreq, SourceVel, SourceVRF, SourceSys, RefRA, RefDec, SpecOrigin, AlignSpecOffset, GeoLat and GeoLon as C has them; package-private `int stdOfRestValue()` and similar accessors Tasks 3, 7 and 8 use. + +- [ ] **Step 1: Write the failing tests:** every `test_specframe.rs` test that needs no conversion between SpecFrames (attributes, defaults, ActiveUnit and Unit changes, Label and Symbol, Title, Format and Unformat, `getRefPos` and `setRefPos`, Errors 1 to 12 of `testspecframe.c` that are attribute errors), the SpecFrame cases of `class_attrs`, `frame_class` and `spec_use_defs`, and a native dump and read with every attribute set and unset (Review Focus 2 and 4). +- [ ] **Step 2: Run** `mvn test -Dtest='SpecFrameTest,ClassAttrsTest,FrameClassAttrsTest,SpecUseDefsOracleTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** the attributes, their defaults, the ActiveUnit behaviour, formatting, `overlay` and dump. + `match` and `subFrame` are Task 3's: until then they keep Frame's behaviour, and no Task 2 test converts between SpecFrames. +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS. +- [ ] **Step 5: Commit** `Port SpecFrame attributes and dumps`. + +### Task 3: SpecFrame conversions + +**Files:** +- Modify: `SpecFrame.java` (C `MakeSpecMapping`, `Match`, `SubFrame`, `Overlay`, `GetRefPos`/`SetRefPos`, `TopoVel`, `SorConvert`, `OriginStdOfRest`, `OriginSystem`) +- Test: `SpecFrameTest` (the conversion tests of `test_specframe.rs`), `SpecConvertOracleTest` (new, `spec_convert_oracle`), `SpecOriginSorOracleTest` (new, `spec_origin_sor_oracle`), `FrameSetTest`/`FindFrameTest` additions, the deferred-list gates + +**Interfaces:** +- Consumes: Task 1's SpecMap, Task 2's attribute accessors. +- Produces: `Frame.convert` and `findFrame` between SpecFrames, CmpFrames holding them, and FrameSets; SpecOrigin and AlignSpecOffset behaviour. + +- [ ] **Step 1: Write the failing tests:** the remaining `test_specframe.rs` tests, `test_spec_convert.rs`, `test_spec_origin_sor.rs`, every conversion check of `testspecframe.c`, the Review Focus 1 cases (each unset attribute, C's result or error), and Review Focus 3 (a conversion leaves both Frames' attributes as they were; two threads get identical Mappings). +- [ ] **Step 2: Run** `mvn test -Dtest='SpecFrameTest,SpecConvertOracleTest,SpecOriginSorOracleTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** C's conversion path in C's order: unit change, system change through SpecMap, standard of rest through the reference position, epoch and observer, SpecOrigin and AlignSpecOffset; the alignment rules of `Match` (AlignSystem, AlignStdOfRest, AlignSpecOffset). +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS; `needs SpecFrame` entries with no other reason pass or carry the next one. +- [ ] **Step 5: Commit** `Convert between SpecFrames as C does`. + +### Task 4: DSBSpecFrame + +**Files:** +- Create: `DSBSpecFrame.java` (Rust `frames/dsbspecframe.rs`; C `dsbspecframe.c`) +- Modify: `ObjectRegistry.java` +- Test: `DSBSpecFrameTest` (translates `test_dsbspecframe.rs` and the unit tests), `DsbTopoOracleTest` (new, `dsb_topo_oracle`), the deferred-list gates + +**Interfaces:** +- Consumes: Tasks 2 and 3. +- Produces: the jniast DSBSpecFrame API; SideBand, DSBCentre, IF, AlignSideBand and ImagFreq as C has them; the sideband conversions. + +- [ ] **Step 1: Write the failing tests:** the 33 tests of `test_dsbspecframe.rs`, `test_dsb_topo.rs`, the DSBSpecFrame cases of the oracles already converted, and a dump round trip. +- [ ] **Step 2: Run** `mvn test -Dtest='DSBSpecFrameTest,DsbTopoOracleTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** as C, including the topocentric conversion of DSBCentre. +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS. +- [ ] **Step 5: Commit** `Port DSBSpecFrame`. + +### Task 5: FluxFrame + +**Files:** +- Create: `FluxFrame.java` (Rust `frames/fluxframe.rs`; C `fluxframe.c`) +- Modify: `ObjectRegistry.java` +- Test: `FluxFrameTest` (translates `test_fluxframe.rs`, `test_flux.rs` from `testflux.c`, and the unit tests), `FluxBadunOracleTest` and `FluxUnitSystemOracleTest` (new), the deferred-list gates + +**Interfaces:** +- Consumes: Tasks 2 and 3 (the SpecFrame a FluxFrame holds). +- Produces: the jniast FluxFrame API; System values FLXDN, FLXDNW, SFCBR, SFCBRW and the unit-driven System choice; conversions between FluxFrames. + +- [ ] **Step 1: Write the failing tests:** the 46 tests of `test_fluxframe.rs`, the 9 of `test_flux.rs`, `test_flux_badun.rs`, the two oracles, and a dump round trip. +- [ ] **Step 2: Run** `mvn test -Dtest='FluxFrameTest,FluxBadunOracleTest,FluxUnitSystemOracleTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** as C, at the pinned C's `SFCBRW` read and write behaviour (a quirk resolved upstream; record it in `docs/rust-c-differences.md`). +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS. +- [ ] **Step 5: Commit** `Port FluxFrame`. + +### Task 6: SpecFluxFrame + +**Files:** +- Create: `SpecFluxFrame.java` (Rust `frames/specfluxframe.rs`; C `specfluxframe.c`) +- Modify: `ObjectRegistry.java` +- Test: `SpecFluxFrameTest` (translates `test_specflux.rs` from `testspecflux.c` and the unit tests), `SpecFluxCmpOracleTest` and `SpecFluxPrimaryOracleTest` (new), the deferred-list gates + +**Interfaces:** +- Consumes: Tasks 2, 3 and 5. +- Produces: the jniast SpecFluxFrame API; conversions between SpecFluxFrames. + +- [ ] **Step 1: Write the failing tests:** `test_specflux.rs`, `test_specflux_cmp.rs`, `test_specflux_primary.rs`, the unit tests, and a dump round trip; a conversion that needs C's flux-scaling MathMap and TranMap expects `needs MathMap`. +- [ ] **Step 2: Run** `mvn test -Dtest='SpecFluxFrameTest,SpecFluxCmpOracleTest,SpecFluxPrimaryOracleTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** as C; `MakeMapF`/`MakeMapI` throw `needs MathMap`, the first absent class C builds there. +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS. +- [ ] **Step 5: Commit** `Port SpecFluxFrame`. + +### Task 7: Reading spectral axes from FITS + +**Files:** +- Create: `FitsWcsSpectral.java` (Rust `fitschan/wcs_spectral.rs`; C `WcsSpectral`, `SpecTrans`'s spectral parts already ported, `IsAIPSSpectral`, the DSB keywords) +- Modify: `FitsWcsRead.java` (`buildSpectral` and the spectral branches that throw `needs SpecFrame`), the AIPS, AIPS++, PC and IRAF read paths where they throw `needs SpecFrame` +- Test: `FitsWcsSpectralTest` (the unit tests), `FitsChanSpecUnitOracleTest` (new, `fitschan_spec_unit_oracle`), `TransformOracleTest`, `WcsconvTest`, `ReadWarningsTest` or its equivalent, the `rust-tests.txt` read entries + +**Interfaces:** +- Consumes: Tasks 1 to 4. +- Produces: FitsChan reads of FREQ, ENER, WAVN, WAVE, AWAV, VRAD, VOPT, ZOPT, VELO and BETA axes with the `-F2W`-style non-linear algorithms C supports without absent classes, SPECSYS, SSYSOBS, SSYSSRC, VELOSYS, ZSOURCE, RESTFRQ, RESTWAV and IMAGFREQ. + +- [ ] **Step 1: Write the failing tests:** the unit tests of `wcs_spectral.rs`, `test_fitschan_spec_unit_oracle.rs`, `test_dsbspecframe_read.rs`, the `rust-tests.txt` read entries whose reason is `needs SpecFrame` or `needs DSBSpecFrame`, and Review Focus 5's read half (`-GRI`, `-LOG` and `-TAB` spectral axes throw `needs GrismMap`, `needs MathMap` and `needs LutMap` or `needs FitsTable` as C would build them). +- [ ] **Step 2: Run** `mvn test -Dtest='FitsWcsSpectralTest,FitsChanSpecUnitOracleTest,TransformOracleTest,WcsconvTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** C's `WcsSpectral` path, in C's order of keyword use and warnings. +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS; `headers.txt`, `wcsconv.txt` and `read-warnings.txt` lose every entry whose only reason was a class this phase adds. +- [ ] **Step 5: Commit** `Read spectral axes from FITS headers`. + +### Task 8: Writing spectral axes to FITS + +**Files:** +- Create: `FitsSpectralAxes.java` (Rust `fitschan/fset_to_store/spectral_axes.rs`; C `SpectralAxes`) +- Modify: `FitsFsetToStore.java` (the spectral branch), `FitsWcsWrite.java`, `FitsEncPc.java`, `FitsEncIraf.java`, `FitsEncAips.java` (the spectral keywords of `AIPSFromStore` and `AIPSPPFromStore`), wherever phase 3 throws `needs SpecFrame` on the write side +- Test: `FitsSpectralAxesTest` (the unit tests), `FitsChanWcsWriteTest` and `FitsChanEncodingsOracleTest` cases now in reach, `WcsconvTest`, the `rust-tests.txt` write entries + +**Interfaces:** +- Consumes: Tasks 1 to 4 and phase 3's writers. +- Produces: spectral axes written in FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS and FITS-AIPS++ as C writes them; `-GRI`/`-GRA` (C's `grism` branch) throws `needs GrismMap`. + +- [ ] **Step 1: Write the failing tests:** the unit tests of `spectral_axes.rs`, the write entries of `rust-tests.txt` and the oracle cases whose reason is a class this phase adds, `wcsconv` write rows for spectral inputs, and Review Focus 5's write half (each encoding's spectral header written and read back transforms as the original). +- [ ] **Step 2: Run** `mvn test -Dtest='FitsSpectralAxesTest,FitsChanWcsWriteTest,FitsChanEncodingsOracleTest,WcsconvTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** C's `SpectralAxes`, including its choice of algorithm, reference value and keywords, at the pinned C (the upstream fix to its default reference value is recorded, not followed). +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS. +- [ ] **Step 5: Commit** `Write spectral axes to FITS headers`. + +### Task 9: FITS-CLASS + +**Files:** +- Modify: `FitsEncClass.java` (Rust `fitschan/enc_class.rs`; C `ClassTrans`, `CLASSFromStore`), `FitsSpecTrans.java` (the FITS-CLASS refusal becomes C's `ClassTrans`), `FitsChan.java` read dispatch +- Test: `FitsEncClassTest` (the unit tests), `FitsChanClassTest` (translates `test_fitschan_class.rs`), `WcsconvTest` CLASS rows, `TransformOracleTest` + +**Interfaces:** +- Consumes: Tasks 1 to 8. +- Produces: FITS-CLASS read and write as C, with the pinned C's quirks (the `astTranN` three-coordinate call and the axis indices recorded in `docs/rust-c-differences.md` stay as C). + +- [ ] **Step 1: Write the failing tests:** the unit tests of `enc_class.rs`, `test_fitschan_class.rs`, the 9 FITS-CLASS `wcsconv` rows and the FITS-CLASS headers. +- [ ] **Step 2: Run** `mvn test -Dtest='FitsEncClassTest,FitsChanClassTest,WcsconvTest'` — Expected: FAIL. +- [ ] **Step 3: Implement** as C. +- [ ] **Step 4: Run** the Step 2 command, then `mvn -q test` — Expected: PASS. +- [ ] **Step 5: Commit** `Read and write FITS-CLASS headers`. + +### Task 10: The remaining Rust tests + +**Files:** +- Test: translations of every remaining test in `rust-tests.txt` whose reason names a class this phase adds (`test_find_frame.rs`, `test_convert.rs`, `test_class_attrs.rs`, `test_fitschan_*`, `cmpframe.rs`, `test_frame_api.rs` and the others the list names), and of `test_spec_use_defs.rs`, `test_class_attrs.rs` and `test_frame_class_attrs.rs` cases now in reach + +- [ ] **Step 1: Translate** each test, expected values from C as the Rust test records them. +- [ ] **Step 2: Run** `mvn -q test` — Expected: PASS, or a failure that is a port defect, fixed in the class it belongs to. +- [ ] **Step 3: Commit** `Translate the remaining spectral Rust tests`. + +### Task 11: Sweep the deferred lists + +- [ ] **Step 1: Run** `mvn -q test -Dast.writeDeferred=true` and diff every `deferred/*.txt` against the branch base: no entry names SpecMap, SpecFrame, DSBSpecFrame, FluxFrame or SpecFluxFrame as its reason; every entry that changed reason names a class still absent. +- [ ] **Step 2: Run** `mvn verify` on JDK 21 and `mvn test -Djvm=` — Expected: PASS. +- [ ] **Step 3: Commit** any list changes as `Sweep the deferred lists after phase 4`. + +### Task 12: The phase 4 report + +- [ ] **Step 1: Write** `docs/reports/2026-11-
-phase4-report.md` and `docs/reports/2026-11-
-phase4-rulings.md` in the form of the phase 3 report: what was ported, departures from the plan, gates before and after, tolerances with their traced causes, C defects found, final review, gaps and risks. +- [ ] **Step 2: Commit** `Report phase 4`. diff --git a/src/main/java/uk/ac/starlink/ast/CScan.java b/src/main/java/uk/ac/starlink/ast/CScan.java index cd23aa5..47a3c03 100644 --- a/src/main/java/uk/ac/starlink/ast/CScan.java +++ b/src/main/java/uk/ac/starlink/ast/CScan.java @@ -187,6 +187,37 @@ private static int skipSpace(String s, int i) { return i; } + /** Whether a value holds a character that is not white space, as C's {@code "%*s"} needs. */ + static boolean hasWord(String value) { + for (int i = 0; i < value.length(); i++) { + if (!isCSpace(value.charAt(i))) { + return true; + } + } + return false; + } + + /** + * C's {@code sscanf( value, " %lg %n%*s %n" )} reading all of the value: a number, then one + * word after white space. Gives the number and the index of the word, or null. + */ + static double[] numberThenWord(String value) { + int n = value.length(); + Num num = strtod(value, skipSpace(value, 0)); + if (num == null) { + return null; + } + int off = skipSpace(value, num.end); + int i = off; + while (i < n && !isCSpace(value.charAt(i))) { + i++; + } + if (i == off) { + return null; + } + return skipSpace(value, i) == n ? new double[] {num.value, off} : null; + } + /** * {@code sscanf(s, " %lf %n")} consuming the whole string: the value, or null if the string is * not one number with optional surrounding white space. diff --git a/src/main/java/uk/ac/starlink/ast/CmpFrame.java b/src/main/java/uk/ac/starlink/ast/CmpFrame.java index 1bb62de..e34b5b8 100644 --- a/src/main/java/uk/ac/starlink/ast/CmpFrame.java +++ b/src/main/java/uk/ac/starlink/ast/CmpFrame.java @@ -63,7 +63,7 @@ public CmpFrame(Frame frame1, Frame frame2) { } /** Creates a CmpFrame, marking its components shared if {@code share} (C's {@code astInitCmpFrame}). */ - private CmpFrame(Frame frame1, Frame frame2, boolean share) { + CmpFrame(Frame frame1, Frame frame2, boolean share) { super(); this.frame1 = Objects.requireNonNull(frame1, "frame1"); this.frame2 = Objects.requireNonNull(frame2, "frame2"); @@ -172,6 +172,19 @@ void deepCopy() { perm = perm.clone(); } + /** + * Takes the Object, Mapping, Frame and CmpFrame parts of {@code src}, as C's copy of a CmpFrame + * does: copies of the components and the permutation. + */ + @Override + void castCopyFrom(AstObject src) { + super.castCopyFrom(src); + CmpFrame f = (CmpFrame) src; + frame1 = (Frame) f.frame1.copy(); + frame2 = (Frame) f.frame2.copy(); + perm = f.perm.clone(); + } + // ------------------------------------------------------------------ // Components // ------------------------------------------------------------------ @@ -201,6 +214,16 @@ Mapping[] decomposeInto(boolean[] flags) { return new Mapping[] {frame1, frame2}; } + /** The first component Frame, the CmpFrame's own (C's {@code frame1}). */ + final Frame firstFrame() { + return frame1; + } + + /** The second component Frame, the CmpFrame's own (C's {@code frame2}). */ + final Frame secondFrame() { + return frame2; + } + /** The component Frame holding internal axis {@code internal}, numbered from 1. */ private Frame component(int internal) { return internal <= frame1.getNaxes() ? frame1 : frame2; @@ -342,7 +365,7 @@ public void permAxes(int[] perm) { } /** C's {@code PermAxes} (cmpframe.c), given the permutation numbered from 0. */ - private void permAxes0(int[] perm0) { + void permAxes0(int[] perm0) { checkPerm(perm0, "astPermAxes"); int naxes = getNaxes(); int[] old = perm.clone(); @@ -754,14 +777,20 @@ public double[] resolve(double[] point1, double[] point2, double[] point3, doubl // ------------------------------------------------------------------ /** - * This CmpFrame cast into the class of another (C's {@code Cast}, cmpframe.c): for a CmpFrame - * class, as {@link Frame#cast} does; for any other, a plain Frame with this CmpFrame's axes and - * the attributes set on its components overlaid, itself cast into that class. + * This CmpFrame cast into the class of another (C's {@code Cast}, cmpframe.c): for a class of + * the CmpFrame family, whether an ancestor of this CmpFrame's class or a descendant, a copy of + * this CmpFrame as an instance of that class ({@link #castCopy}); for any other, a plain Frame + * with this CmpFrame's axes and the attributes set on its components overlaid, itself cast + * into that class. */ @Override Frame cast(Frame obj) { if (obj instanceof CmpFrame) { - return super.cast(obj); + // C's astCastCopy into the object's own class is a copy, whose attributes are all valid. + if (obj.getClass() == getClass()) { + return (Frame) copy(); + } + return castCopy(obj); } int naxes = getNaxes(); Frame cfrm = new Frame(naxes); @@ -772,6 +801,30 @@ Frame cast(Frame obj) { return cfrm.cast(obj); } + /** + * A deep copy of this CmpFrame as an instance of the class of {@code obj}, a class of the + * CmpFrame family, with the attributes that class does not allow cleared (C's {@code + * astCastCopy} followed by {@code astCleanAttribs}). As in C, the class need not be an + * ancestor: a CmpFrame cast into a SpecFluxFrame is a SpecFluxFrame holding copies of the + * CmpFrame's components, whatever their classes (cmpframe.c {@code Cast} calls {@code + * astCastCopy} for any {@code obj} that is a CmpFrame or one of its subclasses). Any other + * class is cast as by {@link Frame#castCopy}. + */ + @Override + Frame castCopy(Frame obj) { + CmpFrame res; + if (obj.getClass() == CmpFrame.class) { + res = transientCmpFrame(frame1, frame2); + } else if (obj.getClass() == SpecFluxFrame.class) { + res = new SpecFluxFrame(frame1, frame2, false); + } else { + return super.castCopy(obj); + } + res.castCopyFrom(this); + res.cleanAttribs(); + return res; + } + /** * Overlays the attributes set on the components onto another Frame (C's {@code Overlay}, * cmpframe.c). If the result is a CmpFrame whose two components each take their axes from a diff --git a/src/main/java/uk/ac/starlink/ast/DSBSpecFrame.java b/src/main/java/uk/ac/starlink/ast/DSBSpecFrame.java new file mode 100644 index 0000000..4a5c877 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/DSBSpecFrame.java @@ -0,0 +1,796 @@ +package uk.ac.starlink.ast; + +/** + * A dual sideband spectral coordinate system. A DSBSpecFrame is a SpecFrame describing positions + * in a spectrum from a dual sideband instrument, in which each point holds contributions from two + * frequencies, one in the lower sideband (LSB) and one in the upper sideband (USB), an equal + * distance on either side of the local oscillator (LO) frequency. + * + *

The SideBand attribute says whether the values are positions in the upper sideband, in the + * lower sideband, or topocentric offsets from the LO frequency. The LO frequency is the sum of the + * DSBCentre, a spectral position of interest (given in the System, Unit and standard of rest of + * the DSBSpecFrame and stored as a topocentric frequency), and the intermediate frequency, the + * signed IF attribute. The sideband holding the DSBCentre is the observed sideband, and the other + * is the image sideband; the read-only ImagFreq attribute is the image sideband frequency of the + * rest frequency. Two DSBSpecFrames are aligned as SpecFrames unless both have AlignSideBand set, + * when each is first mapped to its observed sideband. The Domain defaults to {@code DSBSPECTRUM}. + * + *

Ported from C {@code dsbspecframe.c}, with Rust {@code frames/dsbspecframe.rs}. + */ +public class DSBSpecFrame extends SpecFrame { + + /** The lower sideband (C's {@code LSB}). */ + static final int LSB = -1; + + /** Offsets from the local oscillator frequency (C's {@code LO}). */ + static final int LO = 0; + + /** The upper sideband (C's {@code USB}). */ + static final int USB = 1; + + /** The value of an unset SideBand (C's {@code BADSB}). */ + private static final int BADSB = -9999; + + /** The DSBCentre of an unset attribute, a topocentric frequency in Hz. */ + private static final double DEFAULT_DSBCENTRE = 3.0E10; + + /** The IF of an unset attribute, in Hz. */ + private static final double DEFAULT_IF = 4.0E9; + + /** The digits C writes a full-precision double with ({@code AST__DBL_DIG}). */ + private static final int DBL_DIG = 17; + + /** The DSBCentre as a topocentric frequency in Hz, or bad if unset. */ + private double dsbCentre = AST__BAD; + + /** The IF in Hz, or bad if unset. */ + private double ifr = AST__BAD; + + /** The SideBand, {@link #LSB}, {@link #LO} or {@link #USB}, or {@link #BADSB} if unset. */ + private int sideBand = BADSB; + + /** The AlignSideBand flag, 0 or 1, or -1 if unset. */ + private int alignSideBand = -1; + + /** + * Creates a DSBSpecFrame with every attribute at its default: the defaults of a SpecFrame, a + * DSBCentre of 30 GHz (topocentric), an IF of 4 GHz and the lower sideband. + */ + public DSBSpecFrame() { + super(); + } + + /** + * Loads a DSBSpecFrame from its description, as C's {@code astLoadDSBSpecFrame} does: DSBCen, + * IF, SideBn and AlSdBn, each unset if absent. + * + * @param node the description + * @throws AstException with status {@code AST__ATTIN} if the SideBand is not USB, LSB or LO + */ + DSBSpecFrame(NativeNode node) { + super(node); + NativeNode part = node.section("DSBSpecFrame"); + dsbCentre = part.readDouble("DSBCen", AST__BAD); + ifr = part.readDouble("IF", AST__BAD); + String text = part.getStringIfSet("SideBn"); + if (text != null) { + if ("USB".equals(text)) { + sideBand = USB; + } else if ("LSB".equals(text)) { + sideBand = LSB; + } else if ("LO".equals(text)) { + sideBand = LO; + } else { + throw Ast.err( + AstException.AST__ATTIN, "astRead(Channel): Invalid SideBand description \"" + text + "\"."); + } + } + int ival = part.readInt("AlSdBn", -1); + if (ival != -1) { + alignSideBand = ival != 0 ? 1 : 0; + } + } + + @Override + String dumpComment() { + return "Dual sideband spectral axis"; + } + + /** Writes the DSBSpecFrame class's part of a description, as C's {@code Dump} (dsbspecframe.c) does. */ + @Override + void dump(NativeNode node) { + super.dump(node); + node.writeIsA("SpecFrame", "Description of spectral coordinate system"); + node.writeDouble("DSBCen", testDSBCentre(), true, dsbCentreValue(), "Central frequency (Hz topo)"); + node.writeDouble("IF", testIF(), true, ifValue(), "Intermediate frequency (Hz)"); + int ival = sideBandValue(); + String cval; + String comm; + if (ival == LSB) { + cval = "LSB"; + comm = "Represents lower sideband"; + } else if (ival == LO) { + cval = "LO"; + comm = "Represents offset from LO frequency"; + } else { + cval = "USB"; + comm = "Represents upper sideband"; + } + node.writeString("SideBn", testSideBand(), true, cval, comm); + node.writeInt("AlSdBn", testAlignSideBand(), true, alignSideBandValue() ? 1 : 0, "Align sidebands?"); + } + + // ------------------------------------------------------------------ + // Attributes + // ------------------------------------------------------------------ + + /** + * Gets the AlignSideBand attribute: whether the SideBand is taken into account when this + * DSBSpecFrame is aligned with another by {@code findFrame} or {@code convert}. If both + * DSBSpecFrames have AlignSideBand set, values are mapped from the target's sideband to its + * observed sideband, then between the spectral systems of the two, and then from the result's + * observed sideband to its own sideband; otherwise the two are aligned as SpecFrames, the + * SideBand being ignored. The default is false. + * + * @return the AlignSideBand + */ + public boolean getAlignSideBand() { + return getB("AlignSideBand"); + } + + /** + * Sets the AlignSideBand attribute. + * + * @param alignSideBand the AlignSideBand + */ + public void setAlignSideBand(boolean alignSideBand) { + setB("AlignSideBand", alignSideBand); + } + + /** + * Gets the DSBCentre attribute: the central position of interest, which with the IF gives the + * local oscillator frequency. It is given in the System, Unit and standard of rest of this + * DSBSpecFrame, and stored as a topocentric frequency, so it follows a change of those; the + * attributes needed to convert it to a topocentric frequency (such as ObsLon, ObsLat, Epoch, + * RefRA, RefDec and RestFreq) should be set first. The default is 30 GHz, topocentric. + * + * @return the DSBCentre + * @throws AstException if it cannot be converted from a topocentric frequency + */ + public double getDsbCentre() { + return getD("DsbCentre"); + } + + /** + * Sets the DSBCentre attribute. + * + * @param dsbCentre the DSBCentre, in the System and Unit of this DSBSpecFrame + * @throws AstException with status {@code AST__ATTIN} if the value has no topocentric frequency + */ + public void setDsbCentre(double dsbCentre) { + setD("DsbCentre", dsbCentre); + } + + /** + * Gets the IF attribute: the topocentric intermediate frequency in GHz, which added to the + * DSBCentre (as a topocentric frequency) gives the local oscillator frequency. Its sign says + * whether the local oscillator is above or below the DSBCentre, and so which is the observed + * sideband. A value may be given with units of frequency, such as {@code 4000 MHz}. The default + * is 4 GHz. + * + * @return the IF, in GHz + */ + public double getIf() { + return getD("If"); + } + + /** + * Sets the IF attribute. + * + * @param ifreq the IF, in GHz + */ + public void setIf(double ifreq) { + setD("If", ifreq); + } + + /** + * Gets the SideBand attribute: {@code USB} for the upper sideband, {@code LSB} for the lower + * sideband, or {@code LO} for offsets from the local oscillator frequency. It may be set to + * {@code observed} or {@code image} for the sideband that holds the DSBCentre or the other. The + * default is the observed sideband: the lower if the IF is positive, the upper otherwise. + * + * @return the SideBand + */ + public String getSideBand() { + return getC("SideBand"); + } + + /** + * Sets the SideBand attribute. + * + * @param sideBand {@code USB}, {@code LSB}, {@code LO}, {@code observed} or {@code image}, in + * any case + * @throws AstException with status {@code AST__ATTIN} if the value is none of these + */ + public void setSideBand(String sideBand) { + setC("SideBand", sideBand); + } + + /** The DSBCentre as a topocentric frequency in Hz: set, or 3.0E10 (C's {@code GetDSBCentre}). */ + double dsbCentreValue() { + return dsbCentre != AST__BAD ? dsbCentre : DEFAULT_DSBCENTRE; + } + + void setDsbCentreValue(double value) { + dsbCentre = value; + } + + boolean testDSBCentre() { + return dsbCentre != AST__BAD; + } + + void clearDSBCentre() { + dsbCentre = AST__BAD; + } + + /** The IF in Hz: set, or 4.0E9 (C's {@code GetIF}). */ + double ifValue() { + return ifr != AST__BAD ? ifr : DEFAULT_IF; + } + + void setIfValue(double value) { + ifr = value; + } + + boolean testIF() { + return ifr != AST__BAD; + } + + void clearIF() { + ifr = AST__BAD; + } + + /** The SideBand: set, or the observed sideband, {@link #LSB} for a positive IF and {@link #USB} otherwise. */ + int sideBandValue() { + if (sideBand != BADSB) { + return sideBand; + } + return ifValue() > 0 ? LSB : USB; + } + + /** Sets the SideBand, as C's {@code SetSideBand} does: a negative value is LSB, zero LO and a positive one USB. */ + void setSideBandValue(int value) { + sideBand = value < 0 ? LSB : (value == 0 ? LO : USB); + } + + boolean testSideBand() { + return sideBand != BADSB; + } + + void clearSideBand() { + sideBand = BADSB; + } + + /** The AlignSideBand flag: set, or false. */ + boolean alignSideBandValue() { + return alignSideBand == 1; + } + + void setAlignSideBandValue(boolean value) { + alignSideBand = value ? 1 : 0; + } + + boolean testAlignSideBand() { + return alignSideBand != -1; + } + + void clearAlignSideBand() { + alignSideBand = -1; + } + + /** + * The ImagFreq in Hz (C's {@code GetImagFreq}): the rest frequency, taken as a frequency in the + * observed sideband in the source's standard of rest, transformed to the image sideband, with a + * copy of this DSBSpecFrame set to describe it. + * + * @throws AstException if the Mapping between the sidebands cannot be made + */ + double imagFreqValue() { + DSBSpecFrame rfFrame = (DSBSpecFrame) copy(); + rfFrame.setStdOfRestValue(AST__SCSOR); + rfFrame.setSystemValue(AST__FREQ); + rfFrame.setUnit(1, "Hz"); + rfFrame.setC("SideBand", "observed"); + int sb = rfFrame.sideBandValue(); + Mapping map; + if (sb == USB) { + map = rfFrame.toLsbMapping("astGetImagFreq"); + } else if (sb == LSB) { + map = rfFrame.toUsbMapping("astGetImagFreq"); + } else { + throw Ast.err( + AstException.AST__INTER, + "astGetImagFreq(" + astClass() + "): Illegal sideband value (" + sb + + ") encountered (internal AST programming error)."); + } + return transformValue(map, rfFrame.restFreqValue()); + } + + /** The Domain: set, or {@code DSBSPECTRUM}. */ + @Override + public String getDomain() { + return testDomain() ? super.getDomain() : "DSBSPECTRUM"; + } + + /** + * Gets the Label of the axis (C's {@code GetLabel}): set, or the SpecFrame's default followed + * by the SideBand in brackets, as {@code Frequency (LSB)}. + */ + @Override + public String getLabel(int axis) { + validateAxis(axis, true, "astGetLabel"); + String result = super.getLabel(axis); + if (!testLabel(axis)) { + result = result + " (" + getAttrib("sideband") + ")"; + } + return result; + } + + // ------------------------------------------------------------------ + // Sideband Mappings + // ------------------------------------------------------------------ + + /** One value transformed by a Mapping with one input and one output. */ + private static double transformValue(Mapping map, double value) { + return map.tran1(1, new double[] {value}, true)[0]; + } + + /** + * C's {@code VerifyAttrs} (dsbspecframe.c): with UseDefs false, checks that each attribute + * named in {@code attrs} (DSBCentre or IF, separated by white space, a name standing for every + * attribute it starts) is set. + * + * @throws AstException with status {@code AST__NOVAL} if one is not, saying that the + * DSBSpecFrame cannot do {@code purp} + */ + private void verifyDsbAttrs(String purp, String attrs, String method) { + if (getUseDefs()) { + return; + } + int i = 0; + int n = attrs.length(); + while (i < n) { + while (i < n && CScan.isCSpace(attrs.charAt(i))) { + i++; + } + int start = i; + while (i < n && !CScan.isCSpace(attrs.charAt(i))) { + i++; + } + if (i == start) { + break; + } + String a = attrs.substring(start, i); + boolean set; + String desc; + if ("DSBCentre".startsWith(a)) { + set = testDSBCentre(); + desc = "central position of interest"; + } else if ("IF".startsWith(a)) { + set = testIF(); + desc = "intermediate frequency"; + } else { + throw Ast.err( + AstException.AST__INTER, + "VerifyAttrs(DSBSpecFrame): Unknown attribute name \"" + a + + "\" supplied (AST internal programming error)."); + } + if (!set) { + throw Ast.err( + AstException.AST__NOVAL, + method + "(" + astClass() + "): Cannot " + purp + ".\nNo value has been set for the AST \"" + a + + "\" attribute (" + desc + ")."); + } + } + } + + /** + * The local oscillator frequency, a topocentric frequency in Hz (C's {@code GetLO}): the + * DSBCentre plus the IF. + * + * @param checkMsg if not null, the IF and DSBCentre must be set when UseDefs is false, and an + * error says that the DSBSpecFrame cannot do this + * @param method the method named in an error + * @throws AstException with status {@code AST__NOVAL} if an attribute {@code checkMsg} needs + * is not set, or {@code AST__ATTIN} if the frequency is less than the size of the IF + */ + double loValue(String checkMsg, String method) { + if (checkMsg != null) { + verifyDsbAttrs(checkMsg, "IF DSBCentre", method); + } + double fIf = ifValue(); + double result = dsbCentreValue() + fIf; + if (result < Math.abs(fIf)) { + // C reads the DSBCentre for the second message after reporting the first, when its + // getter gives 3.0E10 whatever the attribute holds. + throw Ast.err( + AstException.AST__ATTIN, + method + "(" + astClass() + "): The local oscillator frequency (" + CFormat.format("%g", result) + + " Hz) is too low (less than the intermediate frequency: " + + CFormat.format("%g", Math.abs(fIf)) + " Hz).\n This could be caused by a bad value " + + "for either the IF attribute (currently " + CFormat.format("%g", fIf) + + " Hz) or the DSBCentre attribute (currently " + CFormat.format("%g", DEFAULT_DSBCENTRE) + + " Hz)."); + } + return result; + } + + /** + * The Mapping from the spectral system of this DSBSpecFrame to topocentric frequency in Hz, or + * its inverse (C's {@code TopoMap}): the SpecFrame attributes of this DSBSpecFrame are overlaid + * onto a new SpecFrame, aligned in the topocentric standard of rest, which is converted to a + * copy of itself describing topocentric frequency in Hz. + * + * @param forward true for the Mapping to topocentric frequency, false for its inverse + * @param method the method named in an error + * @throws AstException with status {@code AST__INTER} if there is no conversion + */ + Mapping topoMap(boolean forward, String method) { + SpecFrame tf1 = new SpecFrame(); + super.overlay(new int[] {0}, tf1); + tf1.setAlignStdOfRestValue(AST__TPSOR); + SpecFrame tf2 = (SpecFrame) tf1.copy(); + tf2.setSystemValue(AST__FREQ); + tf2.setStdOfRestValue(AST__TPSOR); + tf2.setUnit(1, "Hz"); + FrameSet fs = tf1.convert(tf2, ""); + if (fs == null) { + throw Ast.err( + AstException.AST__INTER, + method + "(" + astClass() + "): Cannot convert DSBCentre value from the supplied system to " + + "topocentric frequency (internal AST programming error)."); + } + Mapping result = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + if (!forward) { + result.invert(); + } + return result; + } + + /** + * The Mapping from this DSBSpecFrame to a copy of it representing another sideband, as C's + * {@code ToLSBMapping} and {@code ToUSBMapping} build it: {@code tmap}, the Mapping to + * topocentric frequency, then a WinMap taking {@code ina} and {@code inb} to {@code outa} and + * {@code outb}, then {@code tmap} inverted. + */ + private static Mapping sideBandMapping(Mapping tmap, double ina, double inb, double outa, double outb) { + Mapping fmap = new WinMap(1, new double[] {ina}, new double[] {inb}, new double[] {outa}, new double[] {outb}); + Mapping map1 = new CmpMap(tmap, fmap, true); + // The CmpMap keeps the Invert attribute tmap has now, as C's does. + tmap.invert(); + Mapping map2 = new CmpMap(map1, tmap, true); + return map2.simplify(); + } + + /** + * The Mapping from this DSBSpecFrame to a copy of it representing the lower sideband (C's + * {@code ToLSBMapping}): a UnitMap if it represents the lower sideband already. + * + * @param method the method named in an error + * @throws AstException as {@link #loValue} does + */ + Mapping toLsbMapping(String method) { + int sb = sideBandValue(); + if (sb == LSB) { + return new UnitMap(1); + } + Mapping tmap = topoMap(true, method); + double fLo = loValue("create a Mapping to lower sideband", "astGetImagFreq"); + if (sb == USB) { + return sideBandMapping(tmap, 0.0, 2 * fLo, 2 * fLo, 0.0); + } + return sideBandMapping(tmap, 0.0, fLo, fLo, 0.0); + } + + /** + * The Mapping from this DSBSpecFrame to a copy of it representing the upper sideband (C's + * {@code ToUSBMapping}): a UnitMap if it represents the upper sideband already. + * + * @param method the method named in an error + * @throws AstException as {@link #loValue} does + */ + Mapping toUsbMapping(String method) { + int sb = sideBandValue(); + if (sb == USB) { + return new UnitMap(1); + } + Mapping tmap = topoMap(true, method); + double fLo = loValue("create a Mapping to upper sideband", "astGetImagFreq"); + if (sb == LSB) { + return sideBandMapping(tmap, 0.0, 2 * fLo, 2 * fLo, 0.0); + } + return sideBandMapping(tmap, 0.0, -fLo, fLo, 0.0); + } + + /** The Mapping to a copy of this DSBSpecFrame representing its observed sideband, {@code obsSb}. */ + private Mapping toObservedMapping(int obsSb, Frame errorFrame) { + if (obsSb == USB) { + return toUsbMapping("astSubFrame"); + } else if (obsSb == LSB) { + return toLsbMapping("astSubFrame"); + } else { + throw Ast.err( + AstException.AST__INTER, + "astGetImagFreq(" + errorFrame.astClass() + "): Illegal sideband value (" + obsSb + + ") encountered (internal AST programming error)."); + } + } + + /** + * The observed sideband, found as C's {@code SubFrame} finds it: the SideBand is set to {@code + * observed} and then set back to the value it had, so that it is set afterwards. + */ + private int observedSideBand() { + int oldSb = sideBandValue(); + setC("SideBand", "observed"); + int obsSb = sideBandValue(); + setSideBandValue(oldSb); + return obsSb; + } + + // ------------------------------------------------------------------ + // Matching + // ------------------------------------------------------------------ + + /** + * Matches this DSBSpecFrame, a template, against a target (C's {@code Match}, dsbspecframe.c): + * as a SpecFrame matches it; then, if the matched target axis belongs to a DSBSpecFrame, the + * target's {@link #subFrame} is called again with this template, as C calls it. + */ + @Override + FrameFinder.MatchResult match(Frame target, boolean matchSub) { + FrameFinder.MatchResult m = super.match(target, matchSub); + if (m == null) { + return null; + } + Frame frame0 = target.primaryFrame(m.targetAxes[0] + 1, new int[1]); + if (!(frame0 instanceof DSBSpecFrame)) { + return m; + } + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + if (!target.subFrame(this, 1, m.targetAxes, m.templateAxes, map, result)) { + return null; + } + return new FrameFinder.MatchResult(m.templateAxes, m.targetAxes, map[0], result[0]); + } + + /** + * Selects axes from this DSBSpecFrame (C's {@code SubFrame}, dsbspecframe.c): as a SpecFrame + * does; then, if the template and the result are DSBSpecFrames and the sidebands are aligned, + * the Mapping first maps this DSBSpecFrame's values to its observed sideband and last maps the + * result's observed sideband to its own. The sidebands are aligned while a FrameSet's integrity + * is restored ({@code AST__INTFLAG} set on this target), and otherwise if both this target and + * the template have AlignSideBand set. Finding the observed sideband leaves this target's + * SideBand set to the value it had (a C quirk, followed here). + * + * @throws AstException as {@link SpecFrame#subFrame} does, or as {@link #loValue} does + */ + @Override + boolean subFrame( + Frame template, int resultNaxes, int[] targetAxes, int[] templateAxes, Mapping[] map, Frame[] result) { + boolean match = super.subFrame(template, resultNaxes, targetAxes, templateAxes, map, result); + if (match && template instanceof DSBSpecFrame && result[0] instanceof DSBSpecFrame) { + boolean alignsb; + if ((getFrameFlags() & AST__INTFLAG) != 0) { + alignsb = true; + } else { + alignsb = alignSideBandValue() && ((DSBSpecFrame) template).alignSideBandValue(); + } + if (alignsb) { + Mapping map1 = toObservedMapping(observedSideBand(), this); + DSBSpecFrame dsbresult = (DSBSpecFrame) result[0]; + Mapping map2 = dsbresult.toObservedMapping(dsbresult.observedSideBand(), this); + map2.invert(); + Mapping map3 = new CmpMap(map1, map[0], true); + map1 = new CmpMap(map3, map2, true); + map[0] = map1.simplify(); + } + } + if (!match) { + map[0] = null; + result[0] = null; + } + return match; + } + + /** + * Overlays the attributes set on this DSBSpecFrame, the template, onto another Frame (C's + * {@code Overlay}, dsbspecframe.c): those of a SpecFrame, then, onto a DSBSpecFrame, the + * DSBCentre, IF, SideBand and AlignSideBand that are set. + */ + @Override + void overlay(int[] templateAxes, Frame result) { + super.overlay(templateAxes, result); + if (result instanceof DSBSpecFrame) { + DSBSpecFrame res = (DSBSpecFrame) result; + if (testDSBCentre()) { + res.setDsbCentreValue(dsbCentreValue()); + } + if (testIF()) { + res.setIfValue(ifValue()); + } + if (testSideBand()) { + res.setSideBandValue(sideBandValue()); + } + if (testAlignSideBand()) { + res.setAlignSideBandValue(alignSideBandValue()); + } + } + } + + // ------------------------------------------------------------------ + // String-based attribute access + // ------------------------------------------------------------------ + + @Override + String getAttrib(String attrib) { + if ("dsbcentre".equals(attrib)) { + double dval = dsbCentreValue(); + Mapping tmap = topoMap(false, "astGetAttrib"); + double dtemp = transformValue(tmap, dval); + if (dtemp == AST__BAD) { + throw Ast.err( + AstException.AST__INTER, + "astGetAttrib(" + astClass() + "): Cannot convert DSBCentre value from topocentric " + + "frequency to the required system."); + } + return CFormat.format("%." + DBL_DIG + "g", dtemp); + } else if ("if".equals(attrib)) { + return CFormat.format("%." + DBL_DIG + "g", ifValue() * 1.0E-9); + } else if ("imagfreq".equals(attrib)) { + return CFormat.format("%." + DBL_DIG + "g", imagFreqValue() * 1.0E-9); + } else if ("sideband".equals(attrib)) { + int ival = sideBandValue(); + return ival == USB ? "USB" : (ival == LO ? "LO" : "LSB"); + } else if ("alignsideband".equals(attrib)) { + return alignSideBandValue() ? "1" : "0"; + } + return super.getAttrib(attrib); + } + + /** The error C's {@code SetAttrib} reports for a setting it cannot use. */ + private AstException invalidSetting(String setting) { + return Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): The setting \"" + setting + "\" is invalid for a " + astClass() + + "."); + } + + /** + * Sets an attribute from its value as a string, as C's {@code SetAttrib} (dsbspecframe.c) + * does. C takes any setting holding the text {@code dsbcentre=} for a DSBCentre setting, so + * one of another attribute whose value holds that text is refused (a C quirk, followed here). + */ + @Override + void setAttrib(String attrib, String value) { + String setting = attrib + "=" + value; + if (setting.contains("dsbcentre=")) { + setDsbCentreAttrib(attrib, value, setting); + return; + } + Double dval = CScan.scanDouble(value); + double[] numberThenWord = CScan.numberThenWord(value); + Integer ival = CScan.scanInt(value); + String word = oneWord(value); + if ("if".equals(attrib) && dval != null) { + setIfValue(dval * 1.0E9); + } else if ("if".equals(attrib) && numberThenWord != null) { + String unit = value.substring((int) numberThenWord[1]); + Mapping umap = Units.unitMapper(unit, "Hz"); + if (umap == null) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Intermediate frequency given in an inappropriate system " + + "of units \"" + CFormat.format("%g", numberThenWord[0]) + " " + unit + "\"."); + } + setIfValue(transformValue(umap, numberThenWord[0])); + } else if ("sideband".equals(attrib) && word != null) { + if (chrMatch("usb", word)) { + setSideBandValue(USB); + } else if (chrMatch("lsb", word)) { + setSideBandValue(LSB); + } else if (chrMatch("lo", word)) { + setSideBandValue(LO); + } else if (chrMatch("observed", word)) { + setSideBandValue(ifValue() > 0 ? LSB : USB); + } else if (chrMatch("image", word)) { + setSideBandValue(ifValue() <= 0 ? LSB : USB); + } else { + throw invalidSetting(setting); + } + } else if ("alignsideband".equals(attrib) && ival != null) { + setAlignSideBandValue(ival != 0); + } else if ("imagfreq".equals(attrib)) { + throw Ast.err( + AstException.AST__NOWRT, + "astSet: The setting \"" + setting + "\" is invalid for a " + astClass() + + ".\nThis is a read-only attribute."); + } else { + super.setAttrib(attrib, value); + } + } + + /** + * A DSBCentre setting (C's {@code SetAttrib}): a value in the System and Unit of this + * DSBSpecFrame, or a value with units converted to its Unit, converted to a topocentric + * frequency and stored. + */ + private void setDsbCentreAttrib(String attrib, String value, String setting) { + boolean ok = false; + double dval = 0.0; + boolean named = "dsbcentre".equals(attrib); + Double plain = named ? CScan.scanDouble(value) : null; + double[] numberThenWord = named && plain == null ? CScan.numberThenWord(value) : null; + if (plain != null) { + dval = plain; + ok = true; + } else if (numberThenWord != null) { + Mapping umap = Units.unitMapper(value.substring((int) numberThenWord[1]), getUnit(1)); + if (umap == null) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Value supplied for attribute \"DSBCentre\" (" + value + + ") uses units which are inappropriate for the current spectral system (" + + getTitle() + ")."); + } + dval = transformValue(umap, numberThenWord[0]); + ok = dval != AST__BAD; + } + if (!ok) { + throw invalidSetting(setting); + } + Mapping tmap = topoMap(true, "astSetAttrib"); + double dtemp = transformValue(tmap, dval); + if (dtemp == AST__BAD) { + throw invalidSetting(setting); + } + setDsbCentreValue(dtemp); + } + + @Override + boolean testAttrib(String attrib) { + if ("dsbcentre".equals(attrib)) { + return testDSBCentre(); + } else if ("if".equals(attrib)) { + return testIF(); + } else if ("sideband".equals(attrib)) { + return testSideBand(); + } else if ("alignsideband".equals(attrib)) { + return testAlignSideBand(); + } else if ("imagfreq".equals(attrib)) { + return false; + } + return super.testAttrib(attrib); + } + + @Override + void clearAttrib(String attrib) { + if ("dsbcentre".equals(attrib)) { + clearDSBCentre(); + } else if ("if".equals(attrib)) { + clearIF(); + } else if ("sideband".equals(attrib)) { + clearSideBand(); + } else if ("alignsideband".equals(attrib)) { + clearAlignSideBand(); + } else if ("imagfreq".equals(attrib)) { + throw Ast.err( + AstException.AST__NOWRT, + "astClear: Invalid attempt to clear the \"" + attrib + "\" value for a " + astClass() + + ".\nThis is a read-only attribute."); + } else { + super.clearAttrib(attrib); + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsChan.java b/src/main/java/uk/ac/starlink/ast/FitsChan.java index 39e684a..915c52f 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsChan.java +++ b/src/main/java/uk/ac/starlink/ast/FitsChan.java @@ -787,8 +787,8 @@ void setSourceFile(String name) { * @throws AstException as {@link Channel#read} does for the NATIVE encoding, with status {@code * AST__BADIN} also if a long string has a {@code CONTINUE} card missing; or the error of * making the FrameSet for another encoding - * @throws UnsupportedOperationException if the encoding is not NATIVE and its reading is not - * available + * @throws UnsupportedOperationException if the encoding is not NATIVE and the description + * needs a class this library lacks */ @Override public AstObject read() { @@ -848,7 +848,7 @@ private AstObject readNative() { * The FrameSet the cards describe in {@code enc}, an encoding other than NATIVE, or null if they * describe none (C's {@code FitsToStore} and {@code FsetFromStore}). * - * @throws UnsupportedOperationException for an encoding whose reading is not available + * @throws UnsupportedOperationException where the description needs a class this library lacks */ private AstObject readForeign(Encoding enc) { // MODERN-JAVA(21): switch expression @@ -858,12 +858,10 @@ private AstObject readForeign(Encoding enc) { 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: throw Ast.err(AstException.AST__INTER, "astRead(FitsChan): unexpected encoding " + enc + "."); } @@ -1222,8 +1220,8 @@ public void retainFits() { * fails, and then every remaining card with a WCS keyword is removed as a read removes it. The * first remaining card is then current. * - * @throws UnsupportedOperationException if the Encoding is not NATIVE and its reading is not - * available + * @throws UnsupportedOperationException if the Encoding is not NATIVE and a description needs a + * class this library lacks */ public void purgeWCS() { readFromSource(); diff --git a/src/main/java/uk/ac/starlink/ast/FitsEncClass.java b/src/main/java/uk/ac/starlink/ast/FitsEncClass.java index 4532577..c31ea0c 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsEncClass.java +++ b/src/main/java/uk/ac/starlink/ast/FitsEncClass.java @@ -1,25 +1,27 @@ package uk.ac.starlink.ast; /** - * The FITS-CLASS encoding's writer, C's {@code CLASSFromStore}, as far as this library reaches it. + * The cards of a FITS-CLASS header for the primary axis description of a FrameSet: C's {@code + * CLASSFromStore}, which writes the description {@link FitsFsetToStore#fsetToStore} made. * *

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. + * it; it finds the velocities with a SpecFrame matched in the current Frame of the FrameSet, and + * the azimuth and elevation with SkyFrames matched there. * - *

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 + *

Ported from fitschan.c {@code CLASSFromStore}, which includes the fixes of upstream aea3090b + * (a LONPOLE of +180 or -180 degrees is allowed) and 17416d33 (the spectral CDELT is converted to + * Hz once, for the card and for the velocities). The Rust port's {@code fitschan/enc_class.rs} is * organised differently. */ final class FitsEncClass { + /** 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; @@ -29,32 +31,43 @@ final class FitsEncClass { 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. + * C's {@code CLASSFromStore}: writes the primary description in {@code store} to {@code fc} as + * FITS-CLASS cards, each in front of the current card, if FITS-CLASS can hold it. 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 (written with the older codes ATF and GLS), 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 image has three or more pixel axes and 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; it looks up the sizes of the + * celestial pixel axes in {@code dim} at the indices of the celestial WCS axes. A description + * of one pixel axis, to which celestial axes were added, is written as an image of three with + * NAXIS2 and NAXIS3 of 1. * - *

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. + *

The cards are the first three axes' CRPIX, CRVAL (the spectral one less the rest + * frequency, in Hz), CTYPE and CDELT (the spectral one in Hz), EQUINOX (that of the system + * when the description has none), DATE-OBS (and MJD-OBS over a card the header has), RESTFREQ, + * IMAGFREQ, OBJECT and LINE (blank unless the header has them), and, where the current Frame of + * {@code fs} gives them, VELO-LSR, VLSR and DELTAV, the radio velocity in the LSRK of the + * reference channel and the difference to the next channel, and AZIMUTH and ELEVATIO, the + * reference point's. A description lacking a CRPIX, CRVAL or CTYPE on one of the first three + * axes, or with a {@code -TAB} axis, stops those cards part way, and the write gives false + * after writing the others, as C does; {@link FitsChan#write} then removes the cards written. * * @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 dim the size of each pixel axis, or {@code AST__BAD} where unknown * @param method the calling method, for messages * @param cls the class of the object written, for messages - * @return false: the description is refused + * @return true if the description was written * @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) { @@ -64,7 +77,11 @@ static boolean classFromStore( } FitsCardList cards = fc.cards(); int rnd = fc.getFitsRounding(); + double specfactor = 1.0; boolean ok = false; + String lontype = null; + String lattype = null; + String spectype = null; // The primary celestial and spectral axes. int[] axes = st.lonLatSpecAxes(store.naxis); @@ -101,15 +118,15 @@ static boolean classFromStore( } } - // 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. + // The reference point, and the CTYPE values, the projection from the latitude one. C + // sets ok here, 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); + lontype = at(st.ctype, axlon); + lattype = at(st.ctype, axlat); int prj = lattype == null ? WcsMap.AST__WCSBAD : FitsWcsCelestial.wcsPrjType(lattype.substring(4)); if (prj == WcsMap.AST__WCSBAD) { ok = false; @@ -119,9 +136,18 @@ static boolean classFromStore( || 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; + // AIT and SFL need the reference point at the origin of the celestial coordinates, + // and are written with the older codes ATF and GLS. + if (ok && (prj == WcsMap.AST__AIT || prj == WcsMap.AST__SFL)) { + if (latval != 0.0 || lonval != 0.0) { + ok = false; + } else if (prj == WcsMap.AST__SFL) { + lontype = withCode(lontype, "-GLS"); + lattype = withCode(lattype, "-GLS"); + } else { + lontype = withCode(lontype, "-ATF"); + lattype = withCode(lattype, "-ATF"); + } } } else { // A SIN projection whose parameters are both zero. @@ -137,7 +163,11 @@ static boolean classFromStore( // 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)))) { + if (cval == null) { + ok = false; + } else if ("FREQ".startsWith(cval.substring(0, FitsCard.chrLen(cval)))) { + spectype = "FREQ"; + } else { ok = false; } @@ -149,40 +179,58 @@ static boolean classFromStore( ok = false; } - // Units of frequency. + // Units of frequency, and the factor converting them to Hz. 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; + } else if (ok) { + specfactor = hertzPerUnit(cval); + if (specfactor == 0.0) { + ok = false; + } } } // The number of WCS axes, at most three. int naxis = Math.min(st.maxCrpixAxis() + 1, 3); + double[] cdelt = ok ? new double[naxis] : null; - // The sizes of the celestial pixel axes, 0 where unknown; the rotation check is skipped - // when both span one pixel. + // The diagonal of the CD matrix, and no rotation unless both celestial pixel axes span one + // pixel; the sizes of those axes are 0 where unknown. 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)) { + double val = st.cdElement(i, j); + if (i == j) { + cdelt[i] = val; + } else if (val != 0.0 && (naxis2 != 1 || naxis3 != 1)) { ok = false; } } } - // FK4 or FK5, and the equinox the IAU 1984 rule gives them. + // FK4 or FK5, and the equinox: that the IAU 1984 rule gives them, or their default. String radesys = st.radesys; + double equ = value(st.equinox); if (radesys != null) { - Double equ = st.equinox; - if ("FK4".equals(radesys)) { - if (equ != null && equ >= 1984.0) { + if (!"FK4".equals(radesys) && !"FK5".equals(radesys)) { + ok = false; + } + if (equ == BAD) { + if ("FK4".equals(radesys)) { + equ = 1950.0; + } else if ("FK5".equals(radesys)) { + equ = 2000.0; + } else { + ok = false; + } + } else if ("FK4".equals(radesys)) { + if (equ >= 1984.0) { ok = false; } } else if ("FK5".equals(radesys)) { - if (equ != null && equ < 1984.0) { + if (equ < 1984.0) { ok = false; } } else { @@ -191,7 +239,8 @@ static boolean classFromStore( } // A rest frequency. - if (st.restfrq == null) { + double rf = value(st.restfrq); + if (rf == BAD) { ok = false; } @@ -205,12 +254,203 @@ static boolean classFromStore( ok = false; } } + if (!ok) { + return false; + } + + // A description of one pixel axis, to which celestial axes were added, is written as an + // image of three, since FITS-CLASS has no WCSAXES keyword: NAXIS is set to 3 (a card put + // first if there is none), and NAXIS2 and NAXIS3 of 1 are put after NAXIS1, or at the end + // if there is no NAXIS1. + if (store.naxis == 1) { + cards.clearCard(); + cards.setValueAsWriter("NAXIS", FitsCard.Value.ofInt(3), null, rnd); + if (cards.findKeyCard("NAXIS1", method)) { + cards.moveCard(1); + } + cards.setValueAsWriter("NAXIS2", FitsCard.Value.ofInt(1), null, rnd); + cards.setValueAsWriter("NAXIS3", FitsCard.Value.ofInt(1), null, rnd); + } + cards.positionWriteCursor(); + + // CRPIX, CRVAL and CTYPE, which are required, so a missing one stops each loop and the + // write. The spectral CRVAL is written in Hz as an offset from the rest frequency, and the + // celestial CTYPE values with the projection codes chosen above. C's crval values for + // axes not reached are not set; here they are 0. + double[] crval = new double[3]; + 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 { + crval[i] = val; + double v = val; + if (i == axspec) { + v *= specfactor; + v -= rf; + } + 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 = spectype; + } 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 (ok) { - throw new UnsupportedOperationException( - method + "(" + cls + "): the VELO-LSR value of a FITS-CLASS header needs SpecFrame"); + // CDELT, the spectral one in Hz. C's cdelt array has one element per axis written and it + // writes past the end of it here, when the spectral axis is not one of them; no FrameSet + // gives that, since every WCS axis has a CRPIX. + if (axspec >= naxis) { + throw Ast.err( + AstException.AST__INTER, + "CLASSFromStore: the spectral axis " + (axspec + 1) + " is beyond the " + naxis + + " axes written, where C writes past the end of its CDELT array."); } - return false; + cdelt[axspec] *= specfactor; + for (int i = 0; i < naxis; i++) { + setFloat(cards, "CDELT" + (i + 1), cdelt[i], "Pixel size", rnd); + } + + if (equ != BAD) { + setFloat(cards, "EQUINOX", equ, "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); + } + } + + setFloat(cards, "RESTFREQ", rf, "[Hz] Rest frequency", rnd); + + // The image frequency of the rest frequency, for double sideband data. + if (st.imagfreq != null) { + setFloat(cards, "IMAGFREQ", st.imagfreq, "[Hz] Image frequency", rnd); + } + + // OBJECT and LINE, blank unless the header has them. + if (!cards.hasCard("OBJECT")) { + setString(cards, "OBJECT", " ", null, rnd); + } + if (!cards.hasCard("LINE")) { + setString(cards, "LINE", " ", null, rnd); + } + + velocities(cards, curfrm, crval[axspec] * specfactor, cdelt[axspec], rnd); + azimuthElevation(cards, curfrm, crval[axlon], crval[axlat], rnd); + return ok; + } + + /** + * VELO-LSR and VLSR, the radio velocity in the LSRK of the reference channel, whose frequency + * in the source's rest frame is {@code freq} Hz, and DELTAV, the difference of that of the + * channel {@code delta} Hz above it. CLASS takes VELO-LSR to be the velocity of the reference + * channel, not of the source. C finds the spectral axis of {@code curfrm} with a template + * SpecFrame of radio velocity in the LSRK in m/s, whose other attributes come from that axis, + * and converts to it from a copy set to frequency in the source's rest frame in Hz; nothing is + * written when either is not found. + */ + private static void velocities(FitsCardList cards, Frame curfrm, double freq, double delta, int rnd) { + SpecFrame template = new SpecFrame(); + template.set("System=vrad,StdOfRest=lsrk,Unit=m/s,MinAxes=1,MaxAxes=3"); + FrameSet found = curfrm.findFrame(template, ""); + if (found == null) { + return; + } + Frame velofrm = found.getFrame(FrameSet.AST__CURRENT); + Frame freqfrm = (Frame) velofrm.copy(); + freqfrm.set("System=freq,StdOfRest=Source,Unit=Hz"); + FrameSet conv = freqfrm.convert(velofrm, ""); + if (conv == null) { + return; + } + double[] aval = conv.tran1(2, new double[] {freq, freq + delta}, true); + setFloat(cards, "VELO-LSR", aval[0], "[m/s] Reference velocity", rnd); + setFloat(cards, "VLSR", aval[0], "[m/s] Reference velocity", rnd); + setFloat(cards, "DELTAV", aval[1] - aval[0], "[m/s] Velocity resolution", rnd); + } + + /** + * AZIMUTH and ELEVATIO, the azimuth and elevation of the reference point ({@code lon}, {@code + * lat}) in degrees in the celestial system of the CTYPE values. C finds a template SkyFrame of + * that system and one of AZEL in {@code curfrm}, whose other attributes (the observatory, the + * epoch) come from it, and transforms from the one to the other through {@code curfrm}, + * normalising the result with the AZEL template; nothing is written when either is not found + * or the result is bad. + */ + private static void azimuthElevation(FitsCardList cards, Frame curfrm, double lon, double lat, int rnd) { + SkyFrame radecfrm = new SkyFrame(); + radecfrm.set("Permute=0,MinAxes=3,MaxAxes=3"); + FrameSet fsconv1 = curfrm.findFrame(radecfrm, ""); + SkyFrame azelfrm = new SkyFrame(); + azelfrm.set("System=AZEL,Permute=0,MinAxes=3,MaxAxes=3"); + FrameSet fsconv2 = curfrm.findFrame(azelfrm, ""); + if (fsconv1 == null || fsconv2 == null) { + return; + } + Mapping map1 = fsconv1.getMapping(FrameSet.AST__CURRENT, FrameSet.AST__BASE); + Mapping map2 = fsconv2.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Mapping map3 = new CmpMap(map1, map2, true); + double[] azel = map3.tranN(1, 2, new double[] {lon * AST__DD2R, lat * AST__DD2R}, true, 2); + if (azel[0] != BAD && azel[1] != BAD) { + azelfrm.norm(azel); + setFloat(cards, "AZIMUTH", azel[0] * AST__DR2D, "[Deg] Telescope azimuth", rnd); + setFloat(cards, "ELEVATIO", azel[1] * AST__DR2D, "[Deg] Telescope elevation", rnd); + } + } + + /** + * The factor converting the spectral unit {@code unit} to Hz, C's {@code specfactor}: 1, 1e3, + * 1e6 or 1e9 for Hz, kHz, MHz or GHz, and 0 for any other unit, which FITS-CLASS cannot hold. + */ + private static double hertzPerUnit(String unit) { + // MODERN-JAVA(21): switch expression + switch (unit) { + case "Hz": + return 1.0; + case "kHz": + return 1.0e3; + case "MHz": + return 1.0e6; + case "GHz": + return 1.0e9; + default: + return 0.0; + } + } + + /** 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; } /** @@ -253,4 +493,12 @@ private static T at(T[] a, int i) { 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/FitsFsetToStore.java b/src/main/java/uk/ac/starlink/ast/FitsFsetToStore.java index 3e0c56f..9c341ea 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsFsetToStore.java +++ b/src/main/java/uk/ac/starlink/ast/FitsFsetToStore.java @@ -6,7 +6,7 @@ /** * 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}). + * {@code MakeFitsFrameSet} with {@code AddEncodingFrame}, {@code FitsAxisOrder} and {@code ReadCrval}). * *

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 @@ -26,6 +26,9 @@ final class FitsFsetToStore { /** Radians to degrees, C's {@code AST__DR2D}. */ private static final double AST__DR2D = 57.29577951308232; + /** C's {@code AST__DBL_DIG}: the significant digits C's {@code %.*g} gives a double. */ + private static final int AST__DBL_DIG = 17; + /** Machine precision, C's {@code DBL_EPSILON}. */ private static final double DBL_EPSILON = Math.ulp(1.0); @@ -91,7 +94,7 @@ static FitsPlaneStores fsetToStore( * 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 + * axes ({@link FitsSpectralAxes#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 @@ -172,7 +175,7 @@ static boolean addVersion( 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); + Mapping tmap = FitsSpectralAxes.spectralAxes(fc, fset, dim, wperm, s, store, crvals, axisDone, method, cls); 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); @@ -239,12 +242,18 @@ static boolean addVersion( * 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. + *

A SpecFrame whose RefRA and RefDec are both set is given the celestial axes of its + * reference position: when the world Frame has no SkyFrame and at most two axes, a SkyFrame + * (FK5 J2000) is added after its axes, fed by the Mapping of a TAN header with the reference + * position at pixel (0, 0), the constant 0 being given to its two pixel axes; when it has a + * SkyFrame, the SpecFrame's RefRA and RefDec are set, through the FrameSet, to the FK5 J2000 + * position of the fiducial point of the celestial projection, if there is one. + * + *

Then {@link #addEncodingFrame} may add a Frame that suits the encoding, which replaces the + * world Frame. * - * @return the FrameSet, or null if the world Frame holds axes of two SkyFrames + * @return the FrameSet, or null if the world Frame holds axes of two SkyFrames or of two + * SpecFrames, or the celestial axes of a SpecFrame's reference position cannot be found */ // C compares the pointers astPrimaryFrame returns: whether two axes are in the same SkyFrame. @SuppressWarnings({"ReferenceEquality", "PMD.CompareObjectsWithEquals"}) @@ -253,18 +262,28 @@ static FrameSet makeFitsFrameSet( Frame pixfrm = (Frame) fset.getFrame(ipix).copy(); Frame wcsfrm = (Frame) fset.getFrame(iwcs).copy(); Mapping map = (Mapping) fset.getMapping(ipix, iwcs).copy(); + int npix = pixfrm.getNaxes(); 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. + // The SpecFrame and SkyFrame of the world Frame, each of which must be its only one, and + // the Mapping from the internal units of each other axis to its Unit. Mapping remap = null; + SpecFrame specfrm = null; Frame skyfrm = null; boolean ok = true; + int ilat = -1; + int ilon = -1; 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 (pframe instanceof SpecFrame) { + if (specfrm != null) { + ok = false; + break; + } + specfrm = (SpecFrame) pframe; + } else if (FitsMakeIntWorld.isASkyFrame(pframe)) { if (skyfrm != null) { if (pframe != skyfrm) { ok = false; @@ -273,6 +292,11 @@ static FrameSet makeFitsFrameSet( } else { skyfrm = pframe; } + if (paxis[0] == 1) { + ilon = iax; + } else { + ilat = iax; + } } else { String extunit = pframe.getUnit(paxis[0]); String intunit = pframe.getInternalUnit(paxis[0]); @@ -304,17 +328,207 @@ static FrameSet makeFitsFrameSet( 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. + // Two SkyFrames or two SpecFrames 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; + if (specfrm == null || !specfrm.testRefRA() || !specfrm.testRefDec() || (nwcs > 2 && skyfrm == null)) { + ret = new FrameSet(pixfrm); + ret.addFrame(FrameSet.AST__BASE, map, wcsfrm); + } else if (skyfrm == null) { + ret = addReferenceSkyFrame(pixfrm, wcsfrm, map, specfrm, npix); + } else { + ret = setReferencePosition(pixfrm, wcsfrm, map, ilon, ilat); + } + // C passes a NULL FrameSet to AddEncodingFrame, which dereferences it. + if (ret == null) { + return null; + } + + int icurr = addEncodingFrame(ret, enc); + if (icurr != FrameSet.AST__NOFRAME) { + ret.removeFrame(icurr); + } + return ret; + } + + /** + * The FrameSet {@link #makeFitsFrameSet} makes for a SpecFrame with a celestial reference + * position and a world Frame with no SkyFrame: the world Frame and an FK5 J2000 SkyFrame, + * whose axes come from a TAN projection with the reference position at pixel (0, 0), the + * constant 0 being given to those two pixel axes. The projection is that of a FITS-WCS header, + * with an MJD-OBS (UTC) of the SpecFrame's Epoch, read by a FitsChan. + * + * @return the FrameSet, or null if the header gives none + */ + private static FrameSet addReferenceSkyFrame(Frame pixfrm, Frame wcsfrm, Mapping map, SpecFrame specfrm, int npix) { + FitsChan fc = new FitsChan(); + fc.putFits("CRPIX1 = 0", false); + fc.putFits("CRPIX2 = 0", false); + fc.putFits("CDELT1 = 0.0003", false); + fc.putFits("CDELT2 = 0.0003", false); + fc.putFits("CTYPE1 = 'RA---TAN'", false); + fc.putFits("CTYPE2 = 'DEC--TAN'", false); + fc.putFits("RADESYS = 'FK5'", false); + fc.putFits("EQUINOX = 2000.0", false); + fc.putFits("CRVAL1 = " + CFormat.format("%." + AST__DBL_DIG + "g", AST__DR2D * specfrm.refRaValue()), false); + fc.putFits("CRVAL2 = " + CFormat.format("%." + AST__DBL_DIG + "g", AST__DR2D * specfrm.refDecValue()), false); + fc.putFits( + "MJD-OBS = " + + CFormat.format( + "%." + AST__DBL_DIG + "g", + FitsEpoch.tdbConv(specfrm.getEpochMjd(), TimeFrame.AST__UTC, true)), + false); + fc.cards().clearCard(); + AstObject obj = fc.read(); + if (!(obj instanceof FrameSet)) { + return null; + } + FrameSet tfs = (FrameSet) obj; + + // The pixel to world Mapping in parallel with the pixel to sky Mapping, the two sky pixel + // axes being given the constant 0.0, the CRPIX value of the header. + Mapping tmap0 = tfs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Mapping tmap1 = new CmpMap(map, tmap0, false); + int[] perm = new int[npix + 2]; + for (int iax = 0; iax < npix; iax++) { + perm[iax] = iax; + } + perm[npix] = -1; + perm[npix + 1] = -1; + Mapping pm = PermMap.fromInternal(npix, perm, npix + 2, perm, new double[] {0.0}); + Mapping tmap2 = new CmpMap(pm, tmap1, true); + + Frame tfrm0 = new CmpFrame(wcsfrm, tfs.getFrame(FrameSet.AST__CURRENT)); FrameSet ret = new FrameSet(pixfrm); - ret.addFrame(FrameSet.AST__BASE, map, wcsfrm); + ret.addFrame(FrameSet.AST__BASE, tmap2, tfrm0); + return ret; + } + + /** + * The FrameSet {@link #makeFitsFrameSet} makes for a SpecFrame with a celestial reference + * position and a world Frame with a SkyFrame: the world Frame, with the SpecFrame's RefRA and + * RefDec set through the FrameSet to the FK5 J2000 position of the fiducial point of the + * celestial projection, formatted with 20 digits. The SkyFrame's System and Equinox are set to + * FK5 and J2000 meanwhile, and set back if they were set. With no projection, the reference + * position is kept. + * + * @return the FrameSet, or null if the fiducial point is not found + */ + private static FrameSet setReferencePosition(Frame pixfrm, Frame wcsfrm, Mapping map, int ilon, int ilat) { + FrameSet tfs = new FrameSet(pixfrm); + tfs.addFrame(FrameSet.AST__BASE, map, wcsfrm); + + String systemAttr = "System(" + (ilon + 1) + ")"; + String skysys = tfs.test(systemAttr) ? tfs.getC(systemAttr) : null; + tfs.setC(systemAttr, "FK5"); + String equinoxAttr = "Equinox(" + (ilon + 1) + ")"; + String eqn = tfs.test(equinoxAttr) ? tfs.getC(equinoxAttr) : null; + tfs.setC(equinoxAttr, "J2000"); + + FrameSet ret = null; + Mapping tmap0 = tfs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + FitsCelestialAxes.Split split = FitsCelestialAxes.splitMap(tmap0, tmap0.getInvert(), ilon, ilat); + if (split != null) { + double[] fid = FitsFiducial.getFiducialWcs(split.map2, split.map3, ilon, ilat); + if (fid != null) { + // The Digits of the latitude and longitude axes are 20 while the position is + // formatted, so that no precision is lost, and then set back or cleared. + int[] digs = new int[2]; + for (int iax = 0; iax < 2; iax++) { + String digitsAttr = "Digits(" + ((iax != 0 ? ilon : ilat) + 1) + ")"; + digs[iax] = tfs.test(digitsAttr) ? tfs.getI(digitsAttr) : -1; + tfs.setI(digitsAttr, 20); + } + tfs.setC("RefRA", tfs.format(ilon + 1, fid[0])); + tfs.setC("RefDec", tfs.format(ilat + 1, fid[1])); + for (int iax = 0; iax < 2; iax++) { + String digitsAttr = "Digits(" + ((iax != 0 ? ilon : ilat) + 1) + ")"; + if (digs[iax] == -1) { + tfs.clear(digitsAttr); + } else { + tfs.setI(digitsAttr, digs[iax]); + } + } + ret = tfs; + } + } else { + ret = tfs; + } + + if (skysys != null) { + tfs.setC(systemAttr, skysys); + } + if (eqn != null) { + tfs.setC(equinoxAttr, eqn); + } return ret; } + /** + * C's {@code AddEncodingFrame}: for FITS-CLASS, a Frame added to {@code fs} as its current + * Frame, if a SpecFrame and a SkyFrame of the current Frame (the first of each) can be + * converted to it: a CmpFrame of a copy of the SpecFrame, in FREQ with Unit Hz and the Source + * standard of rest, and a copy of the SkyFrame, in FK4 (equinox B1950), FK5 (equinox J2000) + * or galactic coordinates (FK5 for any other system); the Frame added is the one the + * conversion gives. + * + * @return the index of the original current Frame if a Frame was added, otherwise {@link + * FrameSet#AST__NOFRAME} + */ + static int addEncodingFrame(FrameSet fs, FitsChan.Encoding enc) { + int result = FrameSet.AST__NOFRAME; + Frame cfrm = fs.getFrame(FrameSet.AST__CURRENT); + int naxc = cfrm.getNaxes(); + if (enc == FitsChan.Encoding.FITS_CLASS) { + SpecFrame specfrm = null; + SkyFrame skyfrm = null; + int[] paxis = new int[1]; + for (int i = 0; i < naxc; i++) { + Frame pfrm = cfrm.primaryFrame(i + 1, paxis); + if (pfrm instanceof SpecFrame) { + if (specfrm == null) { + specfrm = (SpecFrame) pfrm.copy(); + } + } else if (skyfrm == null && FitsMakeIntWorld.isASkyFrame(pfrm)) { + skyfrm = (SkyFrame) pfrm.copy(); + } + } + + if (specfrm != null && skyfrm != null) { + if (specfrm.systemValue() != SpecFrame.AST__FREQ) { + specfrm.setSystemValue(SpecFrame.AST__FREQ); + } + specfrm.setUnit(1, "Hz"); + specfrm.setStdOfRestValue(SpecFrame.AST__SCSOR); + + int sys = skyfrm.systemValue(); + if (sys != SkyFrame.AST__FK4 && sys != SkyFrame.AST__FK5 && sys != SkyFrame.AST__GALACTIC) { + skyfrm.setSystemValue(SkyFrame.AST__FK5); + sys = SkyFrame.AST__FK5; + } + if (sys == SkyFrame.AST__FK5) { + skyfrm.setC("Equinox", "J2000.0"); + } else if (sys == SkyFrame.AST__FK4) { + skyfrm.setC("Equinox", "B1950.0"); + } + + CmpFrame cmpfrm = new CmpFrame(specfrm, skyfrm); + FrameSet fsconv = cfrm.convert(cmpfrm, ""); + if (fsconv != null) { + Frame newfrm = fsconv.getFrame(FrameSet.AST__CURRENT); + Mapping map = fsconv.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + result = fs.getCurrent(); + fs.addFrame(FrameSet.AST__CURRENT, map, newfrm); + } + } + } + return result; + } + /** * 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 @@ -454,13 +668,4 @@ static double[] readCrval(FitsChan fc0, Frame wcsfrm, char s, String method, Str } 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/FitsSpecTrans.java b/src/main/java/uk/ac/starlink/ast/FitsSpecTrans.java index 113965b..5a24f35 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsSpecTrans.java +++ b/src/main/java/uk/ac/starlink/ast/FitsSpecTrans.java @@ -19,9 +19,10 @@ *

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}. + * every encoding, and translates CmELTi under every encoding. FITS-CLASS has translations of its + * own (C's {@code ClassTrans}): its spectral CRVAL is an offset from the rest frequency, in the + * source's rest frame, whose velocity a VELO-xxx keyword gives, and a blank projection code is + * {@code -GLS}. * *

Ported from Rust {@code fitschan/spec_trans.rs}, following the order and tests of C's {@code * SpecTrans}. @@ -34,6 +35,9 @@ final class FitsSpecTrans { /** C's {@code AST__DR2D}: degrees per radian. */ private static final double AST__DR2D = 57.29577951308232; + /** C's {@code AST__C}: the speed of light in m/s. */ + private static final double AST__C = 2.99792458E8; + /** The {@code tnx} warning (fitschan.c:32460). */ private static final String TNX_WARNING = "This FITS header includes, or was derived from, a TNX projection which" + " requires unsupported IRAF-specific corrections. The WCS information may therefore be incorrect."; @@ -133,9 +137,9 @@ 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-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 + * absent or has no value, an IRAF WAT string holds a word that is not a number, or a + * FITS-CLASS header has no rest frequency or a spectral axis other than frequency */ static FitsCardList specTrans( FitsCardList cards, @@ -159,15 +163,10 @@ 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-CLASS encoding * @throws AstException as {@link #specTrans} does */ static void specTransInplace( FitsCardList cards, FitsChan.Encoding encoding, TransAttrs attrs, TransWarnings 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(' '); @@ -513,6 +512,9 @@ private static final class Translator { /** Whether the encoding is FITS-IRAF, which alone translates the CDjjjiii matrix. */ private final boolean iraf; + /** Whether the encoding is FITS-CLASS, which has translations of its own. */ + private final boolean fitsClass; + /** * 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 @@ -529,6 +531,7 @@ private static final class Translator { this.warnings = warnings; this.pcOrIraf = encoding == FitsChan.Encoding.FITS_PC || encoding == FitsChan.Encoding.FITS_IRAF; this.iraf = encoding == FitsChan.Encoding.FITS_IRAF; + this.fitsClass = encoding == FitsChan.Encoding.FITS_CLASS; this.cardComm = currentComment(src); } @@ -630,6 +633,14 @@ private void setFloat(String keyword, double value, String comment) { cards.setTranslation(keyword, FitsCard.Value.ofFloat(value), comment); } + /** + * C's {@code SetValue( ret, keyword, ... )} of a floating value with no comment, which + * leaves the comment of the keyword in {@code this} as the one a reader sees. + */ + private void replaceFloat(String keyword, double value) { + setFloat(keyword, value, null); + } + /** C's {@code SetValue( ret, keyword, ... )} of a string. */ private void setString(String keyword, String value, String comment) { cards.setTranslation(keyword, FitsCard.Value.ofString(value), comment); @@ -714,7 +725,9 @@ void version(char s) { cmxxx(); epochEquinox(); dateObs(); - // C's ClassTrans runs here for FITS-CLASS, which is not read. + if (fitsClass) { + classTrans(); + } if (ustrEq(prj, "-TAN") && saoTrans()) { prj = "-TPN"; setCelestialSuffix(s, "-TPN"); @@ -738,6 +751,113 @@ void version(char s) { cunit(s); } + /** + * The translations of a FITS-CLASS header (C's {@code ClassTrans}, fitschan.c), made for the + * primary axis description from the celestial axes found: the spectral CRVAL, an offset + * from the rest frequency, is made the frequency; the spectral axis is in the source's + * rest frame (SPECSYS SOURCE); a blank projection code of a celestial axis becomes {@code + * -GLS}; and the source's velocity, the VELO-xxx velocity of the reference channel less + * that channel's radio velocity in the source's rest frame, is given as SSYSSRC, the rest + * frame the VELO-xxx keyword names, and ZSOURCE. + * + *

The spectral axis is the one of the first three that is not celestial (axis 2 when + * there are no celestial axes). C reads the reference frequency of the radio velocity + * from a variable it sets only when that axis has a CTYPE of FREQ and a CRVAL; otherwise + * the variable is not initialised, which here is 0, the value C's recorded outputs of the + * {@code class-spec} and {@code class-spec-hel} wcsconv fixtures, whose one axis is not + * axis 2, encode. + * + * @throws AstException with status {@code AST__BDFTS} if there is neither RESTFRQ nor + * RESTFREQ, if the spectral CTYPE is not FREQ, or if its CRVAL is absent + */ + private void classTrans() { + // The rest frequency. + Double restfreq = getFloat2("RESTFRQ", false); + if (restfreq == null) { + restfreq = getFloat2("RESTFREQ", false); + } + if (restfreq == null) { + throw Ast.err( + AstException.AST__BDFTS, "astRead(FitsChan): Keyword RESTFREQ not found in CLASS FITS header."); + } + + // The spectral axis. + int axspec; + if (axlat + axlon == 1) { + axspec = 2; + } else if (axlat + axlon == 3) { + axspec = 0; + } else { + axspec = 1; + } + + // A FREQ axis, whose CRVAL is made the frequency. C leaves crval unset when this does + // not set it; see the method description. + double crval = 0.0; + String ctypeKey = key("CTYPE", axspec + 1, ' '); + String cval = getString2(ctypeKey); + if (cval != null) { + if (!AstObject.chrMatch("FREQ", cval)) { + throw Ast.err( + AstException.AST__BDFTS, + "astRead(FitsChan): FITS-CLASS keyword " + ctypeKey + " has value \"" + cval + + "\" - CLASS support in AST only includes \"FREQ\" axes."); + } + String crvalKey = key("CRVAL", axspec + 1, ' '); + Double v = getFloat2(crvalKey, true); + crval = v + restfreq; + replaceFloat(crvalKey, crval); + replaceString("SPECSYS", "SOURCE"); + } + + // A blank projection code becomes -GLS. C copies the first four characters with + // strncpy, which stops at the end of a shorter value; a value of more than four + // characters always has four. + for (int ax : new int[] {axlon, axlat}) { + String keyname = key("CTYPE", ax + 1, ' '); + String type = getString2(keyname); + if (type != null && type.length() > 4 && type.startsWith(" ", 4)) { + replaceString(keyname, type.substring(0, 4) + "-GLS"); + } + } + + // The velocity of the reference channel, and the rest frame the keyword giving it + // names: the first of these keywords present, in C's order. + String[][] velocityKeys = { + {"VELO-HEL", "BARYCENT"}, + {"VELO-OBS", "TOPOCENT"}, + {"VELO-TOP", "TOPOCENT"}, + {"VELO-EAR", "GEOCENTR"}, + {"VELO-GEO", "GEOCENTR"}, + {"VELO-LSR", "LSRK"}, + {"VLSR", "LSRK"} + }; + String ssyssrc = null; + Double vref = null; + for (String[] k : velocityKeys) { + vref = getFloat2(k[0], false); + if (vref != null) { + ssyssrc = k[1]; + break; + } + } + if (vref == null) { + warnAtEntry( + "badval", + "A FITS-CLASS header was identified (DELTAV and VLSR/VELO-xxx present) but no usable velocity" + + " reference keyword was found. Assuming LSRK."); + ssyssrc = "LSRK"; + vref = 0.0; + } + + // The radio velocity of the reference channel in the source's rest frame, and the + // source's velocity, the difference of the two, as a redshift. + double v0 = AST__C * (restfreq - crval) / restfreq; + double vsource = vref - v0; + replaceString("SSYSSRC", ssyssrc); + replaceFloat("ZSOURCE", (AST__C / (AST__C - vsource)) - 1.0); + } + /** {@link #withSuffix} of a CTYPE that may be absent, as C's would be when an axis is. */ private static String rewrite(String type, String suffix) { return type == null ? null : withSuffix(type, suffix); diff --git a/src/main/java/uk/ac/starlink/ast/FitsSpectralAxes.java b/src/main/java/uk/ac/starlink/ast/FitsSpectralAxes.java new file mode 100644 index 0000000..4e52088 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsSpectralAxes.java @@ -0,0 +1,405 @@ +package uk.ac.starlink.ast; + +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * C's {@code SpectralAxes} (fitschan.c): the FITS-WCS paper III description of the spectral axes + * of the current Frame of a FrameSet, with C's {@code GetFitsSor}. + * + *

Each axis of a SpecFrame is described, in order of preference, with the linear algorithm (the + * pixel coordinates are linear in the SpecFrame's System), the non-linear {@code -X2P} algorithm + * (linear in FREQ, WAVE, AWAV or VELO, tried in that order), the {@code -LOG} algorithm, the grism + * algorithm ({@code -GRI} or {@code -GRA}, for a Mapping ending in a GrismMap), or, when TabOK is + * positive, the {@code -TAB} algorithm; ForceTab passes over all but the last. An axis none of + * them describes is left to {@link FitsOtherAxes#otherAxes}. + * + *

C tries the {@code -X2P} and grism algorithms by setting the System and Unit of the axis + * through the FrameSet, which remaps the current Frame, and setting them back, so the FrameSet is + * remapped as C remaps it. The {@code -LOG} description holds a MathMap and the {@code -TAB} + * description a FitsTable, which this library does not have; where C makes one, an {@link + * UnsupportedOperationException} is thrown. C's grism algorithm extracts a GrismMap from the + * pixel to wavelength Mapping; a FrameSet of this library's classes holds none, so it finds none, + * as C finds none in such a FrameSet. + * + *

Ported from Rust {@code fitschan/fset_to_store/spectral_axes.rs}, following fitschan.c, whose + * structure is kept where Rust's follows from its ownership rules: the FrameSet is changed in place + * as C changes it, and the SpecFrame read is the one in the FrameSet. + */ +final class FitsSpectralAxes { + + private static final double AST__BAD = AstObject.AST__BAD; + + /** The speed of light in m/s, C's {@code AST__C}. */ + private static final double AST__C = 2.99792458E8; + + /** The systems to one of which every supported spectral system is linearly related. */ + private static final String[] X_SYS = {"FREQ", "WAVE", "AWAV", "VELO"}; + + private FitsSpectralAxes() {} + + /** + * C's {@code SpectralAxes}: stores CTYPE, CRVAL, CUNIT, CNAME and the other spectral keywords + * (OBSGEO for the primary description, RESTFRQ or RESTWAV, IMAGFREQ, SPECSYS, ZSOURCE, SSYSSRC + * and VELOSYS) for each spectral axis of the current Frame of {@code fs} that one of the + * algorithms describes, flags it in {@code axisDone}, and returns the Mapping from the + * current Frame to intermediate world coordinates for those axes, which passes the other axes + * unchanged. + * + *

A spectral Unit not linearly related to the default Unit of the System over the spectral + * range of the pixel grid is first cleared through the FrameSet, which remaps the current + * Frame, and the reference value converted to the default Unit. The reference value is the + * element of {@code crvals}; or, when that is bad, the middle of the spectral range when the + * size of the one pixel axis feeding the spectral axis is known, and the value at pixel 1 + * otherwise; moved to the nearest whole pixel. For the {@code -X2P} algorithm the intermediate + * world coordinate is the X value less its reference value, scaled to change at the rate of + * the SpecFrame's value at the reference point. + * + * @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; the System and Unit of its spectral axes are changed and set back, and + * SourceVRF and SourceVel of its SpecFrames set, as C does + * @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 describes an axis with the {@code -LOG} + * algorithm, which needs MathMap, or with the {@code -TAB} algorithm, which needs FitsTable + */ + static Mapping spectralAxes( + FitsChan fc, + FrameSet fs, + double[] dim, + int[] wperm, + char s, + FitsStore store, + double[] crvals, + boolean[] axisDone, + String method, + String cls) { + Mapping ret = null; + + Frame wcsfrm = fs.getFrame(FrameSet.AST__CURRENT); + int npix = fs.getNin(); + int 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; + } + + int[] paxis = new int[1]; + for (int iax = 0; iax < nwcs; iax++) { + Frame pframe = wcsfrm.primaryFrame(iax + 1, paxis); + if (!(pframe instanceof SpecFrame)) { + continue; + } + SpecFrame specfrm = (SpecFrame) pframe; + int fitsI = wperm[iax]; + + String systemAttr = "System(" + (iax + 1) + ")"; + String origSystem = wcsfrm.getC(systemAttr); + String unitAttr = "Unit(" + (iax + 1) + ")"; + + Mapping map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + + // The pixel axis that feeds the spectral axis, if only one does. The Mapping is + // inverted so that any WCS axes with no inverse do not stop it being split. + int pax = -1; + MapSplit split; + map.invert(); + try { + split = map.mapSplit(new int[] {iax}); + } finally { + map.invert(); + } + if (split != null && split.map.getNout() == 1) { + pax = split.outputs[0]; + } + + // The bounds of the spectral axis over the pixel grid. + double[] bnds = MapBox.mapBox(map, lbndP, ubndP, true, iax, null, null); + double lbndS = bnds[0]; + double ubndS = bnds[1]; + + // FITS-WCS paper III needs CRVAL and so on in linear units: if the conversion from the + // Unit to the default Unit is not linear, the Unit is cleared through the FrameSet, so + // that the SpecFrame is remapped. + SpecFrame tfrm = (SpecFrame) specfrm.copy(); + tfrm.clearUnit(1); + FrameSet tfs = specfrm.convert(tfrm, ""); + if (tfs == null) { + continue; + } + double crval = crvals != null ? crvals[iax] : AST__BAD; + Mapping tmap1 = tfs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + if (!FitsIsMapLinear.isMapLinear(tmap1, new double[] {lbndS}, new double[] {ubndS}, 0, null)) { + fs.clear(unitAttr); + map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + bnds = MapBox.mapBox(map, lbndP, ubndP, true, iax, null, null); + lbndS = bnds[0]; + ubndS = bnds[1]; + crval = tmap1.tran1(1, new double[] {crval}, true)[0]; + } + + // The linear spectral Unit now in use. + String linUnit = specfrm.getUnit(1); + + // The default reference value: the middle of the spectral range if the size of the + // spectral pixel axis is known, otherwise its value at pixel 1; at a whole pixel. + if (crval == AST__BAD) { + if (pax >= 0 && dim[pax] != AST__BAD) { + crval = 0.5 * (lbndS + ubndS); + } else { + crval = lbndS; + } + } + crval = FitsMakeIntWorld.nearestPix(map, crval, iax); + + String ctype = null; + Mapping axmap = null; + if (fc.getForceTab() == 0) { + // The linear algorithm. + if (FitsIsMapLinear.isMapLinear(map, lbndP, ubndP, iax, null)) { + ctype = origSystem; + axmap = FitsOtherAxes.addUnitMaps(new ShiftMap(new double[] {-crval}), iax, nwcs); + } + + // The non-linear algorithm: the pixel coordinates are linear in another system + // X, set on the FrameSet with its default Unit. + for (int ix = 0; ix < X_SYS.length && ctype == null; ix++) { + fs.setC(systemAttr, X_SYS[ix]); + fs.clear(unitAttr); + Mapping tmap3 = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + if (FitsIsMapLinear.isMapLinear(tmap3, lbndP, ubndP, iax, null)) { + ctype = withCode(origSystem, x2pCode(X_SYS[ix], origSystem)); + + // The Mapping giving S as a function of X; its inverse gives the X value + // at the reference value, and its rate there dS/dX. + Frame xfrm = (Frame) specfrm.copy(); + xfrm.setC("System(1)", origSystem); + xfrm.setC("Unit(1)", linUnit); + FrameSet xfs = specfrm.convert(xfrm, ""); + Mapping tmap5 = xfs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + double xval = tmap5.tran1(1, new double[] {crval}, false)[0]; + double dsbydx = tmap5.rate(new double[] {xval}, 1, 1); + + // From S to X, less the X reference value, scaled so that S changes at + // unit rate with the intermediate world coordinate. + Mapping tmap2 = new ShiftMap(new double[] {-xval}); + tmap5.invert(); + Mapping tmap0 = new CmpMap(tmap5, tmap2, true); + Mapping tmapz = new ZoomMap(1, dsbydx); + axmap = FitsOtherAxes.addUnitMaps(new CmpMap(tmap0, tmapz, true), iax, nwcs); + } + + fs.setC(systemAttr, origSystem); + fs.setC(unitAttr, linUnit); + } + + // The log-linear algorithm. + if (ctype == null) { + axmap = FitsOtherAxes.logAxis(map, iax, nwcs, lbndP, ubndP, crval); + if (axmap != null) { + ctype = withCode(origSystem, "-LOG"); + } + } + + // The grism algorithm, tried with the axis as vacuum and as air wavelength in m. + // C looks for a GrismMap producing the axis in the simplified pixel to wavelength + // Mapping (ExtractGrismMap); a FrameSet of this library's classes holds none. + for (int ix = 0; ix < 2 && ctype == null; ix++) { + fs.setC(systemAttr, ix == 0 ? "WAVE" : "AWAV"); + fs.setC(unitAttr, "m"); + fs.setC(systemAttr, origSystem); + fs.setC(unitAttr, linUnit); + } + } + + // The -TAB algorithm, when TabOK is positive. + int extver = fc.getTabOK(); + if (ctype == null && extver > 0) { + Mapping tmap0 = FitsMapTab.isMapTab1D( + map, 1.0, null, wcsfrm, dim, iax, fitsI, new int[1], new int[1], new int[1]); + if (tmap0 != null) { + // C stores the table version in the header of the FitsTable holding the + // table, and the column names. + throw new UnsupportedOperationException( + "SpectralAxes(FitsChan): the -TAB description of FITS-WCS axis " + (fitsI + 1) + + " needs FitsTable"); + } + } + + if (ctype != null) { + ret = ret != null ? new CmpMap(ret, axmap, true) : axmap; + + store.ctype[fitsI] = ctype; + // C's bad value is an item not set. + store.crval[fitsI] = crval != AST__BAD ? crval : null; + store.cunit[fitsI] = linUnit; + + // A set Label is the CTYPE comment and the CNAME. + if (specfrm.testLabel(1)) { + String cname = specfrm.getLabel(1); + store.ctypeCom[fitsI] = cname; + store.cname[fitsI] = cname; + } + + // The other keywords, from attributes that are set, differ from the defaults of + // FITS-WCS paper III, and are good. + if (specfrm.testObsLon() && specfrm.testObsLat() && s == ' ') { + double geolon = specfrm.getObsLonValue(); + double geolat = specfrm.getObsLatValue(); + double h = specfrm.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]; + } + } + if (specfrm.testRestFreq()) { + double restfreq = specfrm.restFreqValue(); + if (restfreq != AST__BAD) { + if ("WAVE".equals(origSystem) + || "VOPT".equals(origSystem) + || "ZOPT".equals(origSystem) + || "AWAV".equals(origSystem)) { + store.restwav = AST__C / restfreq; + } else { + store.restfrq = restfreq; + } + } + if (specfrm instanceof DSBSpecFrame) { + double imagfreq = ((DSBSpecFrame) specfrm).imagFreqValue(); + if (imagfreq != AST__BAD) { + store.imagfreq = imagfreq; + } + } + } + String cval = getFitsSor(specfrm.getC("StdOfRest")); + if (cval != null) { + store.specsys = cval; + } + double vsource; + if (specfrm.testSourceVel()) { + vsource = specfrm.sourceVelValue(); + if (vsource != AST__BAD && Math.abs(vsource) < AST__C) { + store.zsource = Math.sqrt((AST__C + vsource) / (AST__C - vsource)) - 1.0; + cval = getFitsSor(specfrm.getC("SourceVRF")); + if (cval != null) { + store.ssyssrc = cval; + } + } + } else { + vsource = AST__BAD; + } + + // VELOSYS: the source velocity is made zero in the standard of rest (unless that + // is the source's), and is then given in the topocentric rest frame, which is the + // velocity of the standard of rest; the source velocity is set back if it was set. + int sourcevrf; + if (specfrm.stdOfRestValue() != SpecFrame.AST__SCSOR) { + sourcevrf = specfrm.sourceVrfValue(); + specfrm.setSourceVrfValue(specfrm.stdOfRestValue()); + specfrm.setSourceVelValue(0.0); + } else { + vsource = AST__BAD; + sourcevrf = SpecFrame.AST__BADSOR; + } + specfrm.setSourceVrfValue(SpecFrame.AST__TPSOR); + double velosys = specfrm.sourceVelValue(); + if (velosys != AST__BAD) { + store.velosys = velosys; + } + if (vsource != AST__BAD) { + specfrm.setSourceVrfValue(sourcevrf); + specfrm.setSourceVelValue(vsource); + } + + axisDone[iax] = true; + } + } + + return ret != null ? ret.simplify() : new UnitMap(nwcs); + } + + /** + * The CTYPE C makes for an algorithm: {@code code} in place of everything from the fifth + * character of the System {@code system} on, as C's {@code strcpy( ctype + 4, code )} does + * (every spectral System has four characters). + */ + private static String withCode(String system, String code) { + return system.substring(0, Math.min(4, system.length())) + code; + } + + /** + * The code C appends to the four characters of the System for the {@code -X2P} algorithm: + * {@code -X2P}, X naming the system {@code xsys} the pixel coordinates are linear in and P the + * basic system to which {@code origSystem} is linearly related. + */ + private static String x2pCode(String xsys, String origSystem) { + String x; + if ("FREQ".equals(xsys)) { + x = "-F2"; + } else if ("WAVE".equals(xsys)) { + x = "-W2"; + } else if ("AWAV".equals(xsys)) { + x = "-A2"; + } else { + x = "-V2"; + } + String p; + if ("FREQ".equals(origSystem) + || "ENER".equals(origSystem) + || "WAVN".equals(origSystem) + || "VRAD".equals(origSystem)) { + p = "F"; + } else if ("WAVE".equals(origSystem) || "VOPT".equals(origSystem) || "ZOPT".equals(origSystem)) { + p = "W"; + } else if ("AWAV".equals(origSystem)) { + p = "A"; + } else { + p = "V"; + } + return x + p; + } + + /** + * C's {@code GetFitsSor}: the FITS SPECSYS value of the SpecFrame standard of rest {@code + * string}, or null if FITS has none. + */ + static String getFitsSor(String string) { + // MODERN-JAVA(21): switch expression + switch (string) { + case "Topocentric": + return "TOPOCENT"; + case "Geocentric": + return "GEOCENTR"; + case "Barycentric": + return "BARYCENT"; + case "Heliocentric": + return "HELIOCEN"; + case "LSRK": + return "LSRK"; + case "LSRD": + return "LSRD"; + case "Galactic": + return "GALACTOC"; + case "Local_group": + return "LOCALGRP"; + case "Source": + return "SOURCE"; + default: + // C's GetFitsSor returns NULL for any other string. + return null; + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java b/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java index 0b0de53..7d4bacd 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java +++ b/src/main/java/uk/ac/starlink/ast/FitsWcsCelestial.java @@ -68,26 +68,37 @@ static final class CelestialResult { final int latAxis; /** - * The celestial reference position, {@code {longitude, latitude}} in radians, or null: C's - * {@code reflon} and {@code reflat}, from CRVAL, overridden by {@code RFVAL} and then - * by {@code AXREF}. + * The reference longitude in radians, or {@code AST__BAD}: C's {@code reflon}, from CRVAL, + * overridden by {@code RFVAL} and then by {@code AXREF}. It is kept apart from the + * latitude, as C returns them, since a SpecFrame takes whichever of the two is known (C's + * {@code WcsSpectral}), while SkyRef needs both. */ - final double[] refPos; + final double refLon; + + /** The reference latitude in radians, or {@code AST__BAD}: C's {@code reflat}, as {@link #refLon}. */ + final double refLat; /** - * Whether {@link #refPos} came from {@code AXREF}, so that C sets SkyRef from it even - * when the SkyFrame has one (fitschan.c:36677-36686), where otherwise it sets SkyRef only - * when it is not set (fitschan.c:36566). + * Whether {@link #refLon} and {@link #refLat} came from {@code AXREF}, so that C sets + * SkyRef from them even when the SkyFrame has one (fitschan.c:36677-36686), where + * otherwise it sets SkyRef only when it is not set and both are known (fitschan.c:36566). */ final boolean refPosForced; CelestialResult( - Mapping mapping, SkyFrame frame, int lonAxis, int latAxis, double[] refPos, boolean refPosForced) { + Mapping mapping, + SkyFrame frame, + int lonAxis, + int latAxis, + double refLon, + double refLat, + boolean refPosForced) { this.mapping = mapping; this.frame = frame; this.lonAxis = lonAxis; this.latAxis = latAxis; - this.refPos = refPos; + this.refLon = refLon; + this.refLat = refLat; this.refPosForced = refPosForced; } } @@ -382,14 +393,13 @@ static CelestialResult buildCelestialWithDefB1950( reflat = store.axref[axlat] * AST__DD2R; refPosForced = true; } - double[] refPos = reflon != AST__BAD && reflat != AST__BAD ? new double[] {reflon, reflat} : null; // C builds the Frame of all the axes with the SkyFrame's axes in FITS order; the SkyFrame // returned here has its axes in the order the Mapping delivers them. if (axlat < axlon) { sfrm.permAxes(new int[] {2, 1}); } - return new CelestialResult(ret, sfrm, axlon, axlat, refPos, refPosForced); + return new CelestialResult(ret, sfrm, axlon, axlat, reflon, reflat, refPosForced); } /** Adds {@code val} to element {@code axis} of {@code outa} and {@code outb}, or makes both bad. */ diff --git a/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java b/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java index ea3a868..1c901f7 100644 --- a/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java +++ b/src/main/java/uk/ac/starlink/ast/FitsWcsRead.java @@ -19,9 +19,9 @@ * to intermediate world coordinate Mapping, then one Mapping over every axis for each class of * axis (celestial, spectral, the others) and any {@code -TAB} look-ups, all in series. * - *

The Frames and Mappings of spectral axes (SpecFrame), of {@code -TAB} axes when TabOK is - * above zero (LutMap) and of non-spectral {@code -LOG} axes (MathMap) are not available: a header - * using them makes the read throw {@link UnsupportedOperationException}. + *

Spectral axes are described by {@link FitsWcsSpectral}. The Mappings of {@code -TAB} axes when + * TabOK is above zero (LutMap), of {@code -LOG} axes (MathMap) and of grism axes (GrismMap) are + * not available: a header using them makes the read throw {@link UnsupportedOperationException}. * *

Ported from Rust {@code fitschan/wcs_read.rs} and the FITS-WCS branch of {@code * fitschan/mod.rs}'s {@code read}. @@ -42,7 +42,7 @@ private FitsWcsRead() {} /** * 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 + * (FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++, FITS-CLASS), 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 @@ -50,8 +50,8 @@ private FitsWcsRead() {} * when no FrameSet is made and Clean is not set, available again (C's {@code FixUsed}). * * @throws AstException as C's read reports it - * @throws UnsupportedOperationException if the header has a spectral axis, a {@code -TAB} axis - * with TabOK above zero, or a non-spectral {@code -LOG} axis + * @throws UnsupportedOperationException if the header has a {@code -TAB} axis with TabOK above + * zero, a {@code -LOG} axis with a non-zero CRVAL, or a {@code -GRI} or {@code -GRA} axis */ static FrameSet read(FitsChan fc, FitsChan.Encoding encoding) { FitsCardList cards = fc.cards(); @@ -477,10 +477,10 @@ private static MapFrm wcsMapFrm( Mapping map1 = FitsWcsMatrix.buildPixelToIwc(store, cards, warnings, cursors); FitsWcsCelestial.CelestialResult celestial = FitsWcsCelestial.buildCelestialWithDefB1950( store, s, defB1950, readRfval(cards, store.naxis, s), warnings); - buildSpectral(store); - Frame frm = buildWorldFrame(store, celestial); - String[] iwcUnits = iwc ? iwcAxisUnits(store, celestial) : null; - Mapping ret = buildPixelToWorld(store, map1, celestial).simplify(); + World world = buildWorld(store, celestial, s, warnings); + Frame frm = world.frame; + Mapping ret = + buildPixelToWorld(store, map1, celestial, world.spectralMap).simplify(); frm.setIdent(String.valueOf(s)); if (store.dut1 != null) { frm.setDut1(store.dut1 * SPD); @@ -497,9 +497,9 @@ private static MapFrm wcsMapFrm( Frame iwcfrm = new Frame(wcsaxes); iwcfrm.setTitle("FITS Intermediate World Coordinates"); iwcfrm.setDomain("IWC" + s); - for (int i = 0; i < iwcUnits.length; i++) { - if (iwcUnits[i] != null) { - iwcfrm.setUnit(i + 1, iwcUnits[i]); + for (int i = 0; i < world.iwcUnits.length; i++) { + if (world.iwcUnits[i] != null) { + iwcfrm.setUnit(i + 1, world.iwcUnits[i]); } } FrameSet fs = new FrameSet(frm); @@ -526,8 +526,8 @@ private static Double[] readRfval(FitsCardList cards, int naxis, char s) { /** * C's {@code TabMapping} (fitschan.c:33898), which makes the look-up Mapping of every {@code - * -TAB} axis when TabOK is above zero; with TabOK at most zero it makes none and the axes are - * read as linear. + * -TAB} axis when TabOK is above zero; with TabOK at most zero it makes none, a non-spectral + * {@code -TAB} axis is read as linear, and a spectral one is refused by {@code WcsSpectral}. * * @throws UnsupportedOperationException for a {@code -TAB} axis with TabOK above zero, whose * look-up needs LutMap @@ -545,22 +545,6 @@ private static void tabMapping(FitsStore store, int tabOk) { } } - /** - * C's {@code WcsSpectral} (fitschan.c:39913), which describes each axis whose CTYPE names a - * spectral system with a SpecFrame. - * - * @throws UnsupportedOperationException for the first such axis, since that needs SpecFrame - */ - private static void buildSpectral(FitsStore store) { - for (int axis = 0; axis < store.naxis; axis++) { - String ctype = store.ctype[axis]; - if (ctype != null && FitsStore.isSpectralCtype(ctype)) { - throw new UnsupportedOperationException( - "FitsChan: the spectral axis " + (axis + 1) + " (CTYPE '" + ctype + "') needs SpecFrame"); - } - } - } - /** * The pixel Frame of a FITS-WCS read, with {@code npix} axes: Title "Pixel Coordinates", * Domain GRID and each axis labelled "Pixel axis n" (fitschan.c:12183-12187). @@ -611,23 +595,6 @@ private static void addFrame(FrameSet fset, int pixel, int npix, MapFrm mf) { fset.setCurrent(nf + 1); } - /** - * The units C gives the axes of the IWC Frame: degrees for the celestial axes ({@code - * WcsCelestial}, fitschan.c:36605-36606) and any CUNIT for the others ({@code WcsOthers}, - * fitschan.c:39350-39353); a null element leaves the Unit unset. - */ - private static String[] iwcAxisUnits(FitsStore store, FitsWcsCelestial.CelestialResult celestial) { - String[] units = new String[store.naxis]; - for (int i = 0; i < store.naxis; i++) { - if (celestial != null && (celestial.lonAxis == i || celestial.latAxis == i)) { - units[i] = "deg"; - } else { - units[i] = store.cunit[i]; - } - } - return units; - } - /** * The pixel to world coordinate Mapping of an axis description, before simplification: as * C's {@code WcsMapFrm} builds it (fitschan.c:38335-38341), the following stages in series, @@ -637,23 +604,19 @@ private static String[] iwcAxisUnits(FitsStore store, FitsWcsCelestial.Celestial *

  • {@code map1}, pixel to IWC ({@code WcsIntWorld}); *
  • the celestial Mapping, or a UnitMap when there are no celestial axes ({@code * WcsCelestial}); - *
  • one UnitMap per axis in parallel ({@code WcsSpectral}, which makes a UnitMap for each - * axis that is not spectral, and no spectral axis reaches here); - *
  • a UnitMap when every axis is celestial, and otherwise one Mapping per axis in - * parallel: {@link #othersAxisMap} for an axis no other stage describes and a UnitMap for - * the others ({@code WcsOthers}). + *
  • {@code map3}, one Mapping per axis in parallel, a UnitMap for each axis that is not + * spectral ({@code WcsSpectral}); + *
  • a UnitMap when the celestial and spectral stages describe every axis, and otherwise + * one Mapping per axis in parallel: {@link #othersAxisMap} for an axis no other stage + * describes and a UnitMap for the others ({@code WcsOthers}). * * *

    No {@code -TAB} look-up Mapping reaches here (see {@link #tabMapping}). */ private static Mapping buildPixelToWorld( - FitsStore store, Mapping map1, FitsWcsCelestial.CelestialResult celestial) { + FitsStore store, Mapping map1, FitsWcsCelestial.CelestialResult celestial, Mapping map3) { int naxis = store.naxis; - boolean[] claimed = new boolean[naxis]; - if (celestial != null) { - claimed[celestial.lonAxis] = true; - claimed[celestial.latAxis] = true; - } + boolean[] claimed = claimedAxes(store, celestial); boolean otherAxis = false; for (boolean c : claimed) { if (!c) { @@ -662,11 +625,6 @@ private static Mapping buildPixelToWorld( } } Mapping map2 = celestial != null ? celestial.mapping : new UnitMap(naxis); - Mapping map3 = null; - for (int i = 0; i < naxis; i++) { - Mapping part = new UnitMap(1); - map3 = map3 == null ? part : new CmpMap(map3, part, false); - } Mapping map4; if (otherAxis) { map4 = null; @@ -682,6 +640,20 @@ private static Mapping buildPixelToWorld( return new CmpMap(map6, map4, true); } + /** + * Which axes of {@code store} the celestial and spectral stages describe, leaving the others + * to {@code WcsOthers}, which finds them as the axes whose primary Frame still has the Domain + * {@code WcsMapFrm} gave the Frame it started from. + */ + private static boolean[] claimedAxes(FitsStore store, FitsWcsCelestial.CelestialResult celestial) { + boolean[] claimed = FitsWcsSpectral.spectralAxes(store); + if (celestial != null) { + claimed[celestial.lonAxis] = true; + claimed[celestial.latAxis] = true; + } + return claimed; + } + /** * The IWC to WCS Mapping C's {@code WcsOthers} makes for an axis no other stage describes * (fitschan.c:39355-39368): {@code LogWcs} for a CTYPE ending in {@code -LOG}, and otherwise @@ -705,28 +677,50 @@ private static Mapping othersAxisMap(FitsStore store, int axis) { return crval != 0.0 ? new ShiftMap(new double[] {crval}) : new UnitMap(1); } + /** The WCS Frame of an axis description, the units of its IWC Frame and its spectral Mapping. */ + static final class World { + /** The WCS Frame. */ + final Frame frame; + + /** The Unit of each axis of the IWC Frame, or null to leave it unset. */ + final String[] iwcUnits; + + /** The Mapping of the spectral stage ({@code WcsSpectral}), over every axis. */ + final Mapping spectralMap; + + World(Frame frame, String[] iwcUnits, Mapping spectralMap) { + this.frame = frame; + this.iwcUnits = iwcUnits; + this.spectralMap = spectralMap; + } + } + /** - * The WCS Frame of an axis description, as C's {@code WcsMapFrm} makes it from a Frame with - * an axis for each WCS axis, which {@code WcsCelestial} restructures to hold the SkyFrame of - * any celestial axes and {@code WcsOthers} completes for the other axes. + * The WCS Frame of axis description {@code s}, as C's {@code WcsMapFrm} makes it from a Frame + * with an axis for each WCS axis, which {@code WcsCelestial} restructures to hold the SkyFrame + * of any celestial axes, {@code WcsSpectral} to hold a SpecFrame for each spectral axis, and + * {@code WcsOthers} completes for the other axes; with the units those stages give the axes of + * the IWC Frame (degrees for the celestial axes, the spectral unit for a spectral axis, and + * any CUNIT for the others) and the Mapping of the spectral stage. * *

      - *
    • With no celestial axes, a Frame whose axes carry the CTYPE, CNAME and CUNIT values, - * its Domain made of the CTYPE values, and any WCSNAME as Domain and in the Title. - *
    • With only celestial axes, the SkyFrame. - *
    • Otherwise a CmpFrame of the other axes, picked from such a Frame, and the SkyFrame, - * its axes permuted back to the FITS order; the WCSNAME names the CmpFrame. + *
    • With no celestial or spectral axes, a Frame whose axes carry the CTYPE, CNAME and + * CUNIT values, its Domain made of the CTYPE values, and any WCSNAME as Domain and in + * the Title. + *
    • With only celestial axes, the SkyFrame; with only one spectral axis, the SpecFrame. + *
    • Otherwise CmpFrames of the other axes, picked from such a Frame, the SkyFrame and the + * SpecFrames, their axes permuted back to the FITS order; the WCSNAME names the outer + * CmpFrame when there are other axes. *
    * *

    The SkyFrame takes the reference position as SkyRef (see {@link #wcsCelestialFrame}). + * + * @param warnings receives the warnings the spectral stage raises */ - static Frame buildWorldFrame(FitsStore store, FitsWcsCelestial.CelestialResult celestial) { + static World buildWorld( + FitsStore store, FitsWcsCelestial.CelestialResult celestial, char s, FitsWarnings warnings) { int naxis = store.naxis; - boolean[] claimed = new boolean[naxis]; - if (celestial != null) { - claimed[celestial.lonAxis] = true; - claimed[celestial.latAxis] = true; - } + boolean[] claimed = claimedAxes(store, celestial); int nother = 0; for (boolean c : claimed) { if (!c) { @@ -742,17 +736,25 @@ static Frame buildWorldFrame(FitsStore store, FitsWcsCelestial.CelestialResult c others[j++] = i; } } + String[] iwcUnits = new String[naxis]; // The Frame of every axis, carrying what WcsOthers sets on the axes it describes; the - // celestial stage replaces the axes it describes. + // celestial and spectral stages replace the axes they describe. Frame frame = seedLinearFrame(store, all, others); if (celestial != null) { frame = wcsCelestialFrame(frame, celestial, naxis); + iwcUnits[celestial.lonAxis] = "deg"; + iwcUnits[celestial.latAxis] = "deg"; + } + FitsWcsSpectral.Result spectral = FitsWcsSpectral.wcsSpectral(store, s, frame, iwcUnits, celestial, warnings); + frame = spectral.frame; + for (int axis : others) { + iwcUnits[axis] = store.cunit[axis]; } // WcsOthers sets the WCSNAME only when it describes some axes. if (nother > 0) { applyWcsname(store, frame); } - return frame; + return new World(frame, iwcUnits, spectral.map); } /** @@ -780,14 +782,14 @@ private static Frame wcsCelestialFrame(Frame frame, FitsWcsCelestial.CelestialRe if (paxis[0] != 1) { sfrm.permAxes(new int[] {2, 1}); } - double[] ref = celestial.refPos; - if (ref != null - && !celestial.refPosForced + double reflon = celestial.refLon; + double reflat = celestial.refLat; + if (!celestial.refPosForced && !sfrm.testSkyRef(1) - && ref[0] != AstObject.AST__BAD - && ref[1] != AstObject.AST__BAD) { - sfrm.setSkyRef(1, ref[0]); - sfrm.setSkyRef(2, ref[1]); + && reflon != AstObject.AST__BAD + && reflat != AstObject.AST__BAD) { + sfrm.setSkyRef(1, reflon); + sfrm.setSkyRef(2, reflat); sfrm.setSkyRefIs("Ignored"); } int[] axes = new int[naxes]; @@ -815,9 +817,9 @@ private static Frame wcsCelestialFrame(Frame frame, FitsWcsCelestial.CelestialRe } } result.permAxes(axes); - if (ref != null && celestial.refPosForced) { - sfrm.setSkyRef(1, ref[0]); - sfrm.setSkyRef(2, ref[1]); + if (celestial.refPosForced) { + sfrm.setSkyRef(1, reflon); + sfrm.setSkyRef(2, reflat); sfrm.setSkyRefIs("Ignored"); } return result; diff --git a/src/main/java/uk/ac/starlink/ast/FitsWcsSpectral.java b/src/main/java/uk/ac/starlink/ast/FitsWcsSpectral.java new file mode 100644 index 0000000..ecb457a --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FitsWcsSpectral.java @@ -0,0 +1,457 @@ +package uk.ac.starlink.ast; + +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * The spectral axes of a FITS-WCS axis description: C's {@code WcsSpectral}, which describes each + * axis whose CTYPE names a spectral system of FITS-WCS paper III with a SpecFrame (a DSBSpecFrame + * when the header gives IMAGFREQ) and makes the Mapping from its intermediate world coordinate to + * that system, leaving the other axes unchanged. + * + *

    The SpecFrame takes its System from the CTYPE, its reference position from the celestial + * axes, its Unit from CUNIT, its Epoch from the date of observation, its rest frequency from + * RESTFRQ or RESTWAV, the observer's position from OBSGEO-X/Y/Z, the source velocity from SSYSSRC + * and ZSOURCE, its standard of rest from SPECSYS and its Label from CNAME, in C's order. The + * Mapping depends on the algorithm code: a linear axis adds CRVAL, a {@code -X2P} axis (C's {@code + * NonLinSpecWcs}) is linear in the system X and converted to the axis's own system, and the + * {@code -LOG} and {@code -GRI}/{@code -GRA} axes need MathMap and GrismMap, which are not + * available. + * + *

    Ported from Rust {@code fitschan/wcs_spectral.rs}, following C's {@code WcsSpectral}, {@code + * NonLinSpecWcs}, {@code GrismSpecWcs}, {@code LogWcs} and {@code DSBSetUp} (fitschan.c) where + * the two differ. + */ +final class FitsWcsSpectral { + + /** The method C's read reports errors from. */ + private static final String METHOD = "astRead"; + + /** The class C's read reports errors for. */ + private static final String CLASS = "FitsChan"; + + private FitsWcsSpectral() {} + + /** What {@link #wcsSpectral} makes: the Mapping over every axis, and the Frame describing them. */ + static final class Result { + /** The Mapping from intermediate world coordinates, one Mapping per axis in parallel. */ + final Mapping map; + + /** The Frame, with a SpecFrame for each spectral axis. */ + final Frame frame; + + Result(Mapping map, Frame frame) { + this.map = map; + this.frame = frame; + } + } + + /** + * Whether each axis of {@code store} is one {@link #wcsSpectral} describes: its CTYPE names a + * spectral system, as C's {@code IsSpectral} decides. + */ + static boolean[] spectralAxes(FitsStore store) { + boolean[] spectral = new boolean[store.naxis]; + for (int i = 0; i < store.naxis; i++) { + spectral[i] = store.ctype[i] != null && FitsStore.isSpectral(store.ctype[i]) != null; + } + return spectral; + } + + /** + * C's {@code WcsSpectral} (fitschan.c:39913) for axis description {@code s} of {@code store}. + * For each spectral axis in turn, the SpecFrame describing it replaces that axis of {@code + * frm}: the other axes are picked from the Frame, joined with the SpecFrame in a CmpFrame, and + * permuted to put the spectral axis back in place (the SpecFrame alone replaces a Frame with no + * other axes). Each spectral axis's element of {@code iwcUnits}, the units of the IWC Frame, is + * set to its unit. + * + * @param frm the Frame describing every axis, as {@code WcsCelestial} leaves it + * @param celestial the celestial axes, whose SkyFrame and reference position give the + * SpecFrames their reference position, or null when there are none + * @param warnings receives the warnings raised + * @return the Mapping, one Mapping per axis in parallel, a UnitMap for each axis that is not + * spectral, and the Frame + * @throws AstException with status {@code AST__BDFTS} for an algorithm code that cannot be + * implemented, as C reports it, or as the attribute settings report a bad keyword value + * @throws UnsupportedOperationException for a {@code -LOG} axis with a non-zero CRVAL, whose + * Mapping needs MathMap, or a {@code -GRI} or {@code -GRA} axis, whose Mapping needs + * GrismMap + */ + static Result wcsSpectral( + FitsStore store, + char s, + Frame frm, + String[] iwcUnits, + FitsWcsCelestial.CelestialResult celestial, + FitsWarnings warnings) { + int naxes = frm.getNaxes(); + int[] axes = new int[naxes]; + Mapping ret = null; + Frame frame = frm; + for (int i = 0; i < naxes; i++) { + Mapping map1 = null; + String ctype = store.ctype[i]; + String defunit = ctype != null ? FitsStore.isSpectral(ctype) : null; + if (defunit != null) { + SpecFrame specfrm = specFrame(store, i, ctype, defunit, iwcUnits, celestial, warnings); + String algcode = algorithmCode(ctype); + if (algcode.isEmpty()) { + map1 = linearWcs(store, i); + } else if ("-LOG".equals(algcode)) { + map1 = logWcs(store, i, ctype); + } else if (algcode.charAt(0) == '-' && algcode.length() > 2 && algcode.charAt(2) == '2') { + map1 = nonLinSpecWcs(algcode, store, i, specfrm, warnings); + } else if ("-GRI".equals(algcode) || "-GRA".equals(algcode)) { + map1 = grismSpecWcs(algcode, i, specfrm, ctype); + } else { + // An algorithm code C does not know, which it reports below. + map1 = null; + } + if (map1 == null) { + throw Ast.err( + AstException.AST__BDFTS, + METHOD + "(" + CLASS + "): Cannot implement spectral algorithm code '" + + ctype.substring(4) + "' specified in FITS keyword '" + + FitsWcsKeywords.keyFor("CTYPE", i + 1, s) + "'.\n" + METHOD + "(" + CLASS + + "): Unknown algorithm code or unusable parameter values."); + } + frame = replaceAxis(frame, i, specfrm, axes); + } + if (map1 == null) { + map1 = new UnitMap(1); + } + ret = ret == null ? map1 : new CmpMap(ret, map1, false); + } + return new Result(ret, frame); + } + + /** + * The Frame {@code frm} with axis {@code i} (from 0) replaced by {@code specfrm}: the other + * axes picked into a Frame and joined with the SpecFrame in a CmpFrame, or the SpecFrame alone + * when there are no other axes, then permuted to put the spectral axis back in place + * (fitschan.c:40171-40206). {@code axes} is workspace with an element for each axis. + */ + private static Frame replaceAxis(Frame frm, int i, SpecFrame specfrm, int[] axes) { + int naxes = frm.getNaxes(); + int j = 0; + for (int k = 0; k < naxes; k++) { + if (k != i) { + axes[j++] = k + 1; + } + } + Frame result; + if (j == 0) { + result = specfrm; + } else { + Frame ofrm = frm.pickAxes(j, axes, null); + result = new CmpFrame(ofrm, specfrm); + } + j = 0; + for (int kk = 0; kk < naxes; kk++) { + axes[kk] = kk == i ? naxes : ++j; + } + result.permAxes(axes); + return result; + } + + /** + * The SpecFrame (or DSBSpecFrame) of spectral axis {@code i} (from 0), set up as C's {@code + * WcsSpectral} sets it up before choosing the Mapping (fitschan.c:40043-40136), in C's order. + * The axis's element of {@code iwcUnits} is set to its unit. + */ + private static SpecFrame specFrame( + FitsStore store, + int i, + String ctype, + String defunit, + String[] iwcUnits, + FitsWcsCelestial.CelestialResult celestial, + FitsWarnings warnings) { + // A SpecFrame, or a DSBSpecFrame when there is an IMAGFREQ. C sets the System from the + // first four characters of the CTYPE, without trailing spaces, which are also legal + // System values. + SpecFrame specfrm = store.imagfreq == null ? new SpecFrame() : new DSBSpecFrame(); + specfrm.setC("System", systemType(ctype)); + + // The reference position, if there are celestial axes. + if (celestial != null) { + specfrm.setRefPos(celestial.frame, celestial.refLon, celestial.refLat); + } + + // The Unit: CUNIT, or the default unit of the system; also the Unit of the IWC axis. + String cunit = store.cunit[i] != null ? store.cunit[i] : defunit; + specfrm.setUnit(1, cunit); + iwcUnits[i] = cunit; + + // The date of observation. + Double mjd = FitsEpoch.chooseEpoch(store, warnings); + if (mjd != null && mjd != AstObject.AST__BAD) { + specfrm.setEpochMjd(mjd); + } + + // The rest frequency, from RESTFRQ (Hz) or else RESTWAV (m); C sets the bad value when there + // is neither, which leaves the RestFreq unset. + double restfrq; + if (store.restfrq != null) { + restfrq = store.restfrq; + } else if (store.restwav != null) { + restfrq = SpecMap.AST__C / store.restwav; + } else { + restfrq = AstObject.AST__BAD; + } + specfrm.setRestFreqValue(restfrq); + + // The observer's position, from the primary axis description's OBSGEO-X/Y/Z. + if (store.obsgeox != null && store.obsgeoy != null && store.obsgeoz != null) { + double[] geo = Pal.gc2gd(new double[] {store.obsgeox, store.obsgeoy, store.obsgeoz}); + if (geo != null) { + specfrm.setObsLatValue(geo[1]); + specfrm.setObsLonValue(geo[0]); + specfrm.setObsAlt(geo[2]); + } + } + + // The rest frame of the source velocity, and the source velocity from the redshift + // ZSOURCE (relativistic). + if (store.ssyssrc != null) { + specfrm.setC("SourceVRF", store.ssyssrc); + } + if (store.zsource != null) { + double vsource = store.zsource + 1.0; + vsource *= vsource; + vsource = SpecMap.AST__C * (vsource - 1.0) / (vsource + 1.0); + specfrm.setSourceVelValue(vsource); + } + + // The standard of rest; the FITS codes are also legal StdOfRest values. + if (store.specsys != null) { + specfrm.setC("StdOfRest", store.specsys); + } + + // The axis Label, from CNAME. + if (store.cname[i] != null) { + specfrm.setLabel(1, store.cname[i]); + } + + // The observation centre: AXREF, which a write gives a -TAB axis with no inverse, in + // preference to CRVAL. + Double obscentre = store.axref[i] != null ? store.axref[i] : store.crval[i]; + if (specfrm instanceof DSBSpecFrame) { + dsbSetUp(store, (DSBSpecFrame) specfrm, obscentre != null ? obscentre : AstObject.AST__BAD); + } + return specfrm; + } + + /** + * The spectral system code of a CTYPE, its first four characters without trailing spaces, as + * C's {@code IsSpectral} extracts it. + */ + private static String systemType(String ctype) { + String stype = ctype.substring(0, 4); + int n = stype.length(); + while (n > 0 && stype.charAt(n - 1) == ' ') { + n--; + } + return stype.substring(0, n); + } + + /** + * The algorithm code of a CTYPE, as C's {@code IsSpectral} extracts it: at most four + * characters after the first four, without trailing spaces. + */ + static String algorithmCode(String ctype) { + if (ctype.length() <= 4) { + return ""; + } + String rest = ctype.substring(4); + if (rest.length() > 4) { + rest = rest.substring(0, 4); + } + int n = rest.length(); + while (n > 0 && rest.charAt(n - 1) == ' ') { + n--; + } + return rest.substring(0, n); + } + + /** + * C's {@code DSBSetUp} (fitschan.c:9177): sets the DSBCentre of {@code dsb} to {@code crval}, + * its IF to the difference between the topocentric local oscillator frequency, half way + * between the topocentric rest and image frequencies, and the topocentric DSBCentre, and its + * SideBand to the observed sideband. The RestFreq and IMAGFREQ are frequencies in the source's + * rest frame. Nothing is set when there is no conversion from that rest frame to the + * topocentric one, or it gives a bad frequency. + */ + private static void dsbSetUp(FitsStore store, DSBSpecFrame dsb, double crval) { + DSBSpecFrame dsbSrc = (DSBSpecFrame) dsb.copy(); + dsbSrc.setStdOfRestValue(SpecFrame.AST__SCSOR); + dsbSrc.setSystemValue(SpecFrame.AST__FREQ); + dsbSrc.setUnit(1, "Hz"); + DSBSpecFrame dsbTopo = (DSBSpecFrame) dsbSrc.copy(); + dsbTopo.setStdOfRestValue(SpecFrame.AST__TPSOR); + FrameSet fs = dsbSrc.convert(dsbTopo, ""); + if (fs == null) { + return; + } + double imagfreq = store.imagfreq != null ? store.imagfreq : AstObject.AST__BAD; + double[] out = fs.tran1(2, new double[] {dsb.restFreqValue(), imagfreq}, true); + if (out[0] != AstObject.AST__BAD && out[1] != AstObject.AST__BAD) { + dsb.setD("DSBCentre", crval); + dsbTopo = (DSBSpecFrame) dsb.copy(); + dsbTopo.setStdOfRestValue(SpecFrame.AST__TPSOR); + dsbTopo.setSystemValue(SpecFrame.AST__FREQ); + dsbTopo.setUnit(1, "Hz"); + double dsbcentre = dsbTopo.getD("DSBCentre"); + double lo = 0.5 * (out[1] + out[0]); + dsb.setIfValue(lo - dsbcentre); + dsb.setC("SideBand", "observed"); + } + } + + /** + * C's {@code LinearWcs} (fitschan.c:20713): a ShiftMap adding CRVAL, or a UnitMap when CRVAL + * is zero or absent. + */ + private static Mapping linearWcs(FitsStore store, int i) { + double crv = store.crval[i] != null ? store.crval[i] : 0.0; + return crv != 0.0 ? new ShiftMap(new double[] {crv}) : new UnitMap(1); + } + + /** + * C's {@code LogWcs} (fitschan.c:20904) for a spectral axis: a MathMap {@code S = Sr*exp(w/Sr)} + * with {@code Sr} the CRVAL, or null when CRVAL is zero or absent, which has no logarithmic + * form. + * + * @throws UnsupportedOperationException when CRVAL is not zero, since the MathMap is not + * available + */ + private static Mapping logWcs(FitsStore store, int i, String ctype) { + double crv = store.crval[i] != null ? store.crval[i] : 0.0; + if (crv != 0.0) { + throw new UnsupportedOperationException( + "FitsChan: the -LOG spectral axis " + (i + 1) + " (CTYPE '" + ctype + "') needs MathMap"); + } + return null; + } + + /** + * C's {@code NonLinSpecWcs} (fitschan.c:23867): the Mapping of a {@code -X2P} axis, sampled + * linearly in the system X the second character of the code names (F, W, V or A), from the + * intermediate world coordinate {@code w} to the axis's system S. FITS-WCS paper III makes + * {@code dS/dw} one at the reference point, so {@code w} maps to X through a WinMap (a ZoomMap + * when the reference value in X is zero) scaled by {@code dX/dS} there, and X to S through the + * conversion between two copies of the SpecFrame. A {@code badctype} warning is raised when + * the fourth character of the code is not the P system that S implies. + * + * @return the Mapping, or null when X is not one of those, there is no conversion from S to + * X, or {@code dS/dX} at the reference point is bad or zero + */ + private static Mapping nonLinSpecWcs( + String algcode, FitsStore store, int i, SpecFrame specfrm, FitsWarnings warnings) { + SpecFrame xfrm = (SpecFrame) specfrm.copy(); + boolean ok = true; + char x = algcode.charAt(1); + if (x == 'F') { + xfrm.setSystemValue(SpecFrame.AST__FREQ); + xfrm.setUnit(1, "Hz"); + } else if (x == 'W') { + xfrm.setSystemValue(SpecFrame.AST__WAVELEN); + xfrm.setUnit(1, "m"); + } else if (x == 'V') { + xfrm.setSystemValue(SpecFrame.AST__VREL); + xfrm.setUnit(1, "m/s"); + } else if (x == 'A') { + xfrm.setSystemValue(SpecFrame.AST__AIRWAVE); + xfrm.setUnit(1, "m"); + } else { + ok = false; + } + Mapping map1 = null; + if (ok) { + ok = false; + FrameSet fs = specfrm.convert(xfrm, ""); + if (fs != null) { + map1 = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + ok = true; + } + + // A warning when the P system is not the one S implies; AST interprets the illegal P + // system correctly, so the read goes on. + char pc = requiredP(specfrm); + char p = algcode.length() > 3 ? algcode.charAt(3) : '\0'; + if (p != pc) { + String text = specfrm.getC("System"); + warnings.push(new FitsWarnings.Warning( + "badctype", + "The spectral CTYPE value " + text + algcode + " is not legal - using " + text + + algcode.substring(0, Math.min(3, algcode.length())) + pc + " instead.")); + } + } + if (!ok) { + return null; + } + double crv = store.crval[i] != null ? store.crval[i] : 0.0; + crv = map1.tran1(1, new double[] {crv}, true)[0]; + map1.invert(); + double ds = map1.rate(new double[] {crv}, 1, 1); + if (ds == AstObject.AST__BAD || ds == 0.0) { + return null; + } + Mapping map2; + if (crv != 0.0) { + map2 = new WinMap( + 1, new double[] {0.0}, new double[] {crv * ds}, new double[] {crv}, new double[] {2.0 * crv}); + } else { + map2 = new ZoomMap(1, 1.0 / ds); + } + return new CmpMap(map2, map1, true); + } + + /** + * The P character of a {@code -X2P} code that the System of {@code specfrm} implies + * (fitschan.c:23995-24012): F for frequency, energy, wavenumber and radio velocity, W for + * wavelength, optical velocity and redshift, A for air wavelength, V for beta and apparent + * radial velocity. + */ + private static char requiredP(SpecFrame specfrm) { + int sys = specfrm.systemValue(); + if (sys == SpecFrame.AST__FREQ + || sys == SpecFrame.AST__ENERGY + || sys == SpecFrame.AST__WAVENUM + || sys == SpecFrame.AST__VRADIO) { + return 'F'; + } else if (sys == SpecFrame.AST__WAVELEN || sys == SpecFrame.AST__VOPTICAL || sys == SpecFrame.AST__REDSHIFT) { + return 'W'; + } else if (sys == SpecFrame.AST__AIRWAVE) { + return 'A'; + } else if (sys == SpecFrame.AST__BETA || sys == SpecFrame.AST__VREL) { + return 'V'; + } else { + throw Ast.err( + AstException.AST__INTER, + METHOD + ": Function NonLinSpecWcs does not yet support spectral axes of type " + + specfrm.getC("System") + " (internal AST programming error)."); + } + } + + /** + * C's {@code GrismSpecWcs} (fitschan.c:14424) for a {@code -GRI} (vacuum) or {@code -GRA} (air + * wavelength) axis: the Mapping is built from the conversion of the SpecFrame to wavelength in + * metres and a GrismMap. + * + * @return null when there is no conversion from the SpecFrame to wavelength + * @throws UnsupportedOperationException when there is one, since the GrismMap is not + * available + */ + private static Mapping grismSpecWcs(String algcode, int i, SpecFrame specfrm, String ctype) { + SpecFrame wfrm = (SpecFrame) specfrm.copy(); + wfrm.setSystemValue("-GRI".equals(algcode) ? SpecFrame.AST__WAVELEN : SpecFrame.AST__AIRWAVE); + wfrm.setUnit(1, "m"); + FrameSet fs = specfrm.convert(wfrm, ""); + if (fs == null) { + return null; + } + throw new UnsupportedOperationException( + "FitsChan: the " + algcode + " spectral axis " + (i + 1) + " (CTYPE '" + ctype + "') needs GrismMap"); + } +} diff --git a/src/main/java/uk/ac/starlink/ast/FluxFrame.java b/src/main/java/uk/ac/starlink/ast/FluxFrame.java new file mode 100644 index 0000000..c589f57 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/FluxFrame.java @@ -0,0 +1,911 @@ +package uk.ac.starlink.ast; + +/** + * A description of flux values. A FluxFrame is a one-dimensional Frame describing the signal + * level in an observation, in the system its System attribute names: flux density per unit + * frequency ({@code FLXDN}, the default, in W/m^2/Hz), flux density per unit wavelength ({@code + * FLXDNW}, in W/m^2/Angstrom), surface brightness per unit frequency ({@code SFCBR}, in + * W/m^2/Hz/arcmin**2) or surface brightness per unit wavelength ({@code SFCBRW}, in + * W/m^2/Angstrom/arcmin**2; {@code SRCBR} is accepted for it too). The Unit attribute may give + * other units of the same kind; with a Unit set and no System, the System is the first of these + * whose default units can be converted to the Unit. The Unit last used with each System comes back + * when the System does. + * + *

    All flux values are taken to be measured at one spectral position, the SpecVal attribute, + * given in the spectral system of the SpecFrame supplied when the FluxFrame is made (or, with no + * SpecFrame, as a frequency in Hz for a per-frequency System and a wavelength in Angstrom for a + * per-wavelength one). A FluxFrame is therefore more suited to images than to spectra. Two + * FluxFrames convert between flux densities per unit frequency and per unit wavelength only when + * their SpecVals give the same spectral position, and never between a flux density and a surface + * brightness. A FluxFrame always uses the Unit of its axis when it is aligned with another (its + * ActiveUnit flag is always true). + * + *

    Ported from C {@code fluxframe.c}, with Rust {@code frames/fluxframe.rs}. + */ +public class FluxFrame extends Frame { + + /** The System of flux density per unit frequency. */ + static final int AST__FLUXDEN = 1; + + /** The System of flux density per unit wavelength. */ + static final int AST__FLUXDENW = 2; + + /** The System of surface brightness per unit frequency. */ + static final int AST__SBRIGHT = 3; + + /** The System of surface brightness per unit wavelength. */ + static final int AST__SBRIGHTW = 4; + + private static final int FIRST_SYSTEM = AST__FLUXDEN; + private static final int LAST_SYSTEM = AST__SBRIGHTW; + + /** The digits C writes a full-precision double with ({@code AST__DBL_DIG}). */ + private static final int DBL_DIG = 17; + + /** The SpecVal, or bad if unset. */ + private double specValue = AST__BAD; + + /** The SpecVal used when none is set, given when the FluxFrame is made, or bad (C's {@code defspecval}). */ + private double defSpecVal; + + /** The SpecFrame giving the spectral system of the SpecVal, or null for the default one. */ + private SpecFrame specFrame; + + /** The Unit last set with each System, indexed by System code, or null (C's {@code usedunits}). */ + private String[] usedUnits = new String[LAST_SYSTEM + 1]; + + /** + * Creates a FluxFrame for flux values measured at a spectral position. + * + * @param specval the spectral position at which the flux values are measured, in the spectral + * system and units of {@code specfrm}: the default SpecVal. It may be {@link #AST__BAD} if + * the position is not known, but then no conversion to another FluxFrame may be found. + * @param specfrm the spectral system of {@code specval}, of which a deep copy is kept; or null + * (allowed if {@code specval} is bad), for a frequency in Hz with a per-frequency System and + * a wavelength in Angstrom with a per-wavelength one + */ + // C's astFluxFrame checks that the Unit suits the System once its options string is applied; + // these constructors take no options, and the default Unit and System always agree. + public FluxFrame(double specval, SpecFrame specfrm) { + super(1); + defSpecVal = specval; + specFrame = specfrm == null ? null : (SpecFrame) specfrm.copy(); + } + + /** Creates a FluxFrame with every attribute at its default and no spectral position. */ + public FluxFrame() { + this(AST__BAD, null); + } + + /** + * Loads a FluxFrame from its description, as C's {@code astLoadFluxFrame} does: DfSpc, the + * SpecFrame SpcFr, SpcVl and the Unit used with each System ({@code U}), each unset if + * absent. + * + * @param node the description + * @throws AstException with status {@code AST__LDERR} if SpcFr is not a SpecFrame + */ + FluxFrame(NativeNode node) { + super(node); + NativeNode part = node.section("FluxFrame"); + defSpecVal = part.readDouble("DfSpc", AST__BAD); + NativeNode desc = part.readObject("SpcFr"); + if (desc != null) { + AstObject obj = ObjectRegistry.loadNested(desc, "SpcFr"); + // C stores whatever Object it reads; a FluxFrame here holds only a SpecFrame. + if (!(obj instanceof SpecFrame)) { + throw Ast.err( + AstException.AST__LDERR, + "astLoadFluxFrame(FluxFrame): The object SpcFr is a " + obj.astClass() + ", not a SpecFrame."); + } + specFrame = (SpecFrame) obj; + } + specValue = part.readDouble("SpcVl", AST__BAD); + for (int sys = FIRST_SYSTEM; sys <= LAST_SYSTEM; sys++) { + String unit = part.getStringIfSet(usedUnitKey(sys)); + if (unit != null) { + usedUnits[sys] = unit; + } + } + } + + @Override + String dumpComment() { + return "Description of flux values"; + } + + /** The key of the dump item holding the Unit used with a System: {@code U} and its name, as {@code UFlxdn}. */ + private static String usedUnitKey(int sys) { + String name = fluxSystemString(sys); + StringBuilder sb = new StringBuilder("U").append(name); + for (int j = 2; j < sb.length(); j++) { + sb.setCharAt(j, CScan.toLower(sb.charAt(j))); + } + return sb.toString(); + } + + /** Writes the FluxFrame class's part of a description, as C's {@code Dump} (fluxframe.c) does. */ + @Override + void dump(NativeNode node) { + super.dump(node); + node.writeIsA("Frame", "Coordinate system description"); + boolean set = testSpecVal(); + double dval = specValValue(); + if (dval != AST__BAD) { + node.writeDouble("SpcVl", set, false, dval, "Spectral position"); + } + if (specFrame != null) { + node.writeObject("SpcFr", true, false, NativeNode.of(specFrame), "SpcVl coord system"); + } + if (defSpecVal != AST__BAD) { + node.writeDouble("DfSpc", true, false, defSpecVal, "Default spectral position"); + } + for (int i = 0; i < usedUnits.length; i++) { + if (usedUnits[i] != null) { + node.writeString(usedUnitKey(i), true, false, usedUnits[i], "Preferred units for " + systemLabel(i)); + } + } + } + + /** Copies the record of the Unit used with each System and the SpecFrame, as C's {@code Copy} (fluxframe.c) does. */ + @Override + void deepCopy() { + super.deepCopy(); + usedUnits = usedUnits.clone(); + if (specFrame != null) { + specFrame = (SpecFrame) specFrame.copy(); + } + } + + // ------------------------------------------------------------------ + // Systems + // ------------------------------------------------------------------ + + /** The System code a name gives, ignoring case and trailing white space (C's {@code SystemCode}). */ + @Override + int systemCode(String name) { + if (chrMatch("FLXDN", name)) { + return AST__FLUXDEN; + } else if (chrMatch("FLXDNW", name)) { + return AST__FLUXDENW; + } else if (chrMatch("SFCBR", name)) { + return AST__SBRIGHT; + } else if (chrMatch("SFCBRW", name) || chrMatch("SRCBR", name)) { + return AST__SBRIGHTW; + } + return AST__BADSYSTEM; + } + + /** The name of a System code, or null (C's {@code SystemString}). */ + @Override + String systemString(int code) { + return fluxSystemString(code); + } + + /** The name of a System code, or null (C's {@code FluxSystemString}). */ + private static String fluxSystemString(int code) { + switch (code) { + case AST__FLUXDEN: + return "FLXDN"; + case AST__FLUXDENW: + return "FLXDNW"; + case AST__SBRIGHT: + return "SFCBR"; + case AST__SBRIGHTW: + return "SFCBRW"; + default: + return null; + } + } + + /** The description of a System code, in lower case, or null (C's {@code SystemLabel}). */ + static String systemLabel(int system) { + switch (system) { + case AST__FLUXDEN: + return "flux density"; + case AST__FLUXDENW: + return "flux wavelength density"; + case AST__SBRIGHT: + return "surface brightness"; + case AST__SBRIGHTW: + return "surface brightness (per wavelength)"; + default: + return null; + } + } + + /** A System's description with its first letter in upper case, as C's labels and titles start. */ + private static String capitalised(int system) { + String label = systemLabel(system); + return CScan.toUpper(label.charAt(0)) + label.substring(1); + } + + /** + * Checks a System code (C's {@code ValidateSystem}). + * + * @throws AstException with status {@code AST__AXIIN} if it is not a flux System + */ + @Override + int validateSystem(int code, String method) { + if (code < FIRST_SYSTEM || code > LAST_SYSTEM) { + throw Ast.err( + AstException.AST__AXIIN, + method + "(" + astClass() + "): Bad value (" + code + ") given for the System or AlignSystem" + + " attribute of a " + astClass() + "."); + } + return code; + } + + /** + * The default units of a System (C's {@code DefUnit}). + * + * @throws AstException with status {@code AST__SCSIN} if the System is not a flux System + */ + static String defUnit(int system, String method, String cls) { + switch (system) { + case AST__FLUXDEN: + return "W/m^2/Hz"; + case AST__FLUXDENW: + return "W/m^2/Angstrom"; + case AST__SBRIGHT: + return "W/m^2/Hz/arcmin**2"; + case AST__SBRIGHTW: + return "W/m^2/Angstrom/arcmin**2"; + default: + throw Ast.err( + AstException.AST__SCSIN, + method + "(" + cls + "): Corrupt " + cls + " contains illegal System identification code (" + + system + ")."); + } + } + + /** + * The spectral System a flux System is a density in (C's {@code DensitySystem}): frequency for + * a per-frequency System, wavelength for a per-wavelength one. + * + * @throws AstException with status {@code AST__INTER} if the System is not a flux System + */ + private static int densitySystem(int sys) { + switch (sys) { + case AST__FLUXDEN: + case AST__SBRIGHT: + return SpecFrame.AST__FREQ; + case AST__FLUXDENW: + case AST__SBRIGHTW: + return SpecFrame.AST__WAVELEN; + default: + throw Ast.err( + AstException.AST__INTER, + "DensitySystem(FluxFrame): The DensitySystem method does not yet support FluxFrame system " + + sys + " (AST internal programming error)."); + } + } + + /** + * The default units of the spectral System a flux System is a density in (C's {@code + * DensityUnit}): {@code Hz} or {@code Angstrom}. + * + * @throws AstException with status {@code AST__INTER} if the System is not a flux System + */ + private static String densityUnit(int sys) { + switch (sys) { + case AST__FLUXDEN: + case AST__SBRIGHT: + return "Hz"; + case AST__FLUXDENW: + case AST__SBRIGHTW: + return "Angstrom"; + default: + throw Ast.err( + AstException.AST__INTER, + "DensityUnit(FluxFrame): The DensityUnit method does not yet support FluxFrame system " + sys + + " (AST internal programming error)."); + } + } + + /** The spectral System this FluxFrame's values are a density in (C's {@code astGetDensitySystem}). */ + int getDensitySystem() { + return densitySystem(systemValue()); + } + + /** The default units of the spectral System this FluxFrame's values are a density in (C's {@code astGetDensityUnit}). */ + String getDensityUnit() { + return densityUnit(systemValue()); + } + + /** + * Whether values in units {@code from} can be converted to units {@code to}, as C finds by + * asking {@code astUnitMapper} for the Mapping. The conversion is found without making the + * Mapping, which for some units, such as logarithmic ones, needs a class this library does + * not have. + */ + private static boolean unitsConvert(String from, String to) { + return Units.relabel(from, to, null) != null; + } + + /** + * The System (C's {@code GetSystem}): set; or, with a Unit set, the first System whose default + * units can be converted from the Unit; or {@link #AST__FLUXDEN}. + * + * @throws AstException with status {@code AST__BADUN} if the System is not set and the Unit + * suits no flux System + */ + @Override + int systemValue() { + boolean unitSet = testUnit(1); + if (testSystem()) { + return super.systemValue(); + } else if (unitSet) { + String units = getUnit(1); + for (int i = FIRST_SYSTEM; i <= LAST_SYSTEM; i++) { + if (unitsConvert(units, defUnit(i, "astGetSystem", astClass()))) { + return i; + } + } + throw Ast.err( + AstException.AST__BADUN, + "astGetSystem(" + astClass() + "): The current units (" + getUnit(1) + + ") cannot be used with any of the supported flux systems."); + } + return AST__FLUXDEN; + } + + /** The AlignSystem: set, or {@link #AST__FLUXDEN} (C's {@code GetAlignSystem}). */ + @Override + int alignSystemValue() { + return testAlignSystem() ? super.alignSystemValue() : AST__FLUXDEN; + } + + /** + * Sets the System (C's {@code SetSystem}). If the System changes, the Unit last used with the + * new System is restored, or the Unit cleared, and the Label, Symbol and Title, whose defaults + * depend on the System, are cleared. + */ + @Override + void setSystemValue(int newsys) { + int oldsys = systemValue(); + super.setSystemValue(newsys); + if (oldsys != newsys) { + restoreUnit(newsys); + clearLabel(1); + clearSymbol(1); + clearTitle(); + } + } + + /** + * Clears the System (C's {@code ClearSystem}). If that changes the System, the Unit last used + * with the new System is restored, or the Unit cleared, and the Label, Symbol and Title are + * cleared. + */ + @Override + void clearSystem() { + int oldsys = systemValue(); + super.clearSystem(); + int newsys = systemValue(); + if (newsys != oldsys) { + restoreUnit(newsys); + clearLabel(1); + clearSymbol(1); + clearTitle(); + } + } + + /** + * Sets the Unit to the one last used with System {@code sys}, or clears it if there is none, + * through the Frame class's methods, which do not change the record of the Units used. + */ + private void restoreUnit(int sys) { + if (sys < usedUnits.length && usedUnits[sys] != null) { + super.setUnit(1, usedUnits[sys]); + } else { + super.clearUnit(1); + } + } + + // ------------------------------------------------------------------ + // SpecVal + // ------------------------------------------------------------------ + + /** + * Gets the SpecVal attribute: the spectral position (frequency, wavelength, etc.) at which + * the flux values are measured, in the spectral system of the SpecFrame the FluxFrame was made + * with. It is used when finding the Mapping between two FluxFrames. The default is the value + * the FluxFrame was made with. + * + * @return the SpecVal + * @throws AstException with status {@code AST__ATGER} if it is bad, which it is if neither set + * nor given when the FluxFrame was made + */ + public double getSpecVal() { + return getD("SpecVal"); + } + + /** + * Sets the SpecVal attribute; see {@link #getSpecVal}. + * + * @param specVal the SpecVal + */ + public void setSpecVal(double specVal) { + setD("SpecVal", specVal); + } + + /** The SpecVal: set, or the default given when the FluxFrame was made, either of which may be bad. */ + double specValValue() { + return specValue != AST__BAD ? specValue : defSpecVal; + } + + void setSpecValValue(double value) { + specValue = value; + } + + boolean testSpecVal() { + return specValue != AST__BAD; + } + + void clearSpecVal() { + specValue = AST__BAD; + } + + /** + * The SpecFrame describing the spectral system of the SpecVal (C's {@code GetSpecFrame}): the + * one the FluxFrame holds, or a new one in the frequency (Hz) or wavelength (Angstrom) its + * System is a density in. + */ + private SpecFrame getSpecFrame() { + if (specFrame != null) { + return specFrame; + } + SpecFrame result = new SpecFrame(); + result.setSystemValue(getDensitySystem()); + result.setUnit(1, getDensityUnit()); + return result; + } + + // ------------------------------------------------------------------ + // Frame attributes with FluxFrame defaults + // ------------------------------------------------------------------ + + /** The Domain: set, or {@code FLUX}. */ + @Override + public String getDomain() { + return testDomain() ? super.getDomain() : "FLUX"; + } + + /** + * Gets the ActiveUnit flag, which is always true for a FluxFrame: a difference in the Unit of + * two FluxFrames is always allowed for when one is converted to the other. + * + * @return true + */ + @Override + public boolean getActiveUnit() { + return true; + } + + @Override + boolean testActiveUnit() { + return false; + } + + /** Gets the Unit of the axis: set, or the default units of the System. */ + @Override + public String getUnit(int axis) { + validateAxis(axis, true, "astGetUnit"); + if (testUnit(axis)) { + return super.getUnit(axis); + } + return defUnit(systemValue(), "astGetUnit", astClass()); + } + + /** + * Sets the Unit of the axis (C's {@code SetUnit}). A Unit that can be converted from the + * default units of the System is recorded as the Unit used with that System, which comes back + * when the System does; any other Unit clears the System, which then follows from the Unit. + * + * @throws AstException with status {@code AST__BADUN} if the System is not set and the Unit + * suits no flux System (the Unit is set nonetheless) + */ + @Override + public void setUnit(int axis, String unit) { + super.setUnit(axis, unit); + validateAxis(axis, true, "astSetUnit"); + int system = systemValue(); + if (unitsConvert(defUnit(system, "astSetUnit", astClass()), unit)) { + if (usedUnits[system] == null || !usedUnits[system].equals(unit)) { + usedUnits[system] = unit; + } + } else { + super.clearSystem(); + } + } + + /** Clears the Unit of the axis and the record of the Unit used with the current System (C's {@code ClearUnit}). */ + @Override + void clearUnit(int axis) { + validateAxis(axis, true, "astClearUnit"); + int system = systemValue(); + if (system < usedUnits.length) { + usedUnits[system] = null; + } + super.clearUnit(axis); + } + + /** + * Gets the Label of the axis (C's {@code GetLabel}): set, or the System's description, + * rewritten for a set Unit, as {@code log( Flux density )} for {@code log(Jy)}. + */ + @Override + public String getLabel(int axis) { + validateAxis(axis, true, "astGetLabel"); + if (testLabel(axis)) { + return super.getLabel(axis); + } + int system = systemValue(); + String result = capitalised(system); + if (testUnit(axis)) { + Units.LabelledMapping lm = Units.relabel(defUnit(system, "astGetLabel", astClass()), getUnit(axis), result); + if (lm != null && lm.label != null) { + result = lm.label; + } + } + return result; + } + + /** + * Gets the Symbol of the axis (C's {@code GetSymbol}): set, or {@code S_nu}, {@code S_lambda}, + * {@code mu_nu} or {@code mu_lambda} for the System, rewritten for a set Unit. + */ + @Override + public String getSymbol(int axis) { + validateAxis(axis, true, "astGetSymbol"); + if (testSymbol(axis)) { + return super.getSymbol(axis); + } + int system = systemValue(); + String result; + switch (system) { + case AST__FLUXDEN: + result = "S_nu"; + break; + case AST__FLUXDENW: + result = "S_lambda"; + break; + case AST__SBRIGHT: + result = "mu_nu"; + break; + case AST__SBRIGHTW: + result = "mu_lambda"; + break; + default: + throw Ast.err( + AstException.AST__SCSIN, + "astGetSymbol(" + astClass() + "): Corrupt " + astClass() + + " contains invalid System identification code (" + system + ")."); + } + if (testUnit(axis)) { + Units.LabelledMapping lm = + Units.relabel(defUnit(system, "astGetSymbol", astClass()), getUnit(axis), result); + if (lm != null && lm.label != null) { + result = lm.label; + } + } + return result; + } + + /** + * Gets the Title (C's {@code GetTitle}): set, or the System's description followed, if the + * SpecVal is known, by {@code " at = "}, the SpecVal formatted by its SpecFrame, and that + * SpecFrame's Unit. + * + * @return the Title + */ + @Override + public String getTitle() { + if (testTitle()) { + return super.getTitle(); + } + StringBuilder sb = new StringBuilder(capitalised(systemValue())); + double specval = specValValue(); + SpecFrame sf = getSpecFrame(); + if (specval != AST__BAD) { + sb.append(" at = ").append(sf.format(1, specval)).append(' ').append(sf.getUnit(1)); + } + return sb.toString(); + } + + // ------------------------------------------------------------------ + // Conversion + // ------------------------------------------------------------------ + + /** + * The Mapping from flux values in this FluxFrame, the target, to those in {@code result} (C's + * {@code MakeFluxMapping}): from the target's Unit to the default units of its System, a + * ZoomMap by the rate of change of the result's density spectral system with the target's at + * the SpecVal, and from the default units of the result's System to its Unit, simplified. + * A surface brightness is converted only to a surface brightness, as a flux density per unit + * area. Between a per-frequency and a per-wavelength System the two SpecVals must give the + * same spectral position. + * + * @return the Mapping, or null if there is none + * @throws AstException with status {@code AST__BADUN} if either System follows from a Unit + * that suits no flux System + * @throws UnsupportedOperationException if a units conversion needs a MathMap + */ + Mapping makeFluxMapping(FluxFrame result) { + int rsysIn = systemValue(); + int rsysOut = result.systemValue(); + Mapping map1 = Units.unitMapper(getUnit(1), defUnit(rsysIn, "MakeFluxMapping", "FluxFrame")); + int sysIn; + boolean sbIn; + if (rsysIn == AST__SBRIGHT) { + sysIn = AST__FLUXDEN; + sbIn = true; + } else if (rsysIn == AST__SBRIGHTW) { + sysIn = AST__FLUXDENW; + sbIn = true; + } else { + sysIn = rsysIn; + sbIn = false; + } + int sysOut; + boolean sbOut; + if (rsysOut == AST__SBRIGHT) { + sysOut = AST__FLUXDEN; + sbOut = true; + } else if (rsysOut == AST__SBRIGHTW) { + sysOut = AST__FLUXDENW; + sbOut = true; + } else { + sysOut = rsysOut; + sbOut = false; + } + double zoom; + if (sbIn != sbOut) { + zoom = AST__BAD; + } else if (sysIn == sysOut) { + zoom = 1.0; + } else { + zoom = densityZoom(result, sysIn, sysOut); + } + Mapping map2 = zoom != AST__BAD ? new ZoomMap(1, Math.abs(zoom)) : null; + Mapping map3 = Units.unitMapper(defUnit(rsysOut, "MakeFluxMapping", "FluxFrame"), result.getUnit(1)); + if (map1 == null || map2 == null || map3 == null) { + return null; + } + Mapping map4 = new CmpMap(map1, map2, true); + Mapping map5 = new CmpMap(map4, map3, true); + return map5.simplify(); + } + + /** + * The rate of change of the density spectral system of {@code result}'s flux System {@code + * sysOut} with that of this FluxFrame's {@code sysIn}, at the SpecVal, or bad if the two + * SpecVals are not the same spectral position or either is bad (part of C's {@code + * MakeFluxMapping}). + */ + private double densityZoom(FluxFrame result, int sysIn, int sysOut) { + SpecFrame sfin1 = getSpecFrame(); + SpecFrame sfin2 = (SpecFrame) sfin1.copy(); + sfin2.setSystemValue(densitySystem(sysIn)); + sfin2.setUnit(1, densityUnit(sysIn)); + SpecFrame sfout1 = result.getSpecFrame(); + SpecFrame sfout2 = (SpecFrame) sfout1.copy(); + sfout2.setSystemValue(densitySystem(sysOut)); + sfout2.setUnit(1, densityUnit(sysOut)); + double zoom = AST__BAD; + FrameSet fs = sfout2.convert(sfin2, ""); + if (fs != null) { + Mapping smap = + fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT).simplify(); + fs = sfin1.convert(sfin2, ""); + Mapping smapIn = fs != null ? fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) : null; + fs = sfout1.convert(sfout2, ""); + Mapping smapOut = fs != null ? fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) : null; + if (smapIn == null || smapOut == null) { + // C passes the missing Mapping to astTran1, which reports the null pointer. + throw Ast.err( + AstException.AST__INTER, + "MakeFluxMapping(FluxFrame): No Mapping from the SpecFrame of a FluxFrame to its density" + + " system (internal programming error)."); + } + double specval2 = smapIn.tran1(1, new double[] {specValValue()}, true)[0]; + double specvalIn = smap.tran1(1, new double[] {specval2}, false)[0]; + double specvalOut = smapOut.tran1(1, new double[] {result.specValValue()}, true)[0]; + if (MappingHelpers.astEquals(specvalIn, specvalOut, 1.0E8) && specvalIn != AST__BAD) { + if (smap instanceof UnitMap) { + zoom = 1.0; + } else if (smap instanceof ZoomMap) { + zoom = ((ZoomMap) smap).getZoom(); + } else { + zoom = smap.rate(new double[] {0.5 * (specvalIn + specvalOut)}, 1, 1); + } + } + } + return zoom; + } + + // ------------------------------------------------------------------ + // Match, SubFrame and Overlay + // ------------------------------------------------------------------ + + /** + * Matches this FluxFrame, a template, against a target (C's {@code Match}, fluxframe.c): the + * target must pass the Frame tests and have an axis of a FluxFrame, the first of which is + * selected. + */ + @Override + FrameFinder.MatchResult match(Frame target, boolean matchSub) { + FrameFinder.MatchResult parent = super.match(target, matchSub); + if (parent == null) { + return null; + } + int targetNaxes = target.getNaxes(); + int[] pax = new int[1]; + int targetAxis0 = -1; + for (int iaxis = 0; iaxis < targetNaxes; iaxis++) { + if (target.primaryFrame(iaxis + 1, pax) instanceof FluxFrame) { + targetAxis0 = iaxis; + break; + } + } + if (targetAxis0 < 0) { + return null; + } + int[] templateAxes = parent.templateAxes; + int[] targetAxes = parent.targetAxes; + templateAxes[0] = 0; + targetAxes[0] = targetAxis0; + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + if (!target.subFrame(this, 1, targetAxes, templateAxes, map, result)) { + return null; + } + return new FrameFinder.MatchResult(templateAxes, targetAxes, map[0], result[0]); + } + + /** + * Selects axes from this FluxFrame (C's {@code SubFrame}, fluxframe.c). Selecting the one + * axis gives a FluxFrame, a copy with the template's attributes overlaid, and the Mapping + * converts between the two FluxFrames ({@link #makeFluxMapping}). Any other selection gives a + * plain Frame, made from a copy whose Domain, Title, Label, Symbol and Unit are set to their + * values and whose System and AlignSystem are cleared. + */ + // C works out an alignment System for MakeFluxMapping, which does not use it, so it is not + // found here. + @Override + boolean subFrame( + Frame template, int resultNaxes, int[] targetAxes, int[] templateAxes, Mapping[] map, Frame[] result) { + map[0] = null; + result[0] = null; + boolean match; + if (resultNaxes == 1 && targetAxes[0] == 0) { + FluxFrame res = (FluxFrame) copy(); + result[0] = res; + if (template != null) { + template.overlay(templateAxes, res); + } + Mapping m = makeFluxMapping(res); + match = m != null; + map[0] = m; + } else { + FluxFrame temp = (FluxFrame) copy(); + if (!temp.testDomain()) { + temp.setDomain(temp.getDomain()); + } + if (!temp.testTitle()) { + temp.setTitle(temp.getTitle()); + } + if (!temp.testLabel(1)) { + temp.setLabel(1, temp.getLabel(1)); + } + if (!temp.testSymbol(1)) { + temp.setSymbol(1, temp.getSymbol(1)); + } + if (!temp.testUnit(1)) { + temp.setUnit(1, temp.getUnit(1)); + } + temp.clearSystem(); + temp.clearAlignSystem(); + match = temp.frameSubFrame(template, resultNaxes, targetAxes, templateAxes, map, result); + } + if (!match) { + map[0] = null; + result[0] = null; + } + return match; + } + + /** The Frame class's {@code SubFrame}, for a copy of this FluxFrame. */ + private boolean frameSubFrame( + Frame template, int resultNaxes, int[] targetAxes, int[] templateAxes, Mapping[] map, Frame[] result) { + return super.subFrame(template, resultNaxes, targetAxes, templateAxes, map, result); + } + + /** + * Overlays the attributes set on this FluxFrame, the template, onto another Frame (C's {@code + * Overlay}, fluxframe.c). Onto a FluxFrame, a change of System set on the template first + * clears the result's Title, Label and Symbol, and its Unit if the two Systems' default units + * differ; the result takes the template's default SpecVal and a copy of its SpecFrame; then + * the Frame attributes are overlaid, and the SpecVal if set on the template. Onto another class + * of Frame, a System set on this template is cleared, with its AlignSystem, while the Frame + * attributes are overlaid, and then the System and the AlignSystem's value are set again: the + * template's AlignSystem is left set, and the change of System clears its Title, Label and + * Symbol and may change its Unit (a C quirk, followed here). + */ + @Override + void overlay(int[] templateAxes, Frame result) { + String method = "astOverlay"; + int oldSystem = result.systemValue(); + int newSystem = systemValue(); + int newAlignSystem = AST__BADSYSTEM; + boolean resetSystem = false; + boolean fluxframe = result instanceof FluxFrame; + if (fluxframe) { + if (newSystem != oldSystem && testSystem()) { + result.clearTitle(); + if (!defUnit(newSystem, method, astClass()).equals(defUnit(oldSystem, method, result.astClass()))) { + result.clearUnit(1); + } + result.clearLabel(1); + result.clearSymbol(1); + } + FluxFrame resff = (FluxFrame) result; + resff.defSpecVal = defSpecVal; + resff.specFrame = specFrame != null ? (SpecFrame) specFrame.copy() : null; + } else if (testSystem()) { + clearSystem(); + newAlignSystem = alignSystemValue(); + clearAlignSystem(); + resetSystem = true; + } + super.overlay(templateAxes, result); + if (resetSystem) { + setSystemValue(newSystem); + setAlignSystemValue(newAlignSystem); + } + if (fluxframe && testSpecVal()) { + ((FluxFrame) result).setSpecValValue(specValValue()); + } + } + + // ------------------------------------------------------------------ + // String-based attribute access + // ------------------------------------------------------------------ + + @Override + String getAttrib(String attrib) { + if ("specval".equals(attrib)) { + double dval = specValValue(); + return dval != AST__BAD ? CFormat.format("%." + DBL_DIG + "g", dval) : ""; + } + return super.getAttrib(attrib); + } + + @Override + void setAttrib(String attrib, String value) { + Double dval = CScan.scanDouble(value); + if ("specval".equals(attrib) && dval != null) { + setSpecValValue(dval); + } else { + super.setAttrib(attrib, value); + } + } + + @Override + boolean testAttrib(String attrib) { + if ("specval".equals(attrib)) { + return testSpecVal(); + } + return super.testAttrib(attrib); + } + + @Override + void clearAttrib(String attrib) { + if ("specval".equals(attrib)) { + clearSpecVal(); + } else { + super.clearAttrib(attrib); + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/Frame.java b/src/main/java/uk/ac/starlink/ast/Frame.java index fae54a7..55d46db 100644 --- a/src/main/java/uk/ac/starlink/ast/Frame.java +++ b/src/main/java/uk/ac/starlink/ast/Frame.java @@ -817,9 +817,11 @@ Frame cast(Frame obj) { /** * A deep copy of this Frame as an instance of the class of {@code obj}, one of its ancestors, * with the attributes that class does not allow cleared (C's {@code astCastCopy} followed by - * {@code astCleanAttribs}). The ancestors of the Frame classes that are not FrameSets are - * Frame itself; the copy then has this Frame's Object, Mapping and Frame attributes, except - * the ID, as C's copy has, and copies of its Axis objects and variants. + * {@code astCleanAttribs}). Here {@code obj} is a plain Frame, the ancestor of every Frame + * class that is not a FrameSet; the copy then has this Frame's Object, Mapping and Frame + * attributes, except the ID, as C's copy has, and copies of its Axis objects and variants. + * A class with another Frame class as an ancestor overrides this for that ancestor, and + * {@link CmpFrame} for every class of its family, as cmpframe.c's {@code Cast} does. * * @throws AstException with status {@code AST__INTER} if {@code obj} is not a plain Frame */ @@ -3145,16 +3147,6 @@ static String oneWord(String value) { return i == value.length() ? value.substring(start) : null; } - /** Whether a value holds a character that is not white space, as C's {@code "%*s"} needs. */ - private static boolean hasWord(String value) { - for (int i = 0; i < value.length(); i++) { - if (!CScan.isCSpace(value.charAt(i))) { - return true; - } - } - return false; - } - /** C's {@code SetAttrib} (frame.c); {@code original} as for {@link #getAttrib(String, String)}. */ private void setAttrib(String attrib, String value, String original) { Integer ival = CScan.scanInt(value); @@ -3224,9 +3216,9 @@ private void setAttrib(String attrib, String value, String original) { setTitle(value); } else if ("unit".equals(ix)) { setUnit(axis, value); - } else if ("obslat".equals(attrib) && hasWord(value)) { + } else if ("obslat".equals(attrib) && CScan.hasWord(value)) { setObsLatValue(readObsAngle(value, 'N', 'S', "ObsLat", "observers latitude")); - } else if ("obslon".equals(attrib) && hasWord(value)) { + } else if ("obslon".equals(attrib) && CScan.hasWord(value)) { setObsLonValue(readObsAngle(value, 'E', 'W', "ObsLon", "observers longitude")); } else if ("obsalt".equals(attrib) && dval != null) { setObsAlt(dval); diff --git a/src/main/java/uk/ac/starlink/ast/ObjectRegistry.java b/src/main/java/uk/ac/starlink/ast/ObjectRegistry.java index 5f05827..4e9f85a 100644 --- a/src/main/java/uk/ac/starlink/ast/ObjectRegistry.java +++ b/src/main/java/uk/ac/starlink/ast/ObjectRegistry.java @@ -34,8 +34,12 @@ static Loader loader(String className) { return CmpFrame::new; case "CmpMap": return CmpMap::new; + case "DSBSpecFrame": + return DSBSpecFrame::new; case "FitsChan": return FitsChan::new; + case "FluxFrame": + return FluxFrame::new; case "Frame": return Frame::new; case "FrameSet": @@ -56,6 +60,12 @@ static Loader loader(String className) { return SkyFrame::new; case "SlaMap": return SlaMap::new; + case "SpecFluxFrame": + return SpecFluxFrame::new; + case "SpecFrame": + return SpecFrame::new; + case "SpecMap": + return SpecMap::new; case "SphMap": return SphMap::new; case "TimeFrame": diff --git a/src/main/java/uk/ac/starlink/ast/SpecFluxFrame.java b/src/main/java/uk/ac/starlink/ast/SpecFluxFrame.java new file mode 100644 index 0000000..c18e46c --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/SpecFluxFrame.java @@ -0,0 +1,347 @@ +package uk.ac.starlink.ast; + +/** + * A compound spectrum/flux Frame. A SpecFluxFrame combines a SpecFrame and a FluxFrame into a + * single two-dimensional compound Frame. Such a Frame can, for instance, describe a plot of a + * spectrum in which the first axis represents spectral position and the second axis represents + * flux. + * + *

    A SpecFluxFrame is a CmpFrame of the two, and behaves as one, except that its default Title + * is the FluxFrame's Label, then {@code versus} and the SpecFrame's Label (as {@code Flux density + * versus Frequency}), and that when it is aligned with another SpecFluxFrame the flux values are + * converted as the spectral positions they are densities in change, as well as with the flux + * System and Unit. Where C converts between SpecFluxFrames whose SpecFrames or FluxFrames differ + * it builds Mappings this library does not have (a RateMap, a MathMap and a TranMap), and such a + * conversion throws {@link UnsupportedOperationException}. So does a conversion between a + * SpecFluxFrame and a FluxFrame or SpecFrame that do not match directly (a FluxFrame in another + * flux System, say): C then casts the CmpFrame its match gives into a SpecFluxFrame and converts + * between SpecFluxFrames. SpecFluxFrames with equal components, and those C finds no conversion + * between, behave as in C. + * + *

    Ported from C {@code specfluxframe.c}, with Rust {@code frames/specfluxframe.rs}. + */ +public class SpecFluxFrame extends CmpFrame { + + /** + * Creates a SpecFluxFrame. The SpecFrame and FluxFrame are held, not copied, as by {@link + * CmpFrame#CmpFrame}: later changes to them change the SpecFluxFrame. + * + * @param frame1 SpecFrame which will form the first axis in the new SpecFluxFrame + * @param frame2 FluxFrame which will form the second axis in the new SpecFluxFrame + */ + public SpecFluxFrame(SpecFrame frame1, FluxFrame frame2) { + super(frame1, frame2); + } + + /** + * Creates a SpecFluxFrame of any two Frames, marking them shared if {@code share}, for {@link + * CmpFrame#castCopy}: C's {@code astCastCopy} of a CmpFrame into a SpecFluxFrame keeps the + * CmpFrame's components whatever their classes. Such a SpecFluxFrame is used only as the + * template of a match against a SpecFluxFrame, which reads its axes and attributes, not its + * SpecFrame and FluxFrame. + */ + SpecFluxFrame(Frame frame1, Frame frame2, boolean share) { + super(frame1, frame2, share); + } + + /** + * Loads a SpecFluxFrame from its description, as C's {@code astLoadSpecFluxFrame} does: as the + * CmpFrame it is, with no values of its own. + * + * @param node the description + * @throws AstException with status {@code AST__LDERR} if the first component is not a SpecFrame + * or the second not a FluxFrame + */ + SpecFluxFrame(NativeNode node) { + super(node); + node.section("SpecFluxFrame"); + checkLoadedComponents(this); + } + + /** + * Checks that a loaded SpecFluxFrame holds a SpecFrame and a FluxFrame. C keeps components of + * any class; here they must be the classes this class reads them as. + * + * @throws AstException with status {@code AST__LDERR} if they are not + */ + private static void checkLoadedComponents(SpecFluxFrame sff) { + Frame frame1 = sff.firstFrame(); + Frame frame2 = sff.secondFrame(); + if (!(frame1 instanceof SpecFrame) || !(frame2 instanceof FluxFrame)) { + throw Ast.err( + AstException.AST__LDERR, + "astLoadSpecFluxFrame(SpecFluxFrame): The components of a SpecFluxFrame are a " + + frame1.astClass() + " and a " + frame2.astClass() + + ", not a SpecFrame and a FluxFrame."); + } + } + + @Override + String dumpComment() { + return "Compound spectral/flux coordinate system description"; + } + + /** + * Writes the description as the CmpFrame it is, followed by the SpecFluxFrame class's empty + * part (specfluxframe.c {@code Dump} writes nothing). + */ + @Override + void dump(NativeNode node) { + super.dump(node); + node.writeIsA("CmpFrame", "Compound coordinate system description"); + } + + // ------------------------------------------------------------------ + // Components + // ------------------------------------------------------------------ + + /** + * The FluxFrame (C's {@code GetFluxFrame}): the SpecFluxFrame's own, or, if {@code std}, a + * copy with its System set explicitly and its Unit cleared, so that it uses the default units + * of its System. + */ + private FluxFrame getFluxFrame(boolean std) { + FluxFrame ff = (FluxFrame) secondFrame(); + if (!std) { + return ff; + } + FluxFrame ret = (FluxFrame) ff.copy(); + ret.setSystemValue(ff.systemValue()); + ret.clearUnit(1); + return ret; + } + + /** + * The SpecFrame (C's {@code GetSpecFrame}): the SpecFluxFrame's own, or, if {@code std}, a copy + * with its System and Unit set to the spectral system and units the FluxFrame's values are a + * density in (frequency in Hz or wavelength in Angstrom). + */ + private SpecFrame getSpecFrame(boolean std) { + SpecFrame sf = (SpecFrame) firstFrame(); + if (!std) { + return sf; + } + FluxFrame ff = (FluxFrame) secondFrame(); + SpecFrame ret = (SpecFrame) sf.copy(); + ret.setSystemValue(ff.getDensitySystem()); + ret.setUnit(1, ff.getDensityUnit()); + return ret; + } + + // ------------------------------------------------------------------ + // Attributes + // ------------------------------------------------------------------ + + /** + * Gets the Title: the one set, or by default the FluxFrame's Label, its first letter in upper + * case, followed by {@code versus} and the SpecFrame's Label (C's {@code GetTitle}). + * + * @return the Title + */ + // C formats the default into a 101-character buffer, which long Labels overflow; here the + // whole Title is returned. + @Override + public String getTitle() { + if (testTitle()) { + return super.getTitle(); + } + // C reads the Labels of the components as Frames, whatever their classes. + String title = secondFrame().getLabel(1) + " versus " + firstFrame().getLabel(1); + return CScan.toUpper(title.charAt(0)) + title.substring(1); + } + + // ------------------------------------------------------------------ + // Match and SubFrame + // ------------------------------------------------------------------ + + /** + * Matches this SpecFluxFrame, a template, against a target (C's {@code Match}, + * specfluxframe.c). A target that is not a SpecFluxFrame is matched as by a CmpFrame. Against + * a SpecFluxFrame, the result has two axes, associated with the target's axes in the order + * that puts the spectral and flux axes where the template has them (or, with PreserveAxes + * set, in the target's order), which needs Permute set if the two have them in different + * orders; the target's {@link #subFrame} then makes the result and the conversion. + */ + @Override + FrameFinder.MatchResult match(Frame target, boolean matchSub) { + if (!(target instanceof SpecFluxFrame)) { + return super.match(target, matchSub); + } + boolean swap1 = validateAxis(1, true, "astMatch") != 1; + boolean swap2 = target.validateAxis(1, true, "astMatch") != 1; + boolean swap = swap1 != swap2; + if (swap && !getPermute()) { + return null; + } + int[] templateAxes; + int[] targetAxes; + if (getPreserveAxes()) { + templateAxes = new int[] {swap ? 1 : 0, swap ? 0 : 1}; + targetAxes = new int[] {0, 1}; + } else { + templateAxes = new int[] {0, 1}; + targetAxes = new int[] {swap ? 1 : 0, swap ? 0 : 1}; + } + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + if (!target.subFrame(this, 2, targetAxes, templateAxes, map, result)) { + return null; + } + return new FrameFinder.MatchResult(templateAxes, targetAxes, map[0], result[0]); + } + + /** + * Selects axes from this SpecFluxFrame, the target (C's {@code SubFrame}, specfluxframe.c). + * With a SpecFluxFrame template and two axes selected, the result is a copy with its axes in + * the order selected and the template's attributes overlaid, and the Mapping converts between + * the two ({@link #makeSFMapping}), with PermMaps swapping the coordinates of either Frame + * whose flux axis comes first. Any other selection is made as by a CmpFrame. + */ + @Override + boolean subFrame( + Frame template, int resultNaxes, int[] targetAxes, int[] templateAxes, Mapping[] map, Frame[] result) { + if (!(template instanceof SpecFluxFrame) || resultNaxes != 2) { + return super.subFrame(template, resultNaxes, targetAxes, templateAxes, map, result); + } + map[0] = null; + result[0] = null; + SpecFluxFrame res = (SpecFluxFrame) copy(); + res.permAxes0(new int[] {targetAxes[0], targetAxes[1]}); + template.overlay(templateAxes, res); + Mapping m = makeSFMapping(this, res); + if (m == null) { + return false; + } + boolean targetSwap = validateAxis(1, true, "astSubFrame") != 1; + boolean resultSwap = targetSwap != (targetAxes[0] != 0); + PermMap permmap = null; + if (targetSwap || resultSwap) { + int[] perm = {1, 0}; + permmap = PermMap.fromInternal(2, perm, 2, perm, null); + } + if (targetSwap) { + m = new CmpMap(permmap, m, true); + } + if (resultSwap) { + m = new CmpMap(m, permmap, true); + } + map[0] = m; + result[0] = res; + return true; + } + + // ------------------------------------------------------------------ + // Conversion between SpecFluxFrames + // ------------------------------------------------------------------ + + /** + * The Mapping from {@code target} to {@code result}, ignoring their axis permutations, or null + * if there is none (C's {@code MakeSFMapping}). If their SpecFrames are equal and their + * FluxFrames are equal it is a UnitMap. Otherwise C makes a chain of Mappings whose middle + * part, the conversion between the standardised Frames ({@link #makeMap3}), is a TranMap + * holding a RateMap and MathMaps; it is made only if the target's values convert to the + * standardised Frames ({@link #makeMap2}). + * + * @throws UnsupportedOperationException if the SpecFrames or FluxFrames are not equal and C + * would make that TranMap, or if comparing them needs a Mapping this library does not + * have + */ + private static Mapping makeSFMapping(SpecFluxFrame target, SpecFluxFrame result) { + boolean same = astEqual(target.getSpecFrame(false), result.getSpecFrame(false)) + && astEqual(target.getFluxFrame(false), result.getFluxFrame(false)); + if (same) { + return new UnitMap(2); + } + if (target.makeMap2() != null) { + makeMap3(target, result); + } + // makeMap3 throws where C would make its TranMap; otherwise C makes no conversion either. + return null; + } + + /** + * Whether two Frames are equal, as C's {@code astEqual} finds (object.c {@code astEqual_} and + * frame.c {@code Equal}): they are the same Frame, or of the same class with a conversion from + * {@code that} to {@code frame} that simplifies to a UnitMap. + */ + @SuppressWarnings({"ReferenceEquality", "PMD.CompareObjectsWithEquals"}) // C compares the pointers. + private static boolean astEqual(Frame frame, Frame that) { + if (frame == that) { + return true; + } + if (!frame.astClass().equals(that.astClass())) { + return false; + } + FrameSet fs = that.convert(frame, ""); + return fs != null + && fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT).simplify() instanceof UnitMap; + } + + /** + * The conversion of this SpecFluxFrame's flux value and spectral value to the standardised + * FluxFrame and SpecFrame ({@link #getFluxFrame} and {@link #getSpecFrame}), with a third, + * unchanged, value, as three Mappings in parallel, or null if either Frame does not convert + * (C's {@code MakeMap2}). + */ + private Mapping makeMap2() { + FrameSet fs = getFluxFrame(false).convert(getFluxFrame(true), ""); + if (fs == null) { + return null; + } + Mapping ax1Map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + fs = getSpecFrame(false).convert(getSpecFrame(true), ""); + if (fs == null) { + return null; + } + Mapping ax2Map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + Mapping tmap = CmpMap.transientCmpMap(ax1Map, ax2Map, false); + return CmpMap.transientCmpMap(tmap, new UnitMap(1), false); + } + + /** + * The conversion of flux and spectral values between the standardised Frames of {@code target} + * and {@code result}, as far as this library can follow C's {@code MakeMap3}. C makes a TranMap + * of the Mappings {@link #makeMapF} and {@link #makeMapI} give, each of which throws where C + * would build its RateMap, and looks for the conversion between the SpecFrames themselves; if + * neither standardised SpecFrame converts to the other, C makes no Mapping. + * + * @throws UnsupportedOperationException if the standardised SpecFrames convert + */ + private static void makeMap3(SpecFluxFrame target, SpecFluxFrame result) { + // C makes the standardised FluxFrames as well, though MakeMapF and MakeMapI do not use them. + target.getFluxFrame(true); + SpecFrame sf1 = target.getSpecFrame(true); + result.getFluxFrame(true); + SpecFrame sf2 = result.getSpecFrame(true); + makeMapF(sf1, sf2); + makeMapI(sf1, sf2); + target.getSpecFrame(false).convert(result.getSpecFrame(false), ""); + } + + /** + * The forward part of C's flux conversion ({@code MakeMapF}): if the standardised SpecFrame + * {@code x1} converts to {@code x2}, C builds a RateMap of that conversion to scale the flux, + * and a MathMap dividing by it, which this library does not have. + * + * @throws UnsupportedOperationException if {@code x1} converts to {@code x2} + */ + private static void makeMapF(SpecFrame x1, SpecFrame x2) { + if (x1.convert(x2, "") != null) { + throw new UnsupportedOperationException( + "MakeMapF(SpecFluxFrame): the conversion of flux values between SpecFluxFrames needs RateMap"); + } + } + + /** + * The inverse part of C's flux conversion ({@code MakeMapI}): as {@link #makeMapF}, with a + * MathMap multiplying by the rate. + * + * @throws UnsupportedOperationException if {@code x1} converts to {@code x2} + */ + private static void makeMapI(SpecFrame x1, SpecFrame x2) { + if (x1.convert(x2, "") != null) { + throw new UnsupportedOperationException( + "MakeMapI(SpecFluxFrame): the conversion of flux values between SpecFluxFrames needs RateMap"); + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/SpecFrame.java b/src/main/java/uk/ac/starlink/ast/SpecFrame.java new file mode 100644 index 0000000..9b6a71e --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/SpecFrame.java @@ -0,0 +1,2400 @@ +package uk.ac.starlink.ast; + +/** + * A spectral coordinate system. A SpecFrame is a one-dimensional Frame describing positions in an + * electro-magnetic spectrum, in the coordinate system its System attribute names: frequency + * ({@code FREQ}), energy ({@code ENER}), wave-number ({@code WAVN}), wavelength ({@code WAVE}, the + * default), wavelength in air ({@code AWAV}), radio velocity ({@code VRAD}), optical velocity + * ({@code VOPT}), redshift ({@code ZOPT}), the beta factor ({@code BETA}) or apparent radial + * velocity ({@code VELO}). The velocities and redshift are relative to the rest frequency given by + * the RestFreq attribute; the default units of each System (GHz, J, 1/m, Angstrom, km/s, or none + * for redshift and beta) may be changed through the Unit attribute, and the Unit last used with + * each System comes back when the System does. + * + *

    The StdOfRest attribute gives the standard of rest of the values, qualified as it needs by + * the Epoch, the observer's position (ObsLon, ObsLat, ObsAlt), the source position (RefRA, RefDec) + * and, for the source's rest frame, its velocity (SourceVel, given in the spectral system + * SourceSys and the rest frame SourceVRF). Two SpecFrames are aligned in the System and standard + * of rest given by their AlignSystem and AlignStdOfRest attributes. A SpecOrigin may be set, + * making the axis values offsets from that spectral position; with AlignSpecOffset set, two + * SpecFrames are aligned in their offset values. + * + *

    The per-axis attributes Direction, Bottom, Top, Format, Label, Symbol and Unit may be named + * without an axis number. A SpecFrame always uses the Unit of its axis when it is aligned with + * another (its ActiveUnit flag is always true). The attributes GeoLat and GeoLon are the ObsLat + * and ObsLon under the names an older version of the SpecFrame used. + * + *

    Ported from C {@code specframe.c}, with Rust {@code frames/specframe.rs}. + */ +public class SpecFrame extends Frame { + + /** The frequency System. */ + static final int AST__FREQ = 1; + + /** The energy System. */ + static final int AST__ENERGY = 2; + + /** The wave-number System. */ + static final int AST__WAVENUM = 3; + + /** The wavelength System. */ + static final int AST__WAVELEN = 4; + + /** The wavelength in air System. */ + static final int AST__AIRWAVE = 5; + + /** The radio velocity System. */ + static final int AST__VRADIO = 6; + + /** The optical velocity System. */ + static final int AST__VOPTICAL = 7; + + /** The redshift System. */ + static final int AST__REDSHIFT = 8; + + /** The beta factor System. */ + static final int AST__BETA = 9; + + /** The apparent radial velocity System. */ + static final int AST__VREL = 10; + + /** The standard of rest of an unset attribute. */ + static final int AST__BADSOR = 0; + + /** The topocentric standard of rest. */ + static final int AST__TPSOR = 1; + + /** The geocentric standard of rest. */ + static final int AST__GESOR = 2; + + /** The barycentric standard of rest. */ + static final int AST__BYSOR = 3; + + /** The heliocentric standard of rest. */ + static final int AST__HLSOR = 4; + + /** The dynamical local standard of rest. */ + static final int AST__LDSOR = 5; + + /** The kinematical local standard of rest. */ + static final int AST__LKSOR = 6; + + /** The Local Group standard of rest. */ + static final int AST__LGSOR = 7; + + /** The Galactic standard of rest. */ + static final int AST__GLSOR = 8; + + /** The rest frame of the source. */ + static final int AST__SCSOR = 9; + + private static final int FIRST_SYSTEM = AST__FREQ; + private static final int LAST_SYSTEM = AST__VREL; + private static final int FIRST_SOR = AST__TPSOR; + private static final int LAST_SOR = AST__SCSOR; + + /** The value of an unset integer attribute (C's {@code -INT_MAX}). */ + private static final int UNSET = -Integer.MAX_VALUE; + + /** The digits C writes a full-precision double with ({@code AST__DBL_DIG}). */ + private static final int DBL_DIG = 17; + + /** The names of the per-axis Frame attributes that may be given without an axis number. */ + private static final String[] ONE_AXIS_NAMES = {"direction", "bottom", "top", "format", "label", "symbol", "unit"}; + + /** The AlignStdOfRest code, or {@link #AST__BADSOR} if unset. */ + private int alignStdOfRest = AST__BADSOR; + + /** The RefDec in radians (FK5 J2000), or bad if unset. */ + private double refDecRadians = AST__BAD; + + /** The RefRA in radians (FK5 J2000), or bad if unset. */ + private double refRaRadians = AST__BAD; + + /** The RestFreq in Hz, or bad if unset. */ + private double restFreq = AST__BAD; + + /** The SourceVel, in m/s for a velocity and dimensionless otherwise, or bad if unset. */ + private double sourceVel = AST__BAD; + + /** The SourceVRF code, or {@link #AST__BADSOR} if unset. */ + private int sourceVrfCode = AST__BADSOR; + + /** The SourceSys code, or {@link Frame#AST__BADSYSTEM} if unset. */ + private int sourceSys = AST__BADSYSTEM; + + /** The StdOfRest code, or {@link #AST__BADSOR} if unset. */ + private int stdOfRest = AST__BADSOR; + + /** The Unit last set with each System, indexed by System code, or null (C's {@code usedunits}). */ + private String[] usedUnits = new String[LAST_SYSTEM + 1]; + + /** The SpecOrigin in the default units of the System, or bad if unset. */ + private double specOrigin = AST__BAD; + + /** The AlignSpecOffset flag, 0 or 1, or {@link #UNSET}. */ + private int alignSpecOffset = UNSET; + + /** + * Creates a SpecFrame with every attribute at its default: wavelength in Angstrom, in the + * heliocentric standard of rest. + */ + public SpecFrame() { + super(1); + } + + /** + * Loads a SpecFrame from its description, as C's {@code astLoadSpecFrame} does: SoR, AlSoR, + * RefRA, RefDec, RstFrq, AlSpOf, SrcVel, SrcVRF, SrcSys, the Unit used with each System + * ({@code U}) and SpOrg, each unset if absent, and the GeoLat and GeoLon an old version + * wrote, used as the ObsLat and ObsLon if those are not set. + * + * @param node the description + * @throws AstException with status {@code AST__ATTIN} if a standard of rest or spectral system + * is not a known one + */ + // C's loader passes the observer's position through the Frame class's setters. + @SuppressWarnings("PMD.ConstructorCallsOverridableMethod") + SpecFrame(NativeNode node) { + super(node); + NativeNode part = node.section("SpecFrame"); + String sval = part.getStringIfSet("SoR"); + if (sval != null) { + stdOfRest = stdOfRestCode(sval); + if (stdOfRest == AST__BADSOR) { + throw Ast.err( + AstException.AST__ATTIN, + "astRead(Channel): Invalid standard of rest description \"" + sval + "\"."); + } + } + sval = part.getStringIfSet("AlSoR"); + if (sval != null) { + alignStdOfRest = stdOfRestCode(sval); + if (alignStdOfRest == AST__BADSOR) { + throw Ast.err( + AstException.AST__ATTIN, + "astRead(Channel): Invalid alignment standard of rest description \"" + sval + "\"."); + } + } + if (!testObsLat()) { + double obslat = part.readDouble("GeoLat", AST__BAD); + if (obslat != AST__BAD) { + setObsLatValue(obslat); + } + } + if (!testObsLon()) { + double obslon = part.readDouble("GeoLon", AST__BAD); + if (obslon != AST__BAD) { + setObsLonValue(obslon); + } + } + refRaRadians = part.readDouble("RefRA", AST__BAD); + refDecRadians = part.readDouble("RefDec", AST__BAD); + restFreq = part.readDouble("RstFrq", AST__BAD); + int ival = part.readInt("AlSpOf", UNSET); + if (ival != UNSET) { + alignSpecOffset = ival != 0 ? 1 : 0; + } + sourceVel = part.readDouble("SrcVel", AST__BAD); + sval = part.getStringIfSet("SrcVRF"); + if (sval != null) { + sourceVrfCode = stdOfRestCode(sval); + if (sourceVrfCode == AST__BADSOR) { + throw Ast.err( + AstException.AST__ATTIN, + "astRead(Channel): Invalid source velocity rest frame description \"" + sval + "\"."); + } + } + sval = part.getStringIfSet("SrcSys"); + if (sval != null) { + sourceSys = systemCode(sval); + if (sourceSys == AST__BADSYSTEM) { + throw Ast.err( + AstException.AST__ATTIN, + "astRead(Channel): Invalid source velocity spectral system description \"" + sval + "\"."); + } + } + for (int sys = FIRST_SYSTEM; sys <= LAST_SYSTEM; sys++) { + String unit = part.getStringIfSet(usedUnitKey(sys)); + if (unit != null) { + usedUnits[sys] = unit; + } + } + specOrigin = part.readDouble("SpOrg", AST__BAD); + } + + @Override + String dumpComment() { + return "Description of spectral coordinate system"; + } + + /** The key of the dump item holding the Unit used with a System: {@code U} and its name, as {@code UFreq}. */ + private String usedUnitKey(int sys) { + String name = systemString(sys); + StringBuilder sb = new StringBuilder("U").append(name); + for (int j = 2; j < sb.length(); j++) { + sb.setCharAt(j, CScan.toLower(sb.charAt(j))); + } + return sb.toString(); + } + + /** Writes the SpecFrame class's part of a description, as C's {@code Dump} (specframe.c) does. */ + @Override + void dump(NativeNode node) { + super.dump(node); + node.writeIsA("Frame", "Coordinate system description"); + boolean set = testStdOfRest(); + String sval = set ? corruptChecked(stdOfRest, "standard of rest identification code") : getAttrib("stdofrest"); + node.writeString("SoR", set, true, sval, "Standard of rest"); + set = testAlignStdOfRest(); + sval = set + ? corruptChecked(alignStdOfRest, "alignment standard of rest identification code") + : getAttrib("alignstdofrest"); + node.writeString("AlSoR", set, false, sval, "Alignment standard of rest"); + node.writeDouble("RefRA", testRefRA(), false, refRaValue(), "Reference RA (rads, FK5 J2000)"); + node.writeDouble("RefDec", testRefDec(), false, refDecValue(), "Reference Dec (rads, FK5 J2000)"); + node.writeDouble("RstFrq", testRestFreq(), false, restFreqValue(), "Rest frequency (Hz)"); + node.writeDouble("SrcVel", testSourceVel(), false, sourceVelValue(), "Source velocity (m/s)"); + set = testSourceVRF(); + sval = set + ? corruptChecked(sourceVrfCode, "source velocity rest frame identification code") + : getAttrib("sourcevrf"); + node.writeString("SrcVRF", set, false, sval, "Source velocity rest frame"); + set = testSourceSys(); + if (set) { + sval = systemString(sourceSys); + if (sval == null) { + throw Ast.err( + AstException.AST__SCSIN, + "astWrite(Channel): Corrupt " + astClass() + + " contains invalid source velocity spectral system identification code (" + + sourceSys + ")."); + } + } else { + sval = getAttrib("sourcesys"); + } + node.writeString("SrcSys", set, false, sval, "Source velocity spectral system"); + int ival = alignSpecOffsetValue() ? 1 : 0; + node.writeInt( + "AlSpOf", + testAlignSpecOffset(), + false, + ival, + ival != 0 ? "Align in offset coords" : "Align in system coords"); + for (int i = 0; i < usedUnits.length; i++) { + if (usedUnits[i] != null) { + node.writeString(usedUnitKey(i), true, false, usedUnits[i], "Preferred units for " + systemLabel(i)); + } + } + double dval = specOriginValue(); + if (dval != AST__BAD) { + node.writeDouble("SpOrg", testSpecOrigin(), false, dval, "Spec offset"); + } + } + + /** The name of a standard of rest code a dump writes, or the error C reports for a corrupt one. */ + private String corruptChecked(int sor, String what) { + String s = stdOfRestString(sor); + if (s == null) { + throw Ast.err( + AstException.AST__SCSIN, + "astWrite(Channel): Corrupt " + astClass() + " contains invalid " + what + " (" + sor + ")."); + } + return s; + } + + /** Copies the record of the Unit used with each System, as C's {@code Copy} (specframe.c) does. */ + @Override + void deepCopy() { + super.deepCopy(); + usedUnits = usedUnits.clone(); + } + + /** + * A deep copy of this SpecFrame, of a subclass, as an instance of the class of {@code obj} (C's + * {@code astCastCopy} followed by {@code astCleanAttribs}): a SpecFrame with this Frame's + * Object, Mapping, Frame and SpecFrame attributes, or a plain Frame as {@link Frame#castCopy} + * gives it. + */ + @Override + Frame castCopy(Frame obj) { + if (obj.getClass() != SpecFrame.class) { + return super.castCopy(obj); + } + SpecFrame spec = new SpecFrame(); + spec.castCopyFrom(this); + spec.cleanAttribs(); + return spec; + } + + /** Takes the Object, Mapping, Frame and SpecFrame parts of {@code src}, as C's copy of a SpecFrame does. */ + @Override + void castCopyFrom(AstObject src) { + super.castCopyFrom(src); + SpecFrame f = (SpecFrame) src; + alignStdOfRest = f.alignStdOfRest; + refDecRadians = f.refDecRadians; + refRaRadians = f.refRaRadians; + restFreq = f.restFreq; + sourceVel = f.sourceVel; + sourceVrfCode = f.sourceVrfCode; + sourceSys = f.sourceSys; + stdOfRest = f.stdOfRest; + usedUnits = f.usedUnits.clone(); + specOrigin = f.specOrigin; + alignSpecOffset = f.alignSpecOffset; + } + + // ------------------------------------------------------------------ + // Systems and standards of rest + // ------------------------------------------------------------------ + + /** + * Whether a System's values do not depend on the rest frequency (C's {@code ABS_SYSTEM}): + * frequency, energy, wave-number and the wavelengths. + */ + static boolean absSystem(int sys) { + return sys == AST__ENERGY + || sys == AST__WAVENUM + || sys == AST__WAVELEN + || sys == AST__AIRWAVE + || sys == AST__FREQ; + } + + /** + * The standard of rest code a name gives, ignoring case and trailing white space, or {@link + * #AST__BADSOR} (C's {@code StdOfRestCode}). + */ + static int stdOfRestCode(String sor) { + if (chrMatch("TOPO", sor) || chrMatch("TOPOCENT", sor) || chrMatch("TOPOCENTRIC", sor)) { + return AST__TPSOR; + } else if (chrMatch("GEO", sor) || chrMatch("GEOCENTR", sor) || chrMatch("GEOCENTRIC", sor)) { + return AST__GESOR; + } else if (chrMatch("BARY", sor) || chrMatch("BARYCENT", sor) || chrMatch("BARYCENTRIC", sor)) { + return AST__BYSOR; + } else if (chrMatch("HELIO", sor) || chrMatch("HELIOCEN", sor) || chrMatch("HELIOCENTRIC", sor)) { + return AST__HLSOR; + } else if (chrMatch("LSRK", sor) || chrMatch("LSR", sor)) { + return AST__LKSOR; + } else if (chrMatch("LSRD", sor)) { + return AST__LDSOR; + } else if (chrMatch("GAL", sor) || chrMatch("GALACTOC", sor) || chrMatch("GALACTIC", sor)) { + return AST__GLSOR; + } else if (chrMatch("LG", sor) + || chrMatch("LOCALGRP", sor) + || chrMatch("LOCAL_GROUP", sor) + || chrMatch("LOCAL-GROUP", sor)) { + return AST__LGSOR; + } else if (chrMatch("SOURCE", sor) || chrMatch("SRC", sor)) { + return AST__SCSOR; + } + return AST__BADSOR; + } + + /** The name of a standard of rest code, or null (C's {@code StdOfRestString}). */ + static String stdOfRestString(int sor) { + switch (sor) { + case AST__TPSOR: + return "Topocentric"; + case AST__GESOR: + return "Geocentric"; + case AST__BYSOR: + return "Barycentric"; + case AST__HLSOR: + return "Heliocentric"; + case AST__LDSOR: + return "LSRD"; + case AST__LKSOR: + return "LSRK"; + case AST__LGSOR: + return "Local_group"; + case AST__GLSOR: + return "Galactic"; + case AST__SCSOR: + return "Source"; + default: + return null; + } + } + + /** The System code a name gives, ignoring case and trailing white space (C's {@code SystemCode}). */ + @Override + int systemCode(String name) { + if (chrMatch("FREQ", name)) { + return AST__FREQ; + } else if (chrMatch("ENER", name) || chrMatch("ENERGY", name)) { + return AST__ENERGY; + } else if (chrMatch("WAVN", name) || chrMatch("WAVENUM", name)) { + return AST__WAVENUM; + } else if (chrMatch("WAVE", name) || chrMatch("WAVELEN", name)) { + return AST__WAVELEN; + } else if (chrMatch("AWAV", name) || chrMatch("AIRWAVE", name)) { + return AST__AIRWAVE; + } else if (chrMatch("VRAD", name) || chrMatch("VRADIO", name)) { + return AST__VRADIO; + } else if (chrMatch("VOPT", name) || chrMatch("VOPTICAL", name)) { + return AST__VOPTICAL; + } else if (chrMatch("ZOPT", name) || chrMatch("REDSHIFT", name)) { + return AST__REDSHIFT; + } else if (chrMatch("BETA", name)) { + return AST__BETA; + } else if (chrMatch("VELO", name) || chrMatch("VREL", name)) { + return AST__VREL; + } + return AST__BADSYSTEM; + } + + /** The name of a System code, or null (C's {@code SystemString}). */ + @Override + String systemString(int code) { + switch (code) { + case AST__FREQ: + return "FREQ"; + case AST__ENERGY: + return "ENER"; + case AST__WAVENUM: + return "WAVN"; + case AST__WAVELEN: + return "WAVE"; + case AST__AIRWAVE: + return "AWAV"; + case AST__VRADIO: + return "VRAD"; + case AST__VOPTICAL: + return "VOPT"; + case AST__REDSHIFT: + return "ZOPT"; + case AST__BETA: + return "BETA"; + case AST__VREL: + return "VELO"; + default: + return null; + } + } + + /** The description of a System code, in lower case, or null (C's {@code SystemLabel}). */ + static String systemLabel(int system) { + switch (system) { + case AST__FREQ: + return "frequency"; + case AST__ENERGY: + return "energy"; + case AST__WAVENUM: + return "wave-number"; + case AST__WAVELEN: + return "wavelength"; + case AST__AIRWAVE: + return "wavelength in air"; + case AST__VRADIO: + return "radio velocity"; + case AST__VOPTICAL: + return "optical velocity"; + case AST__REDSHIFT: + return "redshift"; + case AST__BETA: + return "beta factor"; + case AST__VREL: + return "apparent radial velocity"; + default: + return null; + } + } + + /** A System's description with its first letter in upper case, as C's labels and titles start. */ + private static String capitalised(int system) { + String label = systemLabel(system); + return CScan.toUpper(label.charAt(0)) + label.substring(1); + } + + /** + * Checks a System code (C's {@code ValidateSystem}). + * + * @throws AstException with status {@code AST__AXIIN} if it is not a spectral System + */ + @Override + int validateSystem(int code, String method) { + if (code < FIRST_SYSTEM || code > LAST_SYSTEM) { + throw Ast.err( + AstException.AST__AXIIN, + method + "(" + astClass() + "): Bad value (" + code + ") given for the System or AlignSystem" + + " attribute of a " + astClass() + "."); + } + return code; + } + + /** + * The default units of a System (C's {@code DefUnit}): {@code GHz}, {@code J}, {@code 1/m}, + * {@code Angstrom} for both wavelengths, {@code km/s} for the velocities, and none for redshift + * and beta. + * + * @throws AstException with status {@code AST__SCSIN} if the System is not a spectral System + */ + static String defUnit(int system, String method, String cls) { + switch (system) { + case AST__FREQ: + return "GHz"; + case AST__ENERGY: + return "J"; + case AST__WAVENUM: + return "1/m"; + case AST__WAVELEN: + case AST__AIRWAVE: + return "Angstrom"; + case AST__VRADIO: + case AST__VOPTICAL: + case AST__VREL: + return "km/s"; + case AST__REDSHIFT: + case AST__BETA: + return ""; + default: + throw Ast.err( + AstException.AST__SCSIN, + method + "(" + cls + "): Corrupt " + cls + " contains illegal System identification code (" + + system + ")."); + } + } + + /** + * The units of the values a SpecMap converts in a System (C's {@code SpecMapUnit}): {@code + * Hz}, {@code J}, {@code 1/m}, {@code m} for both wavelengths, {@code m/s} for the velocities, + * and none for redshift and beta. + * + * @throws AstException with status {@code AST__SCSIN} if the System is not a spectral System + */ + static String specMapUnit(int system, String method, String cls) { + switch (system) { + case AST__FREQ: + return "Hz"; + case AST__ENERGY: + return "J"; + case AST__WAVENUM: + return "1/m"; + case AST__WAVELEN: + case AST__AIRWAVE: + return "m"; + case AST__VRADIO: + case AST__VOPTICAL: + case AST__VREL: + return "m/s"; + case AST__REDSHIFT: + case AST__BETA: + return ""; + default: + throw Ast.err( + AstException.AST__SCSIN, + method + "(" + cls + "): Corrupt " + cls + " contains illegal System identification code (" + + system + ")."); + } + } + + @Override + int systemValue() { + return testSystem() ? super.systemValue() : AST__WAVELEN; + } + + @Override + int alignSystemValue() { + return testAlignSystem() ? super.alignSystemValue() : AST__WAVELEN; + } + + /** + * Sets the System (C's {@code SetSystem}). If the System changes, the Unit last used with the + * new System is restored, or the Unit cleared; a set SpecOrigin is re-expressed in the new + * System; and the Label, Symbol and Title, whose defaults depend on the System, are cleared. + */ + @Override + void setSystemValue(int newsys) { + int oldsys = systemValue(); + super.setSystemValue(newsys); + if (oldsys != newsys) { + restoreUnit(newsys); + originSystem(oldsys, "astSetSystem"); + clearLabel(1); + clearSymbol(1); + clearTitle(); + } + } + + /** + * Clears the System (C's {@code ClearSystem}). If the System changes, the Unit last used with + * the default System is restored, or the Unit cleared; the Label, Symbol and Title are + * cleared; and a set SpecOrigin is re-expressed in the default System. + */ + @Override + void clearSystem() { + int oldsys = systemValue(); + super.clearSystem(); + int newsys = systemValue(); + if (newsys != oldsys) { + restoreUnit(newsys); + clearLabel(1); + clearSymbol(1); + clearTitle(); + originSystem(oldsys, "astClearSystem"); + } + } + + /** Sets the Unit to the one last used with System {@code sys}, or clears it if there is none. */ + private void restoreUnit(int sys) { + if (sys < usedUnits.length && usedUnits[sys] != null) { + setUnit(1, usedUnits[sys]); + } else { + clearUnit(1); + } + } + + // ------------------------------------------------------------------ + // SpecFrame attributes + // ------------------------------------------------------------------ + + /** + * Gets the StdOfRest attribute: the standard of rest of the axis values. It is one of {@code + * Topocentric} (the observer, on the surface of the Earth), {@code Geocentric} (the centre of + * the Earth), {@code Barycentric} (the barycentre of the solar system), {@code Heliocentric} + * (the centre of the Sun), {@code LSRK} (the kinematical local standard of rest), {@code LSRD} + * (the dynamical local standard of rest), {@code Galactic} (the centre of the Milky Way), + * {@code Local_group} (the Local Group) or {@code Source} (the source, moving at SourceVel + * relative to SourceVRF towards RefRA, RefDec). Each is qualified as it needs by the Epoch, + * ObsLon, ObsLat, ObsAlt, RefRA and RefDec attributes. The default is Heliocentric. + * + * @return the StdOfRest + */ + public String getStdOfRest() { + return getC("StdOfRest"); + } + + /** + * Sets the StdOfRest attribute. A set SpecOrigin is re-expressed in the new standard of rest. + * + * @param stdOfRest the StdOfRest: any of the names {@link #getStdOfRest} gives, in any case, or + * the abbreviations {@code Topo}, {@code Topocent}, {@code Geo}, {@code Geocentr}, {@code + * Bary}, {@code Barycent}, {@code Helio}, {@code Heliocen}, {@code LSR}, {@code Gal}, {@code + * Galactoc}, {@code LG}, {@code LocalGrp}, {@code Local-group} or {@code Src} + * @throws AstException with status {@code AST__ATTIN} if the name is not a standard of rest + */ + public void setStdOfRest(String stdOfRest) { + setC("StdOfRest", stdOfRest); + } + + /** The StdOfRest code: set, or {@link #AST__HLSOR} (C's {@code GetStdOfRest}). */ + int stdOfRestValue() { + return stdOfRest != AST__BADSOR ? stdOfRest : AST__HLSOR; + } + + /** + * Sets the StdOfRest code (C's {@code SetStdOfRest}), first re-expressing a set SpecOrigin in + * it. + * + * @throws AstException with status {@code AST__ATTIN} if the code is not a standard of rest, + * or {@code AST__ATSER} if the SpecOrigin cannot be re-expressed + */ + void setStdOfRestValue(int value) { + if (value < FIRST_SOR || value > LAST_SOR) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetStdOfRest(" + astClass() + "): Bad value (" + value + ") given for StdOfRest attribute."); + } + originStdOfRest(value, "astSetStdOfRest"); + stdOfRest = value; + } + + boolean testStdOfRest() { + return stdOfRest != AST__BADSOR; + } + + /** + * Clears the StdOfRest (C's {@code ClearStdOfRest}), first re-expressing a set SpecOrigin in + * the heliocentric standard of rest. + */ + void clearStdOfRest() { + originStdOfRest(AST__HLSOR, "astClearStdOfRest"); + stdOfRest = AST__BADSOR; + } + + /** + * Gets the AlignStdOfRest attribute: the standard of rest in which two SpecFrames are aligned + * when one is converted to the other. The conversion found goes from the target's System to the + * AlignSystem, then from the target's standard of rest to the AlignStdOfRest, from that to the + * template's standard of rest, and from the AlignSystem to the template's System. It takes the + * values {@link #getStdOfRest} describes; the default is Heliocentric. + * + * @return the AlignStdOfRest + */ + public String getAlignStdOfRest() { + return getC("AlignStdOfRest"); + } + + /** + * Sets the AlignStdOfRest attribute. + * + * @param alignStdOfRest the AlignStdOfRest, as {@link #setStdOfRest} accepts it + * @throws AstException with status {@code AST__ATTIN} if the name is not a standard of rest + */ + public void setAlignStdOfRest(String alignStdOfRest) { + setC("AlignStdOfRest", alignStdOfRest); + } + + /** The AlignStdOfRest code: set, or {@link #AST__HLSOR}. */ + int alignStdOfRestValue() { + return alignStdOfRest != AST__BADSOR ? alignStdOfRest : AST__HLSOR; + } + + /** + * Sets the AlignStdOfRest code. + * + * @throws AstException with status {@code AST__ATTIN} if the code is not a standard of rest + */ + void setAlignStdOfRestValue(int value) { + if (value < FIRST_SOR || value > LAST_SOR) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetAlignStdOfRest(" + astClass() + "): Bad value (" + value + + ") given for AlignStdOfRest attribute."); + } + alignStdOfRest = value; + } + + boolean testAlignStdOfRest() { + return alignStdOfRest != AST__BADSOR; + } + + void clearAlignStdOfRest() { + alignStdOfRest = AST__BADSOR; + } + + /** + * Gets the RefRA attribute: the right ascension (FK5 J2000) of the source, towards which the + * Source standard of rest moves and which the other standards of rest are corrected for, as + * hours, minutes and seconds. The default is zero. {@link #getRefPos} gives the position in + * another celestial coordinate system. + * + * @return the RefRA + */ + public String getRefRA() { + return getC("RefRA"); + } + + /** + * Sets the RefRA attribute. + * + * @param refRA the right ascension (FK5 J2000), as an FK5 J2000 SkyFrame reads it, such as + * {@code 10:30:00} + * @throws AstException with status {@code AST__ATTIN} if the value cannot be read + */ + public void setRefRA(String refRA) { + setC("RefRA", refRA); + } + + /** The RefRA in radians: set, or zero (C's {@code GetRefRA}). */ + double refRaValue() { + return refRaRadians != AST__BAD ? refRaRadians : 0.0; + } + + void setRefRaValue(double value) { + refRaRadians = value; + } + + boolean testRefRA() { + return refRaRadians != AST__BAD; + } + + void clearRefRA() { + refRaRadians = AST__BAD; + } + + /** + * Gets the RefDec attribute: the declination (FK5 J2000) of the source, as degrees, minutes and + * seconds. The default is zero. + * + * @return the RefDec + */ + public String getRefDec() { + return getC("RefDec"); + } + + /** + * Sets the RefDec attribute. + * + * @param refDec the declination (FK5 J2000), as an FK5 J2000 SkyFrame reads it, such as {@code + * -30:00:00} + * @throws AstException with status {@code AST__ATTIN} if the value cannot be read + */ + public void setRefDec(String refDec) { + setC("RefDec", refDec); + } + + /** The RefDec in radians: set, or zero (C's {@code GetRefDec}). */ + double refDecValue() { + return refDecRadians != AST__BAD ? refDecRadians : 0.0; + } + + void setRefDecValue(double value) { + refDecRadians = value; + } + + boolean testRefDec() { + return refDecRadians != AST__BAD; + } + + void clearRefDec() { + refDecRadians = AST__BAD; + } + + /** + * Gets the RestFreq attribute: the frequency of zero velocity, in GHz, used when converting + * between a velocity or redshift and the other Systems. The default is 1.0E5 GHz. + * + * @return the RestFreq, in GHz + */ + public double getRestFreq() { + return getD("RestFreq"); + } + + /** + * Sets the RestFreq attribute. + * + * @param restFreq the RestFreq, in GHz + */ + public void setRestFreq(double restFreq) { + setD("RestFreq", restFreq); + } + + /** + * Sets the RestFreq attribute from text: a frequency in GHz, or a value followed by its units, + * which may be those of a frequency, of a (vacuum) wavelength or of an energy, the value then + * being converted to a frequency. {@code 1.4E5}, {@code 1.4E14 Hz}, {@code 2.14E-6 m}, {@code + * 21400 Angstrom}, {@code 9.28E-20 J} and {@code 0.58 eV} all give about 1.4E14 Hz. + * + * @param restFreq the RestFreq + * @throws AstException with status {@code AST__ATTIN} if the units are not a frequency, + * wavelength or energy, or the wavelength is zero + */ + public void setRestFreq(String restFreq) { + set("RestFreq=" + restFreq); + } + + /** The RestFreq in Hz: set, or 1.0E14 (C's {@code GetRestFreq}). */ + double restFreqValue() { + return restFreq != AST__BAD ? restFreq : 1.0E14; + } + + void setRestFreqValue(double value) { + restFreq = value; + } + + boolean testRestFreq() { + return restFreq != AST__BAD; + } + + void clearRestFreq() { + restFreq = AST__BAD; + } + + /** + * Gets the SourceVel attribute: the velocity of the source, which defines the Source standard + * of rest, in the spectral system given by SourceSys (km/s for a velocity) and the rest frame + * given by SourceVRF. A positive value means the source moves away from the observer. The + * default is zero. + * + * @return the SourceVel + */ + public double getSourceVel() { + return getD("SourceVel"); + } + + /** + * Sets the SourceVel attribute, in the spectral system given by SourceSys and the rest frame + * given by SourceVRF, which should be set first: a later change to either re-expresses the + * SourceVel in the new one. + * + * @param sourceVel the SourceVel + */ + public void setSourceVel(double sourceVel) { + setD("SourceVel", sourceVel); + } + + /** The SourceVel, in m/s for a velocity: set, or zero (C's {@code GetSourceVel}). */ + double sourceVelValue() { + return sourceVel != AST__BAD ? sourceVel : 0.0; + } + + void setSourceVelValue(double value) { + sourceVel = value; + } + + boolean testSourceVel() { + return sourceVel != AST__BAD; + } + + void clearSourceVel() { + sourceVel = AST__BAD; + } + + /** Whether SourceSys is a velocity, which the SourceVel attribute gives in km/s. */ + private boolean sourceVelInKms() { + int sys = sourceSysValue(); + return sys == AST__VREL || sys == AST__VRADIO || sys == AST__VOPTICAL; + } + + /** + * Gets the SourceVRF attribute as a number, as jniast's accessor does. The attribute is the + * rest frame of the SourceVel, a standard of rest as {@link #getStdOfRest} describes them + * other than Source; its value is the name of one, so this accessor fails: {@code + * getC("SourceVRF")} gives the name. + * + * @return the SourceVRF, read as a number + * @throws AstException with status {@code AST__ATGER}, as the value is not a number + */ + public double getSourceVRF() { + return getD("SourceVRF"); + } + + /** + * Sets the SourceVRF attribute from a number, as jniast's accessor does. The attribute takes + * the name of a standard of rest, so this accessor fails: {@code setC("SourceVRF", name)} sets + * it, re-expressing a set SourceVel in the new rest frame. + * + * @param sourceVRF the value, written as a number + * @throws AstException with status {@code AST__ATTIN}, as a number is not a standard of rest + */ + public void setSourceVRF(double sourceVRF) { + setD("SourceVRF", sourceVRF); + } + + /** The SourceVRF code: set, or {@link #AST__HLSOR}. */ + int sourceVrfValue() { + return sourceVrfCode != AST__BADSOR ? sourceVrfCode : AST__HLSOR; + } + + /** + * Sets the SourceVRF code, first re-expressing a set SourceVel in the new rest frame. + * + * @throws AstException with status {@code AST__ATTIN} if the code is not a standard of rest, + * or is the Source rest frame + */ + void setSourceVrfValue(int value) { + if (value < FIRST_SOR || value > LAST_SOR || value == AST__SCSOR) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetSourceVRF(" + astClass() + "): Bad value (" + value + ") given for SourceVRF attribute."); + } + if (testSourceVel()) { + setSourceVelValue(convertSourceVel(value, sourceSysValue())); + } + sourceVrfCode = value; + } + + boolean testSourceVRF() { + return sourceVrfCode != AST__BADSOR; + } + + /** Clears the SourceVRF, first re-expressing a set SourceVel in the heliocentric rest frame. */ + void clearSourceVRF() { + if (testSourceVel()) { + setSourceVelValue(convertSourceVel(AST__HLSOR, sourceSysValue())); + } + sourceVrfCode = AST__BADSOR; + } + + /** + * Gets the SourceSys attribute: the spectral system of the SourceVel, one of {@code VRAD}, + * {@code VOPT}, {@code ZOPT}, {@code BETA} and {@code VELO} (the default). + * + * @return the SourceSys + */ + public String getSourceSys() { + return getC("SourceSys"); + } + + /** + * Sets the SourceSys attribute, re-expressing a set SourceVel in the new spectral system. + * + * @param sourceSys the SourceSys, in any case, or the long forms {@code VRADIO}, {@code + * VOPTICAL}, {@code REDSHIFT} or {@code VREL} + * @throws AstException with status {@code AST__ATTIN} if the name is not one of these + */ + public void setSourceSys(String sourceSys) { + setC("SourceSys", sourceSys); + } + + /** The SourceSys code: set, or {@link #AST__VREL}. */ + int sourceSysValue() { + return sourceSys != AST__BADSYSTEM ? sourceSys : AST__VREL; + } + + /** + * Sets the SourceSys code, first re-expressing a set SourceVel in the new spectral system. + * + * @throws AstException with status {@code AST__ATTIN} if the code is not a velocity, redshift + * or beta + */ + void setSourceSysValue(int value) { + if (value != AST__VREL + && value != AST__BETA + && value != AST__VRADIO + && value != AST__REDSHIFT + && value != AST__VOPTICAL) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetSourceSys(" + astClass() + "): Bad value (" + value + ") given for SourceSys attribute."); + } + if (testSourceVel()) { + setSourceVelValue(convertSourceVel(sourceVrfValue(), value)); + } + sourceSys = value; + } + + boolean testSourceSys() { + return sourceSys != AST__BADSYSTEM; + } + + /** Clears the SourceSys, first re-expressing a set SourceVel as an apparent radial velocity. */ + void clearSourceSys() { + if (testSourceVel()) { + setSourceVelValue(convertSourceVel(sourceVrfValue(), AST__VREL)); + } + sourceSys = AST__BADSYSTEM; + } + + /** The SpecOrigin in the default units of the System: set, or zero (C's {@code GetSpecOrigin}). */ + double specOriginValue() { + return specOrigin != AST__BAD ? specOrigin : 0.0; + } + + void setSpecOriginValue(double value) { + specOrigin = value; + } + + boolean testSpecOrigin() { + return specOrigin != AST__BAD; + } + + void clearSpecOrigin() { + specOrigin = AST__BAD; + } + + /** + * The SpecOrigin in the units of the axis (C's {@code GetSpecOriginCur}), which the SpecOrigin + * attribute reports. + * + * @throws AstException with status {@code AST__BADUN} if the Unit cannot be converted from the + * System's default units + */ + double specOriginCur() { + double result = specOriginValue(); + if (result != 0.0 && result != AST__BAD) { + String def = defUnit(systemValue(), "astGetSpecOrigin", "SpecFrame"); + String cur = getUnit(1); + if (!cur.equals(def)) { + Mapping map = Units.unitMapper(def, cur); + if (map == null) { + throw Ast.err( + AstException.AST__BADUN, + "astGetSpecOrigin(" + astClass() + "): The current units (" + cur + + ") are not suitable for a SpecFrame."); + } + result = transformValue(map, result); + } + } + return result; + } + + /** The AlignSpecOffset flag: set, or false (C's {@code GetAlignSpecOffset}). */ + boolean alignSpecOffsetValue() { + return alignSpecOffset != UNSET && alignSpecOffset != 0; + } + + void setAlignSpecOffsetValue(boolean value) { + alignSpecOffset = value ? 1 : 0; + } + + boolean testAlignSpecOffset() { + return alignSpecOffset != UNSET; + } + + void clearAlignSpecOffset() { + alignSpecOffset = UNSET; + } + + /** + * Gets the GeoLat attribute, the latitude of the observer, which is the ObsLat attribute under + * the name an older version of the SpecFrame used. + * + * @return the ObsLat + */ + public String getGeoLat() { + return getObsLat(); + } + + /** + * Sets the GeoLat attribute, which sets the ObsLat attribute. + * + * @param geoLat the latitude, as {@code N} or {@code S} followed by an angle in degrees + * @throws AstException with status {@code AST__ATTIN} if the value cannot be read + */ + public void setGeoLat(String geoLat) { + setObsLat(geoLat); + } + + /** + * Gets the GeoLon attribute, the longitude of the observer, which is the ObsLon attribute under + * the name an older version of the SpecFrame used. + * + * @return the ObsLon + */ + public String getGeoLon() { + return getObsLon(); + } + + /** + * Sets the GeoLon attribute, which sets the ObsLon attribute. + * + * @param geoLon the longitude, as {@code E} or {@code W} followed by an angle in degrees + * @throws AstException with status {@code AST__ATTIN} if the value cannot be read + */ + public void setGeoLon(String geoLon) { + setObsLon(geoLon); + } + + // ------------------------------------------------------------------ + // The reference position + // ------------------------------------------------------------------ + + /** + * The FK5 J2000 SkyFrame in which C formats and reads RefRA and RefDec and stores the reference + * position. + */ + private static SkyFrame refSkyFrame() { + SkyFrame sf = new SkyFrame(); + sf.set("system=FK5,equinox=J2000"); + return sf; + } + + /** + * Gets the reference position (the RefRA and RefDec attributes) in the celestial coordinate + * system of a SkyFrame (C's {@code astGetRefPos}). + * + * @param frm the SkyFrame giving the coordinate system, or null for FK5 J2000 + * @return the longitude and latitude, in radians; both bad if there is no conversion to the + * SkyFrame's coordinate system + */ + public double[] getRefPos(SkyFrame frm) { + if (frm == null) { + return new double[] {refRaValue(), refDecValue()}; + } + double lon = AST__BAD; + double lat = AST__BAD; + FrameSet fs = refSkyFrame().findFrame(frm, ""); + if (fs != null) { + SkyFrame fb = (SkyFrame) fs.getFrame(FrameSet.AST__BASE); + double[] xin; + double[] yin; + if (fb.getLonAxis() == 1) { + xin = new double[] {refRaValue()}; + yin = new double[] {refDecValue()}; + } else { + yin = new double[] {refRaValue()}; + xin = new double[] {refDecValue()}; + } + double[][] out = fs.tran2(1, xin, yin, true); + SkyFrame fc = (SkyFrame) fs.getFrame(FrameSet.AST__CURRENT); + if (fc.getLonAxis() == 1) { + lon = out[0][0]; + lat = out[1][0]; + } else { + lon = out[1][0]; + lat = out[0][0]; + } + } + return new double[] {lon, lat}; + } + + /** + * Sets the reference position (the RefRA and RefDec attributes) from a position in the + * celestial coordinate system of a SkyFrame, converted to FK5 J2000 (C's {@code + * astSetRefPos}). Nothing is set if there is no conversion from the SkyFrame's coordinate + * system. + * + * @param frm the SkyFrame giving the coordinate system, or null for FK5 J2000 + * @param lon the longitude, in radians + * @param lat the latitude, in radians + */ + public void setRefPos(SkyFrame frm, double lon, double lat) { + if (frm == null) { + setRefRaValue(lon); + setRefDecValue(lat); + return; + } + FrameSet fs = frm.findFrame(refSkyFrame(), ""); + if (fs != null) { + SkyFrame fb = (SkyFrame) fs.getFrame(FrameSet.AST__BASE); + double[] xin; + double[] yin; + if (fb.getLonAxis() == 1) { + xin = new double[] {lon}; + yin = new double[] {lat}; + } else { + xin = new double[] {lat}; + yin = new double[] {lon}; + } + double[][] out = fs.tran2(1, xin, yin, true); + SkyFrame fc = (SkyFrame) fs.getFrame(FrameSet.AST__CURRENT); + if (fc.getLonAxis() == 1) { + setRefRaValue(out[0][0]); + setRefDecValue(out[1][0]); + } else { + setRefRaValue(out[1][0]); + setRefDecValue(out[0][0]); + } + } + } + + // ------------------------------------------------------------------ + // Frame attributes with SpecFrame defaults + // ------------------------------------------------------------------ + + /** The Domain: set, or {@code SPECTRUM}. */ + @Override + public String getDomain() { + return testDomain() ? super.getDomain() : "SPECTRUM"; + } + + /** + * Gets the ActiveUnit flag, which is always true for a SpecFrame: a difference in the Unit of + * two SpecFrames is always allowed for when one is converted to the other. + * + * @return true + */ + @Override + public boolean getActiveUnit() { + return true; + } + + @Override + boolean testActiveUnit() { + return false; + } + + /** Gets the Unit of the axis: set, or the default units of the System. */ + @Override + public String getUnit(int axis) { + validateAxis(axis, true, "astGetUnit"); + if (testUnit(axis)) { + return super.getUnit(axis); + } + return defUnit(systemValue(), "astGetUnit", astClass()); + } + + /** + * Sets the Unit of the axis (C's {@code SetUnit}), recording it as the Unit used with the + * current System, which comes back when the System does. Units of another kind than the + * System's, such as Angstrom for frequency, are accepted; a SpecOrigin cannot then be given or + * read, and the SpecFrame cannot be converted. + */ + @Override + public void setUnit(int axis, String unit) { + validateAxis(axis, true, "astSetUnit"); + int system = systemValue(); + if (usedUnits[system] == null || !usedUnits[system].equals(unit)) { + usedUnits[system] = unit; + } + super.setUnit(axis, unit); + } + + /** Clears the Unit of the axis and the record of the Unit used with the current System (C's {@code ClearUnit}). */ + @Override + void clearUnit(int axis) { + validateAxis(axis, true, "astClearUnit"); + int system = systemValue(); + if (system < usedUnits.length) { + usedUnits[system] = null; + } + super.clearUnit(axis); + } + + /** + * Gets the Label of the axis (C's {@code GetLabel}): set; or the System's description, followed + * by {@code offset from} and the formatted SpecOrigin if it is not zero, and rewritten for a set + * Unit, as {@code log( Frequency )} for {@code log(GHz)}. + * + * @throws AstException with status {@code AST__BADUN} if a SpecOrigin is set and the Unit + * cannot be converted from the System's default units + */ + @Override + public String getLabel(int axis) { + validateAxis(axis, true, "astGetLabel"); + if (testLabel(axis)) { + return super.getLabel(axis); + } + int system = systemValue(); + String result = capitalised(system); + double orig = specOriginCur(); + if (orig != 0.0) { + result = result + " offset from " + format(1, orig); + } + if (testUnit(axis)) { + Units.LabelledMapping lm = Units.relabel(defUnit(system, "astGetLabel", astClass()), getUnit(axis), result); + if (lm != null && lm.label != null) { + result = lm.label; + } + } + return result; + } + + /** + * Gets the Symbol of the axis (C's {@code GetSymbol}): set, or the System's name ({@code FREQ}, + * {@code ENER}, {@code WAVN}, {@code WAVE}, {@code AWAV}, {@code VRAD}, {@code VOPT}, {@code + * ZOPT}, {@code BETA} or {@code VELO}), rewritten for a set Unit. + */ + @Override + public String getSymbol(int axis) { + validateAxis(axis, true, "astGetSymbol"); + if (testSymbol(axis)) { + return super.getSymbol(axis); + } + int system = systemValue(); + String result = systemString(system); + if (result == null) { + throw Ast.err( + AstException.AST__SCSIN, + "astGetSymbol(" + astClass() + "): Corrupt " + astClass() + + " contains invalid System identification code (" + system + ")."); + } + if (testUnit(axis)) { + Units.LabelledMapping lm = + Units.relabel(defUnit(system, "astGetSymbol", astClass()), getUnit(axis), result); + if (lm != null && lm.label != null) { + result = lm.label; + } + } + return result; + } + + /** + * Gets the Title (C's {@code GetTitle}): set, or the System's description, followed by the + * StdOfRest in brackets if it is set, and for a velocity, redshift or beta by the rest + * frequency in GHz if the RestFreq is set or UseDefs is true. + * + * @return the Title + */ + @Override + public String getTitle() { + if (testTitle()) { + return super.getTitle(); + } + int system = systemValue(); + String sorString = stdOfRestString(stdOfRestValue()); + double rf = restFreqValue(); + StringBuilder sb = new StringBuilder(capitalised(system)); + if (testStdOfRest()) { + sb.append(" (").append(sorString).append(')'); + } + if (!absSystem(system) && (testRestFreq() || getUseDefs())) { + sb.append(", rest frequency = ") + .append(CFormat.format("%g", rf * 1.0E-9)) + .append(" GHz"); + } + return sb.toString(); + } + + // ------------------------------------------------------------------ + // Conversions of attribute values + // ------------------------------------------------------------------ + + /** One value transformed by a Mapping with one input and one output. */ + private static double transformValue(Mapping map, double value) { + return map.tran1(1, new double[] {value}, true)[0]; + } + + /** + * A value in units {@code oldunit} in the default units of the System (C's {@code ToUnits}). + * + * @throws AstException with status {@code AST__BADUN} if the units cannot be converted + */ + double toUnits(String oldunit, double oldval, String method) { + String defunit = defUnit(systemValue(), method, "SpecFrame"); + Mapping map = Units.unitMapper(oldunit, defunit); + if (map == null) { + throw Ast.err( + AstException.AST__BADUN, + method + "(" + astClass() + "): Cannot convert the supplied attribute value from units of " + + oldunit + " to " + defunit + "."); + } + return transformValue(map, oldval); + } + + /** + * Re-expresses a set SpecOrigin in standard of rest {@code newsor}, before the StdOfRest + * changes to it (C's {@code OriginStdOfRest}): through the conversion from this SpecFrame to a + * copy in the new standard of rest. + * + * @throws AstException with status {@code AST__ATSER} if the SpecOrigin cannot be converted + */ + private void originStdOfRest(int newsor, String method) { + if (!testSpecOrigin() || newsor == stdOfRestValue()) { + return; + } + double origin = specOriginCur(); + clearSpecOrigin(); + SpecFrame sf = (SpecFrame) copy(); + sf.setStdOfRestValue(newsor); + FrameSet fs = convert(sf, ""); + double neworigin = AST__BAD; + if (fs != null) { + neworigin = transformValue(fs, origin); + } + if (neworigin == AST__BAD) { + throw Ast.err( + AstException.AST__ATSER, + method + "(" + astClass() + "): Cannot convert the SpecOrigin value to a different rest frame."); + } + setSpecOriginValue(toUnits(getUnit(1), neworigin, method)); + } + + /** + * Re-expresses a set SpecOrigin, in System {@code oldsys}, in the System the SpecFrame now has + * (C's {@code OriginSystem}): through the conversion between two copies with no Unit, + * SpecOrigin or AlignSpecOffset, one in the old System and one in the new. + * + * @throws AstException with status {@code AST__ATSER} if the SpecOrigin cannot be converted + */ + private void originSystem(int oldsys, String method) { + if (!testSpecOrigin() || oldsys == systemValue()) { + return; + } + double origin = specOriginValue(); + SpecFrame sf1 = (SpecFrame) copy(); + sf1.clearUnit(1); + sf1.clearSpecOrigin(); + sf1.clearAlignSpecOffset(); + SpecFrame sf2 = (SpecFrame) sf1.copy(); + sf2.setSystemValue(oldsys); + FrameSet fs = sf2.convert(sf1, ""); + double neworigin = AST__BAD; + if (fs != null) { + neworigin = transformValue(fs, origin); + } + if (neworigin == AST__BAD) { + throw Ast.err( + AstException.AST__ATSER, + method + "(" + astClass() + "): Cannot convert the SpecOrigin value to a different spectral" + + " system."); + } + setSpecOriginValue(neworigin); + } + + /** + * The SourceVel in rest frame {@code newsor} and spectral system {@code newsys} (C's {@code + * ConvertSourceVel}): in m/s for a velocity, through a SpecMap from the SourceSys to apparent + * radial velocity, to frequency, from the SourceVRF to {@code newsor}, and back. + * + * @throws AstException with status {@code AST__NOVAL} if UseDefs is false and the SourceVel, or + * for a conversion the RestFreq, is not set, or the error of the change of rest frame + */ + double convertSourceVel(int newsor, int newsys) { + String purp = "convert source velocity to a new standard of rest"; + double ret = sourceVelValue(); + verifyAttrs(purp, "SourceVel", "astMatch"); + int sor = sourceVrfValue(); + int sys = sourceSysValue(); + if (sor != newsor || sys != newsys) { + verifyAttrs(purp, "RestFreq", "astMatch"); + SpecFrame from = (SpecFrame) copy(); + from.setStdOfRestValue(sor); + SpecFrame to = (SpecFrame) copy(); + to.setStdOfRestValue(newsor); + SpecMap specmap = new SpecMap(1, 0); + if (sys == AST__VRADIO) { + specmap.specAdd("VRTOVL", null); + } else if (sys == AST__VOPTICAL) { + specmap.specAdd("VOTOVL", null); + } else if (sys == AST__REDSHIFT) { + specmap.specAdd("ZOTOVL", null); + } else if (sys == AST__BETA) { + specmap.specAdd("BTTOVL", null); + } + double rf = restFreqValue(); + specmap.specAdd("VLTOFR", new double[] {rf}); + sorConvert(from, to, specmap); + specmap.specAdd("FRTOVL", new double[] {rf}); + if (newsys == AST__VRADIO) { + specmap.specAdd("VLTOVR", null); + } else if (newsys == AST__VOPTICAL) { + specmap.specAdd("VLTOVO", null); + } else if (newsys == AST__REDSHIFT) { + specmap.specAdd("VLTOZO", null); + } else if (newsys == AST__BETA) { + specmap.specAdd("VLTOBT", null); + } + ret = transformValue(specmap, ret); + } + return ret; + } + + /** + * Whether two SpecFrames use the same standard of rest (C's {@code EqualSor}): the same + * StdOfRest, RefRA and RefDec, and what that standard of rest depends on: the SourceVel, + * SourceVRF and SourceSys for the source, the Epoch for the geocentric, barycentric and + * heliocentric ones, and the Epoch and observer's position for the topocentric one. + */ + static boolean equalSor(SpecFrame self, SpecFrame that) { + int sor = self.stdOfRestValue(); + if (that.stdOfRestValue() != sor) { + return false; + } + if (!MappingHelpers.astEqual(self.refRaValue(), that.refRaValue()) + || !MappingHelpers.astEqual(self.refDecValue(), that.refDecValue())) { + return false; + } + if (sor == AST__SCSOR) { + return MappingHelpers.astEqual(self.sourceVelValue(), that.sourceVelValue()) + && self.sourceVrfValue() == that.sourceVrfValue() + && self.sourceSysValue() == that.sourceSysValue(); + } else if (sor == AST__GESOR || sor == AST__BYSOR || sor == AST__HLSOR) { + return MappingHelpers.astEqual(self.getEpochMjd(), that.getEpochMjd()); + } else if (sor == AST__TPSOR) { + return MappingHelpers.astEqual(self.getEpochMjd(), that.getEpochMjd()) + && MappingHelpers.astEqual(self.getObsAlt(), that.getObsAlt()) + && MappingHelpers.astEqual(self.getObsLonValue(), that.getObsLonValue()) + && MappingHelpers.astEqual(self.getObsLatValue(), that.getObsLatValue()); + } else if (sor == AST__LKSOR || sor == AST__LDSOR || sor == AST__GLSOR || sor == AST__LGSOR) { + return true; + } else { + throw Ast.err( + AstException.AST__INTER, + "SorEqual(SpecFrame): Function SorEqual does not yet support rest frame " + sor + + " (AST internal programming error)"); + } + } + + /** + * Adds to {@code specmap} the conversion of a frequency from the standard of rest of {@code + * self} to that of {@code that}, through the heliocentric one, unless they are the same (C's + * {@code SorConvert}). Each side's RefRA and RefDec, and the Epoch, observer's position and + * source velocity its standard of rest needs, are used. + * + * @throws AstException with status {@code AST__NOVAL} if UseDefs is false on a side and an + * attribute it needs is not set + */ + static void sorConvert(SpecFrame self, SpecFrame that, SpecMap specmap) { + if (equalSor(self, that)) { + return; + } + String vmess = "convert between different standards of rest"; + int from = self.stdOfRestValue(); + double ra = self.refRaValue(); + double dec = self.refDecValue(); + double lon = self.getObsLonValue(); + double lat = self.getObsLatValue(); + double alt = self.getObsAlt(); + double epoch = self.getEpochMjd(); + self.verifyAttrs(vmess, "RefRA RefDec", "astMatch"); + if (from == AST__TPSOR) { + self.verifyAttrs(vmess, "ObsLon ObsLat ObsAlt Epoch", "astMatch"); + specmap.specAdd("TPF2HL", new double[] {lon, lat, alt, epoch, ra, dec}); + } else if (from == AST__GESOR) { + self.verifyAttrs(vmess, "Epoch", "astMatch"); + specmap.specAdd("GEF2HL", new double[] {epoch, ra, dec}); + } else if (from == AST__BYSOR) { + self.verifyAttrs(vmess, "Epoch", "astMatch"); + specmap.specAdd("BYF2HL", new double[] {epoch, ra, dec}); + } else if (from == AST__LKSOR) { + specmap.specAdd("LKF2HL", new double[] {ra, dec}); + } else if (from == AST__LDSOR) { + specmap.specAdd("LDF2HL", new double[] {ra, dec}); + } else if (from == AST__LGSOR) { + specmap.specAdd("LGF2HL", new double[] {ra, dec}); + } else if (from == AST__GLSOR) { + specmap.specAdd("GLF2HL", new double[] {ra, dec}); + } else if (from == AST__SCSOR) { + specmap.specAdd("USF2HL", new double[] {self.convertSourceVel(AST__HLSOR, AST__VREL), ra, dec}); + } + int to = that.stdOfRestValue(); + ra = that.refRaValue(); + dec = that.refDecValue(); + lon = that.getObsLonValue(); + lat = that.getObsLatValue(); + alt = that.getObsAlt(); + epoch = that.getEpochMjd(); + that.verifyAttrs(vmess, "RefRA RefDec", "astMatch"); + if (to == AST__TPSOR) { + that.verifyAttrs(vmess, "ObsLon ObsLat ObsAlt Epoch", "astMatch"); + specmap.specAdd("HLF2TP", new double[] {lon, lat, alt, epoch, ra, dec}); + } else if (to == AST__GESOR) { + that.verifyAttrs(vmess, "Epoch", "astMatch"); + specmap.specAdd("HLF2GE", new double[] {epoch, ra, dec}); + } else if (to == AST__BYSOR) { + that.verifyAttrs(vmess, "Epoch", "astMatch"); + specmap.specAdd("HLF2BY", new double[] {epoch, ra, dec}); + } else if (to == AST__LKSOR) { + specmap.specAdd("HLF2LK", new double[] {ra, dec}); + } else if (to == AST__LDSOR) { + specmap.specAdd("HLF2LD", new double[] {ra, dec}); + } else if (to == AST__LGSOR) { + specmap.specAdd("HLF2LG", new double[] {ra, dec}); + } else if (to == AST__GLSOR) { + specmap.specAdd("HLF2GL", new double[] {ra, dec}); + } else if (to == AST__SCSOR) { + specmap.specAdd("HLF2US", new double[] {that.convertSourceVel(AST__HLSOR, AST__VREL), ra, dec}); + } + } + + /** + * C's {@code VerifyAttrs}: with UseDefs false, checks that each attribute named in {@code + * attrs} (separated by white space, a name standing for every attribute it starts) is set. + * + * @throws AstException with status {@code AST__NOVAL} if one is not, saying that the SpecFrame + * cannot do {@code purp} + */ + void verifyAttrs(String purp, String attrs, String method) { + if (getUseDefs()) { + return; + } + int i = 0; + int n = attrs.length(); + while (i < n) { + while (i < n && CScan.isCSpace(attrs.charAt(i))) { + i++; + } + int start = i; + while (i < n && !CScan.isCSpace(attrs.charAt(i))) { + i++; + } + if (i == start) { + break; + } + String a = attrs.substring(start, i); + boolean set; + String desc; + if ("ObsLat".startsWith(a)) { + set = testObsLat(); + desc = "observer's latitude"; + } else if ("ObsLon".startsWith(a)) { + set = testObsLon(); + desc = "observer's longitude"; + } else if ("ObsAlt".startsWith(a)) { + set = testObsAlt(); + desc = "observer's altitude"; + } else if ("RefRA".startsWith(a)) { + set = testRefRA(); + desc = "source RA"; + } else if ("RefDec".startsWith(a)) { + set = testRefDec(); + desc = "source Dec"; + } else if ("RestFreq".startsWith(a)) { + set = testRestFreq(); + desc = "rest frequency"; + } else if ("SourceVel".startsWith(a)) { + set = testSourceVel(); + desc = "source velocity"; + } else if ("StdOfRest".startsWith(a)) { + set = testStdOfRest(); + desc = "spectral standard of rest"; + } else if ("Epoch".startsWith(a)) { + set = testEpoch(); + desc = "epoch of observation"; + } else { + throw Ast.err( + AstException.AST__INTER, + "VerifyAttrs(SpecFrame): Unknown attribute name \"" + a + + "\" supplied (AST internal programming error)."); + } + if (!set) { + throw Ast.err( + AstException.AST__NOVAL, + method + "(" + astClass() + "): Cannot " + purp + ".\nNo value has been set for the AST \"" + a + + "\" attribute (" + desc + ")."); + } + } + } + + // ------------------------------------------------------------------ + // Matching + // ------------------------------------------------------------------ + + /** Adds to {@code specmap} the conversion from System {@code system} to frequency. */ + private void addToFrequency(SpecMap specmap, int system, double rf, String vmess) { + if (system == AST__ENERGY) { + specmap.specAdd("ENTOFR", null); + } else if (system == AST__WAVENUM) { + specmap.specAdd("WNTOFR", null); + } else if (system == AST__WAVELEN) { + specmap.specAdd("WVTOFR", null); + } else if (system == AST__AIRWAVE) { + specmap.specAdd("AWTOFR", null); + } else { + if (system == AST__VRADIO) { + specmap.specAdd("VRTOVL", null); + } else if (system == AST__VOPTICAL) { + specmap.specAdd("VOTOVL", null); + } else if (system == AST__REDSHIFT) { + specmap.specAdd("ZOTOVL", null); + } else if (system == AST__BETA) { + specmap.specAdd("BTTOVL", null); + } else if (system != AST__VREL) { + throw Ast.err(AstException.AST__INTER, "MakeSpecMapping(SpecFrame): unexpected System " + system + "."); + } + verifyAttrs(vmess, "RestFreq", "astMatch"); + specmap.specAdd("VLTOFR", new double[] {rf}); + } + } + + /** Adds to {@code specmap} the conversion from frequency to System {@code system}. */ + private void addFromFrequency(SpecMap specmap, int system, double rf, String vmess) { + if (system == AST__ENERGY) { + specmap.specAdd("FRTOEN", null); + } else if (system == AST__WAVENUM) { + specmap.specAdd("FRTOWN", null); + } else if (system == AST__WAVELEN) { + specmap.specAdd("FRTOWV", null); + } else if (system == AST__AIRWAVE) { + specmap.specAdd("FRTOAW", null); + } else { + verifyAttrs(vmess, "RestFreq", "astMatch"); + specmap.specAdd("FRTOVL", new double[] {rf}); + if (system == AST__VRADIO) { + specmap.specAdd("VLTOVR", null); + } else if (system == AST__VOPTICAL) { + specmap.specAdd("VLTOVO", null); + } else if (system == AST__REDSHIFT) { + specmap.specAdd("VLTOZO", null); + } else if (system == AST__BETA) { + specmap.specAdd("VLTOBT", null); + } else if (system != AST__VREL) { + throw Ast.err(AstException.AST__INTER, "MakeSpecMapping(SpecFrame): unexpected System " + system + "."); + } + } + } + + /** + * A copy of {@code alignFrm} with the properties that define the rest frames of {@code frm}: + * its Epoch, RefRA, RefDec, SourceVRF, SourceVel and observer's position. + */ + private static SpecFrame alignCopy(SpecFrame alignFrm, SpecFrame frm) { + SpecFrame a = (SpecFrame) alignFrm.copy(); + a.setEpochMjd(frm.getEpochMjd()); + a.setRefRaValue(frm.refRaValue()); + a.setRefDecValue(frm.refDecValue()); + a.setSourceVrfValue(frm.sourceVrfValue()); + a.setSourceVelValue(frm.sourceVelValue()); + a.setObsLatValue(frm.getObsLatValue()); + a.setObsLonValue(frm.getObsLonValue()); + a.setObsAlt(frm.getObsAlt()); + return a; + } + + /** + * The Mapping from SpecFrame {@code target} to SpecFrame {@code result}, or null if there is + * none (C's {@code MakeSpecMapping}). The values go from the target's System to frequency, from + * the target's standard of rest to the alignment standard of rest, to the alignment System and + * back (only for a relative alignment System and different rest frequencies), from the + * alignment standard of rest to the result's, and from frequency to the result's System, using + * the target's properties on the way to the alignment Frame and the result's after it. The + * alignment System (frequency for an absolute System, apparent radial velocity for a relative + * one) and standard of rest are the System and StdOfRest of {@code alignFrm}. Restoring a + * FrameSet's integrity ({@code AST__INTFLAG} set on the target), the alignment rest frames are + * defined by {@code alignFrm}'s own properties; otherwise by those of the target and of the + * result, so that, say, two source rest frames align however their sources differ. The + * Mapping converts between the two Frames' units, and adds the target's SpecOrigin before and + * subtracts the result's after, or, if both Frames have AlignSpecOffset set, the target's + * origin transformed (the result's own when that is bad). + * + * @param report whether a Unit of another kind than the System's is an error rather than no + * Mapping + * @throws AstException with status {@code AST__NOVAL} if UseDefs is false and an attribute the + * conversion needs is not set, or {@code AST__BADUN} for units that cannot be converted when + * {@code report} is true + */ + private static Mapping makeSpecMapping(SpecFrame target, SpecFrame result, SpecFrame alignFrm, boolean report) { + boolean match = true; + SpecMap specmap = new SpecMap(1, 0); + double targetRf = target.restFreqValue(); + double resultRf = result.restFreqValue(); + int targetSystem = target.systemValue(); + int resultSystem = result.systemValue(); + int alignSystem = alignFrm.systemValue(); + String vmess = "convert between spectral systems"; + result.verifyAttrs(vmess, "StdOfRest", "astMatch"); + target.verifyAttrs(vmess, "StdOfRest", "astMatch"); + + SpecFrame alignTarget; + SpecFrame alignResult; + if ((target.getFrameFlags() & AST__INTFLAG) != 0) { + alignTarget = alignFrm; + alignResult = alignFrm; + } else { + alignTarget = alignCopy(alignFrm, target); + alignResult = alignCopy(alignFrm, result); + } + alignSystem = absSystem(alignSystem) ? AST__FREQ : AST__VREL; + + boolean step2 = true; + boolean step3 = true; + boolean step4 = true; + boolean step5 = true; + boolean step6 = true; + boolean step7 = true; + if (targetSystem == AST__FREQ) { + step2 = false; + } + if (equalSor(target, alignTarget)) { + step3 = false; + } + if (equalSor(result, alignResult)) { + step6 = false; + } + if (resultSystem == AST__FREQ) { + step7 = false; + } + // C compares the rest frequencies exactly. + boolean sameRf = resultRf == targetRf; + if (alignSystem == AST__FREQ || sameRf) { + step4 = false; + step5 = false; + } + if (!step4 && !step5 && equalSor(target, result)) { + step3 = false; + step6 = false; + } + if (!step3 + && !step4 + && !step5 + && !step6 + && equalSor(target, result) + && targetSystem == resultSystem + && !absSystem(targetSystem) + && sameRf) { + step2 = false; + step7 = false; + } + + if (step2 && targetSystem != AST__FREQ) { + target.addToFrequency(specmap, targetSystem, targetRf, vmess); + } + if (step3) { + sorConvert(target, alignTarget, specmap); + } + if (step4 && alignSystem == AST__VREL) { + target.verifyAttrs(vmess, "RestFreq", "astMatch"); + specmap.specAdd("FRTOVL", new double[] {targetRf}); + } + if (step5 && alignSystem == AST__VREL) { + result.verifyAttrs(vmess, "RestFreq", "astMatch"); + specmap.specAdd("VLTOFR", new double[] {resultRf}); + } + if (step6) { + sorConvert(alignResult, result, specmap); + } + if (step7 && resultSystem != AST__FREQ) { + result.addFromFrequency(specmap, resultSystem, resultRf, vmess); + } + + String utarg = target.getUnit(1); + Mapping umap1 = Units.unitMapper(utarg, specMapUnit(targetSystem, "MakeSpecMap", "SpecFrame")); + String ures = result.getUnit(1); + Mapping umap2 = Units.unitMapper(specMapUnit(resultSystem, "MakeSpecMap", "SpecFrame"), ures); + Mapping map2; + if (umap1 != null && umap2 != null) { + map2 = new CmpMap(new CmpMap(umap1, specmap, true), umap2, true); + } else { + map2 = specmap.simplify(); + if (!(map2 instanceof UnitMap) || !ures.equals(utarg)) { + match = false; + if (report) { + String uerr; + int serr; + if (umap1 == null) { + uerr = utarg; + serr = target.systemValue(); + } else { + uerr = ures; + serr = result.systemValue(); + } + throw Ast.err( + AstException.AST__BADUN, + "astMatch(SpecFrame): Inappropriate units (" + uerr + ") specified for a " + + systemLabel(serr) + " axis."); + } + } + } + + double targetOrigin = target.specOriginCur(); + Mapping map1; + if (targetOrigin != 0.0) { + map1 = new CmpMap(new ShiftMap(new double[] {targetOrigin}), map2, true); + } else { + map1 = map2; + } + + double resultOrigin; + if (target.alignSpecOffsetValue() && result.alignSpecOffsetValue()) { + resultOrigin = transformValue(map1, 0.0); + if (resultOrigin == AST__BAD) { + resultOrigin = result.specOriginCur(); + } + } else { + resultOrigin = result.specOriginCur(); + } + if (resultOrigin != 0.0) { + map2 = new CmpMap(map1, new ShiftMap(new double[] {-resultOrigin}), true); + } else { + map2 = map1; + } + Mapping map = map2.simplify(); + return match ? map : null; + } + + /** + * Matches this SpecFrame, a template, against a target (C's {@code Match}, specframe.c): the + * target must pass the Frame tests and have an axis of a SpecFrame, the first of which is + * selected. + */ + @Override + FrameFinder.MatchResult match(Frame target, boolean matchSub) { + FrameFinder.MatchResult parent = super.match(target, matchSub); + if (parent == null) { + return null; + } + int targetNaxes = target.getNaxes(); + int[] pax = new int[1]; + int targetAxis0 = -1; + for (int iaxis = 0; iaxis < targetNaxes; iaxis++) { + if (target.primaryFrame(iaxis + 1, pax) instanceof SpecFrame) { + targetAxis0 = iaxis; + break; + } + } + if (targetAxis0 < 0) { + return null; + } + int[] templateAxes = parent.templateAxes; + int[] targetAxes = parent.targetAxes; + templateAxes[0] = 0; + targetAxes[0] = targetAxis0; + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + if (!target.subFrame(this, 1, targetAxes, templateAxes, map, result)) { + return null; + } + return new FrameFinder.MatchResult(templateAxes, targetAxes, map[0], result[0]); + } + + /** + * Selects axes from this SpecFrame (C's {@code SubFrame}, specframe.c). Selecting the one axis + * gives a SpecFrame, a copy with the template's attributes overlaid, and the Mapping converts + * between the two SpecFrames, aligned in the AlignSystem and AlignStdOfRest of a copy of the + * template (of this SpecFrame if the template is not a SpecFrame or there is none); with a + * SpecFrame template, units that cannot be converted are an error rather than no match. Any + * other selection gives a plain Frame, made from a copy whose Domain, Title, Label, Symbol and + * Unit are set to their values and whose System and AlignSystem are cleared, which clears the + * Title, Label and Symbol again if the System changes (a C quirk, followed here). + * + * @throws AstException with status {@code AST__NOVAL} if UseDefs is false and the StdOfRest, + * or an attribute the conversion needs, is not set, or {@code AST__BADUN} for units that + * cannot be converted + */ + @Override + boolean subFrame( + Frame template, int resultNaxes, int[] targetAxes, int[] templateAxes, Mapping[] map, Frame[] result) { + map[0] = null; + result[0] = null; + boolean match; + if (resultNaxes == 1 && targetAxes[0] == 0) { + SpecFrame res = (SpecFrame) copy(); + result[0] = res; + boolean report = false; + SpecFrame alignFrm; + if (template != null) { + template.overlay(templateAxes, res); + if (template instanceof SpecFrame) { + alignFrm = (SpecFrame) template.copy(); + report = true; + } else { + alignFrm = (SpecFrame) copy(); + } + } else { + verifyAttrs("convert between different spectral systems", "StdOfRest", "astMatch"); + alignFrm = (SpecFrame) copy(); + } + alignFrm.setSystemValue(alignFrm.alignSystemValue()); + alignFrm.setStdOfRestValue(alignFrm.alignStdOfRestValue()); + Mapping m = makeSpecMapping(this, res, alignFrm, report); + match = m != null; + map[0] = m; + } else { + SpecFrame temp = (SpecFrame) copy(); + if (!temp.testDomain()) { + temp.setDomain(temp.getDomain()); + } + if (!temp.testTitle()) { + temp.setTitle(temp.getTitle()); + } + if (!temp.testLabel(1)) { + temp.setLabel(1, temp.getLabel(1)); + } + if (!temp.testSymbol(1)) { + temp.setSymbol(1, temp.getSymbol(1)); + } + if (!temp.testUnit(1)) { + temp.setUnit(1, temp.getUnit(1)); + } + temp.clearSystem(); + temp.clearAlignSystem(); + match = temp.frameSubFrame(template, resultNaxes, targetAxes, templateAxes, map, result); + } + if (!match) { + map[0] = null; + result[0] = null; + } + return match; + } + + /** The Frame class's {@code SubFrame}, for a copy of this SpecFrame. */ + private boolean frameSubFrame( + Frame template, int resultNaxes, int[] targetAxes, int[] templateAxes, Mapping[] map, Frame[] result) { + return super.subFrame(template, resultNaxes, targetAxes, templateAxes, map, result); + } + + // ------------------------------------------------------------------ + // Overlay + // ------------------------------------------------------------------ + + /** + * Overlays the attributes set on this SpecFrame, the template, onto another Frame (C's {@code + * Overlay}, specframe.c). Onto a SpecFrame, a change of System set on the template first clears + * the result's Title, Label and Symbol, and its Unit if the two Systems' default units differ; + * then the Frame attributes are overlaid, and the SpecFrame attributes set on the template, + * SourceVRF before SourceVel. Onto another class of Frame a template with a System set gives + * the Frame attributes of a copy whose System and AlignSystem are cleared, with what that does + * to a SpecFrame: a change of System clears the copy's Title, Label and Symbol, and its Unit + * unless one was used with the default System, so those are not overlaid (a C quirk, followed + * here). + */ + @Override + void overlay(int[] templateAxes, Frame result) { + String method = "astOverlay"; + int oldSystem = result.systemValue(); + int newSystem = systemValue(); + SpecFrame templt = this; + boolean specframe = result instanceof SpecFrame; + if (specframe) { + if (newSystem != oldSystem && testSystem()) { + result.clearTitle(); + if (!defUnit(newSystem, method, astClass()).equals(defUnit(oldSystem, method, result.astClass()))) { + result.clearUnit(1); + } + result.clearLabel(1); + result.clearSymbol(1); + } + } else if (testSystem()) { + templt = (SpecFrame) copy(); + templt.clearSystem(); + templt.clearAlignSystem(); + } + templt.frameOverlay(templateAxes, result); + if (specframe) { + SpecFrame res = (SpecFrame) result; + if (testAlignStdOfRest()) { + res.setAlignStdOfRestValue(alignStdOfRestValue()); + } + if (testAlignSpecOffset()) { + res.setAlignSpecOffsetValue(alignSpecOffsetValue()); + } + if (testRefDec()) { + res.setRefDecValue(refDecValue()); + } + if (testRefRA()) { + res.setRefRaValue(refRaValue()); + } + if (testRestFreq()) { + res.setRestFreqValue(restFreqValue()); + } + if (testSourceSys()) { + res.setSourceSysValue(sourceSysValue()); + } + if (testSourceVRF()) { + res.setSourceVrfValue(sourceVrfValue()); + } + if (testSourceVel()) { + res.setSourceVelValue(sourceVelValue()); + } + if (testStdOfRest()) { + res.setStdOfRestValue(stdOfRestValue()); + } + if (testSpecOrigin()) { + res.setSpecOriginValue(specOriginValue()); + } + } + } + + /** The Frame class's {@code Overlay}, for this SpecFrame or a copy of it. */ + private void frameOverlay(int[] templateAxes, Frame result) { + super.overlay(templateAxes, result); + } + + // ------------------------------------------------------------------ + // String-based attribute access + // ------------------------------------------------------------------ + + /** Whether a name is one of the per-axis Frame attributes allowed without an axis number. */ + private static boolean isOneAxisName(String attrib) { + for (String n : ONE_AXIS_NAMES) { + if (n.equals(attrib)) { + return true; + } + } + return false; + } + + /** The name of a standard of rest code, or the error C's {@code GetAttrib} reports for a corrupt one. */ + private String checkedSorString(int sor, String attribute) { + String s = stdOfRestString(sor); + if (s == null) { + throw Ast.err( + AstException.AST__SCSIN, + "astGetAttrib(" + astClass() + "): Corrupt " + astClass() + " contains invalid " + attribute + + " identification code (" + sor + ")."); + } + return s; + } + + /** C's {@code astChrLen}: the length of a string without trailing white space. */ + private static int chrLen(String s) { + int n = s.length(); + while (n > 0 && CScan.isCSpace(s.charAt(n - 1))) { + n--; + } + return n; + } + + @Override + String getAttrib(String attrib) { + if (isOneAxisName(attrib)) { + return super.getAttrib(attrib + "(1)"); + } else if ("alignstdofrest".equals(attrib)) { + return checkedSorString(alignStdOfRestValue(), "AlignStdOfRest"); + } else if ("alignspecoffset".equals(attrib)) { + return alignSpecOffsetValue() ? "1" : "0"; + } else if ("geolat".equals(attrib)) { + return getAttrib("obslat"); + } else if ("geolon".equals(attrib)) { + return getAttrib("obslon"); + } else if ("refdec".equals(attrib)) { + return refSkyFrame().format(2, refDecValue()); + } else if ("refra".equals(attrib)) { + return refSkyFrame().format(1, refRaValue()); + } else if ("restfreq".equals(attrib)) { + return CFormat.format("%." + DBL_DIG + "g", restFreqValue() * 1.0E-9); + } else if ("sourcevel".equals(attrib)) { + double dval = sourceVelValue(); + if (sourceVelInKms()) { + dval *= 1.0E-3; + } + return CFormat.format("%." + DBL_DIG + "g", dval); + } else if ("specorigin".equals(attrib)) { + return CFormat.format("%." + DBL_DIG + "g", specOriginCur()); + } else if ("sourcevrf".equals(attrib)) { + return checkedSorString(sourceVrfValue(), "SourceVRF"); + } else if ("sourcesys".equals(attrib)) { + int sys = sourceSysValue(); + String s = systemString(sys); + if (s == null) { + throw Ast.err( + AstException.AST__SCSIN, + "astGetAttrib(" + astClass() + "): Corrupt " + astClass() + + " contains invalid SourceSys identification code (" + sys + ")."); + } + return s; + } else if ("stdofrest".equals(attrib)) { + return checkedSorString(stdOfRestValue(), "StdOfRest"); + } + return super.getAttrib(attrib); + } + + /** The error C's {@code SetAttrib} reports for an unknown standard of rest. */ + private AstException badSor(String value) { + return Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Invalid standard of rest description \"" + value + "\"."); + } + + @Override + void setAttrib(String attrib, String value) { + Double dval = CScan.scanDouble(value); + Integer ival = CScan.scanInt(value); + String w = oneWord(value); + if (isOneAxisName(attrib)) { + super.setAttrib(attrib + "(1)", value); + } else if ("alignstdofrest".equals(attrib) && w != null) { + int sor = stdOfRestCode(value); + if (sor == AST__BADSOR) { + throw badSor(value); + } + setAlignStdOfRestValue(sor); + } else if ("geolat".equals(attrib) && CScan.hasWord(value)) { + setAttrib("obslat", value); + } else if ("geolon".equals(attrib) && CScan.hasWord(value)) { + setAttrib("obslon", value); + } else if ("refdec".equals(attrib) && CScan.hasWord(value)) { + double[] dv = {AST__BAD}; + int nc = refSkyFrame().unformat(2, value, dv); + if (nc != chrLen(value)) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Invalid reference declination \"" + value + "\"."); + } + setRefDecValue(dv[0]); + } else if ("refra".equals(attrib) && CScan.hasWord(value)) { + double[] dv = {AST__BAD}; + int nc = refSkyFrame().unformat(1, value, dv); + if (nc != chrLen(value)) { + throw Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Invalid reference right ascension \"" + value + "\"."); + } + setRefRaValue(dv[0]); + } else if ("alignspecoffset".equals(attrib) && ival != null) { + setAlignSpecOffsetValue(ival != 0); + } else if ("restfreq".equals(attrib) && dval != null) { + setRestFreqValue(dval * 1.0E9); + } else if ("restfreq".equals(attrib) && CScan.numberThenWord(value) != null) { + double[] nw = CScan.numberThenWord(value); + setRestFreqValue(restFreqFromUnits(nw[0], value.substring((int) nw[1]))); + } else if ("sourcevel".equals(attrib) && dval != null) { + double v = dval; + if (sourceVelInKms()) { + v *= 1.0E3; + } + setSourceVelValue(v); + } else if ("sourcevrf".equals(attrib) && w != null) { + int sor = stdOfRestCode(value); + if (sor == AST__BADSOR) { + throw badSor(value); + } + setSourceVrfValue(sor); + } else if ("sourcesys".equals(attrib) && w != null) { + setSourceSysValue(systemCode(value)); + } else if ("stdofrest".equals(attrib) && w != null) { + int sor = stdOfRestCode(value); + if (sor == AST__BADSOR) { + throw badSor(value); + } + setStdOfRestValue(sor); + } else if ("specorigin".equals(attrib) && dval != null) { + setSpecOriginValue(toUnits(getUnit(1), dval, "astSetSpecOrigin")); + } else if ("specorigin".equals(attrib) && CScan.numberThenWord(value) != null) { + double[] nw = CScan.numberThenWord(value); + setSpecOriginValue(toUnits(value.substring((int) nw[1]), nw[0], "astSetSpecOrigin")); + } else { + super.setAttrib(attrib, value); + } + } + + /** + * A rest frequency in Hz from a value in units {@code unit} (C's {@code SetAttrib}): a + * frequency converted to Hz, a vacuum wavelength converted to metres and then to a frequency, + * or an energy converted to Joules and then to a frequency. + * + * @throws AstException with status {@code AST__ATTIN} if the units are none of these, or the + * wavelength is zero or bad, or the energy bad + */ + private double restFreqFromUnits(double dval, String unit) { + Mapping umap = Units.unitMapper(unit, "Hz"); + if (umap != null) { + return transformValue(umap, dval); + } + umap = Units.unitMapper(unit, "m"); + if (umap != null) { + double dtemp = transformValue(umap, dval); + if (dtemp != AST__BAD && dtemp != 0.0) { + return SpecMap.AST__C / dtemp; + } + throw Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Invalid rest wavelength \"" + CFormat.format("%g", dval) + " " + + unit + "\" supplied."); + } + umap = Units.unitMapper(unit, "J"); + if (umap != null) { + double dtemp = transformValue(umap, dval); + if (dtemp != AST__BAD) { + return dtemp * (1.0 / SpecMap.AST__H); + } + throw Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Invalid rest energy \"" + CFormat.format("%g", dval) + " " + unit + + "\" supplied."); + } + throw Ast.err( + AstException.AST__ATTIN, + "astSetAttrib(" + astClass() + "): Rest frequency given in an unsupported system of units \"" + + CFormat.format("%g", dval) + " " + unit + "\"."); + } + + @Override + boolean testAttrib(String attrib) { + if (isOneAxisName(attrib)) { + return super.testAttrib(attrib + "(1)"); + } else if ("alignstdofrest".equals(attrib)) { + return testAlignStdOfRest(); + } else if ("geolat".equals(attrib)) { + return testAttrib("obslat"); + } else if ("geolon".equals(attrib)) { + return testAttrib("obslon"); + } else if ("refdec".equals(attrib)) { + return testRefDec(); + } else if ("refra".equals(attrib)) { + return testRefRA(); + } else if ("restfreq".equals(attrib)) { + return testRestFreq(); + } else if ("sourcevel".equals(attrib)) { + return testSourceVel(); + } else if ("sourcevrf".equals(attrib)) { + return testSourceVRF(); + } else if ("sourcesys".equals(attrib)) { + return testSourceSys(); + } else if ("stdofrest".equals(attrib)) { + return testStdOfRest(); + } else if ("specorigin".equals(attrib)) { + return testSpecOrigin(); + } else if ("alignspecoffset".equals(attrib)) { + return testAlignSpecOffset(); + } + return super.testAttrib(attrib); + } + + @Override + void clearAttrib(String attrib) { + if (isOneAxisName(attrib)) { + super.clearAttrib(attrib + "(1)"); + } else if ("alignstdofrest".equals(attrib)) { + clearAlignStdOfRest(); + } else if ("geolat".equals(attrib)) { + clearAttrib("obslat"); + } else if ("geolon".equals(attrib)) { + clearAttrib("obslon"); + } else if ("refdec".equals(attrib)) { + clearRefDec(); + } else if ("refra".equals(attrib)) { + clearRefRA(); + } else if ("restfreq".equals(attrib)) { + clearRestFreq(); + } else if ("sourcevel".equals(attrib)) { + clearSourceVel(); + } else if ("specorigin".equals(attrib)) { + clearSpecOrigin(); + } else if ("alignspecoffset".equals(attrib)) { + clearAlignSpecOffset(); + } else if ("sourcevrf".equals(attrib)) { + clearSourceVRF(); + } else if ("sourcesys".equals(attrib)) { + clearSourceSys(); + } else if ("stdofrest".equals(attrib)) { + clearStdOfRest(); + } else { + super.clearAttrib(attrib); + } + } +} diff --git a/src/main/java/uk/ac/starlink/ast/SpecMap.java b/src/main/java/uk/ac/starlink/ast/SpecMap.java new file mode 100644 index 0000000..d2a2f10 --- /dev/null +++ b/src/main/java/uk/ac/starlink/ast/SpecMap.java @@ -0,0 +1,1104 @@ +package uk.ac.starlink.ast; + +import java.util.ArrayList; +import java.util.List; +import uk.ac.starlink.ast.internal.pal.Pal; + +/** + * A sequence of conversions between standard spectral coordinate systems. + * + *

    A SpecMap is a specialised form of Mapping which can be used to represent a sequence of + * conversions between standard spectral coordinate systems: frequency, wavelength and various forms + * of velocity, and different standards of rest. When first created it performs a unit (null) + * Mapping. {@link #specAdd} then appends coordinate conversion steps, so that multi-step + * conversions between a variety of spectral coordinate systems can be assembled out of a set of + * building blocks. + * + *

    The conversions between standards of rest need the source position as an RA and Dec. It can + * be given as arguments of those conversions, in which case the SpecMap is 1-dimensional, + * transforming only the spectral axis values, and always uses the same source position. That may + * not describe a 3-D spectral cube accurately, since changes of spatial position can change the + * Doppler shift between standards of rest significantly. For that case a 3-dimensional SpecMap + * takes the source RA and Dec from its second and third coordinates, which it copies unchanged from + * input to output, and modifies the first (the spectral axis) appropriately. + * + *

    For details of the individual coordinate conversions available, see {@link #specAdd}. + * + *

    Ported from Rust {@code mappings/specmap.rs} and C {@code specmap.c}. + */ +public class SpecMap extends Mapping { + + /** The speed of light in metres per second, C's {@code AST__C}. */ + static final double AST__C = 2.99792458E8; + + /** Planck's constant in Joule seconds, C's {@code AST__H}. */ + static final double AST__H = 6.6260755E-34; + + /** The astronomical unit in metres that specmap.c converts au/s to m/s with. */ + private static final double AU = 149.597870E9; + + /** + * The conversions a SpecMap can apply: C's conversion codes with their values. Each has its + * string (its name), the comment Dump writes for it, its number of arguments, and the + * descriptions of the values it stores, which are its arguments followed, for a change of rest + * frame, by the frequency correction factor worked out from them (specmap.c {@code + * CvtString}). + */ + enum Cvt { + FRTOVL(1, "Convert frequency to rel. velocity", 1, "Rest frequency (Hz)"), + VLTOFR(2, "Convert rel. velocity to frequency", 1, "Rest frequency (Hz)"), + ENTOFR(3, "Convert energy to frequency", 0), + FRTOEN(4, "Convert frequency to energy", 0), + WNTOFR(5, "Convert wave number to frequency", 0), + FRTOWN(6, "Convert frequency to wave number", 0), + WVTOFR(7, "Convert wavelength (vacuum) to frequency", 0), + FRTOWV(8, "Convert frequency to wavelength (vacuum)", 0), + AWTOFR(9, "Convert wavelength (air) to frequency", 0), + FRTOAW(10, "Convert frequency to wavelength (air)", 0), + VRTOVL(11, "Convert radio to rel. velocity", 0), + VLTOVR(12, "Convert relativistic to radio velocity", 0), + VOTOVL(13, "Convert optical to rel. velocity", 0), + VLTOVO(14, "Convert relativistic to optical velocity", 0), + ZOTOVL(15, "Convert redshift to rel. velocity", 0), + VLTOZO(16, "Convert rel. velocity to redshift", 0), + BTTOVL(17, "Convert beta factor to rel. velocity", 0), + VLTOBT(18, "Convert rel. velocity to beta factor", 0), + USF2HL(19, "Convert from user-defined to heliocentric frequency", 3, Desc.USER), + HLF2US(20, "Convert from heliocentric to user-defined frequency", 3, Desc.USER), + TPF2HL(21, "Convert from Topocentric to heliocentric frequency", 6, Desc.TOPO), + HLF2TP(22, "Convert from Heliocentric to topocentric frequency", 6, Desc.TOPO), + GEF2HL(23, "Convert from Geocentric to heliocentric frequency", 3, Desc.EPOCH), + HLF2GE(24, "Convert from Heliocentric to geocentric frequency", 3, Desc.EPOCH), + BYF2HL(25, "Convert from Barycentric to heliocentric frequency", 3, Desc.EPOCH), + HLF2BY(26, "Convert from Heliocentric to barycentric frequency", 3, Desc.EPOCH), + LKF2HL(27, "Convert from LSRK to heliocentric frequency", 2, Desc.POSITION), + HLF2LK(28, "Convert from Heliocentric to LSRK frequency", 2, Desc.POSITION), + LDF2HL(29, "Convert from LSRD to heliocentric frequency", 2, Desc.POSITION), + HLF2LD(30, "Convert from Heliocentric to LSRD frequency", 2, Desc.POSITION), + LGF2HL(31, "Convert from Local group to heliocentric frequency", 2, Desc.POSITION), + HLF2LG(32, "Convert from Heliocentric to local group frequency", 2, Desc.POSITION), + GLF2HL(33, "Convert from Galactic to heliocentric frequency", 2, Desc.POSITION), + HLF2GL(34, "Convert from Heliocentric to galactic frequency", 2, Desc.POSITION); + + /** C's integer code for the conversion. */ + final int cCode; + + /** The comment Dump writes beside the conversion. */ + final String comment; + + /** The number of arguments the conversion takes. */ + final int nargs; + + /** The descriptions of the stored values, one for each. */ + // The array is private and never modified. + @SuppressWarnings("ImmutableEnumChecker") + private final String[] argdescs; + + Cvt(int cCode, String comment, int nargs, String... argdesc) { + this.cCode = cCode; + this.comment = comment; + this.nargs = nargs; + this.argdescs = argdesc; + } + + /** The number of values stored for the conversion, C's {@code szargs}. */ + int szargs() { + return argdescs.length; + } + + /** The description of stored value {@code i}. */ + String argdesc(int i) { + return argdescs[i]; + } + + /** Whether the conversion is a change of rest frame, which {@code FrameChange} applies. */ + boolean isFrameChange() { + return cCode >= USF2HL.cCode; + } + + /** + * The conversion that undoes this one, as the {@code SWAP_CODES} and {@code SWAP_CODES2} + * macros of specmap.c {@code MapMerge} exchange them: each odd code with the even code + * after it. + */ + Cvt inverse() { + int code = cCode % 2 == 1 ? cCode + 1 : cCode - 1; + for (Cvt c : values()) { + if (c.cCode == code) { + return c; + } + } + throw Ast.err( + AstException.AST__INTER, + "SpecMap: conversion " + this + " has no inverse (internal AST programming error)."); + } + + /** + * The conversion named {@code s}, matched as C's {@code CvtCode} matches it, with {@code + * astChrMatch} (ignoring case and trailing white space), or null if there is none. + */ + static Cvt fromCode(String s) { + for (Cvt c : values()) { + if (chrMatch(s, c.name())) { + return c; + } + } + return null; + } + } + + /** The argument descriptions the changes of rest frame share (specmap.c {@code CvtString}). */ + private static final class Desc { + static final String RA = "RA of source (FK5 J2000, radians)"; + static final String DEC = "DEC of source (FK5 J2000, radians)"; + static final String EPOCH_MJD = "UT1 epoch of observaton (Modified Julian Date)"; + static final String FCORR = "Frequency correction factor"; + + static final String[] USER = {"Velocity offset (m/s)", RA, DEC, FCORR}; + static final String[] TOPO = { + "Longitude (positive eastwards, radians)", + "Latitude (geodetic, radians)", + "Altitude (geodetic, metres)", + EPOCH_MJD, + RA, + DEC, + FCORR + }; + static final String[] EPOCH = {EPOCH_MJD, RA, DEC, FCORR}; + static final String[] POSITION = {RA, DEC, FCORR}; + + private Desc() {} + } + + /** One conversion of the sequence: C's {@code cvttype} and {@code cvtargs}. */ + private static final class Step { + final Cvt cvt; + + /** + * The arguments followed, for a change of rest frame, by the frequency correction factor, + * {@link #AST__BAD} until a 1-dimensional transformation works it out; {@code szargs} in + * all. + */ + final double[] args; + + Step(Cvt cvt, double[] args) { + this.cvt = cvt; + this.args = args; + } + } + + /** + * The parameters that define a reference frame, with intermediate results cached while one + * conversion is applied (specmap.c {@code FrameDef}). A cached value is {@link #AST__BAD}, or + * null, until it is worked out. + */ + private static final class FrameDef { + /** The observer's geodetic altitude (m). */ + double obsalt = AST__BAD; + + /** The observer's geodetic latitude (radians). */ + double obslat = AST__BAD; + + /** The observer's longitude (radians, positive east). */ + double obslon = AST__BAD; + + /** The epoch of observation (UT1 MJD). */ + double epoch = AST__BAD; + + /** The Dec of the reference point (FK5 J2000). */ + double refdec = AST__BAD; + + /** The RA of the reference point (FK5 J2000). */ + double refra = AST__BAD; + + /** The heliocentric velocity of the user-defined system (m/s). */ + double veluser = AST__BAD; + + /** The local apparent sidereal time. */ + double last = AST__BAD; + + /** The mean to apparent parameters. */ + double[] amprms; + + /** The user-defined velocity as an FK5 J2000 vector. */ + double[] vuser; + + /** The Earth-Sun velocity. */ + double[] dvh; + + /** The barycentre-Sun velocity. */ + double[] dvb; + } + + /** The conversions, in the order they were added. */ + private List steps = new ArrayList<>(); + + /** + * Creates a SpecMap with no conversions, which performs a unit Mapping. + * + *

    The nature and units of the values supplied to the SpecMap's first input (its spectral + * input) must suit the first conversion step it applies, and those it gives are set by the + * last: if the first step is "FRTOVL" the input is a frequency in Hz, and if the last is + * "VLTOVO" the output is an optical velocity in metres per second. See {@link #specAdd} for + * the units each conversion expects and gives. + * + * @param nin the number of inputs to the Mapping, which is also the number of outputs: 1, or 3 + * for a SpecMap whose second and third axes give the RA and Dec (FK5 J2000) of the source. + * In either case the first input and output are the spectral axis. In a 3-dimensional + * SpecMap the position replaces the RA and DEC arguments of the conversions between + * standards of rest listed for {@link #specAdd} + * @param flags reserved for future use; should be zero, and has no effect + * @throws AstException with status {@code AST__BADNI} if {@code nin} is neither 1 nor 3 + */ + public SpecMap(int nin, int flags) { + super(checkNin(nin), nin, true, true); + } + + /** C's check in {@code astInitSpecMap}: {@code nin} must be 1 or 3. */ + private static int checkNin(int nin) { + if (nin != 1 && nin != 3) { + // C's message says "1 or 2"; the check is for 1 or 3. + throw Ast.err( + AstException.AST__BADNI, + "astInitSpecMap(SpecMap): Supplied number of SpecMap axes (" + nin + + ") is illegal; it should be 1 or 2. "); + } + return nin; + } + + /** + * Loads a SpecMap from its description, as C's {@code astLoadSpecMap} does: the number of + * conversions, then each conversion's string and every value stored for it, the frequency + * correction factor included, as written, a missing value being {@link #AST__BAD}. + * + * @throws AstException with status {@code AST__BADIN} if a conversion's string is missing or + * names no conversion + */ + SpecMap(NativeNode node) { + super(node); + NativeNode part = node.section("SpecMap"); + int ncvt = Math.max(0, part.readInt("Nspec", 0)); + for (int icvt = 0; icvt < ncvt; icvt++) { + String key = "Spec" + (icvt + 1); + String sval = part.readString(key, null); + if (sval == null) { + throw Ast.err( + AstException.AST__BADIN, + "astRead(Channel): A spectral coordinate conversion type is missing from the input SpecMap" + + " data."); + } + Cvt cvt = Cvt.fromCode(sval); + if (cvt == null) { + throw Ast.err( + AstException.AST__BADIN, + "astRead(Channel): Invalid spectral conversion type \"" + sval + "\" in SpecMap data."); + } + double[] args = new double[cvt.szargs()]; + for (int iarg = 0; iarg < args.length; iarg++) { + args[iarg] = part.readDouble(key + argLetter(iarg), AST__BAD); + } + steps.add(new Step(cvt, args)); + } + } + + /** The letter that follows a conversion's key for argument {@code i}, C's {@code ALPHABET}. */ + private static char argLetter(int i) { + return (char) ('a' + i); + } + + /** Completes a copy as C's {@code Copy} (specmap.c) does, with its own conversions. */ + @Override + void deepCopy() { + super.deepCopy(); + List copied = new ArrayList<>(steps.size()); + for (Step s : steps) { + copied.add(new Step(s.cvt, s.args.clone())); + } + steps = copied; + } + + @Override + String dumpComment() { + return "Conversion between spectral coordinate systems"; + } + + /** + * Writes the number of conversions, set when there are any, then each conversion's string and + * every stored value that is not bad, the frequency correction factor included, as C's {@code + * Dump} (specmap.c) does. + */ + @Override + void dump(NativeNode node) { + super.dump(node); + node.writeIsA("Mapping", "Mapping between coordinate systems"); + int ncvt = steps.size(); + node.writeInt("Nspec", ncvt != 0, false, ncvt, "Number of conversion steps"); + for (int icvt = 0; icvt < ncvt; icvt++) { + Step s = steps.get(icvt); + String key = "Spec" + (icvt + 1); + node.writeString(key, true, true, s.cvt.name(), s.cvt.comment); + for (int iarg = 0; iarg < s.cvt.szargs(); iarg++) { + if (s.args[iarg] != AST__BAD) { + node.writeDouble(key + argLetter(iarg), true, true, s.args[iarg], s.cvt.argdesc(iarg)); + } + } + } + } + + // ------------------------------------------------------------------ + // Adding conversions + // ------------------------------------------------------------------ + + /** + * Adds one of the standard spectral coordinate system conversions listed below to an existing + * SpecMap. + * + *

    When a SpecMap is first created, it simply performs a unit (null) Mapping. By using this + * method repeatedly, one or more coordinate conversion steps may then be added, which the + * SpecMap will perform in sequence. This allows multi-step conversions between a variety of + * spectral coordinate systems to be assembled out of the building blocks provided by this + * class. + * + *

    Normally, if a SpecMap's Invert attribute is zero (the default), then its forward + * transformation is performed by carrying out each of the individual coordinate conversions + * specified by this method in the order given (the most recently added conversion applied + * last). This order is reversed if the SpecMap's Invert attribute is non-zero (or if the + * inverse transformation is requested by any other means) and each individual coordinate + * conversion is also replaced by its own inverse. This process inverts the overall effect of + * the SpecMap. In this case, the first conversion to be applied would be the inverse of the one + * most recently added. + * + *

    When assembling a multi-stage conversion, it can sometimes be difficult to determine the + * most economical conversion path. For example, when converting between reference frames, + * converting first to the heliographic reference frame as an intermediate stage is often + * sensible in formulating the problem, but may introduce unnecessary extra conversion steps. A + * solution to this is to include all the steps which are (logically) necessary, but then to + * simplify the resulting SpecMap. The simplification process will eliminate any steps which + * turn out not to be needed. This method does not check that the sequence of coordinate + * conversions added to a SpecMap is physically meaningful. + * + *

    The conversions (case is not significant), with the arguments each takes in the order they + * are given, are: + * + *

      + *
    • {@code "FRTOVL"} (RF): convert frequency to relativistic velocity; + *
    • {@code "VLTOFR"} (RF): convert relativistic velocity to frequency; + *
    • {@code "ENTOFR"}: convert energy to frequency; + *
    • {@code "FRTOEN"}: convert frequency to energy; + *
    • {@code "WNTOFR"}: convert wave number to frequency; + *
    • {@code "FRTOWN"}: convert frequency to wave number; + *
    • {@code "WVTOFR"}: convert wavelength (vacuum) to frequency; + *
    • {@code "FRTOWV"}: convert frequency to wavelength (vacuum); + *
    • {@code "AWTOFR"}: convert wavelength (air) to frequency; + *
    • {@code "FRTOAW"}: convert frequency to wavelength (air); + *
    • {@code "VRTOVL"}: convert radio to relativistic velocity; + *
    • {@code "VLTOVR"}: convert relativistic to radio velocity; + *
    • {@code "VOTOVL"}: convert optical to relativistic velocity; + *
    • {@code "VLTOVO"}: convert relativistic to optical velocity; + *
    • {@code "ZOTOVL"}: convert redshift to relativistic velocity; + *
    • {@code "VLTOZO"}: convert relativistic velocity to redshift; + *
    • {@code "BTTOVL"}: convert beta factor to relativistic velocity; + *
    • {@code "VLTOBT"}: convert relativistic velocity to beta factor; + *
    • {@code "USF2HL"} (VOFF, RA, DEC): convert frequency from a user-defined reference frame + * to heliocentric; + *
    • {@code "HLF2US"} (VOFF, RA, DEC): convert frequency from heliocentric reference frame + * to user-defined; + *
    • {@code "TPF2HL"} (OBSLON, OBSLAT, OBSALT, EPOCH, RA, DEC): convert frequency from + * topocentric reference frame to heliocentric; + *
    • {@code "HLF2TP"} (OBSLON, OBSLAT, OBSALT, EPOCH, RA, DEC): convert frequency from + * heliocentric reference frame to topocentric; + *
    • {@code "GEF2HL"} (EPOCH, RA, DEC): convert frequency from geocentric reference frame to + * heliocentric; + *
    • {@code "HLF2GE"} (EPOCH, RA, DEC): convert frequency from heliocentric reference frame + * to geocentric; + *
    • {@code "BYF2HL"} (EPOCH, RA, DEC): convert frequency from barycentric reference frame + * to heliocentric; + *
    • {@code "HLF2BY"} (EPOCH, RA, DEC): convert frequency from heliocentric reference frame + * to barycentric; + *
    • {@code "LKF2HL"} (RA, DEC): convert frequency from kinematic LSR reference frame to + * heliocentric; + *
    • {@code "HLF2LK"} (RA, DEC): convert frequency from heliocentric reference frame to + * kinematic LSR; + *
    • {@code "LDF2HL"} (RA, DEC): convert frequency from dynamical LSR reference frame to + * heliocentric; + *
    • {@code "HLF2LD"} (RA, DEC): convert frequency from heliocentric reference frame to + * dynamical LSR; + *
    • {@code "LGF2HL"} (RA, DEC): convert frequency from local group reference frame to + * heliocentric; + *
    • {@code "HLF2LG"} (RA, DEC): convert frequency from heliocentric reference frame to + * local group; + *
    • {@code "GLF2HL"} (RA, DEC): convert frequency from galactic reference frame to + * heliocentric; + *
    • {@code "HLF2GL"} (RA, DEC): convert frequency from heliocentric reference frame to + * galactic. + *
    + * + *

    The units for the values processed by the above conversions are: all velocities, metres + * per second (positive if the source recedes from the observer); frequency, Hertz; all + * wavelengths, metres; energy, Joules; wave number, cycles per metre. + * + *

    The arguments are: RF, the rest frequency (Hz); OBSALT, the geodetic altitude of the + * observer (IAU 1975, metres); OBSLAT, the geodetic latitude of the observer (IAU 1975, + * radians); OBSLON, the longitude of the observer (radians, positive eastwards); EPOCH, the + * epoch of observation (UT1 expressed as a Modified Julian Date); RA, the Right Ascension of the + * source (radians, FK5 J2000); DEC, the Declination of the source (radians, FK5 J2000); VOFF, + * the velocity of the user-defined reference frame, towards the position given by RA and DEC, + * measured in the heliocentric reference frame. + * + *

    If the SpecMap is 3-dimensional, source positions are provided by the values supplied to + * inputs 2 and 3 of the SpecMap (which are simply copied to outputs 2 and 3). Usable values are + * still required for the RA and DEC arguments in order to define the "user-defined" reference + * frame used by USF2HL and HLF2US. However, {@link #AST__BAD} can be supplied for RA and DEC if + * the user-defined reference frame is not required. + * + * @param cvt the conversion, as one of the strings above (case is not significant) + * @param args its arguments, in the order given above; may be null if it takes none + * @throws AstException with status {@code AST__SPCIN} if {@code cvt} names no conversion, or + * {@code AST__TIMIN} if {@code args} does not hold exactly the conversion's number of + * arguments + */ + public void specAdd(String cvt, double[] args) { + Cvt type = Cvt.fromCode(cvt); + if (type == null) { + throw Ast.err( + AstException.AST__SPCIN, + "astAddSpec(" + astClass() + "): Invalid SpecMap spectral coordinate conversion type \"" + cvt + + "\"."); + } + addSpecCvt(type, args == null ? 0 : args.length, args); + } + + /** + * C's {@code AddSpecCvt}: appends conversion {@code type} with its {@code narg} arguments, + * followed by {@link #AST__BAD} in each slot for a value worked out from them later. + * + * @throws AstException with status {@code AST__TIMIN} if {@code narg} is not the conversion's + * number of arguments + */ + private void addSpecCvt(Cvt type, int narg, double[] args) { + if (narg != type.nargs) { + throw Ast.err( + AstException.AST__TIMIN, + "AddSpecCvt(" + astClass() + "): Invalid no. of arguments for spectral coordinate conversion type " + + type.cCode + " - " + narg + " supplied, " + type.nargs + " required."); + } + double[] stored = new double[type.szargs()]; + for (int i = 0; i < stored.length; i++) { + stored[i] = i < type.nargs ? args[i] : AST__BAD; + } + steps.add(new Step(type, stored)); + } + + // ------------------------------------------------------------------ + // Simplification + // ------------------------------------------------------------------ + + /** + * specmap.c {@code MapMerge}. In series, or alone in the list, the SpecMap and the SpecMaps + * with the same number of axes adjacent to it are condensed into one Mapping: their conversions + * are gathered in the order they are applied, each SpecMap's in reverse and each conversion + * exchanged for its inverse where the list applies the SpecMap inverted (a change of rest + * frame having its frequency correction factor reciprocated), and the gathered list is then + * simplified, pass after pass until a pass removes nothing, by removing adjacent pairs of + * mutually inverse conversions whose arguments are equal. If that removed a Mapping or a + * conversion, or the nominated SpecMap is applied inverted, the run is replaced by a UnitMap, + * when no conversion is left, or else by a new SpecMap of the conversions left, applied + * forward, which has none of the frequency correction factors. + */ + @Override + int mapMerge(MergeList list, int where, boolean series) { + if (!series && list.size() != 1) { + return -1; + } + int nin = list.map(where).getNin(); + int nstep0 = ((SpecMap) list.map(where)).steps.size(); + int imap1 = where; + while (imap1 - 1 >= 0 && isSpecMap(list.map(imap1 - 1), nin)) { + nstep0 += ((SpecMap) list.map(imap1 - 1)).steps.size(); + imap1--; + } + int imap2 = where; + while (imap2 + 1 < list.size() && isSpecMap(list.map(imap2 + 1), nin)) { + nstep0 += ((SpecMap) list.map(imap2 + 1)).steps.size(); + imap2++; + } + + List gathered = new ArrayList<>(nstep0); + for (int imap = imap1; imap <= imap2; imap++) { + SpecMap specmap = (SpecMap) list.map(imap); + boolean invert = list.invert(imap); + int ncvt = specmap.steps.size(); + for (int k = 0; k < ncvt; k++) { + Step step = specmap.steps.get(invert ? ncvt - 1 - k : k); + double[] args = step.args.clone(); + Cvt cvt = step.cvt; + if (invert) { + cvt = cvt.inverse(); + if (cvt.isFrameChange()) { + // SWAP_CODES2: the frequency correction factor is reciprocated. + int jarg = cvt.nargs; + double tmp = args[jarg]; + args[jarg] = tmp != AST__BAD && tmp != 0.0 ? 1.0 / tmp : AST__BAD; + } + } + gathered.add(new Step(cvt, args)); + } + } + + boolean done = false; + while (!done) { + int nstep1 = gathered.size(); + List kept = new ArrayList<>(nstep1); + int istep = 0; + while (istep < nstep1) { + boolean keep = true; + if (istep < nstep1 - 1 && cancels(gathered.get(istep), gathered.get(istep + 1))) { + istep++; + keep = false; + } + if (keep) { + kept.add(gathered.get(istep)); + } + istep++; + } + done = kept.size() >= nstep1; + gathered = kept; + } + + int nstep = gathered.size(); + int ngone = imap2 - imap1; + boolean unit = nstep == 0; + boolean simpler = ngone != 0 || nstep < nstep0 || unit || list.invert(where); + if (!simpler) { + return -1; + } + Mapping replacement; + if (unit) { + replacement = new UnitMap(list.map(where).getNin()); + } else { + SpecMap sm = new SpecMap(nin, 0); + for (Step step : gathered) { + sm.addSpecCvt(step.cvt, step.cvt.nargs, step.args); + } + replacement = sm; + } + list.replaceRangeWith(imap1, imap2, replacement); + return imap1; + } + + /** Whether {@code map} is a SpecMap with {@code nin} axes, which specmap.c {@code MapMerge} merges. */ + private static boolean isSpecMap(Mapping map, int nin) { + return map.getClass() == SpecMap.class && map.getNin() == nin; + } + + /** + * Whether {@code s1} followed by {@code s2} is one of the pairs specmap.c {@code MapMerge} + * removes: a conversion and its inverse, in either order, with the arguments the user supplied + * (none, one, two, three or six of them) equal to within {@code astEQUAL}. A frequency + * correction factor, which the user does not supply, is not compared. + */ + private static boolean cancels(Step s1, Step s2) { + if (s1.cvt.inverse() != s2.cvt) { + return false; + } + for (int i = 0; i < s1.cvt.nargs; i++) { + if (!MappingHelpers.astEqual(s1.args[i], s2.args[i])) { + return false; + } + } + return true; + } + + // ------------------------------------------------------------------ + // Transformation + // ------------------------------------------------------------------ + + /** + * Applies the conversions as C's {@code Transform} (specmap.c) does: the output starts as a + * copy of the input, a value that is not finite becoming {@link #AST__BAD}, and each conversion + * in turn (the inverse of each in reverse order for the inverse transformation) updates the + * spectral values in place. A 3-dimensional SpecMap copies its second and third axes, which + * give each point's source position for the changes of rest frame. + */ + @Override + void transformInto(double[][] in, int npoint, boolean forward, double[][] out) { + validateTransformInto(in, npoint, forward, out); + boolean fwd = effectiveForward(forward); + boolean map3d = in.length == 3; + double[] spec = copyAxis(in[0], npoint, out[0]); + double[] alpha = map3d ? copyAxis(in[1], npoint, out[1]) : null; + double[] beta = map3d ? copyAxis(in[2], npoint, out[2]) : null; + int ncvt = steps.size(); + for (int k = 0; k < ncvt; k++) { + Step s = steps.get(fwd ? k : ncvt - 1 - k); + if (!frameChange(s, npoint, alpha, beta, spec, fwd)) { + systemChange(s.cvt, npoint, spec, s.args, fwd); + } + } + } + + /** Copies the first {@code npoint} values of {@code src} to {@code dst}, each bad value as {@link #AST__BAD}. */ + private static double[] copyAxis(double[] src, int npoint, double[] dst) { + for (int i = 0; i < npoint; i++) { + dst[i] = isBad(src[i]) ? AST__BAD : src[i]; + } + return dst; + } + + /** + * C's {@code SystemChange}: changes the {@code np} spectral values in {@code values} between two + * spectral systems with conversion {@code cvt}, or its inverse if {@code forward} is false, + * which is applied as the forward direction of the inverse conversion. + */ + private static void systemChange(Cvt cvt, int np, double[] values, double[] args, boolean forward) { + Cvt c = forward ? cvt : cvt.inverse(); + // MODERN-JAVA(14): switch with arrow labels + switch (c) { + case FRTOVL: + if (args[0] != AST__BAD) { + double temp = args[0] * args[0]; + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double f2 = v * v; + double d = temp + f2; + values[i] = d > 0.0 ? finite(AST__C * ((temp - f2) / d)) : AST__BAD; + } + } + } else { + setBad(values, np); + } + break; + case VLTOFR: + if (args[0] != AST__BAD) { + double temp = args[0]; + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double d = AST__C + v; + if (d != 0.0) { + d = (AST__C - v) / d; + values[i] = d >= 0.0 ? finite(temp * Math.sqrt(d)) : AST__BAD; + } else { + values[i] = AST__BAD; + } + } + } + } else { + setBad(values, np); + } + break; + case ENTOFR: + for (int i = 0; i < np; i++) { + if (values[i] != AST__BAD) { + values[i] /= AST__H; + } + } + break; + case FRTOEN: + for (int i = 0; i < np; i++) { + if (values[i] != AST__BAD) { + values[i] *= AST__H; + } + } + break; + case WNTOFR: + case BTTOVL: + for (int i = 0; i < np; i++) { + if (values[i] != AST__BAD) { + values[i] *= AST__C; + } + } + break; + case FRTOWN: + case VLTOBT: + for (int i = 0; i < np; i++) { + if (values[i] != AST__BAD) { + values[i] /= AST__C; + } + } + break; + case WVTOFR: + case FRTOWV: + for (int i = 0; i < np; i++) { + double v = values[i]; + values[i] = v != AST__BAD && v != 0.0 ? finite(AST__C / v) : AST__BAD; + } + break; + case AWTOFR: + for (int i = 0; i < np; i++) { + double v = values[i]; + values[i] = v != AST__BAD && v != 0.0 ? finite(AST__C / (v * refrac(v))) : AST__BAD; + } + break; + case FRTOAW: + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD && v != 0.0) { + // The vacuum wavelength. Refrac needs the wavelength in air, which is first + // taken to be the vacuum wavelength; each estimate of the air wavelength + // gives a better refractive index for the next. + double temp = AST__C / v; + double w = temp; + for (int iter = 0; iter < 3; iter++) { + w = temp / refrac(w); + if (!Double.isFinite(w)) { + w = AST__BAD; + break; + } + } + values[i] = w; + } else { + values[i] = AST__BAD; + } + } + break; + case VRTOVL: + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double temp = 1.0 - v / AST__C; + temp *= temp; + values[i] = finite(AST__C * (1.0 - temp) / (1.0 + temp)); + } + } + break; + case VLTOVR: + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double temp = AST__C + v; + if (temp != 0.0) { + temp = (AST__C - v) / temp; + values[i] = temp >= 0.0 ? finite(AST__C * (1.0 - Math.sqrt(temp))) : AST__BAD; + } else { + values[i] = AST__BAD; + } + } + } + break; + case VOTOVL: + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double temp = 1.0 + v / AST__C; + temp *= temp; + values[i] = finite(AST__C * (temp - 1.0) / (temp + 1.0)); + } + } + break; + case VLTOVO: + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double temp = AST__C - v; + if (temp != 0.0) { + temp = (AST__C + v) / temp; + values[i] = temp >= 0.0 ? finite(AST__C * (Math.sqrt(temp) - 1.0)) : AST__BAD; + } else { + values[i] = AST__BAD; + } + } + } + break; + case ZOTOVL: + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double temp = 1.0 + v; + temp *= temp; + values[i] = finite(AST__C * (temp - 1.0) / (temp + 1.0)); + } + } + break; + case VLTOZO: + for (int i = 0; i < np; i++) { + double v = values[i]; + if (v != AST__BAD) { + double temp = AST__C - v; + if (temp != 0.0) { + temp = (AST__C + v) / temp; + values[i] = temp >= 0.0 ? finite(Math.sqrt(temp) - 1.0) : AST__BAD; + } else { + values[i] = AST__BAD; + } + } + } + break; + default: + throw Ast.err( + AstException.AST__INTER, + "astTransform(SpecMap): Corrupt SpecMap contains invalid spectral coordinate conversion " + c + + " (internal AST programming error)."); + } + } + + /** {@code v}, or {@link #AST__BAD} if it is not finite (C's {@code astISFINITE} check). */ + private static double finite(double v) { + return Double.isFinite(v) ? v : AST__BAD; + } + + /** Sets the first {@code np} values to {@link #AST__BAD}. */ + private static void setBad(double[] values, int np) { + for (int i = 0; i < np; i++) { + values[i] = AST__BAD; + } + } + + /** + * C's {@code Refrac}: the refractive index of dry air at standard temperature and pressure, at + * wavelength {@code wavelen} in metres, by the formula of FITS-WCS paper III (Greisen et al). + * The wavelength should be the air wavelength, but the vacuum wavelength makes no significant + * difference. + */ + private static double refrac(double wavelen) { + if (wavelen == 0.0) { + return 1.0; + } + // The squared wave number in units of (per um)**2. + double w2 = 1.0E-12 / (wavelen * wavelen); + return 1.0 + 1.0E-6 * (287.6155 + 1.62887 * w2 + 0.01360 * w2 * w2); + } + + /** + * C's {@code FrameChange}: applies to the {@code np} frequencies in {@code freq} the Doppler + * shift of the change of rest frame {@code s}, in direction {@code forward}. + * + *

    With {@code ra} null (a 1-dimensional SpecMap) every frequency is observed at the source + * position in the conversion's arguments, and the frequency correction factor is worked out + * once and kept in the conversion's last argument slot; an unphysical velocity leaves it bad and + * makes every frequency bad. Otherwise each frequency is observed at its own position in {@code + * ra} and {@code dec}, and the inverse negates the velocity correction. + * + * @return false, changing nothing, if {@code s} is not a change of rest frame + */ + private static boolean frameChange(Step s, int np, double[] ra, double[] dec, double[] freq, boolean forward) { + if (!s.cvt.isFrameChange()) { + return false; + } + double[] args = s.args; + FrameDef def = new FrameDef(); + int sign; + int ifcorr; + // MODERN-JAVA(14): switch with arrow labels + switch (s.cvt) { + case USF2HL: + case HLF2US: + def.veluser = args[0]; + def.refra = args[1]; + def.refdec = args[2]; + ifcorr = 3; + break; + case TPF2HL: + case HLF2TP: + def.obslon = args[0]; + def.obslat = args[1]; + def.obsalt = args[2]; + def.epoch = args[3]; + def.refra = args[4]; + def.refdec = args[5]; + ifcorr = 6; + break; + case GEF2HL: + case HLF2GE: + case BYF2HL: + case HLF2BY: + def.epoch = args[0]; + def.refra = args[1]; + def.refdec = args[2]; + ifcorr = 3; + break; + case LKF2HL: + case HLF2LK: + case LDF2HL: + case HLF2LD: + case LGF2HL: + case HLF2LG: + case GLF2HL: + case HLF2GL: + def.refra = args[0]; + def.refdec = args[1]; + ifcorr = 2; + break; + default: + throw Ast.err(AstException.AST__INTER, "FrameChange(SpecMap): unexpected conversion " + s.cvt + "."); + } + // The conversions to heliocentric have odd codes. + sign = s.cvt.cCode % 2 == 1 ? -1 : 1; + + if (ra == null) { + if (args[ifcorr] == AST__BAD) { + // The component of the velocity of the output system away from the source, as + // measured in the input system. If it is positive the output frequency is lower + // than the input frequency. + double v = sign * velocity(s.cvt, def.refra, def.refdec, def); + if (v < AST__C && v > -AST__C) { + args[ifcorr] = Math.sqrt((AST__C - v) / (AST__C + v)); + } + } + double fcorr = args[ifcorr]; + if (fcorr != AST__BAD && fcorr != 0.0) { + double factor = forward ? fcorr : 1.0 / fcorr; + for (int i = 0; i < np; i++) { + if (freq[i] != AST__BAD) { + freq[i] *= factor; + } + } + } else { + setBad(freq, np); + } + } else { + if (!forward) { + sign = -sign; + } + for (int i = 0; i < np; i++) { + if (ra[i] == AST__BAD || dec[i] == AST__BAD || freq[i] == AST__BAD) { + freq[i] = AST__BAD; + } else { + double v = sign * velocity(s.cvt, ra[i], dec[i], def); + if (v < AST__C && v > -AST__C) { + freq[i] *= Math.sqrt((AST__C - v) / (AST__C + v)); + } else { + freq[i] = AST__BAD; + } + } + } + } + return true; + } + + /** + * The component away from the source at {@code ra}, {@code dec} (FK5 J2000, radians) of the + * velocity of the rest frame that change of rest frame {@code cvt} goes to or from, in m/s, + * measured within the heliocentric frame of rest: C's {@code cvtFunc} for the conversion. + */ + private static double velocity(Cvt cvt, double ra, double dec, FrameDef def) { + // MODERN-JAVA(14): switch expression + switch (cvt) { + case USF2HL: + case HLF2US: + return userVel(ra, dec, def); + case TPF2HL: + case HLF2TP: + return topoVel(ra, dec, def); + case GEF2HL: + case HLF2GE: + return geoVel(ra, dec, def); + case BYF2HL: + case HLF2BY: + return baryVel(ra, dec, def); + case LKF2HL: + case HLF2LK: + // The component away from the source of the velocity of the Sun relative to the + // kinematic LSR, negated: the velocity of the LSR away from the source. + return -1000.0 * Pal.rvlsrk(ra, dec); + case LDF2HL: + case HLF2LD: + return -1000.0 * Pal.rvlsrd(ra, dec); + case LGF2HL: + case HLF2LG: + return -1000.0 * Pal.rvlg(ra, dec); + case GLF2HL: + case HLF2GL: + // The velocity of the Sun relative to the dynamical LSR, plus that of the + // dynamical LSR relative to the galactic centre. + return -1000.0 * (Pal.rvlsrd(ra, dec) + Pal.rvgalc(ra, dec)); + default: + throw Ast.err( + AstException.AST__INTER, + "astTransform(SpecMap): conversion " + cvt + + " is not a change of rest frame (internal AST programming error)."); + } + } + + /** C's {@code BaryVel}: the velocity of the Earth-Sun barycentre away from the source. */ + private static double baryVel(double ra, double dec, FrameDef def) { + double[] v = Pal.dcs2c(ra, dec); + if (def.dvb == null) { + double[][] e = Pal.evp(def.epoch, 2000.0); + double[] dvb = e[0]; + double[] dvh = e[2]; + // The barycentric velocity of the Earth becomes the heliocentric velocity of the + // barycentre. + def.dvb = new double[] {dvh[0] - dvb[0], dvh[1] - dvb[1], dvh[2] - dvb[2]}; + } + return -Pal.dvdv(v, def.dvb) * AU; + } + + /** C's {@code GeoVel}: the velocity of the Earth away from the source. */ + private static double geoVel(double ra, double dec, FrameDef def) { + double[] v = Pal.dcs2c(ra, dec); + if (def.dvh == null) { + def.dvh = Pal.evp(def.epoch, 2000.0)[2]; + } + return -Pal.dvdv(v, def.dvh) * AU; + } + + /** + * C's {@code TopoVel}: the velocity of the observer away from the source, the observer's + * velocity relative to the centre of the Earth plus the Earth's relative to the Sun. + */ + private static double topoVel(double ra, double dec, FrameDef def) { + if (def.amprms == null) { + def.amprms = Pal.mappa(2000.0, def.epoch); + } + // The source's apparent RA and Dec. + double[] app = Pal.mapqkz(ra, dec, def.amprms); + if (def.last == AST__BAD) { + def.last = Pal.gmst(def.epoch) + Pal.eqeqx(def.epoch) + def.obslon; + } + double vobs = 1000.0 * rverot(def.obslat, def.obsalt, app[0], app[1], def.last); + double vearth = geoVel(ra, dec, def); + return vobs + vearth; + } + + /** + * C's {@code Rverot}: the component in direction ({@code ra}, {@code da}) (geocentric apparent, + * radians) of the Earth-rotation velocity of an observer at geodetic latitude {@code phi} and + * height {@code h} (m), at local apparent sidereal time {@code st}, in km/s, positive when the + * observer recedes from that direction. PAL's {@code palPvobs} gives au/s with ERFA's au, which + * converts it back. + */ + private static double rverot(double phi, double h, double ra, double da, double st) { + double[] v = Pal.dcs2c(ra, da); + double[] pv = Pal.pvobs(phi, h, st); + return -Pal.dvdv(v, new double[] {pv[3], pv[4], pv[5]}) * (Pal.ERFA_DAU / 1000.0); + } + + /** + * C's {@code UserVel}: the component away from the source of the velocity of the user-defined + * rest frame, whose direction is the reference RA and Dec and whose magnitude, positive when the + * source moves away from the observer, is the user velocity, in the heliocentric rest frame. + */ + private static double userVel(double ra, double dec, FrameDef def) { + if (def.vuser == null) { + def.vuser = new double[] { + def.veluser * Math.cos(def.refra) * Math.cos(def.refdec), + def.veluser * Math.sin(def.refra) * Math.cos(def.refdec), + def.veluser * Math.sin(def.refdec) + }; + } + double[] vb = Pal.dcs2c(ra, dec); + // Negated: the user velocity is positive when the source moves away from the observer. + return -Pal.dvdv(def.vuser, vb); + } + + /** + * The rate of change of the output with respect to the input, as C's {@code Rate} (specmap.c) + * finds it: one for a SpecMap with no conversions; for a 1-dimensional SpecMap whose only + * conversion is between frequency and wavelength, the derivative -c/x^2, which holds in both + * directions, so the Invert attribute is not consulted; and otherwise the numerical estimate of + * the Mapping class. + */ + @Override + double rateAt(double[] at, int ax1, int ax2) { + if (steps.isEmpty()) { + return 1.0; + } + Cvt cvt = steps.get(0).cvt; + if (getNin() != 1 || steps.size() != 1 || (cvt != Cvt.WVTOFR && cvt != Cvt.FRTOWV)) { + return super.rateAt(at, ax1, ax2); + } + return at[0] != AST__BAD ? -AST__C / (at[0] * at[0]) : AST__BAD; + } +} diff --git a/src/main/java/uk/ac/starlink/ast/TimeFrame.java b/src/main/java/uk/ac/starlink/ast/TimeFrame.java index 3f3e77a..a935e9d 100644 --- a/src/main/java/uk/ac/starlink/ast/TimeFrame.java +++ b/src/main/java/uk/ac/starlink/ast/TimeFrame.java @@ -1895,47 +1895,6 @@ private String checkedTimeScaleString(int ts, String attribute) { return s; } - /** Whether a value holds a character that is not white space, as C's {@code "%*s"} needs. */ - private static boolean hasWord(String value) { - for (int i = 0; i < value.length(); i++) { - if (!CScan.isCSpace(value.charAt(i))) { - return true; - } - } - return false; - } - - /** - * C's {@code sscanf( value, " %lg %n%*s %n" )} reading all of the value: a number, then one - * word after white space. Gives the number and the index of the word, or null. - */ - private static double[] numberThenWord(String value) { - int i = 0; - int n = value.length(); - while (i < n && CScan.isCSpace(value.charAt(i))) { - i++; - } - CScan.Num num = CScan.strtod(value, i); - if (num == null) { - return null; - } - i = num.end; - while (i < n && CScan.isCSpace(value.charAt(i))) { - i++; - } - int off = i; - while (i < n && !CScan.isCSpace(value.charAt(i))) { - i++; - } - if (i == off) { - return null; - } - while (i < n && CScan.isCSpace(value.charAt(i))) { - i++; - } - return i == n ? new double[] {num.value, off} : null; - } - /** Sets the TimeOrigin from a date, converted to the System (C's {@code SetAttrib}). */ private void setTimeOriginDate(String value) { double mjd; @@ -1968,16 +1927,16 @@ void setAttrib(String attrib, String value) { "astSetAttrib(" + astClass() + "): Invalid time scale description \"" + value + "\"."); } setAlignTimeScaleValue(ts); - } else if ("clocklat".equals(attrib) && hasWord(value)) { + } else if ("clocklat".equals(attrib) && CScan.hasWord(value)) { setAttrib("obslat", value); - } else if ("clocklon".equals(attrib) && hasWord(value)) { + } else if ("clocklon".equals(attrib) && CScan.hasWord(value)) { setAttrib("obslon", value); } else if ("ltoffset".equals(attrib) && dval != null) { setLtOffset(dval); } else if ("timeorigin".equals(attrib) && dval != null) { setTimeOriginValue(toUnits(getUnit(1), dval, "astSetTimeOrigin")); - } else if ("timeorigin".equals(attrib) && numberThenWord(value) != null) { - double[] nw = numberThenWord(value); + } else if ("timeorigin".equals(attrib) && CScan.numberThenWord(value) != null) { + double[] nw = CScan.numberThenWord(value); double origin; try { origin = toUnits(value.substring((int) nw[1]), nw[0], "astSetTimeOrigin"); diff --git a/src/main/java/uk/ac/starlink/ast/UnitsMapper.java b/src/main/java/uk/ac/starlink/ast/UnitsMapper.java index 6101af0..ee9501c 100644 --- a/src/main/java/uk/ac/starlink/ast/UnitsMapper.java +++ b/src/main/java/uk/ac/starlink/ast/UnitsMapper.java @@ -52,8 +52,8 @@ static Mapping makeMapping(Node tree) { + "' (internal AST programming error)."); } String invexp = UnitsToExpr.makeExp(inv, UnitsToExpr.MATHMAP, true); - throw new UnsupportedOperationException("This conversion of units needs a MathMap, which is not available" - + " (forward \"output_units=" + fwdexp + "\", inverse \"input_units=" + invexp + "\")."); + throw new UnsupportedOperationException("This conversion of units (forward \"output_units=" + fwdexp + + "\", inverse \"input_units=" + invexp + "\") needs MathMap"); } /** diff --git a/src/test/java/uk/ac/starlink/ast/ClassAttrsTest.java b/src/test/java/uk/ac/starlink/ast/ClassAttrsTest.java index 8067731..0b68254 100644 --- a/src/test/java/uk/ac/starlink/ast/ClassAttrsTest.java +++ b/src/test/java/uk/ac/starlink/ast/ClassAttrsTest.java @@ -10,30 +10,42 @@ import uk.ac.starlink.ast.testsupport.ProbeData; /** - * Translation of Rust {@code tests/test_class_attrs.rs}: the class attributes of TimeFrame checked - * against C ({@code oracle/class_attrs.json}, from {@code + * Translation of Rust {@code tests/test_class_attrs.rs}: the class attributes of TimeFrame, + * SpecFrame, DSBSpecFrame and FluxFrame checked against C ({@code oracle/class_attrs.json}, from {@code * tools/oracle_fixtures/class_attrs_probe.c}). The probe applies each {@code ;}-separated setting * to a default object of the class with {@code astSet}, reads every attribute back with {@code * astGetC}, {@code astGetI} or {@code astGetD} and its {@code astTest} result, and dumps the * object; {@link #make} and {@link #mismatch} do the same through the Java API. * - *

    The probe's SpecFrame, DSBSpecFrame and FluxFrame cases are skipped (out of scope), and the - * tests {@code spec_frame_domain_is_cleaned}, {@code dsb_centre_with_no_topocentric_frequency_is_rejected} - * and {@code flux_frame_domain_is_cleaned} are listed in {@code deferred/rust-tests.txt}. + *

    The probe makes its FluxFrame with {@code astFluxFrame( AST__BAD, NULL, " " )}. The test + * {@code flux_frame_domain_is_cleaned} is in {@link FluxFrameTest}, {@code + * spec_frame_domain_is_cleaned} in {@link SpecFrameTest} and {@code + * dsb_centre_with_no_topocentric_frequency_is_rejected} in {@link DSBSpecFrameTest}. */ class ClassAttrsTest { /** Whether the probe's class is one this library provides. */ private static boolean inScope(String cls) { - return "TimeFrame".equals(cls); + return "TimeFrame".equals(cls) + || "SpecFrame".equals(cls) + || "DSBSpecFrame".equals(cls) + || "FluxFrame".equals(cls); } /** A default object of {@code cls} with each {@code ;}-separated setting applied, as the probe does. */ private static Frame make(String cls, String settings) { - if (!"TimeFrame".equals(cls)) { + Frame f; + if ("TimeFrame".equals(cls)) { + f = new TimeFrame(); + } else if ("SpecFrame".equals(cls)) { + f = new SpecFrame(); + } else if ("DSBSpecFrame".equals(cls)) { + f = new DSBSpecFrame(); + } else if ("FluxFrame".equals(cls)) { + f = new FluxFrame(AstObject.AST__BAD, null); + } else { throw new IllegalArgumentException("unexpected class " + cls); } - Frame f = new TimeFrame(); int start = 0; while (start < settings.length()) { int semi = settings.indexOf(';', start); @@ -130,7 +142,7 @@ void everyAttributeMatchesTheCLibrary() { failures.add(what + ": " + e.getMessage()); } } - assertEquals(165, run, "the in-scope cases the C probe recorded"); + assertEquals(165 + 442 + 132 + 72, run, "the in-scope cases the C probe recorded"); assertTrue( failures.isEmpty(), failures.size() + " of " + run + " cases differ:\n" + String.join("\n", failures)); } @@ -159,7 +171,7 @@ void dumpMatchesTheCLibrary() { + "--- C\n" + expected); } } - assertEquals(15, run, "the in-scope dumps the C probe recorded"); + assertEquals(15 + 26 + 11 + 9, run, "the in-scope dumps the C probe recorded"); assertTrue( failures.isEmpty(), failures.size() + " of " + run + " dumps differ:\n" + String.join("\n", failures)); } @@ -182,17 +194,12 @@ void timeFrameDomainIsCleaned() { * astSetC( cmpframe, "Domain", "" )} leaves {@code astTest( cmpframe, "Domain" )} true with the * value {@code ""}, and {@code astSetC( cmpframe, "Title", "" )} leaves {@code astTest( cmpframe, * "Title" )} true. - * - *

    The Rust test joins a TimeFrame and a FluxFrame (out of scope); here the second component - * is a 1-d Frame. The components do not affect these results: the Domain and Title are the - * CmpFrame's own, and cmpframe.c {@code GetDomain} and {@code GetTitle} consult the components - * only when the attribute is not set. */ @Test void cmpFrameDomainIsCleanedAndEmptyIsSet() { TimeFrame a = new TimeFrame(); a.set("System=MJD"); - CmpFrame cf = new CmpFrame(a, new Frame(1)); + CmpFrame cf = new CmpFrame(a, new FluxFrame()); cf.setDomain("my cmp"); assertEquals("MYCMP", cf.getDomain()); cf.setDomain(""); diff --git a/src/test/java/uk/ac/starlink/ast/CmpFrameModuleTest.java b/src/test/java/uk/ac/starlink/ast/CmpFrameModuleTest.java index 1ebb3ad..84846b3 100644 --- a/src/test/java/uk/ac/starlink/ast/CmpFrameModuleTest.java +++ b/src/test/java/uk/ac/starlink/ast/CmpFrameModuleTest.java @@ -26,9 +26,6 @@ * {@code GoodPerm}'s permutation arrays holding axis indices from 0, as C passes them (Rust passes * them from 1). Where C's {@code ComponentMatch} fills only the first entries of an axis list (one * per result axis), only those are compared. - * - *

    The three {@code overlay_template_*} tests overlay a CmpFrame holding a SpecFrame and are - * deferred. */ class CmpFrameModuleTest { @@ -553,4 +550,63 @@ void cloneIsADeepCopy() { assertEquals(cmp.getEpochMjd(), copy.getEpochMjd()); assertEquals(cmp.getDomain(), copy.getDomain()); } + + // ------------------------------------------------------------------ + // Overlay (cmpframe.c Overlay) + // ------------------------------------------------------------------ + + private static SkyFrame skySystem(String system) { + SkyFrame f = new SkyFrame(); + f.setSystem(system); + return f; + } + + private static SpecFrame freq() { + SpecFrame f = new SpecFrame(); + f.setSystem("FREQ"); + return f; + } + + /** + * A CmpFrame template whose components line up with those of a CmpFrame result overlays each + * component onto the corresponding one: the SkyFrame takes the template SkyFrame's System and + * Title. + */ + @Test + void overlayTemplateCleanPartitionCopiesSkyFrameSystem() { + SkyFrame skyTemplate = skySystem("GALACTIC"); + skyTemplate.setTitle("custom-galactic"); + CmpFrame template = new CmpFrame(skyTemplate, freq()); + CmpFrame result = new CmpFrame(skySystem("FK5"), freq()); + template.overlay(new int[] {0, 1, 2}, result); + SkyFrame resultSky = assertInstanceOf(SkyFrame.class, result.decompose()[0]); + assertEquals("GALACTIC", resultSky.getSystem()); + assertEquals("custom-galactic", resultSky.getTitle()); + } + + /** + * A CmpFrame template overlaid onto a Frame that is not a CmpFrame overlays each component onto + * the whole result, with the axes of the other component marked as none (cmpframe.c {@code + * Overlay}). + */ + @Test + void overlayTemplateFallbackNonCmpFrameResult() { + CmpFrame template = new CmpFrame(skySystem("GALACTIC"), freq()); + Frame result = new Frame(template.getNaxes()); + template.overlay(new int[] {0, 1, 2}, result); + assertEquals(template.getNaxes(), result.getNaxes()); + } + + /** + * A permuted template whose axes cross the components of the result is overlaid axis by axis + * rather than component by component. + */ + @Test + void overlayTemplateFallsThroughWhenPartitionUnclean() { + CmpFrame template = new CmpFrame(skySystem("GALACTIC"), freq()); + template.permAxes(new int[] {1, 3, 2}); + CmpFrame result = new CmpFrame(skySystem("FK5"), freq()); + template.overlay(new int[] {0, 1, 2}, result); + assertEquals(3, result.getNaxes()); + } } diff --git a/src/test/java/uk/ac/starlink/ast/ConstructorChecksTest.java b/src/test/java/uk/ac/starlink/ast/ConstructorChecksTest.java index 421d186..fd4bf88 100644 --- a/src/test/java/uk/ac/starlink/ast/ConstructorChecksTest.java +++ b/src/test/java/uk/ac/starlink/ast/ConstructorChecksTest.java @@ -9,8 +9,7 @@ * Translation of Rust {@code tests/test_constructor_checks.rs}: constructors and setters refuse * arguments C refuses, with C's status. * - *

    {@code a_conversion_takes_exactly_its_arguments} is translated for SlaMap and TimeMap; its - * SpecMap part, and the other tests, need classes outside the first phase. + *

    The other tests need classes outside the first phase. */ class ConstructorChecksTest { @@ -38,8 +37,8 @@ void aPolymapTermNeedsARealOutput() { } /** - * slamap.c AddSlaCvt and timemap.c AddTimeCvt: each conversion takes exactly its number of - * arguments, or it is AST__TIMIN. + * slamap.c AddSlaCvt, specmap.c AddSpecCvt and timemap.c AddTimeCvt: each conversion takes + * exactly its number of arguments, or it is AST__TIMIN. */ @Test void aConversionTakesExactlyItsArguments() { @@ -50,6 +49,11 @@ void aConversionTakesExactlyItsArguments() { assertEquals(AstException.AST__TIMIN, e.getStatus()); sla.add("PREC", new double[] {1950.0, 2000.0}); + SpecMap spec = new SpecMap(1, 0); + e = assertThrows(AstException.class, () -> spec.specAdd("FRTOVL", new double[0])); + assertEquals(AstException.AST__TIMIN, e.getStatus()); + spec.specAdd("FRTOVL", new double[] {1.0e11}); + TimeMap time = new TimeMap(); e = assertThrows(AstException.class, () -> time.timeAdd("MJDTOMJD", new double[] {0.0})); assertEquals(AstException.AST__TIMIN, e.getStatus()); diff --git a/src/test/java/uk/ac/starlink/ast/ConvertTest.java b/src/test/java/uk/ac/starlink/ast/ConvertTest.java index 14af10f..3ed720a 100644 --- a/src/test/java/uk/ac/starlink/ast/ConvertTest.java +++ b/src/test/java/uk/ac/starlink/ast/ConvertTest.java @@ -12,12 +12,12 @@ * convert} between Frames. * *

    {@code convert_constant_numerator_units}, {@code convert_domain_gate_blocks_mismatch}, {@code - * find_frame_domain_mismatch_returns_none} and {@code convert_basic_sky_unitmap} run here; the - * last leaves out its {@code astEqual} checks that the base and current Frames of each result are - * the Frames converted, which need {@code astEqual}, outside the first phase. The tests whose - * Frames include a SpecFrame or a Circle are deferred, among them the CmpFrame tests ({@code - * convert_basic_cmp_permmap}, {@code convert_sky_cmp_permmap} and {@code - * find_frame_cmp_needs_widened_axes}), whose CmpFrames hold a SpecFrame. + * find_frame_domain_mismatch_returns_none}, {@code convert_basic_sky_unitmap}, and the CmpFrame + * tests ({@code convert_basic_cmp_permmap}, {@code convert_sky_cmp_permmap} and {@code + * find_frame_cmp_needs_widened_axes}), whose CmpFrames hold a SpecFrame, run here; they leave out + * their {@code astEqual} checks that the base and current Frames of each result are the Frames + * converted, as this library has no {@code astEqual}. The tests whose Frames include a Circle are + * deferred. * *

    {@code aFramesetTriesItsBaseFrameFirst} has no Rust counterpart: it checks the order in which * frameset.c {@code ConvertX} tries a FrameSet's Frames. @@ -37,6 +37,72 @@ private static SkyFrame sky(String system) { return f; } + /** The CmpFrame of a frequency SpecFrame and an FK5 SkyFrame (testconvert.c {@code cf}). */ + private static CmpFrame specSky() { + SpecFrame df = new SpecFrame(); + df.setSystem("FREQ"); + return new CmpFrame(df, sky("FK5")); + } + + private static boolean isPerm(FrameSet fs) { + return fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) instanceof PermMap; + } + + /** + * A plain two-axis Frame converts to and from a CmpFrame of a SpecFrame and a SkyFrame only if + * its Domain is SKY, with a PermMap, as the CmpFrame holds the SkyFrame on axes 2 and 3 + * (testconvert.c Errors 11-26). + */ + @Test + void convertBasicCmpPermmap() { + CmpFrame cf = specSky(); + Frame notSky = new Frame(2); + notSky.setDomain("NOTSKY"); + assertNull(notSky.convert(cf, "")); + assertNull(cf.convert(notSky, "")); + + Frame bf = new Frame(2); + bf.setDomain("SKY"); + FrameSet fs = bf.convert(cf, ""); + assertNotNull(fs, "bf->cf converts"); + assertTrue(isPerm(fs)); + fs = cf.convert(bf, ""); + assertNotNull(fs, "cf->bf converts"); + assertTrue(isPerm(fs)); + } + + /** A SkyFrame converts to and from a CmpFrame holding it with a PermMap. */ + @Test + void convertSkyCmpPermmap() { + SkyFrame sf = sky("FK5"); + CmpFrame cf = specSky(); + FrameSet fs = sf.convert(cf, ""); + assertNotNull(fs, "sf->cf converts"); + assertTrue(isPerm(fs)); + fs = cf.convert(sf, ""); + assertNotNull(fs, "cf->sf converts"); + assertTrue(isPerm(fs)); + } + + /** + * A CmpFrame template is found in a SkyFrame target; a SkyFrame template, whose MinAxes and + * MaxAxes are 2, is not found in the three-axis CmpFrame until they are widened, and then with + * a PermMap. + */ + @Test + void findFrameCmpNeedsWidenedAxes() { + SkyFrame sf = sky("FK5"); + CmpFrame cf = specSky(); + assertNotNull(sf.findFrame(cf, " ")); + assertNull(cf.findFrame(sf, " ")); + SkyFrame sf2 = sky("FK5"); + sf2.setMaxAxes(3); + sf2.setMinAxes(1); + FrameSet fs = cf.findFrame(sf2, " "); + assertNotNull(fs, "widened template matches"); + assertTrue(isPerm(fs)); + } + /** * Converting a plain Frame whose Domain is SKY to a SkyFrame, and the reverse, both give a * UnitMap (testconvert.c Errors 1-8). diff --git a/src/test/java/uk/ac/starlink/ast/DSBSpecFrameReadTest.java b/src/test/java/uk/ac/starlink/ast/DSBSpecFrameReadTest.java new file mode 100644 index 0000000..3880d92 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/DSBSpecFrameReadTest.java @@ -0,0 +1,41 @@ +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_dsbspecframe_read.rs}: a FITS-CLASS header with an IMAGFREQ + * keyword describes its spectral axis with a DSBSpecFrame, whose IF, DSBCentre and SideBand C's + * {@code DSBSetUp} (fitschan.c) sets. The values are those C gives reading the same fixtures and + * picking the spectral axis ({@code astGetC} of DSBCentre, IF and SideBand). + */ +class DSBSpecFrameReadTest { + + /** + * Checks the DSBSpecFrame read from the wcsconv fixture {@code name} with the FITS-CLASS + * encoding, on world axis {@code axis}, against C's values. + */ + private static void assertDsb(String name, int axis, String sideBand, double ifGhz, double centre, double tol) { + FitsChan fc = FitsHeaders.fixture("wcsconv/inputs/" + name); + fc.setEncoding("FITS-CLASS"); + FrameSet fs = FitsHeaders.readFrameSet(fc); + Frame dsb = fs.pickAxes(1, new int[] {axis}, null); + assertEquals("DSBSpecFrame", dsb.astClass()); + assertEquals(sideBand, dsb.getC("SideBand"), "SideBand"); + assertEquals(ifGhz, dsb.getD("IF"), 1e-6, "IF (GHz)"); + assertEquals(centre, dsb.getD("DSBCentre"), tol, "DSBCentre (Hz, source rest frame)"); + } + + @Test + void classWriteBuildsDsbSpecFrame() { + // class-write.head: CTYPE1 = FREQ, with IMAGFREQ. + assertDsb("class-write.head", 1, "USB", -6.459953212758027, 110201354300.00003, 1.0); + } + + @Test + void janBuildsDsbSpecFrame() { + // jan.fits-class: CTYPE3 = FREQ, with IMAGFREQ. + assertDsb("jan.fits-class", 3, "USB", -3.9999795728960574, 220398648224.8721, 10.0); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/DSBSpecFrameTest.java b/src/test/java/uk/ac/starlink/ast/DSBSpecFrameTest.java new file mode 100644 index 0000000..95374ae --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/DSBSpecFrameTest.java @@ -0,0 +1,796 @@ +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.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; +import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.Fixtures; + +/** + * Translation of the tests of Rust {@code tests/test_dsbspecframe.rs} and {@code + * frames/dsbspecframe.rs}: construction and defaults, the SideBand, IF, DSBCentre, AlignSideBand + * and ImagFreq attributes and the units they are given in, the sideband Mappings, conversions + * between DSBSpecFrames and SpecFrames, FrameSet integrity, Overlay, Match and native dumps. + * + *

    The expected values are C's, from a probe run against the pinned C library ({@code + * task-4-probes/dsb_cases.c}; each case is a list of attribute settings, applied as the probe + * applies them), where the Rust tests compare with formulae. Rust sets the topocentric DSBCentre + * in Hz and the IF in Hz directly; here they are given as attributes, in a topocentric frequency + * System in Hz where the DSBCentre is that frequency, and the IF in GHz. + * + *

    Rust's {@code observed_sideband_usb}, {@code observed_sideband_lsb} and {@code + * observed_sideband_lo} test {@code observed_freq}, which C does not have; {@code lo_offset_mapping} + * tests Rust's port of {@code ToLOMapping}, which C never calls, and is translated as the + * conversion to the LO offset C makes with {@code ToLSBMapping}. + */ +class DSBSpecFrameTest { + + /** A topocentric frequency in Hz, the DSBCentre 220 GHz and the IF 4 GHz (the LO 224 GHz). */ + private static final String H = "System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=220e9,IF=4"; + + /** As {@link #H} in GHz. */ + private static final String G = "System=FREQ,StdOfRest=TOPO,DSBCentre=220,IF=4"; + + /** A DSBSpecFrame with the settings applied, as the probe's {@code make} does. */ + private static DSBSpecFrame make(String settings) { + DSBSpecFrame f = new DSBSpecFrame(); + if (!settings.isEmpty()) { + f.set(settings); + } + return f; + } + + /** As {@link #make}, or a SpecFrame for settings starting {@code S:}. */ + private static Frame makeAny(String settings) { + if (settings.startsWith("S:")) { + SpecFrame f = new SpecFrame(); + f.set(settings.substring(2)); + return f; + } + return make(settings); + } + + /** The result of the probe's {@code conv}: the converted value, its inverse, the Mapping class. */ + private static final class Conv { + final double forward; + final double inverse; + final String mapClass; + + Conv(double forward, double inverse, String mapClass) { + this.forward = forward; + this.inverse = inverse; + this.mapClass = mapClass; + } + } + + private static Conv conv(Frame from, Frame to, double x) { + FrameSet fs = from.convert(to, ""); + assertNotNull(fs, "a conversion"); + double y = fs.tran1(1, new double[] {x}, true)[0]; + double z = fs.tran1(1, new double[] {y}, false)[0]; + String cls = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) + .simplify() + .astClass(); + return new Conv(y, z, cls); + } + + private static Conv conv(String a, String b, double x) { + return conv(makeAny(a), makeAny(b), x); + } + + private static void assertConv(String a, String b, double x, double forward, double inverse, String cls) { + Conv c = conv(a, b, x); + assertTrue(CValues.cValueEq(c.forward, forward), "forward: got " + c.forward + ", C gives " + forward); + assertTrue(CValues.cValueEq(c.inverse, inverse), "inverse: got " + c.inverse + ", C gives " + inverse); + assertEquals(cls, c.mapClass, "simplified Mapping"); + } + + private static void assertCEq(double want, double got, String what) { + assertTrue(CValues.cValueEq(got, want), what + ": got " + got + ", C gives " + want); + } + + private static AstException assertFails(int status, Runnable r) { + AstException e = assertThrows(AstException.class, r::run); + assertEquals(status, e.getStatus(), e.getMessage()); + return e; + } + + // ------------------------------------------------------------------ + // Construction and attributes + // ------------------------------------------------------------------ + + @Test + void constructionDefaults() { + DSBSpecFrame f = make("System=FREQ"); + assertEquals("FREQ", f.getC("System")); + assertEquals("LSB", f.getSideBand()); + assertFalse(f.test("SideBand")); + assertFalse(f.getAlignSideBand()); + assertFalse(f.test("AlignSideBand")); + assertEquals("4", f.getC("IF")); + assertFalse(f.test("IF")); + assertEquals(3.0E10, f.dsbCentreValue()); + assertEquals(4.0E9, f.ifValue()); + assertEquals("30000000000", make("System=FREQ,Unit=Hz,StdOfRest=TOPO").getC("DSBCentre")); + assertEquals(1, f.getNaxes()); + } + + /** The SideBand defaults to the observed sideband, LSB for a positive IF and USB otherwise. */ + @Test + void sideBandDefaultFollowsTheSignOfTheIf() { + assertEquals("LSB", make("System=FREQ,IF=4").getSideBand()); + assertEquals("USB", make("System=FREQ,IF=-4").getSideBand()); + assertEquals("USB", make("System=FREQ,IF=0").getSideBand()); + DSBSpecFrame f = make("System=FREQ"); + f.setIfValue(-4.0E9); + assertEquals("USB", f.getSideBand()); + } + + @Test + void explicitSideBandOverridesTheDefault() { + DSBSpecFrame f = make("System=FREQ,IF=4,SideBand=USB"); + assertEquals("USB", f.getSideBand()); + assertTrue(f.test("SideBand")); + } + + @Test + void setDsbCentre() { + DSBSpecFrame f = make("System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=1e11"); + assertEquals("100000000000", f.getC("DSBCentre")); + assertTrue(f.test("DSBCentre")); + assertEquals(1.0E11, f.dsbCentreValue()); + DSBSpecFrame g = make("System=FREQ"); + g.setDsbCentreValue(1.0E11); + assertEquals(1.0E11, g.dsbCentreValue()); + assertTrue(g.testDSBCentre()); + } + + @Test + void setAlignSideBand() { + DSBSpecFrame f = make("System=FREQ"); + assertFalse(f.getAlignSideBand()); + f.set("AlignSideBand=1"); + assertTrue(f.getAlignSideBand()); + assertTrue(f.test("AlignSideBand")); + assertEquals(1, make("System=FREQ,AlignSideBand=2").getI("AlignSideBand")); + } + + /** The names of the sidebands, read ignoring case and white space as C's {@code astChrMatch} reads them. */ + @Test + void sideBandNames() { + String[][] cases = { + {"System=FREQ", "SideBand=USB", "USB"}, + {"System=FREQ", "SideBand=lsb", "LSB"}, + {"System=FREQ", "SideBand=LO", "LO"}, + {"System=FREQ", "SideBand= Lo ", "LO"}, + {"System=FREQ,IF=4", "SideBand=observed", "LSB"}, + {"System=FREQ,IF=4", "SideBand=image", "USB"}, + {"System=FREQ,IF=-4", "SideBand=OBSERVED", "USB"}, + {"System=FREQ,IF=-4", "SideBand=Image", "LSB"}, + }; + for (String[] c : cases) { + DSBSpecFrame f = make(c[0]); + f.set(c[1]); + assertEquals(c[2], f.getC("SideBand"), c[0] + " " + c[1]); + assertTrue(f.test("SideBand")); + } + DSBSpecFrame f = make("System=FREQ"); + AstException e = assertFails(AstException.AST__ATTIN, () -> f.set("SideBand=bogus")); + assertEquals( + "astSetAttrib(DSBSpecFrame): The setting \"sideband=bogus\" is invalid for a DSBSpecFrame.", + e.getMsgText()); + e = assertFails(AstException.AST__BADAT, () -> f.set("SideBand=u sb")); + assertEquals("astSet: The attribute setting \"sideband=u sb\" is invalid for a DSBSpecFrame.", e.getMsgText()); + assertEquals("LSB", f.getC("SideBand")); + assertFalse(f.test("SideBand")); + } + + @Test + void specFrameAttributes() { + DSBSpecFrame f = make("System=VRAD"); + assertEquals("VRAD", f.getSystem()); + f.set("System=FREQ"); + assertEquals("FREQ", f.getSystem()); + f.set("RestFreq=1.42"); + assertEquals(1.4200000000000002, f.getRestFreq()); + assertEquals(1.42E9, f.restFreqValue()); + } + + /** The Domain defaults to DSBSPECTRUM without being set (dsbspecframe.c {@code GetDomain}). */ + @Test + void domainDefaultIsUnset() { + DSBSpecFrame f = make("System=FREQ"); + assertEquals("DSBSPECTRUM", f.getDomain()); + assertFalse(f.test("Domain")); + f.setDomain("FOO"); + assertEquals("FOO", f.getDomain()); + assertTrue(f.test("Domain")); + } + + /** A default Label ends with the SideBand (dsbspecframe.c {@code GetLabel}). */ + @Test + void labelNamesTheSideBand() { + assertEquals("Radio velocity (LO)", make("System=VRAD,SideBand=LO").getLabel(1)); + assertEquals("Frequency (LSB)", make("System=FREQ").getC("Label")); + DSBSpecFrame f = make("System=VRAD,Label(1)=Speed"); + assertEquals("Speed", f.getLabel(1)); + assertTrue(f.test("Label(1)")); + } + + /** DSBSpecFrame does not override Unformat in C; it reads as a Frame does (axis.c). */ + @Test + void unformatBaseContract() { + DSBSpecFrame f = make("System=FREQ"); + double[] v = {0.0}; + assertEquals(8, f.unformat(1, " 12.5 ", v)); + assertEquals(12.5, v[0]); + assertEquals(5, f.unformat(1, "", v)); + assertEquals(AstObject.AST__BAD, v[0]); + assertEquals(11, f.unformat(1, " < b a d > ", v)); + assertEquals(AstObject.AST__BAD, v[0]); + assertEquals(4, f.unformat(1, "12.5xyz", v)); + assertEquals(12.5, v[0]); + assertEquals(0, f.unformat(1, "xyz", v)); + } + + @Test + void ifIsGivenInGhz() { + DSBSpecFrame f = make("System=FREQ,IF=6"); + assertEquals(6.0, f.getIf()); + assertEquals(6.0E9, f.ifValue()); + assertEquals("4", make("System=FREQ,IF=4000 MHz").getC("IF")); + DSBSpecFrame g = make("System=FREQ"); + AstException e = assertFails(AstException.AST__ATTIN, () -> g.set("IF=4 m")); + assertEquals( + "astSetAttrib(DSBSpecFrame): Intermediate frequency given in an inappropriate system of units \"4 m\".", + e.getMsgText()); + assertEquals("4", g.getC("IF")); + assertFalse(g.test("IF")); + } + + /** In a topocentric frequency System the DSBCentre is the stored topocentric frequency. */ + @Test + void dsbCentreRoundTripsTopocentric() { + assertEquals( + "30000000000", + make("System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=3e10").getC("DSBCentre")); + DSBSpecFrame f = make("System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=2.5e10"); + assertEquals("25000000000", f.getC("DSBCentre")); + assertEquals(2.5E10, f.dsbCentreValue()); + } + + /** In another standard of rest the DSBCentre is converted from the stored topocentric frequency. */ + @Test + void dsbCentreInANonTopocentricStandardOfRest() { + DSBSpecFrame f = make("System=FREQ,StdOfRest=TOPO,DSBCentre=30,StdOfRest=LSRK," + + "ObsLat=17.188733853924695,ObsLon=-57.295779513082323,Epoch=2000.0"); + f.setRefPos(null, 1.2, 0.5); + // C's dump gives DSBCen = 29999999999.999996: 30 GHz converted to Hz. + assertEquals(2.9999999999999996E10, f.dsbCentreValue()); + assertCEq(30.002408543763334, f.getD("DSBCentre"), "DSBCentre"); + } + + @Test + void dsbCentreGivenWithUnits() { + assertCEq( + 229.99999999999997, + make("System=FREQ,StdOfRest=TOPO,DSBCentre=230000 MHz").getD("DSBCentre"), + "DSBCentre"); + DSBSpecFrame f = make("System=FREQ,StdOfRest=TOPO"); + AstException e = assertFails(AstException.AST__ATTIN, () -> f.set("DSBCentre=5 m")); + assertEquals( + "astSetAttrib(DSBSpecFrame): Value supplied for attribute \"DSBCentre\" (5 m) uses units which are " + + "inappropriate for the current spectral system (Frequency (Topocentric)).", + e.getMsgText()); + assertEquals(30.000000000000004, f.getD("DSBCentre")); + assertFalse(f.test("DSBCentre")); + } + + /** + * C finds a DSBCentre setting by searching the whole setting for {@code dsbcentre=}, so a + * setting of another attribute whose value holds that text is refused (a C quirk, followed + * here). + */ + @Test + void aSettingHoldingDsbCentreIsRefused() { + DSBSpecFrame f = make("System=FREQ"); + AstException e = assertFails(AstException.AST__ATTIN, () -> f.set("Title=dsbcentre=3")); + assertEquals( + "astSetAttrib(DSBSpecFrame): The setting \"title=dsbcentre=3\" is invalid for a DSBSpecFrame.", + e.getMsgText()); + assertEquals("Frequency", f.getTitle()); + assertFalse(f.test("Title")); + } + + /** Rust {@code tests/test_class_attrs.rs::dsb_centre_with_no_topocentric_frequency_is_rejected}. */ + @Test + void dsbCentreWithNoTopocentricFrequencyIsRejected() { + DSBSpecFrame f = make("System=ZOPT"); + AstException e = assertFails(AstException.AST__ATTIN, () -> f.set("DSBCentre=-1")); + assertEquals( + "astSetAttrib(DSBSpecFrame): The setting \"dsbcentre=-1\" is invalid for a DSBSpecFrame.", + e.getMsgText()); + assertFalse(f.test("DSBCentre")); + assertEquals(3.0E10, f.dsbCentreValue()); + assertCEq(3332.007159764053, f.getD("DSBCentre"), "DSBCentre"); + } + + // ------------------------------------------------------------------ + // ImagFreq and the local oscillator + // ------------------------------------------------------------------ + + @Test + void imagFreq() { + DSBSpecFrame f = make(H + ",SideBand=USB,RestFreq=225,SourceVRF=TOPO,SourceVel=0"); + assertCEq(223.0, f.getD("ImagFreq"), "ImagFreq"); + assertFalse(f.test("ImagFreq")); + } + + /** With no RestFreq set, C uses its default, 1.0E14 Hz. */ + @Test + void imagFreqUsesTheDefaultRestFreq() { + assertCEq(-99931.99334537596, make("").getD("ImagFreq"), "ImagFreq"); + } + + @Test + void imagFreqIsReadOnly() { + DSBSpecFrame f = make("System=FREQ"); + AstException e = assertFails(AstException.AST__NOWRT, () -> f.set("ImagFreq=3")); + assertEquals( + "astSet: The setting \"imagfreq=3\" is invalid for a DSBSpecFrame.\nThis is a read-only attribute.", + e.getMsgText()); + e = assertFails(AstException.AST__NOWRT, () -> f.clear("ImagFreq")); + assertEquals( + "astClear: Invalid attempt to clear the \"imagfreq\" value for a DSBSpecFrame.\n" + + "This is a read-only attribute.", + e.getMsgText()); + assertFalse(f.test("ImagFreq")); + } + + @Test + void loFrequency() { + DSBSpecFrame f = make(H); + assertEquals(224.0E9, f.loValue(null, "astGetLO")); + assertConv( + H + ",SideBand=USB,AlignSideBand=1", + H + ",SideBand=LSB,AlignSideBand=1", + 224.0E9, + 224.0E9, + 224.0E9, + "WinMap"); + } + + /** + * The local oscillator frequency must be at least the size of the IF (dsbspecframe.c {@code + * GetLO}); C reads the DSBCentre for its message after reporting the error, when the getter + * gives its default. + */ + @Test + void loBelowTheIfIsAnError() { + String below = "System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=5e9,IF=-4"; + String message = "astGetImagFreq(DSBSpecFrame): The local oscillator frequency (1e+09 Hz) is too low (less " + + "than the intermediate frequency: 4e+09 Hz).\n This could be caused by a bad value for either " + + "the IF attribute (currently -4e+09 Hz) or the DSBCentre attribute (currently 3e+10 Hz)."; + AstException e = assertFails(AstException.AST__ATTIN, () -> make(below).getD("ImagFreq")); + assertEquals(message, e.getMsgText()); + e = assertFails( + AstException.AST__ATTIN, + () -> conv(below + ",AlignSideBand=1", below + ",SideBand=LSB,AlignSideBand=1", 6.0E9)); + assertEquals(message, e.getMsgText()); + assertFails(AstException.AST__ATTIN, () -> make(below).loValue(null, "astGetImagFreq")); + DSBSpecFrame above = make("System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=5e9,IF=-2"); + assertEquals(3.0E9, above.loValue(null, "astGetLO")); + assertCEq(-99993.99941282728, above.getD("ImagFreq"), "ImagFreq"); + } + + /** With UseDefs false a change of sideband needs the IF and DSBCentre set (dsbspecframe.c {@code GetLO}). */ + @Test + void useDefsRequiresTheIfAndDsbCentre() { + String lsb = "StdOfRest=TOPO,System=FREQ,SideBand=LSB,AlignSideBand=1"; + AstException e = assertFails( + AstException.AST__NOVAL, + () -> conv("StdOfRest=TOPO,System=FREQ,SideBand=USB,AlignSideBand=1,UseDefs=0", lsb, 230.0)); + assertEquals( + "astGetImagFreq(DSBSpecFrame): Cannot create a Mapping to lower sideband.\n" + + "No value has been set for the AST \"IF\" attribute (intermediate frequency).", + e.getMsgText()); + e = assertFails( + AstException.AST__NOVAL, + () -> conv("StdOfRest=TOPO,System=FREQ,SideBand=USB,AlignSideBand=1,IF=4,UseDefs=0", lsb, 230.0)); + assertEquals( + "astGetImagFreq(DSBSpecFrame): Cannot create a Mapping to lower sideband.\n" + + "No value has been set for the AST \"DSBCentre\" attribute (central position of interest).", + e.getMsgText()); + } + + // ------------------------------------------------------------------ + // Sideband Mappings and conversions + // ------------------------------------------------------------------ + + @Test + void sideBandFlipUsbToLsb() { + Mapping m = make(H + ",SideBand=USB").toLsbMapping("astSubFrame"); + assertEquals("WinMap", m.astClass()); + assertCEq(223.0E9, m.tran1(1, new double[] {225.0E9}, true)[0], "LSB"); + assertConv( + H + ",SideBand=USB,AlignSideBand=1", + H + ",SideBand=LSB,AlignSideBand=1", + 225.0E9, + 223.0E9, + 225.0E9, + "WinMap"); + } + + @Test + void sideBandFlipLsbToUsb() { + Mapping m = make(H + ",SideBand=LSB").toUsbMapping("astSubFrame"); + assertEquals("WinMap", m.astClass()); + assertCEq(229.0E9, m.tran1(1, new double[] {219.0E9}, true)[0], "USB"); + assertConv( + H + ",SideBand=LSB,AlignSideBand=1", + H + ",SideBand=USB,AlignSideBand=1", + 219.0E9, + 229.0E9, + 219.0E9, + "WinMap"); + } + + /** The Mapping to the sideband a DSBSpecFrame represents is a UnitMap (dsbspecframe.c {@code ToUSBMapping}). */ + @Test + void sideBandIdentityWhenAlreadyTheTarget() { + Mapping m = make(G + ",SideBand=USB").toUsbMapping("astSubFrame"); + assertInstanceOf(UnitMap.class, m); + assertEquals(225.0E9, m.tran1(1, new double[] {225.0E9}, true)[0]); + assertInstanceOf(UnitMap.class, make(G + ",SideBand=LSB").toLsbMapping("astSubFrame")); + } + + /** Offsets from the LO, to and from each sideband. */ + @Test + void loOffsetMappings() { + assertConv( + H + ",SideBand=USB,AlignSideBand=1", + H + ",SideBand=LO,AlignSideBand=1", + 225.0E9, + 1.0E9, + 225.0E9, + "ShiftMap"); + assertConv( + H + ",SideBand=LO,AlignSideBand=1", + H + ",SideBand=USB,AlignSideBand=1", + 1.0E9, + 225.0E9, + 1.0E9, + "ShiftMap"); + assertConv( + H + ",SideBand=LO,AlignSideBand=1", + H + ",SideBand=LSB,AlignSideBand=1", + 1.0E9, + 223.0E9, + 1.0E9, + "WinMap"); + } + + @Test + void convertDsbToDsbSameSideBand() { + assertConv(G + ",SideBand=USB", G + ",SideBand=USB", 225.0E9, 225.0E9, 225.0E9, "UnitMap"); + } + + @Test + void convertDsbToDsbDifferentSideBandWithAlign() { + assertConv( + H + ",SideBand=USB,AlignSideBand=1", + H + ",SideBand=LSB,AlignSideBand=1", + 225.0E9, + 223.0E9, + 225.0E9, + "WinMap"); + } + + /** Unless both have AlignSideBand set, two DSBSpecFrames align as SpecFrames. */ + @Test + void convertDsbToDsbDifferentSideBandNoAlign() { + assertConv(G + ",SideBand=USB", G + ",SideBand=LSB", 225.0E9, 225.0E9, 225.0E9, "UnitMap"); + assertConv(H + ",SideBand=USB,AlignSideBand=1", H + ",SideBand=LSB", 225.0E9, 225.0E9, 225.0E9, "UnitMap"); + } + + @Test + void convertDsbToSpecFrame() { + assertConv(G + ",SideBand=USB", "S:System=FREQ,StdOfRest=TOPO", 225.0E9, 225.0E9, 225.0E9, "UnitMap"); + assertConv("S:System=FREQ,StdOfRest=TOPO", G + ",SideBand=USB", 225.0E9, 225.0E9, 225.0E9, "UnitMap"); + } + + @Test + void alignmentThroughAFrameSet() { + assertConv( + H + ",SideBand=USB,AlignSideBand=1", + H + ",SideBand=LSB,AlignSideBand=1", + 226.0E9, + 222.0E9, + 226.0E9, + "WinMap"); + } + + @Test + void alignmentOfDsbSpecFramesWithDifferentLos() { + assertConv( + H + ",SideBand=USB,AlignSideBand=1", + "System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=230e9,IF=5,SideBand=USB,AlignSideBand=1", + 225.0E9, + 247.0E9, + 225.0E9, + "ShiftMap"); + } + + /** + * Aligning in sidebands sets the SideBand of the target, which C's {@code SubFrame} reads and + * puts back with its setter while it finds the observed sideband (a C quirk, followed here). + */ + @Test + void anAlignmentInSideBandsSetsTheTargetsSideBand() { + DSBSpecFrame from = make(H + ",AlignSideBand=1"); + DSBSpecFrame to = make(H + ",SideBand=LSB,AlignSideBand=1"); + assertFalse(from.test("SideBand")); + Conv c = conv(from, to, 225.0E9); + assertEquals(225.0E9, c.forward); + assertEquals("UnitMap", c.mapClass); + assertTrue(from.test("SideBand")); + assertTrue(to.test("SideBand")); + + DSBSpecFrame plain = make(H); + conv(plain, make(H + ",SideBand=LSB"), 225.0E9); + assertFalse(plain.test("SideBand")); + } + + /** Setting a DSBSpecFrame attribute through a FrameSet aligns in sidebands (dsbspecframe.c {@code SubFrame}). */ + @Test + void frameSetIntegrityFollowsTheSideBand() { + String[][] cases = { + {H + ",SideBand=USB", "SideBand=LSB", "225.0E9", "223.0E9", "WinMap"}, + {G + ",SideBand=USB", "SideBand=LSB", "225.0", "222.99999999999997", "WinMap"}, + {H + ",SideBand=USB", "IF=5", "225.0E9", "227.0E9", "ShiftMap"}, + {H + ",SideBand=USB", "DSBCentre=230e9", "225.0E9", "245.0E9", "ShiftMap"}, + }; + for (String[] c : cases) { + DSBSpecFrame f = make(c[0]); + FrameSet fs = new FrameSet((Frame) f.copy()); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(1), f); + fs.set(c[1]); + double y = fs.tran1(1, new double[] {Double.parseDouble(c[2])}, true)[0]; + assertCEq(Double.parseDouble(c[3]), y, c[0] + " " + c[1]); + assertEquals( + c[4], + fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) + .simplify() + .astClass(), + c[1]); + } + } + + /** + * A DSBSpecFrame template that does not match a SpecFrame target is cast into a SpecFrame + * and tried again, which fails as well. + */ + @Test + void aTemplateCastIntoASpecFrame() { + SpecFrame target = new SpecFrame(); + target.set("System=FREQ"); + assertNull(target.findFrame(make("System=FREQ,Domain=FOO"), "")); + SpecFrame target2 = new SpecFrame(); + target2.set("System=FREQ,Domain=FOO"); + assertNull(target2.findFrame(make("System=VRAD,Domain=FOO,MinAxes=2,MaxAxes=2"), "")); + Frame cast = make("System=VRAD,SideBand=USB").cast(target); + assertEquals(SpecFrame.class, cast.getClass()); + assertEquals("VRAD", cast.getC("System")); + assertEquals("Radio velocity", cast.getLabel(1)); + } + + // ------------------------------------------------------------------ + // Overlay, Match and picking axes (frames/dsbspecframe.rs) + // ------------------------------------------------------------------ + + @Test + void overlayTemplateCopiesSetAttributes() { + DSBSpecFrame template = make("System=FREQ"); + template.setDsbCentreValue(2.5E10); + template.setIfValue(3.0E9); + template.setSideBandValue(DSBSpecFrame.USB); + template.setAlignSideBandValue(true); + DSBSpecFrame target = make("System=FREQ"); + template.overlay(new int[] {0}, target); + assertEquals(2.5E10, target.dsbCentreValue()); + assertEquals(3.0E9, target.ifValue()); + assertEquals("USB", target.getSideBand()); + assertTrue(target.getAlignSideBand()); + } + + @Test + void overlayTemplateSkipsUnsetAttributes() { + DSBSpecFrame template = make("System=FREQ"); + DSBSpecFrame target = make("System=FREQ"); + target.setDsbCentreValue(7.7E10); + target.setIfValue(1.5E9); + template.overlay(new int[] {0}, target); + assertEquals(7.7E10, target.dsbCentreValue()); + assertEquals(1.5E9, target.ifValue()); + assertFalse(target.testSideBand()); + assertFalse(target.testAlignSideBand()); + } + + /** A DSBSpecFrame template overlays the DSBSpecFrame attributes onto a DSBSpecFrame only. */ + @Test + void overlayOntoASpecFrame() { + DSBSpecFrame template = make("System=VRAD,SideBand=USB,IF=5"); + SpecFrame target = new SpecFrame(); + template.overlay(new int[] {0}, target); + assertEquals("VRAD", target.getSystem()); + } + + @Test + void matchSelf() { + FrameFinder.MatchResult m = make("System=FREQ").match(make("System=FREQ"), false); + assertNotNull(m); + assertEquals(0, m.targetAxes[0]); + assertEquals(0, m.templateAxes[0]); + assertEquals(1, m.result.getNaxes()); + assertInstanceOf(DSBSpecFrame.class, m.result); + } + + /** A DSBSpecFrame template matches a SpecFrame target, as a SpecFrame template does. */ + @Test + void matchAgainstASpecFrameTarget() { + SpecFrame target = new SpecFrame(); + target.set("System=FREQ"); + FrameFinder.MatchResult m = make("System=FREQ").match(target, true); + assertNotNull(m); + assertEquals(SpecFrame.class, m.result.getClass()); + } + + @Test + void matchAgainstAPlainFrameFails() { + assertNull(make("System=FREQ").match(new Frame(1), false)); + } + + @Test + void pickAxesFull() { + Frame f = make("System=FREQ,SideBand=USB").pickAxes(1, new int[] {1}, null); + assertEquals("USB", assertInstanceOf(DSBSpecFrame.class, f).getSideBand()); + assertEquals(1, f.getNaxes()); + } + + // ------------------------------------------------------------------ + // Dumps + // ------------------------------------------------------------------ + + private static final String DUMP_ALL = String.join( + "\n", + " Begin DSBSpecFrame \t# Dual sideband spectral axis", + "# Title = \"Radio velocity, rest frequency = 230 GHz\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"DSBSPECTRUM\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Radio velocity (LO)\" \t# Label for axis 1", + " System = \"VRAD\" \t# Coordinate system type", + "# Uni1 = \"km/s\" \t# Units for axis 1", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + "# SoR = \"Heliocentric\" \t# Standard of rest", + " RstFrq = 230000000000 \t# Rest frequency (Hz)", + " IsA SpecFrame \t# Description of spectral coordinate system", + " DSBCen = 229969822691.80344 \t# Central frequency (Hz topo)", + " IF = -4000000000 \t# Intermediate frequency (Hz)", + " SideBn = \"LO\" \t# Represents offset from LO frequency", + " AlSdBn = 1 \t# Align sidebands?", + " End DSBSpecFrame", + ""); + + private static final String DUMP_SET = String.join( + "\n", + " Begin DSBSpecFrame \t# Dual sideband spectral axis", + "# Title = \"Frequency (Topocentric)\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"DSBSPECTRUM\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Frequency (USB)\" \t# Label for axis 1", + " System = \"FREQ\" \t# Coordinate system type", + "# Uni1 = \"Hz\" \t# Units for axis 1 (Hertz)", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " Unit = \"Hz\" \t# Axis units (Hertz)", + " End Axis", + " IsA Frame \t# Coordinate system description", + " SoR = \"Topocentric\" \t# Standard of rest", + " RstFrq = 220398676500 \t# Rest frequency (Hz)", + " UFreq = \"Hz\" \t# Preferred units for frequency", + " IsA SpecFrame \t# Description of spectral coordinate system", + " DSBCen = 220463127593.87799 \t# Central frequency (Hz topo)", + " IF = -3999979572.89606 \t# Intermediate frequency (Hz)", + " SideBn = \"USB\" \t# Represents upper sideband", + "# AlSdBn = 0 \t# Align sidebands?", + " End DSBSpecFrame", + ""); + + /** Every DSBSpecFrame attribute set: C's dump, read back to the same DSBSpecFrame. */ + @Test + void dumpMatchesTheCLibraryAndReadsBack() { + DSBSpecFrame f = make("System=VRAD,RestFreq=230,DSBCentre=10,IF=-4,SideBand=LO,AlignSideBand=1"); + assertEquals(DUMP_ALL, ChannelText.dump(f)); + DSBSpecFrame back = assertInstanceOf(DSBSpecFrame.class, ChannelText.read(DUMP_ALL)); + assertEquals(DUMP_ALL, ChannelText.dump(back)); + assertEquals(229969822691.80344, back.dsbCentreValue()); + assertEquals(-4.0E9, back.ifValue()); + assertEquals("LO", back.getSideBand()); + assertTrue(back.getAlignSideBand()); + } + + /** Rust's {@code serialization_round_trip}. */ + @Test + void serialisationRoundTrip() { + DSBSpecFrame f = make("System=FREQ,Unit=Hz,StdOfRest=TOPO,DSBCentre=220.463127593878e9," + + "IF=-3.99997957289606,SideBand=USB,RestFreq=220.3986765"); + assertEquals(DUMP_SET, ChannelText.dump(f)); + DSBSpecFrame back = assertInstanceOf(DSBSpecFrame.class, ChannelText.read(DUMP_SET)); + assertEquals(f.dsbCentreValue(), back.dsbCentreValue()); + assertEquals(f.ifValue(), back.ifValue()); + assertEquals("USB", back.getSideBand()); + assertEquals(DUMP_SET, ChannelText.dump(back)); + } + + /** Rust's {@code deserialize_fixture}: C's {@code serialisation/jan-dsb.ast}. */ + @Test + void readsTheCFixture() { + String text = Fixtures.read("serialisation/jan-dsb.ast"); + DSBSpecFrame f = assertInstanceOf(DSBSpecFrame.class, ChannelText.read(text)); + assertEquals("USB", f.getSideBand()); + assertEquals(220463127593.87817, f.dsbCentreValue()); + assertEquals(-3999979572.896057, f.ifValue()); + assertFalse(f.testAlignSideBand()); + assertEquals(text, ChannelText.dump(f)); + } + + /** An unknown SideBand in a dump is refused, as C's loader refuses it. */ + @Test + void loaderRefusesAnUnknownSideBand() { + String text = DUMP_ALL.replace("SideBn = \"LO\"", "SideBn = \"XX\""); + AstException e = assertFails(AstException.AST__ATTIN, () -> ChannelText.read(text)); + assertTrue(e.getMsgText().contains("Invalid SideBand description \"XX\"."), e.getMsgText()); + } + + @Test + void copiesAreIndependent() { + DSBSpecFrame f = make("System=FREQ,IF=4,SideBand=USB"); + DSBSpecFrame g = (DSBSpecFrame) f.copy(); + g.set("SideBand=LO,IF=-3"); + assertEquals("USB", f.getSideBand()); + assertEquals(4.0, f.getIf()); + } + + // ------------------------------------------------------------------ + // jniast accessors + // ------------------------------------------------------------------ + + @Test + void jniastAccessors() { + DSBSpecFrame f = new DSBSpecFrame(); + f.set("System=FREQ,Unit=Hz,StdOfRest=TOPO"); + f.setDsbCentre(2.5E10); + assertEquals(2.5E10, f.getDsbCentre()); + f.setIf(-3.0); + assertEquals(-3.0, f.getIf()); + assertEquals("USB", f.getSideBand()); + f.setSideBand("LO"); + assertEquals("LO", f.getSideBand()); + f.setAlignSideBand(true); + assertTrue(f.getAlignSideBand()); + f.setAlignSideBand(false); + assertFalse(f.getAlignSideBand()); + assertTrue(f.test("AlignSideBand")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/DsbTopoOracleTest.java b/src/test/java/uk/ac/starlink/ast/DsbTopoOracleTest.java new file mode 100644 index 0000000..01e31ff --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/DsbTopoOracleTest.java @@ -0,0 +1,120 @@ +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.List; +import java.util.function.DoubleSupplier; +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_dsb_topo.rs}: the DSBSpecFrame values that pass through + * C's {@code TopoMap} (dsbspecframe.c), checked against C ({@code oracle/dsb_topo.json}, from + * {@code tools/oracle_fixtures/dsb_topo_probe.c}). {@code TopoMap} overlays the DSBSpecFrame onto a + * new SpecFrame, aligns it in the topocentric standard of rest and converts it to a copy set to + * topocentric frequency in Hz, so the SpecOrigin and the alignment settings take part in the + * conversions of the DSBCentre, the ImagFreq and a change of sideband. + */ +class DsbTopoOracleTest { + + /** The probe's per-case settings. */ + private static String settings(String name) { + switch (name) { + case "plain": + return ""; + case "origin": + return "SpecOrigin=229"; + case "align_bary": + return "AlignStdOfRest=BARY"; + case "origin_align_offset": + return "SpecOrigin=229,AlignSpecOffset=1"; + case "origin_align_bary": + return "SpecOrigin=229,AlignStdOfRest=BARY"; + default: + throw new IllegalArgumentException("no case " + name); + } + } + + /** The probe's upper sideband DSBSpecFrame with the case's settings and DSBCentre=230. */ + private static DSBSpecFrame usb(String name) { + DSBSpecFrame f = new DSBSpecFrame(); + f.set("System=FREQ,Unit=GHz,StdOfRest=LSRK,Epoch=2005.0,IF=4,SideBand=USB,AlignSideBand=1"); + f.setRefPos(null, 2.6, 0.35); + String s = settings(name); + if (!s.isEmpty()) { + f.set(s); + } + f.setD("DSBCentre", 230.0); + return f; + } + + /** The value, or null where it raises an error, as the probe's {@code opt} prints None. */ + private static double[] opt(DoubleSupplier v) { + try { + return new double[] {v.getAsDouble()}; + } catch (AstException e) { + return null; + } + } + + /** The points converted from {@code usb} to a copy in the lower sideband, or null on an error. */ + private static double[] toLsb(DSBSpecFrame usb, double[] points) { + try { + DSBSpecFrame lsb = (DSBSpecFrame) usb.copy(); + lsb.set("SideBand=LSB"); + FrameSet fs = usb.convert(lsb, ""); + if (fs == null) { + return null; + } + return fs.tran1(points.length, points, true); + } catch (AstException e) { + return null; + } + } + + private static double[] want(JsonNode v) { + if (v.isNull()) { + return null; + } + if (v.isArray()) { + return new double[] {ProbeData.toDouble(v.get(0)), ProbeData.toDouble(v.get(1))}; + } + return new double[] {ProbeData.toDouble(v)}; + } + + private static boolean same(double[] got, double[] want) { + if (got == null || want == null) { + return got == null && want == null; + } + return CValues.cValuesEq(got, want); + } + + @Test + void topocentricConversionsMatchTheCLibrary() { + JsonNode consts = ProbeData.load("dsb_topo"); + JsonNode p = consts.get("POINTS"); + double[] points = {ProbeData.toDouble(p.get(0)), ProbeData.toDouble(p.get(1))}; + List failures = new ArrayList<>(); + int ran = 0; + for (JsonNode c : consts.get("CASES")) { + String name = c.get(0).asText(); + ran++; + DSBSpecFrame f = usb(name); + double[][] got = {opt(() -> f.getD("DSBCentre")), opt(() -> f.getD("ImagFreq")), toLsb(f, points)}; + for (int i = 0; i < 3; i++) { + double[] wanted = want(c.get(i + 1)); + if (!same(got[i], wanted)) { + failures.add(name + " item " + i + ": got " + Arrays.toString(got[i]) + ", C gives " + + Arrays.toString(wanted)); + } + } + } + assertEquals(5, ran, "the cases the C probe recorded"); + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FindFrameTest.java b/src/test/java/uk/ac/starlink/ast/FindFrameTest.java index 52775c3..2ff7c34 100644 --- a/src/test/java/uk/ac/starlink/ast/FindFrameTest.java +++ b/src/test/java/uk/ac/starlink/ast/FindFrameTest.java @@ -17,8 +17,6 @@ * FrameSet::find_frame(&template, &[])} is {@code findFrame(template, " ")}, and with {@code * &["X"]} it is {@code findFrame(template, "X")}. * - *

    The tests whose Frames include a SpecFrame are deferred. - * *

    {@code matchEndAndPreserveAxesChooseTheAxes} has no Rust counterpart: it checks the axes * frame.c {@code Match} associates under the MatchEnd and PreserveAxes attributes. * @@ -34,6 +32,73 @@ private static Frame named(int naxes, String domain) { return f; } + private static SkyFrame fk5() { + SkyFrame f = new SkyFrame(); + f.setSystem("FK5"); + return f; + } + + private static SpecFrame spec(String system) { + SpecFrame f = new SpecFrame(); + f.setSystem(system); + return f; + } + + /** A CmpFrame template matches a CmpFrame target of the same classes, with all three axes. */ + @Test + void cmpframeMatchAgainstCmpframeTemplate() { + CmpFrame template = new CmpFrame(fk5(), spec("FREQ")); + CmpFrame target = new CmpFrame(fk5(), spec("FREQ")); + FrameFinder.MatchResult m = template.match(target, false); + assertNotNull(m, "CmpFrame matches CmpFrame"); + assertEquals(3, m.result.getNaxes()); + assertEquals(3, m.templateAxes.length); + assertEquals(3, m.targetAxes.length); + } + + /** A SkyFrame template, whose MaxAxes is 2, does not match a three-axis CmpFrame. */ + @Test + void cmpframeMatchWithDefaultMaxAxesFails() { + assertNull(fk5().match(new CmpFrame(fk5(), spec("FREQ")), false)); + } + + /** With MaxAxes 3, a SkyFrame template finds the SkyFrame inside a CmpFrame. */ + @Test + void cmpframeMatchAgainstSkyframeTemplateWithMaxAxes() { + SkyFrame template = fk5(); + template.setMaxAxes(3); + template.setMinAxes(2); + FrameFinder.MatchResult m = template.match(new CmpFrame(fk5(), spec("FREQ")), false); + assertNotNull(m, "the SkyFrame template finds the CmpFrame's SkyFrame"); + assertEquals(2, m.result.getNaxes()); + } + + /** A SpecFrame template finds the spectral axis of a CmpFrame of a SkyFrame and a SpecFrame. */ + @Test + void findFrameSpecframeTemplateIntoCmpframeSkySpec() { + SpecFrame template = spec("VRAD"); + template.setStdOfRest("LSRK"); + template.setUnit(1, "m/s"); + template.setMinAxes(1); + template.setMaxAxes(3); + FrameSet result = new CmpFrame(fk5(), spec("FREQ")).findFrame(template, ""); + assertNotNull(result, "the SpecFrame template matches the CmpFrame's SpecFrame"); + Frame current = result.getFrame(FrameSet.AST__CURRENT); + assertEquals(1, current.getNaxes()); + assertInstanceOf(SpecFrame.class, current); + } + + /** The SpecFrame is found whichever axes of the CmpFrame it has. */ + @Test + void findFrameSpecframeTemplateIntoCmpframeSpecSky() { + SpecFrame template = spec("VRAD"); + template.setMinAxes(1); + template.setMaxAxes(3); + FrameSet result = new CmpFrame(spec("FREQ"), fk5()).findFrame(template, ""); + assertNotNull(result, "the SpecFrame template matches regardless of component order"); + assertEquals(1, result.getFrame(FrameSet.AST__CURRENT).getNaxes()); + } + @Test void findFrameBasicSelf() { Frame target = new Frame(2); diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java index b6309f9..b4750e4 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanAstwarnTest.java @@ -18,9 +18,6 @@ *

    C's {@code Warn} (fitschan.c:35453) stores its cards in front of the current card (from * fitschan.c:35590), and during a read the current card is the last {@code NAXIS} that C's * {@code DistortMaps} looked up with {@code astGetFitsF} (fitschan.c:9019). - * - *

    Listed in {@code deferred/rust-tests.txt}: {@code - * badctype_warning_names_the_legal_ctype_and_precedes_naxis1} (a spectral axis, SpecFrame). */ class FitsChanAstwarnTest { @@ -318,4 +315,39 @@ void strictSweepWarningIsAnError() { assertEquals(before, fc.toHeader()); assertEquals(1, fc.getCard()); } + + /** A one-axis air wavelength header whose {@code -A2F} code names the wrong P system. */ + private static final String ONE_AXIS_BADCTYPE = String.join( + "\n", + "SIMPLE = T / Fits standard", + "BITPIX = -32 / Bits per pixel", + "NAXIS = 1 / Number of dimensions", + "NAXIS1 = 1024 / Length of axis", + "CTYPE1 = 'AWAV-A2F' / Air wavelength sampled, expressed as frequency", + "CRVAL1 = 5.000E-07 / Reference air wavelength (metres)", + "CRPIX1 = 512.500 / Reference pixel", + "CDELT1 = 1.000E-10 / Wavelength increment (metres)", + "CUNIT1 = 'm ' / Axis units", + "RESTFRQ = 5.996E+14 / Rest frequency (Hz)", + "SPECSYS = 'BARYCENT' / Spectral reference frame", + ""); + + @Test + void badctypeWarningNamesTheLegalCtypeAndPrecedesNaxis1() { + FitsChan fc = FitsChan.fromHeader(ONE_AXIS_BADCTYPE); + assertNotNull(fc.read()); + // The text and wrapping of C's cards, from the wcsconv fixture expected/awav-a2f.native. + assertEquals( + Arrays.asList( + " ", + "The spectral CTYPE value AWAV-A2F is not legal - using ", + "AWAV-A2A instead.", + " "), + FitsHeaders.astwarnValues(fc)); + // A one-axis header parks C's card cursor on NAXIS1, so the block precedes it. + List kws = FitsHeaders.keywords(fc); + int firstWarn = kws.indexOf("ASTWARN"); + int naxis1 = kws.indexOf("NAXIS1"); + assertTrue(firstWarn >= 0 && firstWarn < naxis1, "the block precedes NAXIS1: " + kws); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanAxisCountOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanAxisCountOracleTest.java index ae9ae3d..acc0eb4 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanAxisCountOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanAxisCountOracleTest.java @@ -29,8 +29,8 @@ * gives a FrameSet, nothing or an error, Ncard after the read, the names of the cards left, the * number of axes of each Frame, and the current Frame's position for pixel (2, 3, 4, ...). * - *

    The cases in {@link #EXCLUDED} have a spectral axis, which needs SpecFrame; each must still - * stop there. + *

    The case in {@link #EXCLUDED} has a {@code -LOG} spectral axis, which C maps with a MathMap; + * it must still stop there. */ class FitsChanAxisCountOracleTest { @@ -39,16 +39,7 @@ class FitsChanAxisCountOracleTest { private static Map exclusions() { Map m = new LinkedHashMap<>(); - for (String name : Arrays.asList( - "three_ctypes", - "wcsaxes3_npix2", - "alt_fewer_axes", - "spec_log_crval0", - "spec_unknown_code", - "spec_x2p_unknown_x", - "spec_log")) { - m.put(name, "needs SpecFrame"); - } + m.put("spec_log", "needs MathMap"); return m; } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java index 84d1f73..e84a6e4 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanCInlineTest.java @@ -16,6 +16,7 @@ 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.FreshThread; /** * Translation of Rust {@code tests/test_fitschan_c_inline.rs}: checks made inline in {@code main()} @@ -26,10 +27,9 @@ * 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}). + *

    Listed in {@code deferred/rust-tests.txt}: {@code log_spectral_axis_writes_freq_log}, whose + * FrameSet is built with a MathMap, and {@code show_fits_succeeds} (jniast has no {@code + * showFits}). */ class FitsChanCInlineTest { @@ -396,6 +396,37 @@ void sipHeaderDoesNotWriteAsFitsWcs() { assertEquals(244, fc.getNcard()); } + /** + * 14-19: a header whose alternate description C is malformed fails to read unless + * IgnoreBadAlt is set, when it gives the other four Frames; with the BadAlt warning enabled + * the read warns once. + */ + @Test + void alternateAxesWithABadSet() { + String alt = Fixtures.root().resolve("programs/testfitschan/alt.header").toString(); + FitsChan fc = new FitsChan(); + fc.setI("Clean", 0); + assertEquals(0, fc.getI("IgnoreBadAlt"), "Error 14"); + fc.setC("SourceFile", alt); + fc.clear("Card"); + AstException e = assertThrows(AstException.class, fc::read, "Error 15"); + assertEquals(AstException.AST__BDFTS, e.getStatus(), "Error 15: " + e.getMessage()); + + fc.setI("IgnoreBadAlt", 1); + assertEquals(1, fc.getI("IgnoreBadAlt"), "Error 16"); + fc.emptyFits(); + fc.setC("SourceFile", alt); + fc.clear("Card"); + assertEquals(4, FitsHeaders.readFrameSet(fc).getNframe(), "Error 18"); + + fc.emptyFits(); + fc.setC("SourceFile", alt); + fc.setWarnings("BadAlt"); + fc.clear("Card"); + fc.read(); + assertEquals(1, fc.warnings().mapSize(), "Error 19"); + } + /** The header of the AZEL test (630-633), without its MJD-OBS. */ private static final String[] AZEL_SOURCE = { "SIMPLE = T", @@ -423,9 +454,18 @@ void sipHeaderDoesNotWriteAsFitsWcs() { /** * 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. + * + *

    The conversion to AZEL takes the LAST from C's tables of values already computed, which + * any earlier conversion for the same observer fills (as reading {@code alt.header} does), and + * the values expected are those of a C probe that started with empty tables. The tables are + * kept per thread, so the check runs in a new thread, whose tables are empty. */ @Test - void azelWritesAsFitsWcs() { + void azelWritesAsFitsWcs() throws InterruptedException { + FreshThread.assertPasses(FitsChanCInlineTest::azelWritesAsFitsWcsWithEmptyLastTables); + } + + private static void azelWritesAsFitsWcsWithEmptyLastTables() { FrameSet fs = readCards(AZEL_SOURCE); fs.setC("System", "AZEL"); assertEquals(RT_OK, roundtrip(fs, "FITS-WCS", 1e-3, "CTYPE", "AZ---TAN"), "Error 630-633"); @@ -623,4 +663,83 @@ void dateAndObservatoryWriteBack() { List got = FitsHeaders.foundCards(wfc); assertTrue(FitsHeaders.cardsMatchC(got, want), String.join("\n", got)); } + + /** + * testfitschan.c's spectral FrameSet: a GRID axis mapped by a ZoomMap of {@code zoom} to a + * SpecFrame with {@code attrs}, its System then set to {@code newSys} through the FrameSet, + * and its Unit to {@code newUnit} unless that is null. + */ + private static FrameSet specFrameSet(String attrs, double zoom, String newSys, String newUnit) { + SpecFrame spec = new SpecFrame(); + spec.set(attrs); + Frame pixel = new Frame(1); + pixel.setDomain("GRID"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__CURRENT, new ZoomMap(1, zoom), spec); + if (newSys != null) { + fs.setC("System", newSys); + } + if (newUnit != null) { + fs.setC("Unit(1)", newUnit); + } + return fs; + } + + /** + * 600-609: linear SpecFrames in six Systems, and pixel axes linear in FREQ written as VOPT and + * WAVE, round-trip through FITS-WCS with C's CTYPE1. + */ + @Test + void spectralSystemsThroughFitsWcs() { + String[][] linear = { + {"System=FREQ,Unit=Hz,StdOfRest=Barycentric,RestFreq=1.4204e9 Hz", "FREQ"}, + {"System=WAVE,Unit=m,StdOfRest=Barycentric,RestFreq=5.996e14 Hz", "WAVE"}, + {"System=VRAD,Unit=m/s,StdOfRest=LSRK,RestFreq=1.4204e9 Hz", "VRAD"}, + {"System=VOPT,Unit=m/s,StdOfRest=Barycentric,RestFreq=1.4204e9 Hz", "VOPT"}, + {"System=ZOPT,Unit= ,StdOfRest=Barycentric,RestFreq=1.4204e9 Hz", "ZOPT"}, + {"System=BETA,Unit= ,StdOfRest=Barycentric,RestFreq=1.4204e9 Hz", "BETA"}, + }; + double[] zooms = {1.0e6, 1.0e-10, 1000.0, 1000.0, 1.0e-6, 1.0e-6}; + for (int i = 0; i < linear.length; i++) { + FrameSet fs = specFrameSet(linear[i][0], zooms[i], null, null); + assertEquals( + RT_OK, + roundtrip(fs, "FITS-WCS", 1e-3, "CTYPE1", linear[i][1]), + "Error " + (600 + i) + ": " + linear[i][1]); + } + String freq = "System=FREQ,Unit=Hz,StdOfRest=Barycentric,RestFreq=1.4204e9 Hz"; + assertEquals( + RT_OK, + roundtrip(specFrameSet(freq, 1.0e6, "VOPT", null), "FITS-WCS", 1e-3, "CTYPE1", "VOPT-F2W"), + "Error 606-607"); + assertEquals( + RT_OK, + roundtrip(specFrameSet(freq, 1.0e6, "WAVE", "m"), "FITS-WCS", 1e-3, "CTYPE1", "WAVE-F2W"), + "Error 608-609"); + } + + /** + * 650-655, 660-665: SpecFrames whose pixel axis is linear in one System, written in another, + * give C's non-linear FITS-WCS algorithm codes and read back. + */ + @Test + void nonLinearSpectralWrites() { + Object[][] cases = { + {"System=WAVE,Unit=m", 1.0e-10, "WAVN", "1/m", 1e-3, "WAVN-W2F", 650}, + {"System=FREQ,Unit=Hz", 1.0e6, "AWAV", "m", 1e-3, "AWAV-F2A", 652}, + {"System=VELO,Unit=m/s", 1000.0, "BETA", null, 1e-3, "BETA", 654}, + {"System=FREQ,Unit=Hz", 1.0e6, "VELO", "m/s", 1e-3, "VELO-F2V", 660}, + {"System=AWAV,Unit=m", 1.0e-10, "FREQ", "Hz", 0.1, "FREQ-A2F", 662}, + {"System=VELO,Unit=m/s", 1000.0, "FREQ", "Hz", 1e-3, "FREQ-V2F", 664}, + }; + for (Object[] c : cases) { + FrameSet fs = specFrameSet( + c[0] + ",StdOfRest=Barycentric,RestFreq=1.4204e9 Hz", (Double) c[1], (String) c[2], (String) c[3]); + int err = (Integer) c[6]; + assertEquals( + RT_OK, + roundtrip(fs, "FITS-WCS", (Double) c[4], "CTYPE1", (String) c[5]), + "Error " + err + "-" + (err + 1) + ": " + c[5]); + } + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanClassTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanClassTest.java new file mode 100644 index 0000000..790e56c --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanClassTest.java @@ -0,0 +1,86 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import org.junit.jupiter.api.Test; + +/** + * Translation of Rust {@code tests/test_fitschan_class.rs}: the celestial projection of FrameSets + * read from FITS-CLASS headers. The expected projections are those C gives reading the same + * headers ({@code astGetC} of Projection on the SkyFrame {@code astFindFrame} finds in the current + * Frame). + */ +class FitsChanClassTest { + + /** + * A FITS-CLASS header whose celestial CTYPEs have no projection code; DELTAV and a VELO-xxx + * keyword make the encoding guessed FITS-CLASS. + */ + private static final String CLASS_BLANK_PROJECTION = String.join( + "\n", + "SIMPLE = T", + "BITPIX = -32", + "NAXIS = 3", + "NAXIS1 = 1024", + "NAXIS2 = 1", + "NAXIS3 = 1", + "CTYPE1 = 'FREQ '", + "CTYPE2 = 'RA-- '", + "CTYPE3 = 'DEC- '", + "CRVAL1 = 0.0", + "CRVAL2 = 40.738", + "CRVAL3 = 62.933", + "CRPIX1 = 512.500", + "CRPIX2 = 0.5", + "CRPIX3 = 0.5", + "CDELT1 = 39062.5", + "CDELT2 = -0.0100", + "CDELT3 = 0.0100", + "EQUINOX = 2000.0", + "RADESYS = 'FK5 '", + "RESTFREQ= 1.102013543E11", + "VELO-OBS= 2500.0", + "DELTAV = -106.266", + ""); + + /** Galactic celestial axes with an explicit {@code -GLS} projection code. */ + private static final String EXPLICIT_GLS = String.join( + "\n", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CTYPE1 = 'GLON-GLS'", + "CTYPE2 = 'GLAT-GLS'", + "CRVAL1 = 10.0", + "CRVAL2 = 20.0", + "CRPIX1 = 50.5", + "CRPIX2 = 50.5", + "CDELT1 = -0.01", + "CDELT2 = 0.01", + ""); + + /** The Projection of the SkyFrame in the current Frame of the FrameSet {@code header} reads as. */ + private static String projection(String header) { + FrameSet fs = FitsHeaders.readFrameSet(FitsChan.fromHeader(header)); + Frame cur = fs.getFrame(FrameSet.AST__CURRENT); + SkyFrame template = new SkyFrame(); + template.setMaxAxes(100); + FrameSet found = cur.findFrame(template, ""); + assertNotNull(found, "a SkyFrame in the current Frame"); + return found.getC("Projection"); + } + + @Test + void blankClassProjectionKeepsTheGlsDescription() { + // C's ClassTrans gives a blank projection code -GLS; SpecTrans translates -GLS to -SFL only + // when the projection it took from the CTYPE values before ClassTrans ran was -GLS, so the + // WcsMap is a GLS one, described as sinusoidal. + assertEquals("sinusoidal", projection(CLASS_BLANK_PROJECTION)); + } + + @Test + void explicitGlsProjectionBecomesSfl() { + assertEquals("Sanson-Flamsteed", projection(EXPLICIT_GLS)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java index c026d6f..6d3a302 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanCursorOracleTest.java @@ -37,11 +37,9 @@ * *

    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}, + * and writes need only the classes of this library. A read or write that stops at an out-of-scope + * class (such as {@code needs MathMap}) 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. */ @@ -50,14 +48,8 @@ class FitsChanCursorOracleTest { /** 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 read, are not excluded, and whose reads - * need only the encodings read here. - */ - private static final int RUNNABLE = 247; - - /** 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 number of cases run here: those that are not excluded. */ + private static final int RUNNABLE = 257; /** * The start of the reason of a case whose transcript hangs on the last bit of an elementary @@ -75,18 +67,6 @@ class FitsChanCursorOracleTest { private static Map excludedCases() { Map m = new LinkedHashMap<>(); - // Headers with a spectral axis, whose FITS-WCS read builds a SpecFrame. - for (String name : Arrays.asList( - "dist_sip_axis3", - "dist_zpx_three", - "sao_three_ctypes", - "iwc_on_spectral", - "iwc_off_spectral", - "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). @@ -610,7 +590,6 @@ void excludedReadCasesStillDiffer() throws IOException { @Test void cardFunctionsMatchTheCLibrary() throws IOException { List failed = new ArrayList<>(); - List waitingCases = new ArrayList<>(); int run = 0; for (JsonNode c : ProbeData.load("fitschan_cursor").get("CASES")) { List ops = ops(c); @@ -625,12 +604,8 @@ void cardFunctionsMatchTheCLibrary() throws IOException { } catch (UnsupportedOperationException e) { assertTrue(uses(ops, READS), name + ": " + e.getMessage()); String reason = Deferred.unavailableReason(e.getMessage()); - if (reason != null && reason.startsWith("encoding ") && !"encoding FITS-WCS".equals(reason)) { - waitingCases.add(name + " (" + reason + ")"); - } else { - failed.add(name + ": the read stops (" + e.getMessage() + "); list it in EXCLUDED with \"" + reason - + "\""); - } + failed.add(name + ": the read stops (" + e.getMessage() + "); list it in EXCLUDED with \"" + reason + + "\""); continue; } run++; @@ -647,10 +622,6 @@ void cardFunctionsMatchTheCLibrary() throws IOException { } assertTrue(failed.isEmpty(), String.join("\n\n", failed)); assertEquals(RUNNABLE, run, "cases run"); - assertEquals( - WAITING_FOR_ANOTHER_ENCODING, - waitingCases.size(), - "cases waiting for the read of another encoding: " + waitingCases); } /** diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsOracleTest.java index 8f9ba5d..c90cccc 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsOracleTest.java @@ -9,12 +9,12 @@ 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.FreshThread; import uk.ac.starlink.ast.testsupport.ProbeData; /** @@ -30,31 +30,21 @@ * {@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. + *

    Every encoding's column runs. A write that stops for want of a class or an encoding this + * library does not have would be in {@link #EXCLUDED}, by header and encoding, with the reason it + * gives, measured, so the list is checked both ways; the header's other writes are compared. No + * write stops so. */ class FitsChanEncodingsOracleTest { - /** Headers whose read stops for want of a class, with the reason the read gives. */ + /** + * Writes that stop for want of a class, keyed by header and encoding ({@code "

    + * "}), with the reason they give. + */ 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); + return Collections.emptyMap(); } /** @@ -164,41 +154,49 @@ private static Written written(List header, String epoch, String enc) { 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); - } + /** + * The probe makes every case's writes in order in one process, and the FITS-CLASS writes + * convert the reference point to azimuth and elevation with the LAST from SkyFrame's tables of values + * already computed, which the earlier cases' conversions fill; the tables are kept per thread, + * so the writes run in the probe's order on a new thread, whose tables are empty, as the + * probe's were. + */ + @Test + void writesMatchC() throws InterruptedException { + FreshThread.assertPasses(FitsChanEncodingsOracleTest::compareWrites); } - @Test - void writesMatchC() { + /** Every case's writes, in the probe's order, compared with C's. */ + private static void compareWrites() { 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(); + String key = name + " " + enc; + String listed = EXCLUDED.get(key); + String needs = null; + Written got = null; + try { + got = written(header, epoch, enc); + } catch (UnsupportedOperationException e) { + needs = FitsHeaders.outOfScope(e); + } + if (needs != null || listed != null) { + if (needs == null || !needs.equals(listed)) { + failed.add(key + ": the write gives \"" + needs + "\" but it is listed as \"" + listed + "\""); + } + continue; + } 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) @@ -215,6 +213,6 @@ void writesMatchC() { } } assertTrue(failed.isEmpty(), String.join("\n", failed)); - assertEquals(7 * (25 - EXCLUDED.size()), run, "writes run, seven encodings for each header"); + 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 index 1969cbe..2cc4184 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanEncodingsTest.java @@ -1,19 +1,20 @@ package uk.ac.starlink.ast; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; 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 + * a header of each encoding, and the FrameSets the FITS-IRAF, FITS-PC, FITS-CLASS 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). + * deferred/rust-tests.txt}: {@code + * freq_log_builds_log_mapping} (a {@code -LOG} spectral axis, which C maps with a MathMap) and + * {@code grism_builds_grism_mapping} (a {@code -GRI} axis, which C maps with a GrismMap). */ class FitsChanEncodingsTest { @@ -72,6 +73,14 @@ void readIrafProducesFrameSet() { assertEquals(2, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); } + @Test + void readClassProducesFrameSet() { + // A spectral axis and two celestial axes. + FrameSet fs = read("wcsconv/inputs/class-write.head", "FITS-CLASS"); + assertEquals(2, fs.getNframe()); + assertEquals(3, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + } + @Test void readPcProducesFrameSet() { FrameSet fs = read("wcsconv/inputs/pc-sparse.head", "FITS-PC"); @@ -93,4 +102,14 @@ void pcFrameSetHasSky() { void dssFrameSetHasSky() { assertSky(read("wcsconv/expected/dss.dss", "DSS"), "FK5"); } + + @Test + void readAipsSpectral() { + // A one-axis spectral header read with the FITS-AIPS encoding: the pixel Frame and the + // SpecFrame. + FrameSet fs = read("wcsconv/inputs/velo-aips.head", "FITS-AIPS"); + assertEquals(2, fs.getNframe()); + assertEquals(1, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + assertInstanceOf(SpecFrame.class, fs.getFrame(FrameSet.AST__CURRENT)); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java index 67b3d54..6a0cc3d 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanErrorsTest.java @@ -5,7 +5,6 @@ import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; @@ -28,7 +27,8 @@ * counterpart, since none of those is excluded. * *

    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}) + * that encoding, which must refuse it, and to FITS-WCS, which must accept it, as C does. A case + * whose read or write 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. @@ -36,31 +36,18 @@ class FitsChanErrorsTest { /** - * Cases that do not match C, each with why: {@code needs } where the read stops at an - * out-of-scope class, otherwise the gap the case exposes. + * Cases that do not match C, each with why: {@code needs } where the read or write + * stops at an out-of-scope class, otherwise the gap the case exposes. */ private static final Map EXCLUDED = excludedCases(); private static Map excludedCases() { Map m = new LinkedHashMap<>(); - // A spectral CTYPE is reached after the celestial axes are decoded (C WcsMapFrm calls - // WcsSpectral after WcsCelestial), so these reads stop at the SpecFrame before C's error - // or warning is checked. - for (String name : Arrays.asList( - "distortion-sip-on-axis3", - "noctype-missing", - "aips-reject-wave", - "aips++-reject-wave", - "aips-reject-topocent", - "aips++-reject-topocent", - "error-unknown-spectral-algorithm")) { - m.put(name, "needs SpecFrame"); - } return Collections.unmodifiableMap(m); } /** The number of cases run: every case of C's table but those excluded. */ - private static final int RUNNABLE = 27; + private static final int RUNNABLE = 34; private static String text(JsonNode c, String field) { JsonNode v = c.get(field); @@ -164,15 +151,20 @@ private static String check(JsonNode c) { 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"; + try { + 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"; + } + } catch (UnsupportedOperationException e) { + String reason = Deferred.unavailableReason(e.getMessage()); + return "write " + (reason == null ? "unavailable" : reason) + ": " + e.getMessage(); } } return null; @@ -229,7 +221,9 @@ void excludedCasesStillDiffer() { String err = check(c); if (err == null) { problems.add(e.getKey() + " now matches C; remove it from EXCLUDED. Reason on record: " + e.getValue()); - } else if (e.getValue().startsWith("needs ") && !err.startsWith("read " + e.getValue() + ":")) { + } else if (e.getValue().startsWith("needs ") + && !err.startsWith("read " + e.getValue() + ":") + && !err.startsWith("write " + e.getValue() + ":")) { problems.add(e.getKey() + " is excluded as \"" + e.getValue() + "\" but gives: " + err); } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanNativeKeywordTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanNativeKeywordTest.java index f656221..7608ea3 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanNativeKeywordTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanNativeKeywordTest.java @@ -12,10 +12,10 @@ * keyword-card form of the NATIVE encoding ({@code BEGAST_xx}, {@code ENDAST_xx} and data-keyword * cards). * - *

    Of the four headers, {@code polco.head} and {@code polco2.head} hold a MathMap and {@code - * specflux.head} a SpecFrame, classes out of scope, so {@code polco_loads}, {@code polco2_loads} - * and {@code specflux_loads} are listed in {@code deferred/rust-tests.txt}, and {@code - * native_read_consumes_its_cards} is translated for {@code timeplot.head} only. + *

    {@code polco.head} and {@code polco2.head} hold a MathMap, a class out of scope, so {@code + * polco_loads} and {@code polco2_loads} are listed in {@code deferred/rust-tests.txt}, and {@code + * native_read_consumes_its_cards} is translated for {@code specflux.head} and {@code + * timeplot.head}. */ class FitsChanNativeKeywordTest { @@ -23,6 +23,12 @@ private static FitsChan header(String name) { return FitsChan.fromHeader(Fixtures.read("wcsconv/inputs/" + name)); } + @Test + void specfluxLoads() { + AstObject obj = header("specflux.head").read(); + assertNotNull(obj, "specflux.head: read returned null"); + } + @Test void timeplotLoads() { AstObject obj = header("timeplot.head").read(); @@ -38,9 +44,11 @@ void timeplotLoads() { */ @Test void nativeReadConsumesItsCards() { - FitsChan fc = header("timeplot.head"); - assertTrue(fc.getNcard() > 0, "no cards to start with"); - assertNotNull(fc.read(), "read returned null"); - assertEquals(1, fc.getNcard(), "cards left after a NATIVE read"); + for (String name : new String[] {"specflux.head", "timeplot.head"}) { + FitsChan fc = header(name); + assertTrue(fc.getNcard() > 0, name + ": no cards to start with"); + assertNotNull(fc.read(), name + ": read returned null"); + assertEquals(1, fc.getNcard(), name + ": cards left after a NATIVE read"); + } } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanReadChainOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanReadChainOracleTest.java index fa72c99..11b3cd8 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanReadChainOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanReadChainOracleTest.java @@ -25,8 +25,8 @@ * Mapping C simplified ({@code WcsMapFrm} returns {@code astSimplify} of it). Each case is compared * with C's whole dump. * - *

    The cases in {@link #EXCLUDED} have a spectral axis (SpecFrame) or a {@code -LOG} axis (which - * C maps with a MathMap); each must still stop there. + *

    The cases in {@link #EXCLUDED} have a {@code -LOG} axis (which C maps with a MathMap); each + * must still stop there. */ class FitsChanReadChainOracleTest { @@ -35,7 +35,6 @@ class FitsChanReadChainOracleTest { private static Map exclusions() { Map m = new LinkedHashMap<>(); - m.put("spectral_and_linear", "needs SpecFrame"); m.put("other_log", "needs MathMap"); m.put("other_log_and_linear", "needs MathMap"); return m; diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java index fbf4068..f097a96 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanReadTest.java @@ -15,9 +15,8 @@ * WcsOthers}. * *

    Listed in {@code deferred/rust-tests.txt}: {@code log_suffix_is_stripped_from_the_domain_and_symbol} - * (a {@code -LOG} axis, which C maps with a MathMap), {@code dsb_centre_prefers_axref_over_crval} - * (a DSBSpecFrame) and {@code unset_system_still_leaves_system_unset} (a constructor of the Rust - * port's own). + * (a {@code -LOG} axis, which C maps with a MathMap) and {@code + * unset_system_still_leaves_system_unset} (a constructor of the Rust port's own). */ class FitsChanReadTest { @@ -286,4 +285,35 @@ void aNaxisBeyondTheWcsAxesIsNotRead() { "CDELT1 = 0.25"); assertEquals(0.5, fs.tran1(1, new double[] {3.0}, true)[0]); } + + /** A topocentric FREQ axis with IMAGFREQ, which makes a DSBSpecFrame. */ + private static final String DSB_FREQ = String.join( + "\n", + "NAXIS = 1", + "NAXIS1 = 10", + "CTYPE1 = 'FREQ'", + "CUNIT1 = 'Hz'", + "CRPIX1 = 1", + "CRVAL1 = 2.30E11", + "CDELT1 = 1.0E6", + "SPECSYS = 'TOPOCENT'", + "IMAGFREQ= 2.40E11", + ""); + + /** The DSBCentre of the DSBSpecFrame read from {@code header}, in Hz. */ + private static double dsbCentreOf(String header) { + Frame f = currentFrame(header); + assertInstanceOf(DSBSpecFrame.class, f, "current Frame is a " + f.astClass()); + return ((DSBSpecFrame) f).getDsbCentre(); + } + + /** + * C's {@code WcsSpectral} takes the observation centre from AXREF when the header has one, and + * from CRVAL otherwise; the values are those C reports for the same two headers. + */ + @Test + void dsbCentrePrefersAxrefOverCrval() { + assertEquals(2.30e11, dsbCentreOf(DSB_FREQ)); + assertEquals(2.32e11, dsbCentreOf(DSB_FREQ + "AXREF1 = 2.32E11\n")); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanSpecUnitOracleTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanSpecUnitOracleTest.java new file mode 100644 index 0000000..c6d277b --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanSpecUnitOracleTest.java @@ -0,0 +1,133 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +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.Map; +import java.util.TreeMap; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_fitschan_spec_unit_oracle.rs}: how a FITS-WCS write + * describes a spectral axis, against C's {@code SpectralAxes} ({@code + * oracle/fitschan_spec_unit.json}, from {@code tools/oracle_fixtures/fitschan_spec_unit_probe.c}): + * the default reference value is the middle of the spectral range when the size of the spectral + * pixel axis is known and its first pixel otherwise, and a spectral Unit that is not linearly + * related to the default Unit is cleared first. + * + *

    Each case reads a frequency cube, optionally sets the Unit of its spectral axis, and writes it + * to a FitsChan holding the case's NAXIS cards; the value the write returns and the cards written + * are compared with C's. + * + *

    The read of the cube is checked for every case. A case can stop at something not available: + * a logarithmic Unit set through the FrameSet needs the MathMap that converts to it ({@code needs + * MathMap}). Such cases are listed with their reason in {@link #UNAVAILABLE}, and the list is checked both ways: a listed case must stop with the reason + * listed, and every other case must match C. + */ +class FitsChanSpecUnitOracleTest { + + /** The cube every case reads. */ + private static final String[] HEADER = { + "NAXIS = 3", + "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", + }; + + /** The cases that stop at something not available, with the reason ({@code needs }). */ + private static final Map UNAVAILABLE = unavailableCases(); + + private static Map unavailableCases() { + Map m = new TreeMap<>(); + m.put("unit_log", "needs MathMap"); + m.put("unit_log_no_dims", "needs MathMap"); + return Collections.unmodifiableMap(m); + } + + /** The FrameSet read from {@link #HEADER}: a CmpFrame of the SkyFrame and a SpecFrame. */ + private static FrameSet readCube() { + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.chan(HEADER)); + Frame cur = fs.getFrame(FrameSet.AST__CURRENT); + assertInstanceOf(CmpFrame.class, cur); + assertInstanceOf(SpecFrame.class, cur.primaryFrame(3, new int[1])); + assertEquals("LSRK", cur.getC("StdOfRest(3)")); + return fs; + } + + /** + * The value the write returns followed by the cards written, or, for a case that stops at + * something not available, the reason, from {@code needs} on. + */ + private static List written(String unit, String dims) { + FrameSet fs = readCube(); + FitsChan out = new FitsChan(); + out.setEncoding("FITS-WCS"); + for (String card : dims.split("~", -1)) { + if (!card.isEmpty()) { + out.putFits(card, false); + } + } + int ret; + try { + if (!unit.isEmpty()) { + fs.setUnit(3, unit); + } + ret = out.write(fs); + } catch (UnsupportedOperationException e) { + String msg = e.getMessage(); + int at = msg.lastIndexOf("needs "); + assertTrue(at >= 0, msg); + List reason = new ArrayList<>(); + reason.add(msg.substring(at)); + return reason; + } + List got = new ArrayList<>(); + got.add(Integer.toString(ret)); + got.addAll(FitsHeaders.foundCards(out)); + return got; + } + + @Test + void spectralAxesMatchC() { + List failed = new ArrayList<>(); + Map stopped = new TreeMap<>(); + for (JsonNode c : ProbeData.load("fitschan_spec_unit").get("CASES")) { + String name = c.get(0).asText(); + List got = written(c.get(1).asText(), c.get(2).asText()); + if (got.size() == 1 && got.get(0).startsWith("needs ")) { + stopped.put(name, got.get(0)); + continue; + } + List want = new ArrayList<>(); + want.add(Integer.toString(c.get(3).asInt())); + for (JsonNode card : c.get(4)) { + want.add(card.asText()); + } + if (!got.equals(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(UNAVAILABLE, stopped, "the cases that stop at something not available"); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanTimeTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanTimeTest.java new file mode 100644 index 0000000..e3f5caa --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsChanTimeTest.java @@ -0,0 +1,135 @@ +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 java.util.List; +import java.util.Locale; +import org.junit.jupiter.api.Test; + +/** + * Translation of Rust {@code tests/test_fitschan_time.rs}: the DUT1 and DTAI values a FITS-WCS read + * sets on the world Frame (C's {@code WcsMapFrm}), and the TELESCOP condition on reading DTAI at + * all (C's {@code WcsFcRead} uses it only for JCMT and UKIRT). + * + *

    The header has a spectral axis as well as the celestial pair, so the world Frame is a + * CmpFrame: C sets the values on the SkyFrame in {@code WcsSkyFrame} and on the whole world Frame + * in {@code WcsMapFrm}, and only a compound Frame tells the two apart. The NATIVE dump of the + * FrameSet shows a CmpFrame's own value as a card just after its {@code BEGAST} card. + */ +class FitsChanTimeTest { + + /** The (FREQ, RA, Dec) header, with an optional TELESCOP card and DTAI value. */ + private static String header(String telescop, Double dtai) { + StringBuilder text = new StringBuilder(String.join( + "\n", + "NAXIS1 = 100 / Spectral axis", + "NAXIS2 = 100 / Spatial axis", + "NAXIS3 = 100 / Spatial axis", + "CTYPE1 = 'FREQ ' / Frequency axis", + "CTYPE2 = 'RA---TAN' / Right Ascension", + "CTYPE3 = 'DEC--TAN' / Declination", + "CRVAL1 = 3.4500E+11 / Reference frequency (Hz)", + "CRVAL2 = 83.633 / Reference RA (deg)", + "CRVAL3 = 22.014 / Reference Dec (deg)", + "CRPIX1 = 50.0 / Reference pixel", + "CRPIX2 = 50.5 / Reference pixel", + "CRPIX3 = 50.5 / Reference pixel", + "CDELT1 = 6.1035E+04 / Frequency increment (Hz)", + "CDELT2 = -0.0002778 / Degrees/pixel", + "CDELT3 = 0.0002778 / Degrees/pixel", + "CUNIT1 = 'Hz ' / Frequency units", + "CUNIT2 = 'deg ' / Angular units", + "CUNIT3 = 'deg ' / Angular units", + "RADESYS = 'FK5 ' / Reference frame", + "EQUINOX = 2000.0 / Equinox", + "SPECSYS = 'LSRK ' / Spectral reference frame", + "RESTFRQ = 3.4506E+11 / Rest frequency (Hz)", + "LONPOLE = 180.000 / Native longitude of celestial pole", + "LATPOLE = 22.014 / Native latitude of celestial pole", + "DUT1 = 0.001 / UT1-UTC in days", + "")); + if (telescop != null) { + text.append(String.format(Locale.ROOT, "TELESCOP= '%-8s' / Telescope name\n", telescop)); + } + if (dtai != null) { + text.append(String.format(Locale.ROOT, "DTAI = %.3f / TAI-UTC in seconds\n", dtai)); + } + return text.toString(); + } + + private static FrameSet read(String text) { + return FitsHeaders.readFrameSet(FitsChan.fromHeader(text)); + } + + /** The world Frame read from {@code text}, which is a CmpFrame. */ + private static Frame topFrame(String text) { + Frame frame = read(text).getFrame(FrameSet.AST__CURRENT); + assertInstanceOf(CmpFrame.class, frame); + return frame; + } + + /** + * Whether the first card of the NATIVE dump of the FrameSet read from {@code text} whose + * keyword starts with {@code prefix} lies just after the CmpFrame's {@code BEGAST} card, so + * that it is the CmpFrame's own value. + */ + private static boolean cmpFrameCarries(String text, String prefix) { + FitsChan out = new FitsChan(); + out.setEncoding("NATIVE"); + out.write(read(text)); + List lines = FitsHeaders.headerLines(out); + int begast = -1; + int first = -1; + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + if (begast < 0 && line.contains("'CmpFrame'")) { + begast = i; + } + if (first < 0 && line.startsWith(prefix)) { + first = i; + } + } + assertTrue(begast >= 0, "the dump holds a CmpFrame: " + lines); + assertTrue(first >= 0, "the dump holds a " + prefix + " card: " + lines); + return first < begast + 5; + } + + @Test + void dtaiSetOnWorldFrameForJcmt() { + String text = header("JCMT", 37.0); + Frame frame = topFrame(text); + assertTrue(frame.test("Dtai"), "Dtai is set for a JCMT header"); + assertEquals(37.0, frame.getDtai(), 1e-9); + assertTrue(cmpFrameCarries(text, "DTAI_"), "the CmpFrame carries its own Dtai"); + } + + @Test + void dtaiSetOnWorldFrameForUkirt() { + Frame frame = topFrame(header("UKIRT", 37.0)); + assertTrue(frame.test("Dtai"), "Dtai is set for a UKIRT header"); + assertEquals(37.0, frame.getDtai(), 1e-9); + } + + @Test + void dtaiIgnoredForOtherTelescope() { + assertFalse(topFrame(header("HST", 37.0)).test("Dtai")); + } + + @Test + void dtaiIgnoredWhenTelescopAbsent() { + assertFalse(topFrame(header(null, 37.0)).test("Dtai")); + } + + @Test + void dut1SetOnWorldFrameRegardlessOfTelescop() { + // DUT1 is given in days and set in seconds. + String text = header(null, null); + Frame frame = topFrame(text); + assertTrue(frame.test("Dut1"), "Dut1 is set whatever the TELESCOP"); + assertEquals(0.001 * 86400.0, frame.getDut1(), 1e-6); + assertTrue(cmpFrameCarries(text, "DUT1_"), "the CmpFrame carries its own Dut1"); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java index bf81c60..c0cd6c5 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanWcsTest.java @@ -1,6 +1,7 @@ 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; @@ -14,11 +15,6 @@ * *

    The values the Rust test copies from {@code fixtures/oracle/headers.oracle} are read from that * file here, with the Rust test's tolerances. - * - *

    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). */ class FitsChanWcsTest { @@ -115,6 +111,13 @@ void car3NaxisInferredFromCtypeIndices() { assertEquals(2, readFixture("car3.head").getNin()); } + @Test + void janClassNoNaxisKeyword() { + // jan.fits-class has CTYPE1 RA, CTYPE2 DEC and CTYPE3 FREQ but no NAXIS: the FITS-CLASS + // read takes the axis count from the CRPIX indices. + assertEquals(3, readFixture("jan.fits-class").getNin()); + } + @Test void sipReadDefaultRefitsInverseViaPolytran() { // With SipReplace at its default, C replaces the inverse by an astPolyTran fit over three @@ -188,6 +191,27 @@ private static void checkInverseRows(String name, int[] rows, double tol) { } } + @Test + void classNoprojBuildsSfl() { + // class-noproj.head is a FITS-CLASS header whose celestial CTYPEs have no projection code, + // which C's ClassTrans makes -GLS. Forward rows 1, 4, 2 and 6 (pixel 1, 512.5, 1024 and + // 256.75 on the spectral axis) with Rust's tolerances: 1e-3 Hz on the spectral axis and + // 1e-9 radians on the celestial axes; inverse rows 4 and 1 to 1e-6 pixels. + FrameSet fs = readFixture("class-noproj.head"); + OracleSection fwd = FitsHeaders.headersOracle("wcsconv/inputs/class-noproj.head", true); + for (int row : new int[] {1, 4, 2, 6}) { + double[] got = FitsHeaders.tran(fs, FitsHeaders.oracleIn(fwd, row), true); + double[] want = FitsHeaders.oracleOut(fwd, row); + for (int k = 0; k < want.length; k++) { + double tol = Math.max(k == 0 ? 1e-3 : 1e-9, Math.abs(want[k]) * 1e-12); + assertTrue( + Math.abs(got[k] - want[k]) <= tol, + "forward row " + row + " axis " + (k + 1) + ": got " + got[k] + ", C gives " + want[k]); + } + } + checkInverseRows("class-noproj.head", new int[] {4, 1}, 1e-6); + } + @Test void glsLonpoleDefaultMatchesC() { // GLS (SFL) has theta0 = 0, so the LONPOLE default WcsNatPole chooses is 0, not 180. @@ -287,4 +311,47 @@ void serpensSwappedAxisTransform() { 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]); } + + /** A one-axis frequency header. */ + private static final String SPECTRAL_HEADER = String.join( + "\n", + "NAXIS = 1 / Number of axes", + "CRPIX1 = 1.0 / Reference pixel", + "CRVAL1 = 1.42040575E9 / Reference frequency (Hz)", + "CDELT1 = 1000000.00 / Frequency step (Hz)", + "CTYPE1 = 'FREQ ' / Frequency axis", + "CUNIT1 = 'Hz ' / Units", + "SPECSYS = 'BARYCENT' / Reference frame", + "RESTFRQ = 1.42040575E9 / Rest frequency (Hz)", + ""); + + @Test + void readSpectralHeader() { + FrameSet fs = FitsHeaders.readFrameSet(wcsChan(SPECTRAL_HEADER)); + assertEquals(2, fs.getNframe(), "pixel and spectral Frames"); + assertEquals(1, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + assertInstanceOf(SpecFrame.class, fs.getFrame(FrameSet.AST__CURRENT)); + } + + @Test + void axesSwapNonAdjacentCelestialAxes() { + // axes-swap.head has CTYPE1 = DEC--TAN, CTYPE2 = WAVE, CTYPE3 = RA---TAN and CTYPE4 = + // STOKES: the celestial pair is separated by the spectral axis. + FrameSet fs = readFixture("axes-swap.head"); + assertEquals(4, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + checkForwardRows("axes-swap.head", new int[] {1, 4, 5}, 1e-12); + } + + @Test + void crota3dForwardMatchesOracleInverseUndefined() { + // crota-3d.head (WAVE, RA---TAN, DEC--TAN with a CROTA3 coupling the celestial axes) is + // read with the FITS-AIPS encoding C guesses for it. + Mapping map = readFixture("crota-3d.head"); + assertEquals(3, map.getNin()); + assertEquals(3, map.getNout()); + checkForwardRows("crota-3d.head", new int[] {1, 2, 5}, 1e-12); + // The pixel to IWC MatrixMap is near-singular, so C leaves the inverse undefined. + assertTrue(map.getTranForward(), "forward defined"); + assertFalse(map.getTranInverse(), "inverse undefined, as C's astGetTranInverse gives 0"); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanWcsWriteTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanWcsWriteTest.java index 34de474..1f804e3 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanWcsWriteTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanWcsWriteTest.java @@ -1,5 +1,6 @@ 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.assertTrue; @@ -13,9 +14,9 @@ * 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), + *

    Listed in {@code deferred/rust-tests.txt}: {@code grism_interference_order_survives_a_round_trip} + * and {@code a_non_linear_grism_axis_writes_a_header_that_reads_back} (GrismMap, which the read of + * their {@code WAVE-GRI} headers builds), * 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). */ @@ -124,4 +125,56 @@ void aFrameSetWhoseMappingHasNoInverseWritesNothing() { FitsHeaders.padded("NAXIS1 = 100", "NAXIS2 = 100"), FitsHeaders.foundCards(fc)); } + + /** Rust's {@code SPECTRAL_HEADER}: a frequency axis in Hz. */ + private static final String[] SPECTRAL_HEADER = { + "NAXIS = 1 / Number of axes", + "CRPIX1 = 1.0 / Reference pixel", + "CRVAL1 = 1.42040575E9 / Reference frequency (Hz)", + "CDELT1 = 1000000.00 / Frequency step (Hz)", + "CTYPE1 = 'FREQ ' / Frequency axis", + "CUNIT1 = 'Hz ' / Units", + "SPECSYS = 'BARYCENT' / Reference frame", + "RESTFRQ = 1.42040575E9 / Rest frequency (Hz)", + }; + + /** The FrameSet read FITS-WCS from {@link #SPECTRAL_HEADER}. */ + private static FrameSet readSpectral() { + FitsChan fc = FitsHeaders.chan(SPECTRAL_HEADER); + fc.setEncoding("FITS-WCS"); + return FitsHeaders.readFrameSet(fc); + } + + @Test + void writeSpectralFrameset() { + // C probe roundtrip_probe of Task 8, on Rust's SPECTRAL_HEADER. + FitsChan fc = written(readSpectral()); + List want = FitsHeaders.padded( + "WCSAXES = 1 / Number of WCS axes", + "CRPIX1 = 1.0 / Reference pixel on axis 1", + "CRVAL1 = 1420405750.0 / Value at ref. pixel on axis 1", + "CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 1000000.0 / Pixel size on axis 1", + "CUNIT1 = 'Hz ' / Units for axis 1", + "SPECSYS = 'BARYCENT' / Standard of rest for spectral axis", + "VELOSYS = 29327.576999844281 / [m/s] Topo. apparent velocity of rest frame", + "RESTFRQ = 1420405750.0 / [Hz] Rest frequency"); + List got = FitsHeaders.foundCards(fc); + assertTrue(FitsHeaders.cardsMatchC(got, want), got.toString()); + fc.clear("Card"); + assertEquals("FREQ", fc.getFitsS("CTYPE1")); + } + + @Test + void writeSpectralRoundTrip() { + // C probe roundtrip_probe of Task 8: both FrameSets give these frequencies. + FrameSet fs1 = readSpectral(); + FitsChan fc2 = written(fs1); + fc2.clear("Card"); + FrameSet fs2 = FitsHeaders.readFrameSet(fc2); + double[] pix = {1, 2, 100}; + double[] want = {1420405750.0, 1421405750.0, 1519405750.0}; + assertArrayEquals(want, fs1.tran1(3, pix, true), 0.0); + assertArrayEquals(want, fs2.tran1(3, pix, true), 0.0); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsChanWriteTest.java b/src/test/java/uk/ac/starlink/ast/FitsChanWriteTest.java index b9fa22c..1cdf09b 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsChanWriteTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsChanWriteTest.java @@ -18,6 +18,7 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; import uk.ac.starlink.ast.testsupport.Deferred; import uk.ac.starlink.ast.testsupport.OracleSection; @@ -264,12 +265,18 @@ void cardsGoInFrontOfAConsumedCurrentCard() { * 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 + * TNX or ZPX projection read as TPN or ZPN; for FITS-WCS, crota-3d, a spectral cube whose + * celestial axes are rotated: C probe {@code write_probe} of Task 8; for FITS-CLASS, class-noproj, + * class-spec and class-spec-hel: C probe {@code classrt.c} of Task 10), 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 + * from the pole, where longitude changes fast; 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, + * description; and vopt-f2w, vopt-geo, vrad-v2f and vrad-wav, whose velocity axes, sampled + * linearly in frequency or wavelength, C writes with the {@code -X2P} algorithm, the reference + * at pixel 1 and a CDELT from the numerical rate of the conversion there, so that the cards + * read back give velocities up to 1e-3 m/s from those of the header, the same values as C's + * read of C's cards: C probe {@code roundtrip_probe} of Task 8), 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). */ @@ -280,6 +287,10 @@ private static Map notRoundTripped() { for (String h : Arrays.asList( "programs/joye_car_headers/CHIPASS_Equ.head", "wcsconv/inputs/car6.head", + "wcsconv/inputs/class-noproj.head", + "wcsconv/inputs/class-spec-hel.head", + "wcsconv/inputs/class-spec.head", + "wcsconv/inputs/crota-3d.head", "wcsconv/inputs/tsc.head", "wcsconv/inputs/iraf-longpole.head", "wcsconv/inputs/projp-nopv0.head", @@ -301,7 +312,11 @@ private static Map notRoundTripped() { "wcsconv/inputs/offset-sky.head", "wcsconv/inputs/offset-sref.head", "wcsconv/inputs/scp.head", - "wcsconv/inputs/skyref-alt.head")) { + "wcsconv/inputs/skyref-alt.head", + "wcsconv/inputs/vopt-f2w.head", + "wcsconv/inputs/vopt-geo.head", + "wcsconv/inputs/vrad-v2f.head", + "wcsconv/inputs/vrad-wav.head")) { m.put(h, DIFFERS); } m.put("wcsconv/inputs/skyref.head", READ_FAILS); @@ -359,17 +374,17 @@ private static String roundTrip( } /** 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")); + private static final Set ROUND_TRIP_ENCODINGS = new LinkedHashSet<>( + Arrays.asList("FITS-WCS", "FITS-PC", "FITS-IRAF", "FITS-AIPS", "FITS-AIPS++", "FITS-CLASS", "DSS")); /** - * Every FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++ and DSS header of {@code + * Every FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS, FITS-AIPS++, FITS-CLASS 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. + * header. */ @Test void everyInScopeHeaderRoundTrips() { @@ -435,4 +450,36 @@ void threadsWriteCopiesIdentically() throws Exception { pool.shutdown(); } } + + /** + * A spectral cube (wcsconv's skyspec3d, FITS-WCS with RA, Dec and frequency axes) written with + * each of FITS-WCS, FITS-PC, FITS-IRAF, FITS-AIPS and FITS-AIPS++ into a new FitsChan and read + * back transforms as the header does: C's write of each returns 1, and C's read of C's cards + * gives these values at these pixels (C probe {@code roundtrip_probe} of Task 8). + */ + @Test + void spectralCubeRoundTripsInEachEncoding() { + double[][] pixels = {{1, 1, 1}, {10, 20, 30}, {64, 64, 128}}; + double[][] want = { + {-3.1296012703025604, 0.7768103146506354, 1371400000}, + {-3.1317713222141985, 0.780138109793003, 1400400000}, + {3.138128627580643, 0.7878386196480921, 1498400000}, + }; + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.fixture("wcsconv/inputs/skyspec3d.head")); + for (String encoding : new String[] {"FITS-WCS", "FITS-PC", "FITS-IRAF", "FITS-AIPS", "FITS-AIPS++"}) { + FitsChan out = new FitsChan(); + out.setEncoding(encoding); + assertEquals(1, out.write(fs), encoding); + out.clear("Card"); + FrameSet back = FitsHeaders.readFrameSet(out); + for (int i = 0; i < pixels.length; i++) { + double[] got = back.tranN(1, 3, pixels[i], true, 3); + for (int j = 0; j < 3; j++) { + assertTrue( + CValues.ulpClose(got[j], want[i][j], 4), + encoding + " pixel " + i + " axis " + j + ": " + got[j] + " vs C " + want[i][j]); + } + } + } + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsEncClassTest.java b/src/test/java/uk/ac/starlink/ast/FitsEncClassTest.java index 24da306..d603690 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsEncClassTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsEncClassTest.java @@ -10,18 +10,18 @@ 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. + * Translation of the unit tests of Rust {@code fitschan/enc_class.rs}: C's {@code ClassTrans}, + * which translates a FITS-CLASS header for a read, and {@code CLASSFromStore}, which writes one. * - *

    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). + *

    The reads translate the header as a FITS-CLASS read does ({@link FitsSpecTrans#specTrans}) + * and make the description C's {@code WcsToStore} makes of it; Rust's {@code + * read_class_spatial_axes_unchanged}, {@code read_class_equinox_and_radesys} and {@code + * read_class_mjdobs} make it from the untranslated header, as Rust does. The writes give {@code + * CLASSFromStore} the FrameSet it takes the VELO-LSR and AZIMUTH values from: for Rust's writes, a + * FrameSet with a plain Frame, from which C finds neither. The values are those of C's arithmetic + * in {@code ClassTrans} and {@code CLASSFromStore}; the wcsconv FITS-CLASS rows compare whole + * headers with C's. The FrameSets with a FREQ axis but no SpecFrame are C probe {@code p2.c}'s + * (phase 3). */ class FitsEncClassTest { @@ -71,41 +71,237 @@ void readClassMjdobs() { assertEquals(52413.59, classStore().mjdobs); } + /** + * The primary description C's {@code WcsToStore} makes of {@code header} translated as a + * FITS-CLASS read translates it. + */ + private static FitsStore translated(String header) { + FitsCardList trans = FitsSpecTrans.specTrans( + FitsCardList.fromHeader(header), + FitsChan.Encoding.FITS_CLASS, + new FitsSpecTrans.TransAttrs(), + new FitsSpecTrans.TransWarnings(), + new FitsWarnings()); + return FitsWcsKeywords.extractWcsKeywordsWithAlts(trans).primary; + } + + /** {@link #CLASS_HEADER} with its spatial and velocity cards replaced as {@code edits} gives. */ + private static String classHeader(String... edits) { + String h = CLASS_HEADER; + for (int i = 0; i < edits.length; i += 2) { + h = h.replace(edits[i], edits[i + 1]); + } + return h; + } + + @Test + void readClassOffsetFrequency() { + // CRVAL1 is 0, an offset from RESTFREQ, so the frequency is RESTFREQ. + assertEquals(0.110201354300e12, translated(CLASS_HEADER).crval[0], 1.0); + } + + @Test + void readClassWithNonzeroOffset() { + FitsStore store = translated(classHeader( + "CRVAL1 = 0.000000000000E+000", + "CRVAL1 = 1.000000000000E+006", + "RADESYS = 'FK5 '\nEQUINOX = 2000.0\nSPECSYS = 'SOURCE '\n", + "", + "MJD-OBS = 52413.59\n", + "")); + assertEquals(0.110201354300e12 + 1.0e6, store.crval[0], 1.0); + } + + @Test + void readClassGlsToSfl() { + FitsStore store = translated(classHeader("RA---TAN", "GLON-GLS", "DEC--TAN", "GLAT-GLS")); + assertEquals("GLON-SFL", store.ctype[1]); + assertEquals("GLAT-SFL", store.ctype[2]); + } + + @Test + void readClassSsyssrcFromVeloLsr() { + FitsStore store = translated(CLASS_HEADER); + assertEquals("SOURCE", store.specsys); + assertEquals("LSRK", store.ssyssrc); + } + + @Test + void readClassSsyssrcFromVeloHel() { + FitsStore store = translated(classHeader("VELO-LSR", "VELO-HEL", "SPECSYS = 'SOURCE '\n", "")); + assertEquals("SOURCE", store.specsys); + assertEquals("BARYCENT", store.ssyssrc); + } + + /** + * The description of Rust's {@code write_class_subtracts_restfreq} and {@code + * write_class_sfl_to_gls}: a FREQ axis at the rest frequency and celestial axes {@code lontype} + * and {@code lattype} with reference point ({@code lon}, {@code lat}). + */ + private static FitsPlaneStores writeStores(String lontype, String lattype, double lon, double lat) { + 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] = lontype; + store.crval[1] = lon; + store.crpix[1] = 0.5; + store.cdelt[1] = -0.01; + store.ctype[2] = lattype; + store.crval[2] = lat; + store.crpix[2] = 0.5; + store.cdelt[2] = 0.01; + store.restfrq = 0.110201354300e12; + store.specsys = "SOURCE"; + store.cunit[0] = "Hz"; + return stores; + } + + /** The image dimensions of a FitsChan without NAXISi cards. */ + private static double[] unknownDims() { + return new double[] {AstObject.AST__BAD, AstObject.AST__BAD, AstObject.AST__BAD}; + } + @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]); + void writeClassSubtractsRestfreq() { + FitsPlaneStores stores = writeStores("RA---TAN", "DEC--TAN", 40.738, 62.933); + stores.get(' ').radesys = "FK5"; + stores.get(' ').equinox = 2000.0; + FitsChan fc = new FitsChan(); + assertTrue(FitsEncClass.classFromStore( + fc, stores, new FrameSet(new Frame(3)), unknownDims(), "astWrite", "FitsChan")); + assertEquals(0.0, fc.getFitsF("CRVAL1"), 1.0); + assertEquals(40.738, fc.getFitsF("CRVAL2"), 1e-10); + } + + @Test + void writeClassSflToGls() { + // An SFL projection at the origin, the only one FITS-CLASS can hold, is written with the + // older code GLS. + FitsChan fc = new FitsChan(); + assertTrue(FitsEncClass.classFromStore( + fc, + writeStores("GLON-SFL", "GLAT-SFL", 0.0, 0.0), + new FrameSet(new Frame(3)), + unknownDims(), + "astWrite", + "FitsChan")); + assertEquals("GLON-GLS", fc.getFitsS("CTYPE2")); + assertEquals("GLAT-GLS", fc.getFitsS("CTYPE3")); + } + + @Test + void aDescriptionWithoutSpecsysIsRefused() { + FitsPlaneStores stores = writeStores("RA---TAN", "DEC--TAN", 40.738, 62.933); + stores.get(' ').specsys = null; + assertFalse(FitsEncClass.classFromStore( + new FitsChan(), stores, new FrameSet(new Frame(3)), unknownDims(), "astWrite", "FitsChan")); + } + + /** A FitsPlaneStores whose primary description has the values of {@code st} CLASSFromStore uses. */ + private static FitsPlaneStores storesOf(FitsStore st) { + FitsPlaneStores stores = new FitsPlaneStores(3); + FitsStore out = stores.version(' ', 3); + for (int i = 0; i < 3; i++) { + out.ctype[i] = st.ctype[i]; + out.crval[i] = st.crval[i]; + out.crpix[i] = st.crpix[i]; + out.cdelt[i] = st.cdelt[i]; + out.cunit[i] = st.cunit[i]; } + out.specsys = st.specsys; + out.restfrq = st.restfrq; + out.radesys = st.radesys; + out.equinox = st.equinox; + out.mjdobs = st.mjdobs; + return stores; + } + + @Test + void roundTripClass() { + // Read, written and read again, both reads translated as a FITS-CLASS read is. The header + // gives no CUNIT1; a description made from a FrameSet has the SpecFrame's unit, which + // FITS-CLASS needs. + FitsStore store = translated(CLASS_HEADER); + store.cunit[0] = "Hz"; + FitsChan fc = new FitsChan(); + assertTrue(FitsEncClass.classFromStore( + fc, storesOf(store), new FrameSet(new Frame(3)), unknownDims(), "astWrite", "FitsChan")); + FitsStore store2 = translated(String.join("\n", FitsHeaders.foundCards(fc)) + "\n"); + assertEquals(store.crval[0], store2.crval[0], 1.0); + assertEquals(store.crval[1], store2.crval[1], 1e-10); + } + + @Test + void spectralCdeltIsScaledToHertzOnce() { + // CLASSFromStore converts the spectral CRVAL and CDELT of a description in kHz to Hz once, + // for the cards and for the VELO-LSR and DELTAV values, so a description in kHz is written + // as the same description in Hz is (the fix the pinned C has as 17416d33). The FrameSet, + // read from CLASS_HEADER, gives the SpecFrame the velocities are found with. + FitsChan in = FitsChan.fromHeader(CLASS_HEADER); + in.setEncoding("FITS-CLASS"); + FrameSet fs = FitsHeaders.readFrameSet(in); + List> written = new java.util.ArrayList<>(); + for (String unit : new String[] {"Hz", "kHz"}) { + double f = "Hz".equals(unit) ? 1.0 : 1.0e3; + FitsPlaneStores stores = writeStores("RA---TAN", "DEC--TAN", 40.738, 62.933); + FitsStore st = stores.get(' '); + st.crval[0] = 1.1e11 / f; + st.cdelt[0] = 39062.5 / f; + st.cunit[0] = unit; + FitsChan fc = new FitsChan(); + assertTrue(FitsEncClass.classFromStore(fc, stores, fs, unknownDims(), "astWrite", "FitsChan"), unit); + written.add(FitsHeaders.foundCards(fc)); + } + assertEquals(written.get(0), written.get(1)); + assertTrue(written.get(0).stream().anyMatch(c -> c.startsWith("DELTAV")), String.join("\n", written.get(0))); + } + + @Test + void aSpectrumWithAReferencePositionIsWrittenAsACube() { + // The one-axis FITS-CLASS header class-spec.head, read, given RefRA and RefDec, and + // written back as FITS-CLASS: MakeFitsFrameSet adds celestial axes at the reference + // position, and CLASSFromStore writes the description as an image of three axes, setting + // NAXIS to 3 and putting NAXIS2 and NAXIS3 of 1 after NAXIS1. The cards are C's (C probe + // write_set_probe of the task report: astRead, astSet, astWrite to the same FitsChan). + FitsChan fc = FitsHeaders.fixture("wcsconv/inputs/class-spec.head"); + fc.setEncoding("FITS-CLASS"); + FrameSet fs = FitsHeaders.readFrameSet(fc); + fs.set("RefRA=10:00:00,RefDec=20:00:00"); + assertEquals(1, fc.write(fs)); + List want = FitsHeaders.padded( + "SIMPLE = T / Fits standard", + "BITPIX = -32 / Bits per pixel", + "NAXIS = 3 / Number of dimensions", + "NAXIS1 = 1024 / Spectral axis", + "CTYPE1 = 'FREQ ' / spectral axis is frequency", + "CRVAL1 = -110201350647.34827 / Value at ref. pixel on axis 1", + "CDELT1 = 19531.672938506857 / Pixel size", + "CRPIX1 = 579.0 / Reference pixel on axis 1", + "NAXIS2 = 1", + "NAXIS3 = 1", + "LINE = '13co10 ' / Line name", + "RESTFREQ= 110201354300.0 / Rest frequency", + "VELO-LSR= 299792438.17278373 / [m/s] Reference velocity", + "CRPIX2 = 1.0 / Reference pixel on axis 2", + "CRPIX3 = 1.0 / Reference pixel on axis 3", + "CRVAL2 = 150.0 / Value at ref. pixel on axis 2", + "CRVAL3 = 20.0 / Value at ref. pixel on axis 3", + "CTYPE2 = 'RA---TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CTYPE3 = 'DEC--TAN' / Type of co-ordinate on axis 3", // codespell:ignore + "CDELT2 = -0.017453292519943295 / Pixel size", + "CDELT3 = 0.017453292519943295 / Pixel size", + "EQUINOX = 2000.0 / Epoch of reference equinox", + "DATE-OBS= '2000-01-01T11:58:55.816' / Date of observation", + "OBJECT = ' '", + "VLSR = 299792438.17278373 / [m/s] Reference velocity", + "DELTAV = -106.31700652837753 / [m/s] Velocity resolution", + "IMAGFREQ= 97250382992.51059 / [Hz] Image frequency", + "END"); + List got = FitsHeaders.foundCards(fc); + assertTrue(FitsHeaders.cardsMatchC(got, want), "--- Java\n" + String.join("\n", got)); } /** @@ -214,4 +410,28 @@ void oneSpatialPixelOfAFourAxisImageFailsAsC() { e.getMessage()); assertEquals(5, FitsHeaders.foundCards(fc).size()); } + + @Test + void aSpectralAxisBeyondTheWrittenAxesIsAnInternalError() { + // CRPIX is set for axis 1 only, so one axis is written but the spectral axis is the third; + // C then writes past its CDELT array. A FrameSet always gives a CRPIX for every axis, so + // this is unreachable by a write. + FitsPlaneStores stores = writeStores("RA---TAN", "DEC--TAN", 40.738, 62.933); + FitsStore st = stores.get(' '); + st.ctype[0] = "RA---TAN"; + st.ctype[1] = "DEC--TAN"; + st.ctype[2] = "FREQ"; + st.cunit[0] = null; + st.cunit[2] = "Hz"; + st.crpix[1] = null; + st.crpix[2] = null; + st.radesys = "FK5"; + st.equinox = 2000.0; + AstException e = assertThrows( + AstException.class, + () -> FitsEncClass.classFromStore( + new FitsChan(), stores, new FrameSet(new Frame(3)), unknownDims(), "astWrite", "FitsChan")); + assertEquals(AstException.AST__INTER, e.getStatus()); + assertTrue(e.getMessage().contains("CLASSFromStore"), e.getMessage()); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FitsFsetToStoreTest.java b/src/test/java/uk/ac/starlink/ast/FitsFsetToStoreTest.java index 4032637..0d1f72f 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsFsetToStoreTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsFsetToStoreTest.java @@ -3,7 +3,6 @@ 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; @@ -14,16 +13,15 @@ /** * 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 + * fitschan/wcs_write/plane_stores.rs} (C {@code FsetToStore}, {@code AddVersion}, {@code + * MakeFitsFrameSet}, {@code FitsAxisOrder} and {@code ReadCrval}, 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. + *

    The tests of {@code spectral_axes.rs} are in {@link FitsSpectralAxesTest}. */ class FitsFsetToStoreTest { @@ -95,13 +93,6 @@ void identityChainYieldsCentralPixelCrpix() { 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. @@ -363,6 +354,22 @@ void twoSkyFramesCannotBeDescribed() { assertNull(fsetToStore(new FitsChan(), fs, 100, 100, 100, 100)); } + @Test + void twoSpecFramesCannotBeDescribed() { + // As two SkyFrames: MakeFitsFrameSet finds two SpecFrames and makes no FrameSet, and C + // then passes the NULL FrameSet to AddEncodingFrame, which crashes (C probe twospec.c: + // SIGSEGV, exit status 139, in astWrite). + SpecFrame freq = new SpecFrame(); + freq.setSystem("FREQ"); + freq.setUnit(1, "GHz"); + SpecFrame wave = new SpecFrame(); + wave.setSystem("WAVE"); + wave.setUnit(1, "m"); + FrameSet fs = frameSet(new ZoomMap(2, 0.001), new CmpFrame(freq, wave)); + assertNull(FitsFsetToStore.makeFitsFrameSet( + new FitsChan(), fs, 1, 2, FitsChan.Encoding.FITS_WCS, "FitsChan", "astWrite")); + } + @Test void theReferencePointAlreadyInTheFitsChanIsUsed() { // C probe readcrval: the FrameSet read from the FitsChan, written back to it, keeps diff --git a/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java b/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java index 3f85dfe..80aaf40 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsSpecTransTest.java @@ -20,8 +20,7 @@ * *

    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, 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 + * translations only FITS-PC and FITS-IRAF make run under that encoding. 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 @@ -570,20 +569,116 @@ void cnxxxZeroCdeltFallsBackToCrvalOrOne() { assertEquals(1.0, cards.getStoredFloat("CDELT1A")); } + @Test + void translatesClassSpectralCrvalAndSpecsys() { + // C's ClassTrans: the spectral CRVAL is an offset from RESTFREQ, so 0 becomes 1e9; the + // spectral axis is in the source's rest frame; VELO-LSR gives SSYSSRC LSRK, and ZSOURCE + // is the redshift of the source velocity VELO-LSR less the reference channel's radio + // velocity, which is zero at the incremented CRVAL. + FitsCardList cards = FitsCardList.fromHeader("CTYPE1 = 'RA---GLS'\n" + + "CTYPE2 = 'DEC--GLS'\n" + + "CTYPE3 = 'FREQ '\n" + + "CRVAL1 = 0.0\n" + + "CRVAL2 = 0.0\n" + + "CRVAL3 = 0.0\n" + + "RESTFREQ= 1.0E9 / [Hz] Rest frequency\n" + + "VELO-LSR= 1.0E4\n" + + "END"); + FitsSpecTrans.specTransInplace( + cards, FitsChan.Encoding.FITS_CLASS, new FitsSpecTrans.TransAttrs(), new FitsSpecTrans.TransWarnings()); + assertEquals(1.0e9, cards.getStoredFloat("CRVAL3")); + assertEquals("SOURCE", cards.getString("SPECSYS")); + assertEquals("LSRK", cards.getString("SSYSSRC")); + double c = 299792458.0; + assertEquals(c / (c - 1.0e4) - 1.0, cards.getStoredFloat("ZSOURCE")); + } + + /** A FITS-CLASS header of three axes, whose spectral CRVAL3 is an offset from RESTFREQ. */ + private static final String CLASS_TRANS_HEADER = "NAXIS = 3\n" + + "CTYPE1 = 'RA---GLS'\n" + + "CTYPE2 = 'DEC--GLS'\n" + + "CTYPE3 = 'FREQ '\n" + + "CRVAL1 = 0.0\n" + + "CRVAL2 = 0.0\n" + + "CRVAL3 = 0.0\n" + + "CRPIX1 = 1.0\n" + + "CRPIX2 = 1.0\n" + + "CRPIX3 = 1.0\n" + + "CDELT1 = -0.1\n" + + "CDELT2 = 0.1\n" + + "CDELT3 = 1.0E6\n" + + "RESTFREQ= 1.0E9 / [Hz] Rest frequency\n" + + "VELO-LSR= 1.0E4\n" + + "END"; + + /** The RESTFREQ card of {@link #CLASS_TRANS_HEADER}. */ + private static final String CLASS_RESTFREQ = "RESTFREQ= 1.0E9 / [Hz] Rest frequency\n"; + + /** The VELO-LSR card of {@link #CLASS_TRANS_HEADER}. */ + private static final String CLASS_VELO_LSR = "VELO-LSR= 1.0E4\n"; + // ------------------------------------------------------------------ // C behaviour beyond the Rust tests // ------------------------------------------------------------------ @Test - 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()); + void fitsClassReportsAMissingRestFrequency() { + // C's ClassTrans reports AST__BDFTS when there is neither RESTFRQ nor RESTFREQ; the message + // is C's, from a read of CLASS_TRANS_HEADER without RESTFREQ (C probe of the task report). + AstException e = assertThrows( + AstException.class, + () -> under(FitsChan.Encoding.FITS_CLASS, CLASS_TRANS_HEADER.replace(CLASS_RESTFREQ, ""))); + assertEquals(AstException.AST__BDFTS, e.getStatus()); + assertTrue( + e.getMessage().contains("astRead(FitsChan): Keyword RESTFREQ not found in CLASS FITS header."), + e.getMessage()); + } + + @Test + void fitsClassReportsASpectralAxisOtherThanFrequency() { + // C's ClassTrans reports AST__BDFTS for a spectral CTYPE other than FREQ, quoting the value + // with its trailing spaces (C probe). + AstException e = assertThrows( + AstException.class, + () -> under(FitsChan.Encoding.FITS_CLASS, CLASS_TRANS_HEADER.replace("'FREQ '", "'VRAD '"))); + assertEquals(AstException.AST__BDFTS, e.getStatus()); + assertTrue( + e.getMessage() + .contains("astRead(FitsChan): FITS-CLASS keyword CTYPE3 has value \"VRAD \" - CLASS support" + + " in AST only includes \"FREQ\" axes."), + e.getMessage()); + } + + @Test + void fitsClassWithoutAVelocityKeywordAssumesLsrk() { + // C's ClassTrans warns (badval) that it assumes LSRK with a reference velocity of zero, + // before the scan for QV cards (C probe: the ASTWARN cards go in front of the first card). + FitsSpecTrans.TransWarnings w = new FitsSpecTrans.TransWarnings(); + FitsCardList cards = FitsCardList.fromHeader(CLASS_TRANS_HEADER.replace(CLASS_VELO_LSR, "")); + FitsSpecTrans.specTransInplace(cards, FitsChan.Encoding.FITS_CLASS, new FitsSpecTrans.TransAttrs(), w); + assertEquals(1, w.entry.size()); + assertTrue(w.end.isEmpty()); + assertEquals("badval", w.entry.get(0).condition); + assertEquals( + "A FITS-CLASS header was identified (DELTAV and VLSR/VELO-xxx present) but no usable velocity" + + " reference keyword was found. Assuming LSRK.", + w.entry.get(0).text); + assertEquals("LSRK", cards.getString("SSYSSRC")); + assertEquals(0.0, cards.getStoredFloat("ZSOURCE")); + } + + @Test + void fitsClassReadGivesCsSourceVelocity() { + // The SpecFrame read from CLASS_TRANS_HEADER: C gives StdOfRest Source, RestFreq 1e9 Hz, + // SourceVRF LSRK and SourceVel 10000.166782032104 m/s (C probe, astShow of the FrameSet). + FitsChan fc = FitsChan.fromHeader(CLASS_TRANS_HEADER); + fc.setEncoding("FITS-CLASS"); + FrameSet fs = FitsHeaders.readFrameSet(fc); + SpecFrame spec = (SpecFrame) fs.pickAxes(1, new int[] {3}, null); + assertEquals("Source", spec.getC("StdOfRest")); + assertEquals(1.0e9, spec.restFreqValue()); + assertEquals("LSRK", spec.getC("SourceVRF")); + assertEquals(10000.166782032104, spec.sourceVelValue()); } @Test diff --git a/src/test/java/uk/ac/starlink/ast/FitsSpectralAxesTest.java b/src/test/java/uk/ac/starlink/ast/FitsSpectralAxesTest.java new file mode 100644 index 0000000..756bb8f --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsSpectralAxesTest.java @@ -0,0 +1,800 @@ +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 java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * Translation of the unit tests of Rust {@code fitschan/fset_to_store/spectral_axes.rs} (C {@code + * SpectralAxes}, fitschan.c), and FrameSets with a spectral axis written as C writes them, from + * C's {@code SpectralAxes} and the SpecFrame parts of {@code MakeFitsFrameSet}: the cards each + * write gives are those of C probe {@code spectral_axes_probe}, which writes the same FrameSets + * with the pinned C library into a FitsChan holding the NAXIS cards. + * + *

    The Rust tests' expectations are checked against the cards C writes for the same FrameSets. + * {@code x2p_cascade_picks_freq_for_wavelength_axis} builds its axis with a MathMap; here the + * frequency axis is set to wavelength through the FrameSet, as {@code testfitschan.c} does. {@code + * nonlinear_unit_is_cleared} sets the Unit {@code log(Hz)}, whose conversion to the default Unit is + * the MathMap C builds, so it expects {@code needs MathMap}. Listed in {@code + * deferred/rust-tests.txt}: {@code try_grism_cascade_emits_gri_pv_and_chain} (GrismMap). + */ +class FitsSpectralAxesTest { + + private static final double BAD = AstObject.AST__BAD; + + /** C's {@code AST__C}, the speed of light in m/s. */ + private static final double AST__C = 2.99792458E8; + + /** C's cards for freq_basic (C probe {@code spectral_axes_probe}, case {@code freq_basic}). */ + private static final String[] C_FREQ_BASIC = { + "wrote 1", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 51.0 / Reference pixel on axis 2", + "CRVAL1 = 50.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 51.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'FREQ ' / 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", + "CUNIT2 = 'GHz ' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "VELOSYS = 29336.889452278185 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for restwav (C probe {@code spectral_axes_probe}, case {@code restwav}). */ + private static final String[] C_RESTWAV = { + "wrote 1", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 51.0 / Reference pixel on axis 2", + "CRVAL1 = 50.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 51.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'WAVE ' / 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", + "CUNIT2 = 'Angstrom' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "VELOSYS = 29336.889452286428 / [m/s] Topo. apparent velocity of rest frame", + "RESTWAV = 0.21112144929577464 / [m] Rest wavelength", + }; + /** C's cards for obsgeo (C probe {@code spectral_axes_probe}, case {@code obsgeo}). */ + private static final String[] C_OBSGEO = { + "wrote 1", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 51.0 / Reference pixel on axis 2", + "CRVAL1 = 50.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 51.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'FREQ ' / 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", + "CUNIT2 = 'GHz ' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "VELOSYS = 29508.815578196482 / [m/s] Topo. apparent velocity of rest frame", + "OBSGEO-X= 3980583.1459730188 / [m] Observatory geocentric X", + "OBSGEO-Y= 0.0 / [m] Observatory geocentric Y", + "OBSGEO-Z= 4966822.9821469523 / [m] Observatory geocentric Z", + }; + /** C's cards for label (C probe {@code spectral_axes_probe}, case {@code label}). */ + private static final String[] C_LABEL = { + "wrote 1", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 51.0 / Reference pixel on axis 2", + "CRVAL1 = 50.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 51.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'FREQ ' / MyFrequency", + "CDELT1 = 1.0 / Pixel size on axis 1", + "CDELT2 = 1.0 / Pixel size on axis 2", + "CUNIT2 = 'GHz ' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "VELOSYS = 29336.889452278185 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for sourcevel (C probe {@code spectral_axes_probe}, case {@code sourcevel}). */ + private static final String[] C_SOURCEVEL = { + "wrote 1", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 51.0 / Reference pixel on axis 2", + "CRVAL1 = 50.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 51.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'FREQ ' / 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", + "CUNIT2 = 'GHz ' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "SSYSSRC = 'HELIOCEN' / Standard of rest for source redshift", + "ZSOURCE = 0.0033412228058471438 / [] Redshift of source", + "VELOSYS = 29336.889452278185 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for midpoint (C probe {@code spectral_axes_probe}, case {@code midpoint}). */ + private static final String[] C_MIDPOINT = { + "wrote 1", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 200", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 101.0 / Reference pixel on axis 2", + "CRVAL1 = 50.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 101.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'FREQ ' / 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", + "CUNIT2 = 'GHz ' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "VELOSYS = 29336.889452278185 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for mhz (C probe {@code spectral_axes_probe}, case {@code mhz}). */ + private static final String[] C_MHZ = { + "wrote 1", + "NAXIS = 2", + "NAXIS1 = 100", + "NAXIS2 = 100", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRPIX2 = 51.0 / Reference pixel on axis 2", + "CRVAL1 = 50.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 51.0 / Value at ref. pixel on axis 2", + "CTYPE1 = 'x1 ' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'FREQ ' / 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", + "CUNIT2 = 'MHz ' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "VELOSYS = 29336.889452278185 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for nodims (C probe {@code spectral_axes_probe}, case {@code nodims}). */ + private static final String[] C_NODIMS = { + "wrote 1", + "NAXIS = 2", + "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 = 'FREQ ' / 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", + "CUNIT2 = 'GHz ' / Units for axis 2", + "SPECSYS = 'HELIOCEN' / Standard of rest for spectral axis", + "VELOSYS = 29336.889452278185 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for wave_f2w (C probe {@code spectral_axes_probe}, case {@code wave_f2w}). */ + private static final String[] C_WAVE_F2W = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "CRPIX1 = 2.0 / Reference pixel on axis 1", + "CRVAL1 = 149.896229 / Value at ref. pixel on axis 1", + "CTYPE1 = 'WAVE-F2W' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = -74.948114841600017 / Pixel size on axis 1", + "CUNIT1 = 'm ' / Units for axis 1", + "SPECSYS = 'BARYCENT' / Standard of rest for spectral axis", + "VELOSYS = 29327.576999852943 / [m/s] Topo. apparent velocity of rest frame", + "RESTWAV = 0.21106199521261618 / [m] Rest wavelength", + }; + /** C's cards for refpos_1d (C probe {@code spectral_axes_probe}, case {@code refpos_1d}). */ + private static final String[] C_REFPOS_1D = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "WCSAXES = 3 / Number of WCS axes", + "CRPIX1 = 51.0 / Reference pixel on axis 1", + "CRPIX2 = 1.0 / Reference pixel on axis 2", + "CRPIX3 = 1.0 / Reference pixel on axis 3", + "CRVAL1 = 51000000.0 / Value at ref. pixel on axis 1", + "CRVAL2 = 150.0 / Value at ref. pixel on axis 2", + "CRVAL3 = -30.0 / Value at ref. pixel on axis 3", + "CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1", // codespell:ignore + "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.017453292519943295 / Pixel size on axis 2", + "CDELT3 = 0.017453292519943295 / Pixel size on axis 3", + "CUNIT1 = 'Hz ' / Units for axis 1", + "MJD-OBS = 53370.749257130272 / Modified Julian Date of observation", + "DATE-OBS= '2004-12-31T17:58:55.816' / Date of observation", + "RADESYS = 'FK5 ' / Reference frame for RA/DEC values", + "EQUINOX = 2000.0 / [yr] Epoch of reference equinox", + "SPECSYS = 'LSRK ' / Standard of rest for spectral axis", + "VELOSYS = -8800.6985066334782 / [m/s] Topo. apparent velocity of rest frame", + "RESTFRQ = 1420400000.0 / [Hz] Rest frequency", + }; + /** C's cards for refpos_1d_norest (C probe {@code spectral_axes_probe}, case {@code refpos_1d_norest}). */ + private static final String[] C_REFPOS_1D_NOREST = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "CRPIX1 = 51.0 / Reference pixel on axis 1", + "CRVAL1 = 51000000.0 / Value at ref. pixel on axis 1", + "CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 1000000.0 / Pixel size on axis 1", + "CUNIT1 = 'Hz ' / Units for axis 1", + "SPECSYS = 'LSRK ' / Standard of rest for spectral axis", + "VELOSYS = -14029.888048206089 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for refpos_sky (C probe {@code spectral_axes_probe}, case {@code refpos_sky}). */ + private static final String[] C_REFPOS_SKY = { + "wrote 1", + "NAXIS = 3", + "NAXIS1 = 10", + "NAXIS2 = 10", + "CRPIX1 = 5.0 / Reference pixel on axis 1", + "CRPIX2 = 5.0 / Reference pixel on axis 2", + "CRPIX3 = 1.0 / Reference pixel on axis 3", + "CRVAL1 = 150.0 / Value at ref. pixel on axis 1", + "CRVAL2 = -30.0 / Value at ref. pixel on axis 2", + "CRVAL3 = 1391000000.0 / Value at ref. pixel on axis 3", + "CTYPE1 = 'RA---TAN' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'DEC--TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3", // codespell:ignore + "CDELT1 = -10.0E-4 / Pixel size on axis 1", + "CDELT2 = 0.001 / Pixel size on axis 2", + "CDELT3 = 1000000.0 / Pixel size on axis 3", + "CUNIT3 = 'Hz ' / Units for axis 3", + "MJD-OBS = 53000.0 / Modified Julian Date of observation", + "DATE-OBS= '2003-12-27T00:00:00.000' / Date of observation", + "RADESYS = 'FK5 ' / Reference frame for RA/DEC values", + "EQUINOX = 2000.0 / [yr] Epoch of reference equinox", + "SPECSYS = 'LSRK ' / Standard of rest for spectral axis", + "VELOSYS = -9733.4645274796458 / [m/s] Topo. apparent velocity of rest frame", + "RESTFRQ = 1420405752.0 / [Hz] Rest frequency", + }; + /** C's cards for refpos_sky_gal (C probe {@code spectral_axes_probe}, case {@code refpos_sky_gal}). */ + private static final String[] C_REFPOS_SKY_GAL = { + "wrote 1", + "NAXIS = 3", + "NAXIS1 = 10", + "NAXIS2 = 10", + "CRPIX1 = 5.0 / Reference pixel on axis 1", + "CRPIX2 = 5.0 / Reference pixel on axis 2", + "CRPIX3 = 1.0 / Reference pixel on axis 3", + "CRVAL1 = 264.20062324371702 / Value at ref. pixel on axis 1", + "CRVAL2 = 19.693479497483363 / Value at ref. pixel on axis 2", + "CRVAL3 = 1391000000.0 / Value at ref. pixel on axis 3", + "CTYPE1 = 'GLON-TAN' / Type of co-ordinate on axis 1", // codespell:ignore + "CTYPE2 = 'GLAT-TAN' / Type of co-ordinate on axis 2", // codespell:ignore + "CTYPE3 = 'FREQ ' / Type of co-ordinate on axis 3", // codespell:ignore + "CDELT1 = -10.0E-4 / Pixel size on axis 1", + "CDELT2 = 0.00099999999998380486 / Pixel size on axis 2", + "CDELT3 = 1000000.0 / Pixel size on axis 3", + "PC1_1 = 0.76588220346060187 / Transformation matrix element", + "PC1_2 = 0.64298090984284539 / Transformation matrix element", + "PC2_1 = -0.64298090987813616 / Transformation matrix element", + "PC2_2 = 0.76588220343097413 / Transformation matrix element", + "CUNIT3 = 'Hz ' / Units for axis 3", + "MJD-OBS = 53000.0 / Modified Julian Date of observation", + "DATE-OBS= '2003-12-27T00:00:00.000' / Date of observation", + "SPECSYS = 'LSRK ' / Standard of rest for spectral axis", + "VELOSYS = -9733.4645274796458 / [m/s] Topo. apparent velocity of rest frame", + "RESTFRQ = 1420405752.0 / [Hz] Rest frequency", + }; + /** C's cards for dsb (C probe {@code spectral_axes_probe}, case {@code dsb}). */ + private static final String[] C_DSB = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "CRPIX1 = 51.0 / Reference pixel on axis 1", + "CRVAL1 = 0.051 / Value at ref. pixel on axis 1", + "CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 0.001 / Pixel size on axis 1", + "CUNIT1 = 'GHz ' / Units for axis 1", + "SPECSYS = 'LSRK ' / Standard of rest for spectral axis", + "VELOSYS = 29046.889455035784 / [m/s] Topo. apparent velocity of rest frame", + "RESTFRQ = 230500000000.0 / [Hz] Rest frequency", + "IMAGFREQ= 237501227871.66501 / [Hz] Image frequency", + }; + /** C's cards for dsb_norest (C probe {@code spectral_axes_probe}, case {@code dsb_norest}). */ + private static final String[] C_DSB_NOREST = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "CRPIX1 = 51.0 / Reference pixel on axis 1", + "CRVAL1 = 0.051 / Value at ref. pixel on axis 1", + "CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 0.001 / Pixel size on axis 1", + "CUNIT1 = 'GHz ' / Units for axis 1", + "SPECSYS = 'LSRK ' / Standard of rest for spectral axis", + "VELOSYS = 29046.889455018489 / [m/s] Topo. apparent velocity of rest frame", + }; + /** C's cards for source_sor (C probe {@code spectral_axes_probe}, case {@code source_sor}). */ + private static final String[] C_SOURCE_SOR = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "CRPIX1 = 51.0 / Reference pixel on axis 1", + "CRVAL1 = 51000000.0 / Value at ref. pixel on axis 1", + "CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 1000000.0 / Pixel size on axis 1", + "CUNIT1 = 'Hz ' / Units for axis 1", + "SPECSYS = 'SOURCE ' / Standard of rest for spectral axis", + "SSYSSRC = 'LSRK ' / Standard of rest for source redshift", + "ZSOURCE = 0.0033421933742774357 / [] Redshift of source", + "VELOSYS = 1029336.5534594683 / [m/s] Topo. apparent velocity of rest frame", + "RESTFRQ = 1420400000.0 / [Hz] Rest frequency", + }; + /** C's cards for zsource_vrad (C probe {@code spectral_axes_probe}, case {@code zsource_vrad}). */ + private static final String[] C_ZSOURCE_VRAD = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "CRPIX1 = 51.0 / Reference pixel on axis 1", + "CRVAL1 = 51.0 / Value at ref. pixel on axis 1", + "CTYPE1 = 'VRAD ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 1.0 / Pixel size on axis 1", + "CUNIT1 = 'km/s ' / Units for axis 1", + "SPECSYS = 'BARYCENT' / Standard of rest for spectral axis", + "SSYSSRC = 'HELIOCEN' / Standard of rest for source redshift", + "ZSOURCE = -6.6690580876693772E-4 / [] Redshift of source", + "VELOSYS = 29327.576999852943 / [m/s] Topo. apparent velocity of rest frame", + "RESTFRQ = 1420400000.0 / [Hz] Rest frequency", + }; + /** C's cards for quad_notab (C probe {@code spectral_axes_probe}, case {@code quad_notab}). */ + private static final String[] C_QUAD_NOTAB = { + "wrote 0", "NAXIS = 1", "NAXIS1 = 100", + }; + /** C's cards for forcetab_notabok (C probe {@code spectral_axes_probe}, case {@code forcetab_notabok}). */ + private static final String[] C_FORCETAB_NOTABOK = { + "wrote 1", + "NAXIS = 1", + "NAXIS1 = 100", + "CRPIX1 = 50.0 / Reference pixel on axis 1", + "CRVAL1 = 0.05 / Value at ref. pixel on axis 1", + "CTYPE1 = 'FREQ ' / Type of co-ordinate on axis 1", // codespell:ignore + "CDELT1 = 0.001 / Pixel size on axis 1", + }; + + /** A FrameSet from a 2-D pixel Frame to a CmpFrame of a 1-D Frame and {@code spec}. */ + private static FrameSet twoAxis(Frame spec, Mapping map) { + Frame pixel = new Frame(2); + pixel.setDomain("GRID"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, map != null ? map : new UnitMap(2), new CmpFrame(new Frame(1), spec)); + return fs; + } + + /** A FrameSet from a 1-D pixel Frame to {@code spec} through {@code map}. */ + private static FrameSet oneAxis(Frame spec, Mapping map) { + Frame pixel = new Frame(1); + pixel.setDomain("GRID"); + FrameSet fs = new FrameSet(pixel); + fs.addFrame(FrameSet.AST__BASE, map, spec); + return fs; + } + + private static SpecFrame spec(String settings) { + SpecFrame sf = new SpecFrame(); + sf.set(settings); + return sf; + } + + /** + * What C's probe prints for a write of {@code fs} with FITS-WCS into a FitsChan with {@code + * attrs} set and holding NAXIS (the number of pixel axes) and, unless zero, NAXIS1 and NAXIS2: + * the value the write returns, then the cards. + */ + private static List written(FrameSet fs, String attrs, int n1, int n2) { + FitsChan fc = new FitsChan(); + fc.setEncoding("FITS-WCS"); + if (!attrs.isEmpty()) { + fc.set(attrs); + } + fc.putFits("NAXIS = " + fs.getNin(), false); + if (n1 != 0) { + fc.putFits("NAXIS1 = " + n1, false); + } + if (n2 != 0) { + fc.putFits("NAXIS2 = " + n2, false); + } + List got = new ArrayList<>(); + got.add("wrote " + fc.write(fs)); + got.addAll(FitsHeaders.foundCards(fc)); + return got; + } + + private static void assertWritesAsC(String[] want, FrameSet fs, String attrs, int n1, int n2) { + assertWritesAsC(want, fs, attrs, n1, n2, Collections.emptyMap()); + } + + /** + * {@link #assertWritesAsC(String[], FrameSet, String, int, int)}, the number on a card whose + * keyword is a key of {@code atol} needing only to be within that absolute tolerance of C's. + */ + private static void assertWritesAsC( + String[] want, FrameSet fs, String attrs, int n1, int n2, Map atol) { + List got = written(fs, attrs, n1, n2); + List w = new ArrayList<>(); + w.add(want[0]); + w.addAll(FitsHeaders.padded(Arrays.copyOfRange(want, 1, want.length))); + assertTrue(FitsHeaders.cardsMatchC(got, w, Collections.emptySet(), atol), String.join("\n", got)); + } + + /** {@link FitsSpectralAxes#spectralAxes} for {@code fs}, with the FITS axes in Frame order. */ + private static Mapping spectralAxes( + 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 FitsSpectralAxes.spectralAxes( + new FitsChan(), fs, dim, wperm, ' ', store, crvals, axisDone, "astWrite", "FitsChan"); + } + + /** The PolyMap of the Taylor series to degree 20 of {@code sr exp(slope p)}. */ + 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; + } + + /** The PolyMap {@code c0 + c1 p + c2 p^2}. */ + private static PolyMap 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"); + return pm; + } + + // ------------------------------------------------------------------ + // spectral_axes.rs + // ------------------------------------------------------------------ + + @Test + void noSpectralAxisReturnsUnitMap() { + FrameSet fs = new FrameSet(new Frame(2)); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(2), new Frame(2)); + FitsStore store = new FitsStore(2); + boolean[] axisDone = new boolean[2]; + Mapping map = spectralAxes(fs, new double[] {100, 100}, store, null, axisDone); + assertInstanceOf(UnitMap.class, map); + assertEquals(2, map.getNin()); + assertFalse(axisDone[0] || axisDone[1]); + assertNull(store.ctype[0]); + assertNull(store.ctype[1]); + } + + @Test + void freqSpecAxisWritesKeywords() { + FitsStore store = new FitsStore(2); + boolean[] axisDone = new boolean[2]; + Mapping map = spectralAxes( + twoAxis(spec("System=FREQ"), null), + new double[] {100, 100}, + store, + new double[] {BAD, 1.42e9}, + axisDone); + assertFalse(axisDone[0]); + assertTrue(axisDone[1]); + assertEquals("FREQ", store.ctype[1]); + assertEquals("GHz", store.cunit[1]); + assertEquals(1.42e9, store.crval[1]); + assertEquals("HELIOCEN", store.specsys); + // C's VELOSYS for this SpecFrame (case freq_basic). + assertEquals(29336.889452278185, store.velosys, 4 * Math.ulp(29336.889452278185)); + assertEquals(2, map.getNin()); + assertEquals(2, map.getNout()); + assertArrayEquals(new double[] {10, 0}, map.tranN(1, 2, new double[] {10, 1.42e9}, true, 2), 1e-3); + assertWritesAsC(C_FREQ_BASIC, twoAxis(spec("System=FREQ"), null), "", 100, 100); + } + + @Test + void restwavEmittedForWavelengthSystems() { + FitsStore store = new FitsStore(2); + boolean[] axisDone = new boolean[2]; + spectralAxes( + twoAxis(spec("System=WAVE,RestFreq=1.42"), null), + new double[] {100, 100}, + store, + new double[] {BAD, 0.21}, + axisDone); + assertEquals(AST__C / 1.42e9, store.restwav, 1e-9); + assertNull(store.restfrq); + assertWritesAsC(C_RESTWAV, twoAxis(spec("System=WAVE,RestFreq=1.42"), null), "", 100, 100); + } + + @Test + void obsgeoEmittedWhenObserverSet() { + String settings = "System=FREQ,ObsLon=E0:0:0,ObsLat=N51:28:40,ObsAlt=0"; + FitsStore store = new FitsStore(2); + spectralAxes( + twoAxis(spec(settings), null), + new double[] {100, 100}, + store, + new double[] {BAD, 1.42e9}, + new boolean[2]); + double r = Math.sqrt( + store.obsgeox * store.obsgeox + store.obsgeoy * store.obsgeoy + store.obsgeoz * store.obsgeoz); + assertTrue(Math.abs(r - 6_371_000.0) < 50_000.0, Double.toString(r)); + assertWritesAsC(C_OBSGEO, twoAxis(spec(settings), null), "", 100, 100); + } + + @Test + void labelOverrideEmitsCtypeCommentAndCname() { + String settings = "System=FREQ,Label(1)=MyFrequency"; + FitsStore store = new FitsStore(2); + spectralAxes( + twoAxis(spec(settings), null), + new double[] {100, 100}, + store, + new double[] {BAD, 1.42e9}, + new boolean[2]); + assertEquals("MyFrequency", store.ctypeCom[1]); + assertEquals("MyFrequency", store.cname[1]); + // C writes the label as the CTYPE comment; FITS-WCS writes no CNAME for it. + assertWritesAsC(C_LABEL, twoAxis(spec(settings), null), "", 100, 100); + } + + @Test + void sourceVelocityEmitsZsourceSsyssrc() { + String settings = "System=FREQ,SourceVel=1000"; + FitsStore store = new FitsStore(2); + spectralAxes( + twoAxis(spec(settings), null), + new double[] {100, 100}, + store, + new double[] {BAD, 1.42e9}, + new boolean[2]); + double expected = Math.sqrt((AST__C + 1.0e6) / (AST__C - 1.0e6)) - 1.0; + assertEquals(expected, store.zsource, 1e-9); + assertEquals("HELIOCEN", store.ssyssrc); + assertWritesAsC(C_SOURCEVEL, twoAxis(spec(settings), null), "", 100, 100); + } + + @Test + void crvalDefaultUsesBoundsMidpoint() { + FitsStore store = new FitsStore(2); + spectralAxes(twoAxis(spec("System=FREQ"), null), new double[] {100, 200}, store, null, new boolean[2]); + assertEquals(101.0, store.crval[1]); + assertWritesAsC(C_MIDPOINT, twoAxis(spec("System=FREQ"), null), "", 100, 200); + } + + @Test + void crvalDefaultIsPixelOneWithoutTheSpectralSize() { + assertWritesAsC(C_NODIMS, twoAxis(spec("System=FREQ"), null), "", 0, 0); + } + + @Test + void linearUnitMhzPreservesUserCunit() { + FitsStore store = new FitsStore(2); + spectralAxes( + twoAxis(spec("System=FREQ,Unit(1)=MHz"), null), new double[] {100, 100}, store, null, new boolean[2]); + assertEquals("MHz", store.cunit[1]); + assertWritesAsC(C_MHZ, twoAxis(spec("System=FREQ,Unit(1)=MHz"), null), "", 100, 100); + } + + @Test + void nonlinearUnitNeedsMathMap() { + // The conversion from log(Hz) to the default Unit is the MathMap C builds. + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> spectralAxes( + twoAxis(spec("System=FREQ,Unit(1)=log(Hz)"), null), + new double[] {100, 100}, + new FitsStore(2), + new double[] {BAD, 9.0}, + new boolean[2])); + assertTrue(e.getMessage().endsWith("needs MathMap"), e.getMessage()); + } + + @Test + void x2pCascadePicksFreqForWavelengthAxis() { + // Pixel axis 2 linear in frequency, 1e9 + 1e6 p Hz, the SpecFrame then set to wavelength + // through the FrameSet. + Mapping map = new CmpMap( + new UnitMap(1), new CmpMap(new ZoomMap(1, 1.0e6), new ShiftMap(new double[] {1.0e9}), true), false); + FrameSet fs = twoAxis(spec("System=FREQ,Unit=Hz"), map); + fs.setC("System(2)", "WAVE"); + FitsStore store = new FitsStore(2); + boolean[] axisDone = new boolean[2]; + spectralAxes(fs, new double[] {100, 100}, store, new double[] {BAD, AST__C / 1.05e9}, axisDone); + assertEquals("WAVE-F2W", store.ctype[1]); + assertTrue(axisDone[1]); + } + + // ------------------------------------------------------------------ + // Writes compared with C + // ------------------------------------------------------------------ + + @Test + void waveF2wWritesAsC() { + // testfitschan.c's non-linear WAVE-F2W FrameSet. + FrameSet fs = oneAxis(spec("System=FREQ,Unit=Hz,StdOfRest=Bary,RestFreq=1.4204E9 Hz"), new ZoomMap(1, 1.0e6)); + fs.set("System=WAVE"); + fs.set("Unit(1)=m"); + assertWritesAsC(C_WAVE_F2W, fs, "", 100, 0); + } + + @Test + void referencePositionAddsCelestialAxes() { + // MakeFitsFrameSet adds an FK5 SkyFrame for a 1-D SpecFrame with RefRA and RefDec set. + FrameSet fs = oneAxis( + spec("System=FREQ,Unit=Hz,StdOfRest=LSRK,RefRA=10:00:00,RefDec=-30:00:00,Epoch=2005.0," + + "RestFreq=1.4204E9 Hz"), + new ZoomMap(1, 1.0e6)); + assertWritesAsC(C_REFPOS_1D, fs, "", 100, 0); + assertEquals(1, fs.getNout(), "the FrameSet written is not changed"); + } + + @Test + void referenceRaAloneAddsNoAxes() { + FrameSet fs = oneAxis(spec("System=FREQ,Unit=Hz,StdOfRest=LSRK,RefRA=10:00:00"), new ZoomMap(1, 1.0e6)); + assertWritesAsC(C_REFPOS_1D_NOREST, fs, "", 100, 0); + } + + @Test + void referencePositionIsTheCelestialReferencePoint() { + // MakeFitsFrameSet sets RefRA and RefDec to the fiducial point of the celestial axes, so + // VELOSYS is that of (150, -30), whatever the SpecFrame had; also with the celestial + // axes galactic, which are set to FK5 J2000 to find it. + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.chan( + "NAXIS = 3", + "NAXIS1 = 10", + "NAXIS2 = 10", + "NAXIS3 = 20", + "CRPIX1 = 5", + "CRPIX2 = 5", + "CRPIX3 = 10", + "CRVAL1 = 150", + "CRVAL2 = -30", + "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", + "MJD-OBS = 53000.0")); + fs.set("RefRA=0:0:0,RefDec=0:0:0"); + assertEquals("0:00:00.0", fs.getC("RefRA")); + assertEquals("0:00:00", fs.getC("RefDec")); + assertWritesAsC(C_REFPOS_SKY, fs, "", 10, 10); + assertEquals("0:00:00.0", fs.getC("RefRA"), "the FrameSet written is not changed"); + fs.set("System(1)=GALACTIC"); + // C fits the galactic TAN projection (FitLine) to points transformed through SphMaps and + // SlaMaps, whose sines and arctangents in java.lang.Math differ from C's libm by about an + // ULP, by different amounts on different processors and Java runtimes. An ULP of the + // galactic longitude (264 degrees, 6e-14) over the few pixels the fit spans is about 1e-11 + // of the 0.001 degree pixel size, so the fitted CDELT2 and PC elements need only agree + // with C's to that relative tolerance. + Map fitted = new HashMap<>(); + fitted.put("CDELT2", 1.0e-14); + for (String pc : new String[] {"PC1_1", "PC1_2", "PC2_1", "PC2_2"}) { + fitted.put(pc, 1.0e-11); + } + assertWritesAsC(C_REFPOS_SKY_GAL, fs, "", 10, 10, fitted); + } + + @Test + void dsbSpecFrameWritesImagfreq() { + DSBSpecFrame dsb = new DSBSpecFrame(); + dsb.set("System=FREQ,Unit=GHz,StdOfRest=LSRK,RestFreq=230.5,DSBCentre=230,IF=4,SideBand=USB"); + assertWritesAsC(C_DSB, oneAxis(dsb, new ZoomMap(1, 0.001)), "", 100, 0); + } + + @Test + void dsbSpecFrameWithoutRestFreqWritesNoImagfreq() { + DSBSpecFrame dsb = new DSBSpecFrame(); + dsb.set("System=FREQ,Unit=GHz,StdOfRest=LSRK,DSBCentre=230,IF=4,SideBand=USB"); + assertWritesAsC(C_DSB_NOREST, oneAxis(dsb, new ZoomMap(1, 0.001)), "", 100, 0); + } + + @Test + void sourceStandardOfRestWritesTheSourceVelocityAsVelosys() { + assertWritesAsC( + C_SOURCE_SOR, + oneAxis( + spec("System=FREQ,Unit=Hz,StdOfRest=Source,SourceVel=1000,SourceVRF=LSRK,RestFreq=1.4204E9 Hz"), + new ZoomMap(1, 1.0e6)), + "", + 100, + 0); + } + + @Test + void sourceVelocityKeepsItsRestFrame() { + FrameSet fs = oneAxis( + spec("System=VRAD,StdOfRest=Bary,SourceVel=-200,SourceVRF=Helio,RestFreq=1.4204E9 Hz"), + new ZoomMap(1, 1.0)); + assertWritesAsC(C_ZSOURCE_VRAD, fs, "", 100, 0); + SpecFrame sf = (SpecFrame) fs.getFrame(FrameSet.AST__CURRENT); + assertEquals("Heliocentric", sf.getC("SourceVRF")); + assertEquals(-200.0, sf.getSourceVel(), 1e-9); + } + + @Test + void logarithmicAxisNeedsMathMap() { + // C probe case log: C writes FREQ-LOG, whose Mapping holds a MathMap. + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> written(oneAxis(spec("System=FREQ"), exponential(1.4, 0.001)), "", 100, 0)); + assertTrue(e.getMessage().endsWith("needs MathMap"), e.getMessage()); + } + + @Test + void tabulatedAxisNeedsFitsTable() { + // C probe cases quad_tab and forcetab: C writes FREQ-TAB, with its table in a FitsTable. + for (FrameSet fs : Arrays.asList( + oneAxis(spec("System=FREQ"), quadratic(1.4, 0.001, 0.0001)), + oneAxis(spec("System=FREQ"), new ZoomMap(1, 0.001)))) { + String attrs = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) instanceof ZoomMap + ? "TabOK=1,ForceTab=1" + : "TabOK=1"; + UnsupportedOperationException e = + assertThrows(UnsupportedOperationException.class, () -> written(fs, attrs, 100, 0)); + assertTrue(e.getMessage().endsWith("needs FitsTable"), e.getMessage()); + } + } + + @Test + void axisNoAlgorithmDescribesIsNotWritten() { + // Without TabOK, a quadratic spectral axis is left to OtherAxes, whose linear description + // MakeIntWorld rejects. + assertWritesAsC(C_QUAD_NOTAB, oneAxis(spec("System=FREQ"), quadratic(1.4, 0.001, 0.0001)), "", 100, 0); + } + + @Test + void forceTabWithoutTabOkLeavesTheAxisToOtherAxes() { + assertWritesAsC(C_FORCETAB_NOTABOK, oneAxis(spec("System=FREQ"), new ZoomMap(1, 0.001)), "ForceTab=1", 100, 0); + } + + @Test + void getFitsSorNamesEachStandardOfRest() { + String[] ast = { + "Topocentric", + "Geocentric", + "Barycentric", + "Heliocentric", + "LSRK", + "LSRD", + "Galactic", + "Local_group", + "Source" + }; + String[] fits = { + "TOPOCENT", "GEOCENTR", "BARYCENT", "HELIOCEN", "LSRK", "LSRD", "GALACTOC", "LOCALGRP", "SOURCE" + }; + for (int i = 0; i < ast.length; i++) { + assertEquals(fits[i], FitsSpectralAxes.getFitsSor(ast[i])); + } + assertNull(FitsSpectralAxes.getFitsSor("lsrk")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FitsWcsCelestialTest.java b/src/test/java/uk/ac/starlink/ast/FitsWcsCelestialTest.java index caa3d00..c31a1b5 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsWcsCelestialTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsWcsCelestialTest.java @@ -175,7 +175,7 @@ void axrefOverridesCrvalReferencePosition() { store.axref[0] = 119.5; store.axref[1] = 30.5; FitsWcsCelestial.CelestialResult cel = buildCelestial(store); - assertArrayEquals(new double[] {119.5 * DD2R, 30.5 * DD2R}, cel.refPos); + assertArrayEquals(new double[] {119.5 * DD2R, 30.5 * DD2R}, new double[] {cel.refLon, cel.refLat}); assertTrue(cel.refPosForced); } @@ -188,7 +188,7 @@ void crvalReferencePositionIsNotForced() { store.cdelt[0] = -0.01; store.cdelt[1] = 0.01; FitsWcsCelestial.CelestialResult cel = buildCelestial(store); - assertEquals(120.0 * DD2R, cel.refPos[0]); + assertEquals(120.0 * DD2R, cel.refLon); assertFalse(cel.refPosForced); } @@ -278,7 +278,7 @@ void carLinIsLinear() { double[] p = forward(cel.mapping, 1.0, 2.0); assertEquals(1.0 * DD2R + 10.0 * DD2R, p[0], 1e-15); assertEquals(2.0 * DD2R + 20.0 * DD2R, p[1], 1e-15); - assertArrayEquals(new double[] {10.0 * DD2R, 20.0 * DD2R}, cel.refPos); + assertArrayEquals(new double[] {10.0 * DD2R, 20.0 * DD2R}, new double[] {cel.refLon, cel.refLat}); } /** With latitude first, the SkyFrame's axes are swapped to match the Mapping's outputs. */ diff --git a/src/test/java/uk/ac/starlink/ast/FitsWcsReadTest.java b/src/test/java/uk/ac/starlink/ast/FitsWcsReadTest.java index 018731a..785a762 100644 --- a/src/test/java/uk/ac/starlink/ast/FitsWcsReadTest.java +++ b/src/test/java/uk/ac/starlink/ast/FitsWcsReadTest.java @@ -15,10 +15,6 @@ * Translates the unit tests of Rust {@code fitschan/wcs_read.rs} ({@code mod tests}), which build * FitsStores directly, and adds tests of the pieces of C's {@code FsetFromStore}, {@code WcsMapFrm} * and {@code WcsOthers} the read is made of. - * - *

    {@code decode_1d_spectral}, {@code decode_3d_mixed} and {@code - * build_pixel_to_world_handles_non_adjacent_celestial_axes} read spectral axes, which need - * SpecFrame, and are listed in {@code deferred/rust-tests.txt}. */ class FitsWcsReadTest { @@ -72,12 +68,66 @@ void tabAxisNeedsLutMapWhenTabOkIsPositive() { } @Test - void spectralAxisNeedsSpecFrame() { + void decode1dSpectral() { FitsStore store = new FitsStore(1); store.ctype[0] = "FREQ"; + store.crpix[0] = 1.0; store.crval[0] = 1.4e9; - UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, () -> decodeWcs(store)); - assertTrue(e.getMessage().endsWith(" needs SpecFrame"), e.getMessage()); + store.cdelt[0] = 1.0e6; + FrameSet fs = decodeWcs(store); + assertEquals(2, fs.getNframe()); + assertEquals(1, fs.getFrame(FrameSet.AST__BASE).getNaxes()); + assertEquals(1, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + // CRPIX maps to CRVAL. + assertEquals(1.4e9, FitsHeaders.tran(fs, new double[] {1.0}, true)[0], 1.0); + } + + @Test + void decode3dMixed() { + FitsStore store = new FitsStore(3); + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.ctype[2] = "FREQ"; + store.crpix[0] = 128.0; + store.crpix[1] = 128.0; + store.crpix[2] = 1.0; + store.crval[0] = 180.0; + store.crval[1] = 45.0; + store.crval[2] = 1.4e9; + store.cdelt[0] = -0.001; + store.cdelt[1] = 0.001; + store.cdelt[2] = 1.0e6; + FrameSet fs = decodeWcs(store); + assertEquals(2, fs.getNframe()); + assertEquals(3, fs.getFrame(FrameSet.AST__BASE).getNaxes()); + assertEquals(3, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + } + + @Test + void buildPixelToWorldHandlesNonAdjacentCelestialAxes() { + // FITS axes DEC, WAVE, RA: the celestial pair is separated by the spectral axis. + FitsStore store = new FitsStore(3); + store.ctype[0] = "DEC--TAN"; + store.ctype[1] = "WAVE "; + store.ctype[2] = "RA---TAN"; + store.crval[0] = 22.0; + store.crval[1] = 5.0e-7; + store.crval[2] = 83.6; + store.crpix[0] = 50.5; + store.crpix[1] = 25.5; + store.crpix[2] = 50.5; + store.cdelt[0] = 2.78e-4; + store.cdelt[1] = 1.0e-10; + store.cdelt[2] = -2.78e-4; + store.cunit[1] = "m"; + FrameSet fs = decodeWcs(store); + assertEquals(3, fs.getFrame(FrameSet.AST__BASE).getNaxes()); + assertEquals(3, fs.getFrame(FrameSet.AST__CURRENT).getNaxes()); + // At the reference pixel, axis 1 is the declination and axis 3 the right ascension. + double[] out = FitsHeaders.tran(fs, new double[] {50.5, 25.5, 50.5}, true); + assertEquals(22.0, Math.toDegrees(out[0]), 1e-9); + assertEquals(5.0e-7, out[1], 1e-20); + assertEquals(83.6, Math.toDegrees(out[2]), 1e-9); } @Test @@ -129,14 +179,14 @@ void linearFrameTakesSymbolsLabelsUnitsAndWcsname() { store.ctype[1] = "Y"; store.cname[1] = "Height"; store.cunit[0] = "m"; - Frame frame = FitsWcsRead.buildWorldFrame(store, null); + Frame frame = FitsWcsRead.buildWorld(store, null, ' ', new FitsWarnings()).frame; assertEquals("X", frame.getSymbol(1)); assertEquals("X", frame.getLabel(1)); assertEquals("Height", frame.getLabel(2)); assertEquals("m", frame.getUnit(1)); assertEquals("X-Y", frame.getDomain()); store.wcsname = "Plane"; - frame = FitsWcsRead.buildWorldFrame(store, null); + frame = FitsWcsRead.buildWorld(store, null, ' ', new FitsWarnings()).frame; assertEquals("PLANE", frame.getDomain()); assertEquals("Plane coordinates", frame.getTitle()); } diff --git a/src/test/java/uk/ac/starlink/ast/FitsWcsSpectralTest.java b/src/test/java/uk/ac/starlink/ast/FitsWcsSpectralTest.java new file mode 100644 index 0000000..e2d18e4 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FitsWcsSpectralTest.java @@ -0,0 +1,551 @@ +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.assertSame; +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 {@link FitsWcsSpectral}, C's {@code WcsSpectral}: the unit tests of Rust {@code + * fitschan/wcs_spectral.rs} ({@code mod tests}), which build FitsStores directly, and reads of + * spectral headers through a FitsChan compared with what C's {@code astRead} gives for the same + * cards (the SpecFrame's attributes as {@code astGetC} formats them, the pixel to world transform, + * and the error status and messages), including the read half of the plan's Review Focus 5: a + * spectral axis whose Mapping needs a class that is not available ({@code -LOG} through MathMap, + * {@code -GRI} through GrismMap, {@code -TAB} through LutMap) fails with {@code needs }. + */ +class FitsWcsSpectralTest { + + // ------------------------------------------------------------------ + // fitschan/wcs_spectral.rs + // ------------------------------------------------------------------ + + /** Rust's {@code build_spectral} on {@code store}, with no celestial axes. */ + private static FitsWcsSpectral.Result spectral(FitsStore store) { + return FitsWcsSpectral.wcsSpectral( + store, ' ', new Frame(store.naxis), new String[store.naxis], null, new FitsWarnings()); + } + + /** The SpecFrame the spectral stage put on {@code axis} (from 1) of its Frame. */ + private static SpecFrame specFrameOn(FitsWcsSpectral.Result result, int axis) { + Frame primary = result.frame.primaryFrame(axis, new int[1]); + assertInstanceOf(SpecFrame.class, primary, "axis " + axis + " is in a " + primary.astClass()); + return (SpecFrame) primary; + } + + @Test + void detectsFreqAxis() { + FitsStore store = new FitsStore(3); + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + store.ctype[2] = "FREQ"; + store.crval[2] = 1.4e9; + FitsWcsSpectral.Result result = spectral(store); + assertEquals("FREQ", specFrameOn(result, 3).getC("System")); + assertEquals(3, result.map.getNin()); + assertEquals(3, result.map.getNout()); + assertFalse(result.frame.primaryFrame(1, new int[1]) instanceof SpecFrame); + } + + @Test + void detectsWaveAxis() { + FitsStore store = new FitsStore(1); + store.ctype[0] = "WAVE"; + store.crval[0] = 5.0e-7; + assertEquals("WAVE", specFrameOn(spectral(store), 1).getC("System")); + } + + @Test + void detectsVradAxis() { + FitsStore store = new FitsStore(1); + store.ctype[0] = "VRAD"; + store.crval[0] = 0.0; + assertEquals("VRAD", specFrameOn(spectral(store), 1).getC("System")); + } + + @Test + void setsStdOfRest() { + FitsStore store = new FitsStore(1); + store.ctype[0] = "FREQ"; + store.crval[0] = 1.0e9; + store.specsys = "LSRK"; + assertEquals("LSRK", specFrameOn(spectral(store), 1).getStdOfRest()); + } + + @Test + void setsRestFreq() { + FitsStore store = new FitsStore(1); + store.ctype[0] = "VRAD"; + store.crval[0] = 0.0; + store.restfrq = 1.420405751786e9; + assertEquals(1.420405751786e9, specFrameOn(spectral(store), 1).restFreqValue(), 1.0); + } + + @Test + void noSpectralReturnsUnitMapsAndTheFrame() { + FitsStore store = new FitsStore(2); + store.ctype[0] = "RA---TAN"; + store.ctype[1] = "DEC--TAN"; + Frame frame = new Frame(2); + FitsWcsSpectral.Result result = + FitsWcsSpectral.wcsSpectral(store, ' ', frame, new String[2], null, new FitsWarnings()); + assertSame(frame, result.frame); + double[] out = FitsHeaders.tran(result.map, new double[] {3.0, 4.0}, true); + assertEquals(3.0, out[0]); + assertEquals(4.0, out[1]); + } + + @Test + void crvalShiftMapping() { + FitsStore store = new FitsStore(1); + store.ctype[0] = "FREQ"; + store.crval[0] = 1.4e9; + Mapping map = spectral(store).map; + assertEquals(1.4e9, FitsHeaders.tran(map, new double[] {0.0}, true)[0], 1.0); + assertEquals(1.4e9 + 1.0e6, FitsHeaders.tran(map, new double[] {1.0e6}, true)[0], 1.0); + } + + @Test + void everySpectralAxisInAxisOrder() { + FitsStore store = new FitsStore(3); + store.ctype[0] = "WAVE"; + store.ctype[1] = "RA---TAN"; + store.ctype[2] = "FREQ"; + store.crval[0] = 1.0e-6; + store.crval[2] = 1.4e9; + String[] iwcUnits = new String[3]; + FitsWcsSpectral.Result result = + FitsWcsSpectral.wcsSpectral(store, ' ', new Frame(3), iwcUnits, null, new FitsWarnings()); + assertEquals("WAVE", specFrameOn(result, 1).getC("System")); + assertEquals("FREQ", specFrameOn(result, 3).getC("System")); + assertFalse(result.frame.primaryFrame(2, new int[1]) instanceof SpecFrame); + // Each spectral axis's IWC unit is the default unit of its system. + assertEquals(Arrays.asList("m", null, "Hz"), Arrays.asList(iwcUnits)); + } + + @Test + void algorithmCodeIsAtMostFourCharactersWithoutTrailingSpaces() { + assertEquals("", FitsWcsSpectral.algorithmCode("FREQ")); + assertEquals("", FitsWcsSpectral.algorithmCode("FREQ ")); + assertEquals("-F2W", FitsWcsSpectral.algorithmCode("FREQ-F2W")); + assertEquals("-F2W", FitsWcsSpectral.algorithmCode("FREQ-F2WXYZ")); + assertEquals("-LOG", FitsWcsSpectral.algorithmCode("FREQ-LOG ")); + } + + // ------------------------------------------------------------------ + // Headers read through a FitsChan, against C's astRead + // ------------------------------------------------------------------ + + /** The cards every one-axis header below starts with. */ + private static final String[] COMMON = {"NAXIS = 1", "NAXIS1 = 10", "CRPIX1 = 1", "CDELT1 = 1.0E6"}; + + /** The one-axis header of {@link #COMMON} followed by {@code cards}. */ + private static FitsChan oneAxis(String... cards) { + String[] all = Arrays.copyOf(COMMON, COMMON.length + cards.length); + System.arraycopy(cards, 0, all, COMMON.length, cards.length); + return FitsHeaders.chan(all); + } + + /** The attributes C's probe prints for the Frame of a spectral axis, in its order. */ + private static final String[] ATTRS = { + "Class", + "System", + "Unit(1)", + "Label(1)", + "Domain", + "StdOfRest", + "SourceVRF", + "SourceSys", + "SourceVel", + "RestFreq", + "RefRA", + "RefDec", + "Epoch", + "ObsLon", + "ObsLat", + "ObsAlt" + }; + + /** + * Checks the Frame of axis {@code axis} (from 1) of {@code fs}, picked from its current Frame, + * against C's attribute values, {@code want} holding one value for each of {@link #ATTRS} + * (the first five for a Frame that is not a SpecFrame) and then, for a DSBSpecFrame, the + * DSBCentre, IF, SideBand and ImagFreq. + */ + private static void assertAttributes(FrameSet fs, int axis, String... want) { + Frame f = fs.pickAxes(1, new int[] {axis}, null); + int n = 0; + for (int i = 0; i < ATTRS.length && n < want.length; i++) { + if (i >= 5 && !(f instanceof SpecFrame)) { + break; + } + String attr = ATTRS[i]; + String got = "Class".equals(attr) ? f.astClass() : f.getC(attr); + assertEquals(want[n++], got, attr); + } + if (f instanceof DSBSpecFrame) { + for (String attr : new String[] {"DSBCentre", "IF", "SideBand", "ImagFreq"}) { + assertEquals(want[n++], f.getC(attr), attr); + } + } + assertEquals(want.length, n, "attributes compared"); + } + + /** + * Checks the transform of the pixel positions (1, ...) and (7.5, ...) by {@code fs} against + * C's, given as one row per position. + */ + private static void assertForward(FrameSet fs, double[]... want) { + int naxes = fs.getNin(); + for (int p = 0; p < want.length; p++) { + double[] in = new double[naxes]; + Arrays.fill(in, p == 0 ? 1.0 : 7.5); + double[] out = FitsHeaders.tran(fs, in, true); + for (int k = 0; k < naxes; k++) { + assertEquals(want[p][k], out[k], Math.abs(want[p][k]) * 1e-13, "point " + p + " axis " + (k + 1)); + } + } + } + + /** The current Frame's class, Domain and Title. */ + private static void assertCurrent(FrameSet fs, String cls, String domain, String title) { + Frame cur = fs.getFrame(FrameSet.AST__CURRENT); + assertEquals(cls, cur.astClass()); + assertEquals(domain, cur.getDomain()); + assertEquals(title, cur.getTitle()); + } + + /** + * A DSBSpecFrame, from IMAGFREQ, with every keyword WcsSpectral sets on it: the reference + * position from the celestial axes, the Epoch from MJD-OBS, the observer from OBSGEO, the + * source velocity from SSYSSRC and ZSOURCE, the standard of rest, the rest frequency and the + * Label from CNAME; DSBSetUp then sets the DSBCentre, IF and SideBand. + */ + @Test + void dsbSpecFrameTakesEveryKeywordAsC() { + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.chan( + "NAXIS = 3", + "NAXIS1 = 10", + "NAXIS2 = 10", + "NAXIS3 = 10", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CTYPE3 = 'FREQ'", + "CRPIX1 = 5", + "CRPIX2 = 5", + "CRPIX3 = 3", + "CRVAL1 = 83.6", + "CRVAL2 = 22.0", + "CRVAL3 = 2.30E11", + "CDELT1 = -0.001", + "CDELT2 = 0.001", + "CDELT3 = 1.0E6", + "CNAME3 = 'Sky frequency'", + "RADESYS = 'FK5'", + "EQUINOX = 2000.0", + "MJD-OBS = 53000.25", + "SPECSYS = 'LSRK'", + "SSYSSRC = 'BARYCENT'", + "ZSOURCE = 0.01", + "RESTFRQ = 2.31E11", + "IMAGFREQ= 2.40E11", + "OBSGEO-X= -5464588.868", + "OBSGEO-Y= -2493001.1635", + "OBSGEO-Z= 2150654.3527")); + assertAttributes( + fs, + 3, + "DSBSpecFrame", + "FREQ", + "Hz", + "Sky frequency", + "DSBSPECTRUM", + "LSRK", + "Barycentric", + "VELO", + "2982.9356991238064", + "231.00000000000003", + "5:34:24.0", + "22:00:00", + "2003.9856283172294", + "W155:28:37.36", + "N19:49:22.19", + "4123.7639304737932", + "230000000000.00003", + "3.177611669601685", + "LSB", + "240.00000000000006"); + assertCurrent(fs, "CmpFrame", "SKY-DSBSPECTRUM", "3-d compound coordinate system"); + assertForward(fs, new double[] {1.4591705484727806, 0.3839026212843969, 229998000000.0}, new double[] { + 1.4590481938817685, 0.384016068285372, 230004500000.0 + }); + } + + /** The rest frequency from RESTWAV, and a CUNIT that is not the default unit. */ + @Test + void restWavelengthGivesTheRestFrequency() { + FrameSet fs = FitsHeaders.readFrameSet(oneAxis( + "CTYPE1 = 'VOPT'", "CRVAL1 = 1.5E6", "CUNIT1 = 'km/s'", "RESTWAV = 2.1E-1", "SPECSYS = 'BARYCENT'")); + assertAttributes( + fs, + 1, + "SpecFrame", + "VOPT", + "km/s", + "Optical velocity", + "SPECTRUM", + "Barycentric", + "Heliocentric", + "VELO", + "0", + "1.4275831333333335", + "0:00:00.0", + "0:00:00", + "2000.0", + "E0:00:00.00", + "N0:00:00.00", + "0"); + assertCurrent(fs, "SpecFrame", "SPECTRUM", "Optical velocity (Barycentric), rest frequency = 1.42758 GHz"); + assertForward(fs, new double[] {1500000.0}, new double[] {8000000.0}); + } + + /** A {@code -F2W} axis: wavelength, sampled linearly in frequency (C's NonLinSpecWcs). */ + @Test + void wavelengthSampledInFrequency() { + FrameSet fs = FitsHeaders.readFrameSet( + oneAxis("CTYPE1 = 'WAVE-F2W'", "CRVAL1 = 0.21", "CDELT1 = 1.0E-5", "RESTFRQ = 1.42E9")); + assertEquals("WAVE", fs.getC("System")); + assertEquals("1.4200000000000002", fs.getC("RestFreq")); + assertCurrent(fs, "SpecFrame", "SPECTRUM", "Wavelength"); + assertForward(fs, new double[] {0.20999999999999996}, new double[] {0.21006502012527684}); + } + + /** A {@code -V2F} axis: radio velocity, sampled linearly in apparent radial velocity. */ + @Test + void radioVelocitySampledInApparentVelocity() { + FrameSet fs = FitsHeaders.readFrameSet(oneAxis("CTYPE1 = 'VRAD-V2F'", "CRVAL1 = 1.0E5", "RESTFRQ = 1.42E9")); + assertCurrent(fs, "SpecFrame", "SPECTRUM", "Radio velocity, rest frequency = 1.42 GHz"); + assertForward(fs, new double[] {99999.99999999505}, new double[] {6531061.606396163}); + } + + /** ZOPT's default unit is blank, and C sets that blank Unit. */ + @Test + void redshiftHasABlankDefaultUnit() { + FrameSet fs = FitsHeaders.readFrameSet(oneAxis("CTYPE1 = 'ZOPT'", "CRVAL1 = 0.5", "CDELT1 = 0.01")); + assertAttributes(fs, 1, "SpecFrame", "ZOPT", "", "Redshift", "SPECTRUM"); + assertCurrent(fs, "SpecFrame", "SPECTRUM", "Redshift, rest frequency = 100000 GHz"); + assertForward(fs, new double[] {0.5}, new double[] {0.565}); + } + + /** C's IsSpectral compares the system code case by case, so a lower-case CTYPE is a linear axis. */ + @Test + void lowerCaseSystemIsALinearAxis() { + FrameSet fs = FitsHeaders.readFrameSet(oneAxis("CTYPE1 = 'freq'", "CRVAL1 = 1.4E9")); + assertAttributes(fs, 1, "Frame", "Cartesian", "", "freq", "FREQ"); + assertCurrent(fs, "Frame", "FREQ", "1-d coordinate system"); + assertForward(fs, new double[] {1400000000.0}, new double[] {1406500000.0}); + } + + /** Two spectral axes, each its own SpecFrame; with no other axes the WCSNAME is not used. */ + @Test + void twoSpectralAxesIgnoreTheWcsname() { + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.chan( + "NAXIS = 2", + "NAXIS1 = 10", + "NAXIS2 = 10", + "CRPIX1 = 1", + "CRPIX2 = 1", + "CTYPE1 = 'WAVE'", + "CTYPE2 = 'FREQ'", + "CRVAL1 = 1.0E-6", + "CRVAL2 = 1.4E9", + "CDELT1 = 1.0E-9", + "CDELT2 = 1.0E6", + "WCSNAME = 'TWO'")); + assertAttributes(fs, 2, "SpecFrame", "FREQ", "Hz", "Frequency", "SPECTRUM"); + assertAttributes(fs, 1, "SpecFrame", "WAVE", "m", "Wavelength", "SPECTRUM"); + assertCurrent(fs, "CmpFrame", "SPECTRUM-SPECTRUM", "2-d compound coordinate system"); + assertForward(fs, new double[] {1.0e-6, 1400000000.0}, new double[] {1.0064999999999998e-06, 1406500000.0}); + } + + /** A spectral axis and another axis: the WCSNAME names the CmpFrame. */ + @Test + void wcsnameNamesTheFrameWithAnotherAxis() { + FrameSet fs = FitsHeaders.readFrameSet(FitsHeaders.chan( + "NAXIS = 2", + "NAXIS1 = 10", + "NAXIS2 = 4", + "CRPIX1 = 1", + "CRPIX2 = 1", + "CTYPE1 = 'FREQ'", + "CTYPE2 = 'STOKES'", + "CRVAL1 = 1.4E9", + "CRVAL2 = 1", + "CDELT1 = 1.0E6", + "CDELT2 = 1", + "WCSNAME = 'NAMED'")); + assertCurrent(fs, "CmpFrame", "NAMED", "NAMED coordinates"); + assertForward(fs, new double[] {1400000000.0, 1.0}, new double[] {1406500000.0, 7.5}); + } + + /** The error C's read reports for an algorithm code it cannot implement on axis 1. */ + private static void assertCannotImplement(String code, FitsChan fc) { + AstException e = assertThrows(AstException.class, fc::read); + assertEquals(AstException.AST__BDFTS, e.getStatus()); + assertEquals( + "astRead(FitsChan): Cannot implement spectral algorithm code '" + code + + "' specified in FITS keyword 'CTYPE1'.\nastRead(FitsChan): Unknown algorithm code or" + + " unusable parameter values.", + e.getMsgText()); + } + + @Test + void unknownAlgorithmCodeIsAnError() { + assertCannotImplement("-XYZ", oneAxis("CTYPE1 = 'FREQ-XYZ'", "CRVAL1 = 1.4E9")); + } + + @Test + void unknownLinearSystemOfAnX2pCodeIsAnError() { + assertCannotImplement("-Q2F", oneAxis("CTYPE1 = 'FREQ-Q2F'", "CRVAL1 = 1.4E9")); + } + + /** A {@code -LOG} spectral axis with a zero CRVAL has no logarithmic form, and C fails. */ + @Test + void logAxisWithZeroCrvalIsAnError() { + assertCannotImplement("-LOG", oneAxis("CTYPE1 = 'FREQ-LOG'", "CRVAL1 = 0.0")); + } + + /** With TabOK not above zero C reads no table, and the spectral stage fails at {@code -TAB}. */ + @Test + void tabAxisWithoutTabOkIsAnError() { + assertCannotImplement("-TAB", oneAxis("CTYPE1 = 'WAVE-TAB'", "CRVAL1 = 1.4E9")); + } + + /** C sets SPECSYS as the StdOfRest attribute, which refuses a value it does not know. */ + @Test + void unknownSpecsysIsAnError() { + AstException e = assertThrows( + AstException.class, + () -> oneAxis("CTYPE1 = 'FREQ'", "CRVAL1 = 1.4E9", "SPECSYS = 'BOGUS'") + .read()); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertEquals("astSetAttrib(SpecFrame): Invalid standard of rest description \"BOGUS\".", e.getMsgText()); + } + + /** C sets SSYSSRC as the SourceVRF attribute, which refuses a value it does not know. */ + @Test + void unknownSsyssrcIsAnError() { + AstException e = assertThrows( + AstException.class, + () -> oneAxis("CTYPE1 = 'FREQ'", "CRVAL1 = 1.4E9", "SSYSSRC = 'BOGUS'") + .read()); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertEquals("astSetAttrib(SpecFrame): Invalid standard of rest description \"BOGUS\".", e.getMsgText()); + } + + // ------------------------------------------------------------------ + // Review Focus 5, read half: spectral axes needing absent classes + // ------------------------------------------------------------------ + + /** C maps a {@code -LOG} spectral axis with a non-zero CRVAL with a MathMap (C's LogWcs). */ + @Test + void logSpectralAxisNeedsMathMap() { + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> oneAxis("CTYPE1 = 'FREQ-LOG'", "CRVAL1 = 1.4E9").read()); + assertTrue(e.getMessage().endsWith(" needs MathMap"), e.getMessage()); + } + + /** C maps a {@code -GRI} axis with a GrismMap once the SpecFrame converts to wavelength. */ + @Test + void grismAxisNeedsGrismMap() { + for (String ctype : new String[] {"WAVE-GRI", "WAVE-GRA"}) { + UnsupportedOperationException e = assertThrows( + UnsupportedOperationException.class, + () -> oneAxis( + "CTYPE1 = '" + ctype + "'", + "CRVAL1 = 5.0E-7", + "CDELT1 = 1.0E-10", + "PV1_0 = 3.0E5", + "PV1_1 = 1") + .read()); + assertTrue(e.getMessage().endsWith(" needs GrismMap"), e.getMessage()); + } + } + + /** With TabOK above zero C reads a {@code -TAB} spectral axis through a LutMap. */ + @Test + void tabSpectralAxisNeedsLutMapWithTabOk() { + FitsChan fc = oneAxis("CTYPE1 = 'WAVE-TAB'", "CRVAL1 = 1.4E9", "PS1_0 = 'WCS-TAB'"); + fc.setI("TabOK", 1); + UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, fc::read); + assertTrue(e.getMessage().endsWith(" needs LutMap"), e.getMessage()); + } + + /** + * A header with CRVAL1 but no CRVAL2: C's {@code WcsCelestial} returns the reference longitude + * and latitude separately, and {@code WcsSpectral} passes both to {@code astSetRefPos}, so the + * SpecFrame takes RefRA from CRVAL1 and leaves RefDec unset. C's values: RefRA 10:00:00.0, + * RefDec 0:00:00 (unset), the barycentric velocity 0 m/s converts to -8899.1984878203566 m/s + * LSRK, and a FITS-WCS write gives VELOSYS 28372.571560485387 m/s. + */ + @Test + void oneCelestialReferenceValueSetsOneReferenceCoordinate() { + FitsChan fc = FitsHeaders.chan( + "NAXIS1 = 100", + "NAXIS2 = 100", + "NAXIS3 = 1024", + "CTYPE1 = 'RA---TAN'", + "CTYPE2 = 'DEC--TAN'", + "CTYPE3 = 'VRAD '", + "CRVAL1 = 150.000", + "CRVAL3 = 0.0", + "CRPIX1 = 50.500", + "CRPIX2 = 50.500", + "CRPIX3 = 512.500", + "CDELT1 = -0.00083333", + "CDELT2 = 0.00083333", + "CDELT3 = 1000.0", + "CUNIT1 = 'deg '", + "CUNIT2 = 'deg '", + "CUNIT3 = 'm/s '", + "RADESYS = 'FK5 '", + "EQUINOX = 2000.0", + "RESTFRQ = 1.420405752E9", + "MJD-OBS = 52413.59", + "SSYSSRC = 'BARYCENT'", + "SPECSYS = 'BARYCENT'"); + FrameSet fs = FitsHeaders.readFrameSet(fc); + Frame spec = fs.pickAxes(1, new int[] {3}, null); + assertInstanceOf(SpecFrame.class, spec); + assertEquals("10:00:00.0", spec.getC("RefRA")); + assertEquals("0:00:00", spec.getC("RefDec")); + assertTrue(spec.test("RefRA")); + assertFalse(spec.test("RefDec")); + + Frame lsrk = (Frame) spec.copy(); + lsrk.set("StdOfRest=LSRK"); + double v = FitsHeaders.tran(spec.convert(lsrk, ""), new double[] {0.0}, true)[0]; + assertEquals(-8899.198487820357, v, 8899.2 * 1e-12); + + FitsChan out = new FitsChan(); + out.setEncoding("FITS-WCS"); + out.putFits("NAXIS1 = 100", false); + out.putFits("NAXIS2 = 100", false); + out.putFits("NAXIS3 = 1024", false); + assertEquals(1, out.write(fs)); + out.clear("Card"); + String velosys = out.findFits("VELOSYS", false); + assertTrue( + FitsHeaders.cardsMatchC( + Arrays.asList(velosys), + FitsHeaders.padded( + "VELOSYS = 28372.571560485387 / [m/s] Topo. apparent velocity of rest frame")), + velosys); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FluxBadunOracleTest.java b/src/test/java/uk/ac/starlink/ast/FluxBadunOracleTest.java new file mode 100644 index 0000000..f1d2ad4 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FluxBadunOracleTest.java @@ -0,0 +1,69 @@ +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 java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_flux_badun.rs}: where a FluxFrame Unit that suits no flux + * System is reported, checked against C ({@code oracle/flux_badun.json}, from {@code + * tools/oracle_fixtures/flux_badun_probe.c}). C's {@code GetSystem} takes an unset System from a + * set Unit and reports AST__BADUN when no flux System's default units convert to it; {@code + * SetUnit} stores the Unit and then reads the System, clearing a set System the Unit does not + * suit; and the Title, Label and Symbol defaults read the System (fluxframe.c). + */ +class FluxBadunOracleTest { + + /** {@code Ok:} or {@code Err:}, as the probe records an outcome. */ + private static String outcome(Supplier f) { + try { + return "Ok:" + f.get(); + } catch (AstException e) { + return "Err:" + (e.getStatus() == AstException.AST__BADUN ? "Badun" : "other"); + } + } + + private static String want(JsonNode r) { + return r.get("variant").asText() + ":" + r.get("value").asText(); + } + + @Test + void badUnitsAreReportedAsInTheCLibrary() { + JsonNode data = ProbeData.load("flux_badun"); + JsonNode attrs = data.get("ATTRS"); + List failures = new ArrayList<>(); + int run = 0; + for (JsonNode c : data.get("CASES")) { + String system = c.get(0).asText(); + String unit = c.get(1).asText(); + FluxFrame f = new FluxFrame(1.4e9, null); + if (!system.isEmpty()) { + f.set(system); + } + List got = new ArrayList<>(); + List exp = new ArrayList<>(); + got.add(outcome(() -> { + f.setUnit(1, unit); + return ""; + })); + exp.add(want(c.get(2))); + for (int i = 0; i < attrs.size(); i++) { + String attr = attrs.get(i).asText(); + got.add(outcome(() -> f.getC(attr))); + exp.add(want(c.get(3).get(i))); + } + if (!got.equals(exp)) { + failures.add("[" + system + "] Unit=" + unit + ": got " + got + ", C gives " + exp); + } + run++; + } + assertEquals(6, run); + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FluxFrameTest.java b/src/test/java/uk/ac/starlink/ast/FluxFrameTest.java new file mode 100644 index 0000000..f9f747d --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FluxFrameTest.java @@ -0,0 +1,1003 @@ +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.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 FluxFrame tests of Rust {@code tests/test_fluxframe.rs}, of Rust {@code + * tests/test_flux.rs} (ported from C's {@code ast_tester/testflux.c}), of the unit tests of Rust + * {@code frames/fluxframe.rs}, and of {@code test_class_attrs.rs::flux_frame_domain_is_cleaned} + * and {@code test_frame_api.rs::density_follows_the_c_library}, with further tests of the + * attributes, the System a Unit implies, conversions and dumps. + * + *

    Rust makes a FluxFrame with a System argument, leaving FLXDN unset; here a FluxFrame is made + * with {@code astFluxFrame}'s arguments, a default SpecVal and a SpecFrame, and the System and + * other attributes set as C's options string sets them. The expected values are C's, from a probe + * built against the pinned C library that makes the same FluxFrames with {@code astFluxFrame( specval, + * specfrm, options )} and prints {@code astGetC}, {@code astFormat}, {@code astUnformat}, the + * values {@code astConvert} gives with the class of the simplified Mapping, and {@code astShow}. + * Rust tests that call {@code make_flux_mapping} call the package-private {@link + * FluxFrame#makeFluxMapping}; the SpecFrame that Rust's {@code set_spec_frame} attaches is given to + * the constructor. + * + *

    {@code test_fluxframe_equal_same}, {@code test_fluxframe_equal_different_system} and {@code + * test_fluxframe_equal_different_specval_is_equal} test {@code astEqual}, which this library does + * not have, and are listed in {@code deferred/rust-tests.txt}. The SpecFluxFrame tests of {@code + * test_fluxframe.rs} are in {@link SpecFluxFrameTest}, and {@code + * system_from_unit_matches_the_c_library} is in {@link FluxUnitSystemOracleTest}. + */ +class FluxFrameTest { + + /** A FluxFrame with default SpecVal {@code dsv}, no SpecFrame and the settings applied. */ + private static FluxFrame flux(double dsv, String settings) { + return flux(dsv, null, settings); + } + + /** + * A FluxFrame with default SpecVal {@code dsv}, a SpecFrame made from {@code sfSettings} (none + * if null) and the settings applied, as the probe's {@code astFluxFrame} calls make them. + */ + private static FluxFrame flux(double dsv, String sfSettings, String settings) { + SpecFrame sf = null; + if (sfSettings != null) { + sf = new SpecFrame(); + sf.set(sfSettings); + } + FluxFrame f = new FluxFrame(dsv, sf); + if (!settings.isEmpty()) { + f.set(settings); + } + return f; + } + + /** The Mapping {@code astConvert} gives from {@code from} to {@code to}, simplified, or null. */ + private static Mapping conversion(Frame from, Frame to) { + FrameSet fs = from.convert(to, ""); + return fs == null + ? null + : fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT).simplify(); + } + + private static double tran(Mapping map, double x) { + return map.tran1(1, new double[] {x}, true)[0]; + } + + private static double zoom(Mapping map) { + return assertInstanceOf(ZoomMap.class, map).getZoom(); + } + + // ------------------------------------------------------------------ + // Construction and Systems (test_fluxframe.rs) + // ------------------------------------------------------------------ + + @Test + void newFluxden() { + FluxFrame ff = new FluxFrame(); + assertEquals(1, ff.getNaxes()); + assertEquals("FLXDN", ff.getSystem()); + assertFalse(ff.testSystem()); + } + + @Test + void newFluxdenw() { + FluxFrame ff = flux(AstObject.AST__BAD, "System=FLXDNW"); + assertEquals(1, ff.getNaxes()); + assertEquals("FLXDNW", ff.getSystem()); + assertTrue(ff.testSystem()); + } + + @Test + void newSbright() { + FluxFrame ff = flux(AstObject.AST__BAD, "System=SFCBR"); + assertEquals(1, ff.getNaxes()); + assertEquals("SFCBR", ff.getSystem()); + } + + @Test + void newSbrightw() { + FluxFrame ff = flux(AstObject.AST__BAD, "System=SFCBRW"); + assertEquals(1, ff.getNaxes()); + assertEquals("SFCBRW", ff.getSystem()); + } + + /** Rust's {@code test_flux_system_parse}, as System settings. */ + @Test + void systemNames() { + assertEquals("FLXDN", flux(AstObject.AST__BAD, "System=FLXDN").getSystem()); + assertEquals("FLXDN", flux(AstObject.AST__BAD, "System=flxdn").getSystem()); + assertEquals("FLXDNW", flux(AstObject.AST__BAD, "System=FLXDNW").getSystem()); + assertEquals("SFCBR", flux(AstObject.AST__BAD, "System=SFCBR").getSystem()); + assertEquals("SFCBRW", flux(AstObject.AST__BAD, "System=SFCBRW").getSystem()); + assertEquals("SFCBRW", flux(AstObject.AST__BAD, "System=SRCBR").getSystem()); + AstException e = assertThrows(AstException.class, () -> flux(AstObject.AST__BAD, "System=NONSENSE")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + } + + /** + * Rust's {@code flux_system_parse_matches_c_names_only}: C's {@code SystemCode} matches with + * {@code astChrMatch}, which ignores case and trailing white space but not leading white + * space, and knows no long names. A setting skips the leading white space before the name. + */ + @Test + void systemNamesMatchTheCNamesOnly() { + FluxFrame ff = new FluxFrame(); + assertEquals("SFCBR", flux(AstObject.AST__BAD, "System=sfcbr ").getSystem()); + assertEquals(Frame.AST__BADSYSTEM, ff.systemCode(" SFCBR")); + for (String name : new String[] {"FLUXDEN", "FLUXDENW", "SBRIGHT", "SBRIGHTW", "Cartesian"}) { + AstException e = assertThrows(AstException.class, () -> ff.setSystem(name)); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertEquals("astSetAttrib(FluxFrame): Invalid System description \"" + name + "\".", e.getMsgText()); + } + assertFalse(ff.testSystem()); + } + + /** Rust's {@code test_flux_system_properties}: each System's density system and default units. */ + @Test + void systemProperties() { + String[][] want = { + {"FLXDN", "W/m^2/Hz", "Hz"}, + {"FLXDNW", "W/m^2/Angstrom", "Angstrom"}, + {"SFCBR", "W/m^2/Hz/arcmin**2", "Hz"}, + {"SFCBRW", "W/m^2/Angstrom/arcmin**2", "Angstrom"}, + }; + for (String[] w : want) { + FluxFrame ff = flux(AstObject.AST__BAD, "System=" + w[0]); + assertEquals(w[1], ff.getUnit(1), w[0]); + assertFalse(ff.testUnit(1), w[0]); + assertEquals(w[2], ff.getDensityUnit(), w[0]); + assertEquals("Hz".equals(w[2]) ? SpecFrame.AST__FREQ : SpecFrame.AST__WAVELEN, ff.getDensitySystem(), w[0]); + } + } + + /** The defaults of each System: Label, Symbol and Title. */ + @Test + void systemDefaults() { + FluxFrame ff = new FluxFrame(); + assertEquals("Flux density", ff.getLabel(1)); + assertEquals("Flux density", ff.getC("Label")); + assertEquals("S_nu", ff.getSymbol(1)); + assertEquals("Flux density", ff.getTitle()); + assertEquals("FLUX", ff.getDomain()); + assertEquals("FLXDN", ff.getAlignSystem()); + assertTrue(ff.getActiveUnit()); + assertFalse(ff.testActiveUnit()); + FluxFrame w = flux(AstObject.AST__BAD, "System=FLXDNW"); + assertEquals("Flux wavelength density", w.getLabel(1)); + assertEquals("S_lambda", w.getSymbol(1)); + assertEquals("Flux wavelength density", w.getTitle()); + FluxFrame sb = flux(AstObject.AST__BAD, "System=SFCBR"); + assertEquals("Surface brightness", sb.getLabel(1)); + assertEquals("mu_nu", sb.getSymbol(1)); + FluxFrame sbw = flux(AstObject.AST__BAD, "System=SFCBRW"); + assertEquals("Surface brightness (per wavelength)", sbw.getLabel(1)); + assertEquals("mu_lambda", sbw.getSymbol(1)); + FluxFrame al = flux(AstObject.AST__BAD, "AlignSystem=SFCBR"); + assertEquals("SFCBR", al.getAlignSystem()); + assertTrue(al.testAttrib("alignsystem")); + } + + // ------------------------------------------------------------------ + // SpecVal + // ------------------------------------------------------------------ + + /** Rust's {@code test_fluxframe_spec_val}. */ + @Test + void specVal() { + FluxFrame ff = new FluxFrame(); + assertEquals("", ff.getC("SpecVal")); + AstException e = assertThrows(AstException.class, ff::getSpecVal); + assertEquals(AstException.AST__ATGER, e.getStatus()); + ff.setSpecVal(1.4e9); + assertEquals(1.4e9, ff.getSpecVal()); + assertEquals("1400000000", ff.getC("SpecVal")); + assertTrue(ff.test("SpecVal")); + ff.clear("SpecVal"); + assertEquals("", ff.getC("SpecVal")); + assertFalse(ff.test("SpecVal")); + } + + /** A SpecVal that is not a number is not a SpecVal setting. */ + @Test + void specValSettingMustBeANumber() { + FluxFrame ff = new FluxFrame(); + AstException e = assertThrows(AstException.class, () -> ff.set("SpecVal=fred")); + assertEquals(AstException.AST__BADAT, e.getStatus()); + assertEquals("astSet: The attribute setting \"specval=fred\" is invalid for a FluxFrame.", e.getMsgText()); + } + + /** The Title gives the SpecVal in the units of its SpecFrame. */ + @Test + void titleGivesTheSpecVal() { + assertEquals( + "Flux density at = 1.4E+09 Hz", + flux(AstObject.AST__BAD, "SpecVal=1.4e9").getTitle()); + assertEquals( + "Flux density at = 123 GHz", + flux(123.0, "System=FREQ,Unit=GHz", "").getTitle()); + assertEquals( + "Flux wavelength density at = 5000 Angstrom", + flux(5000.0, "System=FLXDNW").getTitle()); + assertEquals("1400000000", flux(1.4e9, "").getC("SpecVal")); + } + + /** Rust's {@code test_flux.rs::spec_val_defaults_to_the_constructor_value} (testflux.c Errors 1 to 6, CheckDump 1). */ + @Test + void specValDefaultsToTheConstructorValue() { + FluxFrame ff = flux(123.0, "System=freq,Unit=GHz", ""); + assertEquals(123.0, ff.getSpecVal(), "Error 1"); + assertFalse(ff.test("SpecVal"), "Error 2"); + ff.setSpecVal(333.3); + assertEquals(333.3, ff.getSpecVal(), "Error 3"); + assertTrue(ff.test("SpecVal"), "Error 4"); + ff.clear("SpecVal"); + assertEquals(123.0, ff.getSpecVal(), "Error 5"); + assertFalse(ff.test("SpecVal"), "Error 6"); + FluxFrame read = assertInstanceOf(FluxFrame.class, ChannelText.read(ChannelText.dump(ff))); + assertEquals(ff.getSpecVal(), read.getSpecVal(), "CheckDump 1"); + } + + // ------------------------------------------------------------------ + // Format, Unformat and Distance + // ------------------------------------------------------------------ + + /** Rust's {@code test_fluxframe_format}: the Frame's {@code %1.7G}, with no units. */ + @Test + void format() { + FluxFrame ff = new FluxFrame(); + assertEquals("1.5", ff.format(1, 1.5)); + assertEquals("0.00123", ff.format(1, 1.23e-3)); + assertEquals("1E-26", ff.format(1, 1.0e-26)); + assertEquals("1.4E+09", ff.format(1, 1.4e9)); + assertEquals("", ff.format(1, AstObject.AST__BAD)); + } + + /** Rust's {@code test_fluxframe_unformat}. */ + @Test + void unformat() { + double[] v = new double[1]; + assertEquals(7, new FluxFrame().unformat(1, "1.5e-3 Jy", v)); + assertEquals(0.0015, v[0]); + } + + /** Rust's {@code test_fluxframe_unformat_base_contract}. */ + @Test + void unformatBaseContract() { + FluxFrame ff = new FluxFrame(); + Object[][] cases = { + {"12.5", 12.5, 4}, + {" 12.5 ", 12.5, 8}, + {"12.5xyz", 12.5, 4}, + {"", AstObject.AST__BAD, 5}, + {" < b a d > ", AstObject.AST__BAD, 11}, + {"xyz", null, 0}, + {"", null, 0}, + }; + for (Object[] c : cases) { + double[] v = {0.0}; + assertEquals((int) c[2], ff.unformat(1, (String) c[0], v), (String) c[0]); + if (c[1] != null) { + assertEquals((double) c[1], v[0], (String) c[0]); + } + } + } + + /** Rust's {@code test_fluxframe_distance}. */ + @Test + void distance() { + assertEquals(2.0, new FluxFrame().distance(new double[] {1.0}, new double[] {3.0})); + } + + // ------------------------------------------------------------------ + // Units and the System they imply + // ------------------------------------------------------------------ + + /** Rust's {@code test_fluxframe_unit_accessors}. */ + @Test + void unitAccessors() { + FluxFrame ff = new FluxFrame(); + assertFalse(ff.testUnit(1)); + assertEquals("W/m^2/Hz", ff.getUnit(1)); + ff.setUnit(1, "Jy"); + assertTrue(ff.testUnit(1)); + assertEquals("Jy", ff.getUnit(1)); + ff.clearUnit(1); + assertFalse(ff.testUnit(1)); + assertEquals("W/m^2/Hz", ff.getUnit(1)); + } + + /** Rust's {@code test_fluxframe_system_derived_from_unit}. */ + @Test + void systemDerivedFromUnit() { + FluxFrame ff = new FluxFrame(); + ff.setUnit(1, "Jy"); + assertEquals("FLXDN", ff.getSystem()); + assertFalse(ff.testSystem()); + FluxFrame w = new FluxFrame(); + w.setUnit(1, "W/m^2/Angstrom"); + assertEquals("FLXDNW", w.getSystem()); + assertFalse(w.testSystem()); + } + + /** A Unit that is a function of the default units rewrites the default Label and Symbol. */ + @Test + void logarithmicUnit() { + FluxFrame ff = flux(AstObject.AST__BAD, "Unit=log(Jy)"); + assertEquals("FLXDN", ff.getSystem()); + assertEquals("log( Flux density )", ff.getLabel(1)); + assertEquals("log( S_nu )", ff.getSymbol(1)); + } + + /** The Unit used with each System comes back with the System; a change of System clears the Label and Title. */ + @Test + void unitsFollowTheSystem() { + assertEquals( + "W/m^2/Angstrom", + flux(AstObject.AST__BAD, "Unit=Jy,System=FLXDNW").getUnit(1)); + FluxFrame ff = flux(AstObject.AST__BAD, "Unit=Jy,System=FLXDNW,Unit=W/m^2/nm,System=FLXDN"); + assertEquals("Jy", ff.getUnit(1)); + assertTrue(ff.testUnit(1)); + ff.setSystem("FLXDNW"); + assertEquals("W/m^2/nm", ff.getUnit(1)); + assertEquals("Mine", flux(AstObject.AST__BAD, "Label(1)=Mine,Unit=Jy").getLabel(1)); + assertEquals( + "Surface brightness", + flux(AstObject.AST__BAD, "Label(1)=Mine,System=SFCBR").getLabel(1)); + assertEquals( + "Surface brightness", + flux(AstObject.AST__BAD, "Title=Mine,System=SFCBR").getTitle()); + assertEquals("Jy", flux(AstObject.AST__BAD, "Unit=Jy ").getUnit(1)); + } + + /** A Unit that does not suit a set System clears the System, which then follows from the Unit. */ + @Test + void unitClearsASystemItDoesNotSuit() { + FluxFrame sb = flux(AstObject.AST__BAD, "System=SFCBR,Unit=Jy/arcsec**2"); + assertEquals("Jy/arcsec**2", sb.getUnit(1)); + assertTrue(sb.testSystem()); + FluxFrame ff = flux(AstObject.AST__BAD, "System=FLXDNW,Unit=Jy"); + assertEquals("FLXDN", ff.getSystem()); + assertFalse(ff.testSystem()); + assertEquals("Jy", ff.getUnit(1)); + } + + /** Clearing the System, and clearing the Unit, which forgets the Unit used with the System. */ + @Test + void clearSystemAndUnit() { + FluxFrame sb = flux(AstObject.AST__BAD, "System=SFCBR,Unit=Jy/arcsec**2,Label(1)=L"); + sb.clear("System"); + assertEquals("SFCBR", sb.getSystem()); + assertEquals("Jy/arcsec**2", sb.getUnit(1)); + assertEquals("L", sb.getLabel(1)); + assertTrue(sb.testUnit(1)); + FluxFrame ff = flux(AstObject.AST__BAD, "Unit=Jy,System=FLXDNW,System=FLXDN"); + ff.clear("Unit(1)"); + assertEquals("W/m^2/Hz", ff.getUnit(1)); + assertEquals("FLXDN", ff.getSystem()); + ff.setSystem("FLXDNW"); + ff.setSystem("FLXDN"); + assertEquals("W/m^2/Hz", ff.getUnit(1)); + FluxFrame sv = flux(123.0, "SpecVal=5"); + sv.clear("SpecVal"); + assertEquals("123", sv.getC("SpecVal")); + } + + /** A Unit that suits no flux System is set, and then the System cannot be found. */ + @Test + void unitThatSuitsNoSystem() { + FluxFrame ff = new FluxFrame(); + AstException e = assertThrows(AstException.class, () -> ff.setUnit(1, "m")); + assertEquals(AstException.AST__BADUN, e.getStatus()); + assertEquals( + "astGetSystem(FluxFrame): The current units (m) cannot be used with any of the supported flux" + + " systems.", + e.getMsgText()); + assertEquals("m", ff.getUnit(1)); + } + + /** Rust's {@code test_class_attrs.rs::flux_frame_domain_is_cleaned}. */ + @Test + void domainIsCleaned() { + FluxFrame ff = new FluxFrame(); + ff.setC("Domain", "my flux"); + assertEquals("MYFLUX", ff.getDomain()); + } + + /** + * Rust's {@code test_frame_api.rs::density_follows_the_c_library} ({@code + * oracle/frame_api.json}, the {@code DENSITY} cases of {@code frame_api_probe.c}): C's {@code + * astGetDensitySystem} and {@code astGetDensityUnit}. + */ + @Test + void densityFollowsTheCLibrary() { + com.fasterxml.jackson.databind.JsonNode cases = + uk.ac.starlink.ast.testsupport.ProbeData.load("frame_api").get("DENSITY"); + assertEquals(3, cases.size()); + for (com.fasterxml.jackson.databind.JsonNode c : cases) { + String setting = c.get(0).asText(); + FluxFrame ff = flux(AstObject.AST__BAD, setting); + String sys = new SpecFrame().systemString(ff.getDensitySystem()); + assertEquals(c.get(1).asText(), sys, setting); + assertEquals(c.get(2).asText(), ff.getDensityUnit(), setting); + } + } + + // ------------------------------------------------------------------ + // Conversions (test_fluxframe.rs) + // ------------------------------------------------------------------ + + /** Rust's {@code test_fluxframe_convert_same_system}. */ + @Test + void convertSameSystem() { + Mapping map = conversion(new FluxFrame(), new FluxFrame()); + assertInstanceOf(UnitMap.class, map); + assertEquals(3.0, tran(map, 3.0)); + } + + /** Rust's {@code test_fluxframe_make_flux_mapping_same_system_is_unit}. */ + @Test + void makeFluxMappingSameSystemIsUnit() { + Mapping map = new FluxFrame().makeFluxMapping(new FluxFrame()); + assertEquals(3.0, tran(map, 3.0)); + } + + /** Rust's {@code test_fluxframe_make_flux_mapping_without_specframe_returns_none}. */ + @Test + void makeFluxMappingWithoutSpecFrameReturnsNone() { + FluxFrame ff1 = flux(AstObject.AST__BAD, "SpecVal=1.4e9"); + FluxFrame ff2 = flux(AstObject.AST__BAD, "System=FLXDNW,SpecVal=1.4e9"); + assertNull(ff1.makeFluxMapping(ff2)); + assertNull(conversion(ff1, ff2)); + } + + /** Rust's {@code test_fluxframe_make_flux_mapping_cross_system_with_specframe}. */ + @Test + void makeFluxMappingCrossSystemWithSpecFrame() { + FluxFrame ff1 = flux(AstObject.AST__BAD, "System=FREQ,Unit=Hz", "SpecVal=1.4e9"); + FluxFrame ff2 = flux(AstObject.AST__BAD, "System=FREQ,Unit=Hz", "System=FLXDNW,SpecVal=1.4e9"); + assertEquals(0.6537856304137525, tran(ff1.makeFluxMapping(ff2), 1.0)); + Mapping map = conversion(ff1, ff2); + assertEquals(0.6537856304137525, zoom(map)); + assertEquals(0.9999999999999999, map.tran1(1, new double[] {0.6537856304137525}, false)[0]); + } + + /** Rust's {@code test_fluxframe_make_flux_mapping_surface_brightness_mismatch_none}. */ + @Test + void makeFluxMappingSurfaceBrightnessMismatchNone() { + FluxFrame ff1 = flux(AstObject.AST__BAD, "SpecVal=1.4e9"); + FluxFrame ff2 = flux(AstObject.AST__BAD, "System=SFCBR,SpecVal=1.4e9"); + assertNull(ff1.makeFluxMapping(ff2)); + assertNull(conversion(ff1, ff2)); + } + + /** Rust's {@code test_fluxframe_jy_to_default_units}. */ + @Test + void jyToDefaultUnits() { + FluxFrame jy = flux(AstObject.AST__BAD, "Unit=Jy"); + FluxFrame def = new FluxFrame(); + assertEquals(1.0000000000000002e-26, tran(jy.makeFluxMapping(def), 1.0)); + assertEquals(1.0000000000000002e-26, zoom(conversion(jy, def))); + assertEquals(0.9999999999999999, tran(def.makeFluxMapping(jy), 1.0e-26)); + assertEquals(9.999999999999999e25, zoom(conversion(def, jy))); + } + + /** Rust's {@code test_fluxframe_cross_system_with_units}. */ + @Test + void crossSystemWithUnits() { + FluxFrame jy = flux(AstObject.AST__BAD, "System=FREQ,Unit=Hz", "Unit=Jy,SpecVal=1.4e9"); + FluxFrame w = flux(AstObject.AST__BAD, "System=FREQ,Unit=Hz", "System=FLXDNW,SpecVal=1.4e9"); + assertEquals(6.537856304137527e-27, tran(jy.makeFluxMapping(w), 1.0)); + assertEquals(6.537856304137527e-27, zoom(conversion(jy, w))); + } + + /** Rust's {@code test_fluxframe_incompatible_unit_is_badun}. */ + @Test + void incompatibleUnitIsBadun() { + FluxFrame bad = flux(AstObject.AST__BAD, "System=FLXDN"); + bad.setUnit(1, "m"); + FluxFrame def = flux(AstObject.AST__BAD, "System=FLXDN"); + AstException e = assertThrows(AstException.class, () -> bad.makeFluxMapping(def)); + assertEquals(AstException.AST__BADUN, e.getStatus()); + e = assertThrows(AstException.class, () -> bad.convert(def, "")); + assertEquals(AstException.AST__BADUN, e.getStatus()); + assertEquals( + "astGetSystem(FluxFrame): The current units (m) cannot be used with any of the supported flux" + + " systems.", + e.getMsgText()); + } + + /** The SpecVal of a per-wavelength FluxFrame with no SpecFrame is a wavelength in Angstrom. */ + @Test + void specValInTheDensitySystem() { + Mapping map = conversion(flux(5000.0, "System=FLXDNW"), flux(5.99584916e14, "System=FLXDN")); + assertEquals(8.339102404752465e-12, zoom(map)); + } + + /** No conversion between densities when the SpecVal is not known. */ + @Test + void noConversionWithoutASpecVal() { + assertNull(conversion( + flux(AstObject.AST__BAD, "System=FREQ,Unit=Hz", ""), + flux(AstObject.AST__BAD, "System=FREQ,Unit=Hz", "System=FLXDNW"))); + } + + /** A SpecVal given as a radio velocity is converted to the density systems through the SpecFrames. */ + @Test + void specValInAVelocity() { + Mapping map = conversion( + flux(10.0, "System=VRAD,RestFreq=100", ""), + flux(99.99666435e9, "System=FREQ,Unit=Hz", "System=FLXDNW")); + assertEquals(3335.4184464280897, zoom(map)); + } + + /** AlignSystem does not change a conversion. */ + @Test + void alignSystemIsNotUsed() { + Mapping map = conversion(new FluxFrame(), flux(AstObject.AST__BAD, "AlignSystem=FLXDNW")); + assertInstanceOf(UnitMap.class, map); + } + + /** A logarithmic Unit is converted by a MathMap, which this library does not have. */ + @Test + void logarithmicConversionNeedsMathMap() { + FluxFrame jy = flux(AstObject.AST__BAD, "Unit=Jy"); + FluxFrame log = flux(AstObject.AST__BAD, "Unit=log(W/m^2/Hz)"); + UnsupportedOperationException e = assertThrows(UnsupportedOperationException.class, () -> jy.convert(log, "")); + assertTrue(e.getMessage().endsWith("needs MathMap"), e.getMessage()); + } + + // ------------------------------------------------------------------ + // testflux.c (test_flux.rs) + // ------------------------------------------------------------------ + + /** Rust's {@code similar_spec_vals_convert_with_a_unit_map} (Errors 8, 9). */ + @Test + void similarSpecValsConvertWithAUnitMap() { + Mapping map = conversion(flux(123.0, "System=freq,Unit=GHz", ""), flux(123.1, "System=freq,Unit=GHz", "")); + assertNotNull(map, "Error 8"); + assertInstanceOf(UnitMap.class, map, "Error 9"); + } + + /** Rust's {@code per_frequency_units_scale} (Errors 10 to 14). */ + @Test + void perFrequencyUnitsScale() { + FluxFrame ff = flux(123.0, "System=freq,Unit=GHz", "Unit=W/m^2/Hz"); + assertEquals("FLXDN", ff.getSystem(), "Error 10"); + FluxFrame ff2 = flux(123.0, "System=freq,Unit=GHz", "Unit=W/m^2/GHz"); + assertEquals("FLXDN", ff2.getSystem(), "Error 11"); + Mapping map = conversion(ff2, ff); + assertNotNull(map, "Error 12"); + assertEquals(1.0000000000000003e-9, zoom(map), "Error 14"); + } + + /** Rust's {@code per_wavelength_units_scale} (Errors 15 to 19). */ + @Test + void perWavelengthUnitsScale() { + FluxFrame ff = flux(123.0, "System=freq,Unit=GHz", "Unit=W/m^2/m"); + assertEquals("FLXDNW", ff.getSystem(), "Error 15"); + FluxFrame ff2 = flux(123.0e9, "System=freq,Unit=Hz", "Unit=W/m^2/Angstrom"); + assertEquals("FLXDNW", ff2.getSystem(), "Error 16"); + Mapping map = conversion(ff2, ff); + assertNotNull(map, "Error 17"); + assertEquals(1.0e10, zoom(map), "Error 19"); + } + + /** Rust's {@code per_wavelength_units_scale_across_spectral_systems} (Errors 20 to 24). */ + @Test + void perWavelengthUnitsScaleAcrossSpectralSystems() { + FluxFrame ff = flux(123.0, "System=freq,Unit=GHz", "Unit=W/m^2/m"); + assertEquals("FLXDNW", ff.getSystem(), "Error 20"); + FluxFrame ff2 = flux(2437337.06, "System=wave,Unit=nm", "Unit=W/m^2/Angstrom"); + assertEquals("FLXDNW", ff2.getSystem(), "Error 21"); + Mapping map = conversion(ff, ff2); + assertNotNull(map, "Error 22"); + assertEquals(1.0e-10, zoom(map), "Error 24"); + } + + /** Rust's {@code frequency_density_converts_to_wavelength_density} (Errors 25, 26). */ + @Test + void frequencyDensityConvertsToWavelengthDensity() { + FluxFrame ff = flux(123.0, "System=freq,Unit=GHz", "Unit=W/m^2/Hz"); + FluxFrame ff2 = flux(2437337.06, "System=wave,Unit=nm", "Unit=W/m^2/m"); + FrameSet fs = ff.convert(ff2, " "); + assertNotNull(fs, "Error 25"); + assertEquals(5.046491188679814, tran(fs, 1.0e-13), "Error 26"); + assertEquals(50464911886798.13, zoom(conversion(ff, ff2))); + } + + /** Rust's {@code surface_brightness_converts} (Errors 27a, 27b, 27, 28). */ + @Test + void surfaceBrightnessConverts() { + FluxFrame ff = flux(123.0, "System=freq,Unit=GHz", "Unit=W/m^2/Hz/arcsec**2"); + assertEquals("SFCBR", ff.getSystem(), "Error 27a"); + FluxFrame ff2 = flux(2437337.06, "System=wave,Unit=nm", "Unit=W/m^2/m/deg**2"); + assertEquals("SFCBRW", ff2.getSystem(), "Error 27b"); + FrameSet fs = ff.convert(ff2, " "); + assertNotNull(fs, "Error 27"); + assertEquals(65402525.8052904, tran(fs, 1.0e-13), "Error 28"); + } + + /** Rust's {@code surface_brightness_does_not_convert_to_flux_density} (Error 29). */ + @Test + void surfaceBrightnessDoesNotConvertToFluxDensity() { + FluxFrame ff = flux(123.0, "System=freq,Unit=GHz", "Unit=W/m^2/Hz/arcsec**2"); + FluxFrame ff2 = flux(2437337.06, "System=wave,Unit=nm", "Unit=W/m^2/m"); + assertNull(ff.convert(ff2, " "), "Error 29"); + } + + /** Rust's {@code per_wavelength_surface_brightness_reads_back} (Errors 30 to 32). */ + @Test + void perWavelengthSurfaceBrightnessReadsBack() { + FluxFrame ff = flux(AstObject.AST__BAD, "System=SFCBRW"); + assertEquals("SFCBRW", ff.getC("System"), "Error 31"); + FluxFrame copy = assertInstanceOf(FluxFrame.class, ChannelText.read(ChannelText.dump(ff)), "Error 32"); + assertEquals("SFCBRW", copy.getC("System"), "Error 32"); + } + + // ------------------------------------------------------------------ + // Match, SubFrame, Overlay and PickAxes (frames/fluxframe.rs) + // ------------------------------------------------------------------ + + /** Rust's {@code test_system_default_is_fluxden_unset}. */ + @Test + void systemDefaultIsFluxdenUnset() { + FluxFrame f = new FluxFrame(); + assertFalse(f.testSystem()); + f.setSystem("SFCBR"); + assertTrue(f.testSystem()); + } + + /** Rust's {@code match_template_fluxframe_self}. */ + @Test + void matchTemplateSelf() { + FluxFrame template = flux(AstObject.AST__BAD, "System=SFCBR"); + FluxFrame target = flux(AstObject.AST__BAD, "System=SFCBR"); + FrameFinder.MatchResult m = template.match(target, false); + assertNotNull(m); + assertEquals(0, m.templateAxes[0]); + assertEquals(0, m.targetAxes[0]); + assertEquals("SFCBR", assertInstanceOf(FluxFrame.class, m.result).getSystem()); + } + + /** Rust's {@code match_template_fluxframe_against_basicframe_fails}. */ + @Test + void matchTemplateAgainstPlainFrameFails() { + assertNull(flux(AstObject.AST__BAD, "System=SFCBR").match(new Frame(1), false)); + } + + /** Rust's {@code match_template_fluxframe_different_system_returns_none}. */ + @Test + void matchTemplateDifferentSystemReturnsNone() { + assertNull(flux(AstObject.AST__BAD, "System=SFCBR").match(flux(AstObject.AST__BAD, "System=FLXDNW"), false)); + } + + /** Rust's {@code sub_frame_fluxframe_to_fluxframe_identity}. */ + @Test + void subFrameIdentity() { + FluxFrame target = flux(AstObject.AST__BAD, "System=SFCBR"); + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + assertTrue(target.subFrame( + flux(AstObject.AST__BAD, "System=SFCBR"), 1, new int[] {0}, new int[] {0}, map, result)); + assertEquals(1, map[0].getNin()); + assertEquals(1, map[0].getNout()); + assertEquals("SFCBR", assertInstanceOf(FluxFrame.class, result[0]).getSystem()); + } + + /** Rust's {@code overlay_template_copies_set_system}. */ + @Test + void overlayTemplateCopiesSetSystem() { + FluxFrame result = new FluxFrame(); + flux(AstObject.AST__BAD, "System=SFCBR").overlay(new int[] {0}, result); + assertEquals("SFCBR", result.getSystem()); + } + + /** Rust's {@code overlay_template_skips_unset_system}. */ + @Test + void overlayTemplateSkipsUnsetSystem() { + FluxFrame result = flux(AstObject.AST__BAD, "System=SFCBR"); + new FluxFrame().overlay(new int[] {0}, result); + assertEquals("SFCBR", result.getSystem()); + } + + /** + * Overlaid onto a plain Frame, a template with its System set has its System and AlignSystem + * cleared and set again (a C quirk, followed here): its AlignSystem is left set, and when + * clearing the System changes it, its Label and Title are cleared before they are overlaid. + * Values from C's {@code astOverlay}. + */ + @Test + void overlayOntoAPlainFrameChangesTheTemplate() { + FluxFrame t = flux(AstObject.AST__BAD, "System=SFCBR,Unit=Jy/arcsec**2,Label(1)=Mine,Title=TT"); + Frame r = new Frame(1); + t.overlay(new int[] {0}, r); + assertEquals("SFCBR", t.getSystem()); + assertEquals("FLXDN", t.getAlignSystem()); + assertTrue(t.testAttrib("alignsystem")); + assertEquals("Mine", t.getLabel(1)); + assertEquals("Jy/arcsec**2", t.getUnit(1)); + assertEquals("TT", t.getTitle()); + assertEquals("Cartesian", r.getSystem()); + assertFalse(r.testSystem()); + assertEquals("Mine", r.getLabel(1)); + assertEquals("Jy/arcsec**2", r.getUnit(1)); + assertEquals("TT", r.getTitle()); + + FluxFrame t2 = flux(AstObject.AST__BAD, "System=SFCBR,Label(1)=Mine,Title=TT"); + Frame r2 = new Frame(1); + t2.overlay(new int[] {0}, r2); + assertEquals("SFCBR", t2.getSystem()); + assertTrue(t2.testAttrib("alignsystem")); + assertEquals("Surface brightness", t2.getLabel(1)); + assertFalse(t2.testLabel(1)); + assertEquals("W/m^2/Hz/arcmin**2", t2.getUnit(1)); + assertFalse(t2.testTitle()); + assertEquals("Axis 1", r2.getLabel(1)); + assertEquals("", r2.getUnit(1)); + assertFalse(r2.testTitle()); + } + + /** Rust's {@code pick_axes_snapshot_full_returns_fluxframe}. */ + @Test + void pickAxesFullReturnsFluxFrame() { + Mapping[] map = new Mapping[1]; + Frame f = flux(1.4e9, "System=SFCBR").pickAxes(1, new int[] {1}, map); + assertEquals("SFCBR", assertInstanceOf(FluxFrame.class, f).getSystem()); + assertInstanceOf(UnitMap.class, map[0]); + } + + /** A FluxFrame template does not find the FluxFrame of a CmpFrame, which has two axes. */ + @Test + void templateDoesNotFindTheFluxFrameOfACmpFrame() { + SpecFrame sf = new SpecFrame(); + sf.setSystem("FREQ"); + CmpFrame cf = new CmpFrame(sf, flux(AstObject.AST__BAD, "Unit=Jy")); + assertNull(cf.findFrame(new FluxFrame(), "")); + } + + // ------------------------------------------------------------------ + // Dumps + // ------------------------------------------------------------------ + + private static final String DUMP_DEFAULT = String.join( + "\n", + " Begin FluxFrame \t# Description of flux values", + "# Title = \"Flux density\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"FLUX\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Flux density\" \t# Label for axis 1", + "# System = \"FLXDN\" \t# Coordinate system type", + "# Uni1 = \"W/m^2/Hz\" \t# Units for axis 1", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + " End FluxFrame", + ""); + + private static final String DUMP_JY = String.join( + "\n", + " Begin FluxFrame \t# Description of flux values", + "# Title = \"Flux density\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"FLUX\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Flux density\" \t# Label for axis 1", + "# System = \"FLXDN\" \t# Coordinate system type", + "# Uni1 = \"Jy\" \t# Units for axis 1 (Jansky)", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " Unit = \"Jy\" \t# Axis units (Jansky)", + " End Axis", + " IsA Frame \t# Coordinate system description", + " UFlxdn = \"Jy\" \t# Preferred units for flux density", + " End FluxFrame", + ""); + + private static final String DUMP_SFCBRW = String.join( + "\n", + " Begin FluxFrame \t# Description of flux values", + "# Title = \"Surface brightness (per wavelength) at = 5E+14 Angstrom\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"FLUX\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Surface brightness (per wavelength)\" \t# Label for axis 1", + " System = \"SFCBRW\" \t# Coordinate system type", + "# Uni1 = \"W/m^2/Angstrom/arcmin**2\" \t# Units for axis 1", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + " SpcVl = 500000000000000 \t# Spectral position", + " End FluxFrame", + ""); + + private static final String DUMP_TITLE = String.join( + "\n", + " Begin FluxFrame \t# Description of flux values", + " Title = \"Test Title\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"FLUX\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Flux density\" \t# Label for axis 1", + "# System = \"FLXDN\" \t# Coordinate system type", + "# Uni1 = \"W/m^2/Hz\" \t# Units for axis 1", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + " End FluxFrame", + ""); + + private static final String DUMP_SF = String.join( + "\n", + " Begin FluxFrame \t# Description of flux values", + "# Title = \"Flux density at = 123 GHz\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"FLUX\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Flux density\" \t# Label for axis 1", + "# System = \"FLXDN\" \t# Coordinate system type", + "# Uni1 = \"W/m^2/Hz\" \t# Units for axis 1", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + " SpcFr = \t# SpcVl coord system", + " Begin SpecFrame \t# Description of spectral coordinate system", + "# Title = \"Frequency\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"SPECTRUM\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Frequency\" \t# Label for axis 1", + " System = \"FREQ\" \t# Coordinate system type", + "# Uni1 = \"GHz\" \t# Units for axis 1", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " Unit = \"GHz\" \t# Axis units", + " End Axis", + " IsA Frame \t# Coordinate system description", + "# SoR = \"Heliocentric\" \t# Standard of rest", + " UFreq = \"GHz\" \t# Preferred units for frequency", + " End SpecFrame", + " DfSpc = 123 \t# Default spectral position", + " End FluxFrame", + ""); + + private static final String DUMP_USED = String.join( + "\n", + " Begin FluxFrame \t# Description of flux values", + "# Title = \"Flux wavelength density at = 1.4E+09 Angstrom\" \t# Title of coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + "# Domain = \"FLUX\" \t# Coordinate system domain", + "# Epoch = 2000 \t# Julian epoch of observation", + "# Lbl1 = \"Flux wavelength density\" \t# Label for axis 1", + " System = \"FLXDNW\" \t# Coordinate system type", + " AlSys = \"SFCBR\" \t# Alignment coordinate system", + "# Uni1 = \"W/m^2/nm\" \t# Units for axis 1", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " Unit = \"W/m^2/nm\" \t# Axis units", + " End Axis", + " IsA Frame \t# Coordinate system description", + " DfSpc = 1400000000 \t# Default spectral position", + " UFlxdn = \"Jy\" \t# Preferred units for flux density", + " UFlxdnw = \"W/m^2/nm\" \t# Preferred units for flux wavelength density", + " End FluxFrame", + ""); + + /** C's dump of {@code frame}, which reads back to a FluxFrame with the same dump. */ + private static FluxFrame assertDumpRoundTrip(String want, FluxFrame frame) { + assertEquals(want, ChannelText.dump(frame)); + FluxFrame back = assertInstanceOf(FluxFrame.class, ChannelText.read(want)); + assertEquals(want, ChannelText.dump(back)); + assertEquals(frame, back); + return back; + } + + /** Rust's {@code test_fluxframe_serialisation_roundtrip_fluxden}. */ + @Test + void dumpDefault() { + assertDumpRoundTrip(DUMP_DEFAULT, new FluxFrame()); + } + + /** Rust's {@code test_fluxframe_unit_serialisation_round_trip}. */ + @Test + void dumpUnit() { + FluxFrame back = assertDumpRoundTrip(DUMP_JY, flux(AstObject.AST__BAD, "Unit=Jy")); + assertEquals("Jy", back.getUnit(1)); + } + + /** Rust's {@code test_fluxframe_serialisation_roundtrip_sbrightw}. */ + @Test + void dumpSbrightw() { + FluxFrame back = assertDumpRoundTrip(DUMP_SFCBRW, flux(AstObject.AST__BAD, "System=SFCBRW,SpecVal=5e14")); + assertEquals(5.0e14, back.getSpecVal()); + assertTrue(back.test("SpecVal")); + } + + /** Rust's {@code test_fluxframe_serialisation_with_title}. */ + @Test + void dumpTitle() { + assertDumpRoundTrip(DUMP_TITLE, flux(AstObject.AST__BAD, "Title=Test Title")); + } + + /** A FluxFrame holding a SpecFrame and a default SpecVal. */ + @Test + void dumpSpecFrame() { + FluxFrame back = assertDumpRoundTrip(DUMP_SF, flux(123.0, "System=FREQ,Unit=GHz", "")); + assertEquals(123.0, back.getSpecVal()); + assertFalse(back.test("SpecVal")); + assertEquals("Flux density at = 123 GHz", back.getTitle()); + } + + /** The Units used with each System are dumped and read back. */ + @Test + void dumpUsedUnits() { + FluxFrame back = + assertDumpRoundTrip(DUMP_USED, flux(1.4e9, "Unit=Jy,System=FLXDNW,Unit=W/m^2/nm,AlignSystem=SFCBR")); + back.setSystem("FLXDN"); + assertEquals("Jy", back.getUnit(1)); + } + + /** + * The Unit used with a System is recorded as given, trailing spaces and all, though the Unit + * itself is stored without them, as C's {@code SetUnit} records it. + */ + @Test + void usedUnitKeepsTrailingSpaces() { + FluxFrame ff = new FluxFrame(); + ff.setC("Unit(1)", "Jy "); + String dump = ChannelText.dump(ff); + assertTrue(dump.contains(" Unit = \"Jy\" \t# Axis units (Jansky)\n"), dump); + assertTrue(dump.contains(" UFlxdn = \"Jy \" \t# Preferred units for flux density\n"), dump); + ff.set("Unit(1)=W/m^2/Hz "); + assertTrue(ChannelText.dump(ff).contains(" UFlxdn = \"W/m^2/Hz \" \t# Preferred units for flux density\n")); + } + + /** A copy holds its own SpecFrame and record of Units. */ + @Test + void copyIsIndependent() { + FluxFrame ff = flux(123.0, "System=FREQ,Unit=GHz", "Unit=Jy"); + FluxFrame copy = (FluxFrame) ff.copy(); + copy.setSystem("FLXDNW"); + copy.setUnit(1, "W/m^2/nm"); + ff.setSystem("FLXDNW"); + assertEquals("W/m^2/Angstrom", ff.getUnit(1)); + assertEquals("W/m^2/nm", copy.getUnit(1)); + assertEquals("Flux wavelength density at = 123 GHz", copy.getTitle()); + } + + /** A dump whose SpcFr is not a SpecFrame is refused. */ + @Test + void loaderRefusesAnotherClassOfSpcFr() { + String text = DUMP_SF.replace("Begin SpecFrame", "Begin Frame") + .replace("End SpecFrame", "End Frame") + .replace("# SoR = \"Heliocentric\" \t# Standard of rest\n", "") + .replace(" UFreq = \"GHz\" \t# Preferred units for frequency\n", "") + .replace(" System = \"FREQ\" \t# Coordinate system type\n", "") + .replace(" IsA Frame \t# Coordinate system description\n", ""); + AstException e = assertThrows(AstException.class, () -> ChannelText.read(text)); + assertEquals(AstException.AST__LDERR, e.getStatus()); + } + + /** jniast's accessors. */ + @Test + void jniastAccessors() { + SpecFrame sf = new SpecFrame(); + sf.setSystem("FREQ"); + FluxFrame ff = new FluxFrame(123.0, sf); + sf.setUnit(1, "Hz"); + assertEquals("Flux density at = 123 GHz", ff.getTitle()); + assertEquals(123.0, ff.getSpecVal()); + ff.setSpecVal(5.0); + assertEquals(5.0, ff.getSpecVal()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FluxUnitSystemOracleTest.java b/src/test/java/uk/ac/starlink/ast/FluxUnitSystemOracleTest.java new file mode 100644 index 0000000..b56e79c --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/FluxUnitSystemOracleTest.java @@ -0,0 +1,35 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_fluxframe.rs::system_from_unit_matches_the_c_library}: a + * FluxFrame whose System follows from its Unit, checked against C ({@code + * oracle/flux_unit_system.json}, from {@code tools/oracle_fixtures/flux_unit_system_probe.c}). C + * reads the SpecVal in the units of the density system of the System the Unit gives (fluxframe.c + * {@code GetSpecFrame}). + */ +class FluxUnitSystemOracleTest { + + @Test + void systemFromUnitMatchesTheCLibrary() { + JsonNode data = ProbeData.load("flux_unit_system"); + // astFluxFrame( 5000.0, NULL, "Unit=W/m^2/Angstrom" ): a default SpecVal, and no System. + FluxFrame a = new FluxFrame(5000.0, null); + a.setUnit(1, "W/m^2/Angstrom"); + assertEquals(data.get("SYSTEM").asText(), a.getSystem()); + assertEquals(data.get("TITLE").asText(), a.getTitle()); + // astFluxFrame( 5.99584916e14, NULL, "System=FLXDN" ). + FluxFrame b = new FluxFrame(5.99584916e14, null); + b.setSystem("FLXDN"); + FrameSet fs = a.convert(b, ""); + double[] out = fs.tran1(2, new double[] {1.0, 3.5}, true); + JsonNode want = data.get("CONVERTED"); + assertEquals(ProbeData.toDouble(want.get(0)), out[0]); + assertEquals(ProbeData.toDouble(want.get(1)), out[1]); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/FrameAxisAttrsTest.java b/src/test/java/uk/ac/starlink/ast/FrameAxisAttrsTest.java index 1115003..a23946a 100644 --- a/src/test/java/uk/ac/starlink/ast/FrameAxisAttrsTest.java +++ b/src/test/java/uk/ac/starlink/ast/FrameAxisAttrsTest.java @@ -18,11 +18,11 @@ * one attribute on the first or last axis of an object of each class and reads every attribute of * every axis back). * - *

    The cases for a plain Frame, a SkyFrame, a TimeFrame, a FrameSet holding a SkyFrame (with - * those of its current Frame, "inner1") and PlainCmpFrame, a CmpFrame of a one-axis and a two-axis - * plain Frame (with those of its components, "inner1" and "inner2"), run here. The probe's - * CmpFrame holds a SpecFrame, and its cases, like those of SpecFrame, DSBSpecFrame, FluxFrame, - * SpecFluxFrame and Circle, are outside the first phase. + *

    The cases for a plain Frame, a SkyFrame, a SpecFrame, a DSBSpecFrame, a TimeFrame, a FluxFrame, + * a FrameSet holding a SkyFrame (with those of its current Frame, "inner1"), the probe's CmpFrame of a SkyFrame and a + * SpecFrame, and PlainCmpFrame, a CmpFrame of a one-axis and a two-axis plain Frame (each with + * those of its components, "inner1" and "inner2"), run here. Those of SpecFluxFrame (not yet + * ported) and Circle (out of scope) do not. * *

    Digits of an axis is set, read and tested through the attribute string ({@code * "Digits(n)"}), as the probe does: for a CmpFrame that goes to the component holding the axis @@ -31,8 +31,16 @@ class FrameAxisAttrsTest { /** The classes whose cases run. */ - private static final List CLASSES = - Arrays.asList("Frame", "SkyFrame", "TimeFrame", "FrameSet", "PlainCmpFrame"); + private static final List CLASSES = Arrays.asList( + "Frame", + "SkyFrame", + "SpecFrame", + "DSBSpecFrame", + "TimeFrame", + "FluxFrame", + "FrameSet", + "CmpFrame", + "PlainCmpFrame"); private static SkyFrame icrs() { SkyFrame f = new SkyFrame(); @@ -46,10 +54,18 @@ private static Frame make(String cls) { return new Frame(2); case "SkyFrame": return icrs(); + case "SpecFrame": + return new SpecFrame(); + case "DSBSpecFrame": + return new DSBSpecFrame(); case "TimeFrame": return new TimeFrame(); + case "FluxFrame": + return new FluxFrame(AstObject.AST__BAD, null); case "FrameSet": return new FrameSet(icrs()); + case "CmpFrame": + return new CmpFrame(icrs(), new SpecFrame()); case "PlainCmpFrame": return new CmpFrame(new Frame(1), new Frame(2)); default: @@ -65,10 +81,10 @@ private static Frame target(String cls, Frame f, String whose) { if ("FrameSet".equals(cls) && "inner1".equals(whose)) { return ((FrameSet) f).getFrame(FrameSet.AST__CURRENT); } - if ("PlainCmpFrame".equals(cls) && "inner1".equals(whose)) { + if (f instanceof CmpFrame && "inner1".equals(whose)) { return ((CmpFrame) f).decompose()[0]; } - if ("PlainCmpFrame".equals(cls) && "inner2".equals(whose)) { + if (f instanceof CmpFrame && "inner2".equals(whose)) { return ((CmpFrame) f).decompose()[1]; } throw new IllegalStateException("a " + cls + " has no Frame " + whose); @@ -192,8 +208,7 @@ void everyClassMatchesTheCLibrary() { failures.add(cls + " \"" + setting + "\" " + whose + " " + attr + ": got " + got + ", C gives " + want); } } - assertEquals( - 2096, run, "the Frame, SkyFrame, TimeFrame, FrameSet and PlainCmpFrame cases the C probe recorded"); + assertEquals(2096 + 80 + 80 + 80 + 864, run, "the cases of the in-scope classes the C probe recorded"); assertTrue(failures.isEmpty(), failures.size() + " cases differ:\n" + String.join("\n", failures)); } diff --git a/src/test/java/uk/ac/starlink/ast/FrameClassAttrsTest.java b/src/test/java/uk/ac/starlink/ast/FrameClassAttrsTest.java index ccb73b5..5bea8a5 100644 --- a/src/test/java/uk/ac/starlink/ast/FrameClassAttrsTest.java +++ b/src/test/java/uk/ac/starlink/ast/FrameClassAttrsTest.java @@ -18,14 +18,14 @@ * astGetC}, {@code astGetI} or {@code astGetD} and its {@code astTest} result; for a FrameSet it * also reads the current Frame ("inner"). {@link #make} and {@link #mismatch} do the same. * - *

    The probe's SpecFrame, DSBSpecFrame, FluxFrame and SpecFluxFrame cases are skipped (out of - * scope), as are its CmpFrame cases, whose CmpFrame joins a SkyFrame and a SpecFrame (needs - * SpecFrame), and its Circle cases (Region, out of scope). + *

    The probe's SpecFluxFrame cases are skipped (that class is not yet ported), as are its + * Circle cases (Region, out of scope). */ class FrameClassAttrsTest { /** The probe's classes this library provides. */ - private static final List IN_SCOPE = Arrays.asList("Frame", "SkyFrame", "TimeFrame", "FrameSet"); + private static final List IN_SCOPE = Arrays.asList( + "Frame", "SkyFrame", "SpecFrame", "DSBSpecFrame", "TimeFrame", "FluxFrame", "CmpFrame", "FrameSet"); /** The object the probe builds for {@code cls}. */ private static Frame make(String cls) { @@ -34,8 +34,16 @@ private static Frame make(String cls) { return new Frame(2); case "SkyFrame": return new SkyFrame(); + case "SpecFrame": + return new SpecFrame(); + case "DSBSpecFrame": + return new DSBSpecFrame(); case "TimeFrame": return new TimeFrame(); + case "FluxFrame": + return new FluxFrame(AstObject.AST__BAD, null); + case "CmpFrame": + return new CmpFrame(new SkyFrame(), new SpecFrame()); case "FrameSet": return new FrameSet(new SkyFrame()); default: @@ -43,11 +51,17 @@ private static Frame make(String cls) { } } - /** The Frame whose attributes show the effect of a setting on {@code f}: a FrameSet's current Frame. */ + /** + * The Frame whose attributes show the effect of a setting on {@code f}: a FrameSet's current + * Frame, or a CmpFrame's first component (its SkyFrame, the primary Frame of axis 1). + */ private static Frame inner(String cls, Frame f) { if ("FrameSet".equals(cls)) { return ((FrameSet) f).getFrame(FrameSet.AST__CURRENT); } + if ("CmpFrame".equals(cls)) { + return f.primaryFrame(1, new int[1]); + } return null; } @@ -129,7 +143,7 @@ void everyClassMatchesTheCLibrary() { failures.add(what + ": " + e.getMessage()); } } - assertEquals(4 * 256 + 256, run, "the in-scope cases the C probe recorded"); + assertEquals(6 * 256 + 2 * 512, run, "the in-scope cases the C probe recorded"); assertTrue( failures.isEmpty(), failures.size() + " of " + run + " cases differ:\n" + String.join("\n", failures)); } diff --git a/src/test/java/uk/ac/starlink/ast/FrameGeometryTest.java b/src/test/java/uk/ac/starlink/ast/FrameGeometryTest.java index 5439e15..b041829 100644 --- a/src/test/java/uk/ac/starlink/ast/FrameGeometryTest.java +++ b/src/test/java/uk/ac/starlink/ast/FrameGeometryTest.java @@ -16,7 +16,7 @@ * *

    A point with fewer coordinates than the Frame has axes, which Rust rejects with a panic * naming the shortfall, raises {@code AST__DIMIN} here with the same words, for a CmpFrame as for - * the other classes. {@code match_axes_finds_sky_in_cmp} needs a SpecFrame and is deferred. + * the other classes. */ class FrameGeometryTest { @@ -210,4 +210,18 @@ void cmpAnglePanicsOnAShortPoint() { void cmpDistancePanicsOnAShortPoint() { assertShortPoint("has 3 axes", () -> cmpPlain().distance(p(0.0, 0.0), p(3.0, 4.0))); } + + /** + * The SkyFrame of a CmpFrame of a SpecFrame and a SkyFrame is on its axes 2 and 3, which C's + * {@code astMatchAxes( cf, sky )} gives. + */ + @Test + void matchAxesFindsSkyInCmp() { + SkyFrame sf = new SkyFrame(); + sf.setSystem("FK5"); + SpecFrame df = new SpecFrame(); + df.setSystem("FREQ"); + CmpFrame cf = new CmpFrame(df, sf); + assertArrayEquals(new int[] {2, 3}, cf.matchAxes(sf)); + } } diff --git a/src/test/java/uk/ac/starlink/ast/FrameLoadTest.java b/src/test/java/uk/ac/starlink/ast/FrameLoadTest.java index da0d97d..7e836c5 100644 --- a/src/test/java/uk/ac/starlink/ast/FrameLoadTest.java +++ b/src/test/java/uk/ac/starlink/ast/FrameLoadTest.java @@ -8,7 +8,6 @@ import com.fasterxml.jackson.databind.JsonNode; import java.util.ArrayList; import java.util.Collections; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; @@ -26,24 +25,13 @@ * axis attributes C reads from it (through {@code astGetC}, {@code astGetI}, {@code astGetD} and * {@code astTest}) or the error it reports. * - *

    SpecFrame and FluxFrame are out of scope, so {@code frame_keys_survive_a_round_trip} and - * {@code legacy_observer_keys_are_read} check their TimeFrame halves only, and the cases of {@link - * #OUT_OF_SCOPE} are left out of {@code hand_written_descriptions_load_as_the_c_library_does}. + *

    The cases of {@link #OUT_OF_SCOPE}, if any, are left out of {@code + * hand_written_descriptions_load_as_the_c_library_does}. */ class FrameLoadTest { /** Cases holding a class that is out of scope, with that class. */ - private static final Map OUT_OF_SCOPE = outOfScope(); - - private static Map outOfScope() { - Map m = new LinkedHashMap<>(); - m.put("spec_bad_system", "SpecFrame"); - m.put("spec_bad_alsys", "SpecFrame"); - m.put("flux_bad_system", "FluxFrame"); - m.put("spec_axis_keys", "SpecFrame"); - m.put("flux_axis_keys", "FluxFrame"); - return Collections.unmodifiableMap(m); - } + private static final Map OUT_OF_SCOPE = Collections.emptyMap(); /** * Hand-written descriptions loaded differently from C, each with what it would take to load it @@ -84,19 +72,31 @@ private static Frame roundTrip(Frame f) { /** * Digits, MinAxes, MaxAxes, MatchEnd, Permute and PreserveAxes survive a native round trip of - * a TimeFrame. + * a SpecFrame and a TimeFrame. */ @Test void frameKeysSurviveARoundTrip() { + SpecFrame s = new SpecFrame(); + s.setSystem("FREQ"); + setFrameKeys(s); + assertFrameKeys(roundTrip(s)); TimeFrame t = new TimeFrame(); t.setSystem("MJD"); setFrameKeys(t); assertFrameKeys(roundTrip(t)); } - /** ClLat and ClLon (timeframe.c) give the observer position when ObsLat and ObsLon are absent. */ + /** + * GeoLat and GeoLon (specframe.c) and ClLat and ClLon (timeframe.c) give the observer position + * when ObsLat and ObsLon are absent. + */ @Test void legacyObserverKeysAreRead() { + String spec = "Begin SpecFrame\n Naxes = 1\n Domain = \"SPECTRUM\"\n System = \"FREQ\"\n " + + "GeoLat = 0.3\n GeoLon = 1.2\nEnd SpecFrame\n"; + Frame s = (Frame) ChannelText.read(spec); + assertEquals(0.3, s.getObsLatValue()); + assertEquals(1.2, s.getObsLonValue()); String time = "Begin TimeFrame\n Naxes = 1\n Domain = \"TIME\"\n System = \"MJD\"\n " + "ClLat = -0.4\n ClLon = 2.5\nEnd TimeFrame\n"; Frame t = (Frame) ChannelText.read(time); @@ -213,7 +213,7 @@ void handWrittenDescriptionsLoadAsTheCLibraryDoes() { failures.add(name + ": got " + got + ", C gives " + want); } } - assertEquals(12, run, "cases run"); + assertEquals(17, run, "cases run"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } diff --git a/src/test/java/uk/ac/starlink/ast/FrameSetIntegrityTest.java b/src/test/java/uk/ac/starlink/ast/FrameSetIntegrityTest.java index bd00756..a9335ae 100644 --- a/src/test/java/uk/ac/starlink/ast/FrameSetIntegrityTest.java +++ b/src/test/java/uk/ac/starlink/ast/FrameSetIntegrityTest.java @@ -23,19 +23,22 @@ * RestoreIntegrity}): it converts the recorded state of the current Frame to its new state with * {@code astConvert}, and reports {@code AST__ILOST} when no conversion exists. * - *

    The probe's FluxFrame, SpecFluxFrame, SpecFrame and DSBSpecFrame cases, and the CmpFrame cases - * (a CmpFrame of a SkyFrame and a SpecFrame), need classes outside the first phase and are skipped. + *

    The probe's SpecFluxFrame cases need a class this version does not have yet and are skipped. * Every value is compared within libm rounding, which is no wider than the Rust test's comparison. - * {@code unit_change_leaves_mappings_alone} reads a FrameSet holding a DSBSpecFrame, a LutMap and - * a SpecMap and is deferred. + * {@code unit_change_leaves_mappings_alone} reads a FrameSet holding a LutMap and is deferred. */ class FrameSetIntegrityTest { private static final JsonNode PROBE = ProbeData.load("integrity"); - /** The prefixes of the cases that need a class outside the first phase. */ - private static final List SKIPPED_PREFIXES = - Arrays.asList("flux_", "specflux_", "spec_", "dsb_", "cmp_sky_spec_"); + /** RefRA of the probe's SpecFrames ({@code integrity_probe.c REF_RA}). */ + private static final double REF_RA = 1.0471975511965976; + + /** RefDec of the probe's SpecFrames ({@code integrity_probe.c REF_DEC}). */ + private static final double REF_DEC = 0.5235987755982988; + + /** The prefixes of the cases that need a class this version does not have. */ + private static final List SKIPPED_PREFIXES = Arrays.asList("specflux_"); private static boolean skipped(String name) { for (String p : SKIPPED_PREFIXES) { @@ -52,9 +55,30 @@ private static SkyFrame sky(String settings) { return f; } + private static SpecFrame spec(String settings) { + SpecFrame f = new SpecFrame(); + f.set(settings); + return f; + } + /** The probe's current Frame for {@code name}. */ private static Frame current(String name) { switch (name) { + case "cmp_sky_spec_equinox": + case "cmp_sky_spec_galactic": + return new CmpFrame(sky("System=FK5"), spec("System=FREQ,Unit=GHz")); + case "spec_vrad": + return spec("System=FREQ,Unit=GHz,RestFreq=230.538"); + case "spec_lsrk": { + SpecFrame f = spec("System=FREQ,Unit=GHz,Epoch=2010.0"); + f.setRefPos(null, REF_RA, REF_DEC); + return f; + } + case "spec_sourcevel": { + SpecFrame f = spec("System=FREQ,Unit=GHz,StdOfRest=Source"); + f.setRefPos(null, REF_RA, REF_DEC); + return f; + } case "frame_activeunit_km": Frame f = new Frame(1); f.set("Unit(1)=m"); @@ -81,6 +105,16 @@ private static Frame current(String name) { SkyFrame p = sky("System=ICRS"); p.permAxes(new int[] {2, 1}); return p; + case "dsb_usb": + DSBSpecFrame d = new DSBSpecFrame(); + d.set("System=FREQ,Unit=GHz,DSBCentre=230.0,IF=4.0,SideBand=LSB"); + return d; + case "flux_unit_jy": + case "flux_system_sfcbr": { + FluxFrame ff = new FluxFrame(1.4e9, null); + ff.set("System=FLXDN"); + return ff; + } case "time_jd": case "time_utc": case "time_origin": @@ -101,7 +135,16 @@ private static String[][] settings(String name) { case "sky_unknown_title": return new String[][] {{"Title", "Renamed"}}; case "sky_fk5_equinox": + case "cmp_sky_spec_equinox": return new String[][] {{"Equinox", "J2050"}}; + case "cmp_sky_spec_galactic": + return new String[][] {{"System", "GALACTIC"}}; + case "spec_vrad": + return new String[][] {{"System", "VRAD"}}; + case "spec_lsrk": + return new String[][] {{"StdOfRest", "LSRK"}}; + case "spec_sourcevel": + return new String[][] {{"SourceVel", "100.0"}}; case "sky_gappt_epoch": return new String[][] {{"Epoch", "2010.0"}}; case "sky_fk4_to_fk5": @@ -118,6 +161,12 @@ private static String[][] settings(String name) { return new String[][] {{"TimeScale", "UTC"}}; case "time_origin": return new String[][] {{"TimeOrigin", "55000.0"}}; + case "dsb_usb": + return new String[][] {{"SideBand", "USB"}}; + case "flux_unit_jy": + return new String[][] {{"Unit(1)", "Jy"}}; + case "flux_system_sfcbr": + return new String[][] {{"System", "SFCBR"}}; default: throw new IllegalArgumentException("no case " + name); } @@ -128,9 +177,18 @@ private static double[][] points(String name) { if ("frame_activeunit_km".equals(name)) { return new double[][] {{1000.0, 5.0}}; } + if (name.startsWith("flux_")) { + return new double[][] {{1.0e-26, 3.0e-26}}; + } if (name.startsWith("time_")) { return new double[][] {{0.25, 1.75}}; } + if (name.startsWith("spec_") || name.startsWith("dsb_")) { + return new double[][] {{230.0, 345.0}}; + } + if (name.startsWith("cmp_")) { + return new double[][] {{1.0, 4.2}, {0.5, -0.9}, {1.0, 2.0}}; + } return new double[][] {{1.0, 4.2}, {0.5, -0.9}}; } @@ -198,7 +256,7 @@ void integrityMatchesTheCLibrary() { failures.add(failure); } } - assertEquals(13, checked, "cases in the first phase"); + assertEquals(21, checked, "the cases with classes this version has"); assertTrue( failures.isEmpty(), failures.size() + " of " + checked + " cases differ from C:\n" + String.join("\n", failures)); diff --git a/src/test/java/uk/ac/starlink/ast/FrameSetVariantsOracleTest.java b/src/test/java/uk/ac/starlink/ast/FrameSetVariantsOracleTest.java index 8f07098..fecc796 100644 --- a/src/test/java/uk/ac/starlink/ast/FrameSetVariantsOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/FrameSetVariantsOracleTest.java @@ -9,9 +9,7 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; import org.junit.jupiter.api.Test; import uk.ac.starlink.ast.testsupport.ProbeData; @@ -19,7 +17,7 @@ * Translation of Rust {@code tests/test_frameset_variants_oracle.rs}: FrameSets whose current Frame * has variants, against C's dumps of them ({@code oracle/frameset_variants.json}, from {@code * tools/oracle_fixtures/frameset_variants_probe.c}), for a current Frame of each kind: a Frame, a - * SkyFrame, a CmpFrame, and a Frame with Digits set. frame.c {@code Dump} writes the variants + * SkyFrame, a SpecFrame, a CmpFrame, and a Frame with Digits set. frame.c {@code Dump} writes the variants * FrameSet as {@code Vrnts}, last in the Frame class's part, so for a subclass of Frame it comes * before the {@code IsA Frame} marker, where {@code astLoadFrame} reads it back. * @@ -28,16 +26,11 @@ * Mapping it stores (frameset.c:1824), so the dumps hold a ZoomMap. The FrameSet read from C's dump * must also have the variants, the selected variant and the transformation of the FrameSet built * here. - * - *

    The probe's {@code specframe} case needs a SpecFrame, outside the first phase, and is skipped. */ class FrameSetVariantsOracleTest { private static final JsonNode CASES = ProbeData.load("frameset_variants").get("CASES"); - /** The cases skipped because they need a class outside the first phase. */ - private static final List SKIPPED = Arrays.asList("specframe"); - private static Frame basic(int naxes, String domain) { Frame f = new Frame(naxes); f.setDomain(domain); @@ -53,6 +46,10 @@ private static Frame current(String name) { SkyFrame sky = new SkyFrame(); sky.setDomain("SKY"); return sky; + case "specframe": + SpecFrame spec = new SpecFrame(); + spec.setDomain("SPEC"); + return spec; case "cmpframe": return new CmpFrame(basic(1, "A"), basic(1, "B")); case "frame_digits": @@ -77,10 +74,11 @@ private static FrameSet frameset(String name) { return fs; } - /** The transformation of two points through {@code fs}, axis by axis. */ + /** The transformation of two points through {@code fs}, axis by axis, on its first one or two axes. */ private static double[][] transform(FrameSet fs) { - double[][] in = {{1.5, 3.0}, {-2.25, 4.0}}; - return fs.tranP(2, 2, in, true, 2); + int naxes = fs.getNin(); + double[][] in = Arrays.copyOf(new double[][] {{1.5, 3.0}, {-2.25, 4.0}}, naxes); + return fs.tranP(2, naxes, in, true, naxes); } /** The text a Channel with Full = 1 writes for {@code obj}. */ @@ -98,14 +96,9 @@ private static String fullDump(AstObject obj) { @Test void dumpsMatchC() { - List skipped = new ArrayList<>(); int checked = 0; for (JsonNode c : CASES) { String name = c.get(0).asText(); - if (SKIPPED.contains(name)) { - skipped.add(name); - continue; - } String cDump = c.get(1).asText(); FrameSet fromC = assertInstanceOf(FrameSet.class, ChannelText.read(cDump), name); assertEquals(c.get(2).asText(), ChannelText.dump(fromC), name + ": C's dump read back"); @@ -116,7 +109,7 @@ void dumpsMatchC() { assertEquals(fromC.testVariant(), fs.testVariant(), name + ": Variant set"); double[][] want = transform(fromC); double[][] got = transform(fs); - for (int axis = 0; axis < 2; axis++) { + for (int axis = 0; axis < want.length; axis++) { assertArrayEquals(want[axis], got[axis], name + ": axis " + (axis + 1)); } @@ -126,7 +119,6 @@ void dumpsMatchC() { assertEquals(c.get(3).asText(), fullDump(fs), name + ": Full = 1"); checked++; } - assertEquals(SKIPPED, skipped); - assertEquals(CASES.size() - SKIPPED.size(), checked); + assertEquals(CASES.size(), checked); } } diff --git a/src/test/java/uk/ac/starlink/ast/FrameTest.java b/src/test/java/uk/ac/starlink/ast/FrameTest.java index 10d78a9..07888b6 100644 --- a/src/test/java/uk/ac/starlink/ast/FrameTest.java +++ b/src/test/java/uk/ac/starlink/ast/FrameTest.java @@ -15,10 +15,11 @@ * ast_tester/testframe.c}, and a table of Unit and NormUnit pairs read back from a one-axis C * Frame. * - *

    The parts for a plain Frame, a SkyFrame, a TimeFrame, a CmpFrame and a FrameSet holding a - * SkyFrame are translated here; of {@code - * spectral_time_and_flux_frames_normalise_the_unit_they_report}, the TimeFrame part. The SpecFrame, - * FluxFrame, DSBSpecFrame and Circle parts need classes outside the first phase. + *

    The parts for a plain Frame, a SkyFrame, a SpecFrame, a TimeFrame, a CmpFrame and a FrameSet + * holding a SkyFrame are translated here; of {@code + * spectral_time_and_flux_frames_normalise_the_unit_they_report}, the SpecFrame, DSBSpecFrame, + * TimeFrame and FluxFrame parts (the FluxFrame values checked against the pinned C library). The + * Circle parts need a class outside this library. */ class FrameTest { @@ -60,14 +61,37 @@ void normUnitEqualsUnitWhenItCannotBeSimplified() { assertEquals(timeFrame.getUnit(1), timeFrame.getNormUnit(1), "NormUnit(1) of a default TimeFrame"); } - /** A TimeFrame normalises the Unit it reports, its default included. */ + /** + * A SpecFrame, a DSBSpecFrame, a TimeFrame and a FluxFrame normalise the Unit they report, their + * defaults included. + */ @Test void spectralTimeAndFluxFramesNormaliseTheUnitTheyReport() { + SpecFrame freq = new SpecFrame(); + freq.setSystem("FREQ"); + assertEquals("GHz", freq.getNormUnit(1)); + freq.setUnit(1, "MHz*1000"); + assertEquals("GHz", freq.getNormUnit(1)); + SpecFrame wavn = new SpecFrame(); + wavn.setSystem("WAVN"); + assertEquals("m**-1", wavn.getNormUnit(1)); + DSBSpecFrame wave = new DSBSpecFrame(); + wave.setSystem("WAVE"); + assertEquals("Angstrom", wave.getNormUnit(1)); + TimeFrame time = new TimeFrame(); time.setSystem("MJD"); assertEquals("d", time.getNormUnit(1)); time.setUnit(1, "1000*s"); assertEquals("ks", time.getNormUnit(1)); + + FluxFrame flux = new FluxFrame(); + assertEquals("(W/Hz)*m**-2", flux.getNormUnit(1)); + flux.setUnit(1, "erg/s/cm**2/Hz"); + assertEquals("(erg/Hz)*cm**-2/s", flux.getNormUnit(1)); + FluxFrame sb = new FluxFrame(); + sb.setSystem("SFCBR"); + assertEquals("(W/Hz)*arcmin**-2*m**-2", sb.getNormUnit(1)); } @Test diff --git a/src/test/java/uk/ac/starlink/ast/JniastApiTest.java b/src/test/java/uk/ac/starlink/ast/JniastApiTest.java index 8bff243..f0d121a 100644 --- a/src/test/java/uk/ac/starlink/ast/JniastApiTest.java +++ b/src/test/java/uk/ac/starlink/ast/JniastApiTest.java @@ -43,7 +43,9 @@ class JniastApiTest { "Channel", "CmpFrame", "CmpMap", + "DSBSpecFrame", "FitsChan", + "FluxFrame", "Frame", "FrameSet", "KeyMap", @@ -56,6 +58,9 @@ class JniastApiTest { "SkyAxis", "SkyFrame", "SlaMap", + "SpecFluxFrame", + "SpecFrame", + "SpecMap", "SphMap", "TimeFrame", "TimeMap", diff --git a/src/test/java/uk/ac/starlink/ast/KeyMapTest.java b/src/test/java/uk/ac/starlink/ast/KeyMapTest.java index 3e39645..cb94244 100644 --- a/src/test/java/uk/ac/starlink/ast/KeyMapTest.java +++ b/src/test/java/uk/ac/starlink/ast/KeyMapTest.java @@ -25,9 +25,9 @@ * therefore translated as C writes them. * *

    The tests built on the seven scalar entries of testkeymap.c, one of which is a SkyFrame, - * are {@code scalarPutsAndTypes}, {@code scalarCrossTypeReads} and {@code - * aScalarReadsAsALengthOneVector}. Those that also store a SpecFrame, which is outside the first - * phase, are on the deferred list. + * are {@code scalarPutsAndTypes}, {@code copyPreservesEveryEntry}, {@code scalarCrossTypeReads} + * and {@code aScalarReadsAsALengthOneVector}; those on its vectors, one of which holds a + * SpecFrame, follow them. */ class KeyMapTest { @@ -1624,4 +1624,165 @@ void aScalarReadsAsALengthOneVector() { assertEquals(1, avec.length); assertInstanceOf(SkyFrame.class, avec[0]); } + + /** + * main (testkeymap.c:433-532): a copy holds every entry, and changing it leaves the original + * as it was. + */ + @Test + void copyPreservesEveryEntry() { + KeyMap map = sevenKeyMap(); + KeyMap map2 = (KeyMap) map.copy(); + + // Error 0. + assertEquals(7, map2.mapSize()); + + // Error badkey / nokey: every put key is present exactly once, and nothing else is. + List keys = readKeys(map2); + Collections.sort(keys); + assertEquals(Arrays.asList("Freda", "Fredc", "Fredd", "Fredi", "Fredk", "Fredr", "Freds"), keys); + + // Error -1: a scalar has length 1 through astMapLength. + assertEquals(1, map2.mapLength("Fredi")); + + // Error 1 / 2, 1k / 2k, 1 / 2B, 3 / 4, 3b / 4b. + assertEquals(1999, map2.mapGet0I("Fredi")); + assertEquals(1999L, map2.mapGet0K("Fredk")); + assertEquals((short) 1999, map2.mapGet0S("Freds")); + assertEquals(1999.9, map2.mapGet0D("Fredd")); + assertEquals(1999.9f, map2.mapGet0F("Fredr")); + + // Error 5 / 6 / 7. + assertEquals("Hello", map2.mapGet0C("Fredc")); + + // Error 5b / 6b / 7b: astMapGetC on a length-1 entry gives the value, with no + // parentheses. + assertEquals("Hello", map2.mapGetC("Fredc")); + + // Error 8 / 9. + assertInstanceOf(SkyFrame.class, map2.mapGet0A("Freda")); + + // The copy is independent of the original. + map2.mapPut0I("Fredi", -7, "com 1"); + map2.mapPut0A("Freda", new SpecFrame(), " "); + map2.mapRemove("Fredc"); + + assertEquals(7, map.mapSize()); + assertEquals(1999, map.mapGet0I("Fredi")); + assertEquals("Hello", map.mapGet0C("Fredc")); + assertInstanceOf(SkyFrame.class, map.mapGet0A("Freda")); + } + + /** + * {@link #sevenKeyMap} with five of its scalars replaced by vectors, as main does at + * testkeymap.c:638-677; Fredk and Fredr stay scalar. C's {@code astSpecFrame( " " )} leaves + * the System at its wavelength default. + */ + private static KeyMap vectorKeyMap() { + KeyMap map = sevenKeyMap(); + map.mapPut1I("Fredi", new int[] {1999, 0}, "com 1"); + // Error 29b. + assertEquals(2, map.mapLength("Fredi")); + map.mapPut1S("Freds", new short[] {1999, 0}, "com 1"); + // Error 29c. + assertEquals(2, map.mapLength("Freds")); + map.mapPut1D("Fredd", new double[] {1999.9, -0.01}, "com2"); + map.mapPut1C("Fredc", new String[] {"Hello", " ", " Hello"}, " "); + map.mapPut1A("Freda", new AstObject[] {new SkyFrame(), null, new SpecFrame(), null}, " "); + return map; + } + + /** + * main (testkeymap.c:638-763). A scalar read of a vector entry gives the entry's first + * element. + */ + @Test + void vectorPutsReplaceScalars() { + KeyMap map2 = (KeyMap) vectorKeyMap().copy(); + + // Error A1 / A2, A1k / A2k, A3 / A4. + assertEquals(1999, map2.mapGet0I("Fredi")); + assertEquals(1999L, map2.mapGet0K("Fredk")); + assertEquals(1999.9, map2.mapGet0D("Fredd")); + + // Error A5 / A6 / A7: MapLenC reports the longest element, " Hello", while MapGet0C + // still gives element 0. + assertEquals(7, map2.mapLenC("Fredc")); + assertEquals("Hello", map2.mapGet0C("Fredc")); + + // Error A8 / A9. + assertInstanceOf(SkyFrame.class, map2.mapGet0A("Freda")); + + // Error A10 / A11, A12 / A13a / A13. + assertEquals(1999.0, map2.mapGet0D("Fredi")); + assertEquals("1999", map2.mapGet0C("Fredi")); + + // Error A14 / A15, A14k / A15k. + assertEquals(2000, map2.mapGet0I("Fredd")); + assertEquals(2000L, map2.mapGet0K("Fredd")); + + // Error A16 / A17a / A17. + assertEquals("1999.9", map2.mapGet0C("Fredd")); + } + + /** main (testkeymap.c:765-835). */ + @Test + void vectorReads() { + KeyMap map2 = (KeyMap) vectorKeyMap().copy(); + + // Error B1 / B2a / B2b / B2c. + assertArrayEquals(new int[] {1999, 0}, map2.mapGet1I("Fredi")); + // Error B3 / B4a / B4b / B4c. + assertArrayEquals(new double[] {1999.9, -0.01}, map2.mapGet1D("Fredd")); + + // Error B5 / B6a / B6b / B6c / B6d / B6e: elements 1 and 3 were put as null and read + // back as null. + AstObject[] avec = map2.mapGet1A("Freda"); + assertEquals(4, avec.length); + assertInstanceOf(SkyFrame.class, avec[0]); + assertNull(avec[1]); + assertInstanceOf(SpecFrame.class, avec[2]); + assertNull(avec[3]); + + // Error B7 / B8a / B8b / B8c / B8d. + assertArrayEquals(new String[] {"Hello", " ", " Hello"}, map2.mapGet1C("Fredc")); + } + + /** main (testkeymap.c:849-877). */ + @Test + void elementReads() { + KeyMap map2 = (KeyMap) vectorKeyMap().copy(); + + // Error B1z / B2bz. + assertEquals(1999, map2.mapGetElemI("Fredi", 0)); + // Error B3z / B4cz. + assertEquals(-0.01, map2.mapGetElemD("Fredd", 1)); + // Error B5z / B6dz. + AstObject[] aval = new AstObject[1]; + assertTrue(map2.mapGetElemA("Freda", 2, aval)); + assertInstanceOf(SpecFrame.class, aval[0]); + // Error B7z / B8dz. + assertEquals(" Hello", map2.mapGetElemC("Fredc", 2)); + } + + /** main (testkeymap.c:879-883): a removed key reads as absent, not as an error. */ + @Test + void removeThenReadFails() { + KeyMap map2 = (KeyMap) vectorKeyMap().copy(); + + // Removing an absent key is silent. + map2.mapRemove("Bert"); + map2.mapRemove("Fredc"); + // Error C1. + assertNull(map2.mapGet1C("Fredc")); + } + + /** main (testkeymap.c:885), on the KeyMap {@link #removeThenReadFails} leaves. */ + @Test + void checkDumpRoundTrip() { + KeyMap map2 = (KeyMap) vectorKeyMap().copy(); + map2.mapRemove("Bert"); + map2.mapRemove("Fredc"); + checkDump(map2); + } } diff --git a/src/test/java/uk/ac/starlink/ast/MatchAxesTest.java b/src/test/java/uk/ac/starlink/ast/MatchAxesTest.java index 9d19902..4ba917e 100644 --- a/src/test/java/uk/ac/starlink/ast/MatchAxesTest.java +++ b/src/test/java/uk/ac/starlink/ast/MatchAxesTest.java @@ -19,11 +19,7 @@ * {@code astMatchAxes( frm1, frm2, axes )} for every pair of a list of Frames). * *

    The probe's Frames are numbered as its {@code make} function builds them. The cases whose - * Frames this version can build run here: the SkyFrame (0), the SkyFrame with its axes swapped - * (1), the one-axis plain Frame (3), the CmpFrame of a one-axis Frame and a SkyFrame with its axes - * permuted (2, 3, 1) (7), the FrameSet whose current Frame is a SkyFrame (8) and the TimeFrame - * (12). The cases using Frames that hold a SpecFrame (2, 4, 5, 6, 9, 11) or a Circle (10) are - * outside this version. + * Frames this version can build run here: all but those using the Circle (10), a Region. * *

    {@code frm1.matchAxes(frm2)} is called, as the probe calls {@code astMatchAxes}, so that a * FrameSet {@code frm1} gives its current Frame as C's FrameSet {@code MatchAxes} does. @@ -43,8 +39,18 @@ private static Frame frame(int i) { SkyFrame swapped = new SkyFrame(); swapped.permAxes(new int[] {2, 1}); return swapped; + case 2: + return new SpecFrame(); case 3: return new Frame(1); + case 4: + return new CmpFrame(new SkyFrame(), new SpecFrame()); + case 5: + CmpFrame permuted = new CmpFrame(new SkyFrame(), new SpecFrame()); + permuted.permAxes(new int[] {3, 2, 1}); + return permuted; + case 6: + return new CmpFrame(new SpecFrame(), new SkyFrame()); case 7: CmpFrame cmp = new CmpFrame(new Frame(1), new SkyFrame()); cmp.permAxes(new int[] {2, 3, 1}); @@ -53,6 +59,12 @@ private static Frame frame(int i) { FrameSet fs = new FrameSet(new Frame(2)); fs.addFrame(FrameSet.AST__BASE, new UnitMap(2), new SkyFrame()); return fs; + case 9: + FrameSet fs3 = new FrameSet(new Frame(3)); + fs3.addFrame(FrameSet.AST__BASE, new UnitMap(3), new CmpFrame(new SpecFrame(), new SkyFrame())); + return fs3; + case 11: + return new CmpFrame(new CmpFrame(new SpecFrame(), new SkyFrame()), new Frame(1)); case 12: return new TimeFrame(); default: @@ -84,7 +96,7 @@ void matchAxesMatchesTheCLibrary() { + Arrays.toString(expected)); } } - assertEquals(36, ran, "the cases with Frames this version builds"); + assertEquals(144, ran, "the cases with Frames this version builds"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } diff --git a/src/test/java/uk/ac/starlink/ast/NanOutputsTest.java b/src/test/java/uk/ac/starlink/ast/NanOutputsTest.java index f646ff6..ada543a 100644 --- a/src/test/java/uk/ac/starlink/ast/NanOutputsTest.java +++ b/src/test/java/uk/ac/starlink/ast/NanOutputsTest.java @@ -14,8 +14,8 @@ * NaN input is taken to be bad. Each Mapping is given points with a NaN on one input axis at a * time, and transformed in each direction it defines. * - *

    The Rust test's LutMap, MathMap, UnitNormMap, SpecMap, PcdMap and TranMap are outside the - * first phase. + *

    The Rust test's LutMap, MathMap, UnitNormMap, PcdMap and TranMap are outside the first + * phase. */ class NanOutputsTest { @@ -32,6 +32,9 @@ private static Map mappings() { SlaMap sla = new SlaMap(); sla.add("EQGAL", new double[0]); m.put("SlaMap", sla); + SpecMap spec = new SpecMap(1, 0); + spec.specAdd("FRTOWV", new double[0]); + m.put("SpecMap", spec); m.put("SphMap", new SphMap()); TimeMap time = new TimeMap(); time.timeAdd("MJDTOJD", new double[] {0.0, 0.0}); diff --git a/src/test/java/uk/ac/starlink/ast/NanProtocolTest.java b/src/test/java/uk/ac/starlink/ast/NanProtocolTest.java index 868d032..1ab19c5 100644 --- a/src/test/java/uk/ac/starlink/ast/NanProtocolTest.java +++ b/src/test/java/uk/ac/starlink/ast/NanProtocolTest.java @@ -171,6 +171,19 @@ void nanProtocolTimemap() { assertNanProtocolMatchesTransform(map, fromRows(rows), 32, true, 1e-14); } + @Test + void nanProtocolSpecmap() { + SpecMap map = new SpecMap(1, 0); + map.specAdd("WNTOFR", new double[0]); + double[][] rows = new double[32][]; + for (int i = 0; i < 32; i++) { + rows[i] = new double[] {i + 1.0}; + } + rows[7][0] = BAD; + rows[11][0] = Double.NaN; + assertNanProtocolMatchesTransform(map, fromRows(rows), 32, true, 1e-14); + } + /** The simplified FrameSet read from {@code lsst.ast}. */ private static Mapping loadLsst() { return LsstOracleTest.loadLsst().simplify(); diff --git a/src/test/java/uk/ac/starlink/ast/NativeRoundTripTest.java b/src/test/java/uk/ac/starlink/ast/NativeRoundTripTest.java index 7d7bfd6..ee1c0b7 100644 --- a/src/test/java/uk/ac/starlink/ast/NativeRoundTripTest.java +++ b/src/test/java/uk/ac/starlink/ast/NativeRoundTripTest.java @@ -236,4 +236,11 @@ void roundTripTimemap() { m.timeAdd("TAITOUTC", new double[] {50000.0, AstObject.AST__BAD}); assertDoubleRoundTrip(m, "TimeMap tai->utc"); } + + @Test + void roundTripSpecmap() { + SpecMap m = new SpecMap(1, 0); + m.specAdd("WNTOFR", new double[0]); + assertDoubleRoundTrip(m, "SpecMap wn->fr"); + } } diff --git a/src/test/java/uk/ac/starlink/ast/NewUnitTest.java b/src/test/java/uk/ac/starlink/ast/NewUnitTest.java index d0d3617..496c7b3 100644 --- a/src/test/java/uk/ac/starlink/ast/NewUnitTest.java +++ b/src/test/java/uk/ac/starlink/ast/NewUnitTest.java @@ -16,8 +16,7 @@ * Symbol for the new Unit and clears a set Format when the Unit changes (frame.c {@code SetUnit}, * {@code ClearUnit} and {@code NewUnit}); trailing spaces are dropped from the Unit. * - *

    The plain Frame cases and {@code time_s} run here; {@code spec_log} and {@code spec_mhz} need - * a SpecFrame, outside the first phase. + *

    Every case runs here. */ class NewUnitTest { @@ -59,6 +58,18 @@ private static Frame run(String name) { f = frame(true); f.clearUnit(1); return f; + case "spec_log": + case "spec_mhz": { + SpecFrame sf = new SpecFrame(); + sf.setSystem("FREQ"); + sf.setLabel(1, "Nu"); + if ("spec_log".equals(name)) { + sf.setSymbol(1, "n"); + } + sf.setFormat(1, "%.3f"); + sf.setUnit(1, "spec_log".equals(name) ? "log(Hz)" : "MHz"); + return sf; + } case "time_s": f = new TimeFrame(); f.set("System=MJD,Label(1)=When,Format(1)=%.3f"); @@ -87,7 +98,7 @@ void unitChangesMatchTheCLibrary() { failures.add(name + ": got " + got + ", C gives " + want); } } - assertEquals(7, ran, "the plain Frame cases and time_s"); + assertEquals(9, ran, "every case the C probe recorded"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } } diff --git a/src/test/java/uk/ac/starlink/ast/OverlayTest.java b/src/test/java/uk/ac/starlink/ast/OverlayTest.java index 8d5ed8c..cd564a3 100644 --- a/src/test/java/uk/ac/starlink/ast/OverlayTest.java +++ b/src/test/java/uk/ac/starlink/ast/OverlayTest.java @@ -2,7 +2,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -19,23 +18,23 @@ * target and then by the template, each through its own class's Overlay (frame.c {@code * SubFrame}). * - *

    The cases of {@code overlay_results_match_the_c_library} whose Frames this version builds run - * here: {@code frame_pick}, the SkyFrame cases ({@code sky_target_frame_template}, {@code - * sky_pick_one}) and the TimeFrame cases ({@code time_target_frame_template}, {@code - * time_system_change}, {@code time_pick_padded}). The cases with a SpecFrame - * or a FluxFrame (among them {@code cmp_template_plain_target}, whose CmpFrame holds a SpecFrame) - * are outside this version. + *

    Every case of {@code overlay_results_match_the_c_library} runs here. */ class OverlayTest { /** J1990 as a TDB Modified Julian Date. */ private static final double J1990 = 47892.0; - /** The current Frame of what {@code target.findFrame(template, "")} finds. */ + /** The current Frame of what {@code target.findFrame(template, "")} finds, or null. */ private static Frame found(Frame target, Frame template) { FrameSet fs = target.findFrame(template, ""); - assertNotNull(fs, "a match"); - return fs.getFrame(FrameSet.AST__CURRENT); + return fs == null ? null : fs.getFrame(FrameSet.AST__CURRENT); + } + + private static SpecFrame spec(String settings) { + SpecFrame f = new SpecFrame(); + f.set(settings); + return f; } private static TimeFrame time(String system) { @@ -44,14 +43,33 @@ private static TimeFrame time(String system) { return f; } + /** The probe's {@code astFluxFrame( 1.4e9, NULL, "System=FLXDN" )}. */ + private static FluxFrame flux() { + FluxFrame f = new FluxFrame(1.4e9, null); + f.setSystem("FLXDN"); + return f; + } + private static SkyFrame sky(String system) { SkyFrame f = new SkyFrame(); f.setSystem(system); return f; } - /** The Frame the probe's case gives, or null if this version cannot build its Frames. */ - private static Frame run(String name) { + /** + * The Frame the probe's case gives, as the one element of an array, which is null if the case + * finds no Frame; or null if this version cannot build the case's Frames. + */ + private static Frame[] run(String name) { + Frame f = build(name); + if (f != null || "cmp_template_plain_target".equals(name)) { + return new Frame[] {f}; + } + return null; + } + + /** The Frame the probe's case gives, or null if there is none or this version cannot build it. */ + private static Frame build(String name) { switch (name) { case "frame_pick": { Frame f = new Frame(2); @@ -94,6 +112,29 @@ private static Frame run(String name) { } case "time_pick_padded": return time("JD").pickAxes(2, new int[] {1, 0}, null); + case "spec_target_frame_template": { + Frame t = new Frame(1); + t.set("Domain=SPECTRUM,Title=Spec,Label(1)=Nu,Digits=8"); + return found(spec("System=FREQ,Unit=GHz"), t); + } + case "spec_system_change": + return found(spec("System=FREQ,Label(1)=Mine,Title=Mine"), spec("System=WAVE")); + case "cmp_template_plain_target": { + Frame target = new Frame(2); + target.setDomain("SPECTRUM-"); + return found(target, new CmpFrame(spec("Title=CmpSpec,Label(1)=Freq"), new Frame(1))); + } + case "spec_pick_padded": + return spec("System=FREQ,Unit=GHz").pickAxes(2, new int[] {1, 0}, null); + case "spec_wave_pick_padded": + return spec("System=WAVE").pickAxes(2, new int[] {1, 0}, null); + case "flux_target_frame_template": { + Frame t = new Frame(1); + t.set("Domain=FLUX,Title=TT,Label(1)=LL,Epoch=2010.0,Digits=9"); + return found(flux(), t); + } + case "flux_pick_padded": + return flux().pickAxes(2, new int[] {1, 0}, null); default: return null; } @@ -105,16 +146,21 @@ void overlayResultsMatchTheCLibrary() { int ran = 0; for (JsonNode c : ProbeData.load("overlay").get("CASES")) { String name = c.get(0).asText(); - Frame f = run(name); - if (f == null) { + Frame[] built = run(name); + if (built == null) { continue; } ran++; + Frame f = built[0]; JsonNode w = c.get(1); - String got = f.getTitle() + "|" + f.getDomain() + "|" + f.getDigits() + "|" + f.testEpoch() + "|" - + f.getEpochMjd() + "|" + f.getLabel(1) + "|" + f.getUnit(1); - String want = - w.get(0).asText() + "|" + w.get(1).asText() + "|" + w.get(2).asInt() + "|" + String got = f == null + ? "None" + : f.getTitle() + "|" + f.getDomain() + "|" + f.getDigits() + "|" + f.testEpoch() + "|" + + f.getEpochMjd() + "|" + f.getLabel(1) + "|" + f.getUnit(1); + String want = w.isNull() + ? "None" + : w.get(0).asText() + "|" + w.get(1).asText() + "|" + + w.get(2).asInt() + "|" + w.get(3).asBoolean() + "|" + ProbeData.toDouble(w.get(4)) + "|" + w.get(5).asText() + "|" + w.get(6).asText(); @@ -122,7 +168,7 @@ void overlayResultsMatchTheCLibrary() { failures.add(name + ": got " + got + ", C gives " + want); } } - assertEquals(6, ran, "the cases with Frames this version builds"); + assertEquals(13, ran, "the cases with Frames this version builds"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } diff --git a/src/test/java/uk/ac/starlink/ast/SectionLoadTest.java b/src/test/java/uk/ac/starlink/ast/SectionLoadTest.java index 7925526..3efcf96 100644 --- a/src/test/java/uk/ac/starlink/ast/SectionLoadTest.java +++ b/src/test/java/uk/ac/starlink/ast/SectionLoadTest.java @@ -35,12 +35,6 @@ class SectionLoadTest { private static Map outOfScope() { Map m = new LinkedHashMap<>(); - m.put("spec_ident_in_frame", "SpecFrame"); - m.put("spec_ident_in_object", "SpecFrame"); - m.put("spec_items_swapped", "SpecFrame"); - m.put("spec_items_placed", "SpecFrame"); - m.put("dsb_sideband_in_spec", "DSBSpecFrame"); - m.put("dsb_sideband_placed", "DSBSpecFrame"); m.put("circle_negate_in_class", "Circle"); m.put("circle_negate_placed", "Circle"); m.put("circle_ident_in_region", "Circle"); @@ -118,7 +112,7 @@ void eachClassReadsOnlyItsOwnPart() { } } } - assertEquals(20, run, "cases run"); + assertEquals(26, run, "cases run"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } } diff --git a/src/test/java/uk/ac/starlink/ast/SimplifyRegressionTest.java b/src/test/java/uk/ac/starlink/ast/SimplifyRegressionTest.java index 6394830..7eff61b 100644 --- a/src/test/java/uk/ac/starlink/ast/SimplifyRegressionTest.java +++ b/src/test/java/uk/ac/starlink/ast/SimplifyRegressionTest.java @@ -135,22 +135,26 @@ static String failure(Row r, Map> oracle, TransformO String refText = Fixtures.read(r.reference); Mapping simplified; Mapping input; + String dump; try { AstObject inObj = ChannelText.read(Fixtures.read(r.input)); AstObject refObj = ChannelText.read(refText); - if (inObj instanceof FrameSet && !(refObj instanceof FrameSet)) { - input = ((FrameSet) inObj).getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); - } else if (inObj instanceof Mapping) { - input = (Mapping) inObj; - } else { + input = inputMapping(inObj, refObj); + if (input == null) { return "input is a " + inObj.getClass().getSimpleName() + ", not a Mapping"; } String inputBefore = withoutRecords(ChannelText.dump(input)); - List transformsBefore = inputTransforms(input, oracle.get(r.input)); simplified = input.simplify(); if (!inputBefore.equals(withoutRecords(ChannelText.dump(input)))) { return "simplify() changed the input's dump"; } + // Both dumps are taken before anything is transformed, since a transformation can + // store values that are written: a 1-dimensional SpecMap keeps each frequency + // correction factor it works out, as C's does (specmap.c FrameChange). What the input + // computed before it was simplified is found from a second reading of it. + dump = ChannelText.dump(simplified); + List transformsBefore = inputTransforms( + inputMapping(ChannelText.read(Fixtures.read(r.input)), refObj), oracle.get(r.input)); List transformsAfter = inputTransforms(input, oracle.get(r.input)); for (int i = 0; i < transformsBefore.size(); i++) { if (!Arrays.deepEquals(transformsBefore.get(i), transformsAfter.get(i))) { @@ -162,7 +166,6 @@ static String failure(Row r, Map> oracle, TransformO } boolean sameFile = r.input.equals(r.reference); - String dump = ChannelText.dump(simplified); if (sameFile) { boolean frame = simplified instanceof Frame; boolean card = hasTopLevelIsSimp(dump); @@ -196,6 +199,20 @@ static String failure(Row r, Map> oracle, TransformO return problem; } + /** + * The Mapping a row simplifies: the input itself, or a FrameSet's base-to-current Mapping when + * the reference is not a FrameSet; null if the input is not a Mapping. + */ + private static Mapping inputMapping(AstObject inObj, AstObject refObj) { + if (inObj instanceof FrameSet && !(refObj instanceof FrameSet)) { + return ((FrameSet) inObj).getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + } else if (inObj instanceof Mapping) { + return (Mapping) inObj; + } else { + return null; + } + } + /** * A dump without its records of simplification, {@code IsSimp} and {@code ReSimp}, which C's * {@code astSimplify} also writes on the Mapping it is given and on its shared components. diff --git a/src/test/java/uk/ac/starlink/ast/SkyGeometryTest.java b/src/test/java/uk/ac/starlink/ast/SkyGeometryTest.java index 86c311a..0f51599 100644 --- a/src/test/java/uk/ac/starlink/ast/SkyGeometryTest.java +++ b/src/test/java/uk/ac/starlink/ast/SkyGeometryTest.java @@ -19,10 +19,9 @@ * {@code astIntersect} on a default SkyFrame and on one with its axes swapped, including bad * inputs and the degenerate cases C reports as bad. * - *

    Of {@code cmp_frame_resolve_matches_the_c_library} and {@code - * cmp_frame_resolve_points_matches_the_c_library}, the cases of kind 1, a CmpFrame of a one-axis - * Frame and a SkyFrame, run here; those of kind 0, a CmpFrame of a SkyFrame and a SpecFrame, need - * a SpecFrame, outside the first phase. + *

    {@code cmp_frame_resolve_matches_the_c_library} and {@code + * cmp_frame_resolve_points_matches_the_c_library} run their cases of kind 0, a CmpFrame of a + * SkyFrame and a SpecFrame, and of kind 1, a CmpFrame of a one-axis Frame and a SkyFrame. */ class SkyGeometryTest { @@ -93,14 +92,12 @@ void intersectMatchesTheCLibrary() { } /** - * The probe's CmpFrame of kind 1, a one-axis Frame and a SkyFrame, with axes 1 and 3 swapped - * when {@code permuted}; null for kind 0, which holds a SpecFrame. + * The probe's CmpFrame of kind 0, a SkyFrame and a SpecFrame, or of kind 1, a one-axis Frame + * and a SkyFrame, with axes 1 and 3 swapped when {@code permuted}. */ private static CmpFrame cmp(int kind, boolean permuted) { - if (kind == 0) { - return null; - } - CmpFrame f = new CmpFrame(new Frame(1), new SkyFrame()); + CmpFrame f = + kind == 0 ? new CmpFrame(new SkyFrame(), new SpecFrame()) : new CmpFrame(new Frame(1), new SkyFrame()); if (permuted) { f.permAxes(new int[] {3, 2, 1}); } @@ -124,9 +121,6 @@ void cmpFrameResolveMatchesTheCLibrary() { int ran = 0; for (JsonNode c : ProbeData.load("sky_geometry").get("CMP_RESOLVE_CASES")) { CmpFrame f = cmp(c.get(0).asInt(), c.get(1).asBoolean()); - if (f == null) { - continue; - } ran++; double[] p4 = new double[3]; double[] d = f.resolve(point(c.get(2)), point(c.get(3)), point(c.get(4)), p4); @@ -138,7 +132,7 @@ void cmpFrameResolveMatchesTheCLibrary() { describeCmp(c, 3) + ": got " + Arrays.toString(got) + ", C gives " + Arrays.toString(want)); } } - assertEquals(8, ran, "the cases of kind 1"); + assertEquals(16, ran, "the cases of kinds 0 and 1"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } @@ -148,9 +142,6 @@ void cmpFrameResolvePointsMatchesTheCLibrary() { int ran = 0; for (JsonNode c : ProbeData.load("sky_geometry").get("CMP_RESOLVE_POINTS_CASES")) { CmpFrame f = cmp(c.get(0).asInt(), c.get(1).asBoolean()); - if (f == null) { - continue; - } ran++; JsonNode pts = c.get(4); int npoint = pts.size(); @@ -173,7 +164,7 @@ void cmpFrameResolvePointsMatchesTheCLibrary() { } } } - assertEquals(4, ran, "the cases of kind 1"); + assertEquals(8, ran, "the cases of kinds 0 and 1"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } diff --git a/src/test/java/uk/ac/starlink/ast/SkyLastTest.java b/src/test/java/uk/ac/starlink/ast/SkyLastTest.java index d4ce77f..e65f99e 100644 --- a/src/test/java/uk/ac/starlink/ast/SkyLastTest.java +++ b/src/test/java/uk/ac/starlink/ast/SkyLastTest.java @@ -8,9 +8,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.FreshThread; import uk.ac.starlink.ast.testsupport.ProbeData; /** @@ -25,25 +25,6 @@ */ class SkyLastTest { - /** Runs {@code body} on a new thread and rethrows anything it throws. */ - private static void assertPassesOnFreshThread(Runnable body) throws InterruptedException { - AtomicReference failure = new AtomicReference<>(); - Thread t = new Thread(body, "fresh LAST table"); - t.setUncaughtExceptionHandler((th, e) -> failure.set(e)); - t.start(); - t.join(); - Throwable e = failure.get(); - if (e instanceof Error) { - throw (Error) e; - } - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } - if (e != null) { - throw new AssertionError(e); - } - } - private static SkyFrame sky(String system, double epoch, double obslon) { SkyFrame f = new SkyFrame(); f.setSystem(system); @@ -95,7 +76,7 @@ private static double[] flatten(JsonNode rows) { @Test void cachedLastFollowsTheCLibrary() throws InterruptedException { - assertPassesOnFreshThread(SkyLastTest::cachedLastSteps); + FreshThread.assertPasses(SkyLastTest::cachedLastSteps); } private static void cachedLastSteps() { @@ -178,7 +159,7 @@ private static void cachedLastSteps() { */ @Test void aFramesetMemberKeepsItsCachedLast() throws InterruptedException { - assertPassesOnFreshThread(SkyLastTest::framesetMemberSteps); + FreshThread.assertPasses(SkyLastTest::framesetMemberSteps); } private static void framesetMemberSteps() { diff --git a/src/test/java/uk/ac/starlink/ast/SpecConvertOracleTest.java b/src/test/java/uk/ac/starlink/ast/SpecConvertOracleTest.java new file mode 100644 index 0000000..1b7097c --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecConvertOracleTest.java @@ -0,0 +1,237 @@ +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 com.fasterxml.jackson.databind.JsonNode; +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.ProbeData; + +/** + * Translation of Rust {@code tests/test_spec_convert.rs}: the Mapping {@code convert} finds between + * SpecFrames, checked against C ({@code oracle/spec_convert.json}, from {@code + * tools/oracle_fixtures/spec_convert_probe.c}; specframe.c {@code Match}, {@code SubFrame} and + * {@code MakeSpecMapping}). It converts between every pair of spectral systems in two + * configurations: with no RestFreq, where C's default of 1.0E14 Hz relates velocities to + * frequencies, and with different RestFreqs, standards of rest, an Epoch and a reference position + * on the two sides. Two named cases cover the units check at the end of {@code MakeSpecMapping}. + * + *

    The named cases {@code dsb_*}, {@code spec_vrad_to_dsb} and {@code dsb_found_in_cube} convert + * DSBSpecFrames, which a DSBSpecFrame template aligns as a SpecFrame unless both have AlignSideBand + * set (dsbspecframe.c {@code Match} and {@code SubFrame}), the last in a (sky, DSBSpecFrame) cube. + */ +class SpecConvertOracleTest { + + /** RefRA of configuration 1 (spec_convert_probe.c {@code REF_RA}). */ + private static final double REF_RA = 1.0471975511965976; + + /** RefDec of configuration 1 (spec_convert_probe.c {@code REF_DEC}). */ + private static final double REF_DEC = 0.5235987755982988; + + /** The probe's {@code config( c, sys, is_to )}. */ + private static SpecFrame config(int c, String sys, boolean isTo) { + SpecFrame f = new SpecFrame(); + f.set("System=" + sys); + if (c == 1) { + f.set("RestFreq=" + (isTo ? "345.5" : "230.5") + ",StdOfRest=" + (isTo ? "Bary" : "LSRK") + + ",Epoch=2010.0"); + f.setRefPos(null, REF_RA, REF_DEC); + } + return f; + } + + /** + * The probe's DSBSpecFrame: the SideBand and AlignSideBand given to its constructor, then + * FREQ in GHz, RestFreq 230.5 GHz, DSBCentre 230 GHz and IF 4 GHz. + */ + private static DSBSpecFrame dsb(String sideBand, boolean align) { + DSBSpecFrame f = new DSBSpecFrame(); + f.set("SideBand=" + sideBand + (align ? ",AlignSideBand=1" : "")); + f.set("System=FREQ,Unit=GHz,RestFreq=230.5,DSBCentre=230.0,IF=4.0"); + return f; + } + + /** The probe's DSBSpecFrame in the lower sideband with System VRAD. */ + private static DSBSpecFrame dsbVrad() { + DSBSpecFrame v = dsb("LSB", false); + v.set("System=VRAD"); + return v; + } + + /** The probe's SpecFrame: VRAD with RestFreq 230.5 GHz. */ + private static SpecFrame specVrad() { + SpecFrame s = new SpecFrame(); + s.set("System=VRAD,RestFreq=230.5"); + return s; + } + + /** + * The probe's {@code dsb_found_in_cube}: a DSBSpecFrame template in VRAD found in a (sky, + * DSBSpecFrame) cube, and two cube positions transformed to it; null when it is not found. + */ + private static double[] foundInCube() { + CmpFrame cube = new CmpFrame(new SkyFrame(), dsb("LSB", false)); + DSBSpecFrame t = (DSBSpecFrame) dsbVrad().copy(); + t.set("MaxAxes=3"); + FrameSet fs = cube.findFrame(t, ""); + if (fs == null) { + return null; + } + double[][] out = fs.tranP(2, 3, new double[][] {{1.0, 2.0}, {0.5, 0.6}, {230.0, 345.0}}, true, 1); + return new double[] {out[0][0], out[0][1]}; + } + + /** + * The two points converted from {@code from} to {@code to}, as the probe's {@code emit} does: + * null when there is no conversion. + * + * @throws AstException when C reports an error + */ + private static double[] convert(Frame from, Frame to, double[] points) { + FrameSet fs = from.convert(to, ""); + if (fs == null) { + return null; + } + return fs.tran1(2, points, true); + } + + private static double[] pointsOf(JsonNode consts, String sys) { + JsonNode systems = consts.get("SYSTEMS"); + for (int i = 0; i < systems.size(); i++) { + if (systems.get(i).asText().equals(sys)) { + JsonNode p = consts.get("POINTS").get(i); + return new double[] {ProbeData.toDouble(p.get(0)), ProbeData.toDouble(p.get(1))}; + } + } + throw new IllegalArgumentException(sys); + } + + /** The probe's case {@code name}. */ + private static Outcome run(JsonNode consts, String name) { + try { + if (name.startsWith("c")) { + int colon1 = name.indexOf(':'); + int colon2 = name.indexOf(':', colon1 + 1); + int c = Integer.parseInt(name.substring(1, colon1)); + String from = name.substring(colon1 + 1, colon2); + String to = name.substring(colon2 + 1); + return Outcome.of(convert(config(c, from, false), config(c, to, true), pointsOf(consts, from))); + } + double[] freq = pointsOf(consts, "FREQ"); + switch (name) { + case "units_same_bad": + case "units_different_bad": { + SpecFrame a = new SpecFrame(); + a.set("System=FREQ"); + a.setC("Unit", "Jy"); + SpecFrame b = new SpecFrame(); + b.set("System=FREQ"); + b.setC("Unit", "units_same_bad".equals(name) ? "Jy" : "W"); + return Outcome.of(convert(a, b, freq)); + } + case "dsb_freq_to_vrad": + return Outcome.of(convert(dsb("LSB", false), dsbVrad(), freq)); + case "dsb_lsb_to_usb": + return Outcome.of(convert(dsb("LSB", false), dsb("USB", false), freq)); + case "dsb_lsb_to_usb_aligned": + return Outcome.of(convert(dsb("LSB", true), dsb("USB", true), freq)); + case "dsb_to_spec_vrad": + return Outcome.of(convert(dsb("LSB", false), specVrad(), freq)); + case "spec_vrad_to_dsb": + return Outcome.of(convert(specVrad(), dsb("LSB", false), pointsOf(consts, "VRAD"))); + case "dsb_found_in_cube": + return Outcome.of(foundInCube()); + default: + throw new IllegalArgumentException("no case " + name); + } + } catch (AstException e) { + return Outcome.error(e); + } + } + + /** A probe result: the two converted points, no conversion, or an error. */ + private static final class Outcome { + final double[] values; + final boolean failed; + final String text; + + private Outcome(double[] values, boolean failed, String text) { + this.values = values; + this.failed = failed; + this.text = text; + } + + static Outcome of(double[] values) { + return new Outcome(values, false, values == null ? "None" : Arrays.toString(values)); + } + + static Outcome error(AstException e) { + return new Outcome(null, true, "Err(" + e.getMessage() + ")"); + } + + static Outcome want(JsonNode w) { + if ("Err".equals(w.get("variant").asText())) { + return new Outcome(null, true, "Err"); + } + JsonNode v = w.get("value"); + if (v == null || v.isNull()) { + return of(null); + } + return of(new double[] {ProbeData.toDouble(v.get(0)), ProbeData.toDouble(v.get(1))}); + } + + boolean matches(Outcome want) { + if (failed || want.failed) { + return failed == want.failed; + } + if (values == null || want.values == null) { + return values == null && want.values == null; + } + return CValues.cValuesEq(values, want.values); + } + } + + @Test + void convertMatchesTheCLibrary() { + JsonNode consts = ProbeData.load("spec_convert"); + List failures = new ArrayList<>(); + int ran = 0; + for (JsonNode c : consts.get("CASES")) { + String name = c.get(0).asText(); + Outcome got = run(consts, name); + ran++; + Outcome want = Outcome.want(c.get(1)); + if (!got.matches(want)) { + failures.add(name + ": got " + got.text + ", C gives " + want.text); + } + } + assertEquals(208, ran, "the cases the C probe recorded"); + assertTrue(failures.isEmpty(), failures.size() + " cases differ from C:\n" + String.join("\n", failures)); + } + + /** + * Two Source rest frames are the same when their SourceVRF and SourceSys are, whether set or + * defaulted (specframe.c {@code EqualSor} uses the getters), so setting SourceVRF to its default + * changes nothing. + */ + @Test + void sourceRestFramesCompareThroughTheirDefaults() { + SpecFrame a = new SpecFrame(); + a.set("System=FREQ,StdOfRest=Source"); + SpecFrame b = (SpecFrame) a.copy(); + b.setC("SourceVRF", a.getC("SourceVRF")); + assertTrue(b.testSourceVRF()); + FrameSet fs = a.convert(b, ""); + assertNotNull(fs); + assertEquals( + "UnitMap", + fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) + .simplify() + .astClass()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecFluxCmpOracleTest.java b/src/test/java/uk/ac/starlink/ast/SpecFluxCmpOracleTest.java new file mode 100644 index 0000000..ccacbbb --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecFluxCmpOracleTest.java @@ -0,0 +1,90 @@ +package uk.ac.starlink.ast; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +import com.fasterxml.jackson.databind.JsonNode; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.Fixtures; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_specflux_cmp.rs}: the SpecFluxFrame methods C inherits + * from CmpFrame, checked against C ({@code oracle/specflux_cmp.json}, from {@code + * tools/oracle_fixtures/specflux_cmp_probe.c}): picking one axis keeps its SpecFrame or FluxFrame + * class, and a SpecFluxFrame template matches the components of a plain CmpFrame (specfluxframe.c + * {@code Match} and {@code SubFrame} hand both to CmpFrame's). The fixture {@code + * specfluxframe_swapped.native} is C's {@code astShow} of a SpecFluxFrame with its axes swapped. + */ +class SpecFluxCmpOracleTest { + + private static SpecFrame spec(String unit) { + SpecFrame s = new SpecFrame(); + s.set("System=FREQ"); + s.setUnit(1, unit); + return s; + } + + private static FluxFrame flux() { + FluxFrame f = new FluxFrame(1.4e9, null); + f.set("System=FLXDN"); + return f; + } + + /** Rust's {@code single_axis_picks_match_the_c_library}. */ + @Test + void singleAxisPicksMatchTheCLibrary() { + int run = 0; + for (JsonNode c : ProbeData.load("specflux_cmp").get("PICKS")) { + boolean swapped = c.get(0).asBoolean(); + int axis = c.get(1).asInt(); + SpecFluxFrame s = new SpecFluxFrame(spec("GHz"), flux()); + if (swapped) { + s.permAxes(new int[] {2, 1}); + } + Frame picked = s.pickAxes(1, new int[] {axis}, new Mapping[1]); + String what = "swapped " + swapped + " axis " + axis; + assertEquals(c.get(2).asText(), picked.astClass(), what); + assertEquals(c.get(3).asText(), picked.getLabel(1), what); + assertEquals(c.get(4).asText(), picked.getUnit(1), what); + run++; + } + assertEquals(4, run); + } + + /** Rust's {@code template_matches_a_plain_cmpframe_as_c_does}. */ + @Test + void templateMatchesAPlainCmpFrameAsCDoes() { + JsonNode found = ProbeData.load("specflux_cmp").get("FOUND"); + CmpFrame target = new CmpFrame(spec("GHz"), flux()); + SpecFluxFrame template = new SpecFluxFrame(spec("MHz"), flux()); + FrameSet fs = target.findFrame(template, ""); + assertNotNull(fs); + assertEquals(found.get(0).asText(), fs.getFrame(FrameSet.AST__CURRENT).astClass()); + double[][] out = fs.tranP(1, 2, new double[][] {{1.4}, {1.0e-26}}, true, 2); + assertEquals(ProbeData.toDouble(found.get(1).get(0)), out[0][0]); + assertEquals(ProbeData.toDouble(found.get(1).get(1)), out[1][0]); + } + + /** + * Rust's {@code native_dump_matches_the_c_library}: a SpecFluxFrame is written as the CmpFrame + * it is in C, with its axis permutation, components and {@code IsA CmpFrame} marker, and reads + * back to the same Frame. + */ + @Test + void nativeDumpMatchesTheCLibrary() { + SpecFluxFrame s = new SpecFluxFrame(spec("GHz"), flux()); + s.setTitle("MyT"); + s.permAxes(new int[] {2, 1}); + String text = ChannelText.dump(s); + assertEquals(Fixtures.read("specfluxframe_swapped.native"), text); + SpecFluxFrame back = assertInstanceOf(SpecFluxFrame.class, ChannelText.read(text)); + assertEquals("MyT", back.getTitle()); + for (int axis = 1; axis <= 2; axis++) { + assertEquals(s.getLabel(axis), back.getLabel(axis)); + assertEquals(s.getUnit(axis), back.getUnit(axis)); + } + assertEquals(text, ChannelText.dump(back)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecFluxFrameTest.java b/src/test/java/uk/ac/starlink/ast/SpecFluxFrameTest.java new file mode 100644 index 0000000..f82d026 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecFluxFrameTest.java @@ -0,0 +1,794 @@ +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.assertNotSame; +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 Rust {@code tests/test_specflux.rs} (ported from C's {@code + * ast_tester/testspecflux.c}), of the SpecFluxFrame tests of Rust {@code tests/test_fluxframe.rs} + * and of the unit tests of Rust {@code frames/specfluxframe.rs}, with further tests of the + * defaults, conversions, matching and dumps. + * + *

    A conversion between two SpecFluxFrames whose SpecFrames and FluxFrames are not each equal + * (C's {@code astEqual}) is built by C's {@code MakeSFMapping} with a RateMap, a MathMap and a + * TranMap ({@code MakeMapF} and {@code MakeMapI}, specfluxframe.c), classes this library does not + * have; such a conversion throws, naming the first absent class C builds. That is RateMap, built + * by {@code MakeMapF}, unless the comparison of the FluxFrames first needs a MathMap for + * logarithmic units ({@code astUnitMapper} in fluxframe.c {@code MakeFluxMapping}). Each such test + * gives C's converted value in its Javadoc. Equal components convert through a UnitMap, and + * SpecFluxFrames whose SpecFrames do not convert do not convert at all; both work here as in C. + * + *

    The expected values are C's: testspecflux.c's, and those of a probe built against the pinned + * C library that makes SpecFluxFrames with {@code astSpecFluxFrame( astSpecFrame( ... ), + * astFluxFrame( specval, NULL, ... ), "" )} and prints {@code astGetC}, {@code astFormat}, {@code + * astUnformat}, {@code astDistance}, the class of the simplified Mapping {@code astConvert}, {@code + * astFindFrame} or {@code astPickAxes} gives with the values it transforms, and {@code astShow}. + * C's {@code astEqual} is not part of this library: where C or Rust compare SpecFluxFrames, the + * test checks the conversion C's {@code Equal} (frame.c) makes, which must simplify to a UnitMap. + * Rust tests that call {@code match_template} and {@code sub_frame} call the package-private + * {@link Frame#match} and {@link Frame#subFrame}; Rust's {@code pick_axes_snapshot} is {@link + * Frame#pickAxes} here, whose classes are C's. + */ +class SpecFluxFrameTest { + + /** The SpecFrame of testspecflux.c, frequency in GHz. */ + private static SpecFrame ghz() { + SpecFrame sf = new SpecFrame(); + sf.set("system=freq,unit=GHz"); + return sf; + } + + /** {@code astFluxFrame( specval, specfrm, settings )}. */ + private static FluxFrame flux(double specval, SpecFrame specfrm, String settings) { + FluxFrame ff = new FluxFrame(specval, specfrm); + if (!settings.isEmpty()) { + ff.set(settings); + } + return ff; + } + + /** The probe's SpecFluxFrame: a new SpecFrame with {@code sfSettings} and a FluxFrame. */ + private static SpecFluxFrame sff(String sfSettings, double dsv, String ffSettings) { + SpecFrame sf = new SpecFrame(); + sf.set(sfSettings); + return new SpecFluxFrame(sf, flux(dsv, null, ffSettings)); + } + + /** A SpecFluxFrame of a frequency SpecFrame and a FLXDN FluxFrame, all defaults. */ + private static SpecFluxFrame plain() { + return sff("System=FREQ", AstObject.AST__BAD, "System=FLXDN"); + } + + /** The simplified Mapping {@code astConvert} gives from {@code from} to {@code to}, or null. */ + private static Mapping conversion(Frame from, Frame to) { + FrameSet fs = from.convert(to, ""); + return fs == null + ? null + : fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT).simplify(); + } + + /** One point transformed by {@code map} (a FrameSet's base-to-current Mapping, for a FrameSet). */ + private static double[] tran2(Mapping map, double x, double y, boolean forward) { + double[][] out = map.tranP(1, 2, new double[][] {{x}, {y}}, forward, 2); + return new double[] {out[0][0], out[1][0]}; + } + + /** Asserts that converting {@code from} to {@code to} throws, naming {@code cls} as needed. */ + private static void assertNeeds(String cls, Frame from, Frame to, String what) { + UnsupportedOperationException e = + assertThrows(UnsupportedOperationException.class, () -> from.convert(to, ""), what); + assertTrue(e.getMessage().endsWith("needs " + cls), what + ": " + e.getMessage()); + } + + // ------------------------------------------------------------------ + // testspecflux.c (test_specflux.rs) + // ------------------------------------------------------------------ + + /** The SpecFluxFrame most of testspecflux.c's checks start from. */ + private static SpecFluxFrame jansky(SpecFrame sf) { + return new SpecFluxFrame(sf, flux(123.0, sf, "Unit=Jy")); + } + + /** testspecflux.c Errors 0 to 6 and CheckDump 1 ({@code spec_val_defaults_to_the_flux_frame_value}). */ + @Test + void specValDefaultsToTheFluxFrameValue() { + SpecFluxFrame sff = jansky(ghz()); + assertEquals("SpecFluxFrame", sff.getC("Class"), "Error 0"); + assertEquals(123.0, sff.getD("specval"), "Error 1"); + assertFalse(sff.test("specval"), "Error 2"); + sff.setD("specval", 333.3); + assertEquals(333.3, sff.getD("specval"), "Error 3"); + assertTrue(sff.test("specval"), "Error 4"); + sff.clear("specval"); + assertEquals(123.0, sff.getD("specval"), "Error 5"); + assertFalse(sff.test("specval"), "Error 6"); + + AstObject read = ChannelText.read(ChannelText.dump(sff)); + assertInstanceOf(SpecFluxFrame.class, read, "CheckDump 1"); + assertEquals(sff.getD("specval"), read.getD("specval"), "CheckDump 1: Object has changed"); + } + + /** + * testspecflux.c Errors 6B, 6C, 7 and 8 ({@code flux_density_converts_to_per_wavelength}). C + * converts (2, 1) to (2, 1.33425638e-26) within 1e-32 (Errors 9 and 10). + */ + @Test + void fluxDensityToPerWavelengthNeedsRateMap() { + SpecFrame sf = ghz(); + SpecFluxFrame sff = jansky(sf); + FluxFrame ff2 = flux(123.1, sf, "System=flxdnw"); + assertEquals("W/m^2/Angstrom", ff2.getC("Unit"), "Error 6B"); + assertEquals("FLXDNW", ff2.getC("System"), "Error 6C"); + SpecFluxFrame sff2 = new SpecFluxFrame(sf, ff2); + assertEquals("SpecFluxFrame", sff2.getC("Class"), "Error 7"); + assertNeeds("RateMap", sff, sff2, "Error 8"); + } + + /** + * testspecflux.c Errors 11 and 14 ({@code conversion_follows_permuted_axes}). C converts with + * the flux on the first result axis (Errors 12, 13), and then from permuted axes too (Errors + * 15, 16). + */ + @Test + void permutedAxesNeedRateMap() { + SpecFrame sf = ghz(); + SpecFluxFrame sff = jansky(sf); + SpecFluxFrame sff2 = new SpecFluxFrame(sf, flux(123.1, sf, "System=flxdnw")); + sff2.permAxes(new int[] {2, 1}); + assertNeeds("RateMap", sff, sff2, "Error 11"); + sff.permAxes(new int[] {2, 1}); + assertNeeds("RateMap", sff, sff2, "Error 14"); + } + + /** + * testspecflux.c Errors 17 and 18 ({@code logarithmic_flux_units_convert}). C converts (2, 1) + * to (2, -24.8747607) and back (Errors 19 to 22). Comparing the FluxFrames converts Jy to + * {@code log(W/m2/nm)}, which needs a MathMap before {@code MakeMapF} is reached. + */ + @Test + void logarithmicFluxUnitsNeedMathMap() { + SpecFrame sf = ghz(); + SpecFluxFrame csff = (SpecFluxFrame) jansky(sf).copy(); + FluxFrame ff2 = flux(AstObject.AST__BAD, null, "Unit=log(W/m2/nm)"); + assertEquals("FLXDNW", ff2.getC("System"), "Error 17"); + SpecFluxFrame sff2 = new SpecFluxFrame(sf, ff2); + assertNeeds("MathMap", csff, sff2, "Error 18"); + } + + /** + * testspecflux.c Errors 23 to 25 ({@code surface_brightness_converts}). C converts (2, 1) to + * (2, -21.3585154) and back (Errors 26 to 29). + */ + @Test + void surfaceBrightnessNeedsMathMap() { + FluxFrame ff2 = flux(AstObject.AST__BAD, null, "Unit=log(W/m2/nm/sr)"); + assertEquals("SFCBRW", ff2.getC("System"), "Error 23"); + SpecFluxFrame sff2 = new SpecFluxFrame(ghz(), ff2); + SpecFrame sf = ghz(); + FluxFrame ff = flux(123.0, sf, "Unit=Jy/deg**2"); + assertEquals("SFCBR", ff.getC("System"), "Error 24"); + SpecFluxFrame sff = new SpecFluxFrame(sf, ff); + assertNeeds("MathMap", sff, sff2, "Error 25"); + } + + /** + * testspecflux.c Errors 30 to 32 ({@code equal_when_and_only_when_the_components_are}): C's + * {@code Equal} converts the second Frame to the first. SpecFluxFrames sharing equal + * components, and a copy, convert through a UnitMap ({@code astEqual} 1); with a FLXDNW + * FluxFrame C's conversion is a CmpMap ({@code astEqual} 0), which needs a RateMap here. + */ + @Test + void equalWhenAndOnlyWhenTheComponentsAre() { + SpecFrame esf = new SpecFrame(); + esf.set("system=freq"); + FluxFrame eff = flux(AstObject.AST__BAD, null, "system=flxdn"); + FluxFrame eff2 = flux(AstObject.AST__BAD, null, "system=flxdnw"); + SpecFluxFrame ea = new SpecFluxFrame(esf, eff); + SpecFluxFrame eb = new SpecFluxFrame(esf, eff); + SpecFluxFrame ec = (SpecFluxFrame) ea.copy(); + SpecFluxFrame ed = new SpecFluxFrame(esf, eff2); + assertInstanceOf(UnitMap.class, conversion(eb, ea), "Error 30"); + assertInstanceOf(UnitMap.class, conversion(ec, ea), "Error 31"); + assertNeeds("RateMap", ed, ea, "Error 32"); + } + + // ------------------------------------------------------------------ + // test_fluxframe.rs + // ------------------------------------------------------------------ + + /** Rust's {@code test_specfluxframe_new}. */ + @Test + void newHasTwoAxes() { + assertEquals(2, plain().getNaxes()); + } + + /** Rust's {@code test_specfluxframe_unformat_base_contract}: each axis is read by its component. */ + @Test + void unformatBaseContract() { + SpecFluxFrame s = plain(); + Object[][] cases = { + {" 12.5 ", 12.5, 8}, + {"", AstObject.AST__BAD, 5}, + {" < b a d > ", AstObject.AST__BAD, 11}, + {"12.5xyz", 12.5, 4}, + {"xyz", 0.0, 0}, + }; + for (int axis = 1; axis <= 2; axis++) { + for (Object[] c : cases) { + double[] v = {0.0}; + assertEquals((int) c[2], s.unformat(axis, (String) c[0], v), axis + " " + c[0]); + assertEquals((double) c[1], v[0], axis + " " + c[0]); + } + } + } + + /** Rust's {@code test_specfluxframe_components}. */ + @Test + void components() { + SpecFrame sf = new SpecFrame(); + sf.set("System=WAVE"); + FluxFrame ff = flux(AstObject.AST__BAD, null, "System=SFCBR"); + SpecFluxFrame s = new SpecFluxFrame(sf, ff); + Frame[] parts = s.decompose(); + assertSame(sf, parts[0]); + assertSame(ff, parts[1]); + assertEquals("WAVE", s.getC("System(1)")); + assertEquals("SFCBR", s.getC("System(2)")); + } + + /** + * Rust's {@code test_specfluxframe_component_mutation}: the SpecFluxFrame holds the Frames it + * is given, as C's {@code astSpecFluxFrame} clones them, so a change to one is a change to it. + */ + @Test + void componentMutation() { + SpecFrame sf = new SpecFrame(); + sf.set("System=FREQ"); + FluxFrame ff = flux(AstObject.AST__BAD, null, "System=FLXDN"); + SpecFluxFrame s = new SpecFluxFrame(sf, ff); + ff.setSystem("SFCBR"); + assertEquals("SFCBR", s.getC("System(2)")); + sf.setSystem("WAVE"); + assertEquals("WAVE", s.getC("System(1)")); + assertEquals("Surface brightness versus Wavelength", s.getTitle()); + } + + /** A copy holds copies of the components, as C's CmpFrame {@code Copy} makes them. */ + @Test + void copyIsIndependent() { + SpecFrame sf = new SpecFrame(); + sf.set("System=FREQ"); + FluxFrame ff = flux(AstObject.AST__BAD, null, "System=FLXDN"); + SpecFluxFrame s = new SpecFluxFrame(sf, ff); + SpecFluxFrame copy = (SpecFluxFrame) s.copy(); + assertInstanceOf(SpecFrame.class, copy.decompose()[0]); + assertInstanceOf(FluxFrame.class, copy.decompose()[1]); + ff.setSystem("SFCBR"); + assertEquals("FLXDN", copy.getC("System(2)")); + copy.setC("System(1)", "WAVE"); + assertEquals("FREQ", sf.getSystem()); + } + + /** Rust's {@code test_specfluxframe_format_axes}. */ + @Test + void formatAxes() { + SpecFluxFrame s = plain(); + assertEquals("1.4E+09", s.format(1, 1.4e9)); + assertEquals("1E-26", s.format(2, 1.0e-26)); + AstException e = assertThrows(AstException.class, () -> s.format(3, 1.0)); + assertEquals(AstException.AST__AXIIN, e.getStatus()); + assertEquals( + "astFormat(SpecFluxFrame): Axis index (3) invalid - it should be in the range 1 to 2.", e.getMsgText()); + } + + /** Rust's {@code test_specfluxframe_distance}. */ + @Test + void distance() { + assertEquals(5.0, plain().distance(new double[] {0.0, 0.0}, new double[] {3.0, 4.0})); + } + + /** Rust's {@code test_specfluxframe_equal}: equal components convert through a UnitMap. */ + @Test + void equalComponentsConvertThroughAUnitMap() { + assertInstanceOf(UnitMap.class, conversion(plain(), plain())); + } + + /** + * Rust's {@code test_specfluxframe_not_equal_different_spec} and {@code + * test_specfluxframe_convert_different_spec_system_converts}: C converts a frequency to a + * wavelength SpecFluxFrame through a CmpMap, (1.4e9, 1e-26) to (2.1413747000000005, 1e-26). + */ + @Test + void differentSpectralSystemsNeedRateMap() { + assertNeeds("RateMap", plain(), sff("System=WAVE", AstObject.AST__BAD, "System=FLXDN"), "FREQ to WAVE"); + } + + /** Rust's {@code test_specfluxframe_convert_same}. */ + @Test + void convertSame() { + SpecFluxFrame a = plain(); + Mapping map = conversion(a, plain()); + assertInstanceOf(UnitMap.class, map); + assertArrayEquals(new double[] {1.4e9, 1.0e-26}, tran2(map, 1.4e9, 1.0e-26, true)); + assertInstanceOf(UnitMap.class, conversion(a, (Frame) a.copy())); + } + + /** Rust's {@code test_specfluxframe_serialisation_roundtrip}. */ + @Test + void serialisationRoundTrip() { + SpecFluxFrame s = plain(); + String text = ChannelText.dump(s); + assertTrue(text.contains("SpecFluxFrame")); + assertTrue(text.contains("SpecFrame")); + assertTrue(text.contains("FluxFrame")); + SpecFluxFrame back = assertInstanceOf(SpecFluxFrame.class, ChannelText.read(text)); + assertEquals(text, ChannelText.dump(back)); + assertEquals(s, back); + assertInstanceOf(UnitMap.class, conversion(back, s)); + } + + private static final String DUMP_ATTRS = ChannelText.text( + " Begin SpecFluxFrame \t# Compound spectral/flux coordinate system description", + "# Title = \"Surface brightness (per wavelength) versus Wavelength\" \t# Title of coordinate system", + "# Naxes = 2 \t# Number of coordinate axes", + "# Domain = \"SPECTRUM-FLUX\" \t# Coordinate system domain", + "# Lbl1 = \"Wavelength\" \t# Label for axis 1", + "# Lbl2 = \"Surface brightness (per wavelength)\" \t# Label for axis 2", + "# Uni1 = \"Angstrom\" \t# Units for axis 1", + "# Uni2 = \"W/m^2/Angstrom/arcmin**2\" \t# Units for axis 2", + " IsA Frame \t# Coordinate system description", + " FrameA = \t# First component Frame", + " Begin SpecFrame \t# Description of spectral coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + " System = \"WAVE\" \t# Coordinate system type", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + " RstFrq = 4.5700000000000001e+23 \t# Rest frequency (Hz)", + " End SpecFrame", + " FrameB = \t# Second component Frame", + " Begin FluxFrame \t# Description of flux values", + " Naxes = 1 \t# Number of coordinate axes", + " System = \"SFCBRW\" \t# Coordinate system type", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + " SpcVl = 457000000000000 \t# Spectral position", + " End FluxFrame", + " IsA CmpFrame \t# Compound coordinate system description", + " End SpecFluxFrame"); + + /** + * Rust's {@code test_specfluxframe_serialisation_with_attributes}, with the RestFreq set as C's + * attribute string sets it (in GHz). + */ + @Test + void serialisationWithAttributes() { + SpecFluxFrame s = sff("System=WAVE,RestFreq=4.57e14", AstObject.AST__BAD, "System=SFCBRW,SpecVal=4.57e14"); + assertEquals(DUMP_ATTRS, ChannelText.dump(s)); + SpecFluxFrame back = assertInstanceOf(SpecFluxFrame.class, ChannelText.read(DUMP_ATTRS)); + assertEquals(DUMP_ATTRS, ChannelText.dump(back)); + assertEquals(s, back); + assertInstanceOf(UnitMap.class, conversion(back, s)); + } + + /** + * Rust's {@code test_specflux_jy_to_fluxdenw} and {@code test_specflux_inverse}: as + * testspecflux.c Errors 8 to 10, with the SpecVal set rather than defaulted. + */ + @Test + void jyToFluxDenWNeedsRateMap() { + SpecFrame sf = ghz(); + FluxFrame ff = flux(AstObject.AST__BAD, sf, "System=FLXDN,Unit=Jy,SpecVal=123.0"); + SpecFluxFrame sff = new SpecFluxFrame(sf, ff); + FluxFrame ff2 = flux(AstObject.AST__BAD, sf, "System=FLXDNW,SpecVal=123.1"); + SpecFluxFrame sff2 = new SpecFluxFrame(sf, ff2); + assertNeeds("RateMap", sff, sff2, "Jy to FLXDNW"); + } + + /** Rust's {@code test_specflux_log_units}: as testspecflux.c Errors 18 to 20. */ + @Test + void logUnitsNeedMathMap() { + SpecFrame sf = ghz(); + SpecFluxFrame sff = new SpecFluxFrame(sf, flux(AstObject.AST__BAD, sf, "System=FLXDN,Unit=Jy,SpecVal=123.0")); + SpecFluxFrame sff2 = new SpecFluxFrame(sf, flux(AstObject.AST__BAD, sf, "System=FLXDNW,Unit=log(W/m2/nm)")); + assertNeeds("MathMap", sff, sff2, "Jy to log(W/m2/nm)"); + } + + /** Rust's {@code test_specflux_surface_brightness}: as testspecflux.c Errors 25 to 27. */ + @Test + void surfaceBrightnessLogUnitsNeedMathMap() { + SpecFrame sf = ghz(); + SpecFluxFrame sff = + new SpecFluxFrame(sf, flux(AstObject.AST__BAD, sf, "System=SFCBR,Unit=Jy/deg**2,SpecVal=123.0")); + SpecFluxFrame sff2 = new SpecFluxFrame(sf, flux(AstObject.AST__BAD, sf, "System=SFCBRW,Unit=log(W/m2/nm/sr)")); + assertNeeds("MathMap", sff, sff2, "Jy/deg**2 to log(W/m2/nm/sr)"); + } + + // ------------------------------------------------------------------ + // frames/specfluxframe.rs unit tests + // ------------------------------------------------------------------ + + /** Rust's {@code match_template_specflux_self}. */ + @Test + void matchSelf() { + FrameFinder.MatchResult m = plain().match(plain(), false); + assertNotNull(m); + assertArrayEquals(new int[] {0, 1}, m.templateAxes); + assertArrayEquals(new int[] {0, 1}, m.targetAxes); + assertEquals(2, m.result.getNaxes()); + assertInstanceOf(SpecFluxFrame.class, m.result); + assertInstanceOf(UnitMap.class, m.map.simplify()); + } + + /** Rust's {@code match_template_specflux_against_basicframe_fails}: CmpFrame's Match finds none. */ + @Test + void matchAgainstAPlainFrameFails() { + assertNull(plain().match(new Frame(2), false)); + assertNull(new Frame(2).findFrame(plain(), "")); + } + + /** Rust's {@code match_template_specflux_swap_blocked_when_permute_false}. */ + @Test + void swapBlockedWhenPermuteFalse() { + SpecFluxFrame template = plain(); + template.setPermute(false); + SpecFluxFrame target = plain(); + target.permAxes(new int[] {2, 1}); + assertNull(template.match(target, false)); + assertNull(target.findFrame(template, "")); + } + + /** + * Rust's {@code match_template_specflux_swap_allowed_when_permute_true}: the result takes the + * template's axis order, so C's Mapping is a PermMap and (1.4, 1e-26) becomes (1e-26, 1.4). + */ + @Test + void swapAllowedWhenPermuteTrue() { + SpecFluxFrame template = plain(); + template.setPermute(true); + SpecFluxFrame target = plain(); + target.permAxes(new int[] {2, 1}); + FrameFinder.MatchResult m = template.match(target, false); + assertNotNull(m); + assertArrayEquals(new int[] {0, 1}, m.templateAxes); + assertArrayEquals(new int[] {1, 0}, m.targetAxes); + FrameSet fs = target.findFrame(template, ""); + assertNotNull(fs); + Frame cur = fs.getFrame(FrameSet.AST__CURRENT); + assertInstanceOf(SpecFluxFrame.class, cur); + assertInstanceOf( + PermMap.class, + fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT).simplify()); + assertArrayEquals(new double[] {1.0e-26, 1.4}, tran2(fs, 1.4, 1.0e-26, true)); + assertEquals("Frequency", cur.getLabel(1)); + } + + /** With PreserveAxes set, the result keeps the target's axis order and the Mapping is a UnitMap. */ + @Test + void preserveAxesKeepsTheTargetOrder() { + SpecFluxFrame template = plain(); + template.setPreserveAxes(true); + SpecFluxFrame target = plain(); + target.permAxes(new int[] {2, 1}); + FrameSet fs = target.findFrame(template, ""); + assertNotNull(fs); + Frame cur = fs.getFrame(FrameSet.AST__CURRENT); + assertInstanceOf(SpecFluxFrame.class, cur); + assertEquals("Flux density", cur.getLabel(1)); + assertInstanceOf( + UnitMap.class, + fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT).simplify()); + assertArrayEquals(new double[] {1.4, 1.0e-26}, tran2(fs, 1.4, 1.0e-26, true)); + } + + /** Rust's {@code sub_frame_specflux_to_specflux_identity}. */ + @Test + void subFrameIdentity() { + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + assertTrue(plain().subFrame(plain(), 2, new int[] {0, 1}, new int[] {0, 1}, map, result)); + assertEquals(2, map[0].getNin()); + assertEquals(2, map[0].getNout()); + SpecFluxFrame r = assertInstanceOf(SpecFluxFrame.class, result[0]); + assertArrayEquals(new int[] {0, 1}, r.getPerm()); + } + + /** Rust's {@code sub_frame_specflux_axis_swap}. */ + @Test + void subFrameAxisSwap() { + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + assertTrue(plain().subFrame(plain(), 2, new int[] {1, 0}, new int[] {0, 1}, map, result)); + SpecFluxFrame r = assertInstanceOf(SpecFluxFrame.class, result[0]); + assertArrayEquals(new int[] {1, 0}, r.getPerm()); + assertInstanceOf(PermMap.class, map[0].simplify()); + } + + /** + * Rust's {@code pick_axes_snapshot_full_returns_specflux} and {@code + * pick_axes_snapshot_partial_returns_basicframe}: C's {@code astPickAxes} picks through + * CmpFrame's {@code SubFrame}, giving a CmpFrame for both axes, in either order, and the + * component's class for one. + */ + @Test + void pickAxesGivesCsClasses() { + SpecFluxFrame s = sff("System=FREQ,Unit=GHz", 1.4e9, "System=FLXDN"); + Mapping[] map = new Mapping[1]; + Frame f = s.pickAxes(2, new int[] {1, 2}, map); + assertEquals("CmpFrame", f.astClass()); + assertInstanceOf(UnitMap.class, map[0].simplify()); + f = s.pickAxes(2, new int[] {2, 1}, map); + assertEquals("CmpFrame", f.astClass()); + assertInstanceOf(PermMap.class, map[0].simplify()); + f = s.pickAxes(1, new int[] {1}, map); + assertEquals("SpecFrame", f.astClass()); + assertInstanceOf(PermMap.class, map[0].simplify()); + } + + // ------------------------------------------------------------------ + // Defaults, Title and dumps + // ------------------------------------------------------------------ + + private static final String DUMP_DEFAULT = ChannelText.text( + " Begin SpecFluxFrame \t# Compound spectral/flux coordinate system description", + "# Title = \"Flux density versus Frequency\" \t# Title of coordinate system", + "# Naxes = 2 \t# Number of coordinate axes", + "# Domain = \"SPECTRUM-FLUX\" \t# Coordinate system domain", + "# Lbl1 = \"Frequency\" \t# Label for axis 1", + "# Lbl2 = \"Flux density\" \t# Label for axis 2", + "# Uni1 = \"GHz\" \t# Units for axis 1", + "# Uni2 = \"W/m^2/Hz\" \t# Units for axis 2", + " IsA Frame \t# Coordinate system description", + " FrameA = \t# First component Frame", + " Begin SpecFrame \t# Description of spectral coordinate system", + " Naxes = 1 \t# Number of coordinate axes", + " System = \"FREQ\" \t# Coordinate system type", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " Unit = \"GHz\" \t# Axis units", + " End Axis", + " IsA Frame \t# Coordinate system description", + " UFreq = \"GHz\" \t# Preferred units for frequency", + " End SpecFrame", + " FrameB = \t# Second component Frame", + " Begin FluxFrame \t# Description of flux values", + " Naxes = 1 \t# Number of coordinate axes", + " System = \"FLXDN\" \t# Coordinate system type", + " Ax1 = \t# Axis number 1", + " Begin Axis \t# Coordinate axis", + " End Axis", + " IsA Frame \t# Coordinate system description", + " DfSpc = 1400000000 \t# Default spectral position", + " End FluxFrame", + " IsA CmpFrame \t# Compound coordinate system description", + " End SpecFluxFrame"); + + /** The defaults C gives, and C's dump, which reads back to the same SpecFluxFrame. */ + @Test + void defaultsAndDump() { + SpecFluxFrame s = sff("System=FREQ,Unit=GHz", 1.4e9, "System=FLXDN"); + assertEquals("Flux density versus Frequency", s.getTitle()); + assertEquals("SPECTRUM-FLUX", s.getDomain()); + assertEquals("Compound", s.getC("System")); + assertEquals("FREQ", s.getC("System(1)")); + assertEquals("FLXDN", s.getC("System(2)")); + assertEquals("Frequency", s.getC("Label(1)")); + assertEquals("Flux density", s.getC("Label(2)")); + assertEquals("GHz", s.getC("Unit(1)")); + assertEquals("W/m^2/Hz", s.getC("Unit(2)")); + assertEquals("1400000000", s.getC("SpecVal")); + assertEquals(DUMP_DEFAULT, ChannelText.dump(s)); + SpecFluxFrame back = assertInstanceOf(SpecFluxFrame.class, ChannelText.read(DUMP_DEFAULT)); + assertEquals(DUMP_DEFAULT, ChannelText.dump(back)); + assertEquals(s, back); + } + + /** + * The default Title is the FluxFrame's Label, its first letter made upper case, then {@code + * versus} and the SpecFrame's Label, whatever the axis order (specfluxframe.c {@code GetTitle}). + */ + @Test + void titleFromTheLabels() { + SpecFluxFrame s = + sff("System=WAVE,Label=wavelength in vacuo", AstObject.AST__BAD, "System=SFCBRW,Label=brightness"); + assertEquals("Brightness versus wavelength in vacuo", s.getTitle()); + s.setTitle("My title"); + assertEquals("My title", s.getTitle()); + s.clear("Title"); + s.permAxes(new int[] {2, 1}); + assertEquals("Brightness versus wavelength in vacuo", s.getTitle()); + } + + /** A dump whose FrameA is not a SpecFrame, or whose FrameB is not a FluxFrame, is refused. */ + @Test + void loaderRefusesOtherComponentClasses() { + String text = DUMP_DEFAULT + .replace(" FrameA = \t# First component Frame", " FrameX = \t# First") + .replace(" FrameB = \t# Second component Frame", " FrameA = \t# First component Frame") + .replace(" FrameX = \t# First", " FrameB = \t# Second component Frame"); + AstException e = assertThrows(AstException.class, () -> ChannelText.read(text)); + assertEquals(AstException.AST__LDERR, e.getStatus()); + } + + // ------------------------------------------------------------------ + // Conversions + // ------------------------------------------------------------------ + + /** + * Equal components in a different axis order convert through a PermMap (specfluxframe.c + * {@code SubFrame} around {@code MakeSFMapping}'s UnitMap), and through a UnitMap when both are + * swapped. + */ + @Test + void swappedEqualComponents() { + SpecFluxFrame s = plain(); + SpecFluxFrame u = (SpecFluxFrame) plain().copy(); + u.permAxes(new int[] {2, 1}); + Mapping map = conversion(s, u); + assertInstanceOf(PermMap.class, map); + assertArrayEquals(new double[] {1.0e-26, 1.4e9}, tran2(map, 1.4e9, 1.0e-26, true)); + map = conversion(u, s); + assertInstanceOf(PermMap.class, map); + assertArrayEquals(new double[] {1.4e9, 1.0e-26}, tran2(map, 1.0e-26, 1.4e9, true)); + map = conversion(u, (Frame) u.copy()); + assertInstanceOf(UnitMap.class, map); + } + + /** + * SpecFluxFrames whose SpecFrames have different Domains do not convert: C's {@code MakeMapF} + * finds no conversion between the standardised SpecFrames, so no RateMap is needed. + */ + @Test + void spectralDomainsThatDifferDoNotConvert() { + SpecFluxFrame s = sff("System=FREQ,Domain=A", AstObject.AST__BAD, "System=FLXDN"); + SpecFluxFrame t = sff("System=FREQ,Domain=B", AstObject.AST__BAD, "System=FLXDN"); + assertNull(s.convert(t, "")); + assertEquals("A-FLUX", s.getDomain()); + assertEquals("B-FLUX", t.getDomain()); + } + + /** + * Every other change goes through C's {@code MakeMapF}. C's values: Jy to mJy gives (2, + * 1000.0000000000001), GHz to MHz (1999.9999999999998, 1), and FluxFrames in different + * Domains (1.4e9, 1e-26), each through a CmpMap. + */ + @Test + void otherChangesNeedRateMap() { + SpecFluxFrame s = sff("System=FREQ,Unit=GHz", 1.4e9, "System=FLXDN,Unit=Jy"); + assertNeeds("RateMap", s, sff("System=FREQ,Unit=GHz", 1.4e9, "System=FLXDN,Unit=mJy"), "Jy to mJy"); + assertNeeds("RateMap", s, sff("System=FREQ,Unit=MHz", 1.4e9, "System=FLXDN,Unit=Jy"), "GHz to MHz"); + assertNeeds( + "RateMap", + sff("System=FREQ", AstObject.AST__BAD, "System=FLXDN,Domain=A"), + sff("System=FREQ", AstObject.AST__BAD, "System=FLXDN,Domain=B"), + "flux Domains"); + } + + /** + * Comparing FluxFrames in logarithmic units needs a MathMap. C converts (2, 1) Jy to (2, 0) + * {@code log(Jy)}, and (2, 0) back to (2, 1). + */ + @Test + void logarithmicUnitsNeedMathMap() { + SpecFluxFrame s = sff("System=FREQ,Unit=GHz", 1.4e9, "System=FLXDN,Unit=Jy"); + SpecFluxFrame t = sff("System=FREQ,Unit=GHz", 1.4e9, "System=FLXDN,Unit=log(Jy)"); + assertNeeds("MathMap", s, t, "Jy to log(Jy)"); + assertNeeds("MathMap", t, s, "log(Jy) to Jy"); + } + + /** jniast's constructor. */ + @Test + void jniastConstructor() { + SpecFrame sf = new SpecFrame(); + FluxFrame ff = new FluxFrame(); + SpecFluxFrame s = new SpecFluxFrame(sf, ff); + assertEquals("SpecFluxFrame", s.getC("Class")); + CmpFrame cmp = s; + assertEquals(2, cmp.getNaxes()); + } + + // ------------------------------------------------------------------ + // Casting between CmpFrames and SpecFluxFrames (cmpframe.c Cast) + // ------------------------------------------------------------------ + + /** + * cmpframe.c {@code Cast} makes a copy of a CmpFrame as an instance of any class of the + * CmpFrame family ({@code astCastCopy}): a SpecFluxFrame cast into a CmpFrame is a plain + * CmpFrame holding copies of its components, and a CmpFrame cast into a SpecFluxFrame is a + * SpecFluxFrame holding copies of the CmpFrame's, whatever their classes. + */ + @Test + void castWithinTheCmpFrameFamilyCopiesTheComponents() { + SpecFrame sf = new SpecFrame(); + FluxFrame ff = new FluxFrame(); + SpecFluxFrame s = new SpecFluxFrame(sf, ff); + s.setTitle("A title"); + Frame asCmp = s.cast(new CmpFrame(new Frame(1), new Frame(1))); + assertEquals(CmpFrame.class, asCmp.getClass()); + assertEquals("A title", asCmp.getTitle()); + Frame[] parts = ((CmpFrame) asCmp).decompose(); + assertInstanceOf(SpecFrame.class, parts[0]); + assertInstanceOf(FluxFrame.class, parts[1]); + assertNotSame(sf, parts[0]); + assertNotSame(ff, parts[1]); + + Frame a = new Frame(1); + Frame b = new Frame(1); + CmpFrame cmp = new CmpFrame(a, b); + cmp.permAxes(new int[] {2, 1}); + Frame asSff = cmp.cast(s); + assertEquals(SpecFluxFrame.class, asSff.getClass()); + Frame[] sffParts = ((CmpFrame) asSff).decompose(); + assertEquals(Frame.class, sffParts[0].getClass()); + assertNotSame(a, sffParts[0]); + assertNotSame(b, sffParts[1]); + assertEquals(2, asSff.validateAxis(1, true, "test")); + } + + /** + * A SpecFluxFrame and a CmpFrame that do not match: C casts the SpecFluxFrame template into a + * plain CmpFrame, which matches no better, and finds no conversion either way. + */ + @Test + void unmatchedCmpFramesDoNotConvert() { + SpecFluxFrame s = new SpecFluxFrame(new SpecFrame(), new FluxFrame()); + CmpFrame cube = new CmpFrame(new SkyFrame(), new SpecFrame()); + assertNull(cube.convert(s, ""), "cube to SpecFluxFrame"); + assertNull(s.convert(cube, ""), "SpecFluxFrame to cube"); + CmpFrame sky1 = new CmpFrame(new SkyFrame(), new Frame(1)); + assertNull(s.convert(sky1, ""), "SpecFluxFrame to sky1"); + assertNull(sky1.convert(s, ""), "sky1 to SpecFluxFrame"); + FrameSet fs = new FrameSet(new Frame(3)); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(3), cube); + assertNull(fs.findFrame(s, ""), "findFrame in a cube"); + } + + /** + * A FluxFrame whose System differs from a SpecFluxFrame's: the CmpFrame C's {@code PartMatch} + * gives is cast into a SpecFluxFrame, whose conversion {@code MakeSFMapping} builds with a + * RateMap. C converts both ways; from the SpecFluxFrame, (5000, 2) gives 239833965686.78632. + */ + @Test + void fluxFrameToSpecFluxFrameNeedsRateMap() { + FluxFrame fw = flux(AstObject.AST__BAD, new SpecFrame(), "System=FLXDNW"); + SpecFluxFrame s = new SpecFluxFrame(new SpecFrame(), flux(AstObject.AST__BAD, new SpecFrame(), "")); + assertNeeds("RateMap", fw, s, "FluxFrame to SpecFluxFrame"); + assertNeeds("RateMap", s, fw, "SpecFluxFrame to FluxFrame"); + } + + /** + * A SpecFrame in another Domain and a SpecFluxFrame whose SpecFrame has SpecOrigin 0: the cast + * reaches {@code MakeSFMapping}, whose standardised SpecFrame ({@code GetSpecFrame}) cannot + * re-express the origin in frequency, and C reports AST__ATSER both ways. With SpecOrigin + * unset C finds no conversion. + */ + @Test + void specFrameToSpecFluxFrameReachesMakeSFMapping() { + SpecFrame foo = new SpecFrame(); + foo.setDomain("FOO"); + SpecFrame origin = new SpecFrame(); + origin.set("SpecOrigin=0"); + SpecFluxFrame s = new SpecFluxFrame(origin, flux(AstObject.AST__BAD, new SpecFrame(), "")); + AstException e = assertThrows(AstException.class, () -> foo.convert(s, "")); + assertEquals(AstException.AST__ATSER, e.getStatus()); + e = assertThrows(AstException.class, () -> s.convert(foo, "")); + assertEquals(AstException.AST__ATSER, e.getStatus()); + + SpecFluxFrame plain = new SpecFluxFrame(new SpecFrame(), flux(AstObject.AST__BAD, new SpecFrame(), "")); + assertNull(foo.convert(plain, "")); + assertNull(plain.convert(foo, "")); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecFluxPrimaryOracleTest.java b/src/test/java/uk/ac/starlink/ast/SpecFluxPrimaryOracleTest.java new file mode 100644 index 0000000..4688625 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecFluxPrimaryOracleTest.java @@ -0,0 +1,107 @@ +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_specflux_primary.rs}: what a SpecFluxFrame inherits from + * CmpFrame, checked against C ({@code oracle/specflux_primary.json}, from {@code + * tools/oracle_fixtures/specflux_primary_probe.c}). A SpecFluxFrame's System is {@code Compound} + * (cmpframe.c {@code GetSystem}), and {@code PrimaryFrame} descends into its SpecFrame and + * FluxFrame, so a SpecFrame template finds the spectral axis of a SpecFluxFrame, alone or inside a + * CmpFrame (cmpframe.c {@code PrimaryFrame}). + */ +class SpecFluxPrimaryOracleTest { + + private static SpecFluxFrame specflux() { + SpecFrame sp = new SpecFrame(); + sp.set("System=FREQ"); + sp.setUnit(1, "GHz"); + return new SpecFluxFrame(sp, flux(0, null)); + } + + /** A FLXDN FluxFrame, with MaxAxes and Unit set if {@code maxAxes} is not 0. */ + private static FluxFrame flux(int maxAxes, String unit) { + FluxFrame f = new FluxFrame(1.4e9, null); + f.set("System=FLXDN"); + if (maxAxes != 0) { + f.setMaxAxes(maxAxes); + f.setUnit(1, unit); + } + return f; + } + + private static SpecFrame specTemplate(int maxAxes) { + SpecFrame t = new SpecFrame(); + t.set("System=WAVE"); + t.setUnit(1, "nm"); + t.setMaxAxes(maxAxes); + return t; + } + + /** The template's value for the probe's point, or null if the template finds nothing. */ + private static Double found(Frame target, Frame template, JsonNode point) { + FrameSet fs = target.findFrame(template, ""); + if (fs == null) { + return null; + } + int naxes = target.getNaxes(); + double[][] in = new double[naxes][1]; + for (int i = 0; i < naxes; i++) { + in[i][0] = point.get(i).asDouble(); + } + return fs.tranP(1, naxes, in, true, fs.getNout())[0][0]; + } + + /** Rust's {@code system_is_compound_as_in_the_c_library}. */ + @Test + void systemIsCompoundAsInTheCLibrary() { + assertEquals( + ProbeData.load("specflux_primary").get("SYSTEM").asText(), + specflux().getSystem()); + } + + /** Rust's {@code templates_find_component_axes_as_in_the_c_library}. */ + @Test + void templatesFindComponentAxesAsInTheCLibrary() { + JsonNode data = ProbeData.load("specflux_primary"); + JsonNode point = data.get("POINT"); + SpecFluxFrame sff = specflux(); + CmpFrame cmp = new CmpFrame(specflux(), new Frame(1)); + List failures = new ArrayList<>(); + int run = 0; + for (JsonNode c : data.get("CASES")) { + String name = c.get(0).asText(); + Double want = c.get(1).isNull() ? null : ProbeData.toDouble(c.get(1)); + Double got; + switch (name) { + case "spec_in_specflux": + got = found(sff, specTemplate(2), point); + break; + case "spec_in_cmp": + got = found(cmp, specTemplate(3), point); + break; + case "flux_in_specflux": + got = found(sff, flux(2, "mJy"), point); + break; + case "flux_in_cmp": + got = found(cmp, flux(3, "mJy"), point); + break; + default: + throw new AssertionError("no set-up for case " + name); + } + if (want == null ? got != null : !want.equals(got)) { + failures.add(name + ": got " + got + ", C gives " + want); + } + run++; + } + assertEquals(4, run); + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecFrameTest.java b/src/test/java/uk/ac/starlink/ast/SpecFrameTest.java new file mode 100644 index 0000000..931c010 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecFrameTest.java @@ -0,0 +1,1308 @@ +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.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 com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of the tests of Rust {@code tests/test_specframe.rs} and {@code + * frames/specframe.rs}, and of the checks of C's {@code ast_tester/testspecframe.c}: construction + * and defaults, the System and StdOfRest names, the attributes and the units they are given in, the + * SpecOrigin, SourceVel, SourceVRF and SourceSys, formatting and reading values, Overlay, the + * reference position, native dumps through a Channel and a FitsChan, and conversions between + * SpecFrames (specframe.c {@code Match}, {@code SubFrame} and {@code MakeSpecMapping}). + * + *

    The expected values of the conversions are C's, from a probe run against the pinned C library + * (each case is a pair of attribute settings, applied as the probe applies them), where the Rust + * tests compare with formulae. Further conversion tests cover a Unit that differs together with + * the System, RestFreq or StdOfRest, FrameSet integrity, each attribute a standard of rest needs + * left unset with and without UseDefs, and conversions that leave their Frames unchanged and give + * the same Mapping in two threads. + * + *

    {@code test_equal_same}, {@code test_not_equal_different_system} and {@code + * test_not_equal_different_sor} test {@code astEqual}, which this library does not have. + */ +class SpecFrameTest { + + /** A SpecFrame with its System set, as Rust's {@code SpecFrame::new(system)}. */ + private static SpecFrame frame(String system) { + SpecFrame f = new SpecFrame(); + f.setSystem(system); + return f; + } + + private static void assertClose(double want, double got, double tol, String what) { + assertTrue(Math.abs(got - want) <= tol, what + ": expected " + want + ", got " + got); + } + + /** The value {@code unformat} reads and the number of characters it uses. */ + private static double[] unformat(SpecFrame f, String text) { + double[] value = {AstObject.AST__BAD}; + int nc = f.unformat(1, text, value); + return new double[] {value[0], nc}; + } + + /** {@code obj} written to a FitsChan with the NATIVE encoding and read back. */ + private static AstObject fitsRoundTrip(AstObject obj) { + FitsChan fc = new FitsChan(); + fc.setEncoding("NATIVE"); + assertEquals(1, fc.write(obj)); + fc.clear("Card"); + AstObject back = fc.read(); + assertNotNull(back, "the FitsChan holds an Object"); + return back; + } + + /** testspecframe.c {@code checkdump}: a Channel dump read back keeps the SpecOrigin. */ + private static SpecFrame checkDump(SpecFrame sf) { + AstObject back = ChannelText.read(ChannelText.dump(sf)); + SpecFrame result = assertInstanceOf(SpecFrame.class, back); + assertEquals(sf.getD("SpecOrigin"), result.getD("SpecOrigin")); + return result; + } + + // ------------------------------------------------------------------ + // Construction and attributes + // ------------------------------------------------------------------ + + @Test + void construction() { + SpecFrame sf = frame("FREQ"); + assertEquals(1, sf.getNaxes()); + assertEquals("FREQ", sf.getSystem()); + assertEquals(SpecFrame.AST__FREQ, sf.systemValue()); + assertEquals("Heliocentric", sf.getStdOfRest()); + assertEquals(SpecFrame.AST__HLSOR, sf.stdOfRestValue()); + } + + @Test + void defaults() { + SpecFrame sf = new SpecFrame(); + assertEquals("WAVE", sf.getSystem()); + assertFalse(sf.test("System")); + assertEquals("WAVE", sf.getAlignSystem()); + assertEquals("SPECTRUM", sf.getDomain()); + assertEquals("Angstrom", sf.getUnit(1)); + assertEquals("Wavelength", sf.getLabel(1)); + assertEquals("WAVE", sf.getSymbol(1)); + assertEquals("Wavelength", sf.getTitle()); + assertEquals("Heliocentric", sf.getAlignStdOfRest()); + assertEquals("Heliocentric", sf.getC("SourceVRF")); + assertEquals("VELO", sf.getSourceSys()); + assertEquals(1.0e5, sf.getRestFreq(), 1.0e-9); + assertEquals(0.0, sf.getSourceVel()); + assertEquals(0.0, sf.getD("SpecOrigin")); + assertEquals(0, sf.getI("AlignSpecOffset")); + assertEquals("0:00:00.0", sf.getRefRA()); + assertEquals("0:00:00", sf.getRefDec()); + assertTrue(sf.getActiveUnit()); + } + + @Test + void attributes() { + SpecFrame sf = frame("WAVE"); + sf.setRestFreqValue(1.42040575e9); + sf.setRefRaValue(1.234); + sf.setRefDecValue(0.567); + sf.setStdOfRest("LSRK"); + sf.setEpochMjd(51544.5); + + assertEquals("WAVE", sf.getSystem()); + assertEquals(SpecFrame.AST__LKSOR, sf.stdOfRestValue()); + assertEquals("LSRK", sf.getStdOfRest()); + assertClose(1.42040575e9, sf.restFreqValue(), 1.0, "rest_freq"); + assertClose(1.42040575, sf.getRestFreq(), 1.0e-12, "RestFreq in GHz"); + assertClose(1.234, sf.refRaValue(), 1e-15, "ref_ra"); + assertClose(0.567, sf.refDecValue(), 1e-15, "ref_dec"); + assertClose(51544.5, sf.getEpochMjd(), 1e-15, "epoch"); + } + + /** Only the names C accepts are System names: the short names and the long forms. */ + @Test + void systemNames() { + SpecFrame sf = new SpecFrame(); + assertEquals(SpecFrame.AST__FREQ, sf.systemCode("FREQ")); + assertEquals(SpecFrame.AST__FREQ, sf.systemCode("freq")); + assertEquals(SpecFrame.AST__WAVELEN, sf.systemCode("WAVE")); + assertEquals(SpecFrame.AST__VREL, sf.systemCode("VELO")); + assertEquals(SpecFrame.AST__VRADIO, sf.systemCode("VRAD")); + assertEquals(SpecFrame.AST__REDSHIFT, sf.systemCode("ZOPT")); + assertEquals(SpecFrame.AST__BETA, sf.systemCode("BETA")); + assertEquals(Frame.AST__BADSYSTEM, sf.systemCode("junk")); + String[] names = {"ENERGY", "WAVENUM", "WAVELEN", "AIRWAVE", "VRADIO", "VOPTICAL", "REDSHIFT", "VREL"}; + int[] codes = { + SpecFrame.AST__ENERGY, + SpecFrame.AST__WAVENUM, + SpecFrame.AST__WAVELEN, + SpecFrame.AST__AIRWAVE, + SpecFrame.AST__VRADIO, + SpecFrame.AST__VOPTICAL, + SpecFrame.AST__REDSHIFT, + SpecFrame.AST__VREL + }; + for (int i = 0; i < names.length; i++) { + assertEquals(codes[i], sf.systemCode(names[i]), names[i]); + } + for (String name : new String[] {"FREQUENCY", "WAVENUMBER", "WAVELENGTH", "AIRWAV", "RELATIVISTIC"}) { + assertEquals(Frame.AST__BADSYSTEM, sf.systemCode(name), name); + } + } + + @Test + void stdOfRestNames() { + assertEquals(SpecFrame.AST__HLSOR, SpecFrame.stdOfRestCode("Heliocentric")); + assertEquals(SpecFrame.AST__HLSOR, SpecFrame.stdOfRestCode("HELIO")); + assertEquals(SpecFrame.AST__LKSOR, SpecFrame.stdOfRestCode("LSRK")); + assertEquals(SpecFrame.AST__LKSOR, SpecFrame.stdOfRestCode("LSR")); + assertEquals(SpecFrame.AST__BYSOR, SpecFrame.stdOfRestCode("BARY")); + assertEquals(SpecFrame.AST__TPSOR, SpecFrame.stdOfRestCode("TOPO")); + assertEquals(SpecFrame.AST__SCSOR, SpecFrame.stdOfRestCode("Source")); + assertEquals(SpecFrame.AST__BADSOR, SpecFrame.stdOfRestCode("garbage")); + } + + /** Rust's {@code is_velocity}: the systems C's {@code ABS_SYSTEM} calls relative. */ + @Test + void relativeSystems() { + assertTrue(SpecFrame.absSystem(SpecFrame.AST__FREQ)); + assertTrue(SpecFrame.absSystem(SpecFrame.AST__ENERGY)); + assertTrue(SpecFrame.absSystem(SpecFrame.AST__WAVENUM)); + assertTrue(SpecFrame.absSystem(SpecFrame.AST__WAVELEN)); + assertTrue(SpecFrame.absSystem(SpecFrame.AST__AIRWAVE)); + assertFalse(SpecFrame.absSystem(SpecFrame.AST__VRADIO)); + assertFalse(SpecFrame.absSystem(SpecFrame.AST__VOPTICAL)); + assertFalse(SpecFrame.absSystem(SpecFrame.AST__REDSHIFT)); + assertFalse(SpecFrame.absSystem(SpecFrame.AST__BETA)); + assertFalse(SpecFrame.absSystem(SpecFrame.AST__VREL)); + } + + /** An unknown standard of rest or System is refused with AST__ATTIN and changes nothing. */ + @Test + void badNamesAreRefused() { + SpecFrame sf = frame("FREQ"); + AstException e = assertThrows(AstException.class, () -> sf.setStdOfRest("nowhere")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertFalse(sf.test("StdOfRest")); + e = assertThrows(AstException.class, () -> sf.setAlignStdOfRest("nowhere")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + e = assertThrows(AstException.class, () -> sf.setC("SourceVRF", "Source")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertFalse(sf.test("SourceVRF")); + e = assertThrows(AstException.class, () -> sf.setSourceSys("FREQ")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertFalse(sf.test("SourceSys")); + e = assertThrows(AstException.class, () -> sf.setSystem("JUNK")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + assertEquals("FREQ", sf.getSystem()); + } + + @Test + void domainIsCleaned() { + SpecFrame sf = frame("FREQ"); + sf.setDomain("my spec"); + assertEquals("MYSPEC", sf.getDomain()); + } + + // ------------------------------------------------------------------ + // RestFreq, SourceVel and SpecOrigin in their units + // ------------------------------------------------------------------ + + /** RestFreq is given in GHz, or as a frequency, wavelength or energy with units. */ + @Test + void restFreqTakesUnits() { + SpecFrame sf = new SpecFrame(); + sf.setRestFreq("230"); + assertEquals(230.0e9, sf.restFreqValue(), 1.0e-3); + sf.setRestFreq("1.4E14 Hz"); + assertEquals(1.4e14, sf.restFreqValue(), 1.0e-3); + sf.setRestFreq("2.0 m"); + assertEquals(SpecMap.AST__C / 2.0, sf.restFreqValue(), 1.0e-6); + sf.setRestFreq("1.0 J"); + assertEquals(1.0 * (1.0 / SpecMap.AST__H), sf.restFreqValue()); + AstException e = assertThrows(AstException.class, () -> sf.setRestFreq("1.0 km/s")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + e = assertThrows(AstException.class, () -> sf.setRestFreq("0.0 m")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + } + + /** SourceVel is given in km/s for a velocity SourceSys, and stored in m/s. */ + @Test + void sourceVelUnits() { + SpecFrame sf = new SpecFrame(); + sf.setSourceVel(10.0); + assertEquals(10000.0, sf.sourceVelValue()); + assertEquals(10.0, sf.getSourceVel()); + sf.clear("SourceVel"); + sf.setSourceSys("ZOPT"); + sf.setSourceVel(0.1); + assertEquals(0.1, sf.sourceVelValue()); + assertEquals(0.1, sf.getSourceVel()); + } + + /** + * testspecframe.c Errors 0 to 3: the SpecOrigin is given in the units of the axis, kept in the + * default units of the System, and survives a dump. + */ + @Test + void specOriginFollowsTheUnit() { + SpecFrame sf = new SpecFrame(); + sf.set("system=freq,unit=Hz"); + assertEquals(0.0, sf.getD("SpecOrigin"), "Error 0"); + double rf = sf.getD("RestFreq"); + sf.setD("SpecOrigin", rf * 1.0e9); + assertTrue(Math.abs(sf.getD("SpecOrigin") - rf * 1.0e9) <= 0.1, "Error 1"); + sf.setC("Unit(1)", "GHz"); + assertEquals(rf, sf.getD("SpecOrigin"), "Error 2"); + checkDump(sf); + } + + /** A SpecOrigin with units is converted to the default units of the System. */ + @Test + void specOriginWithUnits() { + SpecFrame sf = frame("FREQ"); + sf.set("SpecOrigin=1.5 MHz"); + assertEquals(1.5e-3, sf.specOriginValue(), 1.0e-15); + assertEquals("Frequency offset from 0.0015", sf.getLabel(1)); + } + + /** + * testspecframe.c Errors 10 to 12: SourceVel, in C's units, is re-expressed when SourceVRF and + * SourceSys change, and survives a dump. 1000 km/s relative to the LSRK, as an optical + * redshift relative to the barycentre, is 0.00334028336870307, and back. + */ + @Test + void sourceVelFollowsSourceVrfAndSourceSys() { + SpecFrame sf = new SpecFrame(); + sf.set("system=freq,unit=Hz"); + sf.setC("SourceVRF", "LSRK"); + sf.setD("SourceVel", 1000.0); + sf.setC("SourceVRF", "BARY"); + sf.setC("SourceSys", "ZOPT"); + assertClose(0.00334028336870307, sf.getD("SourceVel"), 1.0e-10, "Error 11"); + checkDump(sf); + sf.setC("SourceVRF", "LSRK"); + sf.setC("SourceSys", "VREL"); + assertClose(1000.0, sf.getD("SourceVel"), 1.0e-6, "Error 12"); + } + + // ------------------------------------------------------------------ + // Units of another kind + // ------------------------------------------------------------------ + + /** + * A Unit of another kind (Angstrom on a frequency axis, km/s on a wavelength axis) is stored + * as given and leaves the System as it is (specframe.c {@code SetUnit}); the Label and Symbol + * keep their defaults, as {@code astUnitMapper} finds no Mapping to relabel them with. + */ + @Test + void aUnitOfAnotherKindLeavesTheSystem() { + SpecFrame sf = frame("FREQ"); + sf.setUnit(1, "Angstrom"); + assertEquals("FREQ", sf.getSystem()); + assertEquals("Angstrom", sf.getUnit(1)); + assertEquals("Frequency", sf.getLabel(1)); + assertEquals("FREQ", sf.getSymbol(1)); + + SpecFrame wave = frame("WAVE"); + wave.setUnit(1, "km/s"); + assertEquals("WAVE", wave.getSystem()); + assertEquals("km/s", wave.getUnit(1)); + assertEquals("Wavelength", wave.getLabel(1)); + } + + /** + * A SpecOrigin cannot be given or read in units that do not convert to the System's default + * units: AST__BADUN from specframe.c {@code ToUnits} and {@code GetSpecOriginCur}. + */ + @Test + void anImpossibleUnitIsBadun() { + SpecFrame sf = frame("FREQ"); + sf.setUnit(1, "Angstrom"); + AstException e = assertThrows(AstException.class, () -> sf.setD("SpecOrigin", 5.0)); + assertEquals(AstException.AST__BADUN, e.getStatus()); + assertEquals( + "astSetSpecOrigin(SpecFrame): Cannot convert the supplied attribute value from units of Angstrom" + + " to GHz.", + e.getMsgText()); + assertFalse(sf.test("SpecOrigin")); + + SpecFrame withOrigin = frame("FREQ"); + withOrigin.setD("SpecOrigin", 5.0); + withOrigin.setUnit(1, "Angstrom"); + e = assertThrows(AstException.class, () -> withOrigin.getD("SpecOrigin")); + assertEquals(AstException.AST__BADUN, e.getStatus()); + assertEquals( + "astGetSpecOrigin(SpecFrame): The current units (Angstrom) are not suitable for a SpecFrame.", + e.getMsgText()); + e = assertThrows(AstException.class, () -> withOrigin.getLabel(1)); + assertEquals(AstException.AST__BADUN, e.getStatus()); + } + + /** The Unit used with each System comes back when the System does. */ + @Test + void theUnitOfEachSystemIsRemembered() { + SpecFrame sf = frame("FREQ"); + sf.setUnit(1, "MHz"); + sf.setSystem("VRAD"); + assertEquals("km/s", sf.getUnit(1)); + assertFalse(sf.test("Unit(1)")); + sf.setUnit(1, "m/s"); + sf.setSystem("FREQ"); + assertEquals("MHz", sf.getUnit(1)); + sf.setSystem("VRAD"); + assertEquals("m/s", sf.getUnit(1)); + sf.clear("Unit(1)"); + sf.setSystem("FREQ"); + sf.setSystem("VRAD"); + assertEquals("km/s", sf.getUnit(1)); + } + + // ------------------------------------------------------------------ + // Formatting and reading values + // ------------------------------------------------------------------ + + @Test + void distance() { + SpecFrame sf = frame("FREQ"); + assertClose(1e9, sf.distance(new double[] {1e9}, new double[] {2e9}), 1.0, "distance"); + assertEquals(AstObject.AST__BAD, sf.distance(new double[] {AstObject.AST__BAD}, new double[] {2e9})); + } + + /** SpecFrame does not override Format in C; it formats as a Frame does, without units. */ + @Test + void formatFreq() { + assertEquals("1.42E+09", frame("FREQ").format(1, 1.42e9)); + assertFalse(frame("ZOPT").format(1, 0.5).contains("Hz")); + } + + /** The base {@code %1.7G} contract, with Digits 7. */ + @Test + void formatBaseContract() { + SpecFrame sf = frame("FREQ"); + assertEquals("12.5", sf.format(1, 12.5)); + assertEquals("1.5E+09", sf.format(1, 1.5e9)); + assertEquals("0.0001234568", sf.format(1, 0.000123456789)); + assertEquals("1.234568E+08", sf.format(1, 123456789.0)); + assertEquals("0.3333333", sf.format(1, 1.0 / 3.0)); + assertEquals("", sf.format(1, AstObject.AST__BAD)); + } + + @Test + void unformatReadsANumber() { + double[] r = unformat(frame("FREQ"), "1.5e9 Hz"); + assertClose(1.5e9, r[0], 1.0, "unformat value"); + assertTrue(r[1] > 0, "unformat uses characters"); + } + + /** SpecFrame does not override Unformat in C; it reads as a Frame does (axis.c). */ + @Test + void unformatBaseContract() { + SpecFrame sf = frame("FREQ"); + assertEquals(12.5, unformat(sf, "12.5")[0]); + assertEquals(4, (int) unformat(sf, "12.5")[1]); + assertEquals(12.5, unformat(sf, " 12.5 ")[0]); + assertEquals(8, (int) unformat(sf, " 12.5 ")[1]); + assertEquals(12.5, unformat(sf, "12.5xyz")[0]); + assertEquals(4, (int) unformat(sf, "12.5xyz")[1]); + assertEquals(AstObject.AST__BAD, unformat(sf, "")[0]); + assertEquals(5, (int) unformat(sf, "")[1]); + assertEquals(AstObject.AST__BAD, unformat(sf, " < b a d > ")[0]); + assertEquals(11, (int) unformat(sf, " < b a d > ")[1]); + assertEquals(0, (int) unformat(sf, "xyz")[1]); + assertEquals(0, (int) unformat(sf, "")[1]); + assertEquals(0, (int) unformat(sf, " ")[1]); + } + + // ------------------------------------------------------------------ + // Overlay + // ------------------------------------------------------------------ + + @Test + void overlayCopiesASetSystem() { + SpecFrame template = frame("VRAD"); + SpecFrame result = frame("FREQ"); + result.setTitle("Mine"); + template.overlay(new int[] {0}, result); + assertEquals("VRAD", result.getSystem()); + assertFalse(result.test("Title")); + } + + @Test + void overlaySkipsUnsetAttributes() { + SpecFrame template = frame("FREQ"); + template.clear("System"); + assertFalse(template.test("System")); + SpecFrame result = frame("VRAD"); + template.overlay(new int[] {0}, result); + assertEquals("VRAD", result.getSystem()); + assertFalse(result.test("RestFreq")); + assertFalse(result.test("StdOfRest")); + } + + @Test + void overlayCopiesASetRestFreq() { + SpecFrame template = frame("FREQ"); + template.setRestFreqValue(1.420405751e9); + SpecFrame result = frame("FREQ"); + template.overlay(new int[] {0}, result); + assertEquals(1.420405751e9, result.restFreqValue()); + } + + /** + * Overlaid onto a plain Frame, a SpecFrame with a System set gives none of its System and + * AlignSystem, and itself keeps them: specframe.c {@code Overlay} clears them on a copy. Clearing + * the copy's System changes it, which clears the copy's Title, so the Title is not overlaid + * either (a C quirk, followed here); the Domain is. + */ + @Test + void overlayOntoAPlainFrameLeavesTheSystem() { + SpecFrame template = frame("VRAD"); + template.setAlignSystem("FREQ"); + template.setTitle("Spec"); + template.setDomain("MYSPEC"); + Frame result = new Frame(1); + template.overlay(new int[] {0}, result); + assertEquals("Cartesian", result.getSystem()); + assertFalse(result.test("Title")); + assertEquals("MYSPEC", result.getDomain()); + assertEquals("VRAD", template.getSystem()); + assertEquals("FREQ", template.getAlignSystem()); + assertEquals("Spec", template.getTitle()); + } + + // ------------------------------------------------------------------ + // Reference position + // ------------------------------------------------------------------ + + /** + * RefRA and RefDec are stored in FK5 J2000, so a position given in FK4 B1950 is converted to it. + * The values are the REFRA_B and REFDEC_B cards of the C library's {@code fits-pc-alt} wcsconv + * reference, whose alternate plane describes RA, Dec = 180, 45 degrees in FK4 B1950. + */ + @Test + void setRefPosConvertsFromFk4B1950() { + SkyFrame fk4 = new SkyFrame(); + fk4.set("System=FK4,Equinox=1950,Epoch=1950"); + SpecFrame spec = frame("WAVE"); + spec.setRefPos(fk4, Math.toRadians(180.0), Math.toRadians(45.0)); + assertClose(3.152747005821885, spec.refRaValue(), 1.0e-12, "RefRA"); + assertClose(0.7805403873335395, spec.refDecValue(), 1.0e-12, "RefDec"); + } + + /** + * Rust {@code tests/test_frame_api.rs} {@code ref_pos_follows_the_c_library}: the reference + * position read back with no SkyFrame, in Galactic coordinates, and in FK4 B1950 with the + * axes swapped, as C's {@code astGetRefPos} gives them ({@code oracle/frame_api.json}). + */ + @Test + void refPosFollowsTheCLibrary() { + SpecFrame sf = frame("WAVE"); + sf.setRefPos(null, 1.0, 0.3); + SkyFrame gal = new SkyFrame(); + gal.setSystem("GALACTIC"); + SkyFrame fk4 = new SkyFrame(); + fk4.set("System=FK4,Equinox=1950"); + fk4.permAxes(new int[] {2, 1}); + String[] names = {"none", "galactic", "fk4_swapped"}; + double[][] got = {sf.getRefPos(null), sf.getRefPos(gal), sf.getRefPos(fk4)}; + JsonNode cases = ProbeData.load("frame_api").get("REF_POS"); + assertEquals(names.length, cases.size(), "the test runs every case the C probe recorded"); + for (int i = 0; i < names.length; i++) { + JsonNode c = cases.get(i); + assertEquals(names[i], c.get(0).asText()); + double[] want = { + ProbeData.toDouble(c.get(1).get(0)), ProbeData.toDouble(c.get(1).get(1)) + }; + CValues.assertCValues(got[i], want, names[i]); + } + } + + @Test + void refPosWithoutASkyFrameIsTheStoredPosition() { + SpecFrame spec = new SpecFrame(); + spec.setRefPos(null, 1.0, 0.3); + double[] pos = spec.getRefPos(null); + assertEquals(1.0, pos[0]); + assertEquals(0.3, pos[1]); + assertTrue(spec.test("RefRA")); + assertTrue(spec.test("RefDec")); + } + + @Test + void refRaAndRefDecAreSexagesimal() { + SpecFrame sf = new SpecFrame(); + sf.setRefRA("1:00:00"); + sf.setRefDec("-30:00:00"); + assertEquals(Math.PI / 12.0, sf.refRaValue(), 1.0e-15); + assertEquals(-Math.PI / 6.0, sf.refDecValue(), 1.0e-15); + assertEquals("1:00:00.0", sf.getRefRA()); + assertEquals("-30:00:00", sf.getRefDec()); + AstException e = assertThrows(AstException.class, () -> sf.setRefRA("1:00:00 junk")); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + } + + /** GeoLat and GeoLon are the ObsLat and ObsLon. */ + @Test + void geoLatAndGeoLonAreTheObserverPosition() { + SpecFrame sf = new SpecFrame(); + sf.setGeoLat("N10"); + sf.setGeoLon("W20"); + assertEquals(sf.getObsLat(), sf.getGeoLat()); + assertEquals(sf.getObsLon(), sf.getGeoLon()); + assertTrue(sf.test("GeoLat")); + assertEquals(Math.toRadians(10.0), sf.getObsLatValue(), 1.0e-15); + sf.clear("GeoLon"); + assertFalse(sf.test("ObsLon")); + } + + // ------------------------------------------------------------------ + // Dumps + // ------------------------------------------------------------------ + + @Test + void serialiseRoundTrip() { + SpecFrame sf = frame("WAVE"); + sf.setRestFreqValue(1.42040575e9); + sf.setRefRaValue(1.5); + sf.setRefDecValue(-0.3); + sf.setStdOfRest("LSRK"); + sf.setSourceVelValue(25000.0); + sf.setSourceVrfValue(SpecFrame.AST__HLSOR); + sf.setSourceSysValue(SpecFrame.AST__VREL); + sf.setEpochMjd(51544.5); + sf.setObsLatValue(0.5); + sf.setObsLonValue(-1.0); + sf.setObsAlt(100.0); + sf.setSpecOriginValue(5.0e-7); + sf.setAlignStdOfRestValue(SpecFrame.AST__BYSOR); + + String text = ChannelText.dump(sf); + for (String key : new String[] {"SpecFrame", "SoR", "RstFrq", "RefRA", "SrcVel", "SpOrg", "AlSoR"}) { + assertTrue(text.contains(key), "missing " + key); + } + SpecFrame sf2 = assertInstanceOf(SpecFrame.class, ChannelText.read(text)); + assertEquals("WAVE", sf2.getSystem()); + assertEquals(SpecFrame.AST__LKSOR, sf2.stdOfRestValue()); + assertClose(1.42040575e9, sf2.restFreqValue(), 1.0, "rf"); + assertClose(1.5, sf2.refRaValue(), 1e-14, "refra"); + assertClose(-0.3, sf2.refDecValue(), 1e-14, "refdec"); + assertClose(25000.0, sf2.sourceVelValue(), 1e-10, "srcvel"); + assertEquals(SpecFrame.AST__HLSOR, sf2.sourceVrfValue()); + assertEquals(SpecFrame.AST__VREL, sf2.sourceSysValue()); + assertClose(51544.5, sf2.getEpochMjd(), 1e-14, "epoch"); + assertClose(5.0e-7, sf2.specOriginValue(), 1e-20, "sporg"); + assertEquals(SpecFrame.AST__BYSOR, sf2.alignStdOfRestValue()); + } + + @Test + void serialiseMinimal() { + SpecFrame sf2 = assertInstanceOf(SpecFrame.class, ChannelText.read(ChannelText.dump(frame("FREQ")))); + assertEquals("FREQ", sf2.getSystem()); + assertEquals(SpecFrame.AST__HLSOR, sf2.stdOfRestValue()); + assertFalse(sf2.test("StdOfRest")); + } + + /** The C library's dump of a SpecFrame with a Unit used with its System, item for item. */ + @Test + void theUnitUsedWithASystemIsDumped() { + String c = " Begin SpecFrame \t# Description of spectral coordinate system\n" + + "# Title = \"Frequency (Heliocentric)\" \t# Title of coordinate system\n" + + " Naxes = 1 \t# Number of coordinate axes\n" + + "# Domain = \"SPECTRUM\" \t# Coordinate system domain\n" + + "# Epoch = 2000 \t# Julian epoch of observation\n" + + "# Lbl1 = \"Frequency\" \t# Label for axis 1\n" + + " System = \"FREQ\" \t# Coordinate system type\n" + + "# Uni1 = \"GHz\" \t# Units for axis 1\n" + + " Ax1 = \t# Axis number 1\n" + + " Begin Axis \t# Coordinate axis\n" + + " Unit = \"GHz\" \t# Axis units\n" + + " End Axis\n" + + " IsA Frame \t# Coordinate system description\n" + + " SoR = \"Heliocentric\" \t# Standard of rest\n" + + " UFreq = \"GHz\" \t# Preferred units for frequency\n" + + " End SpecFrame\n"; + SpecFrame sf = frame("FREQ"); + sf.setStdOfRest("Heliocentric"); + sf.setUnit(1, "GHz"); + assertEquals(c, ChannelText.dump(sf)); + SpecFrame back = assertInstanceOf(SpecFrame.class, ChannelText.read(c)); + assertEquals(c, ChannelText.dump(back)); + back.setSystem("VRAD"); + back.setSystem("FREQ"); + assertTrue(back.test("Unit(1)")); + } + + /** A SpecFrame with no attribute set, and with every one set, survives a Channel and a FitsChan. */ + @Test + void everyAttributeSurvivesChannelAndFitsChan() { + SpecFrame unset = new SpecFrame(); + SpecFrame set = frame("VRAD"); + set.setUnit(1, "m/s"); + set.setSystem("FREQ"); + set.setUnit(1, "MHz"); + set.set("AlignSystem=WAVN,StdOfRest=LSRD,AlignStdOfRest=Bary,RefRA=10:00:00,RefDec=-20:00:00"); + set.set("RestFreq=230,SourceVRF=LSRK,SourceSys=ZOPT,SourceVel=0.01,SpecOrigin=200,AlignSpecOffset=1"); + set.set("Epoch=2005.5,ObsLat=N30,ObsLon=W60,ObsAlt=1000,Title=Spectrum,Label(1)=Nu,Symbol(1)=nu"); + for (SpecFrame sf : new SpecFrame[] {unset, set}) { + String text = ChannelText.dump(sf); + SpecFrame back = assertInstanceOf(SpecFrame.class, ChannelText.read(text)); + assertEquals(text, ChannelText.dump(back), "Channel round trip"); + SpecFrame viaFits = assertInstanceOf(SpecFrame.class, fitsRoundTrip(sf)); + assertEquals(text, ChannelText.dump(viaFits), "FitsChan round trip"); + } + SpecFrame back = assertInstanceOf(SpecFrame.class, ChannelText.read(ChannelText.dump(set))); + assertEquals("MHz", back.getUnit(1)); + assertEquals(0.2, back.specOriginValue(), 1.0e-15); + assertEquals("0.01", back.getC("SourceVel")); + assertEquals("Barycentric", back.getAlignStdOfRest()); + assertEquals("LSRD", back.getStdOfRest()); + assertEquals(1, back.getI("AlignSpecOffset")); + } + + /** A dump with an unknown standard of rest is refused with AST__ATTIN, as C's loader does. */ + @Test + void anUnknownStandardOfRestInADumpIsRefused() { + String text = ChannelText.dump(frame("FREQ")).replace("# SoR = \"Heliocentric\"", " SoR = \"Nowhere\""); + AstException e = assertThrows(AstException.class, () -> ChannelText.read(text)); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + } + + // ------------------------------------------------------------------ + // The jniast API + // ------------------------------------------------------------------ + + @Test + void jniastAccessors() { + SpecFrame sf = new SpecFrame(); + sf.setStdOfRest("Topo"); + assertEquals("Topocentric", sf.getStdOfRest()); + sf.setAlignStdOfRest("LG"); + assertEquals("Local_group", sf.getAlignStdOfRest()); + sf.setRestFreq(345.0); + assertEquals(345.0, sf.getRestFreq(), 1.0e-12); + sf.setSourceSys("VRAD"); + assertEquals("VRAD", sf.getSourceSys()); + sf.setSourceVel(-5.0); + assertEquals(-5.0, sf.getSourceVel(), 1.0e-12); + // jniast's SourceVRF accessors pass the value as a number, which is no standard of rest. + assertEquals( + AstException.AST__ATGER, + assertThrows(AstException.class, sf::getSourceVRF).getStatus()); + AstException e = assertThrows(AstException.class, () -> sf.setSourceVRF(1.0)); + assertEquals(AstException.AST__ATTIN, e.getStatus()); + } + + /** UseDefs false leaves an unset RestFreq out of the default Title (specframe.c {@code GetTitle}). */ + @Test + void useDefsLeavesAnUnsetRestFreqOutOfTheTitle() { + SpecFrame sf = frame("VRAD"); + sf.set("UseDefs=0"); + assertEquals("Radio velocity", sf.getTitle()); + sf.setRestFreq(230.0); + assertEquals("Radio velocity, rest frequency = 230 GHz", sf.getTitle()); + } + + /** A copy has its own record of the Unit used with each System. */ + @Test + void aCopyIsIndependent() { + SpecFrame sf = frame("FREQ"); + sf.setUnit(1, "MHz"); + SpecFrame copy = (SpecFrame) sf.copy(); + copy.setUnit(1, "kHz"); + sf.setSystem("VRAD"); + sf.setSystem("FREQ"); + assertEquals("MHz", sf.getUnit(1)); + copy.setSystem("VRAD"); + copy.setSystem("FREQ"); + assertEquals("kHz", copy.getUnit(1)); + } + + // ------------------------------------------------------------------ + // Conversions between SpecFrames + // + // Expected values are C's, from the probe spec_convert_cases.c run against the pinned C + // library; each case is a pair of attribute settings as the probe's make() applies them. + // ------------------------------------------------------------------ + + /** The probe's {@code make}: a SpecFrame with the comma-separated settings applied in order. */ + private static SpecFrame make(String settings) { + SpecFrame f = new SpecFrame(); + if (!settings.isEmpty()) { + f.set(settings); + } + return f; + } + + /** The FrameSet {@code convert} finds from {@code from} to {@code to}, which must exist. */ + private static FrameSet converted(Frame from, Frame to) { + FrameSet fs = from.convert(to, ""); + assertNotNull(fs, "a conversion"); + return fs; + } + + /** The class of the simplified Mapping from the base to the current Frame. */ + private static String mappingClass(FrameSet fs) { + return fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT) + .simplify() + .astClass(); + } + + /** + * Converts {@code x} from a SpecFrame with settings {@code a} to one with {@code b}, and checks + * the value and the class of the simplified Mapping against C's. + */ + private static void assertConverts(String a, String b, double x, boolean forward, double want, String wantClass) { + FrameSet fs = converted(make(a), make(b)); + double got = fs.tran1(1, new double[] {x}, forward)[0]; + assertTrue(CValues.cValueEq(got, want), "[" + a + "] -> [" + b + "]: got " + got + ", C gives " + want); + assertEquals(wantClass, mappingClass(fs), "the Mapping"); + } + + /** + * Checks that converting from {@code a} to {@code b} fails with {@code AST__NOVAL} and C's + * message, naming the attribute that is not set. + */ + private static void assertNoValue(String a, String b, String message) { + SpecFrame from = make(a); + SpecFrame to = make(b); + AstException e = assertThrows(AstException.class, () -> from.convert(to, "")); + assertEquals(AstException.AST__NOVAL, e.getStatus(), e.getMessage()); + assertTrue(e.getMessage().contains(message), "C's message " + message + ", got: " + e.getMessage()); + } + + @Test + void freqToWavelengthConvert() { + assertConverts("System=FREQ,Unit=Hz", "System=WAVE,Unit=m", 5.0e14, true, 5.99584916e-07, "SpecMap"); + assertConverts( + "System=FREQ,Unit=Hz", + "System=WAVE,Unit=m", + 2.99792458e8 / 5.0e14, + false, + 500000000000000.0, + "SpecMap"); + } + + @Test + void freqToEnergy() { + assertConverts("System=FREQ,Unit=Hz", "System=ENER", 1.0e15, true, 6.6260755e-19, "SpecMap"); + } + + @Test + void freqToWavenum() { + assertConverts("System=FREQ,Unit=Hz", "System=WAVN", 3.0e14, true, 1000692.2855944561, "SpecMap"); + } + + @Test + void freqToVrel() { + String a = "System=FREQ,Unit=Hz,RestFreq=1.42040575E9 Hz"; + String b = "System=VELO,Unit=m/s,RestFreq=1.42040575E9 Hz"; + assertConverts(a, b, 1.42040575e9, true, 0.0, "SpecMap"); + assertConverts(a, b, 1.42040575e9 * 1.001, true, -299642.561845836, "SpecMap"); + } + + @Test + void vradioToFreq() { + assertConverts( + "System=VRAD,Unit=m/s,RestFreq=1.42040575E9 Hz", + "System=FREQ,Unit=Hz,RestFreq=1.42040575E9 Hz", + 100000.0, + true, + 1419931953.641187, + "SpecMap"); + } + + /** A heliocentric to LSRK change is a small Doppler shift, and the inverse undoes it. */ + @Test + void sorHelioToLsrk() { + String a = "System=FREQ,StdOfRest=Helio,RefRA=0:00:00,RefDec=0:00:00"; + String b = "System=FREQ,StdOfRest=LSRK,RefRA=0:00:00,RefDec=0:00:00"; + assertConverts(a, b, 1.42040575e9, true, 1420404375.9912238, "CmpMap"); + FrameSet fs = converted(make(a), make(b)); + double y = fs.tran1(1, new double[] {1.42040575e9}, true)[0]; + double back = fs.tran1(1, new double[] {y}, false)[0]; + assertTrue(CValues.cValueEq(back, 1420405749.9999995), "round trip: " + back); + } + + @Test + void sameSystemSameSorIsUnitMap() { + assertConverts("System=FREQ", "System=FREQ", 1.234e10, true, 1.234e10, "UnitMap"); + } + + /** + * FrameSet integrity: a change of System and Unit on the current SpecFrame of a FrameSet remaps + * it by the conversion from the old Frame to the new one. + */ + @Test + void mapFromSystemChange() { + FrameSet fs = new FrameSet(new Frame(1)); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(1), make("System=FREQ,Unit=Hz")); + fs.set("System=WAVE,Unit=m"); + assertEquals("WAVE", fs.getC("System")); + double got = fs.tran1(1, new double[] {5.0e14}, true)[0]; + assertTrue(CValues.cValueEq(got, 5.99584916e-07), "got " + got); + assertEquals("SpecMap", mappingClass(fs)); + } + + @Test + void wavelenToVoptical() { + String a = "System=WAVE,Unit=m,RestFreq=1.42040575E9 Hz"; + String b = "System=VOPT,Unit=m/s,RestFreq=1.42040575E9 Hz"; + double lambda0 = 2.99792458e8 / 1.42040575e9; + assertConverts(a, b, lambda0, true, 0.0, "SpecMap"); + assertConverts(a, b, lambda0 * 1.1, true, 29979245.800000027, "SpecMap"); + } + + @Test + void unitMhzToHzWithinFreq() { + assertConverts("System=FREQ,Unit=MHz", "System=FREQ,Unit=Hz", 1.0, true, 1.0e6, "ZoomMap"); + } + + @Test + void unitKmsToMsWithinVrad() { + assertConverts("System=VRAD,Unit=km/s", "System=VRAD,Unit=m/s", 1.0, true, 1000.0, "ZoomMap"); + } + + @Test + void unitUnchangedReturnsUnitMap() { + assertConverts("System=FREQ", "System=FREQ", 42.0, true, 42.0, "UnitMap"); + } + + @Test + void unitRoundTripMhzToGhz() { + assertConverts("System=FREQ,Unit=MHz", "System=FREQ,Unit=GHz", 1000.0, true, 1.0, "ZoomMap"); + } + + @Test + void badValueTransform() { + FrameSet fs = converted(make("System=FREQ"), make("System=WAVE")); + assertEquals(AstObject.AST__BAD, fs.tran1(1, new double[] {AstObject.AST__BAD}, true)[0]); + } + + /** RestFreq 1.420405752 GHz, LSRK, radio velocity in km/s. */ + private static final String VRAD_LSRK = "System=VRAD,StdOfRest=LSRK,RestFreq=1.420405752E9 Hz"; + + /** Offset to offset: the value plus the first origin less the second. */ + @Test + void convertAppliesSpecOrigins() { + assertConverts(VRAD_LSRK + ",SpecOrigin=10", VRAD_LSRK + ",SpecOrigin=25", 5.0, true, -10.0, "ShiftMap"); + } + + @Test + void convertOffsetToAbsoluteAppliesOrigin() { + assertConverts(VRAD_LSRK + ",SpecOrigin=10", VRAD_LSRK, 5.0, true, 15.0, "ShiftMap"); + } + + /** With AlignSpecOffset set on both Frames the offset values align directly. */ + @Test + void alignSpecOffsetAlignsOffsetValues() { + assertConverts( + VRAD_LSRK + ",SpecOrigin=10,AlignSpecOffset=1", + VRAD_LSRK + ",SpecOrigin=25,AlignSpecOffset=1", + 5.0, + true, + 5.0, + "UnitMap"); + } + + /** A SpecOrigin is re-expressed in a new System, and back again (with C's rounding). */ + @Test + void setSystemRescalesSpecOrigin() { + SpecFrame sf = make(VRAD_LSRK + ",SpecOrigin=10"); + sf.setSystem("FREQ"); + assertEquals("GHz", sf.getUnit(1)); + assertTrue(CValues.cValueEq(sf.getD("SpecOrigin"), 1.4203583723640518), "FREQ: " + sf.getD("SpecOrigin")); + sf.setSystem("VRAD"); + assertEquals("km/s", sf.getUnit(1)); + assertTrue(CValues.cValueEq(sf.getD("SpecOrigin"), 10.000000000076058), "VRAD: " + sf.getD("SpecOrigin")); + } + + /** + * Rust {@code frames/specframe.rs} {@code sub_frame_specframe_to_specframe}: selecting the axis + * of a SpecFrame with a SpecFrame template gives a SpecFrame with the template's System and + * StdOfRest, and a Mapping with one input and one output. + */ + @Test + void subFrameSpecFrameToSpecFrame() { + SpecFrame target = make("System=FREQ,StdOfRest=Helio,RestFreq=1.420405751E9 Hz"); + SpecFrame template = make("System=VRAD,StdOfRest=LSRK,RestFreq=1.420405751E9 Hz"); + Mapping[] map = new Mapping[1]; + Frame[] result = new Frame[1]; + assertTrue(target.subFrame(template, 1, new int[] {0}, new int[] {0}, map, result)); + assertEquals(1, map[0].getNin()); + assertEquals(1, map[0].getNout()); + SpecFrame r = assertInstanceOf(SpecFrame.class, result[0]); + assertEquals(SpecFrame.AST__VRADIO, r.systemValue()); + assertEquals(SpecFrame.AST__LKSOR, r.stdOfRestValue()); + } + + @Test + void matchTemplateSpecFrameSelf() { + FrameFinder.MatchResult m = make("System=VRAD").match(make("System=FREQ"), false); + assertNotNull(m); + assertEquals(1, m.templateAxes.length); + assertEquals(1, m.targetAxes.length); + assertEquals(0, m.templateAxes[0]); + assertEquals(0, m.targetAxes[0]); + assertEquals( + SpecFrame.AST__VRADIO, + assertInstanceOf(SpecFrame.class, m.result).systemValue()); + } + + /** A target with no SpecFrame axis is not matched (specframe.c {@code Match}). */ + @Test + void matchTemplateSpecFrameAgainstBasicFrameFails() { + assertNull(make("System=FREQ").match(new Frame(1), false)); + } + + @Test + void matchTemplateSpecFrameSupportsMaxAxesOversized() { + SpecFrame template = make("System=FREQ"); + template.setMaxAxes(2); + assertNull(template.match(new Frame(2), false)); + } + + /** Picking the axis of a SpecFrame gives a SpecFrame. */ + @Test + void pickAxesSpecFrameFull() { + Frame f = make("System=VRAD").pickAxes(1, new int[] {1}, null); + assertEquals(SpecFrame.AST__VRADIO, assertInstanceOf(SpecFrame.class, f).systemValue()); + } + + /** Picking no axis of a SpecFrame gives a plain one-axis Frame. */ + @Test + void pickAxesSpecFramePartial() { + Frame f = make("System=VRAD").pickAxes(1, new int[] {0}, null); + assertEquals(1, f.getNaxes()); + assertFalse(f instanceof SpecFrame); + } + + /** A SpecFrame's set System is overlaid onto the alignment Frame of a conversion. */ + @Test + void convertThroughGenericDriverTransfersSystem() { + assertConverts( + "System=VRAD,Unit=m/s,RestFreq=1.0E9 Hz,StdOfRest=Topo", + "System=FREQ,Unit=Hz,RestFreq=1.0E9 Hz,StdOfRest=Topo", + 1000.0, + true, + 999996664.3590481, + "SpecMap"); + } + + /** + * testspecframe.c Errors 4 to 9 and 13 to 15: a SpecOrigin is re-expressed when the System and + * StdOfRest change; SpecOrigins shift conversions unless AlignSpecOffset aligns the offsets; and + * with AlignSpecOffset set in a wavelength System, whose zero point has no frequency, a change + * of rest frame converts as it does without it, and a SpecOrigin is still re-expressed. The + * values asserted exactly are C's; the tolerances are testspecframe.c's. + */ + @Test + void testspecframeConversions() { + SpecFrame sf = make("system=freq,unit=Hz"); + double rf = sf.getD("RestFreq"); + sf.setD("SpecOrigin", rf * 1.0e9); + sf.setC("Unit(1)", "GHz"); + sf.setC("System", "vrad"); + assertTrue(Math.abs(sf.getD("SpecOrigin")) <= 1.0e-8, "Error 4"); + assertTrue(CValues.cValueEq(sf.getD("SpecOrigin"), 6.656729789611404e-11), "Error 4: " + sf.getD("SpecOrigin")); + sf.setC("System", "freq"); + sf.setC("Unit(1)", "Hz"); + assertTrue(Math.abs(sf.getD("SpecOrigin") - rf * 1.0e9) <= 0.1, "Error 5"); + assertTrue(CValues.cValueEq(sf.getD("SpecOrigin"), 99999999999999.97), "Error 5: " + sf.getD("SpecOrigin")); + sf.setC("StdOfRest", "LSRD"); + assertTrue(Math.abs(sf.getD("SpecOrigin") - rf * 1.00000212890848e9) <= 10.0, "Error 6"); + assertTrue(CValues.cValueEq(sf.getD("SpecOrigin"), 100000212890839.06), "Error 6: " + sf.getD("SpecOrigin")); + + SpecFrame sf1 = make("system=freq,unit=Hz"); + sf1.setD("SpecOrigin", 1.0e20); + SpecFrame sf2 = make("system=freq,unit=Hz"); + sf2.setD("SpecOrigin", 1.01e20); + FrameSet fs = converted(sf1, sf2); + double x = 0.03e20; + assertEquals(0.02e20, fs.tran1(1, new double[] {x}, true)[0], "Error 7"); + assertEquals(0, sf1.getI("AlignSpecOffset"), "Error 8"); + sf1.setL("AlignSpecOffset", 1); + sf2.setL("AlignSpecOffset", 1); + fs = converted(sf1, sf2); + assertEquals(x, fs.tran1(1, new double[] {x}, true)[0], "Error 9"); + + sf1 = make("system=wave,unit=Angstrom,StdOfRest=LSRK,Epoch=2005.0,RefRA=10:00:00,RefDec=20:00:00"); + sf2 = (SpecFrame) sf1.copy(); + sf2.setC("StdOfRest", "HELIO"); + fs = converted(sf1, sf2); + x = 1.3e7; + double plain = fs.tran1(1, new double[] {x}, true)[0]; + assertTrue(CValues.cValueEq(plain, 13000214.726950744), "without AlignSpecOffset: " + plain); + sf1.setL("AlignSpecOffset", 1); + sf2.setL("AlignSpecOffset", 1); + fs = converted(sf1, sf2); + double y = fs.tran1(1, new double[] {x}, true)[0]; + assertTrue(y != AstObject.AST__BAD && Math.abs(y - plain) <= 1.0e-6, "Error 13: " + y); + sf1.setD("SpecOrigin", 1.299e7); + sf1.setC("StdOfRest", "HELIO"); + assertTrue(Math.abs(sf1.getD("SpecOrigin") - 1.299e7) <= 1.0e3, "Error 15"); + assertTrue(CValues.cValueEq(sf1.getD("SpecOrigin"), 12990214.56177617), "Error 15: " + sf1.getD("SpecOrigin")); + } + + // Regressions: the Unit differs between the two SpecFrames together with the System, the + // RestFreq or the StdOfRest, so the conversion is more than a change of units. + + @Test + void unitsAndSystemDifferTogether() { + assertConverts( + "System=VRAD,Unit=km/s,RestFreq=230", + "System=VOPT,Unit=m/s,RestFreq=230", + 10.0, + true, + 10000.333575262843, + "CmpMap"); + } + + @Test + void unitsRestFreqAndStdOfRestDifferTogether() { + assertConverts( + "System=VRAD,Unit=km/s,RestFreq=230,StdOfRest=Helio", + "System=VRAD,Unit=m/s,RestFreq=345,StdOfRest=LSRK", + 10.0, + true, + 99937679.32679091, + "CmpMap"); + } + + @Test + void identicalSpecFramesConvertWithAUnitMap() { + String a = "System=VRAD,RestFreq=230,StdOfRest=LSRK"; + assertConverts(a, a, 10.0, true, 10.0, "UnitMap"); + assertConverts("", "", 5000.0, true, 5000.0, "UnitMap"); + SpecFrame f = make(a); + assertEquals("UnitMap", mappingClass(converted(f, f))); + } + + /** + * A FrameSet whose current Frame is a SpecFrame keeps its integrity when the System, StdOfRest, + * RestFreq, Unit or SourceVel of that Frame is set through it: the current Frame is remapped by + * the conversion from the Frame before the change to the Frame after it, aligned as the old + * Frame's AlignSystem and AlignStdOfRest say (with C's {@code AST__INTFLAG}, the alignment Frame + * keeps its own rest frame properties). Changing only how two SpecFrames are aligned changes no + * Mapping. + */ + @Test + void framesetIntegrityFollowsTheCLibrary() { + Object[][] cases = { + {"System=VRAD,RestFreq=230", "System=FREQ", 10.0, 229.99232802581045, "CmpMap", "FREQ"}, + {"System=VRAD,RestFreq=230", "StdOfRest=LSRK", 10.0, 10.289990186390046, "CmpMap", "VRAD"}, + {"System=VRAD,RestFreq=230", "RestFreq=345", 10.0, 99937.48600000002, "CmpMap", "VRAD"}, + {"System=VRAD,RestFreq=230", "Unit(1)=m/s", 10.0, 10000.0, "ZoomMap", "VRAD"}, + {"System=FREQ,StdOfRest=Source,RestFreq=230", "SourceVel=100", 230.0, 230.07673254164038, "CmpMap", "FREQ"}, + {"System=VRAD,RestFreq=230", "AlignStdOfRest=LSRK", 10.0, 10.0, "UnitMap", "VRAD"}, + {"System=VRAD,RestFreq=230", "AlignSystem=VRAD,RestFreq=345", 10.0, 10.0, "UnitMap", "VRAD"}, + }; + for (Object[] c : cases) { + String what = c[0] + " then " + c[1]; + FrameSet fs = new FrameSet(new Frame(1)); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(1), make((String) c[0])); + fs.set((String) c[1]); + double got = fs.tran1(1, new double[] {(Double) c[2]}, true)[0]; + assertTrue(CValues.cValueEq(got, (Double) c[3]), what + ": got " + got + ", C gives " + c[3]); + assertEquals(c[4], mappingClass(fs), what); + assertEquals(c[5], fs.getC("System"), what); + } + } + + /** A set SpecOrigin is re-expressed when the System or StdOfRest changes. */ + @Test + void specOriginFollowsSystemAndStdOfRest() { + String base = "System=VRAD,StdOfRest=LSRK,RestFreq=230,SpecOrigin=10"; + SpecFrame f = make(base); + f.set("System=WAVE"); + assertEquals("Angstrom", f.getUnit(1)); + assertTrue(CValues.cValueEq(f.getD("SpecOrigin"), 13034889.492764141), "WAVE: " + f.getD("SpecOrigin")); + f = make(base); + f.set("StdOfRest=Helio"); + assertTrue(CValues.cValueEq(f.getD("SpecOrigin"), 9.710009533114343), "Helio: " + f.getD("SpecOrigin")); + } + + // Review Focus 1: a standard of rest needs a reference position, an Epoch or an observer + // position. With UseDefs true (the default) an unset one takes its default, as C's does; with + // UseDefs false the conversion fails with AST__NOVAL, naming the first one C checks. + + private static final String REF = "RefRA=10:00:00,RefDec=20:00:00"; + + private static final String SOR_MESSAGE = + "astMatch(SpecFrame): Cannot convert between different standards of rest."; + + /** Each case converts 230 GHz, or 10 km/s from a radio velocity. */ + @Test + void unsetAttributesTakeTheirDefaults() { + String helio = "System=FREQ,StdOfRest=Helio,"; + Object[][] cases = { + {"System=FREQ,StdOfRest=Topo", "System=FREQ,StdOfRest=Helio", 230.02250828722228}, + {"System=FREQ,StdOfRest=Topo," + REF + ",Epoch=2005.0", helio + REF + ",Epoch=2005.0", 229.9835593392818}, + {"System=FREQ,StdOfRest=Topo," + REF + ",ObsLon=W30,ObsLat=N20,ObsAlt=1000", helio + REF, 229.98408837024638 + }, + {"System=FREQ,StdOfRest=Geo," + REF, helio + REF, 229.98377836897598}, + {"System=FREQ,StdOfRest=Bary," + REF, helio + REF, 229.9999885899968}, + {"System=FREQ,StdOfRest=LSRK", "System=FREQ,StdOfRest=Helio", 230.00022248735908}, + {"System=FREQ,StdOfRest=Source," + REF + ",RestFreq=230", helio + REF, 229.99999999999997}, + {"System=FREQ,StdOfRest=Source," + REF + ",RestFreq=230,SourceVel=100", helio + REF, 229.923293049313}, + {"System=VRAD", "System=FREQ", 99996.66435904801}, + { + "UseDefs=0,System=FREQ,StdOfRest=Topo," + REF + ",ObsLon=W30,ObsLat=N20,ObsAlt=1000,Epoch=2005.0", + "UseDefs=0," + helio + REF + ",Epoch=2005.0", + 229.98371973623955 + }, + { + "UseDefs=0,System=VRAD,StdOfRest=Helio,RestFreq=230", + "UseDefs=0,System=FREQ,StdOfRest=Helio", + 229.99232802581045 + }, + }; + for (Object[] c : cases) { + assertConverts( + (String) c[0], + (String) c[1], + c[0].toString().contains("System=VRAD") ? 10.0 : 230.0, + true, + (Double) c[2], + "CmpMap"); + } + } + + @Test + void unsetAttributesAreRefusedWithoutUseDefs() { + String noDefs = "UseDefs=0,"; + String helio = noDefs + "System=FREQ,StdOfRest=Helio"; + assertNoValue( + noDefs + "System=FREQ,StdOfRest=Topo", + helio, + SOR_MESSAGE + "\nNo value has been set for the AST" + " \"RefRA\" attribute (source RA)."); + assertNoValue( + noDefs + "System=FREQ,StdOfRest=Topo," + REF + ",Epoch=2005.0", + helio + "," + REF + ",Epoch=2005.0", + SOR_MESSAGE + "\nNo value has been set for the AST \"ObsLon\" attribute (observer's longitude)."); + String epoch = SOR_MESSAGE + "\nNo value has been set for the AST \"Epoch\" attribute (epoch of observation)."; + assertNoValue( + noDefs + "System=FREQ,StdOfRest=Topo," + REF + ",ObsLon=W30,ObsLat=N20,ObsAlt=1000", + helio + "," + REF, + epoch); + assertNoValue(noDefs + "System=FREQ,StdOfRest=Geo," + REF, helio + "," + REF, epoch); + assertNoValue(noDefs + "System=FREQ,StdOfRest=Bary," + REF, helio + "," + REF, epoch); + assertNoValue( + noDefs + "System=FREQ,StdOfRest=LSRK", + helio, + SOR_MESSAGE + "\nNo value has been set for the AST" + " \"RefRA\" attribute (source RA)."); + assertNoValue( + noDefs + "System=FREQ,StdOfRest=LSRK,RefRA=10:00:00", + helio + "," + REF, + SOR_MESSAGE + "\nNo value has been set for the AST \"RefDec\" attribute (source Dec)."); + assertNoValue( + helio + "," + REF, + noDefs + "System=FREQ,StdOfRest=LSRK", + SOR_MESSAGE + "\nNo value has been set for the AST \"RefRA\" attribute (source RA)."); + assertNoValue( + noDefs + "System=FREQ,StdOfRest=Source," + REF + ",RestFreq=230", + helio + "," + REF, + "astMatch(SpecFrame): Cannot convert source velocity to a new standard of rest.\nNo value has been" + + " set for the AST \"SourceVel\" attribute (source velocity)."); + String spectral = "astMatch(SpecFrame): Cannot convert between spectral systems.\nNo value has been set for" + + " the AST "; + assertNoValue(noDefs + "System=FREQ", helio, spectral + "\"StdOfRest\" attribute (spectral standard of rest)."); + assertNoValue( + noDefs + "System=VRAD,StdOfRest=Helio", helio, spectral + "\"RestFreq\" attribute (rest frequency)."); + assertNoValue( + helio, noDefs + "System=VRAD,StdOfRest=Helio", spectral + "\"RestFreq\" attribute (rest frequency)."); + } + + // Review Focus 3: converting and finding Frames, SpecFrames or FrameSets holding one, leave the + // Frames given as they were, and conversions in two threads, each between its own copies, give + // the same Mapping. + + @Test + void convertLeavesBothFramesAsTheyWere() { + SpecFrame a = make("System=VRAD,Unit=m/s,RestFreq=230,StdOfRest=Topo,ObsLon=W30,ObsLat=N20,Epoch=2005.0," + REF + + ",SpecOrigin=12,AlignStdOfRest=LSRK"); + SpecFrame b = make("System=WAVE,RestFreq=345,StdOfRest=LSRK," + REF + ",AlignSpecOffset=1"); + SpecFrame c = make("UseDefs=0,System=FREQ,StdOfRest=Geo"); + String da = ChannelText.dump(a); + String db = ChannelText.dump(b); + String dc = ChannelText.dump(c); + assertNotNull(a.convert(b, "")); + assertNotNull(b.convert(a, "")); + assertNotNull(a.findFrame(b, "")); + assertNotNull(b.findFrame(a, "")); + assertThrows(AstException.class, () -> c.convert(a, "")); + assertThrows(AstException.class, () -> a.convert(c, "")); + assertEquals(da, ChannelText.dump(a)); + assertEquals(db, ChannelText.dump(b)); + assertEquals(dc, ChannelText.dump(c)); + + // astConvert sets the Base of a FrameSet it is given to the Frame it used (frameset.c + // ConvertX), as AST documents; the Frames the FrameSet holds are left as they were. + FrameSet fs = new FrameSet(new Frame(1)); + fs.addFrame(FrameSet.AST__BASE, new UnitMap(1), make("System=FREQ,RestFreq=230,StdOfRest=Bary," + REF)); + String dbase = ChannelText.dump(fs.getFrame(1)); + String dcur = ChannelText.dump(fs.getFrame(2)); + assertNotNull(fs.findFrame(b, "")); + assertNotNull(fs.convert(a, "")); + assertNotNull(a.convert(fs, "")); + assertEquals(dbase, ChannelText.dump(fs.getFrame(1))); + assertEquals(dcur, ChannelText.dump(fs.getFrame(2))); + assertEquals(2, fs.getCurrent()); + assertEquals(da, ChannelText.dump(a)); + assertEquals(db, ChannelText.dump(b)); + } + + // ExecutorService is not AutoCloseable before Java 19; the pool is shut down in the finally block. + @SuppressWarnings("PMD.CloseResource") + @Test + void twoThreadsConvertingCopiesGetIdenticalMappings() throws Exception { + SpecFrame a = make("System=VRAD,Unit=m/s,RestFreq=230,StdOfRest=Topo,ObsLon=W30,ObsLat=N20,Epoch=2005.0," + REF + + ",SpecOrigin=12"); + SpecFrame b = make("System=WAVE,RestFreq=345,StdOfRest=LSRK," + REF); + String want = ChannelText.dump(a.convert(b, "").getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT)); + int nthread = 2; + SpecFrame[][] copies = new SpecFrame[nthread][]; + for (int i = 0; i < nthread; i++) { + copies[i] = new SpecFrame[] {(SpecFrame) a.copy(), (SpecFrame) b.copy()}; + } + // MODERN-JAVA(19): try-with-resources on the ExecutorService + ExecutorService pool = Executors.newFixedThreadPool(nthread); + try { + List> results = new ArrayList<>(); + for (int i = 0; i < nthread; i++) { + SpecFrame[] pair = copies[i]; + results.add(pool.submit(() -> { + String last = null; + for (int r = 0; r < 50; r++) { + String d = ChannelText.dump( + pair[0].convert(pair[1], "").getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT)); + if (last != null && !last.equals(d)) { + return "changed between repeats"; + } + last = d; + } + return last; + })); + } + for (Future f : results) { + assertEquals(want, f.get()); + } + } finally { + pool.shutdown(); + assertTrue(pool.awaitTermination(1, TimeUnit.MINUTES), "threads finished"); + } + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecMap3dOracleTest.java b/src/test/java/uk/ac/starlink/ast/SpecMap3dOracleTest.java new file mode 100644 index 0000000..1d98e85 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecMap3dOracleTest.java @@ -0,0 +1,124 @@ +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 com.fasterxml.jackson.databind.JsonNode; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_specmap_3d.rs}: a 3-dimensional SpecMap, whose second and + * third axes give the RA and Dec of each point's source, matches C's (specmap.c {@code Transform} + * and {@code FrameChange}). Each case of {@code oracle/specmap_3d.json} (C probe {@code + * specmap_3d_probe.c}) loads with three axes and is written again as C writes it, and its forward + * and inverse transformations, of points that include bad values, equal C's bit for bit. A run of + * 3-dimensional SpecMaps simplifies as C's does. + */ +class SpecMap3dOracleTest { + + private static JsonNode consts() { + return ProbeData.load("specmap_3d"); + } + + private static String text(JsonNode lines) { + StringBuilder sb = new StringBuilder(); + for (JsonNode l : lines) { + sb.append(l.asText()).append('\n'); + } + return sb.toString(); + } + + /** The points of {@code rows}, one row per point, as {@code [axis][point]}. */ + private static double[][] columns(JsonNode rows) { + double[][] cols = new double[3][rows.size()]; + for (int p = 0; p < rows.size(); p++) { + for (int c = 0; c < 3; c++) { + cols[c][p] = ProbeData.toDouble(rows.get(p).get(c)); + } + } + return cols; + } + + private static boolean differs(double[][] got, double[][] want) { + for (int c = 0; c < 3; c++) { + for (int p = 0; p < want[c].length; p++) { + if (Double.doubleToRawLongBits(got[c][p]) != Double.doubleToRawLongBits(want[c][p])) { + return true; + } + } + } + return false; + } + + @Test + void transformationsMatchTheCLibrary() { + JsonNode cases = consts().get("CASES"); + List failures = new ArrayList<>(); + for (JsonNode c : cases) { + String name = c.get(0).asText(); + String dump = text(c.get(1)); + AstObject obj = ChannelText.read(dump); + String got = ChannelText.dump(obj); + if (!got.equals(dump)) { + failures.add(name + " re-dump:\n" + got + "\nC gives:\n" + dump); + } + Mapping map = (Mapping) obj; + assertEquals(3, map.getNin(), name); + double[][] in = columns(c.get(2)); + for (int d = 0; d < 2; d++) { + boolean forward = d == 0; + double[][] want = columns(c.get(3 + d)); + double[][] out = map.transform(in, in[0].length, forward); + if (differs(out, want)) { + failures.add(name + " forward=" + forward + ": " + Arrays.deepToString(out) + ", C gives " + + Arrays.deepToString(want)); + } + } + } + assertEquals(4, cases.size()); + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } + + @Test + void aBuiltSpecmapDumpsAsCDoes() { + SpecMap map = new SpecMap(3, 0); + map.specAdd("LKF2HL", new double[] {0.1, 0.2}); + String want = null; + for (JsonNode c : consts().get("CASES")) { + if ("lsrk".equals(c.get(0).asText())) { + want = text(c.get(1)); + } + } + assertEquals(want, ChannelText.dump(map)); + } + + @Test + void onlyOneOrThreeAxes() { + for (int nin : new int[] {0, 2, 4}) { + AstException e = assertThrows(AstException.class, () -> new SpecMap(nin, 0), "nin " + nin); + assertEquals(AstException.AST__BADNI, e.getStatus(), "nin " + nin); + } + } + + @Test + void simplificationMatchesTheCLibrary() { + JsonNode cases = consts().get("SIMPLIFY_CASES"); + List failures = new ArrayList<>(); + for (JsonNode c : cases) { + String name = c.get(0).asText(); + Mapping map = (Mapping) ChannelText.read(text(c.get(1))); + String got = ChannelText.dump(map.simplify()); + String want = text(c.get(2)); + if (!got.equals(want)) { + failures.add(name + ":\n" + got + "\nC gives:\n" + want); + } + } + assertEquals(2, cases.size()); + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecMapTest.java b/src/test/java/uk/ac/starlink/ast/SpecMapTest.java new file mode 100644 index 0000000..4286716 --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecMapTest.java @@ -0,0 +1,482 @@ +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.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.LinkedHashMap; +import java.util.Locale; +import java.util.Map; +import org.junit.jupiter.api.Test; +import uk.ac.starlink.ast.testsupport.CValues; + +/** + * Translation of Rust {@code tests/test_specmap.rs}, itself from C's {@code testspecmap.c}: the + * spectral conversions, alone and chained, in both directions, the changes of rest frame, bad + * values, the rate and native round trips. + * + *

    {@code code_roundtrip} and {@code inverse_pairs} are translated as the behaviour C gives the + * codes: each code {@code astSpecAdd} accepts is written back by name, and simplifying an inverted + * SpecMap gives the inverse conversion. {@code specmap_always_merges_adjacent} becomes a + * simplification of the two SpecMaps in a series CmpMap. Deferred: {@code equality} ({@code + * astEqual}, an out-of-scope method). + */ +class SpecMapTest { + + private static final double C_LIGHT = 2.99792458e8; + private static final double H_PLANCK = 6.6260755e-34; + private static final double BAD = AstObject.AST__BAD; + + /** Every conversion C's {@code CvtCode} recognises, with arguments of the number it takes. */ + private static final Map CONVERSIONS = allConversions(); + + private static Map allConversions() { + Map m = new LinkedHashMap<>(); + double[] none = new double[0]; + m.put("FRTOVL", new double[] {1.42e9}); + m.put("VLTOFR", new double[] {1.42e9}); + for (String c : new String[] { + "ENTOFR", "FRTOEN", "WNTOFR", "FRTOWN", "WVTOFR", "FRTOWV", "AWTOFR", "FRTOAW", "VRTOVL", "VLTOVR", + "VOTOVL", "VLTOVO", "ZOTOVL", "VLTOZO", "BTTOVL", "VLTOBT" + }) { + m.put(c, none); + } + m.put("USF2HL", new double[] {30000.0, 1.0, 0.5}); + m.put("HLF2US", new double[] {30000.0, 1.0, 0.5}); + m.put("TPF2HL", new double[] {-0.1, 0.9, 100.0, 53000.0, 1.0, 0.5}); + m.put("HLF2TP", new double[] {-0.1, 0.9, 100.0, 53000.0, 1.0, 0.5}); + for (String c : new String[] {"GEF2HL", "HLF2GE", "BYF2HL", "HLF2BY"}) { + m.put(c, new double[] {53000.0, 1.5, 0.3}); + } + for (String c : new String[] {"LKF2HL", "HLF2LK", "LDF2HL", "HLF2LD", "LGF2HL", "HLF2LG", "GLF2HL", "HLF2GL"}) { + m.put(c, new double[] {1.0, 0.5}); + } + return m; + } + + /** The name of the conversion that inverts {@code code}: "AATOBB" for "BBTOAA", "HLF2XX" for "XXF2HL". */ + private static String inverseName(String code) { + String sep = code.substring(2, 4); + return code.substring(4) + sep + code.substring(0, 2); + } + + private static SpecMap spec(String cvt, double... args) { + SpecMap m = new SpecMap(1, 0); + m.specAdd(cvt, args); + return m; + } + + private static double transformOne(Mapping m, double val, boolean forward) { + return m.transform(new double[][] {{val}}, 1, forward)[0][0]; + } + + private static double fwd(Mapping m, double val) { + return transformOne(m, val, true); + } + + private static void assertRel(double got, double want, double rtol, String label) { + assertTrue(Math.abs(got - want) / Math.abs(want) < rtol, label + ": got " + got + ", expected " + want); + } + + // ------------------------------------------------------------------ + // Changes of system + // ------------------------------------------------------------------ + + @Test + void freqToWavelength() { + double wv = fwd(spec("FRTOWV"), 5.0e14); + assertTrue(Math.abs(wv - C_LIGHT / 5.0e14) < 1e-20, "FrToWv: got " + wv); + } + + @Test + void freqToEnergy() { + assertRel(fwd(spec("FRTOEN"), 5.0e14), H_PLANCK * 5.0e14, 1e-10, "FrToEn"); + } + + @Test + void energyToFreq() { + assertRel(fwd(spec("ENTOFR"), 3.313e-19), 3.313e-19 / H_PLANCK, 1e-10, "EnToFr"); + } + + @Test + void roundtripFreqWavelength() { + SpecMap m = spec("FRTOWV"); + m.specAdd("WVTOFR", null); + assertRel(fwd(m, 4.567e14), 4.567e14, 1e-12, "freq->wv->freq"); + } + + @Test + void roundtripFreqVelocity() { + SpecMap m = spec("FRTOVL", 1.42e9); + m.specAdd("VLTOFR", new double[] {1.42e9}); + assertRel(fwd(m, 1.41e9), 1.41e9, 1e-12, "freq->vel->freq"); + } + + @Test + void freqToWavenum() { + assertRel(fwd(spec("FRTOWN"), 3.0e14), 3.0e14 / C_LIGHT, 1e-12, "FrToWn"); + } + + @Test + void wavenumToFreq() { + assertRel(fwd(spec("WNTOFR"), 1.0e6), 1.0e6 * C_LIGHT, 1e-12, "WnToFr"); + } + + @Test + void betaToVelocity() { + double vel = fwd(spec("BTTOVL"), 0.5); + assertTrue(Math.abs(vel - 0.5 * C_LIGHT) < 1.0, "BtToVl: got " + vel); + } + + @Test + void velocityToBeta() { + double beta = fwd(spec("VLTOBT"), 1.5e8); + assertTrue(Math.abs(beta - 1.5e8 / C_LIGHT) < 1e-12, "VlToBt: got " + beta); + } + + @Test + void roundtripRedshiftVelocity() { + SpecMap m = spec("ZOTOVL"); + m.specAdd("VLTOZO", new double[0]); + double z = fwd(m, 0.1); + assertTrue(Math.abs(z - 0.1) < 1e-12, "z->v->z: got " + z); + } + + @Test + void roundtripRadioVelocity() { + SpecMap m = spec("VRTOVL"); + m.specAdd("VLTOVR", new double[0]); + assertRel(fwd(m, 1.0e7), 1.0e7, 1e-12, "vr->vl->vr"); + } + + @Test + void roundtripOpticalVelocity() { + SpecMap m = spec("VOTOVL"); + m.specAdd("VLTOVO", new double[0]); + assertRel(fwd(m, 5.0e7), 5.0e7, 1e-12, "vo->vl->vo"); + } + + @Test + void roundtripAirWavelength() { + SpecMap m = spec("FRTOAW"); + m.specAdd("AWTOFR", new double[0]); + assertRel(fwd(m, 5.0e14), 5.0e14, 1e-10, "freq->air wv->freq"); + } + + @Test + void freqToVelocity() { + SpecMap m = spec("FRTOVL", 1.42e9); + double vel = fwd(m, 1.42e9); + assertTrue(Math.abs(vel) < 1.0e-5, "FrToVl at the rest frequency: got " + vel); + // v = c * (rf^2 - f^2) / (rf^2 + f^2) = c * 0.6 at half the rest frequency. + assertRel(fwd(m, 1.42e9 / 2.0), C_LIGHT * 0.6, 1e-10, "FrToVl at rf/2"); + } + + @Test + void velocityToFreq() { + assertRel(fwd(spec("VLTOFR", 1.42e9), 0.0), 1.42e9, 1e-12, "VlToFr at v=0"); + } + + @Test + void multistepChain() { + double air = fwd(spec("FRTOAW"), 5.0e14); + double vac = fwd(spec("FRTOWV"), 5.0e14); + assertTrue(air < vac, "air wavelength " + air + " should be less than vacuum " + vac); + assertTrue(Math.abs(vac / air - 1.0) < 0.001, "refractive index " + vac / air); + } + + // ------------------------------------------------------------------ + // The rate + // ------------------------------------------------------------------ + + /** specmap.c {@code Rate}: a lone wavelength to frequency step has the rate -c/x^2. */ + @Test + void rateWvtofrIsAnalytic() { + double wave = 0.21106199521261618; + double rate = spec("WVTOFR").rate(new double[] {wave}, 1, 1); + double want = -C_LIGHT / (wave * wave); + assertTrue(Math.abs(rate - want) <= 1e-12 * Math.abs(want), "WvToFr rate " + rate); + } + + /** specmap.c {@code Rate} reads the first conversion's code, whatever the Invert attribute. */ + @Test + void rateFrtowvIsAnalytic() { + double freq = 1.4204e9; + double rate = spec("FRTOWV").rate(new double[] {freq}, 1, 1); + double want = -C_LIGHT / (freq * freq); + assertTrue(Math.abs(rate - want) <= 1e-12 * Math.abs(want), "FrToWv rate " + rate); + } + + /** More than one step: the rate is estimated as the Mapping class estimates it. */ + @Test + void rateMultistepFallsBackToNumeric() { + SpecMap m = spec("FRTOWV"); + m.specAdd("WVTOFR", new double[0]); + double rate = m.rate(new double[] {1.4204e9}, 1, 1); + assertTrue(Math.abs(rate - 1.0) <= 1e-6, "multi-step rate " + rate); + } + + // ------------------------------------------------------------------ + // Changes of rest frame + // ------------------------------------------------------------------ + + @Test + void lsrkCorrection() { + double freq = 1.42e9; + double shifted = fwd(spec("LKF2HL", Math.PI / 4.0, Math.PI / 6.0), freq); + assertTrue(Math.abs(shifted - freq) > 1.0, "LSRK shift " + Math.abs(shifted - freq)); + assertTrue(Math.abs(shifted - freq) / freq < 0.001, "LSRK shift " + Math.abs(shifted - freq) / freq); + } + + private static void assertRoundTrip(String x2hl, String hl2x, double freq, double rtol, double... args) { + SpecMap m = spec(x2hl, args); + m.specAdd(hl2x, args); + assertRel(fwd(m, freq), freq, rtol, x2hl + " then " + hl2x); + } + + @Test + void lsrkRoundtrip() { + assertRoundTrip("LKF2HL", "HLF2LK", 1.42e9, 1e-12, 1.0, 0.5); + } + + @Test + void lsrdRoundtrip() { + assertRoundTrip("LDF2HL", "HLF2LD", 5.0e14, 1e-12, 2.0, -0.3); + } + + @Test + void lgRoundtrip() { + assertRoundTrip("LGF2HL", "HLF2LG", 1.0e10, 1e-12, 0.5, 0.8); + } + + @Test + void galacticRoundtrip() { + assertRoundTrip("GLF2HL", "HLF2GL", 2.0e9, 1e-12, 3.0, -1.0); + } + + @Test + void geocentricRoundtrip() { + assertRoundTrip("GEF2HL", "HLF2GE", 1.42e9, 1e-12, 53000.0, 1.5, 0.3); + } + + @Test + void barycentricRoundtrip() { + assertRoundTrip("BYF2HL", "HLF2BY", 1.42e9, 1e-12, 53000.0, 2.5, -0.5); + } + + @Test + void topocentricRoundtrip() { + assertRoundTrip("TPF2HL", "HLF2TP", 1.42e9, 1e-10, -0.1, 0.9, 100.0, 53000.0, 1.0, 0.5); + } + + @Test + void userDefinedRoundtrip() { + assertRoundTrip("USF2HL", "HLF2US", 1.42e9, 1e-12, 30000.0, 1.0, 0.5); + } + + /** + * testspecmap.c {@code check_topocentric_frequency}, with its wanted value. The observer's + * Earth-rotation velocity comes from PAL in au/s and is converted back to km/s with the au PAL + * used, ERFA's {@code ERFA_DAU}. + */ + @Test + void topocentricToHeliocentricFrequency() { + // OBSLON, OBSLAT, OBSALT, EPOCH, RA, DEC; the RA is the C test's, close to pi/2 but not it. + double out = fwd(spec("TPF2HL", -2.71, 0.34, 4200.0, 60000.0, 1.570796326794896, 0.1), 1.0e9); + double want = 1000085270.7870382; + assertTrue(Math.abs(out - want) <= 2.0e-6, "TPF2HL gives " + out + " Hz, expected " + want); + } + + // ------------------------------------------------------------------ + // Inversion, bad values and simplification + // ------------------------------------------------------------------ + + @Test + void inversion() { + SpecMap m = spec("FRTOVL", 1.42e9); + double freq = 1.41e9; + double vel = fwd(m, freq); + assertRel(transformOne(m, vel, false), freq, 1e-12, "inverse"); + Mapping m2 = (Mapping) m.copy(); + m2.invert(); + assertRel(fwd(m2, vel), freq, 1e-12, "inverted forward"); + } + + @Test + void badValuePropagation() { + assertEquals(BAD, fwd(spec("FRTOWV"), BAD)); + } + + /** + * specmap.c {@code SystemChange}: ENTOFR does not test its result, so an overflow gives an + * infinity, while FRTOWV makes a result that is not finite bad. + */ + @Test + void anOverflowIsKeptWhereCKeepsIt() { + assertEquals(Double.POSITIVE_INFINITY, fwd(spec("ENTOFR"), 1.0e308)); + assertEquals(BAD, fwd(spec("FRTOWV"), Double.MIN_VALUE)); + } + + /** + * specmap.c {@code MapMerge}: SpecMaps in series always merge into one, whether or not any of + * their conversions cancel. + */ + @Test + void specmapAlwaysMergesAdjacent() { + Mapping s = new CmpMap(spec("FRTOWV"), spec("VRTOVL"), true).simplify(); + assertInstanceOf(SpecMap.class, s); + String dump = ChannelText.dump(s); + assertTrue(dump.contains("Spec1 = \"FRTOWV\"") && dump.contains("Spec2 = \"VRTOVL\""), dump); + } + + /** + * specmap.c {@code CvtCode} and {@code CvtString}: every code is accepted, in any case and + * with trailing spaces, and written back by its name. + */ + @Test + void codeRoundtrip() { + for (Map.Entry e : CONVERSIONS.entrySet()) { + String code = e.getKey(); + for (String given : new String[] {code, code.toLowerCase(Locale.ROOT) + " "}) { + String dump = ChannelText.dump(spec(given, e.getValue())); + assertTrue(dump.contains("Spec1 = \"" + code + "\""), given + ":\n" + dump); + } + } + assertEquals(34, CONVERSIONS.size()); + } + + /** + * specmap.c {@code MapMerge}: simplifying an inverted SpecMap gives a SpecMap applying the + * inverse conversion forward, and doing that twice gives the original conversion. + */ + @Test + void inversePairs() { + for (Map.Entry e : CONVERSIONS.entrySet()) { + String code = e.getKey(); + String inverse = inverseName(code); + assertTrue(CONVERSIONS.containsKey(inverse), code); + SpecMap m = spec(code, e.getValue()); + m.invert(); + Mapping once = m.simplify(); + assertInstanceOf(SpecMap.class, once, code); + assertFalse(once.getInvert(), code); + assertTrue(ChannelText.dump(once).contains("Spec1 = \"" + inverse + "\""), code); + Mapping twice = (Mapping) once.copy(); + twice.invert(); + twice = twice.simplify(); + assertTrue(ChannelText.dump(twice).contains("Spec1 = \"" + code + "\""), code); + } + } + + // ------------------------------------------------------------------ + // Arguments and errors + // ------------------------------------------------------------------ + + /** specmap.c {@code SpecAdd}: an unknown code is AST__SPCIN. */ + @Test + void anUnknownCodeIsRefused() { + SpecMap m = new SpecMap(1, 0); + AstException e = assertThrows(AstException.class, () -> m.specAdd("FRTOXX", new double[0])); + assertEquals(AstException.AST__SPCIN, e.getStatus()); + } + + /** specmap.c {@code AddSpecCvt}: each conversion takes exactly its number of arguments. */ + @Test + void eachConversionTakesExactlyItsArguments() { + for (Map.Entry e : CONVERSIONS.entrySet()) { + int n = e.getValue().length; + SpecMap m = new SpecMap(1, 0); + AstException ex = + assertThrows(AstException.class, () -> m.specAdd(e.getKey(), new double[n + 1]), e.getKey()); + assertEquals(AstException.AST__TIMIN, ex.getStatus(), e.getKey()); + m.specAdd(e.getKey(), e.getValue()); + } + } + + // ------------------------------------------------------------------ + // Native round trips + // ------------------------------------------------------------------ + + @Test + void serialisationRoundtrip() { + SpecMap m = spec("FRTOWV"); + m.specAdd("WVTOFR", new double[0]); + m.specAdd("FRTOVL", new double[] {1.42e9}); + m.specAdd("LKF2HL", new double[] {1.0, 0.5}); + AstObject back = ChannelText.read(ChannelText.dump(m)); + assertInstanceOf(SpecMap.class, back); + assertTrue(Math.abs(fwd(m, 1.42e9) - fwd((Mapping) back, 1.42e9)) < 1e-6); + } + + /** + * A SpecMap holding every conversion is written with C's comments, reads back as the same + * SpecMap, and transforms as the original does. + */ + @Test + void everyConversionSurvivesANativeRoundTrip() { + for (int nin : new int[] {1, 3}) { + SpecMap m = new SpecMap(nin, 0); + for (Map.Entry e : CONVERSIONS.entrySet()) { + m.specAdd(e.getKey(), e.getValue()); + } + String dump = ChannelText.dump(m); + assertTrue(dump.contains("Nspec = 34 \t# Number of conversion steps"), dump); + assertTrue(dump.contains("Spec22d = 53000 \t# UT1 epoch of observaton (Modified Julian Date)"), dump); + AstObject back = ChannelText.read(dump); + assertInstanceOf(SpecMap.class, back); + assertEquals(dump, ChannelText.dump(back)); + double[][] in = nin == 1 + ? new double[][] {{1.0e9, 1.42e9, BAD}} + : new double[][] {{1.0e9, 1.42e9, BAD}, {1.0, 2.0, 3.0}, {0.5, -0.5, 0.1}}; + for (boolean forward : new boolean[] {true, false}) { + double[][] want = m.transform(in, 3, forward); + double[][] got = ((Mapping) back).transform(in, 3, forward); + for (int c = 0; c < nin; c++) { + assertArrayEquals(want[c], got[c], "nin " + nin + " forward " + forward); + } + } + } + } + + /** + * specmap.c {@code FrameChange} keeps the frequency correction factor of a 1-dimensional + * SpecMap's change of rest frame in the conversion's arguments once it has found it, so a + * SpecMap written after it has transformed points carries the factor. The arguments and + * factors are those of the SpecMaps of C fixture {@code simplify/cap_specmap_06.map}. + */ + @Test + void theFrequencyCorrectionFactorIsKeptAndWritten() { + SpecMap m = spec("USF2HL", 70700.96444689816, -1.3776320118304248, -0.06981317007977327); + m.specAdd("HLF2TP", new double[] { + -2.71363307300091, 0.346026069000144, 0, 54299.24556318331, -1.3776320118304248, -0.06981317007977327 + }); + String before = ChannelText.dump(m); + assertFalse(before.contains("Frequency correction factor"), before); + transformOne(m, 1.0e11, true); + String after = ChannelText.dump(m); + String want = before.replace( + " Spec2 = ", + " Spec1d = 0.99976419476969891 \t# Frequency correction factor\n Spec2 = ") + .replace( + " End SpecMap", + " Spec2g = 0.99997927106231288 \t# Frequency correction factor\n End SpecMap"); + assertTrue(CValues.nativeStringsWithinLibmRounding(after, want), after + "\nC gives:\n" + want); + } + + /** specmap.c {@code astLoadSpecMap}: a missing or unknown conversion is AST__BADIN. */ + @Test + void aLoadNeedsKnownConversions() { + String head = ChannelText.text( + " Begin SpecMap", " Nin = 1", " IsA Mapping", " Nspec = 2", " Spec1 = \"FRTOWV\""); + AstException e = + assertThrows(AstException.class, () -> ChannelText.read(head + ChannelText.text(" End SpecMap"))); + assertEquals(AstException.AST__BADIN, e.getStatus()); + e = assertThrows( + AstException.class, + () -> ChannelText.read(head + ChannelText.text(" Spec2 = \"XXTOYY\"", " End SpecMap"))); + assertEquals(AstException.AST__BADIN, e.getStatus()); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecOriginSorOracleTest.java b/src/test/java/uk/ac/starlink/ast/SpecOriginSorOracleTest.java new file mode 100644 index 0000000..844d82c --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/SpecOriginSorOracleTest.java @@ -0,0 +1,128 @@ +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.CValues; +import uk.ac.starlink.ast.testsupport.ProbeData; + +/** + * Translation of Rust {@code tests/test_spec_origin_sor.rs}: a SpecOrigin and AlignSpecOffset + * through a change of StdOfRest, checked against C ({@code oracle/spec_origin_sor.json}, from + * {@code tools/oracle_fixtures/spec_origin_sor_probe.c}). Setting StdOfRest re-expresses a set + * SpecOrigin in the new rest frame with a conversion from the Frame to a copy of it, AlignSpecOffset + * included, and fails with {@code AST__ATSER} when the result is bad (specframe.c {@code + * OriginStdOfRest}). With AlignSpecOffset set on both Frames, the result's zero point is the target + * origin transformed through the conversion; in a wavelength System that has no value when no + * SpecOrigin is set, and the result's own origin is used instead (specframe.c {@code + * MakeSpecMapping}). + * + *

    The probe's DSBSpecFrames are in the lower sideband with AlignSideBand set and an IF of 4 + * GHz, and their DSBCentre is the value converted. + */ +class SpecOriginSorOracleTest { + + /** + * The probe's Frame: a SpecFrame, or a DSBSpecFrame with its DSBCentre, with its settings, + * reference position and SpecOrigin. + */ + private static SpecFrame build(String cls, String system, boolean offset, JsonNode origin, double value) { + SpecFrame f; + if ("DSBSpecFrame".equals(cls)) { + f = new DSBSpecFrame(); + f.set(system + ",StdOfRest=LSRK,Epoch=2005.0,IF=4,SideBand=LSB,AlignSideBand=1"); + } else if ("SpecFrame".equals(cls)) { + f = new SpecFrame(); + f.set(system + ",StdOfRest=LSRK,Epoch=2005.0"); + } else { + throw new IllegalArgumentException("unexpected class " + cls); + } + f.setRefPos(null, 2.6, 0.35); + if (f instanceof DSBSpecFrame) { + f.setD("DSBCentre", value); + } + f.setI("AlignSpecOffset", offset ? 1 : 0); + if (!origin.isNull()) { + f.setD("SpecOrigin", ProbeData.toDouble(origin)); + } + return f; + } + + /** StdOfRest=HELIO set on a copy, giving its SpecOrigin, "None" or the error. */ + private static String setHelio(SpecFrame f) { + SpecFrame g = (SpecFrame) f.copy(); + try { + g.set("StdOfRest=HELIO"); + } catch (AstException e) { + return e.getStatus() == AstException.AST__ATSER ? "Err:Atser" : "Err:" + e.getMessage(); + } + return g.test("SpecOrigin") ? Double.toString(g.getD("SpecOrigin")) : "None"; + } + + /** The value converted to a copy whose StdOfRest is HELIO, "None" or the error. */ + private static String convert(SpecFrame f, JsonNode origin, double value) { + try { + SpecFrame h = (SpecFrame) f.copy(); + h.clear("SpecOrigin"); + h.set("StdOfRest=HELIO"); + if (!origin.isNull()) { + h.setD("SpecOrigin", ProbeData.toDouble(origin)); + } + FrameSet fs = f.convert(h, ""); + if (fs == null) { + return "None"; + } + return Double.toString(fs.tran1(1, new double[] {value}, true)[0]); + } catch (AstException e) { + return e.getStatus() == AstException.AST__ATSER ? "Err:Atser" : "Err:" + e.getMessage(); + } + } + + /** The probe's result as this test writes it. */ + private static String want(JsonNode w) { + if ("Err".equals(w.get("variant").asText())) { + return "Err:" + w.get("value").asText(); + } + JsonNode v = w.get("value"); + return v == null || v.isNull() ? "None" : Double.toString(ProbeData.toDouble(v)); + } + + private static boolean same(String got, String want) { + if (got.equals(want)) { + return true; + } + if (got.startsWith("Err") || want.startsWith("Err") || "None".equals(got) || "None".equals(want)) { + return false; + } + return CValues.cValueEq(Double.parseDouble(got), Double.parseDouble(want)); + } + + @Test + void originThroughRestFrameChangeMatchesTheCLibrary() { + List failures = new ArrayList<>(); + int ran = 0; + for (JsonNode c : ProbeData.load("spec_origin_sor").get("CASES")) { + ran++; + String cls = c.get(0).asText(); + String system = c.get(1).asText(); + boolean offset = c.get(2).asBoolean(); + JsonNode origin = c.get(3); + double value = ProbeData.toDouble(c.get(4)); + SpecFrame f = build(cls, system, offset, origin, value); + String gotSet = setHelio(f); + String gotConv = convert(f, origin, value); + String wantSet = want(c.get(5)); + String wantConv = want(c.get(6)); + if (!same(gotSet, wantSet) || !same(gotConv, wantConv)) { + failures.add(cls + " [" + system + "] offset=" + offset + " origin=" + origin + ": got (" + gotSet + + ", " + gotConv + "), C gives (" + wantSet + ", " + wantConv + ")"); + } + } + assertEquals(16, ran, "the cases the C probe recorded"); + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } +} diff --git a/src/test/java/uk/ac/starlink/ast/SpecUseDefsTest.java b/src/test/java/uk/ac/starlink/ast/SpecUseDefsTest.java index 09884f0..711de78 100644 --- a/src/test/java/uk/ac/starlink/ast/SpecUseDefsTest.java +++ b/src/test/java/uk/ac/starlink/ast/SpecUseDefsTest.java @@ -11,21 +11,28 @@ import uk.ac.starlink.ast.testsupport.ProbeData; /** - * Translation of Rust {@code tests/test_spec_use_defs.rs}: what UseDefs=0 changes in a TimeFrame, - * checked against C ({@code oracle/spec_use_defs.json}, from {@code + * Translation of Rust {@code tests/test_spec_use_defs.rs}: what UseDefs=0 changes in a TimeFrame + * and in a SpecFrame's Title, checked against C ({@code oracle/spec_use_defs.json}, from {@code * tools/oracle_fixtures/spec_use_defs_probe.c}). Picking the axis of a TimeFrame whose TimeScale * is not set is refused with {@code AST__NOVAL} when UseDefs is false (timeframe.c {@code - * SubFrame} and {@code VerifyAttrs}); finding a TimeFrame in one is not. - * - *

    The TimeFrame cases of {@code conversions_match_the_c_library} run here; its SpecFrame and - * DSBSpecFrame cases, and {@code titles_match_the_c_library}, need a SpecFrame, outside the first - * phase. + * SubFrame} and {@code VerifyAttrs}); finding a TimeFrame in one is not. A SpecFrame's default + * Title leaves out a RestFreq that has not been set (specframe.c {@code GetTitle}). A change of + * sideband between DSBSpecFrames needs their IF and DSBCentre set (dsbspecframe.c {@code GetLO}). */ class SpecUseDefsTest { - /** The probe's {@code make}: a TimeFrame with the settings applied. */ - private static TimeFrame make(String settings) { - TimeFrame f = new TimeFrame(); + /** The probe's {@code make}: a TimeFrame, SpecFrame or DSBSpecFrame with the settings applied. */ + private static Frame make(String cls, String settings) { + Frame f; + if ("TimeFrame".equals(cls)) { + f = new TimeFrame(); + } else if ("SpecFrame".equals(cls)) { + f = new SpecFrame(); + } else if ("DSBSpecFrame".equals(cls)) { + f = new DSBSpecFrame(); + } else { + throw new IllegalArgumentException("unexpected class " + cls); + } if (!settings.isEmpty()) { f.set(settings); } @@ -33,8 +40,8 @@ private static TimeFrame make(String settings) { } /** The value 230 converted, "None" if there is no conversion, or "Err:Noval". */ - private static String convert(String target, String template) { - TimeFrame t = make(target); + private static String convert(String cls, String target, String template) { + Frame t = make(cls, target); Mapping map; try { if ("pick".equals(template)) { @@ -42,7 +49,7 @@ private static String convert(String target, String template) { t.pickAxes(1, new int[] {1}, m); map = m[0]; } else { - FrameSet fs = t.findFrame(make(template), ""); + FrameSet fs = t.findFrame(make(cls, template), ""); if (fs == null) { return "None"; } @@ -54,19 +61,43 @@ private static String convert(String target, String template) { return Double.toString(map.tran1(1, new double[] {230.0}, true)[0]); } + /** The probe's {@code make} for a SpecFrame: the comma-separated settings applied in order. */ + private static SpecFrame makeSpec(String settings) { + SpecFrame f = new SpecFrame(); + if (!settings.isEmpty()) { + f.set(settings); + } + return f; + } + + @Test + void titlesMatchTheCLibrary() { + List failures = new ArrayList<>(); + int ran = 0; + for (JsonNode c : ProbeData.load("spec_use_defs").get("TITLES")) { + ran++; + String settings = c.get(0).asText(); + String want = c.get(1).asText(); + String got = makeSpec(settings).getTitle(); + if (!got.equals(want)) { + failures.add("[" + settings + "]: got \"" + got + "\", C gives \"" + want + "\""); + } + } + assertEquals(5, ran, "the cases the C probe recorded"); + assertTrue(failures.isEmpty(), String.join("\n", failures)); + } + @Test void conversionsMatchTheCLibrary() { List failures = new ArrayList<>(); int ran = 0; for (JsonNode c : ProbeData.load("spec_use_defs").get("CONVERSIONS")) { - if (!"TimeFrame".equals(c.get(0).asText())) { - continue; - } + String cls = c.get(0).asText(); ran++; String target = c.get(1).asText(); String template = c.get(2).asText(); JsonNode w = c.get(3); - String got = convert(target, template); + String got = convert(cls, target, template); boolean ok; String want; if ("Err".equals(w.get("variant").asText())) { @@ -81,10 +112,10 @@ void conversionsMatchTheCLibrary() { ok = !got.startsWith("Err") && !"None".equals(got) && CValues.cValueEq(Double.parseDouble(got), v); } if (!ok) { - failures.add("[" + target + "] -> [" + template + "]: got " + got + ", C gives " + want); + failures.add(cls + " [" + target + "] -> [" + template + "]: got " + got + ", C gives " + want); } } - assertEquals(4, ran, "the TimeFrame cases"); + assertEquals(28, ran, "the cases the C probe recorded"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } } diff --git a/src/test/java/uk/ac/starlink/ast/SystemChangeTest.java b/src/test/java/uk/ac/starlink/ast/SystemChangeTest.java index 58a732b..d71af25 100644 --- a/src/test/java/uk/ac/starlink/ast/SystemChangeTest.java +++ b/src/test/java/uk/ac/starlink/ast/SystemChangeTest.java @@ -14,11 +14,8 @@ * to the other attributes of a TimeFrame, checked against C ({@code oracle/system_change.json}, * from {@code tools/oracle_fixtures/system_change_probe.c}). When the System changes, the Label, * Symbol and Title, whose defaults depend on it, are cleared, and the Unit last used with the new - * System is restored, or cleared (timeframe.c {@code SetSystem} and {@code ClearSystem}). {@link - * #run} makes each Frame as the probe does. - * - *

    The SpecFrame cases ({@code spec_*}) and the FluxFrame case ({@code flux_set_sfcbr}) are - * skipped (out of scope). + * System is restored, or cleared (timeframe.c and specframe.c {@code SetSystem} and {@code + * ClearSystem}, and those of fluxframe.c). {@link #run} makes each Frame as the probe does. */ class SystemChangeTest { @@ -32,6 +29,14 @@ private static TimeFrame time(String system) { return f; } + private static SpecFrame spec(String system, String unit) { + SpecFrame f = new SpecFrame(); + f.set("System=" + system); + f.setUnit(1, unit); + f.set(MINE); + return f; + } + /** The Frame a case leaves, or null for a case whose class is out of scope. */ private static Frame run(String name) { switch (name) { @@ -51,11 +56,31 @@ private static Frame run(String name) { return f; } case "spec_set_vrad": - case "spec_set_back_to_freq": - case "spec_clear": - case "spec_clear_unchanged": - case "flux_set_sfcbr": - return null; + case "spec_set_back_to_freq": { + SpecFrame f = spec("FREQ", "MHz"); + f.set("System=VRAD"); + if ("spec_set_back_to_freq".equals(name)) { + f.set("System=FREQ"); + } + return f; + } + case "spec_clear": { + SpecFrame f = spec("FREQ", "MHz"); + f.clear("System"); + return f; + } + case "spec_clear_unchanged": { + SpecFrame f = spec("WAVE", "nm"); + f.clear("System"); + return f; + } + case "flux_set_sfcbr": { + FluxFrame f = new FluxFrame(AstObject.AST__BAD, null); + f.set("System=FLXDN,Unit=Jy"); + f.set(MINE); + f.set("System=SFCBR"); + return f; + } default: throw new IllegalArgumentException("no Java set-up for case " + name); } @@ -81,7 +106,7 @@ void systemChangesMatchTheCLibrary() { failures.add(name + ": got " + got + ", C gives " + want); } } - assertEquals(3, run, "the in-scope cases the C probe recorded"); + assertEquals(8, run, "the cases the C probe recorded"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } } diff --git a/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java b/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java index f7165ee..ec236cc 100644 --- a/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java +++ b/src/test/java/uk/ac/starlink/ast/TransformOracleTest.java @@ -61,7 +61,7 @@ * FrameSet's base-to-current Mapping, and its base and current Frames say which axes are angular. * Why a {@code .head} fixture cannot be read is measured, not listed by hand: when the read throws * {@code UnsupportedOperationException}, the reason is the text of its message from {@code needs} - * on (such as {@code needs SpecFrame}), or {@code encoding } for an encoding whose read is not + * on (such as {@code needs MathMap}), or {@code encoding } for an encoding whose read is not * available; a failed read of the NATIVE encoding needs the classes its {@code BEGAST} cards name * 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. diff --git a/src/test/java/uk/ac/starlink/ast/UnitMapperTest.java b/src/test/java/uk/ac/starlink/ast/UnitMapperTest.java index b4dea87..c5a6f16 100644 --- a/src/test/java/uk/ac/starlink/ast/UnitMapperTest.java +++ b/src/test/java/uk/ac/starlink/ast/UnitMapperTest.java @@ -25,7 +25,8 @@ *

    C's {@code ZOOM_CASES} are chains of ZoomMaps, each perhaps inverted, nested as the probe * nests them, {@code ((z1 z2) z3)}, and simplified. * - *

    Left to later work: {@code spec_frame_unit_changes_match_the_c_library} (SpecFrame). + *

    C's {@code SPEC_CASES} are the Mappings {@code astConvert} finds between two SpecFrames of one + * System that differ only in Unit (specframe.c {@code MakeSpecMapping}). */ class UnitMapperTest { @@ -93,6 +94,45 @@ private static void checkUnitCases(BiFunction route) { assertTrue(failures.isEmpty(), failures.size() + " cases differ from C:\n" + String.join("\n", failures)); } + /** A SpecFrame with the given System and Unit. */ + private static SpecFrame specFrame(String system, String unit) { + SpecFrame f = new SpecFrame(); + f.setSystem(system); + f.setUnit(1, unit); + return f; + } + + @Test + void specFrameUnitChangesMatchTheCLibrary() { + JsonNode data = ProbeData.load("unit_mapper"); + double[] values = doubles(data.get("VALUES")); + List failures = new ArrayList<>(); + int ran = 0; + for (JsonNode c : data.get("SPEC_CASES")) { + ran++; + String system = c.get(0).asText(); + String from = c.get(1).asText(); + String to = c.get(2).asText(); + FrameSet fs = specFrame(system, from).convert(specFrame(system, to), ""); + if (fs == null) { + failures.add(system + " " + from + " -> " + to + ": no Mapping"); + continue; + } + Mapping map = fs.getMapping(FrameSet.AST__BASE, FrameSet.AST__CURRENT); + double[] wantFwd = doubles(c.get(3).get(0)); + double[] wantInv = doubles(c.get(3).get(1)); + double[] fwd = map.tran1(values.length, values, true); + double[] inv = map.tran1(values.length, values, false); + if (!Arrays.equals(fwd, wantFwd) || !Arrays.equals(inv, wantInv)) { + failures.add(system + " " + from + " -> " + to + ": forward " + Arrays.toString(fwd) + " inverse " + + Arrays.toString(inv) + ", C gives forward " + Arrays.toString(wantFwd) + " inverse " + + Arrays.toString(wantInv)); + } + } + assertEquals(24, ran); + assertTrue(failures.isEmpty(), failures.size() + " cases differ from C:\n" + String.join("\n", failures)); + } + @Test void zoomMapChainsSimplifyAsTheCLibraryDoes() { JsonNode data = ProbeData.load("unit_mapper"); diff --git a/src/test/java/uk/ac/starlink/ast/UseDefsTest.java b/src/test/java/uk/ac/starlink/ast/UseDefsTest.java index d3a0f5d..fbeeb7d 100644 --- a/src/test/java/uk/ac/starlink/ast/UseDefsTest.java +++ b/src/test/java/uk/ac/starlink/ast/UseDefsTest.java @@ -16,8 +16,7 @@ * FrameSet from its current Frame, to which setting it on the FrameSet goes (cmpframe.c, frameset.c * {@code GetUseDefs}). A dump writes {@code UseDfs} when it is set (object.c {@code Dump}). * - *

    Every case but {@code spec_off}, which needs a SpecFrame, outside the first phase, runs here. - * For {@code frameset_own}, set through a FrameSet of two Frames, the dump is not compared: C's + *

    Every case runs here. For {@code frameset_own}, set through a FrameSet of two Frames, the dump is not compared: C's * {@code astSimplify} reduces the Mapping the FrameSet's integrity check puts on its current Frame * to a UnitMap, which this version does not, so the dumps differ in that Mapping; the value, the * test result and the reading back of C's dump are compared. @@ -40,6 +39,8 @@ private static Frame build(String name) { Frame f = off(new Frame(1)); f.setIdent("Me"); return f; + case "spec_off": + return off(new SpecFrame()); case "sky_on": SkyFrame sky = new SkyFrame(); sky.setUseDefs(true); @@ -90,7 +91,7 @@ void useDefsMatchesTheCLibrary() { failures.add(name + ": read back as " + read); } } - assertEquals(9, ran, "every case but spec_off"); + assertEquals(10, ran, "every case"); assertTrue(failures.isEmpty(), String.join("\n", failures)); } } diff --git a/src/test/java/uk/ac/starlink/ast/testsupport/FreshThread.java b/src/test/java/uk/ac/starlink/ast/testsupport/FreshThread.java new file mode 100644 index 0000000..59c72af --- /dev/null +++ b/src/test/java/uk/ac/starlink/ast/testsupport/FreshThread.java @@ -0,0 +1,38 @@ +package uk.ac.starlink.ast.testsupport; + +import java.util.concurrent.atomic.AtomicReference; + +/** + * Runs a check on a new thread. The library keeps some caches per thread, as C keeps them per + * process (SkyFrame's tables of LAST values, for one), so a check whose expected values a C probe + * made in a new process runs on a new thread, whose caches are empty, to see what the probe saw. + */ +public final class FreshThread { + + private FreshThread() {} + + /** + * Runs {@code body} on a new thread, waits for it, and rethrows anything it throws: an Error + * or RuntimeException as it is, anything else wrapped in an AssertionError. + * + * @param body the check + * @throws InterruptedException if the wait is interrupted + */ + public static void assertPasses(Runnable body) throws InterruptedException { + AtomicReference failure = new AtomicReference<>(); + Thread t = new Thread(body, "fresh thread"); + t.setUncaughtExceptionHandler((th, e) -> failure.set(e)); + t.start(); + t.join(); + Throwable e = failure.get(); + if (e instanceof Error) { + throw (Error) e; + } + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + if (e != null) { + throw new AssertionError(e); + } + } +} diff --git a/src/test/java/uk/ac/starlink/ast/testsupport/NativeClassesTest.java b/src/test/java/uk/ac/starlink/ast/testsupport/NativeClassesTest.java index 8068091..8fb1530 100644 --- a/src/test/java/uk/ac/starlink/ast/testsupport/NativeClassesTest.java +++ b/src/test/java/uk/ac/starlink/ast/testsupport/NativeClassesTest.java @@ -12,33 +12,33 @@ class NativeClassesTest { private static final String DUMP = " Begin FrameSet \t# Set of inter-related coordinate systems\n" + " IsA Object\n" + " Frm1 = \t# Frame number 1\n" - + " Begin SpecFrame \t# Description of spectral coordinate system\n" + + " Begin GrismMap \t# Grism Mapping\n" + " Ax1 = \n" + " Begin LutMap\n" + " End LutMap\n" - + " End SpecFrame\n" + + " End GrismMap\n" + " Map2 = \n" + " Begin CmpMap\n" + " MapA = \n" + " Begin ZoomMap\n" + " End ZoomMap\n" + " MapB = \n" - + " Begin SpecFrame\n" - + " End SpecFrame\n" + + " Begin GrismMap\n" + + " End GrismMap\n" + " End CmpMap\n" + " End FrameSet\n"; @Test void listsTheBegunClassesInOrder() { assertEquals( - Arrays.asList("FrameSet", "SpecFrame", "LutMap", "CmpMap", "ZoomMap", "SpecFrame"), + Arrays.asList("FrameSet", "GrismMap", "LutMap", "CmpMap", "ZoomMap", "GrismMap"), NativeClasses.begun(DUMP)); } @Test void missingClassesAreSortedWithoutRepeats() { - assertEquals(Arrays.asList("LutMap", "SpecFrame"), NativeClasses.missing(DUMP)); - assertEquals("needs LutMap, SpecFrame", NativeClasses.needs(DUMP)); + assertEquals(Arrays.asList("GrismMap", "LutMap"), NativeClasses.missing(DUMP)); + assertEquals("needs GrismMap, LutMap", NativeClasses.needs(DUMP)); } @Test diff --git a/src/test/resources/deferred/framesets.txt b/src/test/resources/deferred/framesets.txt index 86d452f..525abfb 100644 --- a/src/test/resources/deferred/framesets.txt +++ b/src/test/resources/deferred/framesets.txt @@ -2,71 +2,12 @@ # | # Rewritten by TransformOracleTest with -Dast.writeDeferred=true. programs/testcmpmap/splittest1.ast | needs LutMap -programs/testfitschan/sparse.ast | needs DSBSpecFrame, LutMap, SpecMap -programs/testplot3d/plot3d-test1.ast | needs DSBSpecFrame, SpecMap -programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism, SpecFrame +programs/testfitschan/sparse.ast | needs LutMap +programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism serialisation/c_dssmap.ast | needs DssMap -serialisation/cmpframe.ast | needs SpecFrame -serialisation/frameset_skyspec.ast | needs SpecFrame -serialisation/jan-dsb.ast | needs DSBSpecFrame serialisation/region_in_cmpframe.ast | needs Box, PointSet -serialisation/specframe.ast | needs SpecFrame -wcsconv/expected/jan.ast | needs DSBSpecFrame -wcsconv/framesets/a20070718_00010_02_cube-ast.ast | needs DSBSpecFrame, SpecMap -wcsconv/framesets/alt-spectral-head.ast | needs SpecFrame -wcsconv/framesets/awav-a2f-head.ast | needs SpecFrame -wcsconv/framesets/axes-swap-head.ast | needs SpecFrame -wcsconv/framesets/beta-frq-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/cd-cross-head.ast | needs SpecFrame -wcsconv/framesets/class-ait-head.ast | needs SpecFrame -wcsconv/framesets/class-arc-head.ast | needs SpecFrame -wcsconv/framesets/class-gal-head.ast | needs SpecFrame -wcsconv/framesets/class-noproj-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-olddate-head.ast | needs SpecFrame -wcsconv/framesets/class-sfl-head.ast | needs SpecFrame -wcsconv/framesets/class-sin-head.ast | needs SpecFrame -wcsconv/framesets/class-spec-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-spec-hel-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-write-head.ast | needs DSBSpecFrame -wcsconv/framesets/crota-3d-head.ast | needs SpecFrame -wcsconv/framesets/cube-reorder-head.ast | needs SpecFrame -wcsconv/framesets/degen-wcsaxes-head.ast | needs SpecFrame -wcsconv/framesets/ener-vel-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/fits-pc-alt-head.ast | needs SpecFrame -wcsconv/framesets/fits-pc-unit-head.ast | needs SpecFrame -wcsconv/framesets/freq-f2w-head.ast | needs SpecFrame -wcsconv/framesets/freq-ghz-bary-head.ast | needs SpecFrame -wcsconv/framesets/freq-log-head.ast | needs MathMap, SpecFrame -wcsconv/framesets/freq-pixel3d-head.ast | needs SpecFrame -wcsconv/framesets/freq-wav-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/grism-head.ast | needs GrismMap, SpecFrame -wcsconv/framesets/jan-fits-class.ast | needs DSBSpecFrame -wcsconv/framesets/longslit-fits-pc.ast | needs SpecFrame -wcsconv/framesets/multi-wcs-spec-head.ast | needs SpecFrame +wcsconv/framesets/freq-log-head.ast | needs MathMap +wcsconv/framesets/grism-head.ast | needs GrismMap wcsconv/framesets/polco-head.ast | needs MathMap wcsconv/framesets/polco2-head.ast | needs MathMap -wcsconv/framesets/restfreq-ghz-head.ast | needs SpecFrame -wcsconv/framesets/restfreq-mhz-head.ast | needs SpecFrame -wcsconv/framesets/sip-3d-head.ast | needs SpecFrame -wcsconv/framesets/sip-3d-swap-head.ast | needs SpecFrame -wcsconv/framesets/skyspec3d-class-head.ast | needs SpecFrame -wcsconv/framesets/skyspec3d-head.ast | needs SpecFrame -wcsconv/framesets/specflux-head.ast | needs SpecFrame -wcsconv/framesets/ssysobs-head.ast | needs SpecFrame -wcsconv/framesets/velo-aips-head.ast | needs SpecFrame -wcsconv/framesets/velo-vel-head.ast | needs SpecFrame -wcsconv/framesets/vopt-f2w-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vopt-geo-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vopt-wav-head.ast | needs SpecFrame -wcsconv/framesets/vrad-lsrd-head.ast | needs SpecFrame -wcsconv/framesets/vrad-v2f-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vrad-wav-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/wave-1d-head.ast | needs SpecFrame -wcsconv/framesets/wave-f2w-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/wave-w2f-head.ast | needs SpecFrame -wcsconv/framesets/wavn-frq-head.ast | needs SpecFrame -wcsconv/framesets/zero-cdelt-head.ast | needs SpecFrame -wcsconv/framesets/zopt-frq-head.ast | needs SpecFrame, SpecMap -wcsconv/inputs/a20070718_00010_02_cube.ast | needs DSBSpecFrame, SpecMap wcsconv/inputs/lsst2.ast | needs SplineMap -wcsconv/inputs/specflux.ast | needs SpecFrame diff --git a/src/test/resources/deferred/full-dumps.txt b/src/test/resources/deferred/full-dumps.txt index 17aa1ac..838d77b 100644 --- a/src/test/resources/deferred/full-dumps.txt +++ b/src/test/resources/deferred/full-dumps.txt @@ -2,15 +2,10 @@ # | # Rewritten by FixtureFullDumpOracleTest with -Dast.writeDeferred=true. programs/testcmpmap/splittest1.ast | needs LutMap -programs/testfitschan/sparse.ast | needs DSBSpecFrame, LutMap, SpecMap -programs/testplot3d/plot3d-test1.ast | needs DSBSpecFrame, SpecMap -programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism, SpecFrame +programs/testfitschan/sparse.ast | needs LutMap +programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism serialisation/c_dssmap.ast | needs DssMap -serialisation/cmpframe.ast | needs SpecFrame -serialisation/frameset_skyspec.ast | needs SpecFrame -serialisation/jan-dsb.ast | needs DSBSpecFrame serialisation/region_in_cmpframe.ast | needs Box, PointSet -serialisation/specframe.ast | needs SpecFrame simplify/box_nullregion_merge.map | needs Box, NullRegion, PointSet simplify/box_nullregion_merge.simp | needs Interval, PointSet simplify/box_parallel_merge.map | needs Box, PointSet @@ -32,30 +27,30 @@ simplify/cap_box_permmap_null.map | needs Box, PointSet simplify/cap_box_permmap_null.simp | needs NullRegion simplify/cap_cheby_consolidate.map | needs ChebyMap simplify/cap_cheby_consolidate.simp | needs ChebyMap -simplify/cap_cmpmap_01.map | needs MathMap, RateMap, SpecMap, TranMap -simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, SpecMap, TranMap +simplify/cap_cmpmap_01.map | needs MathMap, RateMap, TranMap +simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, TranMap simplify/cap_cmpmap_02.map | needs MathMap simplify/cap_cmpmap_02.simp | needs MathMap -simplify/cap_cmpmap_04.map | needs MathMap, RateMap, SpecMap, TranMap -simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, SpecMap, TranMap +simplify/cap_cmpmap_04.map | needs MathMap, RateMap, TranMap +simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, TranMap simplify/cap_cmpperm_resume_inv.map | needs MathMap simplify/cap_cmpperm_resume_inv.simp | needs MathMap simplify/cap_cmpperm_resume.map | needs MathMap simplify/cap_cmpperm_resume.simp | needs MathMap -simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism, SpecFrame -simplify/cap_interval_01.simp | needs Box, Interval, PointSet, SpecFrame +simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism +simplify/cap_interval_01.simp | needs Box, Interval, PointSet simplify/cap_lutmap_01.map | needs LutMap, MathMap simplify/cap_lutmap_01.simp | needs MathMap simplify/cap_mathmap_01.map | needs MathMap simplify/cap_matrixmap_04.map | needs ChebyMap simplify/cap_normmap_cmpframe.map | needs NormMap simplify/cap_normmap_cmpframe.simp | needs NormMap -simplify/cap_permmap_01.map | needs NormMap, SpecFrame -simplify/cap_permmap_01.simp | needs NormMap, SpecFrame -simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_02.simp | needs PointList, PointSet, SpecFrame +simplify/cap_permmap_01.map | needs NormMap +simplify/cap_permmap_01.simp | needs NormMap +simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism +simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism +simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism +simplify/cap_pointlist_02.simp | needs PointList, PointSet simplify/cap_poly_bend_allowed.map | needs Box, MathMap, PointSet, Polygon simplify/cap_poly_bend_allowed.simp | needs Box, MathMap, PointSet, Polygon simplify/cap_poly_bent_edges.map | needs Box, MathMap, PointSet, Polygon @@ -64,45 +59,23 @@ simplify/cap_poly_unc_frame.map | needs Box, PointSet, Polygon simplify/cap_poly_unc_frame.simp | needs Box, PointSet, Polygon simplify/cap_restricted_component_flags.map | needs MathMap simplify/cap_restricted_component_flags.simp | needs MathMap -simplify/cap_slamap_02.map | needs Box, PointSet, SpecFrame -simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism, SpecFrame +simplify/cap_slamap_02.map | needs Box, PointSet +simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism simplify/cap_slamap_07.map | needs Box, Circle, CmpRegion, PointSet simplify/cap_slamap_07.simp | needs NullRegion -simplify/cap_specmap_01.map | needs SpecMap -simplify/cap_specmap_01.simp | needs SpecMap -simplify/cap_specmap_02.map | needs LutMap, SpecMap -simplify/cap_specmap_02.simp | needs LutMap, SpecMap -simplify/cap_specmap_03.map | needs SpecMap -simplify/cap_specmap_03.simp | needs SpecMap -simplify/cap_specmap_04.map | needs SpecMap -simplify/cap_specmap_05.map | needs SpecMap -simplify/cap_specmap_05.simp | needs SpecMap -simplify/cap_specmap_06.map | needs SpecMap -simplify/cap_specmap_06.simp | needs SpecMap -simplify/cap_specmap_07.map | needs SpecMap -simplify/cap_specmap_07.simp | needs SpecMap -simplify/cap_specmap_08.map | needs SpecMap -simplify/cap_specmap_08.simp | needs SpecMap -simplify/cap_specmap_09.map | needs LutMap, SpecMap -simplify/cap_specmap_10.map | needs SpecMap -simplify/cap_specmap_10.simp | needs SpecMap -simplify/cap_specmap_11.map | needs SpecMap -simplify/cap_specmap_12.map | needs SpecMap -simplify/cap_specmap_12.simp | needs SpecMap -simplify/cap_specmap_13.map | needs SpecMap -simplify/cap_specmap_13.simp | needs SpecMap -simplify/cap_specmap_14.map | needs MathMap, SpecMap +simplify/cap_specmap_02.map | needs LutMap +simplify/cap_specmap_02.simp | needs LutMap +simplify/cap_specmap_09.map | needs LutMap +simplify/cap_specmap_14.map | needs MathMap simplify/cap_specmap_14.simp | needs MathMap -simplify/cap_timemap_02.map | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile -simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile +simplify/cap_timemap_02.map | needs Box, Interval, PointSet, StcResourceProfile +simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, StcResourceProfile simplify/cap_unitnormmap_01.map | needs UnitNormMap simplify/cap_unitnormmap_01.simp | needs UnitNormMap -simplify/cap_winmap_01.map | needs SpecMap -simplify/cap_winmap_01.simp | needs SpecMap simplify/cap_xphmap_01.map | needs XphMap simplify/cap_xphmap_02.map | needs XphMap simplify/cap_xphmap_02.simp | needs XphMap -simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet, SpecFrame +simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet simplify/cap_zoommap_04.simp | needs Box, PointList, PointSet simplify/cefit_circle_conformal.map | needs Circle, PointSet simplify/cefit_circle_conformal.simp | needs Circle, PointSet @@ -116,15 +89,11 @@ simplify/cheby_linear_lone_reduce.map | needs ChebyMap simplify/chebymap_inverse_cancel.map | needs ChebyMap simplify/cmpmap_decompose_middle.map | needs MathMap simplify/cmpmap_decompose_middle.simp | needs MathMap -simplify/cmpmap_inverted_lone.map | needs SpecMap -simplify/cmpmap_inverted_lone.simp | needs SpecMap -simplify/cmpmap_inverted_nested.map | needs MathMap, SpecMap -simplify/cmpmap_inverted_nested.simp | needs MathMap, SpecMap +simplify/cmpmap_inverted_nested.map | needs MathMap +simplify/cmpmap_inverted_nested.simp | needs MathMap simplify/cmpmap_parallel_in_series_merge.map | needs MathMap simplify/cmpmap_parallel_series_dim_mismatch.map | needs MathMap simplify/cmpmap_parallel_series_dim_mismatch.simp | needs MathMap -simplify/cmpmap_perm_parallel_swap.map | needs SpecMap -simplify/cmpmap_perm_parallel_swap.simp | needs SpecMap simplify/cmpmap_perm_swap_aconstants.map | needs MathMap simplify/cmpmap_perm_swap_aconstants.simp | needs MathMap simplify/cmpmap_perm_swap_bconstants.map | needs MathMap @@ -241,12 +210,6 @@ simplify/neg_selectormap_not_equal.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_parallel.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_series_lower.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_series_upper.map | needs Box, PointSet, SelectorMap -simplify/neg_spec_2arg_mismatch.map | needs SpecMap -simplify/neg_spec_3arg_mismatch.map | needs SpecMap -simplify/neg_spec_6arg_mismatch.map | needs SpecMap -simplify/neg_spec_arg_mismatch.map | needs SpecMap -simplify/neg_spec_lone_forward.map | needs SpecMap -simplify/neg_spec_parallel.map | needs SpecMap simplify/neg_spline_different_coeffs.map | needs SplineMap simplify/neg_spline_nonspline_neighbour.map | needs SplineMap simplify/neg_spline_parallel.map | needs SplineMap @@ -331,8 +294,6 @@ simplify/regbasepick_cmpregion_subset.map | needs CmpRegion, Interval, PointSet simplify/regbasepick_cmpregion_subset.simp | needs CmpRegion, Interval, PointSet simplify/regbasepick_prism_subset.map | needs Box, PointSet simplify/regbasepick_prism_subset.simp | needs Box, PointSet -simplify/rigby.map | needs SpecMap -simplify/rigby.simp | needs SpecMap simplify/selectormap_inverse_cancel_tail.map | needs Box, PointSet, SelectorMap simplify/selectormap_inverse_cancel.map | needs Box, PointSet, SelectorMap simplify/selectormap_region_simplify_real.map | needs Box, Interval, PointSet, SelectorMap @@ -351,23 +312,6 @@ simplify/simpstab_box_nonlinear_unc.map | needs Box, MathMap, PointSet simplify/simpstab_box_nonlinear_unc.simp | needs Box, MathMap, PointSet simplify/simpstab_permmap_slice_unc.map | needs Box, PointSet simplify/simpstab_permmap_slice_unc.simp | needs Box, PointSet -simplify/spec_geocentric_cancel.map | needs SpecMap -simplify/spec_inverse_cancel.map | needs SpecMap -simplify/spec_invert_normalize.map | needs SpecMap -simplify/spec_invert_normalize.simp | needs SpecMap -simplify/spec_lsr_cancel.map | needs SpecMap -simplify/spec_merge_no_cancel.map | needs SpecMap -simplify/spec_merge_no_cancel.simp | needs SpecMap -simplify/spec_partial_cancel.map | needs SpecMap -simplify/spec_partial_cancel.simp | needs SpecMap -simplify/spec_run_inverted_mid.map | needs SpecMap -simplify/spec_run_inverted_mid.simp | needs SpecMap -simplify/spec_run4_identity.map | needs SpecMap -simplify/spec_topocentric_cancel.map | needs SpecMap -simplify/spec_unit_cancel.map | needs SpecMap -simplify/specmap_invert_normalize.map | needs SpecMap -simplify/specmap_invert_normalize.simp | needs SpecMap -simplify/specmap_pair_cancel.map | needs SpecMap simplify/spline_inverse_cancel.map | needs SplineMap simplify/switchmap_fwdonly_simplify.map | needs SwitchMap simplify/switchmap_fwdonly_simplify.simp | needs SwitchMap @@ -417,63 +361,8 @@ simplify/unitnormmap_winmap_fwd_merge.simp | needs UnitNormMap simplify/unitnormmap_winmap_inv_refused.map | needs UnitNormMap simplify/unitnormmap_winmap_inv_refused.simp | needs UnitNormMap simplify/xph_inverse_cancel.map | needs XphMap -specfluxframe_swapped.native | needs FluxFrame, SpecFluxFrame, SpecFrame -wcsconv/expected/jan.ast | needs DSBSpecFrame -wcsconv/framesets/a20070718_00010_02_cube-ast.ast | needs DSBSpecFrame, SpecMap -wcsconv/framesets/alt-spectral-head.ast | needs SpecFrame -wcsconv/framesets/awav-a2f-head.ast | needs SpecFrame -wcsconv/framesets/axes-swap-head.ast | needs SpecFrame -wcsconv/framesets/beta-frq-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/cd-cross-head.ast | needs SpecFrame -wcsconv/framesets/class-ait-head.ast | needs SpecFrame -wcsconv/framesets/class-arc-head.ast | needs SpecFrame -wcsconv/framesets/class-gal-head.ast | needs SpecFrame -wcsconv/framesets/class-noproj-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-olddate-head.ast | needs SpecFrame -wcsconv/framesets/class-sfl-head.ast | needs SpecFrame -wcsconv/framesets/class-sin-head.ast | needs SpecFrame -wcsconv/framesets/class-spec-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-spec-hel-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-write-head.ast | needs DSBSpecFrame -wcsconv/framesets/crota-3d-head.ast | needs SpecFrame -wcsconv/framesets/cube-reorder-head.ast | needs SpecFrame -wcsconv/framesets/degen-wcsaxes-head.ast | needs SpecFrame -wcsconv/framesets/ener-vel-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/fits-pc-alt-head.ast | needs SpecFrame -wcsconv/framesets/fits-pc-unit-head.ast | needs SpecFrame -wcsconv/framesets/freq-f2w-head.ast | needs SpecFrame -wcsconv/framesets/freq-ghz-bary-head.ast | needs SpecFrame -wcsconv/framesets/freq-log-head.ast | needs MathMap, SpecFrame -wcsconv/framesets/freq-pixel3d-head.ast | needs SpecFrame -wcsconv/framesets/freq-wav-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/grism-head.ast | needs GrismMap, SpecFrame -wcsconv/framesets/jan-fits-class.ast | needs DSBSpecFrame -wcsconv/framesets/longslit-fits-pc.ast | needs SpecFrame -wcsconv/framesets/multi-wcs-spec-head.ast | needs SpecFrame +wcsconv/framesets/freq-log-head.ast | needs MathMap +wcsconv/framesets/grism-head.ast | needs GrismMap wcsconv/framesets/polco-head.ast | needs MathMap wcsconv/framesets/polco2-head.ast | needs MathMap -wcsconv/framesets/restfreq-ghz-head.ast | needs SpecFrame -wcsconv/framesets/restfreq-mhz-head.ast | needs SpecFrame -wcsconv/framesets/sip-3d-head.ast | needs SpecFrame -wcsconv/framesets/sip-3d-swap-head.ast | needs SpecFrame -wcsconv/framesets/skyspec3d-class-head.ast | needs SpecFrame -wcsconv/framesets/skyspec3d-head.ast | needs SpecFrame -wcsconv/framesets/specflux-head.ast | needs SpecFrame -wcsconv/framesets/ssysobs-head.ast | needs SpecFrame -wcsconv/framesets/velo-aips-head.ast | needs SpecFrame -wcsconv/framesets/velo-vel-head.ast | needs SpecFrame -wcsconv/framesets/vopt-f2w-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vopt-geo-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vopt-wav-head.ast | needs SpecFrame -wcsconv/framesets/vrad-lsrd-head.ast | needs SpecFrame -wcsconv/framesets/vrad-v2f-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vrad-wav-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/wave-1d-head.ast | needs SpecFrame -wcsconv/framesets/wave-f2w-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/wave-w2f-head.ast | needs SpecFrame -wcsconv/framesets/wavn-frq-head.ast | needs SpecFrame -wcsconv/framesets/zero-cdelt-head.ast | needs SpecFrame -wcsconv/framesets/zopt-frq-head.ast | needs SpecFrame, SpecMap -wcsconv/inputs/a20070718_00010_02_cube.ast | needs DSBSpecFrame, SpecMap wcsconv/inputs/lsst2.ast | needs SplineMap -wcsconv/inputs/specflux.ast | needs SpecFrame diff --git a/src/test/resources/deferred/headers.txt b/src/test/resources/deferred/headers.txt index 2dc5d98..4c2413d 100644 --- a/src/test/resources/deferred/headers.txt +++ b/src/test/resources/deferred/headers.txt @@ -1,54 +1,7 @@ # Fixtures of fixtures/oracle/headers.oracle whose sections do not all match C: # | # Rewritten by TransformOracleTest with -Dast.writeDeferred=true. -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/class-ait.head | needs SpecFrame -wcsconv/inputs/class-arc.head | needs SpecFrame -wcsconv/inputs/class-gal.head | needs SpecFrame -wcsconv/inputs/class-noproj.head | encoding FITS-CLASS -wcsconv/inputs/class-olddate.head | needs SpecFrame -wcsconv/inputs/class-sfl.head | needs SpecFrame -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/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 | 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/multi-wcs-spec.head | needs SpecFrame +wcsconv/inputs/freq-log.head | needs MathMap +wcsconv/inputs/grism.head | needs GrismMap wcsconv/inputs/polco.head | needs MathMap wcsconv/inputs/polco2.head | needs MathMap -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/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 -wcsconv/inputs/vopt-wav.head | needs SpecFrame -wcsconv/inputs/vrad-lsrd.head | needs SpecFrame -wcsconv/inputs/vrad-v2f.head | needs SpecFrame -wcsconv/inputs/vrad-wav.head | needs SpecFrame -wcsconv/inputs/wave-1d.head | needs SpecFrame -wcsconv/inputs/wave-f2w.head | needs SpecFrame -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 diff --git a/src/test/resources/deferred/read-warnings.txt b/src/test/resources/deferred/read-warnings.txt index 082b6cd..8c9b191 100644 --- a/src/test/resources/deferred/read-warnings.txt +++ b/src/test/resources/deferred/read-warnings.txt @@ -2,17 +2,12 @@ # ./ | # Rewritten by FixtureReadWarningsOracleTest with -Dast.writeDeferred=true. ./programs/testcmpmap/splittest1.ast | needs LutMap -./programs/testfitschan/sparse.ast | needs DSBSpecFrame, LutMap, SpecMap +./programs/testfitschan/sparse.ast | needs LutMap ./programs/testmocchan/backcompat_json.ast | needs MocChan ./programs/testmocchan/backcompat_string.ast | needs MocChan -./programs/testplot3d/plot3d-test1.ast | needs DSBSpecFrame, SpecMap -./programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism, SpecFrame +./programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism ./serialisation/c_dssmap.ast | needs DssMap -./serialisation/cmpframe.ast | needs SpecFrame -./serialisation/frameset_skyspec.ast | needs SpecFrame -./serialisation/jan-dsb.ast | needs DSBSpecFrame ./serialisation/region_in_cmpframe.ast | needs Box, PointSet -./serialisation/specframe.ast | needs SpecFrame ./simplify/box_nullregion_merge.map | needs Box, NullRegion, PointSet ./simplify/box_nullregion_merge.simp | needs Interval, PointSet ./simplify/box_parallel_merge.map | needs Box, PointSet @@ -34,30 +29,30 @@ ./simplify/cap_box_permmap_null_first.simp | needs NullRegion ./simplify/cap_cheby_consolidate.map | needs ChebyMap ./simplify/cap_cheby_consolidate.simp | needs ChebyMap -./simplify/cap_cmpmap_01.map | needs MathMap, RateMap, SpecMap, TranMap -./simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, SpecMap, TranMap +./simplify/cap_cmpmap_01.map | needs MathMap, RateMap, TranMap +./simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, TranMap ./simplify/cap_cmpmap_02.map | needs MathMap ./simplify/cap_cmpmap_02.simp | needs MathMap -./simplify/cap_cmpmap_04.map | needs MathMap, RateMap, SpecMap, TranMap -./simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, SpecMap, TranMap +./simplify/cap_cmpmap_04.map | needs MathMap, RateMap, TranMap +./simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, TranMap ./simplify/cap_cmpperm_resume.map | needs MathMap ./simplify/cap_cmpperm_resume.simp | needs MathMap ./simplify/cap_cmpperm_resume_inv.map | needs MathMap ./simplify/cap_cmpperm_resume_inv.simp | needs MathMap -./simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism, SpecFrame -./simplify/cap_interval_01.simp | needs Box, Interval, PointSet, SpecFrame +./simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism +./simplify/cap_interval_01.simp | needs Box, Interval, PointSet ./simplify/cap_lutmap_01.map | needs LutMap, MathMap ./simplify/cap_lutmap_01.simp | needs MathMap ./simplify/cap_mathmap_01.map | needs MathMap ./simplify/cap_matrixmap_04.map | needs ChebyMap ./simplify/cap_normmap_cmpframe.map | needs NormMap ./simplify/cap_normmap_cmpframe.simp | needs NormMap -./simplify/cap_permmap_01.map | needs NormMap, SpecFrame -./simplify/cap_permmap_01.simp | needs NormMap, SpecFrame -./simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism, SpecFrame -./simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism, SpecFrame -./simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism, SpecFrame -./simplify/cap_pointlist_02.simp | needs PointList, PointSet, SpecFrame +./simplify/cap_permmap_01.map | needs NormMap +./simplify/cap_permmap_01.simp | needs NormMap +./simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism +./simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism +./simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism +./simplify/cap_pointlist_02.simp | needs PointList, PointSet ./simplify/cap_poly_bend_allowed.map | needs Box, MathMap, PointSet, Polygon ./simplify/cap_poly_bend_allowed.simp | needs Box, MathMap, PointSet, Polygon ./simplify/cap_poly_bent_edges.map | needs Box, MathMap, PointSet, Polygon @@ -66,45 +61,23 @@ ./simplify/cap_poly_unc_frame.simp | needs Box, PointSet, Polygon ./simplify/cap_restricted_component_flags.map | needs MathMap ./simplify/cap_restricted_component_flags.simp | needs MathMap -./simplify/cap_slamap_02.map | needs Box, PointSet, SpecFrame -./simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism, SpecFrame +./simplify/cap_slamap_02.map | needs Box, PointSet +./simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism ./simplify/cap_slamap_07.map | needs Box, Circle, CmpRegion, PointSet ./simplify/cap_slamap_07.simp | needs NullRegion -./simplify/cap_specmap_01.map | needs SpecMap -./simplify/cap_specmap_01.simp | needs SpecMap -./simplify/cap_specmap_02.map | needs LutMap, SpecMap -./simplify/cap_specmap_02.simp | needs LutMap, SpecMap -./simplify/cap_specmap_03.map | needs SpecMap -./simplify/cap_specmap_03.simp | needs SpecMap -./simplify/cap_specmap_04.map | needs SpecMap -./simplify/cap_specmap_05.map | needs SpecMap -./simplify/cap_specmap_05.simp | needs SpecMap -./simplify/cap_specmap_06.map | needs SpecMap -./simplify/cap_specmap_06.simp | needs SpecMap -./simplify/cap_specmap_07.map | needs SpecMap -./simplify/cap_specmap_07.simp | needs SpecMap -./simplify/cap_specmap_08.map | needs SpecMap -./simplify/cap_specmap_08.simp | needs SpecMap -./simplify/cap_specmap_09.map | needs LutMap, SpecMap -./simplify/cap_specmap_10.map | needs SpecMap -./simplify/cap_specmap_10.simp | needs SpecMap -./simplify/cap_specmap_11.map | needs SpecMap -./simplify/cap_specmap_12.map | needs SpecMap -./simplify/cap_specmap_12.simp | needs SpecMap -./simplify/cap_specmap_13.map | needs SpecMap -./simplify/cap_specmap_13.simp | needs SpecMap -./simplify/cap_specmap_14.map | needs MathMap, SpecMap +./simplify/cap_specmap_02.map | needs LutMap +./simplify/cap_specmap_02.simp | needs LutMap +./simplify/cap_specmap_09.map | needs LutMap +./simplify/cap_specmap_14.map | needs MathMap ./simplify/cap_specmap_14.simp | needs MathMap -./simplify/cap_timemap_02.map | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile -./simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile +./simplify/cap_timemap_02.map | needs Box, Interval, PointSet, StcResourceProfile +./simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, StcResourceProfile ./simplify/cap_unitnormmap_01.map | needs UnitNormMap ./simplify/cap_unitnormmap_01.simp | needs UnitNormMap -./simplify/cap_winmap_01.map | needs SpecMap -./simplify/cap_winmap_01.simp | needs SpecMap ./simplify/cap_xphmap_01.map | needs XphMap ./simplify/cap_xphmap_02.map | needs XphMap ./simplify/cap_xphmap_02.simp | needs XphMap -./simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet, SpecFrame +./simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet ./simplify/cap_zoommap_04.simp | needs Box, PointList, PointSet ./simplify/cefit_circle_conformal.map | needs Circle, PointSet ./simplify/cefit_circle_conformal.simp | needs Circle, PointSet @@ -118,15 +91,11 @@ ./simplify/chebymap_inverse_cancel.map | needs ChebyMap ./simplify/cmpmap_decompose_middle.map | needs MathMap ./simplify/cmpmap_decompose_middle.simp | needs MathMap -./simplify/cmpmap_inverted_lone.map | needs SpecMap -./simplify/cmpmap_inverted_lone.simp | needs SpecMap -./simplify/cmpmap_inverted_nested.map | needs MathMap, SpecMap -./simplify/cmpmap_inverted_nested.simp | needs MathMap, SpecMap +./simplify/cmpmap_inverted_nested.map | needs MathMap +./simplify/cmpmap_inverted_nested.simp | needs MathMap ./simplify/cmpmap_parallel_in_series_merge.map | needs MathMap ./simplify/cmpmap_parallel_series_dim_mismatch.map | needs MathMap ./simplify/cmpmap_parallel_series_dim_mismatch.simp | needs MathMap -./simplify/cmpmap_perm_parallel_swap.map | needs SpecMap -./simplify/cmpmap_perm_parallel_swap.simp | needs SpecMap ./simplify/cmpmap_perm_swap_aconstants.map | needs MathMap ./simplify/cmpmap_perm_swap_aconstants.simp | needs MathMap ./simplify/cmpmap_perm_swap_bconstants.map | needs MathMap @@ -255,12 +224,6 @@ ./simplify/neg_selectormap_parallel.map | needs Box, PointSet, SelectorMap ./simplify/neg_selectormap_series_lower.map | needs Box, PointSet, SelectorMap ./simplify/neg_selectormap_series_upper.map | needs Box, PointSet, SelectorMap -./simplify/neg_spec_2arg_mismatch.map | needs SpecMap -./simplify/neg_spec_3arg_mismatch.map | needs SpecMap -./simplify/neg_spec_6arg_mismatch.map | needs SpecMap -./simplify/neg_spec_arg_mismatch.map | needs SpecMap -./simplify/neg_spec_lone_forward.map | needs SpecMap -./simplify/neg_spec_parallel.map | needs SpecMap ./simplify/neg_spline_different_coeffs.map | needs SplineMap ./simplify/neg_spline_nonspline_neighbour.map | needs SplineMap ./simplify/neg_spline_parallel.map | needs SplineMap @@ -345,8 +308,6 @@ ./simplify/regbasepick_cmpregion_subset.simp | needs CmpRegion, Interval, PointSet ./simplify/regbasepick_prism_subset.map | needs Box, PointSet ./simplify/regbasepick_prism_subset.simp | needs Box, PointSet -./simplify/rigby.map | needs SpecMap -./simplify/rigby.simp | needs SpecMap ./simplify/selectormap_inverse_cancel.map | needs Box, PointSet, SelectorMap ./simplify/selectormap_inverse_cancel_tail.map | needs Box, PointSet, SelectorMap ./simplify/selectormap_region_simplify.map | needs Box, PointSet, SelectorMap @@ -365,23 +326,6 @@ ./simplify/simpstab_box_nonlinear_unc.simp | needs Box, MathMap, PointSet ./simplify/simpstab_permmap_slice_unc.map | needs Box, PointSet ./simplify/simpstab_permmap_slice_unc.simp | needs Box, PointSet -./simplify/spec_geocentric_cancel.map | needs SpecMap -./simplify/spec_inverse_cancel.map | needs SpecMap -./simplify/spec_invert_normalize.map | needs SpecMap -./simplify/spec_invert_normalize.simp | needs SpecMap -./simplify/spec_lsr_cancel.map | needs SpecMap -./simplify/spec_merge_no_cancel.map | needs SpecMap -./simplify/spec_merge_no_cancel.simp | needs SpecMap -./simplify/spec_partial_cancel.map | needs SpecMap -./simplify/spec_partial_cancel.simp | needs SpecMap -./simplify/spec_run4_identity.map | needs SpecMap -./simplify/spec_run_inverted_mid.map | needs SpecMap -./simplify/spec_run_inverted_mid.simp | needs SpecMap -./simplify/spec_topocentric_cancel.map | needs SpecMap -./simplify/spec_unit_cancel.map | needs SpecMap -./simplify/specmap_invert_normalize.map | needs SpecMap -./simplify/specmap_invert_normalize.simp | needs SpecMap -./simplify/specmap_pair_cancel.map | needs SpecMap ./simplify/spline_inverse_cancel.map | needs SplineMap ./simplify/switchmap_fwdonly_simplify.map | needs SwitchMap ./simplify/switchmap_fwdonly_simplify.simp | needs SwitchMap @@ -436,63 +380,8 @@ ./simplify/unitnormmap_winmap_inv_refused.map | needs UnitNormMap ./simplify/unitnormmap_winmap_inv_refused.simp | needs UnitNormMap ./simplify/xph_inverse_cancel.map | needs XphMap -./specfluxframe_swapped.native | needs FluxFrame, SpecFluxFrame, SpecFrame -./wcsconv/expected/jan.ast | needs DSBSpecFrame -./wcsconv/framesets/a20070718_00010_02_cube-ast.ast | needs DSBSpecFrame, SpecMap -./wcsconv/framesets/alt-spectral-head.ast | needs SpecFrame -./wcsconv/framesets/awav-a2f-head.ast | needs SpecFrame -./wcsconv/framesets/axes-swap-head.ast | needs SpecFrame -./wcsconv/framesets/beta-frq-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/cd-cross-head.ast | needs SpecFrame -./wcsconv/framesets/class-ait-head.ast | needs SpecFrame -./wcsconv/framesets/class-arc-head.ast | needs SpecFrame -./wcsconv/framesets/class-gal-head.ast | needs SpecFrame -./wcsconv/framesets/class-noproj-head.ast | needs DSBSpecFrame -./wcsconv/framesets/class-olddate-head.ast | needs SpecFrame -./wcsconv/framesets/class-sfl-head.ast | needs SpecFrame -./wcsconv/framesets/class-sin-head.ast | needs SpecFrame -./wcsconv/framesets/class-spec-head.ast | needs DSBSpecFrame -./wcsconv/framesets/class-spec-hel-head.ast | needs DSBSpecFrame -./wcsconv/framesets/class-write-head.ast | needs DSBSpecFrame -./wcsconv/framesets/crota-3d-head.ast | needs SpecFrame -./wcsconv/framesets/cube-reorder-head.ast | needs SpecFrame -./wcsconv/framesets/degen-wcsaxes-head.ast | needs SpecFrame -./wcsconv/framesets/ener-vel-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/fits-pc-alt-head.ast | needs SpecFrame -./wcsconv/framesets/fits-pc-unit-head.ast | needs SpecFrame -./wcsconv/framesets/freq-f2w-head.ast | needs SpecFrame -./wcsconv/framesets/freq-ghz-bary-head.ast | needs SpecFrame -./wcsconv/framesets/freq-log-head.ast | needs MathMap, SpecFrame -./wcsconv/framesets/freq-pixel3d-head.ast | needs SpecFrame -./wcsconv/framesets/freq-wav-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/grism-head.ast | needs GrismMap, SpecFrame -./wcsconv/framesets/jan-fits-class.ast | needs DSBSpecFrame -./wcsconv/framesets/longslit-fits-pc.ast | needs SpecFrame -./wcsconv/framesets/multi-wcs-spec-head.ast | needs SpecFrame +./wcsconv/framesets/freq-log-head.ast | needs MathMap +./wcsconv/framesets/grism-head.ast | needs GrismMap ./wcsconv/framesets/polco-head.ast | needs MathMap ./wcsconv/framesets/polco2-head.ast | needs MathMap -./wcsconv/framesets/restfreq-ghz-head.ast | needs SpecFrame -./wcsconv/framesets/restfreq-mhz-head.ast | needs SpecFrame -./wcsconv/framesets/sip-3d-head.ast | needs SpecFrame -./wcsconv/framesets/sip-3d-swap-head.ast | needs SpecFrame -./wcsconv/framesets/skyspec3d-class-head.ast | needs SpecFrame -./wcsconv/framesets/skyspec3d-head.ast | needs SpecFrame -./wcsconv/framesets/specflux-head.ast | needs SpecFrame -./wcsconv/framesets/ssysobs-head.ast | needs SpecFrame -./wcsconv/framesets/velo-aips-head.ast | needs SpecFrame -./wcsconv/framesets/velo-vel-head.ast | needs SpecFrame -./wcsconv/framesets/vopt-f2w-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/vopt-geo-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/vopt-wav-head.ast | needs SpecFrame -./wcsconv/framesets/vrad-lsrd-head.ast | needs SpecFrame -./wcsconv/framesets/vrad-v2f-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/vrad-wav-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/wave-1d-head.ast | needs SpecFrame -./wcsconv/framesets/wave-f2w-head.ast | needs SpecFrame, SpecMap -./wcsconv/framesets/wave-w2f-head.ast | needs SpecFrame -./wcsconv/framesets/wavn-frq-head.ast | needs SpecFrame -./wcsconv/framesets/zero-cdelt-head.ast | needs SpecFrame -./wcsconv/framesets/zopt-frq-head.ast | needs SpecFrame, SpecMap -./wcsconv/inputs/a20070718_00010_02_cube.ast | needs DSBSpecFrame, SpecMap ./wcsconv/inputs/lsst2.ast | needs SplineMap -./wcsconv/inputs/specflux.ast | needs SpecFrame diff --git a/src/test/resources/deferred/rust-tests.txt b/src/test/resources/deferred/rust-tests.txt index 0fea2e2..c7e8302 100644 --- a/src/test/resources/deferred/rust-tests.txt +++ b/src/test/resources/deferred/rust-tests.txt @@ -6,18 +6,11 @@ tests/error_model.rs::with_context_appends | Rust-only API (AstError context) tests/error_model.rs::display_includes_context | Rust-only API (AstError context) tests/error_model.rs::new_tracked_captures_location | Rust-only API (AstError source location) tests/error_model.rs::new_has_no_location | Rust-only API (AstError source location) -tests/test_keymap.rs::clone_preserves_every_entry | SpecFrame (out of scope) -tests/test_keymap.rs::vector_puts_replace_scalars | SpecFrame (out of scope) -tests/test_keymap.rs::vector_reads | SpecFrame (out of scope) -tests/test_keymap.rs::element_reads | SpecFrame (out of scope) -tests/test_keymap.rs::remove_then_read_fails | SpecFrame (out of scope) -tests/test_keymap.rs::check_dump_round_trip | SpecFrame (out of scope) tests/test_keymap_serial.rs::the_c_fixture_keymap_round_trips | Box (Region, out of scope) tests/test_keymap_serial.rs::the_c_fixture_map_sz_matches | Box (Region, out of scope) src/keymap/serial.rs::a_non_ascii_key_does_not_panic_the_presize_filter | Rust-only API (HashMap presizing) tests/test_nan_protocol.rs::nan_protocol_lutmap | LutMap (out of scope) tests/test_nan_protocol.rs::nan_protocol_grismmap | GrismMap (out of scope) -tests/test_nan_protocol.rs::nan_protocol_specmap | SpecMap (out of scope) tests/test_nan_protocol.rs::nan_protocol_normmap | NormMap (out of scope) tests/test_nan_protocol.rs::nan_protocol_unitnormmap | UnitNormMap (out of scope) tests/test_nan_protocol.rs::nan_protocol_carries_a_bad_output_of_a_mapping_without_its_own_nan_path | XphMap (out of scope) @@ -182,7 +175,6 @@ tests/test_native_roundtrip_all.rs::round_trip_unitnormmap | UnitNormMap (out of tests/test_native_roundtrip_all.rs::round_trip_normmap | NormMap (out of scope) tests/test_native_roundtrip_all.rs::round_trip_tranmap | TranMap (out of scope) tests/test_native_roundtrip_all.rs::round_trip_ratemap | RateMap (out of scope) -tests/test_native_roundtrip_all.rs::round_trip_specmap | SpecMap (out of scope) tests/test_native_roundtrip_all.rs::round_trip_splinemap | SplineMap (out of scope) tests/test_native_roundtrip_all.rs::round_trip_mathmap | MathMap (out of scope) src/erfa/c2s.rs::c2s_kernel_is_within_one_ulp_of_c2s | hardware SIMD @@ -239,6 +231,13 @@ tests/test_polymap.rs::polymap_with_more_outputs_than_inputs_equals_its_copy | a tests/test_polymap_simd.rs::simd_falls_back_below_threshold | hardware SIMD tests/test_polymap_simd.rs::simd_inverse_falls_back_below_threshold | hardware SIMD tests/test_slamap.rs::cvt_from_int | Rust-only API (SlaCvtType integer codes) +tests/test_specmap.rs::equality | astEqual (out-of-scope method) +tests/test_specframe.rs::test_equal_same | astEqual (out-of-scope method) +tests/test_specframe.rs::test_not_equal_different_system | astEqual (out-of-scope method) +tests/test_specframe.rs::test_not_equal_different_sor | astEqual (out-of-scope method) +tests/test_dsbspecframe.rs::observed_sideband_usb | Rust-only API (DSBSpecFrame::observed_freq) +tests/test_dsbspecframe.rs::observed_sideband_lsb | Rust-only API (DSBSpecFrame::observed_freq) +tests/test_dsbspecframe.rs::observed_sideband_lo | Rust-only API (DSBSpecFrame::observed_freq) tests/test_timemap.rs::equality | astEqual (out-of-scope method) tests/test_timemap.rs::cvt_type_codes_match_c | Rust-only API (TimeCvtType integer codes) tests/test_timemap.rs::cvt_type_from_int | Rust-only API (TimeCvtType integer codes) @@ -247,7 +246,6 @@ src/units/tests.rs::log_hz_to_hz_is_mathmap | MathMap (out of scope) src/units/tests.rs::sqrt_hz_to_hz_is_mathmap | MathMap (out of scope) src/units/tests.rs::log_kms_to_ms_is_mathmap | MathMap (out of scope) src/units/tests.rs::hz_to_log_hz_is_mathmap | MathMap (out of scope) -tests/test_unit_mapper.rs::spec_frame_unit_changes_match_the_c_library | SpecFrame (out of scope) tests/test_basicframe.rs::map_from_returns_unit | Rust-only API (Frame::map_from) tests/test_frame_equality.rs::basic_frames_differing_only_in_cosmetics_are_equal | astEqual (out-of-scope method) tests/test_frame_equality.rs::basic_frames_differing_in_domain_are_not_equal | astEqual (out-of-scope method) @@ -255,18 +253,9 @@ tests/test_frame_equality.rs::skyframes_differing_only_in_title_are_equal | astE tests/test_frame_equality.rs::skyframe_explicit_default_domain_equals_unset_domain | astEqual (out-of-scope method) tests/test_frame_equality.rs::skyframes_differing_in_system_are_not_equal | astEqual (out-of-scope method) tests/test_frame_equality.rs::normmap_pair_over_cosmetically_different_frames_cancels | NormMap (out of scope) -tests/test_frame_geometry.rs::match_axes_finds_sky_in_cmp | SpecFrame (out of scope) tests/test_norm_points.rs::a_circle_mesh_is_normalised_as_c_does | Circle (Region, out of scope) tests/test_frameset.rs::debug_formatting | Rust-only API (Debug) tests/test_frameset.rs::convert_stops_at_the_first_domain_that_gives_a_conversion | MathMap (out of scope) -tests/test_find_frame.rs::cmpframe_match_against_cmpframe_template | SpecFrame (out of scope) -tests/test_find_frame.rs::cmpframe_match_with_default_max_axes_fails | SpecFrame (out of scope) -tests/test_find_frame.rs::cmpframe_match_against_skyframe_template_with_max_axes | SpecFrame (out of scope) -tests/test_find_frame.rs::find_frame_specframe_template_into_cmpframe_sky_spec | SpecFrame (out of scope) -tests/test_find_frame.rs::find_frame_specframe_template_into_cmpframe_spec_sky | SpecFrame (out of scope) -tests/test_convert.rs::convert_basic_cmp_permmap | SpecFrame (out of scope) -tests/test_convert.rs::convert_sky_cmp_permmap | SpecFrame (out of scope) -tests/test_convert.rs::find_frame_cmp_needs_widened_axes | SpecFrame (out of scope) tests/test_convert.rs::convert_between_regions_does_not_clip | Circle (Region, out of scope) tests/test_frame_in_map_slot.rs::a_region_inside_a_cmpmap_still_reads | Region classes (out of scope) tests/test_frame_in_map_slot.rs::a_region_inside_a_cmpframe_still_reads | Box (Region, out of scope) @@ -277,16 +266,12 @@ tests/test_skyframe.rs::serialise_skyframe_not_a_mapping | Rust-only API (AnyObj tests/test_sky_convert.rs::fk_licences_name_existing_cases | hardware SIMD 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) tests/test_cmpframe.rs::norm_box_probe_carries_bad_on_the_other_components_axes | astNormBox (out-of-scope method) tests/test_cmpframe.rs::norm_box_reaches_the_sky_component | astNormBox (out-of-scope method) tests/test_cmpframe.rs::norm_box_delegates_to_a_second_component_of_a_different_size | astNormBox (out-of-scope method) tests/test_cmpframe.rs::norm_box_reaches_a_sky_second_component | astNormBox (out-of-scope method) tests/test_cmpframe.rs::norm_box_bounds_do_not_depend_on_component_order | Circle (Region, out of scope) -src/frames/cmpframe.rs::overlay_template_clean_partition_copies_skyframe_system | SpecFrame (out of scope) -src/frames/cmpframe.rs::overlay_template_fallback_non_cmpframe_result | SpecFrame (out of scope) -src/frames/cmpframe.rs::overlay_template_falls_through_when_partition_unclean | SpecFrame (out of scope) -tests/test_frameset_integrity.rs::unit_change_leaves_mappings_alone | DSBSpecFrame, LutMap and SpecMap (out of scope) +tests/test_frameset_integrity.rs::unit_change_leaves_mappings_alone | LutMap (out of scope) tests/test_show_tostring_oracle.rs::a_concrete_class_writes_what_its_anyobject_writes | Rust-only API (AnyObject) tests/test_show_tostring_oracle.rs::try_from_returns_the_class_and_rejects_another | Rust-only API (AnyObject) tests/test_show_tostring_oracle.rs::try_from_unboxes_boxed_variants | Rust-only API (AnyObject) @@ -312,11 +297,9 @@ tests/test_clear_on_set.rs::grism_setters_recompute_the_constants | GrismMap (ou tests/test_clear_on_set.rs::grism_sentinel_restores_the_default_and_untests_the_attribute | GrismMap (out of scope) tests/test_clear_on_set.rs::setting_an_unset_seed_to_its_own_default_discards_the_record | MathMap (out of scope) tests/test_clear_on_set.rs::re_setting_an_explicit_seed_to_the_same_value_keeps_the_record | MathMap (out of scope) -tests/test_class_attrs.rs::spec_frame_domain_is_cleaned | SpecFrame (out of scope) -tests/test_class_attrs.rs::dsb_centre_with_no_topocentric_frequency_is_rejected | DSBSpecFrame (out of scope) -tests/test_class_attrs.rs::flux_frame_domain_is_cleaned | FluxFrame (out of scope) -tests/test_frame_api.rs::ref_pos_follows_the_c_library | SpecFrame (out of scope) -tests/test_frame_api.rs::density_follows_the_c_library | FluxFrame (out of scope) +tests/test_fluxframe.rs::test_fluxframe_equal_same | astEqual (out-of-scope method) +tests/test_fluxframe.rs::test_fluxframe_equal_different_system | astEqual (out-of-scope method) +tests/test_fluxframe.rs::test_fluxframe_equal_different_specval_is_equal | astEqual (out-of-scope method) tests/test_channel_dump_oracle.rs::a_clone_shares_the_sink | MocChan (out of scope) tests/test_channel_dump_oracle.rs::a_channel_read_from_a_dump_has_no_source | MocChan (out of scope) tests/test_fixture_full_dump_oracle.rs::write_full_dumps | Rust-only API (ignored test writing the port's text for comparison by hand; the gate lists every difference) @@ -341,40 +324,17 @@ tests/test_serialisation.rs::round_trip_prism | Prism, Circle and Interval (Regi tests/test_serialisation.rs::round_trip_negated_circle | Circle (Region, out of scope) 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/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::translates_class_spectral_crval_and_specsys | out-of-scope method FitsChan.read(FITS-CLASS) -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::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::badctype_warning_names_the_legal_ctype_and_precedes_naxis1 | SpecFrame (out of scope) -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::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::non_linear_spectral_writes | SpecFrame (out of scope) -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_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_c_inline.rs::log_spectral_axis_writes_freq_log | MathMap (out of scope) +tests/test_fitschan_wcs_write.rs::grism_interference_order_survives_a_round_trip | GrismMap (out of scope) +tests/test_fitschan_wcs_write.rs::a_non_linear_grism_axis_writes_a_header_that_reads_back | GrismMap (out of scope) +src/fitschan/fset_to_store/spectral_axes.rs::try_grism_cascade_emits_gri_pv_and_chain | 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) +tests/test_fitschan_encodings.rs::freq_log_builds_log_mapping | MathMap (out of scope) +tests/test_fitschan_encodings.rs::grism_builds_grism_mapping | GrismMap (out of scope) diff --git a/src/test/resources/deferred/serialisation.txt b/src/test/resources/deferred/serialisation.txt index fe394e4..13991f2 100644 --- a/src/test/resources/deferred/serialisation.txt +++ b/src/test/resources/deferred/serialisation.txt @@ -22,30 +22,30 @@ simplify/cap_box_permmap_null_first.map | needs Box, PointSet simplify/cap_box_permmap_null_first.simp | needs NullRegion simplify/cap_cheby_consolidate.map | needs ChebyMap simplify/cap_cheby_consolidate.simp | needs ChebyMap -simplify/cap_cmpmap_01.map | needs MathMap, RateMap, SpecMap, TranMap -simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, SpecMap, TranMap +simplify/cap_cmpmap_01.map | needs MathMap, RateMap, TranMap +simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, TranMap simplify/cap_cmpmap_02.map | needs MathMap simplify/cap_cmpmap_02.simp | needs MathMap -simplify/cap_cmpmap_04.map | needs MathMap, RateMap, SpecMap, TranMap -simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, SpecMap, TranMap +simplify/cap_cmpmap_04.map | needs MathMap, RateMap, TranMap +simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, TranMap simplify/cap_cmpperm_resume.map | needs MathMap simplify/cap_cmpperm_resume.simp | needs MathMap simplify/cap_cmpperm_resume_inv.map | needs MathMap simplify/cap_cmpperm_resume_inv.simp | needs MathMap -simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism, SpecFrame -simplify/cap_interval_01.simp | needs Box, Interval, PointSet, SpecFrame +simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism +simplify/cap_interval_01.simp | needs Box, Interval, PointSet simplify/cap_lutmap_01.map | needs LutMap, MathMap simplify/cap_lutmap_01.simp | needs MathMap simplify/cap_mathmap_01.map | needs MathMap simplify/cap_matrixmap_04.map | needs ChebyMap simplify/cap_normmap_cmpframe.map | needs NormMap simplify/cap_normmap_cmpframe.simp | needs NormMap -simplify/cap_permmap_01.map | needs NormMap, SpecFrame -simplify/cap_permmap_01.simp | needs NormMap, SpecFrame -simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_02.simp | needs PointList, PointSet, SpecFrame +simplify/cap_permmap_01.map | needs NormMap +simplify/cap_permmap_01.simp | needs NormMap +simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism +simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism +simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism +simplify/cap_pointlist_02.simp | needs PointList, PointSet simplify/cap_poly_bend_allowed.map | needs Box, MathMap, PointSet, Polygon simplify/cap_poly_bend_allowed.simp | needs Box, MathMap, PointSet, Polygon simplify/cap_poly_bent_edges.map | needs Box, MathMap, PointSet, Polygon @@ -54,45 +54,23 @@ simplify/cap_poly_unc_frame.map | needs Box, PointSet, Polygon simplify/cap_poly_unc_frame.simp | needs Box, PointSet, Polygon simplify/cap_restricted_component_flags.map | needs MathMap simplify/cap_restricted_component_flags.simp | needs MathMap -simplify/cap_slamap_02.map | needs Box, PointSet, SpecFrame -simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism, SpecFrame +simplify/cap_slamap_02.map | needs Box, PointSet +simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism simplify/cap_slamap_07.map | needs Box, Circle, CmpRegion, PointSet simplify/cap_slamap_07.simp | needs NullRegion -simplify/cap_specmap_01.map | needs SpecMap -simplify/cap_specmap_01.simp | needs SpecMap -simplify/cap_specmap_02.map | needs LutMap, SpecMap -simplify/cap_specmap_02.simp | needs LutMap, SpecMap -simplify/cap_specmap_03.map | needs SpecMap -simplify/cap_specmap_03.simp | needs SpecMap -simplify/cap_specmap_04.map | needs SpecMap -simplify/cap_specmap_05.map | needs SpecMap -simplify/cap_specmap_05.simp | needs SpecMap -simplify/cap_specmap_06.map | needs SpecMap -simplify/cap_specmap_06.simp | needs SpecMap -simplify/cap_specmap_07.map | needs SpecMap -simplify/cap_specmap_07.simp | needs SpecMap -simplify/cap_specmap_08.map | needs SpecMap -simplify/cap_specmap_08.simp | needs SpecMap -simplify/cap_specmap_09.map | needs LutMap, SpecMap -simplify/cap_specmap_10.map | needs SpecMap -simplify/cap_specmap_10.simp | needs SpecMap -simplify/cap_specmap_11.map | needs SpecMap -simplify/cap_specmap_12.map | needs SpecMap -simplify/cap_specmap_12.simp | needs SpecMap -simplify/cap_specmap_13.map | needs SpecMap -simplify/cap_specmap_13.simp | needs SpecMap -simplify/cap_specmap_14.map | needs MathMap, SpecMap +simplify/cap_specmap_02.map | needs LutMap +simplify/cap_specmap_02.simp | needs LutMap +simplify/cap_specmap_09.map | needs LutMap +simplify/cap_specmap_14.map | needs MathMap simplify/cap_specmap_14.simp | needs MathMap -simplify/cap_timemap_02.map | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile -simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile +simplify/cap_timemap_02.map | needs Box, Interval, PointSet, StcResourceProfile +simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, StcResourceProfile simplify/cap_unitnormmap_01.map | needs UnitNormMap simplify/cap_unitnormmap_01.simp | needs UnitNormMap -simplify/cap_winmap_01.map | needs SpecMap -simplify/cap_winmap_01.simp | needs SpecMap simplify/cap_xphmap_01.map | needs XphMap simplify/cap_xphmap_02.map | needs XphMap simplify/cap_xphmap_02.simp | needs XphMap -simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet, SpecFrame +simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet simplify/cap_zoommap_04.simp | needs Box, PointList, PointSet simplify/cefit_circle_conformal.map | needs Circle, PointSet simplify/cefit_circle_conformal.simp | needs Circle, PointSet @@ -106,15 +84,11 @@ simplify/cheby_linear_lone_reduce.map | needs ChebyMap simplify/chebymap_inverse_cancel.map | needs ChebyMap simplify/cmpmap_decompose_middle.map | needs MathMap simplify/cmpmap_decompose_middle.simp | needs MathMap -simplify/cmpmap_inverted_lone.map | needs SpecMap -simplify/cmpmap_inverted_lone.simp | needs SpecMap -simplify/cmpmap_inverted_nested.map | needs MathMap, SpecMap -simplify/cmpmap_inverted_nested.simp | needs MathMap, SpecMap +simplify/cmpmap_inverted_nested.map | needs MathMap +simplify/cmpmap_inverted_nested.simp | needs MathMap simplify/cmpmap_parallel_in_series_merge.map | needs MathMap simplify/cmpmap_parallel_series_dim_mismatch.map | needs MathMap simplify/cmpmap_parallel_series_dim_mismatch.simp | needs MathMap -simplify/cmpmap_perm_parallel_swap.map | needs SpecMap -simplify/cmpmap_perm_parallel_swap.simp | needs SpecMap simplify/cmpmap_perm_swap_aconstants.map | needs MathMap simplify/cmpmap_perm_swap_aconstants.simp | needs MathMap simplify/cmpmap_perm_swap_bconstants.map | needs MathMap @@ -243,12 +217,6 @@ simplify/neg_selectormap_not_equal.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_parallel.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_series_lower.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_series_upper.map | needs Box, PointSet, SelectorMap -simplify/neg_spec_2arg_mismatch.map | needs SpecMap -simplify/neg_spec_3arg_mismatch.map | needs SpecMap -simplify/neg_spec_6arg_mismatch.map | needs SpecMap -simplify/neg_spec_arg_mismatch.map | needs SpecMap -simplify/neg_spec_lone_forward.map | needs SpecMap -simplify/neg_spec_parallel.map | needs SpecMap simplify/neg_spline_different_coeffs.map | needs SplineMap simplify/neg_spline_nonspline_neighbour.map | needs SplineMap simplify/neg_spline_parallel.map | needs SplineMap @@ -333,8 +301,6 @@ simplify/regbasepick_cmpregion_subset.map | needs CmpRegion, Interval, PointSet simplify/regbasepick_cmpregion_subset.simp | needs CmpRegion, Interval, PointSet simplify/regbasepick_prism_subset.map | needs Box, PointSet simplify/regbasepick_prism_subset.simp | needs Box, PointSet -simplify/rigby.map | needs SpecMap -simplify/rigby.simp | needs SpecMap simplify/selectormap_inverse_cancel.map | needs Box, PointSet, SelectorMap simplify/selectormap_inverse_cancel_tail.map | needs Box, PointSet, SelectorMap simplify/selectormap_region_simplify.map | needs Box, PointSet, SelectorMap @@ -353,23 +319,6 @@ simplify/simpstab_box_nonlinear_unc.map | needs Box, MathMap, PointSet simplify/simpstab_box_nonlinear_unc.simp | needs Box, MathMap, PointSet simplify/simpstab_permmap_slice_unc.map | needs Box, PointSet simplify/simpstab_permmap_slice_unc.simp | needs Box, PointSet -simplify/spec_geocentric_cancel.map | needs SpecMap -simplify/spec_inverse_cancel.map | needs SpecMap -simplify/spec_invert_normalize.map | needs SpecMap -simplify/spec_invert_normalize.simp | needs SpecMap -simplify/spec_lsr_cancel.map | needs SpecMap -simplify/spec_merge_no_cancel.map | needs SpecMap -simplify/spec_merge_no_cancel.simp | needs SpecMap -simplify/spec_partial_cancel.map | needs SpecMap -simplify/spec_partial_cancel.simp | needs SpecMap -simplify/spec_run4_identity.map | needs SpecMap -simplify/spec_run_inverted_mid.map | needs SpecMap -simplify/spec_run_inverted_mid.simp | needs SpecMap -simplify/spec_topocentric_cancel.map | needs SpecMap -simplify/spec_unit_cancel.map | needs SpecMap -simplify/specmap_invert_normalize.map | needs SpecMap -simplify/specmap_invert_normalize.simp | needs SpecMap -simplify/specmap_pair_cancel.map | needs SpecMap simplify/spline_inverse_cancel.map | needs SplineMap simplify/switchmap_fwdonly_simplify.map | needs SwitchMap simplify/switchmap_fwdonly_simplify.simp | needs SwitchMap @@ -424,70 +373,14 @@ simplify/unitnormmap_winmap_fwd_merge.simp | needs UnitNormMap simplify/unitnormmap_winmap_inv_refused.map | needs UnitNormMap simplify/unitnormmap_winmap_inv_refused.simp | needs UnitNormMap simplify/xph_inverse_cancel.map | needs XphMap -wcsconv/framesets/a20070718_00010_02_cube-ast.ast | needs DSBSpecFrame, SpecMap -wcsconv/framesets/alt-spectral-head.ast | needs SpecFrame -wcsconv/framesets/awav-a2f-head.ast | needs SpecFrame -wcsconv/framesets/axes-swap-head.ast | needs SpecFrame -wcsconv/framesets/beta-frq-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/cd-cross-head.ast | needs SpecFrame -wcsconv/framesets/class-ait-head.ast | needs SpecFrame -wcsconv/framesets/class-arc-head.ast | needs SpecFrame -wcsconv/framesets/class-gal-head.ast | needs SpecFrame -wcsconv/framesets/class-noproj-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-olddate-head.ast | needs SpecFrame -wcsconv/framesets/class-sfl-head.ast | needs SpecFrame -wcsconv/framesets/class-sin-head.ast | needs SpecFrame -wcsconv/framesets/class-spec-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-spec-hel-head.ast | needs DSBSpecFrame -wcsconv/framesets/class-write-head.ast | needs DSBSpecFrame -wcsconv/framesets/crota-3d-head.ast | needs SpecFrame -wcsconv/framesets/cube-reorder-head.ast | needs SpecFrame -wcsconv/framesets/degen-wcsaxes-head.ast | needs SpecFrame -wcsconv/framesets/ener-vel-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/fits-pc-alt-head.ast | needs SpecFrame -wcsconv/framesets/fits-pc-unit-head.ast | needs SpecFrame -wcsconv/framesets/freq-f2w-head.ast | needs SpecFrame -wcsconv/framesets/freq-ghz-bary-head.ast | needs SpecFrame -wcsconv/framesets/freq-log-head.ast | needs MathMap, SpecFrame -wcsconv/framesets/freq-pixel3d-head.ast | needs SpecFrame -wcsconv/framesets/freq-wav-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/grism-head.ast | needs GrismMap, SpecFrame -wcsconv/framesets/jan-fits-class.ast | needs DSBSpecFrame -wcsconv/framesets/longslit-fits-pc.ast | needs SpecFrame -wcsconv/framesets/multi-wcs-spec-head.ast | needs SpecFrame +wcsconv/framesets/freq-log-head.ast | needs MathMap +wcsconv/framesets/grism-head.ast | needs GrismMap wcsconv/framesets/polco-head.ast | needs MathMap wcsconv/framesets/polco2-head.ast | needs MathMap -wcsconv/framesets/restfreq-ghz-head.ast | needs SpecFrame -wcsconv/framesets/restfreq-mhz-head.ast | needs SpecFrame -wcsconv/framesets/sip-3d-head.ast | needs SpecFrame -wcsconv/framesets/sip-3d-swap-head.ast | needs SpecFrame -wcsconv/framesets/skyspec3d-class-head.ast | needs SpecFrame -wcsconv/framesets/skyspec3d-head.ast | needs SpecFrame -wcsconv/framesets/specflux-head.ast | needs SpecFrame -wcsconv/framesets/ssysobs-head.ast | needs SpecFrame -wcsconv/framesets/velo-aips-head.ast | needs SpecFrame -wcsconv/framesets/velo-vel-head.ast | needs SpecFrame -wcsconv/framesets/vopt-f2w-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vopt-geo-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vopt-wav-head.ast | needs SpecFrame -wcsconv/framesets/vrad-lsrd-head.ast | needs SpecFrame -wcsconv/framesets/vrad-v2f-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/vrad-wav-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/wave-1d-head.ast | needs SpecFrame -wcsconv/framesets/wave-f2w-head.ast | needs SpecFrame, SpecMap -wcsconv/framesets/wave-w2f-head.ast | needs SpecFrame -wcsconv/framesets/wavn-frq-head.ast | needs SpecFrame -wcsconv/framesets/zero-cdelt-head.ast | needs SpecFrame -wcsconv/framesets/zopt-frq-head.ast | needs SpecFrame, SpecMap programs/testcmpmap/splittest1.ast | needs LutMap -programs/testfitschan/sparse.ast | needs DSBSpecFrame, LutMap, SpecMap +programs/testfitschan/sparse.ast | needs LutMap programs/testmocchan/backcompat_json.ast | needs MocChan programs/testmocchan/backcompat_string.ast | needs MocChan -programs/testplot3d/plot3d-test1.ast | needs DSBSpecFrame, SpecMap -programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism, SpecFrame +programs/teststcschan/stcschan-test1-doc3.ast | needs Box, Circle, PointList, PointSet, Prism serialisation/c_dssmap.ast | needs DssMap -serialisation/cmpframe.ast | needs SpecFrame -serialisation/frameset_skyspec.ast | needs SpecFrame -serialisation/jan-dsb.ast | needs DSBSpecFrame serialisation/region_in_cmpframe.ast | needs Box, PointSet -serialisation/specframe.ast | needs SpecFrame diff --git a/src/test/resources/deferred/simplify-cases.txt b/src/test/resources/deferred/simplify-cases.txt index 8f049ed..74240e1 100644 --- a/src/test/resources/deferred/simplify-cases.txt +++ b/src/test/resources/deferred/simplify-cases.txt @@ -2,9 +2,6 @@ # | # Rewritten by SimplifyRegressionTest with -Dast.writeDeferred=true. brad | needs LutMap -rigby | needs SpecMap -cmpmap_perm_parallel_swap | needs SpecMap -spec_inverse_cancel | needs SpecMap lut_linear_to_win | needs LutMap lut_inverse_cancel | needs LutMap pcd_zero_to_unit | needs PcdMap @@ -19,12 +16,6 @@ intramap_inverse_cancel | needs IntraMap tranmap_invert_normalize | needs TranMap tranmap_component_simplify | needs TranMap ratemap_simplify_interior | needs RateMap -spec_invert_normalize | needs SpecMap -spec_partial_cancel | needs SpecMap -spec_unit_cancel | needs SpecMap -spec_lsr_cancel | needs SpecMap -spec_geocentric_cancel | needs SpecMap -spec_topocentric_cancel | needs SpecMap normmap_basic_frame_to_unit | needs NormMap normmap_inverse_cancel | needs NormMap normmap_duplicate_elim | needs NormMap @@ -45,10 +36,8 @@ switchmap_inverse_cancel | needs SwitchMap pcd_perm_swap_cancel | needs PcdMap pcd_swap_zoom_simplifies | needs PcdMap pcd_inverted_zoom_swap | needs PcdMap -spec_merge_no_cancel | needs SpecMap neg_win_nonmergeable_series | needs MathMap neg_math_no_simpfi | needs MathMap -neg_spec_arg_mismatch | needs SpecMap neg_grism_same_direction | needs GrismMap neg_lut_nonlinear | needs LutMap neg_lut_different_tables | needs LutMap @@ -61,18 +50,14 @@ neg_perm_no_merge | needs MathMap neg_ratemap_nonratemap_neighbour | needs RateMap neg_ratemap_different_inner | needs RateMap neg_lut_parallel | needs LutMap -neg_spec_2arg_mismatch | needs SpecMap -neg_spec_3arg_mismatch | needs SpecMap neg_grism_different_attrs | needs GrismMap neg_normmap_different_frames | needs NormMap -neg_spec_parallel | needs SpecMap neg_grism_parallel | needs GrismMap neg_grism_inv_then_zoom | needs GrismMap neg_grism_fwd_then_nonzoom | needs GrismMap neg_math_nonmath_neighbour | needs MathMap neg_spline_parallel | needs SplineMap neg_lut_nonlut_neighbour | needs LutMap -neg_spec_lone_forward | needs SpecMap neg_spline_nonspline_neighbour | needs SplineMap neg_tranmap_parallel | needs TranMap neg_tranmap_nontranmap_neighbour | needs TranMap @@ -82,7 +67,6 @@ neg_normmap_nonnorm_neighbour | needs NormMap neg_grism_zoom_before_fwd | needs GrismMap neg_grism_nonzoom_before_inv | needs GrismMap neg_ratemap_parallel | needs RateMap -neg_spec_6arg_mismatch | needs SpecMap neg_spline_different_coeffs | needs SplineMap cmpmap_parallel_in_series_merge | needs MathMap cmpmap_perm_swap_aconstants | needs MathMap @@ -106,42 +90,28 @@ dssmap_inv_winmap_absorb | needs DssMap dssmap_winmap_absorb | needs DssMap dssmap_zoom_no_merge | needs DssMap neg_box_asymmetric_2d | needs Box, PointSet -spec_run_inverted_mid | needs SpecMap -spec_run4_identity | needs SpecMap fitschan_tab_spectral | needs LutMap switchmap_inverse_cancel_distinct_selectors | needs MathMap, SwitchMap -cap_cmpmap_01 | needs MathMap, RateMap, SpecMap, TranMap +cap_cmpmap_01 | needs MathMap, RateMap, TranMap cap_cmpmap_02 | needs MathMap -cap_cmpmap_04 | needs MathMap, RateMap, SpecMap, TranMap -cap_interval_01 | needs Box, Interval, NullRegion, PointSet, Prism, SpecFrame +cap_cmpmap_04 | needs MathMap, RateMap, TranMap +cap_interval_01 | needs Box, Interval, NullRegion, PointSet, Prism cap_lutmap_01 | needs LutMap, MathMap cap_mathmap_01 | needs MathMap cap_matrixmap_04 | needs ChebyMap -cap_permmap_01 | needs NormMap, SpecFrame -cap_pointlist_01 | needs Box, PointList, PointSet, Prism, SpecFrame -cap_pointlist_02 | needs Interval, PointList, PointSet, Prism, SpecFrame -cap_slamap_02 | needs Box, PointSet, Polygon, Prism, SpecFrame +cap_permmap_01 | needs NormMap +cap_pointlist_01 | needs Box, PointList, PointSet, Prism +cap_pointlist_02 | needs Interval, PointList, PointSet, Prism +cap_slamap_02 | needs Box, PointSet, Polygon, Prism cap_slamap_07 | needs Box, Circle, CmpRegion, NullRegion, PointSet -cap_specmap_01 | needs SpecMap -cap_specmap_02 | needs LutMap, SpecMap -cap_specmap_03 | needs SpecMap -cap_specmap_04 | needs SpecMap -cap_specmap_05 | needs SpecMap -cap_specmap_06 | needs SpecMap -cap_specmap_07 | needs SpecMap -cap_specmap_08 | needs SpecMap -cap_specmap_09 | needs LutMap, SpecMap -cap_specmap_10 | needs SpecMap -cap_specmap_11 | needs SpecMap -cap_specmap_12 | needs SpecMap -cap_specmap_13 | needs SpecMap -cap_specmap_14 | needs MathMap, SpecMap -cap_timemap_02 | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile +cap_specmap_02 | needs LutMap +cap_specmap_09 | needs LutMap +cap_specmap_14 | needs MathMap +cap_timemap_02 | needs Box, Interval, PointSet, StcResourceProfile cap_unitnormmap_01 | needs UnitNormMap -cap_winmap_01 | needs SpecMap cap_xphmap_01 | needs XphMap cap_xphmap_02 | needs XphMap -cap_zoommap_04 | needs Box, MathMap, PointList, PointSet, SpecFrame +cap_zoommap_04 | needs Box, MathMap, PointList, PointSet neg_tranmap_adjacent_no_merge | needs MathMap, TranMap neg_lut_constant | needs LutMap neg_math_lone | needs MathMap @@ -227,8 +197,6 @@ neg_pcd_diff_disco | needs PcdMap neg_pcd_diff_centre | needs PcdMap neg_pcd_same_invert | needs PcdMap neg_pcd_perm_nonswap | needs PcdMap -specmap_invert_normalize | needs SpecMap -specmap_pair_cancel | needs SpecMap pcd_inverse_cancel_tail | needs PcdMap nullregion_merge_tail | needs NullRegion grism_inverse_cancel_tail | needs GrismMap @@ -246,8 +214,7 @@ lut_exactly_linear | needs LutMap neg_lut_near_linear | needs LutMap parpair_one_side_reduces | needs MathMap neg_parpair_aligned_irreducible | needs MathMap -cmpmap_inverted_lone | needs SpecMap -cmpmap_inverted_nested | needs MathMap, SpecMap +cmpmap_inverted_nested | needs MathMap rate_inner_reduce_series | needs RateMap rate_inner_reduce_lone | needs RateMap cheby_linear_lone_reduce | needs ChebyMap diff --git a/src/test/resources/deferred/simplify.txt b/src/test/resources/deferred/simplify.txt index b641a73..2b5efbb 100644 --- a/src/test/resources/deferred/simplify.txt +++ b/src/test/resources/deferred/simplify.txt @@ -22,29 +22,29 @@ simplify/cap_box_permmap_null_first.map | needs Box, PointSet simplify/cap_box_permmap_null_first.simp | needs NullRegion simplify/cap_cheby_consolidate.map | needs ChebyMap simplify/cap_cheby_consolidate.simp | needs ChebyMap -simplify/cap_cmpmap_01.map | needs MathMap, RateMap, SpecMap, TranMap -simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, SpecMap, TranMap +simplify/cap_cmpmap_01.map | needs MathMap, RateMap, TranMap +simplify/cap_cmpmap_01.simp | needs MathMap, RateMap, TranMap simplify/cap_cmpmap_02.map | needs MathMap simplify/cap_cmpmap_02.simp | needs MathMap -simplify/cap_cmpmap_04.map | needs MathMap, RateMap, SpecMap, TranMap -simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, SpecMap, TranMap +simplify/cap_cmpmap_04.map | needs MathMap, RateMap, TranMap +simplify/cap_cmpmap_04.simp | needs MathMap, RateMap, TranMap simplify/cap_cmpperm_resume.map | needs MathMap simplify/cap_cmpperm_resume.simp | needs MathMap simplify/cap_cmpperm_resume_inv.map | needs MathMap simplify/cap_cmpperm_resume_inv.simp | needs MathMap -simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism, SpecFrame -simplify/cap_interval_01.simp | needs Box, Interval, PointSet, SpecFrame +simplify/cap_interval_01.map | needs Box, Interval, NullRegion, PointSet, Prism +simplify/cap_interval_01.simp | needs Box, Interval, PointSet simplify/cap_lutmap_01.map | needs LutMap, MathMap simplify/cap_lutmap_01.simp | needs MathMap simplify/cap_mathmap_01.map | needs MathMap simplify/cap_normmap_cmpframe.map | needs NormMap simplify/cap_normmap_cmpframe.simp | needs NormMap -simplify/cap_permmap_01.map | needs NormMap, SpecFrame -simplify/cap_permmap_01.simp | needs NormMap, SpecFrame -simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism, SpecFrame -simplify/cap_pointlist_02.simp | needs PointList, PointSet, SpecFrame +simplify/cap_permmap_01.map | needs NormMap +simplify/cap_permmap_01.simp | needs NormMap +simplify/cap_pointlist_01.map | needs Box, PointList, PointSet, Prism +simplify/cap_pointlist_01.simp | needs Box, PointList, PointSet, Prism +simplify/cap_pointlist_02.map | needs Interval, PointList, PointSet, Prism +simplify/cap_pointlist_02.simp | needs PointList, PointSet simplify/cap_poly_bend_allowed.map | needs Box, MathMap, PointSet, Polygon simplify/cap_poly_bend_allowed.simp | needs Box, MathMap, PointSet, Polygon simplify/cap_poly_bent_edges.map | needs Box, MathMap, PointSet, Polygon @@ -53,43 +53,21 @@ simplify/cap_poly_unc_frame.map | needs Box, PointSet, Polygon simplify/cap_poly_unc_frame.simp | needs Box, PointSet, Polygon simplify/cap_restricted_component_flags.map | needs MathMap simplify/cap_restricted_component_flags.simp | needs MathMap -simplify/cap_slamap_02.map | needs Box, PointSet, SpecFrame -simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism, SpecFrame +simplify/cap_slamap_02.map | needs Box, PointSet +simplify/cap_slamap_02.simp | needs Box, PointSet, Polygon, Prism simplify/cap_slamap_07.map | needs Box, Circle, CmpRegion, PointSet simplify/cap_slamap_07.simp | needs NullRegion -simplify/cap_specmap_01.map | needs SpecMap -simplify/cap_specmap_01.simp | needs SpecMap -simplify/cap_specmap_03.map | needs SpecMap -simplify/cap_specmap_03.simp | needs SpecMap -simplify/cap_specmap_04.map | needs SpecMap -simplify/cap_specmap_05.map | needs SpecMap -simplify/cap_specmap_05.simp | needs SpecMap -simplify/cap_specmap_06.map | needs SpecMap -simplify/cap_specmap_06.simp | needs SpecMap -simplify/cap_specmap_07.map | needs SpecMap -simplify/cap_specmap_07.simp | needs SpecMap -simplify/cap_specmap_08.map | needs SpecMap -simplify/cap_specmap_08.simp | needs SpecMap -simplify/cap_specmap_09.map | needs LutMap, SpecMap -simplify/cap_specmap_10.map | needs SpecMap -simplify/cap_specmap_10.simp | needs SpecMap -simplify/cap_specmap_11.map | needs SpecMap -simplify/cap_specmap_12.map | needs SpecMap -simplify/cap_specmap_12.simp | needs SpecMap -simplify/cap_specmap_13.map | needs SpecMap -simplify/cap_specmap_13.simp | needs SpecMap -simplify/cap_specmap_14.map | needs MathMap, SpecMap +simplify/cap_specmap_09.map | needs LutMap +simplify/cap_specmap_14.map | needs MathMap simplify/cap_specmap_14.simp | needs MathMap -simplify/cap_timemap_02.map | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile -simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, SpecFrame, StcResourceProfile +simplify/cap_timemap_02.map | needs Box, Interval, PointSet, StcResourceProfile +simplify/cap_timemap_02.simp | needs Box, Interval, PointSet, StcResourceProfile simplify/cap_unitnormmap_01.map | needs UnitNormMap simplify/cap_unitnormmap_01.simp | needs UnitNormMap -simplify/cap_winmap_01.map | needs SpecMap -simplify/cap_winmap_01.simp | needs SpecMap simplify/cap_xphmap_01.map | needs XphMap simplify/cap_xphmap_02.map | needs XphMap simplify/cap_xphmap_02.simp | needs XphMap -simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet, SpecFrame +simplify/cap_zoommap_04.map | needs Box, MathMap, PointList, PointSet simplify/cap_zoommap_04.simp | needs Box, PointList, PointSet simplify/cefit_circle_conformal.map | needs Circle, PointSet simplify/cefit_circle_conformal.simp | needs Circle, PointSet @@ -103,15 +81,11 @@ simplify/cheby_linear_lone_reduce.map | needs ChebyMap simplify/chebymap_inverse_cancel.map | needs ChebyMap simplify/cmpmap_decompose_middle.map | needs MathMap simplify/cmpmap_decompose_middle.simp | needs MathMap -simplify/cmpmap_inverted_lone.map | needs SpecMap -simplify/cmpmap_inverted_lone.simp | needs SpecMap -simplify/cmpmap_inverted_nested.map | needs MathMap, SpecMap -simplify/cmpmap_inverted_nested.simp | needs MathMap, SpecMap +simplify/cmpmap_inverted_nested.map | needs MathMap +simplify/cmpmap_inverted_nested.simp | needs MathMap simplify/cmpmap_parallel_in_series_merge.map | needs MathMap simplify/cmpmap_parallel_series_dim_mismatch.map | needs MathMap simplify/cmpmap_parallel_series_dim_mismatch.simp | needs MathMap -simplify/cmpmap_perm_parallel_swap.map | needs SpecMap -simplify/cmpmap_perm_parallel_swap.simp | needs SpecMap simplify/cmpmap_perm_swap_aconstants.map | needs MathMap simplify/cmpmap_perm_swap_aconstants.simp | needs MathMap simplify/cmpmap_perm_swap_bconstants.map | needs MathMap @@ -235,12 +209,6 @@ simplify/neg_selectormap_not_equal.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_parallel.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_series_lower.map | needs Box, PointSet, SelectorMap simplify/neg_selectormap_series_upper.map | needs Box, PointSet, SelectorMap -simplify/neg_spec_2arg_mismatch.map | needs SpecMap -simplify/neg_spec_3arg_mismatch.map | needs SpecMap -simplify/neg_spec_6arg_mismatch.map | needs SpecMap -simplify/neg_spec_arg_mismatch.map | needs SpecMap -simplify/neg_spec_lone_forward.map | needs SpecMap -simplify/neg_spec_parallel.map | needs SpecMap simplify/neg_spline_different_coeffs.map | needs SplineMap simplify/neg_spline_nonspline_neighbour.map | needs SplineMap simplify/neg_spline_parallel.map | needs SplineMap @@ -324,8 +292,6 @@ simplify/regbasepick_cmpregion_subset.map | needs CmpRegion, Interval, PointSet simplify/regbasepick_cmpregion_subset.simp | needs CmpRegion, Interval, PointSet simplify/regbasepick_prism_subset.map | needs Box, PointSet simplify/regbasepick_prism_subset.simp | needs Box, PointSet -simplify/rigby.map | needs SpecMap -simplify/rigby.simp | needs SpecMap simplify/selectormap_region_simplify.map | needs Box, PointSet, SelectorMap simplify/selectormap_region_simplify.simp | needs Box, PointSet, SelectorMap simplify/selectormap_region_simplify_real.map | needs Box, Interval, PointSet, SelectorMap @@ -342,23 +308,6 @@ simplify/simpstab_box_nonlinear_unc.map | needs Box, MathMap, PointSet simplify/simpstab_box_nonlinear_unc.simp | needs Box, MathMap, PointSet simplify/simpstab_permmap_slice_unc.map | needs Box, PointSet simplify/simpstab_permmap_slice_unc.simp | needs Box, PointSet -simplify/spec_geocentric_cancel.map | needs SpecMap -simplify/spec_inverse_cancel.map | needs SpecMap -simplify/spec_invert_normalize.map | needs SpecMap -simplify/spec_invert_normalize.simp | needs SpecMap -simplify/spec_lsr_cancel.map | needs SpecMap -simplify/spec_merge_no_cancel.map | needs SpecMap -simplify/spec_merge_no_cancel.simp | needs SpecMap -simplify/spec_partial_cancel.map | needs SpecMap -simplify/spec_partial_cancel.simp | needs SpecMap -simplify/spec_run4_identity.map | needs SpecMap -simplify/spec_run_inverted_mid.map | needs SpecMap -simplify/spec_run_inverted_mid.simp | needs SpecMap -simplify/spec_topocentric_cancel.map | needs SpecMap -simplify/spec_unit_cancel.map | needs SpecMap -simplify/specmap_invert_normalize.map | needs SpecMap -simplify/specmap_invert_normalize.simp | needs SpecMap -simplify/specmap_pair_cancel.map | needs SpecMap simplify/spline_inverse_cancel.map | needs SplineMap simplify/switchmap_fwdonly_simplify.map | needs SwitchMap simplify/switchmap_fwdonly_simplify.simp | needs SwitchMap diff --git a/src/test/resources/deferred/wcsconv.txt b/src/test/resources/deferred/wcsconv.txt index 9a9dd86..16cad8c 100644 --- a/src/test/resources/deferred/wcsconv.txt +++ b/src/test/resources/deferred/wcsconv.txt @@ -1,79 +1,9 @@ # Rows of fixtures/wcsconv/cases.txt that do not match C: # | # Rewritten by WcsconvTest with -Dast.writeDeferred=true. -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 polco_native | needs MathMap polco2_native | needs MathMap -specflux_native | needs SpecFrame -freq-log_native | needs SpecFrame -freq-f2w_native | needs SpecFrame -grism_native | needs SpecFrame -grism_fits-wcs | needs SpecFrame -class-spec_native | encoding FITS-CLASS -class-hel_native | encoding FITS-CLASS -degen-wcsaxes_native | needs SpecFrame -wave-w2f_native | needs SpecFrame -vrad-v2f_native | needs SpecFrame -fits-pc-alt_native | needs SpecFrame -velo-aips_native | needs SpecFrame -awav-a2f_native | needs SpecFrame -cube-reorder_native | needs SpecFrame -velo-vel_native | needs SpecFrame -vopt-wav_native | needs SpecFrame -zopt-frq_native | needs SpecFrame -fits-pc-unit_native | needs SpecFrame -multi-wcs-spec_native | needs SpecFrame -freq-wav_native | needs SpecFrame -wavn-frq_native | needs SpecFrame -zero-cdelt_native | needs SpecFrame -alt-spectral_native | needs SpecFrame -ssysobs_native | needs SpecFrame -ener-vel_native | needs SpecFrame -beta-frq_native | needs SpecFrame -vrad-wav_native | needs SpecFrame -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 -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 | needs SpecFrame -class-ait_native | needs SpecFrame -class-ait_fits-class | needs SpecFrame -class-sin_native | needs SpecFrame -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 | 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 | needs SpecFrame -vopt-f2w_native | needs SpecFrame -vopt-f2w_fits-wcs | needs SpecFrame -wave-f2w_native | needs SpecFrame -wave-f2w_fits-wcs | needs SpecFrame +freq-log_native | needs MathMap +grism_native | needs GrismMap +grism_fits-wcs | needs GrismMap diff --git a/src/test/resources/oracle/dsb_topo.json b/src/test/resources/oracle/dsb_topo.json new file mode 100644 index 0000000..f92181c --- /dev/null +++ b/src/test/resources/oracle/dsb_topo.json @@ -0,0 +1,9 @@ +{ + "source": "crates/starlink-ast/tests/dsb_topo_oracle/cases.rs", + "generator": "tools/oracle_fixtures/dsb_topo_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "POINTS": [0.5,1.0], + "CASES": [["plain",230.00000000000003,-99532.00852615108,[467.4995754917215,466.9995754917215]],["origin",229.99999999999997,-99532.00852615111,[467.4995754917212,466.9995754917211]],["align_bary",230.00000000000003,-99532.00852615108,[467.4995754917215,466.9995754917215]],["origin_align_offset",229.99999999999997,-99532.00852615111,[467.4995754917212,466.9995754917211]],["origin_align_bary",229.99999999999997,-99532.00852615111,[467.4995754917212,466.9995754917211]]] + } +} diff --git a/src/test/resources/oracle/fitschan_spec_unit.json b/src/test/resources/oracle/fitschan_spec_unit.json new file mode 100644 index 0000000..9246059 --- /dev/null +++ b/src/test/resources/oracle/fitschan_spec_unit.json @@ -0,0 +1,8 @@ +{ + "source": "crates/starlink-ast/tests/fitschan_spec_unit_oracle/cases.rs", + "generator": "tools/oracle_fixtures/fitschan_spec_unit_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["all_dims","","NAXIS1 = 10~NAXIS2 = 10~NAXIS3 = 20",1,["NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 11.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 = 1401000000.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 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1000000.0 / Pixel size on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","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 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency "]],["spectral_dim_only","","NAXIS3 = 20",1,["NAXIS3 = 20 ","WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 11.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 = 1401000000.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 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1000000.0 / Pixel size on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","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 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency "]],["spatial_dims_only","","NAXIS1 = 10~NAXIS2 = 10",1,["NAXIS1 = 10 ","NAXIS2 = 10 ","WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 1.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 = 1391000000.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 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1000000.0 / Pixel size on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","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 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency "]],["no_dims","","",1,["WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 1.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 = 1391000000.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 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1000000.0 / Pixel size on axis 3 ","CUNIT3 = 'Hz ' / Units for axis 3 ","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 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency "]],["unit_mhz","MHz","NAXIS1 = 10~NAXIS2 = 10~NAXIS3 = 20",1,["NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 11.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 = 1401.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 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 1.0 / Pixel size on axis 3 ","CUNIT3 = 'MHz ' / Units for axis 3 ","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 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency "]],["unit_log","log(Hz)","NAXIS1 = 10~NAXIS2 = 10~NAXIS3 = 20",1,["NAXIS1 = 10 ","NAXIS2 = 10 ","NAXIS3 = 20 ","WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 11.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 = 1.401 / 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 ","CDELT1 = -0.001 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 0.001 / Pixel size on axis 3 ","CUNIT3 = 'GHz ' / Units for axis 3 ","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 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency "]],["unit_log_no_dims","log(Hz)","",1,["WCSAXES = 3 / Number of WCS axes ","CRPIX1 = 5.0 / Reference pixel on axis 1 ","CRPIX2 = 5.0 / Reference pixel on axis 2 ","CRPIX3 = 1.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 = 1.391 / 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 ","CDELT1 = -10.0E-4 / Pixel size on axis 1 ","CDELT2 = 0.001 / Pixel size on axis 2 ","CDELT3 = 0.001 / Pixel size on axis 3 ","CUNIT3 = 'GHz ' / Units for axis 3 ","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 ","SPECSYS = 'LSRK ' / Standard of rest for spectral axis ","VELOSYS = 27834.620999041868 / [m/s] Topo. apparent velocity of rest frame ","RESTFRQ = 1420405752.0 / [Hz] Rest frequency "]]] + } +} diff --git a/src/test/resources/oracle/flux_badun.json b/src/test/resources/oracle/flux_badun.json new file mode 100644 index 0000000..32a640f --- /dev/null +++ b/src/test/resources/oracle/flux_badun.json @@ -0,0 +1,9 @@ +{ + "source": "crates/starlink-ast/tests/flux_badun_oracle/cases.rs", + "generator": "tools/oracle_fixtures/flux_badun_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "ATTRS": ["System","Title","Label(1)","Symbol(1)","Unit(1)"], + "CASES": [["","Jy",{"variant":"Ok","value":""},[{"variant":"Ok","value":"FLXDN"},{"variant":"Ok","value":"Flux density at = 1.4E+09 Hz"},{"variant":"Ok","value":"Flux density"},{"variant":"Ok","value":"S_nu"},{"variant":"Ok","value":"Jy"}]],["","W/m^2/Hz/arcsec**2",{"variant":"Ok","value":""},[{"variant":"Ok","value":"SFCBR"},{"variant":"Ok","value":"Surface brightness at = 1.4E+09 Hz"},{"variant":"Ok","value":"Surface brightness"},{"variant":"Ok","value":"mu_nu"},{"variant":"Ok","value":"W/m^2/Hz/arcsec**2"}]],["","m",{"variant":"Err","value":"Badun"},[{"variant":"Err","value":"Badun"},{"variant":"Err","value":"Badun"},{"variant":"Err","value":"Badun"},{"variant":"Err","value":"Badun"},{"variant":"Ok","value":"m"}]],["System=FLXDN","Jy",{"variant":"Ok","value":""},[{"variant":"Ok","value":"FLXDN"},{"variant":"Ok","value":"Flux density at = 1.4E+09 Hz"},{"variant":"Ok","value":"Flux density"},{"variant":"Ok","value":"S_nu"},{"variant":"Ok","value":"Jy"}]],["System=FLXDN","W/m^2/Hz/arcsec**2",{"variant":"Ok","value":""},[{"variant":"Ok","value":"SFCBR"},{"variant":"Ok","value":"Surface brightness at = 1.4E+09 Hz"},{"variant":"Ok","value":"Surface brightness"},{"variant":"Ok","value":"mu_nu"},{"variant":"Ok","value":"W/m^2/Hz/arcsec**2"}]],["System=FLXDN","m",{"variant":"Ok","value":""},[{"variant":"Err","value":"Badun"},{"variant":"Err","value":"Badun"},{"variant":"Err","value":"Badun"},{"variant":"Err","value":"Badun"},{"variant":"Ok","value":"m"}]]] + } +} diff --git a/src/test/resources/oracle/flux_unit_system.json b/src/test/resources/oracle/flux_unit_system.json new file mode 100644 index 0000000..02c915e --- /dev/null +++ b/src/test/resources/oracle/flux_unit_system.json @@ -0,0 +1,10 @@ +{ + "source": "crates/starlink-ast/tests/flux_unit_system_oracle/cases.rs", + "generator": "tools/oracle_fixtures/flux_unit_system_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "SYSTEM": "FLXDNW", + "TITLE": "Flux wavelength density at = 5000 Angstrom", + "CONVERTED": [8.339102404752465E-12,2.918685841663363E-11] + } +} diff --git a/src/test/resources/oracle/spec_convert.json b/src/test/resources/oracle/spec_convert.json new file mode 100644 index 0000000..e1bb6dd --- /dev/null +++ b/src/test/resources/oracle/spec_convert.json @@ -0,0 +1,10 @@ +{ + "source": "crates/starlink-ast/tests/spec_convert_oracle/cases.rs", + "generator": "tools/oracle_fixtures/spec_convert_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "SYSTEMS": ["FREQ","ENER","WAVN","WAVE","AWAV","VRAD","VOPT","ZOPT","BETA","VELO"], + "POINTS": [[230.0,345.0],[1.0E-22,2.0E-22],[7.5,11.5],[0.0013,9.0E-4],[0.0013,9.0E-4],[50.0,-120.0],[50.0,-120.0],[0.001,0.25],[0.001,0.25],[50.0,-120.0]], + "CASES": [["c0:FREQ:FREQ",{"variant":"Ok","value":[230.0,345.0]}],["c0:FREQ:ENER",{"variant":"Ok","value":[1.5239973649999997E-22,2.2859960474999996E-22]}],["c0:FREQ:WAVN",{"variant":"Ok","value":[767.1974189557496,1150.7961284336243]}],["c0:FREQ:WAVE",{"variant":"Ok","value":[1.3034454695652176E7,8689636.463768117]}],["c0:FREQ:AWAV",{"variant":"Ok","value":[1.30307068623701E7,8687137.90823632]}],["c0:FREQ:VRAD",{"variant":"Ok","value":[299102.93534659955,298758.1740199]}],["c0:FREQ:VOPT",{"variant":"Ok","value":[1.300447544984307E8,8.659657217967825E7]}],["c0:FREQ:ZOPT",{"variant":"Ok","value":[433.7826086953485,288.85507246375835]}],["c0:FREQ:BETA",{"variant":"Ok","value":[0.9999894200559679,0.9999761952833356]}],["c0:FREQ:VELO",{"variant":"Ok","value":[299789.2862125731,299785.3215254792]}],["c0:ENER:FREQ",{"variant":"Ok","value":[150.9188961097712,301.8377922195424]}],["c0:ENER:ENER",{"variant":"Ok","value":[1.0E-22,2.0E-22]}],["c0:ENER:WAVN",{"variant":"Ok","value":[503.4112502915973,1006.8225005831946]}],["c0:ENER:WAVE",{"variant":"Ok","value":[1.986447461038579E7,9932237.305192895]}],["c0:ENER:AWAV",{"variant":"Ok","value":[1.985876292235029E7,9929381.461162847]}],["c0:ENER:VRAD",{"variant":"Ok","value":[299340.0145317793,298887.57106353407]}],["c0:ENER:VOPT",{"variant":"Ok","value":[1.983449536516886E8,9.902258059414376E7]}],["c0:ENER:ZOPT",{"variant":"Ok","value":[661.6075500194491,330.30377500071654]}],["c0:ENER:BETA",{"variant":"Ok","value":[0.999995444707735,0.9999817789554424]}],["c0:ENER:VELO",{"variant":"Ok","value":[299791.092357735,299786.99546826474]}],["c0:WAVN:FREQ",{"variant":"Ok","value":[2.248443435,3.4476132670000004]}],["c0:WAVN:ENER",{"variant":"Ok","value":[1.4898355957789342E-24,2.2844145801943657E-24]}],["c0:WAVN:WAVN",{"variant":"Ok","value":[7.5,11.5]}],["c0:WAVN:WAVE",{"variant":"Ok","value":[1.3333333333333333E9,8.695652173913044E8]}],["c0:WAVN:AWAV",{"variant":"Ok","value":[1.3329499562651873E9,8.693151888686001E8]}],["c0:WAVN:VRAD",{"variant":"Ok","value":[299785.7173369333,299782.12231564015]}],["c0:WAVN:VOPT",{"variant":"Ok","value":[1.3333035071515982E10,8.695352546027306E9]}],["c0:WAVN:ZOPT",{"variant":"Ok","value":[44474.217798754566,29004.574044445457]}],["c0:WAVN:BETA",{"variant":"Ok","value":[0.9999999989889007,0.9999999976227927]}],["c0:WAVN:VELO",{"variant":"Ok","value":[299792.45769688004,299792.45728733117]}],["c0:WAVE:FREQ",{"variant":"Ok","value":[2.306095830769231E12,3.3310273111111113E12]}],["c0:WAVE:ENER",{"variant":"Ok","value":[1.5280365084912146E-12,2.207163845598421E-12]}],["c0:WAVE:WAVN",{"variant":"Ok","value":[7.692307692307692E12,1.1111111111111111E13]}],["c0:WAVE:WAVE",{"variant":"Ok","value":[0.0013,9.0E-4]}],["c0:WAVE:AWAV",{"variant":"Ok","value":[0.0,0.0]}],["c0:WAVE:VRAD",{"variant":"Ok","value":[-6.89809515407095E12,-1.0022700028970191E13]}],["c0:WAVE:VOPT",{"variant":"Ok","value":[-299792.4449709663,-299792.449032804]}],["c0:WAVE:ZOPT",{"variant":"Ok","value":[-0.9999999565398218,-0.9999999700886539]}],["c0:WAVE:BETA",{"variant":"Ok","value":[-0.9999999999999962,-0.9999999999999982]}],["c0:WAVE:VELO",{"variant":"Ok","value":[-299792.4579999989,-299792.45799999946]}],["c0:AWAV:FREQ",{"variant":"Ok","value":[4.8429708104754924E-8,1.606975749130794E-8]}],["c0:AWAV:ENER",{"variant":"Ok","value":[3.2089890234506805E-32,1.06479426404097E-32]}],["c0:AWAV:WAVN",{"variant":"Ok","value":[1.6154411764673187E-7,5.3602941176418584E-8]}],["c0:AWAV:WAVE",{"variant":"Ok","value":[6.190259444709843E16,1.8655692729784902E17]}],["c0:AWAV:AWAV",{"variant":"Ok","value":[0.0013,9.0E-4]}],["c0:AWAV:VRAD",{"variant":"Ok","value":[299792.458,299792.458]}],["c0:AWAV:VOPT",{"variant":"Ok","value":["BAD","BAD"]}],["c0:AWAV:ZOPT",{"variant":"Ok","value":["BAD","BAD"]}],["c0:AWAV:BETA",{"variant":"Ok","value":[1.0,1.0]}],["c0:AWAV:VELO",{"variant":"Ok","value":[299792.458,299792.458]}],["c0:VRAD:FREQ",{"variant":"Ok","value":[99983.3217952401,100040.02769142378]}],["c0:VRAD:ENER",{"variant":"Ok","value":[6.624970389560564E-20,6.628727765054646E-20]}],["c0:VRAD:WAVN",{"variant":"Ok","value":[333508.46269534936,333697.61320487846]}],["c0:VRAD:WAVE",{"variant":"Ok","value":[29984.24663404934,29967.250601401083]}],["c0:VRAD:AWAV",{"variant":"Ok","value":[29975.619742157323,29958.62859333633]}],["c0:VRAD:VRAD",{"variant":"Ok","value":[50.0,-120.0]}],["c0:VRAD:VOPT",{"variant":"Ok","value":[50.00834049345455,-119.95198598917698]}],["c0:VRAD:ZOPT",{"variant":"Ok","value":[1.6680986849060275E-4,-4.001167567370123E-4]}],["c0:VRAD:BETA",{"variant":"Ok","value":[1.667959557246245E-4,-4.0019680344005235E-4]}],["c0:VRAD:VELO",{"variant":"Ok","value":[50.00416955114436,-119.97598338703615]}],["c0:VOPT:FREQ",{"variant":"Ok","value":[99983.32457640141,100040.04372000045]}],["c0:VOPT:ENER",{"variant":"Ok","value":[6.624970573842412E-20,6.628728827120239E-20]}],["c0:VOPT:WAVN",{"variant":"Ok","value":[333508.4719723049,333697.66667045525]}],["c0:VOPT:WAVE",{"variant":"Ok","value":[29984.245799999993,29967.245799999997]}],["c0:VOPT:AWAV",{"variant":"Ok","value":[29975.618908347642,29958.62379331493]}],["c0:VOPT:VRAD",{"variant":"Ok","value":[49.991662288154906,-120.04805246401655]}],["c0:VOPT:VOPT",{"variant":"Ok","value":[50.0,-120.0]}],["c0:VOPT:ZOPT",{"variant":"Ok","value":[1.6678204759879023E-4,-4.002769142378293E-4]}],["c0:VOPT:BETA",{"variant":"Ok","value":[1.6676813947345554E-4,-4.0035702503543467E-4]}],["c0:VOPT:VELO",{"variant":"Ok","value":[49.99583044883406,-120.0240166129405]}],["c0:ZOPT:FREQ",{"variant":"Ok","value":[99900.09990009993,80000.0]}],["c0:ZOPT:ENER",{"variant":"Ok","value":[6.619456043956045E-20,5.3008604E-20]}],["c0:ZOPT:WAVN",{"variant":"Ok","value":[333230.8643338183,266851.27615852165]}],["c0:ZOPT:WAVE",{"variant":"Ok","value":[30009.225045799994,37474.05725]}],["c0:ZOPT:AWAV",{"variant":"Ok","value":[30000.59097632959,37463.27788010327]}],["c0:ZOPT:VRAD",{"variant":"Ok","value":[299.4929650349216,59958.49159999999]}],["c0:ZOPT:VOPT",{"variant":"Ok","value":[299.792457999967,74948.1145]}],["c0:ZOPT:ZOPT",{"variant":"Ok","value":[0.001,0.25]}],["c0:ZOPT:BETA",{"variant":"Ok","value":[9.995000002495991E-4,0.21951219512195122]}],["c0:ZOPT:VELO",{"variant":"Ok","value":[299.6425618458279,65808.10053658536]}],["c0:BETA:FREQ",{"variant":"Ok","value":[99900.04995003747,77459.66692414835]}],["c0:BETA:ENER",{"variant":"Ok","value":[6.619452734227195E-20,5.132536012442597E-20]}],["c0:BETA:WAVN",{"variant":"Ok","value":[333230.69771834445,258377.63711903768]}],["c0:BETA:WAVE",{"variant":"Ok","value":[30009.240050423774,38703.03990508622]}],["c0:BETA:AWAV",{"variant":"Ok","value":[30000.605976641775,38691.907300627354]}],["c0:BETA:VRAD",{"variant":"Ok","value":[299.64271155492173,67574.2185694827]}],["c0:BETA:VOPT",{"variant":"Ok","value":[299.9425042377281,87237.94105086215]}],["c0:BETA:ZOPT",{"variant":"Ok","value":[0.0010005005003752565,0.2909944487358056]}],["c0:BETA:BETA",{"variant":"Ok","value":[0.001,0.25]}],["c0:BETA:VELO",{"variant":"Ok","value":[299.792458,74948.1145]}],["c0:VELO:FREQ",{"variant":"Ok","value":[99983.32318582074,100040.03570571182]}],["c0:VELO:ENER",{"variant":"Ok","value":[6.624970481701487E-20,6.628728296087422E-20]}],["c0:VELO:WAVN",{"variant":"Ok","value":[333508.4673338271,333697.63993766584]}],["c0:VELO:WAVE",{"variant":"Ok","value":[29984.246217024665,29967.24820070044]}],["c0:VELO:AWAV",{"variant":"Ok","value":[29975.619325252483,29958.626193325526]}],["c0:VELO:VRAD",{"variant":"Ok","value":[49.99583114413446,-120.02402623106671]}],["c0:VELO:VOPT",{"variant":"Ok","value":[50.00417024668444,-119.97599299556074]}],["c0:VELO:ZOPT",{"variant":"Ok","value":[1.667959580446965E-4,-4.0019683549064045E-4]}],["c0:VELO:BETA",{"variant":"Ok","value":[1.6678204759907602E-4,-4.0027691423778246E-4]}],["c0:VELO:VELO",{"variant":"Ok","value":[50.0,-120.0]}],["c1:FREQ:FREQ",{"variant":"Ok","value":[229.9939768507158,344.9909652760738]}],["c1:FREQ:ENER",{"variant":"Ok","value":[1.5239574551580952E-22,2.285936182737143E-22]}],["c1:FREQ:WAVN",{"variant":"Ok","value":[767.1773278923374,1150.7659918385064]}],["c1:FREQ:WAVE",{"variant":"Ok","value":[1.303479604574988E7,8689864.03049992]}],["c1:FREQ:AWAV",{"variant":"Ok","value":[1.3031048114318458E7,8687365.409535224]}],["c1:FREQ:VRAD",{"variant":"Ok","value":[100225.28102381712,441.69253572567897]}],["c1:FREQ:VOPT",{"variant":"Ok","value":[150559.74538065848,442.34425377229024]}],["c1:FREQ:ZOPT",{"variant":"Ok","value":[0.502213252411635,0.0014755016077565575]}],["c1:FREQ:BETA",{"variant":"Ok","value":[0.38587097720763597,0.0014744130564423672]}],["c1:FREQ:VELO",{"variant":"Ok","value":[115681.20872793916,442.01791429815]}],["c1:ENER:FREQ",{"variant":"Ok","value":[150.9149439052448,301.8298878104896]}],["c1:ENER:ENER",{"variant":"Ok","value":[9.999738123944167E-23,1.9999476247888335E-22]}],["c1:ENER:WAVN",{"variant":"Ok","value":[503.39806715632847,1006.7961343126569]}],["c1:ENER:WAVE",{"variant":"Ok","value":[1.9864994827035233E7,9932497.413517617]}],["c1:ENER:AWAV",{"variant":"Ok","value":[1.9859282989420388E7,9929641.494697895]}],["c1:ENER:VRAD",{"variant":"Ok","value":[168842.6403957006,37892.82279140114]}],["c1:ENER:VOPT",{"variant":"Ok","value":[386543.1132740674,43375.32763703363]}],["c1:ENER:ZOPT",{"variant":"Ok","value":[1.2893690383434109,0.14468451917170522]}],["c1:ENER:BETA",{"variant":"Ok","value":[0.6795493486454873,0.13431255365700528]}],["c1:ENER:VELO",{"variant":"Ok","value":[203723.76956272963,40265.890601090505]}],["c1:WAVN:FREQ",{"variant":"Ok","value":[2.2483845536501477,3.44752298226356]}],["c1:WAVN:ENER",{"variant":"Ok","value":[1.4897965805519677E-24,2.284354756846351E-24]}],["c1:WAVN:WAVN",{"variant":"Ok","value":[7.4998035929581235,11.49969884253579]}],["c1:WAVN:WAVE",{"variant":"Ok","value":[1.3333682510551894E9,8.695879898186018E8]}],["c1:WAVN:AWAV",{"variant":"Ok","value":[1.332984863947053E9,8.693379547480778E8]}],["c1:WAVN:VRAD",{"variant":"Ok","value":[297841.5210047261,296801.02127390896]}],["c1:WAVN:VOPT",{"variant":"Ok","value":[4.5768080616017275E7,2.9744472590227637E7]}],["c1:WAVN:ZOPT",{"variant":"Ok","value":[152.66588399637882,99.21688086705517]}],["c1:WAVN:BETA",{"variant":"Ok","value":[0.9999153052117236,0.9998008845348267]}],["c1:WAVN:VELO",{"variant":"Ok","value":[299767.0671412428,299732.7646852699]}],["c1:WAVE:FREQ",{"variant":"Ok","value":[2.3060354396411777E12,3.3309400794817E12]}],["c1:WAVE:ENER",{"variant":"Ok","value":[1.5279964928738133E-12,2.207106045262175E-12]}],["c1:WAVE:WAVN",{"variant":"Ok","value":[7.692106249187821E12,1.111082013771574E13]}],["c1:WAVE:WAVE",{"variant":"Ok","value":[0.0013000340447788094,9.000235694622529E-4]}],["c1:WAVE:AWAV",{"variant":"Ok","value":[0.0,0.0]}],["c1:WAVE:VRAD",{"variant":"Ok","value":["BAD","BAD"]}],["c1:WAVE:VOPT",{"variant":"Ok","value":[-299792.458,-299792.458]}],["c1:WAVE:ZOPT",{"variant":"Ok","value":[-1.0,-1.0]}],["c1:WAVE:BETA",{"variant":"Ok","value":[-1.0,-1.0]}],["c1:WAVE:VELO",{"variant":"Ok","value":[-299792.458,-299792.458]}],["c1:AWAV:FREQ",{"variant":"Ok","value":[4.8428439846660563E-8,1.6069336662836935E-8]}],["c1:AWAV:ENER",{"variant":"Ok","value":[3.2089049877118127E-32,1.0647663796287558E-32]}],["c1:AWAV:WAVN",{"variant":"Ok","value":[1.6153988719309462E-7,5.3601537443736944E-8]}],["c1:AWAV:WAVE",{"variant":"Ok","value":[6.1904215570279736E16,1.865618129050223E17]}],["c1:AWAV:AWAV",{"variant":"Ok","value":[6.188641607777632E16,1.8650817026437763E17]}],["c1:AWAV:VRAD",{"variant":"Ok","value":[299792.458,299792.458]}],["c1:AWAV:VOPT",{"variant":"Ok","value":["BAD","BAD"]}],["c1:AWAV:ZOPT",{"variant":"Ok","value":["BAD","BAD"]}],["c1:AWAV:BETA",{"variant":"Ok","value":[1.0,1.0]}],["c1:AWAV:VELO",{"variant":"Ok","value":[299792.458,299792.458]}],["c1:VRAD:FREQ",{"variant":"Ok","value":[230.45552150167848,230.58622516947608]}],["c1:VRAD:ENER",{"variant":"Ok","value":[1.527015684861995E-22,1.5278817372329487E-22]}],["c1:VRAD:WAVN",{"variant":"Ok","value":[768.7168751312565,769.1528556381364]}],["c1:VRAD:WAVE",{"variant":"Ok","value":[1.3008690616155038E7,1.3001316873098502E7]}],["c1:VRAD:AWAV",{"variant":"Ok","value":[1.3004950190890886E7,1.299757856802734E7]}],["c1:VRAD:VRAD",{"variant":"Ok","value":[99824.7959141533,99711.38354414268]}],["c1:VRAD:VOPT",{"variant":"Ok","value":[149657.80278815652,149403.0399655533]}],["c1:VRAD:ZOPT",{"variant":"Ok","value":[0.49920469576374904,0.4983548984596313]}],["c1:VRAD:BETA",{"variant":"Ok","value":[0.38416340220211814,0.38367998183062296]}],["c1:VRAD:VELO",{"variant":"Ok","value":[115169.29061981563,115024.3648383978]}],["c1:VOPT:FREQ",{"variant":"Ok","value":[230.45552791208738,230.58626211437786]}],["c1:VOPT:ENER",{"variant":"Ok","value":[1.5270157273378484E-22,1.5278819820326572E-22]}],["c1:VOPT:WAVN",{"variant":"Ok","value":[768.7168965140789,769.1529788730637]}],["c1:VOPT:WAVE",{"variant":"Ok","value":[1.3008690254302027E7,1.3001314790006604E7]}],["c1:VOPT:AWAV",{"variant":"Ok","value":[1.300494982914192E7,1.2997576485534398E7]}],["c1:VOPT:VRAD",{"variant":"Ok","value":[99824.79035180238,99711.35148682602]}],["c1:VOPT:VOPT",{"variant":"Ok","value":[149657.7902861351,149402.96799472815]}],["c1:VOPT:ZOPT",{"variant":"Ok","value":[0.4992046540614945,0.4983546583907996]}],["c1:VOPT:BETA",{"variant":"Ok","value":[0.38416337849103077,0.38367984519527093]}],["c1:VOPT:VELO",{"variant":"Ok","value":[115169.28351141045,115024.32387614976]}],["c1:ZOPT:FREQ",{"variant":"Ok","value":[230.26370005685624,184.39517100553047]}],["c1:ZOPT:ENER",{"variant":"Ok","value":[1.5257446614860836E-22,1.2218163249180557E-22]}],["c1:ZOPT:WAVN",{"variant":"Ok","value":[768.0770276644392,615.0760837536828]}],["c1:ZOPT:WAVE",{"variant":"Ok","value":[1.301952752109759E7,1.6258151250121864E7]}],["c1:ZOPT:AWAV",{"variant":"Ok","value":[1.3015783979867814E7,1.6253476498342032E7]}],["c1:ZOPT:VRAD",{"variant":"Ok","value":[99991.24055218617,139791.64306779072]}],["c1:ZOPT:VOPT",{"variant":"Ok","value":[150032.2178539217,261926.66769171035]}],["c1:ZOPT:ZOPT",{"variant":"Ok","value":[0.5004536099901542,0.8736933191685241]}],["c1:ZOPT:BETA",{"variant":"Ok","value":[0.3848729876442564,0.5566124588607315]}],["c1:ZOPT:VELO",{"variant":"Ok","value":[115382.01898367525,166868.21719528257]}],["c1:BETA:FREQ",{"variant":"Ok","value":[230.26358492497738,178.53985660637204]}],["c1:BETA:ENER",{"variant":"Ok","value":[1.525743898613562E-22,1.183018569632995E-22]}],["c1:BETA:WAVN",{"variant":"Ok","value":[768.0766436258292,595.544857257123]}],["c1:BETA:WAVE",{"variant":"Ok","value":[1.3019534030866235E7,1.679134640849154E7]}],["c1:BETA:AWAV",{"variant":"Ok","value":[1.3015790487764688E7,1.678651834561461E7]}],["c1:BETA:VRAD",{"variant":"Ok","value":[99991.34045281998,144872.33509698464]}],["c1:BETA:VOPT",{"variant":"Ok","value":[150032.44276642846,280348.5604133828]}],["c1:BETA:ZOPT",{"variant":"Ok","value":[0.5004543602175224,0.9351421389439449]}],["c1:BETA:BETA",{"variant":"Ok","value":[0.38487341358077937,0.5784837091903029]}],["c1:BETA:VELO",{"variant":"Ok","value":[115382.14667623243,173425.0530911181]}],["c1:VELO:FREQ",{"variant":"Ok","value":[230.45552470688287,230.58624364192625]}],["c1:VELO:ENER",{"variant":"Ok","value":[1.527015706099921E-22,1.5278818596327983E-22]}],["c1:VELO:WAVN",{"variant":"Ok","value":[768.7168858226675,769.1529172555977]}],["c1:VELO:WAVE",{"variant":"Ok","value":[1.3008690435228534E7,1.3001315831552511E7]}],["c1:VELO:AWAV",{"variant":"Ok","value":[1.3004950010016404E7,1.2997577526780825E7]}],["c1:VELO:VRAD",{"variant":"Ok","value":[99824.7931329779,99711.367515485]}],["c1:VELO:VOPT",{"variant":"Ok","value":[149657.79653714588,149403.0039801393]}],["c1:VELO:ZOPT",{"variant":"Ok","value":[0.499204674912622,0.4983547784252107]}],["c1:VELO:BETA",{"variant":"Ok","value":[0.3841633903465747,0.383679913512949]}],["c1:VELO:VELO",{"variant":"Ok","value":[115169.28706561311,115024.3443572744]}],["units_same_bad",{"variant":"Ok","value":[230.0,345.0]}],["units_different_bad",{"variant":"Err","value":[]}],["dsb_freq_to_vrad",{"variant":"Ok","value":[650.3090195228649,-148920.7654707158]}],["dsb_lsb_to_usb",{"variant":"Ok","value":[230.0,345.0]}],["dsb_lsb_to_usb_aligned",{"variant":"Ok","value":[238.00078289694682,123.00078289694683]}],["dsb_to_spec_vrad",{"variant":"Ok","value":[650.3090195228649,-148920.7654707158]}],["spec_vrad_to_dsb",{"variant":"Ok","value":[230.46155673802846,230.5922638287318]}],["dsb_found_in_cube",{"variant":"Ok","value":[650.3090195228649,-148920.7654707158]}]] + } +} diff --git a/src/test/resources/oracle/spec_origin_sor.json b/src/test/resources/oracle/spec_origin_sor.json new file mode 100644 index 0000000..062ee91 --- /dev/null +++ b/src/test/resources/oracle/spec_origin_sor.json @@ -0,0 +1,8 @@ +{ + "source": "crates/starlink-ast/tests/spec_origin_sor_oracle/cases.rs", + "generator": "tools/oracle_fixtures/spec_origin_sor_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["SpecFrame","System=WAVE,Unit=Angstrom",false,null,1.3E7,{"variant":"Ok","value":null},{"variant":"Ok","value":1.30002250497338E7}],["SpecFrame","System=WAVE,Unit=Angstrom",false,1.299E7,1.3E7,{"variant":"Ok","value":1.2990224876618622E7},{"variant":"Ok","value":1.3000449926352419E7}],["SpecFrame","System=WAVE,Unit=Angstrom",true,null,1.3E7,{"variant":"Ok","value":null},{"variant":"Ok","value":1.30002250497338E7}],["SpecFrame","System=WAVE,Unit=Angstrom",true,1.299E7,1.3E7,{"variant":"Ok","value":1.2990224876618622E7},{"variant":"Ok","value":1.3000225049733797E7}],["SpecFrame","System=FREQ,Unit=GHz",false,null,230.0,{"variant":"Ok","value":null},{"variant":"Ok","value":229.99601841979072}],["SpecFrame","System=FREQ,Unit=GHz",false,229.0,230.0,{"variant":"Ok","value":228.99603573100902},{"variant":"Ok","value":229.99205415079973}],["SpecFrame","System=FREQ,Unit=GHz",true,null,230.0,{"variant":"Ok","value":null},{"variant":"Ok","value":229.99601841979072}],["SpecFrame","System=FREQ,Unit=GHz",true,229.0,230.0,{"variant":"Ok","value":228.99603573100902},{"variant":"Ok","value":229.99601841979072}],["DSBSpecFrame","System=WAVE,Unit=Angstrom",false,null,1.3E7,{"variant":"Ok","value":null},{"variant":"Ok","value":1.30002250497338E7}],["DSBSpecFrame","System=WAVE,Unit=Angstrom",false,1.299E7,1.3E7,{"variant":"Ok","value":1.2990224876618622E7},{"variant":"Ok","value":1.3000449926352419E7}],["DSBSpecFrame","System=WAVE,Unit=Angstrom",true,null,1.3E7,{"variant":"Ok","value":null},{"variant":"Ok","value":1.30002250497338E7}],["DSBSpecFrame","System=WAVE,Unit=Angstrom",true,1.299E7,1.3E7,{"variant":"Ok","value":1.2990224876618622E7},{"variant":"Ok","value":1.3000225049733797E7}],["DSBSpecFrame","System=FREQ,Unit=GHz",false,null,230.0,{"variant":"Ok","value":null},{"variant":"Ok","value":229.99601841979072}],["DSBSpecFrame","System=FREQ,Unit=GHz",false,229.0,230.0,{"variant":"Ok","value":228.99603573100902},{"variant":"Ok","value":229.99205415079973}],["DSBSpecFrame","System=FREQ,Unit=GHz",true,null,230.0,{"variant":"Ok","value":null},{"variant":"Ok","value":229.99601841979072}],["DSBSpecFrame","System=FREQ,Unit=GHz",true,229.0,230.0,{"variant":"Ok","value":228.99603573100902},{"variant":"Ok","value":229.99601841979072}]] + } +} diff --git a/src/test/resources/oracle/specflux_cmp.json b/src/test/resources/oracle/specflux_cmp.json new file mode 100644 index 0000000..612c872 --- /dev/null +++ b/src/test/resources/oracle/specflux_cmp.json @@ -0,0 +1,9 @@ +{ + "source": "crates/starlink-ast/tests/specflux_cmp_oracle/cases.rs", + "generator": "tools/oracle_fixtures/specflux_cmp_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "PICKS": [[false,1,"SpecFrame","Frequency","GHz"],[false,2,"FluxFrame","Flux density","W/m^2/Hz"],[true,1,"FluxFrame","Flux density","W/m^2/Hz"],[true,2,"SpecFrame","Frequency","GHz"]], + "FOUND": ["CmpFrame",[1399.9999999999998,1.0E-26]] + } +} diff --git a/src/test/resources/oracle/specflux_primary.json b/src/test/resources/oracle/specflux_primary.json new file mode 100644 index 0000000..f1a80a6 --- /dev/null +++ b/src/test/resources/oracle/specflux_primary.json @@ -0,0 +1,10 @@ +{ + "source": "crates/starlink-ast/tests/specflux_primary_oracle/cases.rs", + "generator": "tools/oracle_fixtures/specflux_primary_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "SYSTEM": "Compound", + "POINT": [1.4,3.0,7.0], + "CASES": [["spec_in_specflux",2.1413747E8],["spec_in_cmp",2.1413747E8],["flux_in_specflux",null],["flux_in_cmp",null]] + } +} diff --git a/src/test/resources/oracle/specmap_3d.json b/src/test/resources/oracle/specmap_3d.json new file mode 100644 index 0000000..cc6ce62 --- /dev/null +++ b/src/test/resources/oracle/specmap_3d.json @@ -0,0 +1,9 @@ +{ + "source": "crates/starlink-ast/tests/specmap_3d_oracle/cases.rs", + "generator": "tools/oracle_fixtures/specmap_3d_probe.c", + "rustCommit": "10f61689f19a5f1eacc7e653c7eab9b03809939f", + "consts": { + "CASES": [["lsrk",[" Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 1 \t# Number of conversion steps"," Spec1 = \"LKF2HL\" \t# Convert from LSRK to heliocentric frequency"," Spec1a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec1b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," End SpecMap"],[[1.0E11,0.0,0.3],[2.3E11,1.2,-0.9],[4.0E14,4.5,1.1],["BAD",2.0,0.2],[1.0E11,"BAD",0.5],[3.0E11,6.1,"BAD"]],[[1.0000107830723381E11,0.0,0.3],[2.299863427085988E11,1.2,-0.9],[4.0002210142223775E14,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]],[[9.999892170439352E10,0.0,0.3],[2.3001365810241287E11,1.2,-0.9],[3.9997789979887694E14,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]]],["topocentric",[" Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 1 \t# Number of conversion steps"," Spec1 = \"HLF2TP\" \t# Convert from Heliocentric to topocentric frequency"," Spec1a = -2.6000000000000001 \t# Longitude (positive eastwards, radians)"," Spec1b = 0.34999999999999998 \t# Latitude (geodetic, radians)"," Spec1c = 4000 \t# Altitude (geodetic, metres)"," Spec1d = 53000 \t# UT1 epoch of observaton (Modified Julian Date)"," Spec1e = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec1f = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," End SpecMap"],[[1.0E11,0.0,0.3],[2.3E11,1.2,-0.9],[4.0E14,4.5,1.1],["BAD",2.0,0.2],[1.0E11,"BAD",0.5],[3.0E11,6.1,"BAD"]],[[9.999039439799974E10,0.0,0.3],[2.2999452373273767E11,1.2,-0.9],[4.000038332709441E14,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]],[[1.000096065247648E11,0.0,0.3],[2.3000547639765457E11,1.2,-0.9],[3.9999616676579044E14,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]]],["chain",[" Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 7 \t# Number of conversion steps"," Spec1 = \"FRTOVL\" \t# Convert frequency to rel. velocity"," Spec1a = 100000000000 \t# Rest frequency (Hz)"," Spec2 = \"VLTOFR\" \t# Convert rel. velocity to frequency"," Spec2a = 100000000000 \t# Rest frequency (Hz)"," Spec3 = \"GEF2HL\" \t# Convert from Geocentric to heliocentric frequency"," Spec3a = 53000 \t# UT1 epoch of observaton (Modified Julian Date)"," Spec3b = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec3c = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," Spec4 = \"HLF2BY\" \t# Convert from Heliocentric to barycentric frequency"," Spec4a = 53000 \t# UT1 epoch of observaton (Modified Julian Date)"," Spec4b = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec4c = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," Spec5 = \"HLF2GL\" \t# Convert from Heliocentric to galactic frequency"," Spec5a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec5b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," Spec6 = \"LGF2HL\" \t# Convert from Local group to heliocentric frequency"," Spec6a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec6b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," Spec7 = \"HLF2LD\" \t# Convert from Heliocentric to LSRD frequency"," Spec7a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec7b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," End SpecMap"],[[1.0E11,0.0,0.3],[2.3E11,1.2,-0.9],[4.0E14,4.5,1.1],["BAD",2.0,0.2],[1.0E11,"BAD",0.5],[3.0E11,6.1,"BAD"]],[[1.0002707559507715E11,0.0,0.3],[2.2998331258327936E11,1.2,-0.9],[4.0004707009386775E14,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]],[[9.997293173381702E10,0.0,0.3],[2.3001668862754712E11,1.2,-0.9],[3.9995293593717056E14,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]]],["user_inverted",[" Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," Invert = 1 \t# Mapping inverted"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 2 \t# Number of conversion steps"," Spec1 = \"USF2HL\" \t# Convert from user-defined to heliocentric frequency"," Spec1a = 15000 \t# Velocity offset (m/s)"," Spec1b = 0.69999999999999996 \t# RA of source (FK5 J2000, radians)"," Spec1c = -0.40000000000000002 \t# DEC of source (FK5 J2000, radians)"," Spec2 = \"FRTOWV\" \t# Convert frequency to wavelength (vacuum)"," End SpecMap"],[[1.0E11,0.0,0.3],[2.3E11,1.2,-0.9],[4.0E14,4.5,1.1],["BAD",2.0,0.2],[1.0E11,"BAD",0.5],[3.0E11,6.1,"BAD"]],[[0.002998008269374796,0.0,0.3],[0.0013034981332549903,1.2,-0.9],[7.494557387811836E-7,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]],[[0.0029980082693747954,0.0,0.3],[0.0013034981332549905,1.2,-0.9],[7.494557387811836E-7,4.5,1.1],["BAD",2.0,0.2],["BAD","BAD",0.5],["BAD",6.1,"BAD"]]]], + "SIMPLIFY_CASES": [["cancelling_pair",[" Begin CmpMap \t# Compound Mapping"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," InvB = 1 \t# Second Mapping used in inverse direction"," MapA = \t# First component Mapping"," Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 1 \t# Number of conversion steps"," Spec1 = \"LKF2HL\" \t# Convert from LSRK to heliocentric frequency"," Spec1a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec1b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," End SpecMap"," MapB = \t# Second component Mapping"," Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," Invert = 1 \t# Mapping inverted"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 1 \t# Number of conversion steps"," Spec1 = \"LKF2HL\" \t# Convert from LSRK to heliocentric frequency"," Spec1a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec1b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," End SpecMap"," End CmpMap"],[" Begin UnitMap \t# Unit (null) Mapping"," Nin = 3 \t# Number of input coordinates"," IsSimp = 1 \t# Mapping has been simplified"," IsA Mapping \t# Mapping between coordinate systems"," End UnitMap"]],["merged_pair",[" Begin CmpMap \t# Compound Mapping"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," MapA = \t# First component Mapping"," Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 1 \t# Number of conversion steps"," Spec1 = \"LKF2HL\" \t# Convert from LSRK to heliocentric frequency"," Spec1a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec1b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," End SpecMap"," MapB = \t# Second component Mapping"," Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 1 \t# Number of conversion steps"," Spec1 = \"FRTOWV\" \t# Convert frequency to wavelength (vacuum)"," End SpecMap"," End CmpMap"],[" Begin SpecMap \t# Conversion between spectral coordinate systems"," Nin = 3 \t# Number of input coordinates"," IsSimp = 1 \t# Mapping has been simplified"," IsA Mapping \t# Mapping between coordinate systems"," Nspec = 2 \t# Number of conversion steps"," Spec1 = \"LKF2HL\" \t# Convert from LSRK to heliocentric frequency"," Spec1a = 0.10000000000000001 \t# RA of source (FK5 J2000, radians)"," Spec1b = 0.20000000000000001 \t# DEC of source (FK5 J2000, radians)"," Spec2 = \"FRTOWV\" \t# Convert frequency to wavelength (vacuum)"," End SpecMap"]]] + } +}