diff --git a/src/exozippy/components/component.py b/src/exozippy/components/component.py index 8a23ed8b..3a00fb03 100644 --- a/src/exozippy/components/component.py +++ b/src/exozippy/components/component.py @@ -354,6 +354,100 @@ def _has(key): wrote[i] = True return wrote + # The fields that state a posterior term or a support, exactly as + # Parameter._user_constraint_fields defines them -- and deliberately NOT + # `initval`, which is a start value and cannot move a posterior. A star + # whose params file carries only an initval for its radius has said where + # the number is, not that anything should fit it. + USER_CONSTRAINT_FIELDS = ("mu", "sigma", "lower", "upper") + + def user_constrained_elements(self, param): + """Elements whose ``param`` the USER constrained in the params file. + + The user-prior half of a readership predicate: a parameter the user + put a prior or a support on is READ, whatever the topology says. + Written for ``Star.structure_consumers`` (review 3.8.1) and shared + with ``Planet.radius_consumers`` (review 2.8.17), so the two cannot + disagree about what counts as a user constraint. + + A ``mu``/``sigma`` is a term in the logp -- the user asserting a + spectroscopic measurement -- so it makes the parameter read by + definition, and the element has to stay free for it to apply to. + Five shipped examples do exactly this (kelt17's 7454 +/- 75 K and + [Fe/H] 0.21 +/- 0.08, hd80606, GaiaBH1, HIP1349, kelt4): + deactivating those would DROP a real constraint and stop reporting a + quantity the user measured, which is the opposite of the point. It + is also why readership cannot be answered from the component topology + alone. + + ``lower``/``upper`` count too, and that is a deliberate widening + rather than an oversight. It is arguable that a bound on a quantity + nothing reads restrains nothing -- but the user has stated an opinion + about this parameter, and the cost of ignoring it is concrete: + ``solve_api._bounds_diagnostics`` skips inactive elements, so a bound + that excludes its own initval stopped being reported to the GUI at + all (caught by + ``test_solve_api.py::test_bounds_excluding_initval_yields_diagnostic``, + which sets exactly ``star.0.teff: {initval: 6207, lower: 7000}``). + Silently dropping a user's input is the failure mode this whole item + is about; do not narrow this back. + + ``sigma: 0`` is the ONE exception, and it overrides the rest of the + entry. That is a pin, and the inactive role subsumes it exactly -- + the value is held, nothing is sampled, no prior applies -- so + honoring it here would make review 3.8.1's fix a no-op on the very + files it exists for (ob08092 and DC2018_128 pinned all six that way + by hand). Those entries become redundant, and ``build_pymc`` says so + per element. + + Read from ``user_params`` (standardized to the index spelling at + ConfigManager construction, i.e. before this runs) and never from the + resolved vectors -- every parameter has bounds and many have a sigma + from defaults.yaml, so a resolved value says nothing about who asked + for it. Most specific spelling wins, as everywhere else: the index + and name forms are checked before the broadcast. Any lookup fault + degrades to "the user wrote nothing", which is the conservative + direction here only in the sense that it matches the old behavior; + it cannot happen for a well-formed params file. + """ + + def is_constrained(entry): + sigma = entry.get("sigma") + if isinstance(sigma, (int, float)) and float(sigma) == 0.0: + return False # an explicit pin, which inactive subsumes + return any(f in entry for f in self.USER_CONSTRAINT_FIELDS) + + return self.user_entry_elements(param, is_constrained) + + def user_entry_elements(self, param, predicate): + """Elements whose most specific params-file entry satisfies + ``predicate``. + + The one lookup behind ``user_constrained_elements`` and + ``Star.user_pinned_stars``, so the two cannot disagree about which entry + they are reading. Most specific spelling wins, as everywhere else, + which is why this stops at the first hit rather than unioning the + three (contrast ``Parameter._user_constraint_fields``, whose union is + a warning heuristic and does not have to adjudicate). + """ + params = getattr(self.config_manager, "user_params", None) or {} + if not params: + return [] + out = [] + for i in range(self.n_elements): + keys = [f"{self.prefix}.{i}.{param}"] + if i < len(self.names): + keys.append(f"{self.prefix}.{self.names[i]}.{param}") + keys.append(f"{self.prefix}.{param}") + for key in keys: + entry = user_entry(params, key) + if entry is None: + continue + if predicate(entry): + out.append(i) + break # most specific spelling wins + return out + def direct_angle_requests(self, angle): """``(flag, per-element request)`` for an angle with direction latents. diff --git a/src/exozippy/components/orbit/orbit.py b/src/exozippy/components/orbit/orbit.py index d2d4fe1c..8721d250 100644 --- a/src/exozippy/components/orbit/orbit.py +++ b/src/exozippy/components/orbit/orbit.py @@ -727,6 +727,23 @@ def inclination_modes(self, system): _, fitchord = self._resolve_switches(system, log=False) return self._inc_modes_for(fitchord, system) + def chord_planets(self, system): + """``{planet index: orbit name}`` for every orbit that SAMPLES the + transit chord, computed without side effects. + + A `chord` orbit derives its cos i from its one planet's `p` + (``from_chord``), so that planet's radius is read by the likelihood + whatever else the topology holds. ``Planet.radius_consumers`` asks + this at its own stage 3, which may run before this orbit's; the modes + come from ``inclination_modes`` for the same reason. + """ + planets = self._chord_planet_indices() + return { + int(planets[o]): self.names[o] + for o, mode in enumerate(self.inclination_modes(system)) + if mode == "chord" + } + def _parse_ecc_parameterization(self, system=None): """Read `fitvcve:`/`fitchord:` into per-orbit mode lists. diff --git a/src/exozippy/components/planet/planet.py b/src/exozippy/components/planet/planet.py index 379ba8d6..015629c7 100644 --- a/src/exozippy/components/planet/planet.py +++ b/src/exozippy/components/planet/planet.py @@ -637,6 +637,114 @@ def register_parameters(self, system): self._push_rv_mass_hints(system, k_ms_guess) self._resolve_chen(system) + # After _resolve_chen: the relation is one of the radius's readers. + self._apply_radius_activity(system) + + # The planet-local parameters that read `radius` (planet/defaults.yaml): + # a user prior on any of them is a likelihood term in R_P. + RADIUS_READERS = ("radius", "p", "density", "logg") + + def radius_consumers(self, system): + """Per planet: the readers of its radius in this topology. + + THE readership predicate for `planet.radius` (review 2.8.17), the + planet's counterpart of ``Star.structure_consumers``: a list, one per + planet, of the labels of what reads it. An empty list means nothing + in the likelihood does, and ``_apply_radius_activity`` makes that + planet's radius INACTIVE. + + What counts is a term in the likelihood, not an expression that + merely mentions the radius: `density` and `logg` read it for every + planet always, and nothing reads them back. The complete list, each + entry naming the code that reads it: + + * **transit** -- every transit file models every planet's disc + through `p` (transit.py), so any transit block marks every planet. + * **rm** -- an rvinstrument ``rm:`` key: the Rossiter-McLaughlin + kernel reads `p` (rm.py ``compute_rm_rv``). Every planet, the + conservative direction, as for transit. + * **dopptom** -- the Doppler-tomography model reads `p` + (dopptom.py). Every planet. + * **chen** -- the Chen & Kipping (2017) potential is a Gaussian in + R_P (``_add_chen_potential``), on the planets ``_resolve_chen`` + enabled. On by default in an RV- or astrometry-only fit, which is + why every RV-only example keeps its radius. + * **orbit chord** -- an orbit sampling the transit chord derives its + cos i from `p` (orbit/defaults.yaml ``from_chord``), so its one + planet's radius is read. Asked of the orbit through the + side-effect-free ``Orbit.chord_planets``, because stage 3 follows + the config key order and the orbit's may not have run. + (A `cosi` orbit REPORTS its chord from `p`, but without + ``fitchord`` that mode needs a transit block, which already marked + every planet.) + * **user prior** -- a ``mu``/``sigma``/``lower``/``upper`` on the + radius or on a planet-local quantity derived from it + (``RADIUS_READERS``), with ``sigma: 0`` a pin the inactive role + subsumes (``Component.user_constrained_elements``). + + NOT a reader: the base prior (``_add_radius_prior``, uniform in + R_P/R_*). It is the prior OF the radius, and applying it to a + dimension nothing else reads is exactly the dead, prior-only + dimension this predicate exists to remove. Microlensing reads the + planet's MASS (through q), never its radius. + """ + from ..rm import rm_enabled + + out = [[] for _ in range(self.n_elements)] + everyone = [] + if in_topology(system, "transit") is not None: + everyone.append("transit") + if rm_enabled(system): + everyone.append("rm") + if in_topology(system, "dopptom") is not None: + everyone.append("dopptom") + for labels in out: + labels.extend(everyone) + + for i, on in enumerate(self.chen): + if on: + out[i].append("chen") + + orbit = system.active_components.get("orbit") + if orbit is not None: + for i, o_name in orbit.chord_planets(system).items(): + out[i].append(f"orbit {o_name} (fitchord)") + + for param in self.RADIUS_READERS: + for i in self.user_constrained_elements(param): + out[i].append(f"user prior on {param}") + return out + + def _apply_radius_activity(self, system): + """Make `radius` INACTIVE on the planets nothing reads it for. + + A microlensing planet (review 2.8.17) is the case: the lens reads its + mass through q, nothing reads its radius, and a free radius was one + sampled dimension refilling its prior plus R_P, rho_P and log g_P + table rows that were pure prior. The treatment is + ``Star._apply_structure_activity``'s, and for the same reason the + radius stays DECLARED (wholly inactive) rather than dropped: + `density`, `logg` and -- with an orbit -- `p` name it in their deps, + and everything that derives from it (those three, then the transit + durations and probabilities through `p`) inherits the role through + ``Component._inherit_inactivity``. Inactive means no raw + coordinate, no prior or potential, no table row, no trace report. + """ + active = [bool(c) for c in self.radius_consumers(system)] + if all(active): + return + self.manifest["radius"] = merge_options( + self.manifest["radius"], mask=active + ) + names = ", ".join(n for n, on in zip(self.names, active) if not on) + logger.debug( + f"{self.log_tag()} nothing in this topology reads the radius of " + f"{names}, so it is not a parameter of this fit: held at its " + f"resolved value, sampled by nothing and not reported (nor is " + f"anything derived from it). A transit, RM or Doppler-tomography " + f"data set, the Chen & Kipping relation, 'fitchord: true' on its " + f"orbit or a params prior on the radius makes it free." + ) # The keys that state a planet's mass, in any of its coordinates. A user # value on one of them and RVInstrument's semi-amplitude estimate are two diff --git a/src/exozippy/components/star/star.md b/src/exozippy/components/star/star.md index 3fadc1cd..d4dbfd11 100644 --- a/src/exozippy/components/star/star.md +++ b/src/exozippy/components/star/star.md @@ -278,7 +278,18 @@ Tests: `tests/test_fitmsini.py`. - **The term.** `Planet.build_likelihood` adds `planet.radius_jacobian = -sum log R_*` over the planets below, R_* being each planet's host through `star_map`, so the implied prior is uniform in (p, R_*). JDE 2026-10-16: match EXOFASTv2 for now; whether a prior uniform in log R_P would be more physical is open. The choice lives in ONE place, `planet/physics.py` `radius_base_prior_logp` (the log-density of the base prior relative to uniform in R_P), plus the Prior-column and prose strings declared beside the call; swapping the base prior is a change there. - **Which planets.** Every planet whose `radius` element is SAMPLED (`Parameter.element_is_sampled`), and only when an orbit exists (p and everything that reads R_P/R_* exist only then). A pinned radius (`sigma: 0`, including a hard link) gets nothing: the term would be a function of R_* alone, a prior on the star. - **Other radius priors multiply it.** A user `mu`/`sigma` on R_P and the Chen & Kipping relation are separate potentials on R_P; they compose with the flat-in-p base prior exactly as EXOFASTv2 applies both as penalties on its derived rp, so the Jacobian stays. The Prior column reports the user's Gaussian and the `$\propto 1/R_*$` term together. -- **The bounds are still on R_P, not on p.** Where nothing constrains R_P (no transit, chen off, no user prior), the 1/R_* factor integrated over the fixed R_P interval is a 1/R_* prior on the host, which EXOFASTv2's p-bounded stepping does not have. Such a radius measures nothing. With chen on (an RV- or astrometry-only fit) EXOFASTv2 carries the same 1/R_* marginal, because the relation fixes R_P = p R_* at a mass-given value. +- **The bounds are still on R_P, not on p.** Where nothing constrains R_P (no transit, chen off, no user prior), the 1/R_* factor integrated over the fixed R_P interval would be a 1/R_* prior on the host, which EXOFASTv2's p-bounded stepping does not have -- but such a radius is now INACTIVE (next section), so it is not sampled and gets no term. With chen on (an RV- or astrometry-only fit) EXOFASTv2 carries the same 1/R_* marginal, because the relation fixes R_P = p R_* at a mass-given value. - **R_* is floored strictly positive inside the log** (`physics.STAR_RADIUS_LOG_FLOOR`, the CLAUDE.md where-trap rule): `star.radius` defaults to `[0.1, 2000]` solRad, but a user may widen it to 0 or drop the bound for a Gaussian. Tests: `tests/test_radius_prior.py` -- carried from the raw coordinates to (p, R_*) through the model's own transform, the no-likelihood density is flat to 1e-6, and with the term removed it is off by exactly `+log R_*`. + +## Which planets have a radius (`Planet.radius_consumers`, review 2.8.17) + +`planet.radius` is a parameter of a fit only where something in the likelihood reads it; elsewhere it is INACTIVE (no raw coordinate, no prior or potential, no table row), exactly the tier-1 treatment "Which stellar structure parameters a topology actually has" gives a star's radius. The case it exists for is the microlensing planet: the lens reads the planet's MASS (through q) and nothing reads its radius, so a free radius was a sampled dimension refilling its prior plus R_P, rho_P and log g_P rows that were pure prior. + +- **The readers**, one predicate (`Planet.radius_consumers`), each naming the code that reads: a `transit` block (every transit file models every planet's disc through `p`), an rvinstrument `rm:` key (the RM kernel reads `p`), `dopptom` (reads `p`) -- those three mark every planet -- the Chen & Kipping relation on that planet (`_resolve_chen`; on by default in an RV- or astrometry-only fit, so those keep their radius), an orbit SAMPLING the transit chord (`fitchord`: cos i derives from `p`; asked through `Orbit.chord_planets`, because the orbit's stage 3 may run after the planet's), and a user `mu`/`sigma`/`lower`/`upper` on `radius`, `p`, `density` or `logg` (`Component.user_constrained_elements`, the rule Star uses, so `sigma: 0` is a pin the inactive role subsumes and an `initval` alone is not a reader). +- **Not a reader: the base prior above.** It is the prior OF the radius; counting it would make the predicate true everywhere. +- **Declared, not dropped.** `density`, `logg` and, with an orbit, `p` name `radius` in their deps, so the radius stays in the manifest, masked; everything derived from it (those, and through `p` the transit durations, `b`, `delta` and the transit probabilities) inherits the role through `Component._inherit_inactivity` and is not reported. The same reason Star keeps its unread radius declared. +- **Blast radius, measured over every shipped config:** only the microlensing configs with a planet (DC2018_128 and its `DC2018/configs` variants, KMT-2019-BLG-1806, kb180087_obj3, MOA-2008-BLG-379, ob170114, OGLE_0383LD) and `examples/HD114762` (an astrometric stellar companion with `chen: false`) change; every transit, RV and astrometry-with-chen example declares the radius exactly as before. All of the changed ones except ob170114 pinned the radius by hand (`sigma: 0`), which is now redundant. + +Tests: `tests/test_planet_radius_activity.py`. diff --git a/src/exozippy/components/star/star.py b/src/exozippy/components/star/star.py index 205fbc27..3ee1bdce 100644 --- a/src/exozippy/components/star/star.py +++ b/src/exozippy/components/star/star.py @@ -611,69 +611,10 @@ def _in_topology(name): _mark(band.CLARET_CONSUMER_LABEL, param, tie_stars) for param in self.STRUCTURE_PARAMS: - _mark("user prior", param, self._user_prior_stars(param)) + _mark("user prior", param, self.user_constrained_elements(param)) return out - # The fields that state a posterior term or a support, exactly as - # Parameter._user_constraint_fields defines them -- and deliberately NOT - # `initval`, which is a start value and cannot move a posterior. A star - # whose params file carries only an initval for its radius has said where - # the number is, not that anything should fit it. - USER_CONSTRAINT_FIELDS = ("mu", "sigma", "lower", "upper") - - def _user_prior_stars(self, param): - """Stars whose ``param`` the USER constrained in the params file. - - A ``mu``/``sigma`` is a term in the logp -- the user asserting a - spectroscopic measurement -- so it makes the parameter read by - definition, and the element has to stay free for it to apply to. - Five shipped examples do exactly this (kelt17's 7454 +/- 75 K and - [Fe/H] 0.21 +/- 0.08, hd80606, GaiaBH1, HIP1349, kelt4): - deactivating those would DROP a real constraint and stop reporting a - quantity the user measured, which is the opposite of the point. It - is also why readership cannot be answered from the component topology - alone. - - ``lower``/``upper`` count too, and that is a deliberate widening - rather than an oversight. It is arguable that a bound on a quantity - nothing reads restrains nothing -- but the user has stated an opinion - about this parameter, and the cost of ignoring it is concrete: - ``solve_api._bounds_diagnostics`` skips inactive elements, so a bound - that excludes its own initval stopped being reported to the GUI at - all (caught by - ``test_solve_api.py::test_bounds_excluding_initval_yields_diagnostic``, - which sets exactly ``star.0.teff: {initval: 6207, lower: 7000}``). - Silently dropping a user's input is the failure mode this whole item - is about; do not narrow this back. - - ``sigma: 0`` is the ONE exception, and it overrides the rest of the - entry. That is a pin, and the inactive role subsumes it exactly -- - the value is held, nothing is sampled, no prior applies -- so - honoring it here would make review 3.8.1's fix a no-op on the very - files it exists for (ob08092 and DC2018_128 pinned all six that way - by hand). Those entries become redundant, and ``build_pymc`` says so - per element. - - Read from ``user_params`` (standardized to the index spelling at - ConfigManager construction, i.e. before this runs) and never from the - resolved vectors -- every parameter has bounds and many have a sigma - from defaults.yaml, so a resolved value says nothing about who asked - for it. Most specific spelling wins, as everywhere else: the index - and name forms are checked before the broadcast. Any lookup fault - degrades to "the user wrote nothing", which is the conservative - direction here only in the sense that it matches the old behavior; - it cannot happen for a well-formed params file. - """ - - def is_constrained(entry): - sigma = entry.get("sigma") - if isinstance(sigma, (int, float)) and float(sigma) == 0.0: - return False # an explicit pin, which inactive subsumes - return any(f in entry for f in self.USER_CONSTRAINT_FIELDS) - - return self._user_entry_stars(param, is_constrained) - def _unread_loggsed_bounds(self, unread): """Manifest options lifting the BC grid's loggsed barrier on the stars whose SED flux nothing reads. @@ -711,35 +652,7 @@ def is_pin(entry): sigma = entry.get("sigma") return isinstance(sigma, (int, float)) and float(sigma) == 0.0 - return self._user_entry_stars(param, is_pin) - - def _user_entry_stars(self, param, predicate): - """Stars whose most specific params-file entry satisfies ``predicate``. - - The one lookup behind ``_user_prior_stars`` and - ``user_pinned_stars``, so the two cannot disagree about which entry - they are reading. Most specific spelling wins, as everywhere else, - which is why this stops at the first hit rather than unioning the - three (contrast ``Parameter._user_constraint_fields``, whose union is - a warning heuristic and does not have to adjudicate). - """ - params = getattr(self.config_manager, "user_params", None) or {} - if not params: - return [] - out = [] - for i in range(self.n_elements): - keys = [f"{self.prefix}.{i}.{param}"] - if i < len(self.names): - keys.append(f"{self.prefix}.{self.names[i]}.{param}") - keys.append(f"{self.prefix}.{param}") - for key in keys: - entry = user_entry(params, key) - if entry is None: - continue - if predicate(entry): - out.append(i) - break # most specific spelling wins - return out + return self.user_entry_elements(param, is_pin) def _apply_structure_activity(self, system): """Mark radius/teff/feh inactive on the stars nothing reads them for. diff --git a/tests/fixtures/mulens/ob170114.json b/tests/fixtures/mulens/ob170114.json index bd6a0fba..2d1881b1 100644 --- a/tests/fixtures/mulens/ob170114.json +++ b/tests/fixtures/mulens/ob170114.json @@ -1,6 +1,6 @@ { "config": "examples/ob170114/ob170114.yaml", - "n_terms": 94, + "n_terms": 92, "params": "examples/ob170114/ob170114.params.yaml", "platform": { "blas": "scipy-openblas", @@ -53,9 +53,6 @@ "planet.log_q_raw": [ 0.0 ], - "planet.radius_raw": [ - 0.0 - ], "source.t_0_raw": [ 0.0 ], @@ -117,7 +114,6 @@ "POT:logit_uniform_prior.orbit.xbigomega": -1.3863031568263726, "POT:logit_uniform_prior.orbit.ybigomega": -1.3863855696114586, "POT:logit_uniform_prior.planet.log_q": -1.6336116906951328, - "POT:logit_uniform_prior.planet.radius": -4.615221501842092, "POT:logit_uniform_prior.source.t_0": -2.4397022381963143, "POT:logit_uniform_prior.source.u_0": -1.386358363167978, "POT:logit_uniform_prior.star.distance": -5.976788841910725, @@ -178,7 +174,6 @@ "RV:orbit.xbigomega_raw": -0.9189385332046727, "RV:orbit.ybigomega_raw": -0.9189385332046727, "RV:planet.log_q_raw": -0.9189385332046727, - "RV:planet.radius_raw": -0.9189385332046727, "RV:source.t_0_raw": -0.9189385332046727, "RV:source.u_0_raw": -0.9189385332046727, "RV:star.distance_raw": -1.8378770664093453, @@ -190,5 +185,5 @@ "RV:star.rv_raw": -1.8378770664093453, "RV:star.teff_raw": -0.9189385332046727 }, - "total_logp": 5851.727910976616 + "total_logp": 5857.2620710116635 } diff --git a/tests/mulens_acceptance_replay.py b/tests/mulens_acceptance_replay.py index 23bbb533..422a9f9c 100644 --- a/tests/mulens_acceptance_replay.py +++ b/tests/mulens_acceptance_replay.py @@ -227,6 +227,15 @@ absolute motions, +3.7e-4 nats; `kinematic_prior` +0.2691, the three low-bound barriers (mu_rel_geo_mag, pi_rel, t_E) from up to 1e-3 to ~0, `event_rate_prior` -1e-6; total +0.2705 each. + +One fixture was re-recorded when a planet radius nothing reads became +inactive (star.md, "Which planets have a radius"; review 2.8.17, PR #608): +ob170114, the only microlensing example whose lens planet's radius was not +already pinned by hand. `planet.radius_raw` and its two terms left +(`RV:planet.radius_raw` -0.9189, `logit_uniform_prior.planet.radius` +-4.6152; total +5.5342 to 5857.2620710116635); every stored start value and +every other term is bit-identical. The hand-pinned fixtures (DC2018_128, +KMT-2019-BLG-1806, OGLE_0383LD) did not move. """ import glob diff --git a/tests/test_planet_radius_activity.py b/tests/test_planet_radius_activity.py new file mode 100644 index 00000000..171cfe16 --- /dev/null +++ b/tests/test_planet_radius_activity.py @@ -0,0 +1,263 @@ +"""planet.radius exists only where something reads it (review 2.8.17, #PR). + +A microlensing planet is read through its MASS (the lens's q); nothing in a +2L1S likelihood reads its radius. It used to be sampled anyway -- one free +dimension refilling its prior, plus R_P, rho_P and log g_P table rows that +were pure prior. `Planet.radius_consumers` is the readership predicate +(transit, rm, dopptom, the Chen & Kipping relation, a chord-sampling orbit, a +user prior), and `Planet._apply_radius_activity` makes the radius INACTIVE on +every planet it finds no reader for -- the treatment +`Star._apply_structure_activity` gives a star radius nothing reads -- with +density and logg inheriting the role (`Component._inherit_inactivity`). +""" + +import numpy as np +import pytest + +from exozippy.components.planet.planet import Planet +from exozippy.manifest import interpret_manifest_entry +from exozippy.system import System + + +def _binary_config(): + """Minimal single-source binary lens: star.Lens hosts planet b (lens + element 1). No data, no orbit: the static pairing a 2L1S fit uses.""" + return { + "star": [{"name": "Lens"}, {"name": "Source"}], + "planet": [{"name": "b"}], + "mulensevent": [{"finite_source": False}], + "lens": [{"body": "star.Lens"}, {"body": "planet.b"}], + "source": [{"body": "star.Source"}], + } + + +def _binary_params(extra=None): + p = { + "source.Source.t_0": {"initval": 2460025.0, "init_scale": 0.1}, + "source.Source.u_0": {"initval": 0.1, "init_scale": 0.01}, + "mulensevent.t_E": {"initval": 30.0, "init_scale": 1.0}, + "lens.b.s": {"initval": 0.98}, + "lens.b.alpha": {"initval": 60.0, "init_scale": 0.9}, + "lens.b.q": {"initval": 1e-3, "init_scale": 1e-4}, + } + for nm in ("Lens", "Source"): + p[f"star.{nm}.ra"] = {"initval": 264.0, "sigma": 0} + p[f"star.{nm}.dec"] = {"initval": -27.0, "sigma": 0} + # Stated proper motions, so the relaxation engine has no default-tier + # start to relax (see test_the_free_radius_leaves_with_only_its_own_terms: + # otherwise the comparison measures the solver's tolerance). + for nm, pm in (("Lens", -5.4), ("Source", -0.6)): + p[f"star.{nm}.pm_ra"] = {"initval": pm} + p[f"star.{nm}.pm_dec"] = {"initval": pm} + p.update(extra or {}) + return p + + +def _prepared(extra_params=None): + system = System(_binary_config(), user_params=_binary_params(extra_params)) + system.prepare() + return system + + +def _radius_active(planet): + """The per-planet activity the manifest declares for `radius`.""" + options = interpret_manifest_entry(planet.manifest["radius"]).options + mask = options.get("mask") + return ( + [True] * planet.n_elements if mask is None else [bool(m) for m in mask] + ) + + +def test_a_lens_planet_radius_is_inactive(): + """ + Given a 2L1S microlensing system whose companion is a planet, + When it is prepared, + Then nothing reads the planet's radius and the manifest declares it + inactive (still declared: density and logg name it in their deps). + """ + # Act + system = _prepared() + + # Assert + planet = system.planet + assert planet.radius_consumers(system) == [[]] + assert "radius" in planet.manifest + assert _radius_active(planet) == [False] + + +@pytest.mark.parametrize( + "entry", + [ + {"mu": 0.1, "sigma": 0.01}, + {"lower": 0.01}, + ], + ids=["prior", "bound"], +) +def test_a_user_constraint_on_the_radius_reads_it(entry): + """ + Given the same system with a params-file prior or bound on planet.radius, + When it is prepared, + Then the user's constraint is the reader and the radius stays active. + """ + # Act + system = _prepared({"planet.b.radius": dict(entry)}) + + # Assert + assert system.planet.radius_consumers(system) == [["user prior on radius"]] + assert _radius_active(system.planet) == [True] + + +def test_a_user_prior_on_a_quantity_derived_from_the_radius_reads_it(): + """ + Given a params-file prior on planet.density, which derives from radius, + When the system is prepared, + Then the radius stays active (the prior is a likelihood term in R_P). + """ + # Act + system = _prepared({"planet.density": {"mu": 1.3, "sigma": 0.2}}) + + # Assert + assert _radius_active(system.planet) == [True] + + +def test_a_user_pin_is_subsumed_by_the_inactive_role(): + """ + Given a params-file `sigma: 0` on planet.radius, + When the system is prepared, + Then it is a pin, not a reader, and the radius is inactive -- exactly + Star's rule for its structure parameters. + """ + # Act + system = _prepared({"planet.b.radius": {"initval": 0.1, "sigma": 0}}) + + # Assert + assert _radius_active(system.planet) == [False] + + +def test_chen_reads_the_radius(): + """ + Given the 2L1S system with `chen: true` forced on the planet, + When it is prepared, + Then the Chen & Kipping potential is the reader and the radius is active. + """ + # Arrange + config = _binary_config() + config["planet"][0]["chen"] = True + + # Act + system = System(config, user_params=_binary_params()) + system.prepare() + + # Assert + assert system.planet.radius_consumers(system) == [["chen"]] + assert _radius_active(system.planet) == [True] + + +def _term_logps(model, point): + """{term name: float} for every free RV, observed RV and potential.""" + names = [ + v.name for v in model.free_RVs + model.observed_RVs + model.potentials + ] + fn = model.compile_fn( + model.logp(sum=False, jacobian=True), + inputs=model.value_vars, + on_unused_input="ignore", + ) + return {n: float(np.sum(v)) for n, v in zip(names, fn(point), strict=True)} + + +def _start(system, model): + point = dict(model.initial_point()) + point.update(system.get_raw_start(model)) + return point + + +def _built(extra_params=None): + """(system, per-term start logps, raw start, free RV names).""" + system = _prepared(extra_params) + model = system.build_model() + terms = _term_logps(model, _start(system, model)) + return ( + system, + terms, + system.get_raw_start(model), + {v.name for v in model.free_RVs}, + ) + + +def _rule_off(monkeypatch): + """The behavior before review 2.8.17: every planet radius active.""" + monkeypatch.setattr( + Planet, "_apply_radius_activity", lambda self, system: None + ) + + +@pytest.mark.slow +def test_inactive_is_bit_identical_to_the_old_hand_pin(monkeypatch): + """ + Given the 2L1S system built now, and built with the rule switched off + but the radius pinned by hand (`sigma: 0`), which is how every shipped + microlensing example with a planet held it, + When each model's per-term logp is evaluated at its own start, + Then the two models sample the same leaves from the same start and every + term -- prior, potential and likelihood -- is BIT-IDENTICAL, so the hand + pins are redundant; and the rows derived from the bookkeeping radius + are not reported. + """ + # Arrange / Act + system, new, new_start, new_free = _built() + _rule_off(monkeypatch) + _, old, old_start, old_free = _built({"planet.b.radius": {"sigma": 0}}) + + # Assert + assert new_free == old_free + assert not any(n.startswith("planet.radius") for n in new_free) + assert new == old + assert set(new_start) == set(old_start) + for name, value in new_start.items(): + np.testing.assert_array_equal(value, old_start[name], err_msg=name) + assert np.isfinite(sum(new.values())) + planet = system.planet + for name in ("radius", "density", "logg"): + assert not getattr(planet, name).element_is_active(0), name + + +@pytest.mark.slow +def test_the_free_radius_leaves_with_only_its_own_terms(monkeypatch): + """ + Given the 2L1S system built now, and built with the rule switched off + and the radius left free (the old default: a sampled, prior-only + dimension), + When each model's per-term logp is evaluated at its own start, + Then exactly the planet.radius coordinate and its prior terms are gone, + and every other start coordinate and every shared term is + BIT-IDENTICAL. + + The fixture states the proper-motion starts on purpose. Left at their + defaults, the relaxation engine relaxes them jointly with every other + default-tier start, to a solver tolerance; the old radius was one more + seed in that solve (its defaults.yaml value seeds a SAMPLED element and + only fills an inactive one), so removing it moved the solved proper + motions by ~4e-9 mas/yr and the event-rate prior by 1.5e-8 nats. That + is a different start, not a different model, and stating the starts + removes it. + """ + # Arrange / Act + _, new, new_start, new_free = _built() + _rule_off(monkeypatch) + _, old, old_start, old_free = _built() + + # Assert: exactly the radius left the sampled set... + removed = old_free - new_free + assert removed and all(n.startswith("planet.radius") for n in removed), ( + removed + ) + assert new_free <= old_free + # ...with the terms it carried, and nothing else. + dropped = set(old) - set(new) + assert dropped and all("planet.radius" in n for n in dropped), dropped + assert set(new) <= set(old) + for name, value in new_start.items(): + np.testing.assert_array_equal(value, old_start[name], err_msg=name) + for name, value in new.items(): + assert value == old[name], (name, value, old[name]) diff --git a/tests/test_radius_prior.py b/tests/test_radius_prior.py index bbb75ebc..05e4c90c 100644 --- a/tests/test_radius_prior.py +++ b/tests/test_radius_prior.py @@ -21,6 +21,12 @@ JACOBIAN = "planet.radius_jacobian" +# A SAMPLED radius in a harness with no data. Since review 2.8.17 a planet +# radius nothing reads is inactive (Planet.radius_consumers), and an initval +# alone is not a reader; a user-stated support is. These are the +# defaults.yaml bounds restated, so the density under test is unchanged. +SAMPLED = {"initval": 1.0, "lower": 0.000001, "upper": 100.0} + def _values(model, nodes): """`nodes` rewritten onto the model's VALUE variables (compiling a @@ -65,7 +71,7 @@ def _build(radius_entries, n_planets=1, star_radius=None): @pytest.fixture(scope="module") def free_model(): - return _build([{"initval": 1.0}]) + return _build([dict(SAMPLED)]) @pytest.fixture(scope="module") @@ -103,7 +109,7 @@ def test_only_the_sampled_planet_of_a_mixed_pair_gets_the_term(): """One planet sampled, one pinned: the potential is -log R_* exactly once (both planets orbit the one star).""" system, model = _build( - [{"initval": 1.0}, {"initval": 0.5, "sigma": 0.0}], n_planets=2 + [dict(SAMPLED), {"initval": 0.5, "sigma": 0.0}], n_planets=2 ) pots = _jacobian_potentials(model) assert len(pots) == 1