diff --git a/AUTONOMY.md b/AUTONOMY.md index a787ef4b..60df894a 100644 --- a/AUTONOMY.md +++ b/AUTONOMY.md @@ -607,10 +607,10 @@ names are unaffected, and so is the rest of the 2026-11-04 grant. The public-API rule "not adopted" on 2026-11-04 is adopted now, in this narrower form. -**Enforcement.** Until the close-out and review checks detect this from the -diff (PyAutoMind `draft/feature/pyautobrain/glance_public_name_check.md`), the -shipping session or the watcher's close-out applies it by reading the diff. -Doubt means `/prm`. +**Enforcement.** Enforced by `bin/public_names.py` (PyAutoBrain#641): the +shift watcher runs it before any close-out session spawns, and refuses on an +added or renamed name or a diff it cannot read, and the ship skills and `/prm` +"Tiered merge" run it as a stop. Doubt means `/prm`. ## Stage-2 adversary amendment — 2026-11-04 @@ -979,6 +979,18 @@ one comments read or one status write in a tick, and a command enacted from any other login or enacted twice: any of these retires the watcher to fake mode. +**Amendment — 2026-11-16 (PyAutoBrain#641), approved by the human.** For the +"Public-name narrowing of `glance` — 2026-11-16", the watcher may also make +read-only `gh api` GET calls (the PR itself for its base and head shas, +`compare` to find the merge base, the PR's file list, the before/after file +contents, and one `contents/` read at head to confirm the package +directory exists) on the **library** PRs its own +workers named, once per close-out and before any close-out session spawns. +These calls make no writes, and a call that fails gives "cannot tell", which +refuses the merge. A PR in any other repo makes no call at all. The revert +condition covers these the same way: any other call, or a repeat for the same +close-out, retires the watcher to fake mode. + ## Human override for Heart RED (development only) Heart RED still parks every autonomous run and blocks every release. After the diff --git a/agents/conductors/batch/_orchestrator.py b/agents/conductors/batch/_orchestrator.py index 3ce6c723..7d4fcacd 100644 --- a/agents/conductors/batch/_orchestrator.py +++ b/agents/conductors/batch/_orchestrator.py @@ -288,7 +288,9 @@ def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, """The close-out session template filled in for one PR (phase 4b). Its Heart check is the scoped development-ship gate for the PR's repo (leg 4, PyAutoHeart#340): only `green` merges. Its CI check is `pyauto-brain - ci-verdict` on the PR (PyAutoBrain#628): only `GREEN` merges.""" + ci-verdict` on the PR (PyAutoBrain#628): only `GREEN` merges. Its + public-name check is `pyauto-brain public-names` (PyAutoBrain#641): an + added or renamed public library name, or a diff it cannot read, refuses.""" repos = pr_repos(pr_url) heart_cmd = (f"bash -c 'source \"{COMMON_SH}\"; consult_vitals_verdict --repos {repos}'" if repos else "") @@ -298,6 +300,8 @@ def closeout_prompt(task: str, pr_url: str, prompt_path: str, brief_path: Path, shift_ledger=SHIFT_LEDGER, pr_repos=repos or "(none — not a GitHub PR URL)", heart_cmd=heart_cmd or "(cannot be scoped — refuse)", ci_verdict_cmd=f"{BRAIN_CLI} ci-verdict {pr_url}" if repos + else "(not a GitHub PR URL — refuse)", + public_names_cmd=f"{BRAIN_CLI} public-names {pr_url}" if repos else "(not a GitHub PR URL — refuse)") @@ -398,16 +402,38 @@ def run_scoped(run, argv: list[str], task: str, **kw): return res +#: The verdict fields of a close-out the watcher refused before any session. +PRESPAWN_GATE = "public-name check (watcher, before spawn)" +PRESPAWN_MODEL = "none — no close-out session started" + + +def public_names_gate(pr_url: str, check=None) -> str: + """The deterministic public-name check (AUTONOMY.md "Public-name + narrowing of `glance` — 2026-11-16", PyAutoBrain#641) on one PR, run by + the watcher before a close-out session spawns: '' to go on, else the + refusal's `why`. A repo outside the ruled libraries goes on; a hit or a + check that cannot tell refuses.""" + try: + if check is None: + sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "bin")) + import public_names as check # noqa: E402 — bin/, beside ci_verdict.py + v = check.for_pr(pr_url) + except Exception as e: # anything unexpected: fail closed + return f"public-name check could not tell: {str(e)[:200]} → human /prm" + return check.reason(v) if v.get("verdict") != "CLEAN" else "" + + class RealSpawner: """`claude --bg` workers from the session template (phase 3b).""" real = True def __init__(self, brief_path: Path, mode: str, cwd: Path | None = None, run=None, - gh=None): + gh=None, public_names=None): self.brief_path, self.mode, self.cwd = Path(brief_path), mode, cwd self.run = run or subprocess.run self.gh = gh or gh_pr_state + self.public_names = public_names or public_names_gate def pr_state(self, url: str) -> dict | None: """GitHub's word on a PR — the merge truth for a close-out (#603).""" @@ -431,6 +457,15 @@ def spawn(self, task: str, prompt_path: str, lease_dir: Path, return {"pid": 0, "agent_id": m.group(1), "session_id": None, "mode": self.mode} def spawn_closeout(self, task: str, pr_url: str, prompt_path: str, lease_dir: Path) -> dict: + # The public-name check runs here, deterministically, before any + # session (#641): a hit or a cannot-tell is this PR's refusal, written + # as the verdict a close-out would write, and nothing is spawned. + why = self.public_names(pr_url) + if why: + verdict = {"result": "refused", "pr": pr_url, "why": why, + "gate": PRESPAWN_GATE, "model": PRESPAWN_MODEL} + (Path(lease_dir) / f"{task}.closeout").write_text(json.dumps(verdict)) + return {"pid": 0, "agent_id": None} argv = closeout_command(task, pr_url, prompt_path, self.brief_path, lease_dir, self.mode) # The same scoped route as a worker (#634): a close-out may be the diff --git a/agents/conductors/batch/closeout_template.md b/agents/conductors/batch/closeout_template.md index f35ce14c..c4d53433 100644 --- a/agents/conductors/batch/closeout_template.md +++ b/agents/conductors/batch/closeout_template.md @@ -14,7 +14,16 @@ outcome — the human merges by `/prm` at check-in. head. Record what decided it. 2. Review the diff adversarially: look for a changed default, a user-visible error message, a removed or weakened test, a renamed public thing, or a - wrong docs claim. Any one of them → refuse. + wrong docs claim. Any one of them → refuse. Added or renamed public + library names are decided by the one check (AUTONOMY.md "Public-name + narrowing of `glance` — 2026-11-16", PyAutoBrain#641). The watcher ran it + before starting you; run it again, as a second layer: + + {public_names_cmd} + + Exit 0 passes (a repo the ruling does not cover prints CLEAN). Exit 1 (a + public name added or renamed) or 2 (it cannot tell) refuses, with its first + output line as the `why`: `public name added/renamed: → human /prm`. 3. Refuse if the PR carries the `decision-taken` label, if its tier is not `glance`, or unless Heart's **scoped development-ship verdict** for the PR's repo ({pr_repos}) is `green` (AUTONOMY.md leg 4, PyAutoHeart#340): diff --git a/agents/faculties/review/AGENTS.md b/agents/faculties/review/AGENTS.md index 4710470d..a1e252aa 100644 --- a/agents/faculties/review/AGENTS.md +++ b/agents/faculties/review/AGENTS.md @@ -44,7 +44,12 @@ Heart and the agent reasons over the verdict. or, for an in-place task with no worktree, the checkouts its `active.md` `- repos:` block claims — or explicit repo paths and emits, per repo: merge-base against `origin/main`, commits ahead, diff stat, changed files, and risk flags (public-API-shaped paths, - config/schema files, tests changed or not, generated files). + config/schema files, tests changed or not, generated files). For a + library repo it also lists the **public-name delta** (`public_names`, + from `bin/public_names.py`, PyAutoBrain#641): an added or renamed public + name raises `public-name-added-or-renamed`, and the merge is a human + `/prm` whatever the tier (AUTONOMY.md "Public-name narrowing of `glance` + — 2026-11-16"). Say so in the verdict; it is not a code finding. 2. The reviewing agent runs, over that surface: a **code review at high effort** (correctness first, then reuse/simplification) and a **verify pass** — drive the affected flow end-to-end, not just tests (for diff --git a/agents/faculties/review/_review.py b/agents/faculties/review/_review.py index 8a67c49c..0621b2f2 100755 --- a/agents/faculties/review/_review.py +++ b/agents/faculties/review/_review.py @@ -33,6 +33,11 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2])) import _pyauto_root # noqa: E402 +# The one public-name check (PyAutoBrain#641), shared with the close-out and +# the tiered merge; it lives beside ci_verdict.py in bin/. +sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "bin")) +import public_names # noqa: E402 + WT_BASE = _pyauto_root.pyauto_wt_root() # Paths that smell like public API / behaviour when changed — flags only, @@ -113,6 +118,11 @@ def repo_surface(repo: Path) -> dict | None: flags.append(name) if any(f.endswith(".py") and "test" not in f.lower() for f in changed): flags.append("python-source") + names = public_name_delta(repo, base) + if names and names["verdict"] == public_names.HIT: + flags.append("public-name-added-or-renamed") + elif names and names["verdict"] == public_names.CANNOT: + flags.append("public-names-cannot-tell") return { "repo": repo.name, "path": str(repo), @@ -124,9 +134,22 @@ def repo_surface(repo: Path) -> dict | None: "files": files, "risk_flags": flags, "claims_to_falsify": claims, + **({"public_names": names} if names else {}), } +def public_name_delta(repo: Path, base: str) -> dict | None: + """The public-name delta of a library repo's branch (AUTONOMY.md + "Public-name narrowing of `glance` — 2026-11-16"): added and renamed + names send the merge to a human `/prm`. None for a repo the ruling does + not cover.""" + v = public_names.for_range(repo, f"{base}..HEAD") + if v.get("not_library"): + return None + keep = ("verdict", "added", "renamed", "removed", "cannot_tell") + return {**{k: v[k] for k in keep}, "reason": public_names.reason(v)} + + def in_place_repos(task: str) -> list[Path]: """Checkouts claimed by an in-place task (worktree: none) in active.md. @@ -208,6 +231,12 @@ def emit_human(surfaces: list[dict], witness: str = "", adversary: bool = False) print(f" {f}") if len(s["files"]) > 40: print(f" ... and {len(s['files']) - 40} more") + names = s.get("public_names") + if names: + print(f" public names: {names['verdict']}" + + (f" — {names['reason']}" if names["reason"] else "")) + for e in names["removed"]: + print(f" info — removed: {e['module']}.{e['name']}") claims = s.get("claims_to_falsify") or [] if claims: print(" claims to falsify (adversarial pass — for EACH: what would") diff --git a/bin/README.md b/bin/README.md index ed7d3369..155cedad 100644 --- a/bin/README.md +++ b/bin/README.md @@ -18,6 +18,14 @@ Executable tooling for the PyAuto organism. mergeability → GREEN / PENDING / RED with reasons; exit 0 · 2 · 1. `/prm` step 2 and the shift close-out run it; the watcher's `pr_health` feeds its `gh pr checks` rows to the same `judge`. +- **`public_names.py`** — `pyauto-brain public-names #`, or + `--repo --range a..b`: does a change add or rename a public name in + a library package (PyAutoBrain#641; AUTONOMY.md "Public-name narrowing of + `glance` — 2026-11-16")? `ast` over each changed module before and after; + exit 0 CLEAN (or not a library repo) · 1 HIT · 2 cannot tell. The shift + watcher refuses on 1 or 2 before any close-out session spawns, the + close-out and the in-turn tiered merge stop on them too, and the review + faculty lists the delta in its ReviewSurface. - **`lane_backfill.py`** — proposes a `Lane:` for every lane-less draft in the planner pool, from intake's own lane signals, as a table for a human to skim; `--apply [--from ]` writes the headers (commits nothing). diff --git a/bin/public_names.py b/bin/public_names.py new file mode 100644 index 00000000..b4dd7fe1 --- /dev/null +++ b/bin/public_names.py @@ -0,0 +1,698 @@ +#!/usr/bin/env python3 +"""bin/public_names.py — does a change add or rename a public library name? +(PyAutoBrain#641) + + pyauto-brain public-names # [--json] + pyauto-brain public-names --repo --range .. [--json] + pyauto-brain public-names --repo-name --before --after [--json] + +WHY. AUTONOMY.md "Public-name narrowing of `glance` — 2026-11-16": a change +that adds or renames a public name in a library package goes to a human `/prm`, +whatever its declared `Consequence:`. The seeded audit's one amended row (row +08, `latent-profile-declarations`) added seven public `latent_*_from` helpers +that no CI, witness or reviewer leg caught. One implementation, run three +ways: deterministically by the shift watcher before it spawns any close-out +session (`_orchestrator.RealSpawner.spawn_closeout`: a hit or a cannot-tell +writes the refusal and no session starts), as a stop in the in-turn tiered +merge (`/prm` reference.md "Tiered merge", the ship skills) and again in the +close-out prompt; the review faculty lists the delta in its ReviewSurface. + +WHAT IS PUBLIC (per module, parsed with `ast`, before and after): + * a module-level `def`, `async def` or `class`, or a `NAME = …` assignment, + whose name has no leading underscore — including ones under a module-level + `if` / `try` / `with`; + * in a package `__init__.py`, also every name it imports (a re-export) and + every `__all__` entry (`=`, `+=`, `.extend(...)`, `.append(...)`); a + `from x import *` counts as the name `* from x`. + +WHICH REPOS. The libraries the ruling names, listed in `config/policy.yaml` +`public_name_libraries:` (a declared config surface), matched case-folded +(owner, repo and list). Membership is decided before the body map is read, so +a repo outside the list passes even when PyAutoMind is unreadable. A listed +library's package directory is its body-map `package:` (PyAutoMind +`repos.yaml`); no package, an unreadable map or config, or a package directory +missing on the head side cannot tell: the check fails closed rather than pass +a library it did not read. + +WHAT IS COMPARED. Only `.py` files under that package directory. Ignored: other +repos (workspaces, organs, assistants), tests (`tests/`, `test_*.py`, `conftest.py`), private +modules (a path part with a leading underscore, other than a dunder file such +as `__init__.py`), private names, and every non-`.py` file — stubs (`.pyi`) +included. A package `__init__` that star-imports (`from .x import *`) a +private module the diff changed, or a star import that cannot be resolved, +cannot tell: what it re-exports is not compared. A changed public module's +names are compared directly, so its star import adds nothing. + +THE VERDICT. `added` names (new in their module), and `renamed` ones: a public +name removed and another added in the same module, paired best-effort (same +kind, alike spelling). Either is a HIT. A removal with no +addition beside it is not covered by the ruling: it is listed as info. A file +that cannot be read or parsed on either side means the check cannot tell — it +fails closed (`/prm`), as does an unreadable `gh` reply. + +Exit status: 0 CLEAN (or not a library repo), 1 HIT, 2 CANNOT-TELL, 64 usage. +`--json` prints one object. `gh` and `git` are behind the `run` seam (a +`subprocess.run`-shaped callable), so the tests are offline. +""" + +from __future__ import annotations + +import argparse +import ast +import difflib +import json +import subprocess +import sys +import urllib.parse +from pathlib import Path, PurePosixPath +from typing import Callable, Iterable + +import re + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from ci_verdict import GhError, UsageError, _gh, parse_ref # noqa: E402 + +BRAIN_HOME = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN_HOME / "agents")) +import _pyauto_root # noqa: E402 +from _repo_paths import repo_path # noqa: E402 + +CLEAN, HIT, CANNOT = "CLEAN", "HIT", "CANNOT-TELL" +EXIT = {CLEAN: 0, HIT: 1, CANNOT: 2} +EXIT_USAGE = 64 + +POLICY_PATH = BRAIN_HOME / "config" / "policy.yaml" +#: The Mind is an organ: its name is framework identity, not an instance fact. +MIND_REPO = "PyAuto" + "Mind" + +#: Names listed before `+N more` in the one-line reason (the digest line). +REASON_NAMES = 8 + +#: `pulls//files` stops at this many files: a PR that reaches it is unread. +GH_FILES_CAP = 3000 + + +class LibrariesError(RuntimeError): + """The library list or its packages cannot be read: cannot tell.""" + + +def _flow_list(text: str, key: str) -> list[str] | None: + """A top-level `key: [a, b, …]` flow list, by a stdlib regex (no PyYAML — + the close-out may run on a bare `python3`).""" + m = re.search(rf"^{re.escape(key)}:\s*\[([^\]]*)\]", text, re.M) + if not m: + return None + return [x.strip().strip("'\"") for x in m.group(1).split(",") if x.strip()] + + +def body_map_packages(text: str) -> dict[str, str]: + """repo name → `package:` from the body map's two-level `repos:` block + (two-space repo keys, four-space fields), without PyYAML.""" + out: dict[str, str] = {} + in_repos, current = False, None + for line in text.splitlines(): + if not line.strip() or line.lstrip().startswith("#"): + continue + if not line.startswith(" "): + in_repos, current = line.startswith("repos:"), None + continue + if not in_repos: + continue + m = re.match(r"^ ([A-Za-z0-9._-]+):\s*(#.*)?$", line) + if m: + current = m.group(1) + continue + m = re.match(r"^ package:\s*['\"]?([A-Za-z0-9_.]+)['\"]?\s*(#.*)?$", line) + if m and current: + out[current] = m.group(1) + return out + + +def ruled_libraries(policy_path: Path = POLICY_PATH) -> list[str]: + """The `public_name_libraries:` list. Raises LibrariesError without it.""" + try: + names = _flow_list(Path(policy_path).read_text(encoding="utf-8"), + "public_name_libraries") + except OSError as e: + raise LibrariesError(f"config/policy.yaml unreadable: {e}") from e + if not names: + raise LibrariesError("no `public_name_libraries:` list in config/policy.yaml") + return names + + +def _body_map(map_path: Path | None = None) -> dict[str, str]: + """casefolded repo name → package, from the body map.""" + if map_path is None: + map_path = repo_path(_pyauto_root.pyauto_root(), MIND_REPO) / "repos.yaml" + try: + text = Path(map_path).read_text(encoding="utf-8") + except OSError as e: + raise LibrariesError(f"the body map is unreadable: {e}") from e + return {k.casefold(): v for k, v in body_map_packages(text).items()} + + +def load_libraries(policy_path: Path = POLICY_PATH, map_path: Path | None = None) -> dict: + """{library repo: package directory} for every ruled library. Raises + LibrariesError when the list, the body map or a package is missing.""" + names = ruled_libraries(policy_path) + packages = _body_map(map_path) + missing = [n for n in names if n.casefold() not in packages] + if missing: + raise LibrariesError("no body-map `package:` for " + ", ".join(missing)) + return {n: packages[n.casefold()] for n in names} + + +def repo_key(repo: str) -> str: + """`Owner/Repo`, a path, a URL or a bare name → the casefolded repo name.""" + name = PurePosixPath(str(repo or "").rstrip("/")).name + if name.endswith(".git"): + name = name[:-4] + return name.casefold() + + +def library_package(repo: str, libs: dict | None = None, + policy_path: Path = POLICY_PATH, map_path: Path | None = None) -> str | None: + """The package directory of a ruled library repo, matched case-folded, or + None for any repo the ruling does not cover. Membership comes from `libs` + or the policy list first, so the body map is read only for a library; + LibrariesError when a library's package cannot be found.""" + key = repo_key(repo) + if libs is not None: + return {k.casefold(): v for k, v in libs.items()}.get(key) + match = [n for n in ruled_libraries(policy_path) if n.casefold() == key] + if not match: + return None + package = _body_map(map_path).get(key) + if not package: + raise LibrariesError(f"no body-map `package:` for {match[0]}") + return package + + +def is_library_module(path: str, package: str) -> bool: + """Whether `path` (repo-relative, `/`-separated) is a public module of + `package`: a `.py` under it, not a test, not under a private part.""" + parts = PurePosixPath(path).parts + if len(parts) < 2 or parts[0] != package or not path.endswith(".py"): + return False + name = parts[-1] + if name == "conftest.py" or name.startswith("test_") or name.endswith("_test.py"): + return False + for part in parts[1:]: + if part in ("test", "tests"): + return False + stem = part[:-3] if part.endswith(".py") else part + if stem.startswith("_") and not (stem.startswith("__") and stem.endswith("__")): + return False + return True + + +def module_name(path: str) -> str: + """`autogalaxy/profiles/__init__.py` → `autogalaxy.profiles`.""" + parts = list(PurePosixPath(path).with_suffix("").parts) + if parts and parts[-1] == "__init__": + parts.pop() + return ".".join(parts) + + +# --- the names one module makes public --------------------------------------------- + +def _bound(target) -> Iterable[str]: + if isinstance(target, ast.Name): + yield target.id + elif isinstance(target, (ast.Tuple, ast.List)): + for elt in target.elts: + yield from _bound(elt) + elif isinstance(target, ast.Starred): + yield from _bound(target.value) + + +def _strings(node) -> list[str]: + if isinstance(node, (ast.List, ast.Tuple)): + return [e.value for e in node.elts + if isinstance(e, ast.Constant) and isinstance(e.value, str)] + return [] + + +def _module_statements(body: list) -> Iterable[ast.stmt]: + """Every statement at module level, through `if` / `try` / `with` blocks + (never into a function or class body).""" + for stmt in body: + yield stmt + blocks = [] + if isinstance(stmt, ast.If): + blocks = [stmt.body, stmt.orelse] + elif isinstance(stmt, (ast.With, ast.AsyncWith)): + blocks = [stmt.body] + elif isinstance(stmt, ast.Try) or type(stmt).__name__ == "TryStar": + blocks = [stmt.body, stmt.orelse, stmt.finalbody, + *[h.body for h in stmt.handlers]] + for block in blocks: + yield from _module_statements(block) + + +def public_names(source: str, is_init: bool = False) -> dict[str, str]: + """The public names of one module's source, `{name: kind}` — kind is + `def`, `class`, `assign`, `import` or `__all__`. Raises SyntaxError or + ValueError when the source does not parse.""" + tree = ast.parse(source) + names: dict[str, str] = {} + for stmt in _module_statements(tree.body): + if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)): + names[stmt.name] = "def" + elif isinstance(stmt, ast.ClassDef): + names[stmt.name] = "class" + elif isinstance(stmt, (ast.Assign, ast.AnnAssign, ast.AugAssign)): + targets = stmt.targets if isinstance(stmt, ast.Assign) else [stmt.target] + for t in targets: + for n in _bound(t): + if n == "__all__" and is_init and stmt.value is not None: + for s in _strings(stmt.value): + names.setdefault(s, "__all__") + elif not isinstance(stmt, ast.AugAssign): + names[n] = "assign" + elif (is_init and isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call) + and isinstance(stmt.value.func, ast.Attribute) + and isinstance(stmt.value.func.value, ast.Name) + and stmt.value.func.value.id == "__all__" + and stmt.value.func.attr in ("extend", "append")): + for arg in stmt.value.args: + found = _strings(arg) if stmt.value.func.attr == "extend" else ( + [arg.value] if isinstance(arg, ast.Constant) + and isinstance(arg.value, str) else []) + for s_ in found: + names.setdefault(s_, "__all__") + elif is_init and isinstance(stmt, ast.Import): + for a in stmt.names: + names[a.asname or a.name.split(".")[0]] = "import" + elif is_init and isinstance(stmt, ast.ImportFrom): + if stmt.module == "__future__": + continue + src = "." * (stmt.level or 0) + (stmt.module or "") + for a in stmt.names: + if a.name == "*": + names[f"* from {src}"] = "import" + else: + names[a.asname or a.name] = "import" + return {n: k for n, k in names.items() if not n.startswith("_")} + + +# --- the comparison ----------------------------------------------------------------- + +#: How alike two spellings must be (difflib ratio) to be read as a rename. +RENAME_RATIO = 0.4 + + +def _pair_renames(removed: dict[str, str], added: dict[str, str]): + """Best-effort pairing of one module's removed and added names into + renames: the same kind (`def`, `class`, ...) and alike spellings, the + closest pair first. A name left unpaired stays added (a hit either way) + or removed (info). Returns (renames [(old, new)], added left, removed + left).""" + removed, added = dict(removed), dict(added) + renames = [] + pairs = sorted( + ((difflib.SequenceMatcher(None, old, new).ratio(), old, new) + for old in removed for new in added if removed[old] == added[new]), + key=lambda p: (-p[0], p[1], p[2])) + for ratio, old, new in pairs: + if ratio >= RENAME_RATIO and old in removed and new in added: + renames.append((old, new)) + del removed[old], added[new] + return renames, added, removed + + +def star_sources(source: str, init_path: str) -> list[str | None]: + """The modules a package `__init__` star-imports, as dotted names; None + for a relative import that climbs above the top-level package.""" + pkg = module_name(init_path).split(".") + out: list[str | None] = [] + for stmt in _module_statements(ast.parse(source).body): + if isinstance(stmt, ast.ImportFrom) and any(a.name == "*" for a in stmt.names): + level = stmt.level or 0 + if level - 1 >= len(pkg): + out.append(None) + continue + base = pkg[:len(pkg) - (level - 1)] if level else [] + out.append(".".join(base + ([stmt.module] if stmt.module else []))) + return out + + +def _private_module(dotted: str) -> bool: + """A module path with a private part (a leading underscore, not dunder).""" + return any(part.startswith("_") and not (part.startswith("__") and part.endswith("__")) + for part in dotted.split(".")[1:]) + + +def star_import_hazards(package: str, changes, after: Callable[[str], str]) -> list[str]: + """Each package `__init__` (after the change) whose star import re-exports + names this check does not compare: a star import of a **private** module + the diff changed (its names are ignored as private, yet the `__init__` + makes them public), or one that cannot be resolved. A star import of a + changed public module adds nothing: that module's names are compared + directly. An `__init__` that cannot be read is no package file (a + namespace package).""" + changed = {module_name(p) for pair in changes for p in pair + if p and p.endswith(".py") and PurePosixPath(p).parts[:1] == (package,)} + inits = {"/".join(m.split(".")[:i]) + "/__init__.py" + for m in changed for i in range(1, len(m.split(".")))} + out = [] + for init in sorted(inits): + try: + source = after(init) + except Exception: + continue + try: + stars = star_sources(source, init) + except (SyntaxError, ValueError) as e: + out.append(f"{init} (after) does not parse: {type(e).__name__}") + continue + for src in stars: + if src is None: + out.append(f"{init} has a star import that cannot be resolved") + elif src in changed and _private_module(src): + out.append(f"{init} star-imports `{src}`, a private module the diff " + "changed") + return out + + +def compare(package: str, changes: Iterable[tuple[str | None, str | None]], + before: Callable[[str], str], after: Callable[[str], str]) -> dict: + """The public-name delta over the changed files. + + `changes` are (path before, path after) — None where the file did not + exist on that side; a renamed file has both. `before` / `after` read a + path's source on that side (they raise to say it could not be read). + Only library modules of `package` are compared.""" + changes = list(changes) + added, renamed, removed = [], [], [] + cannot = star_import_hazards(package, changes, after) + modules = 0 + for old, new in changes: + old = old if old and is_library_module(old, package) else None + new = new if new and is_library_module(new, package) else None + if not old and not new: + continue + modules += 1 + sides = {} + for side, path, read in (("before", old, before), ("after", new, after)): + if not path: + sides[side] = {} + continue + try: + sides[side] = public_names(read(path), path.endswith("__init__.py")) + except (SyntaxError, ValueError, UnicodeDecodeError) as e: + cannot.append(f"{path} ({side}) does not parse: " + f"{type(e).__name__}: {str(e)[:120]}") + except Exception as e: # an unreadable side: fail closed + cannot.append(f"{path} ({side}) could not be read: {str(e)[:160]}") + if len(sides) < 2: + continue + b, a = sides["before"], sides["after"] + if old and new and old != new: + # A moved module: its names are new at the new path. + for n, k in sorted(a.items()): + added.append({"module": module_name(new), "name": n, "kind": k}) + for n, k in sorted(b.items()): + removed.append({"module": module_name(old), "name": n, "kind": k}) + continue + mod = module_name(new or old) + gone = {n: k for n, k in b.items() if n not in a} + new_names = {n: k for n, k in a.items() if n not in b} + pairs, new_names, gone = _pair_renames(gone, new_names) + renamed += [{"module": mod, "old": o, "new": n, "kind": a[n]} for o, n in pairs] + added += [{"module": mod, "name": n, "kind": k} for n, k in sorted(new_names.items())] + removed += [{"module": mod, "name": n, "kind": k} for n, k in sorted(gone.items())] + verdict = CANNOT if cannot else HIT if (added or renamed) else CLEAN + return {"verdict": verdict, "added": added, "renamed": renamed, "removed": removed, + "cannot_tell": cannot, "modules_compared": modules} + + +def label(entry: dict) -> str: + if "old" in entry: + return f"{entry['module']}.{entry['new']} (renamed from {entry['old']})" + return f"{entry['module']}.{entry['name']}" + + +def reason(v: dict) -> str: + """The one-line refusal reason the close-out writes as its `why` (and the + digest shows); empty for a CLEAN.""" + if v["verdict"] == CANNOT: + return ("public-name check could not tell: " + "; ".join(v["cannot_tell"][:2]) + + (f"; +{len(v['cannot_tell']) - 2} more" if len(v["cannot_tell"]) > 2 else "") + + " → human /prm") + if v["verdict"] == HIT: + names = [label(e) for e in v["renamed"]] + [label(e) for e in v["added"]] + shown = ", ".join(names[:REASON_NAMES]) + more = f" +{len(names) - REASON_NAMES} more" if len(names) > REASON_NAMES else "" + return f"public name added/renamed: {shown}{more} → human /prm" + return "" + + +def summary(v: dict) -> str: + head = v.get("subject") or "?" + if v.get("not_library"): + return (f"{CLEAN}: {head} is not a library repo — the public-name ruling " + "does not apply") + if v["verdict"] == CLEAN: + lines = [f"{CLEAN}: no public name added or renamed in {head} " + f"({v['modules_compared']} library module(s) compared)"] + else: + lines = [reason(v)] + for e in v["renamed"]: + lines.append(f" renamed: {e['module']}.{e['old']} → {e['new']} ({e['kind']})") + for e in v["added"]: + lines.append(f" added: {e['module']}.{e['name']} ({e['kind']})") + for c in v["cannot_tell"]: + lines.append(f" cannot tell: {c}") + for e in v["removed"]: + lines.append(f" info — removed (not covered by the ruling): " + f"{e['module']}.{e['name']} ({e['kind']})") + return "\n".join(lines) + + +def missing_package(package: str) -> str: + return (f"package directory `{package}/` is missing at the head — the body " + "map's `package:` may be stale") + + +def _cannot(subject: str, why: str) -> dict: + return {"subject": subject, "verdict": CANNOT, "added": [], "renamed": [], + "removed": [], "cannot_tell": [why], "modules_compared": 0} + + +def _not_library(subject: str) -> dict: + return {"subject": subject, "verdict": CLEAN, "not_library": True, "added": [], + "renamed": [], "removed": [], "cannot_tell": [], "modules_compared": 0} + + +# --- the reads: a local checkout, two trees, or a PR via `gh` ----------------------- + +def _git(run, repo: Path, *args: str) -> str: + res = run(["git", "-C", str(repo), *args], capture_output=True, text=True, + timeout=120) + if res.returncode != 0: + tail = ((res.stderr or res.stdout or "").strip().splitlines() or ["no output"])[-1] + raise RuntimeError(f"git {' '.join(args[:2])} exited {res.returncode}: {tail[:200]}") + return res.stdout + + +def repo_name(repo: Path, run=None) -> str: + """The repo a checkout holds: its `origin` remote's name, else the folder's + (a task worktree folder is named for its repo).""" + run = run or subprocess.run + try: + url = _git(run, repo, "remote", "get-url", "origin").strip() + if url: + return PurePosixPath(url.rstrip("/").replace(":", "/")).name.removesuffix(".git") + except Exception: + pass + return Path(repo).resolve().name + + +def name_status_changes(text: str) -> list[tuple[str | None, str | None]]: + """`git diff --name-status -M` lines → (before path, after path) pairs.""" + out = [] + for line in text.splitlines(): + parts = line.split("\t") + if len(parts) < 2: + continue + st = parts[0][:1] + if st in "RC" and len(parts) >= 3: + out.append((parts[1] if st == "R" else None, parts[2])) + elif st == "A": + out.append((None, parts[1])) + elif st == "D": + out.append((parts[1], None)) + else: + out.append((parts[1], parts[1])) + return out + + +def for_range(repo: Path, rng: str, name: str = "", run=None, + libs: dict | None = None) -> dict: + """The check over `a..b` (or `a...b`) in a local checkout: the before + side is `merge-base a b`, as a PR's diff is.""" + run = run or subprocess.run + repo = Path(repo) + name = name or repo_name(repo, run) + subject = f"{name} {rng}" + try: + package = library_package(name, libs) + except LibrariesError as e: + return _cannot(subject, str(e)) + if not package: + return _not_library(subject) + sep = "..." if "..." in rng else ".." + a, _, b = rng.partition(sep) + if not a or not b: + raise UsageError(f"not a range: {rng!r} (want ..)") + try: + base = _git(run, repo, "merge-base", a, b).strip() or a + head = _git(run, repo, "rev-parse", "--verify", f"{b}^{{commit}}").strip() + changes = name_status_changes( + _git(run, repo, "diff", "--name-status", "-M", base, head, "--", package)) + except Exception as e: + return _cannot(subject, f"the range could not be read: {e}") + try: + _git(run, repo, "cat-file", "-e", f"{head}:{package}") + except Exception: + return _cannot(subject, missing_package(package)) + v = compare(package, changes, lambda p: _git(run, repo, "show", f"{base}:{p}"), + lambda p: _git(run, repo, "show", f"{head}:{p}")) + return {"subject": subject, "base": base, "head": head, **v} + + +def for_trees(before: Path, after: Path, name: str, libs: dict | None = None) -> dict: + """The check over two trees on disk (each a copy of the repo root).""" + subject = f"{name} {before} → {after}" + try: + package = library_package(name, libs) + except LibrariesError as e: + return _cannot(subject, str(e)) + if not package: + return _not_library(subject) + before, after = Path(before), Path(after) + if not (after / package).is_dir(): + return _cannot(subject, missing_package(package)) + paths = set() + for root in (before, after): + pkg = root / package + if pkg.is_dir(): + paths |= {p.relative_to(root).as_posix() for p in pkg.rglob("*.py")} + changes = [] + for p in sorted(paths): + b, a = before / p, after / p + if b.is_file() and a.is_file() and b.read_bytes() == a.read_bytes(): + continue + changes.append((p if b.is_file() else None, p if a.is_file() else None)) + v = compare(package, changes, lambda p: (before / p).read_text(encoding="utf-8"), + lambda p: (after / p).read_text(encoding="utf-8")) + return {"subject": subject, **v} + + +def _gh_raw(run, repo: str, path: str, ref: str) -> str: + """One file's source at `ref`, read-only, through the contents API.""" + argv = ["gh", "api", "-H", "Accept: application/vnd.github.raw", + f"repos/{repo}/contents/{urllib.parse.quote(path)}?ref={ref}"] + res = run(argv, capture_output=True, text=True, timeout=120) + if res.returncode != 0: + tail = ((res.stderr or res.stdout or "").strip().splitlines() or ["no output"])[-1] + raise GhError(f"contents {path}@{ref[:10]} exited {res.returncode}: {tail[:160]}") + return res.stdout + + +def for_pr(ref: str, run=None, libs: dict | None = None) -> dict: + """The check over one pull request, read-only through `gh api`: the + before side is the merge base of its base and head, as GitHub's diff is.""" + run = run or subprocess.run + repo, number = parse_ref(ref) + subject = f"{repo}#{number}" + try: + package = library_package(repo, libs) + except LibrariesError as e: + return _cannot(subject, str(e)) + if not package: + return _not_library(subject) + try: + got = _gh(run, f"repos/{repo}/pulls/{number}", "--jq", + "{base: .base.sha, head: .head.sha}") + pr = got[0] if got and isinstance(got[0], dict) else {} + base_sha, head = str(pr.get("base") or ""), str(pr.get("head") or "") + if not base_sha or not head: + return _cannot(subject, "the PR read gave an empty base or head sha") + mb = _gh(run, f"repos/{repo}/compare/{base_sha}...{head}", "--jq", + "{sha: .merge_base_commit.sha}") + base = str((mb[0] if mb and isinstance(mb[0], dict) else {}).get("sha") or "") + if not base: + return _cannot(subject, "the compare read gave an empty merge-base sha") + try: + _gh(run, f"repos/{repo}/contents/{package}?ref={head}", "--jq", "{t: type}") + except GhError: + return _cannot(subject, missing_package(package)) + files = _gh(run, "--paginate", f"repos/{repo}/pulls/{number}/files?per_page=100", + "--jq", ".[] | {filename, status, previous_filename}") + except GhError as e: + return _cannot(subject, f"gh could not be read: {e}") + if len(files) >= GH_FILES_CAP: + return _cannot(subject, f"the PR lists {len(files)} files — GitHub's cap; " + "the diff cannot be read whole") + changes = [] + for f in files: + st, path = f.get("status"), f.get("filename") + if st == "added": + changes.append((None, path)) + elif st == "removed": + changes.append((path, None)) + elif st == "renamed": + changes.append((f.get("previous_filename") or None, path)) + elif st == "copied": + changes.append((None, path)) + else: + changes.append((path, path)) + v = compare(package, changes, lambda p: _gh_raw(run, repo, p, base), + lambda p: _gh_raw(run, repo, p, head)) + return {"subject": subject, "base": base, "head": head, **v} + + +class _Parser(argparse.ArgumentParser): + def error(self, message): + self.print_usage(sys.stderr) + print(f"public-names: {message}", file=sys.stderr) + raise SystemExit(EXIT_USAGE) + + +def main(argv=None, run=None, libs: dict | None = None) -> int: + p = _Parser(prog="pyauto-brain public-names", + description="Does a change add or rename a public library name? " + "Exit 0 CLEAN, 1 HIT (a human /prm), 2 cannot tell.") + p.add_argument("pr", nargs="?", help="owner/repo#N, owner/repo/pull/N or the PR URL") + p.add_argument("--repo", help="a local checkout (with --range)") + p.add_argument("--range", dest="rng", help=".. in --repo") + p.add_argument("--repo-name", default="", + help="the repo's name (default: --repo's origin remote or folder)") + p.add_argument("--before", help="a tree before the change (with --after, --repo-name)") + p.add_argument("--after", help="a tree after the change") + p.add_argument("--json", action="store_true", help="print one JSON object") + a = p.parse_args(argv) + try: + if a.pr and not (a.repo or a.before or a.after): + v = for_pr(a.pr, run=run, libs=libs) + elif a.repo and a.rng and not (a.pr or a.before or a.after): + v = for_range(Path(a.repo), a.rng, name=a.repo_name, run=run, libs=libs) + elif a.before and a.after and a.repo_name and not (a.pr or a.repo): + v = for_trees(Path(a.before), Path(a.after), a.repo_name, libs=libs) + else: + raise UsageError("pass a PR, or --repo --range .., " + "or --repo-name --before --after ") + except UsageError as e: + print(f"public-names: {e}", file=sys.stderr) + return EXIT_USAGE + if a.json: + print(json.dumps({**v, "reason": reason(v)}, indent=2)) + else: + print(summary(v)) + return EXIT[v["verdict"]] + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/bin/pyauto-brain b/bin/pyauto-brain index 3238c1d8..796c57c2 100755 --- a/bin/pyauto-brain +++ b/bin/pyauto-brain @@ -44,6 +44,9 @@ # pyauto-brain ci-verdict # [--json] # (tool) read-only: one PR's CI verdict — GREEN/PENDING/RED # with reasons (bin/ci_verdict.py; /prm, the close-out, pr_health) +# pyauto-brain public-names # | --repo --range a..b [--json] +# (tool) read-only: does a change add or rename a public +# library name? CLEAN/HIT/CANNOT-TELL (bin/public_names.py) # pyauto-brain help [name] list agents or show one agent's docs # # Renamed from `pyauto-agent`; the former back-compat shim has been removed now @@ -168,6 +171,7 @@ EOF # A tool, not an agent: listed as prose for the same reason as the surfaces. echo "Tools (read-only helpers the merge paths share):" echo " ci-verdict # [--json] — one PR's CI: GREEN, PENDING or RED, with reasons" + echo " public-names # [--json] — a public library name added or renamed: a human /prm" echo echo "Run 'pyauto-brain help ' for that agent's full docs." } @@ -216,6 +220,9 @@ main() { if [[ "$sub" == "ci-verdict" ]]; then exec python3 "$BRAIN_HOME/bin/ci_verdict.py" "$@" fi + if [[ "$sub" == "public-names" ]]; then + exec python3 "$BRAIN_HOME/bin/public_names.py" "$@" + fi local script="${AGENT_SCRIPT[$sub]:-}" if [[ -z "$script" || ! -f "$script" ]]; then echo "pyauto-brain: unknown agent '$sub'" >&2 diff --git a/config/policy.yaml b/config/policy.yaml index 9ddc4028..8b3c36ef 100644 --- a/config/policy.yaml +++ b/config/policy.yaml @@ -46,6 +46,12 @@ repo_aliases: pyautocti: autocti pyautoreduce: autoreduce +# The library repos whose public names an unattended or tiered merge may not add +# or rename (AUTONOMY.md "Public-name narrowing of `glance` — 2026-11-16", +# PyAutoBrain#641; bin/public_names.py). Each one's package directory is its +# body-map `package:`. One flow list on one line: read without PyYAML. +public_name_libraries: [PyAutoFit, PyAutoArray, PyAutoGalaxy, PyAutoLens, PyAutoCTI] + # Which body-map categories mean "library-flow" / "workspace-flow" / # "organism-infrastructure" to the sizing faculty; extra literal targets # that behave as workspace mentions. diff --git a/skills/prm/reference.md b/skills/prm/reference.md index 25ae079d..a3200adb 100644 --- a/skills/prm/reference.md +++ b/skills/prm/reference.md @@ -144,6 +144,12 @@ differences: CI, such as the website, stays a human merge) — report and stop; the human runs `/prm`. The library-first, sibling-branch and data-worktree guards apply verbatim. +- **Public names (step 4, every tier).** Run `pyauto-brain public-names + #` on each PR (`bin/public_names.py`, PyAutoBrain#641). + Exit 1 — a public library name added or renamed — or 2 — it cannot tell — + refuses: report its first line and stop; the human runs `/prm` + (`AUTONOMY.md` "Public-name narrowing of `glance` — 2026-11-16"). A repo + outside the five libraries prints CLEAN, exit 0. - **The merge call.** `gh pr merge --merge` as a **bare, unchained** Bash call (no `&&`, `;` or pipe); if the permission layer denies it, stop and report — never retry it another way. For `glance`, the close-out appends the diff --git a/skills/ship_library/ship_library.md b/skills/ship_library/ship_library.md index 2d460df3..fcec2206 100644 --- a/skills/ship_library/ship_library.md +++ b/skills/ship_library/ship_library.md @@ -156,7 +156,8 @@ Who merges follows the prompt's **declared** `Consequence:` header — `library-shipped, workspace-pending`, and the close-out runs at the workspace PR's own tiered merge. - **`judge`, no declared header**, a `decision-taken` PR, a Heart RED-override - or corrective-PR-exception ship, or any red / pending-at-cap / conflicting / + or corrective-PR-exception ship, a public name added or renamed (`pyauto-brain + public-names` exit 1 or 2), or any red / pending-at-cap / conflicting / SKIPPED leg → **stop at PR-open**; the human runs `/prm`. `gh pr merge` is a bare, unchained Bash call; if denied, stop and report. diff --git a/skills/ship_workspace/ship_workspace.md b/skills/ship_workspace/ship_workspace.md index a3cc5fd1..b0139e70 100644 --- a/skills/ship_workspace/ship_workspace.md +++ b/skills/ship_workspace/ship_workspace.md @@ -114,7 +114,8 @@ Who merges follows the prompt's **declared** `Consequence:` header — workspace PR whose library PR is not `MERGED` stops there). For `glance`, the close-out appends the Shadow-window row and the ledger ends with the post-merge summary. - **`judge`, no declared header**, a `decision-taken` PR, a Heart RED-override - or corrective-PR-exception ship, or any red / pending-at-cap / conflicting / + or corrective-PR-exception ship, a public name added or renamed (`pyauto-brain + public-names` exit 1 or 2), or any red / pending-at-cap / conflicting / SKIPPED leg → **stop at PR-open**; the human runs `/prm`. `gh pr merge` is a bare, unchained Bash call; if denied, stop and report. diff --git a/tests/fixtures/public_names/row08_latent/after/autogalaxy/convert.py.txt b/tests/fixtures/public_names/row08_latent/after/autogalaxy/convert.py.txt new file mode 100644 index 00000000..0296b797 --- /dev/null +++ b/tests/fixtures/public_names/row08_latent/after/autogalaxy/convert.py.txt @@ -0,0 +1,579 @@ +import numpy as np +from typing import Tuple, Optional + +from autofit.mapper.prior_model.latent_parameters import Periodic + +# The ellipticity magnitude at which the axis-ratio conversion saturates. Beyond +# it every magnitude maps onto the same axis ratio, so the likelihood is exactly +# flat in the radial direction and carries no gradient there — a gradient search +# that walks past this cannot walk back. `EllProfile.__model_constraint__` +# reports the distance beyond it, which is how PyAutoFit's multi-start searches +# count the lanes trapped in that region. +# +# Deliberately distinct from the `magnitude_squared >= 1.0` validity threshold in +# `profiles/validate.py`. They answer different questions — this is where the +# *gradient* dies, that is where the *geometry* stops meaning anything — and the +# annulus between them is reachable: at magnitude 0.9995 the radial derivative is +# already exactly zero while `validate_ell_comps` still calls the point valid. +# Stated together here rather than left as unrelated literals in separate files. +ELL_COMPS_MAGNITUDE_CLAMP = 0.999 + +# The amount the x-component of a pair of components is nudged by when both are +# exactly zero, for traced JAX values only (see `_nudge_off_origin`). +_ORIGIN_NUDGE = 1e-8 + + +def _nudge_off_origin(c0, c1, xp=np): + """ + Returns the x-component `c1` of a pair of components (`ell_comps[1]`, `gamma_1`, `multipole_comps[1]`), nudged + by `_ORIGIN_NUDGE` when both components are exactly zero, for traced JAX values only. + + Every polar conversion below computes `sqrt(c0**2 + c1**2)`, whose derivative at the origin is 0/0, so + `jax.grad` returns NaN there even though the profiles themselves are smooth through it (shear and multipole + deflections are linear in their components, so the gradient at the nudged point is exact). The nudged value is + `c1 + nudge`, so the derivative through `c1` is unchanged, and positive, so the angle `arctan2(0, +nudge) = 0` + matches the existing guarded value at the origin. + + Only traced values carry a gradient, so NumPy and concrete JAX values are returned unchanged: staging the nudge + onto a constant component alters how XLA compiles the downstream arithmetic and moves jitted deflections by an + ulp, which flips bit-exact ties in the point solver (`test_static_lattice_jax.py` in PyAutoLens pins one). For + the same reason traced values go through `jax.lax.select` rather than `jnp.where` or an additive offset, both of + which were measured to shift that pinned tie; away from the origin the traced value is selected unchanged. + """ + if xp.__name__.startswith("jax"): + import jax + + if isinstance(c0, jax.core.Tracer) or isinstance(c1, jax.core.Tracer): + return jax.lax.select( + xp.logical_and(c0 == 0, c1 == 0), c1 + _ORIGIN_NUDGE, c1 + ) + return c1 + + +def ell_comps_from(axis_ratio: float, angle: float, xp=np) -> Tuple[float, float]: + """ + Returns the elliptical components e1 and e2 of a light or mass profile from an input angle in degrees and axis + ratio. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-axis_ratio)/(1+axis_ratio) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-axis_ratio)/(1+axis_ratio) * cos(2 * angle) + + Which are the values this function returns. + + Parameters + ---------- + axis_ratio + Ratio of light profiles ellipse's minor and major axes (b/a). + angle + Rotation angle of light profile counter-clockwise from positive x-axis. + """ + angle *= xp.pi / 180.0 + fac = (1 - axis_ratio) / (1 + axis_ratio) + ellip_y = fac * xp.sin(2 * angle) + ellip_x = fac * xp.cos(2 * angle) + return (ellip_y, ellip_x) + + +def axis_ratio_and_angle_from( + ell_comps: Tuple[float, float], xp=np +) -> Tuple[float, float]: + """ + Returns the axis-ratio and position angle in degrees (-45 < angle < 135.0) from input elliptical components e1 + and e2 of a light or mass profile. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-axis_ratio)/(1+axis_ratio) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-axis_ratio)/(1+axis_ratio) * cos(2 * angle) + + The axis-ratio and angle are therefore given by: + + axis_ratio = (1 - fac) / (1 + fac) + angle = 0.5 * arctan(ell_comps[0] / ell_comps[1]) + + where `fac = sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2). + + This function returns the axis-ratio and angle in degrees. + + An additional check is performed which requires the angle is between -45 and 135 degrees. This ensures that + for certain values of `ell_comps` the angle does not jump from one boundary to another (e.g. without this check + certain values of `ell_comps` return -46.0 degrees and others 134.0 degrees). This ensures that when error + estimates are computed from samples of a lens model via marginalization, the calculation is not biased by the + angle jumping between these two values. + + Parameters + ---------- + ell_comps + The elliptical components of the light or mass profile which are converted to an angle. + """ + ell_comps = (ell_comps[0], _nudge_off_origin(ell_comps[0], ell_comps[1], xp=xp)) + + angle = 0.5 * xp.arctan2( + ell_comps[0], + xp.where(xp.logical_and(ell_comps[0] == 0, ell_comps[1] == 0), 1.0, ell_comps[1]), + ) + angle *= 180.0 / xp.pi + + angle = xp.where(angle < -45, angle + 180, angle) + + fac = xp.sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2) + if xp.__name__.startswith("jax"): + import jax + + fac = jax.lax.min(fac, ELL_COMPS_MAGNITUDE_CLAMP) + else: # NumPy + fac = np.minimum(fac, ELL_COMPS_MAGNITUDE_CLAMP) + + axis_ratio = (1 - fac) / (1 + fac) + return axis_ratio, angle + + +def axis_ratio_from(ell_comps: Tuple[float, float], xp=np): + """ + Returns the axis-ratio from input elliptical components e1 and e2 of a light or mass profile. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-axis_ratio)/(1+axis_ratio) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-axis_ratio)/(1+axis_ratio) * cos(2 * angle) + + The axis-ratio is therefore given by: + + axis_ratio = (1 - fac) / (1 + fac) + angle = 0.5 * arctan(ell_comps[0] / ell_comps[1]) + + where `fac = sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2). + + This function returns the axis-ratio. + + Parameters + ---------- + ell_comps + The elliptical components of the light or mass profile which are converted to an angle. + """ + axis_ratio, angle = axis_ratio_and_angle_from(ell_comps=ell_comps, xp=xp) + return axis_ratio + + +def angle_from(ell_comps: Tuple[float, float], xp=np) -> float: + """ + Returns the position angle in degrees (-45 < angle < 135.0) from input elliptical components e1 and e2 + of a light or mass profile. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-q)/(1+q) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-q)/(1+q) * cos(2 * angle) + + axis_ratio = (1 - fac) / (1 + fac) + angle = 0.5 * arctan(ell_comps[0] / ell_comps[1]) + + where `fac = sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2). + + This function returns the angle in degrees. + + An additional check is performed which requires the angle is between -45 and 135 degrees. This ensures that + for certain values of `ell_comps` the angle does not jump from one boundary to another (e.g. without this check + certain values of `ell_comps` return -46.0 degrees and others 134.0 degrees). + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + ell_comps + The elliptical components of the light or mass profile which are converted to an angle. + """ + axis_ratio, angle = axis_ratio_and_angle_from(ell_comps=ell_comps, xp=xp) + return angle + + +def shear_gamma_1_2_from(magnitude: float, angle: float, xp=np) -> Tuple[float, float]: + """ + Returns the shear gamma 1 and gamma 2 values an input shear magnitude and angle in degrees. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Which are the values this function returns. + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + Parameters + ---------- + axis_ratio + Ratio of light profiles ellipse's minor and major axes (b/a). + angle + Rotation angle of light profile counter-clockwise from positive x-axis. + """ + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + return (gamma_1, gamma_2) + + +def shear_magnitude_and_angle_from( + gamma_1: float, gamma_2: float, xp=np +) -> Tuple[float, float]: + """ + Returns the shear magnitude and angle in degrees from input shear gamma 1 and gamma 2 values. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + Which are the values this function returns. + + Additional checks are performed which requires the angle is between 0 and 180 degrees. This ensures that + for certain values of `gamma_1` and `gamma_2` the angle does not jump from one boundary to another (e.g. without + this check certain values of `gamma_1` and `gamma_2` return -1.0 degrees and others 179.0 degrees). + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + gamma_1 + The gamma 1 component of the shear. + gamma_2 + The gamma 2 component of the shear. + """ + gamma_1 = _nudge_off_origin(gamma_2, gamma_1, xp=xp) + + angle = ( + 0.5 + * xp.arctan2(gamma_2, xp.where(xp.logical_and(gamma_1 == 0, gamma_2 == 0), 1.0, gamma_1)) + * 180.0 + / xp.pi + ) + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + + angle = xp.where(angle < 0, angle + 180.0, angle) + angle = xp.where( + xp.logical_and(xp.abs(angle - 90.0) > 45.0, angle > 90.0), angle - 180.0, angle + ) + + return magnitude, angle + + +def shear_magnitude_from(gamma_1: float, gamma_2: float, xp=np) -> float: + """ + Returns the shear magnitude and angle in degrees from input shear gamma 1 and gamma 2 values. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + The magnitude value is what this function returns. + + Parameters + ---------- + gamma_1 + The gamma 1 component of the shear. + gamma_2 + The gamma 2 component of the shear. + """ + magnitude, angle = shear_magnitude_and_angle_from( + gamma_1=gamma_1, gamma_2=gamma_2, xp=xp + ) + return magnitude + + +def shear_angle_from(gamma_1: float, gamma_2: float, xp=np) -> float: + """ + Returns the shear magnitude and angle in degrees from input shear gamma 1 and gamma 2 values. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + The angle value is what this function returns. + + Parameters + ---------- + gamma_1 + The gamma 1 component of the shear. + gamma_2 + The gamma 2 component of the shear. + """ + magnitude, angle = shear_magnitude_and_angle_from( + gamma_1=gamma_1, gamma_2=gamma_2, xp=xp + ) + return angle + + +def multipole_k_m_and_phi_m_from( + multipole_comps: Tuple[float, float], m: int, xp=np +) -> Tuple[float, float]: + r""" + Returns the multipole normalization value `k_m` and angle `phi` from the multipole component parameters. + + The normalization and angle are given by: + + .. math:: + \phi^{\rm mass}_m = \frac{1}{m} \arctan{\frac{\epsilon_{\rm 2}^{\rm mp}}{\epsilon_{\rm 1}^{\rm mp}}}, \, \, + k^{\rm mass}_m = \sqrt{{\epsilon_{\rm 1}^{\rm mp}}^2 + {\epsilon_{\rm 2}^{\rm mp}}^2} \, . + + The conversion depends on the multipole order `m`, to ensure that all possible rotationally symmetric + multiple mass profiles are available in the conversion for multiple components spanning -inf to inf. + + Additional checks are performed which requires the angle `phi_m` is between -45 and 135 degrees. This ensures that + for certain multipole component values the angle does not jump from one boundary to another (e.g. without + this check certain values of the multipole components return -46.0 degrees and others 134.0 degrees). + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + multipole_comps + The first and second components of the multipole. + + Returns + ------- + The normalization and angle parameters of the multipole. + """ + multipole_comps = ( + multipole_comps[0], + _nudge_off_origin(multipole_comps[0], multipole_comps[1], xp=xp), + ) + + phi_m = ( + xp.arctan2( + multipole_comps[0], + xp.where( + xp.logical_and(multipole_comps[0] == 0, multipole_comps[1] == 0), + 1.0, + multipole_comps[1], + ), + ) + * 180.0 + / xp.pi + / float(m) + ) + + k_m = xp.sqrt(multipole_comps[1] ** 2 + multipole_comps[0] ** 2) + + phi_m = xp.where(phi_m < -90.0 / m, phi_m + 360.0 / m, phi_m) + + return k_m, phi_m + + +def multipole_k_m_phi_m_and_shape_angle_from( + multipole_comps: Tuple[float, float], + m: int, + ell_comps: Optional[Tuple[float, float]], + ellipse_angle: Optional[float], + xp=np +) -> Tuple[float, float, float]: + r""" + Returns the multipole normalization value `k_m`, angle `phi` and shape_angle `s` from the multipole + component parameters. The shape angle is the difference between the angle of the underlying elliptical profile and + the multipole `phi_m` and is what defines the shape of the perturbation around the ellipse oriented towards the + direction of the underlying position angle. You must supply either the ell_comps or position angle of the + underlying elliptical profile. + + The normalization and angle are given by: + + .. math:: + \phi^{\rm mass}_m = \frac{1}{m} \arctan{\frac{\epsilon_{\rm 2}^{\rm mp}}{\epsilon_{\rm 1}^{\rm mp}}}, \, \, + k^{\rm mass}_m = \sqrt{{\epsilon_{\rm 1}^{\rm mp}}^2 + {\epsilon_{\rm 2}^{\rm mp}}^2} \, . + + The shape angle is then given as (where \phi_{\rm ell} is the position angle of the underlying elliptical profile): + .. math:: + s^{\rm mass}_m = \phi_{\rm ell} - \phi_m \, . + + + The conversion depends on the multipole order `m`, to ensure that all possible rotationally symmetric + multiple mass profiles are available in the conversion for multiple components spanning -inf to inf. + + Additional checks are performed which requires the angle `phi_m` is between -45 and 135 degrees. This ensures that + for certain multipole component values the angle does not jump from one boundary to another (e.g. without + this check certain values of the multipole components return -46.0 degrees and others 134.0 degrees). The shape angle + is then also checked and required to be in the range +- 360/m. + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + multipole_comps + The first and second components of the multipole. + m + The multipole order. + ell_comps + The elliptical components of the underlying elliptical distribution that the multipole is perturbing. + Note either ell_comps or galaxy_angle must be passed. + ellipse_angle + Alternative to supplying the ell_comps of the underlying profile, the position angle of the underlying profile. + + Returns + ------- + The normalization and angle parameters of the multipole. + """ + if ellipse_angle is None: + if ell_comps is None: + raise AssertionError('You must pass either the ell_comps or the position angle of the underlying distribution.') + else: + angle = ellipse_angle + else: + angle = angle_from(ell_comps, xp=xp) + + + k_m, phi_m = multipole_k_m_and_phi_m_from(multipole_comps, m, xp=xp) + + shape_angle = angle - phi_m + + while angle < -180 / m: + angle += 360 / m + while angle > 180 / m: + angle -= 360 / m + + return k_m, phi_m, shape_angle + + +def multipole_comps_from( + k_m: float, phi_m: Optional[float], m: int, + shape_angle: Optional[float]=None, ellipse_angle: Optional[float]=None, + xp=np +) -> Tuple[float, float]: + r""" + Returns the multipole component parameters from their normalization value `k_m` and angle `phi`. + + .. math:: + \phi^{\rm mass}_m = \frac{1}{m} \arctan{\frac{\epsilon_{\rm 2}^{\rm mp}}{\epsilon_{\rm 1}^{\rm mp}}}, \, \, + k^{\rm mass}_m = \sqrt{{\epsilon_{\rm 1}^{\rm mp}}^2 + {\epsilon_{\rm 2}^{\rm mp}}^2} \, . + + The conversion depends on the multipole order `m`, to ensure that all possible rotationally symmetric + multiple mass profiles are available in the conversion for multiple components spanning -inf to inf. + + Parameters + ---------- + k_m + The magnitude of the multipole. + phi_m + The angle of the multipole. You can supply either phi_m or shape_angle and ellipse_angle. + shape_angle + The shape angle of the multipole, defined as the difference between the underlying position angle and the + multipole phi_m. + ellipse_angle + The position_angle of the underlying elliptical profile. Must be supplied alongside shape_angle as an + alternative to phi_m. + + Returns + ------- + The multipole component parameters. + """ + # Degrees -> radians conversion + deg_to_rad = xp.asarray(np.pi / 180.0) + + if phi_m is not None: + angle = phi_m * float(m) * deg_to_rad + elif (shape_angle is None) or (ellipse_angle is None): + raise AssertionError('You must provide EITHER phi_m OR shape_angle and ellipse_angle.') + else: + multipole_angle = ellipse_angle-shape_angle + angle = multipole_angle * float(m) * deg_to_rad + + multipole_comp_0 = k_m * xp.sin(angle) + multipole_comp_1 = k_m * xp.cos(angle) + + return multipole_comp_0, multipole_comp_1 + + +# Latent-parameter conversions. +# +# PyAutoFit lets a model component declare, as a ``latent_parameters`` class +# attribute, how the parameters it is *sampled* in convert to the ones it is +# *read* in (``autofit.mapper.prior_model.latent_parameters``). The entries below are +# those declarations' functions: each receives every parameter of the component +# by name (the free ones as arrays over the posterior samples, the fixed ones as +# floats) and returns the latent parameters by name. They are what the +# ``corner_anesthetic_latent`` plots show. An angle is returned as ``Periodic`` +# with its period, so PyAutoFit recentres the samples on their circular mean and +# a posterior peaked at the conversion's branch cut is not drawn as two peaks. + + +def latent_shear_from(gamma_1, gamma_2, **kwargs) -> dict: + """A shear's magnitude and angle (degrees) from its ``gamma_1`` / ``gamma_2``.""" + magnitude, angle = shear_magnitude_and_angle_from(gamma_1=gamma_1, gamma_2=gamma_2) + return {"magnitude": magnitude, "angle": Periodic(angle, period=180.0)} + + +def latent_ellipse_from(ell_comps_0, ell_comps_1, **kwargs) -> dict: + """An ellipse's axis ratio and position angle (degrees) from its elliptical components.""" + axis_ratio, angle = axis_ratio_and_angle_from(ell_comps=(ell_comps_0, ell_comps_1)) + return {"axis_ratio": axis_ratio, "angle": Periodic(angle, period=180.0)} + + +def latent_multipole_from(multipole_comps_0, multipole_comps_1, m, **kwargs) -> dict: + """A multipole's strength ``k_m`` and sky angle ``phi_m`` (degrees) from its components.""" + k_m, phi_m = multipole_k_m_and_phi_m_from( + multipole_comps=(multipole_comps_0, multipole_comps_1), m=int(m) + ) + return {"k_m": k_m, "phi_m": Periodic(phi_m, period=360.0 / int(m))} + + +def latent_scaled_multipole_from( + scaled_multipole_comps_0, scaled_multipole_comps_1, m, **kwargs +) -> dict: + """A scaled multipole's strength ``k_m`` (per unit major axis) and sky angle ``phi_m``.""" + k_m, phi_m = multipole_k_m_and_phi_m_from( + multipole_comps=(scaled_multipole_comps_0, scaled_multipole_comps_1), m=int(m) + ) + return {"k_m": k_m, "phi_m": Periodic(phi_m, period=360.0 / int(m))} + + +def latent_light_multipole_3_from(multipole_3_comps_0, multipole_3_comps_1, **kwargs) -> dict: + """The m=3 light-mode strength and phase in its elliptical reference frame.""" + # Light profiles store (cosine, sine); the mass helper accepts (sine, cosine). + k_3, phi_3 = multipole_k_m_and_phi_m_from( + multipole_comps=(multipole_3_comps_1, multipole_3_comps_0), m=3 + ) + return {"k_3": k_3, "phi_3": Periodic(phi_3, period=120.0)} + + +def latent_light_multipole_4_from(multipole_4_comps_0, multipole_4_comps_1, **kwargs) -> dict: + """The m=4 light-mode strength and phase in its elliptical reference frame.""" + k_4, phi_4 = multipole_k_m_and_phi_m_from( + multipole_comps=(multipole_4_comps_1, multipole_4_comps_0), m=4 + ) + return {"k_4": k_4, "phi_4": Periodic(phi_4, period=90.0)} + + +def latent_light_multipoles_from( + multipole_3_comps_0, + multipole_3_comps_1, + multipole_4_comps_0, + multipole_4_comps_1, + **kwargs, +) -> dict: + """The m=3 and m=4 light-mode strengths and phases (degrees).""" + return { + **latent_light_multipole_3_from(multipole_3_comps_0, multipole_3_comps_1), + **latent_light_multipole_4_from(multipole_4_comps_0, multipole_4_comps_1), + } diff --git a/tests/fixtures/public_names/row08_latent/after/autogalaxy/profiles/light/standard/_multipole_mixin.py.txt b/tests/fixtures/public_names/row08_latent/after/autogalaxy/profiles/light/standard/_multipole_mixin.py.txt new file mode 100644 index 00000000..aeeecebd --- /dev/null +++ b/tests/fixtures/public_names/row08_latent/after/autogalaxy/profiles/light/standard/_multipole_mixin.py.txt @@ -0,0 +1,81 @@ +""" +Shared helper for light profiles with m=3 and m=4 Fourier perturbations on the +eccentric radius. + +Used by ``SersicMultipole`` (``sersic_multipole.py``) and ``GaussianMultipole`` +(``gaussian_multipole.py``). The leading underscore signals "implementation +detail" — when the future generalisation lands (a single wrapper-style multipole +that perturbs any radial profile, unified with the ellipse-fitting API), this +module will be replaced rather than evolved in-place. +""" + +from typing import Tuple + +import numpy as np + +import autoarray as aa + +from autogalaxy import convert + + +class _LightProfileMultipoleMixin: + """ + Provides ``perturbed_radii_from`` to light profiles that: + + - set ``multipole_3_comps`` and ``multipole_4_comps`` on ``self`` in ``__init__`` + - inherit from a base profile providing ``eccentric_radii_grid_from`` + """ + + multipole_3_comps: Tuple[float, float] + multipole_4_comps: Tuple[float, float] + + latent_parameters = { + ( + "multipole_3_comps_0", + "multipole_3_comps_1", + ): convert.latent_light_multipole_3_from, + ( + "multipole_4_comps_0", + "multipole_4_comps_1", + ): convert.latent_light_multipole_4_from, + } + + def perturbed_radii_from( + self, + grid: aa.type.Grid2DLike, + xp=np, + **kwargs, + ) -> np.ndarray: + """ + Returns the eccentric radii of ``grid`` perturbed by the m=3 and m=4 Fourier + multipoles, as a raw backend array (numpy or jax.numpy). + + The perturbation is + + r' = r * (1 + c_3 cos(3 theta) + s_3 sin(3 theta) + + c_4 cos(4 theta) + s_4 sin(4 theta)) + + where ``theta = arctan2(y, x)`` is the polar angle in the profile's + elliptical reference frame (the grid is already in that frame after the + ``@aa.decorators.transform`` decorator on the caller's ``image_2d_from``). + + Result is floored at 1e-8 to keep ``r ** (1/n)`` evaluations finite when a + large multipole component drives the radius through zero. + """ + grid_radii = self.eccentric_radii_grid_from(grid=grid, xp=xp, **kwargs) + grid_radii_array = ( + grid_radii.array if hasattr(grid_radii, "array") else grid_radii + ) + y = grid.array[:, 0] + x = grid.array[:, 1] + theta = xp.arctan2(y, x) + c3, s3 = self.multipole_3_comps + c4, s4 = self.multipole_4_comps + perturbation = ( + 1.0 + + c3 * xp.cos(3.0 * theta) + + s3 * xp.sin(3.0 * theta) + + c4 * xp.cos(4.0 * theta) + + s4 * xp.sin(4.0 * theta) + ) + return xp.maximum(xp.multiply(grid_radii_array, perturbation), 1e-8) diff --git a/tests/fixtures/public_names/row08_latent/after/autogalaxy/profiles/mass/sheets/external_shear.py.txt b/tests/fixtures/public_names/row08_latent/after/autogalaxy/profiles/mass/sheets/external_shear.py.txt new file mode 100644 index 00000000..46ff6707 --- /dev/null +++ b/tests/fixtures/public_names/row08_latent/after/autogalaxy/profiles/mass/sheets/external_shear.py.txt @@ -0,0 +1,166 @@ +import numpy as np + +import autoarray as aa + +from autogalaxy.profiles.mass.abstract.abstract import MassProfile + +from autogalaxy import convert + + +class ExternalShear(MassProfile): + r""" + Constant external shear field used in strong-lens mass models. + + The external shear represents the line-of-sight contribution to the lensing + potential from mass external to the primary lens (e.g. nearby group members, + large-scale structure). Because this contribution is approximately uniform over + the small angular extent of a strong-lens system, it is modelled as a constant + shear with two Cartesian components :math:`(\gamma_1, \gamma_2)`. + + The lensing potential is: + + .. math:: + + \psi(\boldsymbol{\theta}) = + -\tfrac{1}{2} |\gamma| \, r^2 \cos\!\big(2(\varphi - \phi_\gamma)\big) + + The deflection field in a reference frame aligned with the shear direction is: + + .. math:: + + \alpha_y = -|\gamma| \, y, \qquad \alpha_x = +|\gamma| \, x + + The convergence vanishes identically: + + .. math:: + + \kappa = 0 + + The shear magnitude and position angle are: + + .. math:: + + |\gamma| = \sqrt{\gamma_1^2 + \gamma_2^2}, \qquad + \phi_\gamma = \tfrac{1}{2} \mathrm{arctan2}(\gamma_2, \gamma_1) + + References + ---------- + - Schneider, Ehlers & Falco 1992, *Gravitational Lenses* (Springer) + """ + + # Read as a magnitude and an angle rather than gamma_1 / gamma_2. + latent_parameters = {("gamma_1", "gamma_2"): convert.latent_shear_from} + + def __init__(self, gamma_1: float = 0.0, gamma_2: float = 0.0): + r""" + Constant external shear term used in strong-lens mass models. + + ``ExternalShear`` represents the line-of-sight contribution to the lensing potential from mass that is + not part of the primary lens — typically nearby group/cluster members, large-scale structure, or + unmodelled satellites. Because this contribution is approximately uniform across the small angular + extent of a strong-lens system, it is parameterised as a constant shear with two components, + :math:`\gamma_1` and :math:`\gamma_2`, in the same convention as + ``LensCalc.shear_yx_2d_via_hessian_from`` and ``ShearYX2DIrregular``: + + - :math:`\gamma_1` produces stretching along the x/y axes + - :math:`\gamma_2` produces stretching along the diagonals + + The associated shear *magnitude* and *position angle* (degrees, anticlockwise from the +x axis) are: + + .. math:: + + |\gamma| = \sqrt{\gamma_1^2 + \gamma_2^2}, \qquad + \phi = \tfrac{1}{2} \, \mathrm{arctan2}(\gamma_2, \gamma_1). + + Note that the shear *position angle* lies in the direction of image stretching. An external mass + located in the *direction of compression* therefore appears at an angle offset by 90 degrees from + :math:`\phi`. + + Parameters + ---------- + gamma_1 + The :math:`\gamma_1` shear component. + gamma_2 + The :math:`\gamma_2` shear component. + """ + + super().__init__(centre=(0.0, 0.0), ell_comps=(0.0, 0.0)) + self.gamma_1 = gamma_1 + self.gamma_2 = gamma_2 + + def magnitude(self, xp=np): + r"""Returns the shear magnitude :math:`|\gamma| = \sqrt{\gamma_1^2 + \gamma_2^2}`.""" + return convert.shear_magnitude_from( + gamma_1=self.gamma_1, gamma_2=self.gamma_2, xp=xp + ) + + def angle(self, xp=np): + r"""Returns the shear position angle :math:`\phi = \tfrac{1}{2}\,\mathrm{arctan2}(\gamma_2, \gamma_1)` + in degrees, in the [0, 180) convention used elsewhere in the package.""" + return convert.shear_angle_from( + gamma_1=self.gamma_1, gamma_2=self.gamma_2, xp=xp + ) + + def convergence_func(self, grid_radius: float, xp=np) -> float: + return 0.0 + + def average_convergence_of_1_radius(self): + return 0.0 + + @aa.decorators.to_array + def convergence_2d_from(self, grid: aa.type.Grid2DLike, xp=np, **kwargs): + """A pure shear term has zero convergence at every grid point.""" + return xp.zeros(shape=grid.shape[0]) + + @aa.decorators.to_array + def potential_2d_from(self, grid: aa.type.Grid2DLike, xp=np, **kwargs): + r""" + Returns the lensing potential of the constant external shear, given by: + + .. math:: + + \psi(\theta) = -\tfrac{1}{2} |\gamma| \, r^2 \, \cos\!\big(2\,(\varphi - \phi_\gamma)\big) + + where :math:`r, \varphi` are the polar coordinates of ``grid`` and :math:`\phi_\gamma` is the shear + position angle (offset by ``-90 deg`` to remain consistent with the deflection-angle convention used + elsewhere in PyAutoLens). + """ + shear_angle = ( + self.angle(xp) - 90 + ) # offset by -90 deg to match the deflection-angle convention used elsewhere + phig = xp.deg2rad(shear_angle) + shear_amp = self.magnitude(xp=xp) + phicoord = xp.arctan2(grid.array[:, 0], grid.array[:, 1]) + rcoord = xp.sqrt(grid.array[:, 0] ** 2.0 + grid.array[:, 1] ** 2.0) + + return -0.5 * shear_amp * rcoord**2 * xp.cos(2 * (phicoord - phig)) + + @aa.decorators.to_vector_yx + @aa.decorators.transform(rotate_back=True) + def deflections_yx_2d_from(self, grid: aa.type.Grid2DLike, xp=np, **kwargs): + r""" + Returns the deflection angles of the constant external shear at each ``(y, x)`` arc-second + coordinate. + + In the profile's rotated reference frame (where the shear position angle is aligned with the x-axis) + the deflection reduces to: + + .. math:: + + \alpha_y(y, x) = -|\gamma| \, y, \qquad \alpha_x(y, x) = +|\gamma| \, x. + + The ``@transform(rotate_back=True)`` decorator rotates the input grid into this aligned frame and + rotates the resulting deflection vectors back into the original frame. Because the shear is a spin-2 + field, the *position angle* :math:`\phi` of the shear is encoded in the rotation of the grid and not + as an extra factor in the deflection formula above. + + Parameters + ---------- + grid + The grid of (y,x) arc-second coordinates the deflection angles are computed on. + xp + The array module (``numpy`` or ``jax.numpy``). + """ + deflection_y = -xp.multiply(self.magnitude(xp=xp), grid.array[:, 0]) + deflection_x = xp.multiply(self.magnitude(xp=xp), grid.array[:, 1]) + return xp.vstack((deflection_y, deflection_x)).T diff --git a/tests/fixtures/public_names/row08_latent/before/autogalaxy/convert.py.txt b/tests/fixtures/public_names/row08_latent/before/autogalaxy/convert.py.txt new file mode 100644 index 00000000..36a4905e --- /dev/null +++ b/tests/fixtures/public_names/row08_latent/before/autogalaxy/convert.py.txt @@ -0,0 +1,503 @@ +import numpy as np +from typing import Tuple, Optional + +# The ellipticity magnitude at which the axis-ratio conversion saturates. Beyond +# it every magnitude maps onto the same axis ratio, so the likelihood is exactly +# flat in the radial direction and carries no gradient there — a gradient search +# that walks past this cannot walk back. `EllProfile.__model_constraint__` +# reports the distance beyond it, which is how PyAutoFit's multi-start searches +# count the lanes trapped in that region. +# +# Deliberately distinct from the `magnitude_squared >= 1.0` validity threshold in +# `profiles/validate.py`. They answer different questions — this is where the +# *gradient* dies, that is where the *geometry* stops meaning anything — and the +# annulus between them is reachable: at magnitude 0.9995 the radial derivative is +# already exactly zero while `validate_ell_comps` still calls the point valid. +# Stated together here rather than left as unrelated literals in separate files. +ELL_COMPS_MAGNITUDE_CLAMP = 0.999 + +# The amount the x-component of a pair of components is nudged by when both are +# exactly zero, for traced JAX values only (see `_nudge_off_origin`). +_ORIGIN_NUDGE = 1e-8 + + +def _nudge_off_origin(c0, c1, xp=np): + """ + Returns the x-component `c1` of a pair of components (`ell_comps[1]`, `gamma_1`, `multipole_comps[1]`), nudged + by `_ORIGIN_NUDGE` when both components are exactly zero, for traced JAX values only. + + Every polar conversion below computes `sqrt(c0**2 + c1**2)`, whose derivative at the origin is 0/0, so + `jax.grad` returns NaN there even though the profiles themselves are smooth through it (shear and multipole + deflections are linear in their components, so the gradient at the nudged point is exact). The nudged value is + `c1 + nudge`, so the derivative through `c1` is unchanged, and positive, so the angle `arctan2(0, +nudge) = 0` + matches the existing guarded value at the origin. + + Only traced values carry a gradient, so NumPy and concrete JAX values are returned unchanged: staging the nudge + onto a constant component alters how XLA compiles the downstream arithmetic and moves jitted deflections by an + ulp, which flips bit-exact ties in the point solver (`test_static_lattice_jax.py` in PyAutoLens pins one). For + the same reason traced values go through `jax.lax.select` rather than `jnp.where` or an additive offset, both of + which were measured to shift that pinned tie; away from the origin the traced value is selected unchanged. + """ + if xp.__name__.startswith("jax"): + import jax + + if isinstance(c0, jax.core.Tracer) or isinstance(c1, jax.core.Tracer): + return jax.lax.select( + xp.logical_and(c0 == 0, c1 == 0), c1 + _ORIGIN_NUDGE, c1 + ) + return c1 + + +def ell_comps_from(axis_ratio: float, angle: float, xp=np) -> Tuple[float, float]: + """ + Returns the elliptical components e1 and e2 of a light or mass profile from an input angle in degrees and axis + ratio. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-axis_ratio)/(1+axis_ratio) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-axis_ratio)/(1+axis_ratio) * cos(2 * angle) + + Which are the values this function returns. + + Parameters + ---------- + axis_ratio + Ratio of light profiles ellipse's minor and major axes (b/a). + angle + Rotation angle of light profile counter-clockwise from positive x-axis. + """ + angle *= xp.pi / 180.0 + fac = (1 - axis_ratio) / (1 + axis_ratio) + ellip_y = fac * xp.sin(2 * angle) + ellip_x = fac * xp.cos(2 * angle) + return (ellip_y, ellip_x) + + +def axis_ratio_and_angle_from( + ell_comps: Tuple[float, float], xp=np +) -> Tuple[float, float]: + """ + Returns the axis-ratio and position angle in degrees (-45 < angle < 135.0) from input elliptical components e1 + and e2 of a light or mass profile. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-axis_ratio)/(1+axis_ratio) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-axis_ratio)/(1+axis_ratio) * cos(2 * angle) + + The axis-ratio and angle are therefore given by: + + axis_ratio = (1 - fac) / (1 + fac) + angle = 0.5 * arctan(ell_comps[0] / ell_comps[1]) + + where `fac = sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2). + + This function returns the axis-ratio and angle in degrees. + + An additional check is performed which requires the angle is between -45 and 135 degrees. This ensures that + for certain values of `ell_comps` the angle does not jump from one boundary to another (e.g. without this check + certain values of `ell_comps` return -46.0 degrees and others 134.0 degrees). This ensures that when error + estimates are computed from samples of a lens model via marginalization, the calculation is not biased by the + angle jumping between these two values. + + Parameters + ---------- + ell_comps + The elliptical components of the light or mass profile which are converted to an angle. + """ + ell_comps = (ell_comps[0], _nudge_off_origin(ell_comps[0], ell_comps[1], xp=xp)) + + angle = 0.5 * xp.arctan2( + ell_comps[0], + xp.where(xp.logical_and(ell_comps[0] == 0, ell_comps[1] == 0), 1.0, ell_comps[1]), + ) + angle *= 180.0 / xp.pi + + angle = xp.where(angle < -45, angle + 180, angle) + + fac = xp.sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2) + if xp.__name__.startswith("jax"): + import jax + + fac = jax.lax.min(fac, ELL_COMPS_MAGNITUDE_CLAMP) + else: # NumPy + fac = np.minimum(fac, ELL_COMPS_MAGNITUDE_CLAMP) + + axis_ratio = (1 - fac) / (1 + fac) + return axis_ratio, angle + + +def axis_ratio_from(ell_comps: Tuple[float, float], xp=np): + """ + Returns the axis-ratio from input elliptical components e1 and e2 of a light or mass profile. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-axis_ratio)/(1+axis_ratio) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-axis_ratio)/(1+axis_ratio) * cos(2 * angle) + + The axis-ratio is therefore given by: + + axis_ratio = (1 - fac) / (1 + fac) + angle = 0.5 * arctan(ell_comps[0] / ell_comps[1]) + + where `fac = sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2). + + This function returns the axis-ratio. + + Parameters + ---------- + ell_comps + The elliptical components of the light or mass profile which are converted to an angle. + """ + axis_ratio, angle = axis_ratio_and_angle_from(ell_comps=ell_comps, xp=xp) + return axis_ratio + + +def angle_from(ell_comps: Tuple[float, float], xp=np) -> float: + """ + Returns the position angle in degrees (-45 < angle < 135.0) from input elliptical components e1 and e2 + of a light or mass profile. + + The elliptical components of a light or mass profile are given by: + + elliptical_component_y = ell_comps[0] = (1-q)/(1+q) * sin(2 * angle) + elliptical_component_x = ell_comps[1] = (1-q)/(1+q) * cos(2 * angle) + + axis_ratio = (1 - fac) / (1 + fac) + angle = 0.5 * arctan(ell_comps[0] / ell_comps[1]) + + where `fac = sqrt(ell_comps[1] ** 2 + ell_comps[0] ** 2). + + This function returns the angle in degrees. + + An additional check is performed which requires the angle is between -45 and 135 degrees. This ensures that + for certain values of `ell_comps` the angle does not jump from one boundary to another (e.g. without this check + certain values of `ell_comps` return -46.0 degrees and others 134.0 degrees). + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + ell_comps + The elliptical components of the light or mass profile which are converted to an angle. + """ + axis_ratio, angle = axis_ratio_and_angle_from(ell_comps=ell_comps, xp=xp) + return angle + + +def shear_gamma_1_2_from(magnitude: float, angle: float, xp=np) -> Tuple[float, float]: + """ + Returns the shear gamma 1 and gamma 2 values an input shear magnitude and angle in degrees. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Which are the values this function returns. + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + Parameters + ---------- + axis_ratio + Ratio of light profiles ellipse's minor and major axes (b/a). + angle + Rotation angle of light profile counter-clockwise from positive x-axis. + """ + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + return (gamma_1, gamma_2) + + +def shear_magnitude_and_angle_from( + gamma_1: float, gamma_2: float, xp=np +) -> Tuple[float, float]: + """ + Returns the shear magnitude and angle in degrees from input shear gamma 1 and gamma 2 values. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + Which are the values this function returns. + + Additional checks are performed which requires the angle is between 0 and 180 degrees. This ensures that + for certain values of `gamma_1` and `gamma_2` the angle does not jump from one boundary to another (e.g. without + this check certain values of `gamma_1` and `gamma_2` return -1.0 degrees and others 179.0 degrees). + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + gamma_1 + The gamma 1 component of the shear. + gamma_2 + The gamma 2 component of the shear. + """ + gamma_1 = _nudge_off_origin(gamma_2, gamma_1, xp=xp) + + angle = ( + 0.5 + * xp.arctan2(gamma_2, xp.where(xp.logical_and(gamma_1 == 0, gamma_2 == 0), 1.0, gamma_1)) + * 180.0 + / xp.pi + ) + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + + angle = xp.where(angle < 0, angle + 180.0, angle) + angle = xp.where( + xp.logical_and(xp.abs(angle - 90.0) > 45.0, angle > 90.0), angle - 180.0, angle + ) + + return magnitude, angle + + +def shear_magnitude_from(gamma_1: float, gamma_2: float, xp=np) -> float: + """ + Returns the shear magnitude and angle in degrees from input shear gamma 1 and gamma 2 values. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + The magnitude value is what this function returns. + + Parameters + ---------- + gamma_1 + The gamma 1 component of the shear. + gamma_2 + The gamma 2 component of the shear. + """ + magnitude, angle = shear_magnitude_and_angle_from( + gamma_1=gamma_1, gamma_2=gamma_2, xp=xp + ) + return magnitude + + +def shear_angle_from(gamma_1: float, gamma_2: float, xp=np) -> float: + """ + Returns the shear magnitude and angle in degrees from input shear gamma 1 and gamma 2 values. + + The gamma 1 and gamma 2 components of a shear are given by: + + gamma_1 = magnitude * xp.cos(2 * angle * xp.pi / 180.0) + gamma_2 = magnitude * xp.sin(2 * angle * xp.pi / 180.0) + + Converting from gamma 1 and gamma 2 to magnitude and angle is given by: + + magnitude = xp.sqrt(gamma_1**2 + gamma_2**2) + angle = xp.arctan2(gamma_2, gamma_1) / 2 * 180.0 / xp.pi + + The angle value is what this function returns. + + Parameters + ---------- + gamma_1 + The gamma 1 component of the shear. + gamma_2 + The gamma 2 component of the shear. + """ + magnitude, angle = shear_magnitude_and_angle_from( + gamma_1=gamma_1, gamma_2=gamma_2, xp=xp + ) + return angle + + +def multipole_k_m_and_phi_m_from( + multipole_comps: Tuple[float, float], m: int, xp=np +) -> Tuple[float, float]: + r""" + Returns the multipole normalization value `k_m` and angle `phi` from the multipole component parameters. + + The normalization and angle are given by: + + .. math:: + \phi^{\rm mass}_m = \frac{1}{m} \arctan{\frac{\epsilon_{\rm 2}^{\rm mp}}{\epsilon_{\rm 1}^{\rm mp}}}, \, \, + k^{\rm mass}_m = \sqrt{{\epsilon_{\rm 1}^{\rm mp}}^2 + {\epsilon_{\rm 2}^{\rm mp}}^2} \, . + + The conversion depends on the multipole order `m`, to ensure that all possible rotationally symmetric + multiple mass profiles are available in the conversion for multiple components spanning -inf to inf. + + Additional checks are performed which requires the angle `phi_m` is between -45 and 135 degrees. This ensures that + for certain multipole component values the angle does not jump from one boundary to another (e.g. without + this check certain values of the multipole components return -46.0 degrees and others 134.0 degrees). + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + multipole_comps + The first and second components of the multipole. + + Returns + ------- + The normalization and angle parameters of the multipole. + """ + multipole_comps = ( + multipole_comps[0], + _nudge_off_origin(multipole_comps[0], multipole_comps[1], xp=xp), + ) + + phi_m = ( + xp.arctan2( + multipole_comps[0], + xp.where( + xp.logical_and(multipole_comps[0] == 0, multipole_comps[1] == 0), + 1.0, + multipole_comps[1], + ), + ) + * 180.0 + / xp.pi + / float(m) + ) + + k_m = xp.sqrt(multipole_comps[1] ** 2 + multipole_comps[0] ** 2) + + phi_m = xp.where(phi_m < -90.0 / m, phi_m + 360.0 / m, phi_m) + + return k_m, phi_m + + +def multipole_k_m_phi_m_and_shape_angle_from( + multipole_comps: Tuple[float, float], + m: int, + ell_comps: Optional[Tuple[float, float]], + ellipse_angle: Optional[float], + xp=np +) -> Tuple[float, float, float]: + r""" + Returns the multipole normalization value `k_m`, angle `phi` and shape_angle `s` from the multipole + component parameters. The shape angle is the difference between the angle of the underlying elliptical profile and + the multipole `phi_m` and is what defines the shape of the perturbation around the ellipse oriented towards the + direction of the underlying position angle. You must supply either the ell_comps or position angle of the + underlying elliptical profile. + + The normalization and angle are given by: + + .. math:: + \phi^{\rm mass}_m = \frac{1}{m} \arctan{\frac{\epsilon_{\rm 2}^{\rm mp}}{\epsilon_{\rm 1}^{\rm mp}}}, \, \, + k^{\rm mass}_m = \sqrt{{\epsilon_{\rm 1}^{\rm mp}}^2 + {\epsilon_{\rm 2}^{\rm mp}}^2} \, . + + The shape angle is then given as (where \phi_{\rm ell} is the position angle of the underlying elliptical profile): + .. math:: + s^{\rm mass}_m = \phi_{\rm ell} - \phi_m \, . + + + The conversion depends on the multipole order `m`, to ensure that all possible rotationally symmetric + multiple mass profiles are available in the conversion for multiple components spanning -inf to inf. + + Additional checks are performed which requires the angle `phi_m` is between -45 and 135 degrees. This ensures that + for certain multipole component values the angle does not jump from one boundary to another (e.g. without + this check certain values of the multipole components return -46.0 degrees and others 134.0 degrees). The shape angle + is then also checked and required to be in the range +- 360/m. + + This ensures that when error estimates are computed from samples of a lens model via marginalization, the + calculation is not biased by the angle jumping between these two values. + + Parameters + ---------- + multipole_comps + The first and second components of the multipole. + m + The multipole order. + ell_comps + The elliptical components of the underlying elliptical distribution that the multipole is perturbing. + Note either ell_comps or galaxy_angle must be passed. + ellipse_angle + Alternative to supplying the ell_comps of the underlying profile, the position angle of the underlying profile. + + Returns + ------- + The normalization and angle parameters of the multipole. + """ + if ellipse_angle is None: + if ell_comps is None: + raise AssertionError('You must pass either the ell_comps or the position angle of the underlying distribution.') + else: + angle = ellipse_angle + else: + angle = angle_from(ell_comps, xp=xp) + + + k_m, phi_m = multipole_k_m_and_phi_m_from(multipole_comps, m, xp=xp) + + shape_angle = angle - phi_m + + while angle < -180 / m: + angle += 360 / m + while angle > 180 / m: + angle -= 360 / m + + return k_m, phi_m, shape_angle + + +def multipole_comps_from( + k_m: float, phi_m: Optional[float], m: int, + shape_angle: Optional[float]=None, ellipse_angle: Optional[float]=None, + xp=np +) -> Tuple[float, float]: + r""" + Returns the multipole component parameters from their normalization value `k_m` and angle `phi`. + + .. math:: + \phi^{\rm mass}_m = \frac{1}{m} \arctan{\frac{\epsilon_{\rm 2}^{\rm mp}}{\epsilon_{\rm 1}^{\rm mp}}}, \, \, + k^{\rm mass}_m = \sqrt{{\epsilon_{\rm 1}^{\rm mp}}^2 + {\epsilon_{\rm 2}^{\rm mp}}^2} \, . + + The conversion depends on the multipole order `m`, to ensure that all possible rotationally symmetric + multiple mass profiles are available in the conversion for multiple components spanning -inf to inf. + + Parameters + ---------- + k_m + The magnitude of the multipole. + phi_m + The angle of the multipole. You can supply either phi_m or shape_angle and ellipse_angle. + shape_angle + The shape angle of the multipole, defined as the difference between the underlying position angle and the + multipole phi_m. + ellipse_angle + The position_angle of the underlying elliptical profile. Must be supplied alongside shape_angle as an + alternative to phi_m. + + Returns + ------- + The multipole component parameters. + """ + # Degrees -> radians conversion + deg_to_rad = xp.asarray(np.pi / 180.0) + + if phi_m is not None: + angle = phi_m * float(m) * deg_to_rad + elif (shape_angle is None) or (ellipse_angle is None): + raise AssertionError('You must provide EITHER phi_m OR shape_angle and ellipse_angle.') + else: + multipole_angle = ellipse_angle-shape_angle + angle = multipole_angle * float(m) * deg_to_rad + + multipole_comp_0 = k_m * xp.sin(angle) + multipole_comp_1 = k_m * xp.cos(angle) + + return multipole_comp_0, multipole_comp_1 diff --git a/tests/fixtures/public_names/row08_latent/before/autogalaxy/profiles/light/standard/_multipole_mixin.py.txt b/tests/fixtures/public_names/row08_latent/before/autogalaxy/profiles/light/standard/_multipole_mixin.py.txt new file mode 100644 index 00000000..2bf2873a --- /dev/null +++ b/tests/fixtures/public_names/row08_latent/before/autogalaxy/profiles/light/standard/_multipole_mixin.py.txt @@ -0,0 +1,68 @@ +""" +Shared helper for light profiles with m=3 and m=4 Fourier perturbations on the +eccentric radius. + +Used by ``SersicMultipole`` (``sersic_multipole.py``) and ``GaussianMultipole`` +(``gaussian_multipole.py``). The leading underscore signals "implementation +detail" — when the future generalisation lands (a single wrapper-style multipole +that perturbs any radial profile, unified with the ellipse-fitting API), this +module will be replaced rather than evolved in-place. +""" + +from typing import Tuple + +import numpy as np + +import autoarray as aa + + +class _LightProfileMultipoleMixin: + """ + Provides ``perturbed_radii_from`` to light profiles that: + + - set ``multipole_3_comps`` and ``multipole_4_comps`` on ``self`` in ``__init__`` + - inherit from a base profile providing ``eccentric_radii_grid_from`` + """ + + multipole_3_comps: Tuple[float, float] + multipole_4_comps: Tuple[float, float] + + def perturbed_radii_from( + self, + grid: aa.type.Grid2DLike, + xp=np, + **kwargs, + ) -> np.ndarray: + """ + Returns the eccentric radii of ``grid`` perturbed by the m=3 and m=4 Fourier + multipoles, as a raw backend array (numpy or jax.numpy). + + The perturbation is + + r' = r * (1 + c_3 cos(3 theta) + s_3 sin(3 theta) + + c_4 cos(4 theta) + s_4 sin(4 theta)) + + where ``theta = arctan2(y, x)`` is the polar angle in the profile's + elliptical reference frame (the grid is already in that frame after the + ``@aa.decorators.transform`` decorator on the caller's ``image_2d_from``). + + Result is floored at 1e-8 to keep ``r ** (1/n)`` evaluations finite when a + large multipole component drives the radius through zero. + """ + grid_radii = self.eccentric_radii_grid_from(grid=grid, xp=xp, **kwargs) + grid_radii_array = ( + grid_radii.array if hasattr(grid_radii, "array") else grid_radii + ) + y = grid.array[:, 0] + x = grid.array[:, 1] + theta = xp.arctan2(y, x) + c3, s3 = self.multipole_3_comps + c4, s4 = self.multipole_4_comps + perturbation = ( + 1.0 + + c3 * xp.cos(3.0 * theta) + + s3 * xp.sin(3.0 * theta) + + c4 * xp.cos(4.0 * theta) + + s4 * xp.sin(4.0 * theta) + ) + return xp.maximum(xp.multiply(grid_radii_array, perturbation), 1e-8) diff --git a/tests/fixtures/public_names/row08_latent/before/autogalaxy/profiles/mass/sheets/external_shear.py.txt b/tests/fixtures/public_names/row08_latent/before/autogalaxy/profiles/mass/sheets/external_shear.py.txt new file mode 100644 index 00000000..e1f27554 --- /dev/null +++ b/tests/fixtures/public_names/row08_latent/before/autogalaxy/profiles/mass/sheets/external_shear.py.txt @@ -0,0 +1,163 @@ +import numpy as np + +import autoarray as aa + +from autogalaxy.profiles.mass.abstract.abstract import MassProfile + +from autogalaxy import convert + + +class ExternalShear(MassProfile): + r""" + Constant external shear field used in strong-lens mass models. + + The external shear represents the line-of-sight contribution to the lensing + potential from mass external to the primary lens (e.g. nearby group members, + large-scale structure). Because this contribution is approximately uniform over + the small angular extent of a strong-lens system, it is modelled as a constant + shear with two Cartesian components :math:`(\gamma_1, \gamma_2)`. + + The lensing potential is: + + .. math:: + + \psi(\boldsymbol{\theta}) = + -\tfrac{1}{2} |\gamma| \, r^2 \cos\!\big(2(\varphi - \phi_\gamma)\big) + + The deflection field in a reference frame aligned with the shear direction is: + + .. math:: + + \alpha_y = -|\gamma| \, y, \qquad \alpha_x = +|\gamma| \, x + + The convergence vanishes identically: + + .. math:: + + \kappa = 0 + + The shear magnitude and position angle are: + + .. math:: + + |\gamma| = \sqrt{\gamma_1^2 + \gamma_2^2}, \qquad + \phi_\gamma = \tfrac{1}{2} \mathrm{arctan2}(\gamma_2, \gamma_1) + + References + ---------- + - Schneider, Ehlers & Falco 1992, *Gravitational Lenses* (Springer) + """ + + def __init__(self, gamma_1: float = 0.0, gamma_2: float = 0.0): + r""" + Constant external shear term used in strong-lens mass models. + + ``ExternalShear`` represents the line-of-sight contribution to the lensing potential from mass that is + not part of the primary lens — typically nearby group/cluster members, large-scale structure, or + unmodelled satellites. Because this contribution is approximately uniform across the small angular + extent of a strong-lens system, it is parameterised as a constant shear with two components, + :math:`\gamma_1` and :math:`\gamma_2`, in the same convention as + ``LensCalc.shear_yx_2d_via_hessian_from`` and ``ShearYX2DIrregular``: + + - :math:`\gamma_1` produces stretching along the x/y axes + - :math:`\gamma_2` produces stretching along the diagonals + + The associated shear *magnitude* and *position angle* (degrees, anticlockwise from the +x axis) are: + + .. math:: + + |\gamma| = \sqrt{\gamma_1^2 + \gamma_2^2}, \qquad + \phi = \tfrac{1}{2} \, \mathrm{arctan2}(\gamma_2, \gamma_1). + + Note that the shear *position angle* lies in the direction of image stretching. An external mass + located in the *direction of compression* therefore appears at an angle offset by 90 degrees from + :math:`\phi`. + + Parameters + ---------- + gamma_1 + The :math:`\gamma_1` shear component. + gamma_2 + The :math:`\gamma_2` shear component. + """ + + super().__init__(centre=(0.0, 0.0), ell_comps=(0.0, 0.0)) + self.gamma_1 = gamma_1 + self.gamma_2 = gamma_2 + + def magnitude(self, xp=np): + r"""Returns the shear magnitude :math:`|\gamma| = \sqrt{\gamma_1^2 + \gamma_2^2}`.""" + return convert.shear_magnitude_from( + gamma_1=self.gamma_1, gamma_2=self.gamma_2, xp=xp + ) + + def angle(self, xp=np): + r"""Returns the shear position angle :math:`\phi = \tfrac{1}{2}\,\mathrm{arctan2}(\gamma_2, \gamma_1)` + in degrees, in the [0, 180) convention used elsewhere in the package.""" + return convert.shear_angle_from( + gamma_1=self.gamma_1, gamma_2=self.gamma_2, xp=xp + ) + + def convergence_func(self, grid_radius: float, xp=np) -> float: + return 0.0 + + def average_convergence_of_1_radius(self): + return 0.0 + + @aa.decorators.to_array + def convergence_2d_from(self, grid: aa.type.Grid2DLike, xp=np, **kwargs): + """A pure shear term has zero convergence at every grid point.""" + return xp.zeros(shape=grid.shape[0]) + + @aa.decorators.to_array + def potential_2d_from(self, grid: aa.type.Grid2DLike, xp=np, **kwargs): + r""" + Returns the lensing potential of the constant external shear, given by: + + .. math:: + + \psi(\theta) = -\tfrac{1}{2} |\gamma| \, r^2 \, \cos\!\big(2\,(\varphi - \phi_\gamma)\big) + + where :math:`r, \varphi` are the polar coordinates of ``grid`` and :math:`\phi_\gamma` is the shear + position angle (offset by ``-90 deg`` to remain consistent with the deflection-angle convention used + elsewhere in PyAutoLens). + """ + shear_angle = ( + self.angle(xp) - 90 + ) # offset by -90 deg to match the deflection-angle convention used elsewhere + phig = xp.deg2rad(shear_angle) + shear_amp = self.magnitude(xp=xp) + phicoord = xp.arctan2(grid.array[:, 0], grid.array[:, 1]) + rcoord = xp.sqrt(grid.array[:, 0] ** 2.0 + grid.array[:, 1] ** 2.0) + + return -0.5 * shear_amp * rcoord**2 * xp.cos(2 * (phicoord - phig)) + + @aa.decorators.to_vector_yx + @aa.decorators.transform(rotate_back=True) + def deflections_yx_2d_from(self, grid: aa.type.Grid2DLike, xp=np, **kwargs): + r""" + Returns the deflection angles of the constant external shear at each ``(y, x)`` arc-second + coordinate. + + In the profile's rotated reference frame (where the shear position angle is aligned with the x-axis) + the deflection reduces to: + + .. math:: + + \alpha_y(y, x) = -|\gamma| \, y, \qquad \alpha_x(y, x) = +|\gamma| \, x. + + The ``@transform(rotate_back=True)`` decorator rotates the input grid into this aligned frame and + rotates the resulting deflection vectors back into the original frame. Because the shear is a spin-2 + field, the *position angle* :math:`\phi` of the shear is encoded in the rotation of the grid and not + as an extra factor in the deflection formula above. + + Parameters + ---------- + grid + The grid of (y,x) arc-second coordinates the deflection angles are computed on. + xp + The array module (``numpy`` or ``jax.numpy``). + """ + deflection_y = -xp.multiply(self.magnitude(xp=xp), grid.array[:, 0]) + deflection_x = xp.multiply(self.magnitude(xp=xp), grid.array[:, 1]) + return xp.vstack((deflection_y, deflection_x)).T diff --git a/tests/test_public_names.py b/tests/test_public_names.py new file mode 100644 index 00000000..f1e823b2 --- /dev/null +++ b/tests/test_public_names.py @@ -0,0 +1,599 @@ +"""`pyauto-brain public-names` — added or renamed public library names go to a +human `/prm` (PyAutoBrain#641; AUTONOMY.md "Public-name narrowing of `glance` +— 2026-11-16"). + +The Witness cases: the seeded audit's row 08 diff (seven `latent_*_from` in +`autogalaxy/convert.py`) is refused; a private helper and a body-only change +pass; a rename is caught; a new `__init__` export is caught; a workspace repo is +ignored; a parse error cannot tell (exit 2); the close-out refusal reaches the +digest. Offline: local git repos in tmp_path, the row's real before/after files +(`fixtures/public_names/row08_latent/`, stored as `.py.txt` so the tenant +firewall does not read upstream library docstrings as organ code), and a fake +`gh` behind the `run` seam. Repo names here are invented (`LibGalaxy`): the +real list is `config/policy.yaml` `public_name_libraries:`. +""" + +from __future__ import annotations + +import json +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +BRAIN_HOME = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BRAIN_HOME / "bin")) + +import public_names as pn # noqa: E402 +from _repo_paths import repo_path # noqa: E402 — public_names put agents/ on the path + +FIXTURE = BRAIN_HOME / "tests" / "fixtures" / "public_names" / "row08_latent" +LATENT = sorted([ + "latent_shear_from", "latent_ellipse_from", "latent_multipole_from", + "latent_scaled_multipole_from", "latent_light_multipole_3_from", + "latent_light_multipole_4_from", "latent_light_multipoles_from"]) +#: The row's merge commit in the real library checkout, when present. +ROW08_MERGE = "e92eea86a8b2a8345b0d0135876df634d05a7865" +LIBS = {"LibGalaxy": "autogalaxy", "LibLens": "autolens"} + +needs_git = pytest.mark.skipif(shutil.which("git") is None, reason="needs git") + + +def _real_libs(): + try: + return pn.load_libraries() + except pn.LibrariesError as e: + pytest.skip(f"no body map here: {e}") + + +def _row08(tmp_path): + """The fixture's before/after trees, with their real `.py` names.""" + for src in FIXTURE.rglob("*.py.txt"): + dst = tmp_path / src.relative_to(FIXTURE).with_suffix("") + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(src.read_text()) + return tmp_path / "before", tmp_path / "after" + + +# --- row 08, the row that made the ruling --------------------------------------------- + +def test_witness_row08_all_seven_latent_helpers_are_added_and_refused(tmp_path): + before, after = _row08(tmp_path) + v = pn.for_trees(before, after, "LibGalaxy", libs=LIBS) + assert v["verdict"] == pn.HIT + assert sorted(e["name"] for e in v["added"]) == LATENT + assert {e["module"] for e in v["added"]} == {"autogalaxy.convert"} + assert v["renamed"] == [] and v["removed"] == [] and v["cannot_tell"] == [] + # external_shear.py only gained a class attribute; _multipole_mixin.py is + # a private module: neither is a public-name change. + assert v["modules_compared"] == 2 + why = pn.reason(v) + assert why.startswith("public name added/renamed: autogalaxy.convert.latent_") + assert why.endswith(" → human /prm") + + +def test_witness_row08_cli_exits_1_and_prints_the_reason_first(tmp_path, capsys): + before, after = _row08(tmp_path) + rc = pn.main(["--repo-name", "LibGalaxy", "--before", str(before), + "--after", str(after)], libs=LIBS) + out = capsys.readouterr().out.splitlines() + assert rc == 1 + assert out[0].startswith("public name added/renamed:") + assert sum(1 for line in out if line.startswith(" added:")) == 7 + + +@needs_git +def test_witness_row08_from_the_real_merge_commit_range(): + libs = _real_libs() + name = next((n for n, pkg in libs.items() if pkg == "autogalaxy"), None) + assert name, "the ruled libraries include the autogalaxy package" + import _pyauto_root + repo = repo_path(_pyauto_root.pyauto_root(), name) + have = subprocess.run(["git", "-C", str(repo), "cat-file", "-e", ROW08_MERGE], + capture_output=True) + if have.returncode != 0: + pytest.skip("no library checkout holding row 08's merge commit") + v = pn.for_range(repo, f"{ROW08_MERGE}^1..{ROW08_MERGE}", name=name, libs=libs) + assert v["verdict"] == pn.HIT + assert sorted(e["name"] for e in v["added"]) == LATENT + assert v["renamed"] == [] + + +# --- a scratch library repo ---------------------------------------------------------- + +def _git(repo, *args): + subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True) + + +def _repo(tmp_path, name="LibGalaxy", package="autogalaxy", files=None): + repo = tmp_path / name + (repo / package).mkdir(parents=True) + _git(tmp_path, "init", "-q", str(repo)) + _git(repo, "config", "user.email", "t@example.invalid") + _git(repo, "config", "user.name", "t") + _write(repo, files or { + f"{package}/__init__.py": "from .convert import ell_from\n", + f"{package}/convert.py": "def ell_from(a):\n return a\n\nSCALE = 2\n", + }) + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", "base") + return repo + + +def _write(repo, files): + for path, text in files.items(): + p = repo / path + p.parent.mkdir(parents=True, exist_ok=True) + p.write_text(text) + + +def _change(repo, files, remove=()): + _write(repo, files) + for path in remove: + (repo / path).unlink() + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", "change") + return pn.for_range(repo, "HEAD~1..HEAD", libs=LIBS) + + +@needs_git +def test_a_private_helper_passes(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/convert.py": + "def _helper(a):\n return a\n\n_CACHE = {}\n\n" + "def ell_from(a):\n return _helper(a)\n\nSCALE = 2\n"}) + assert v["verdict"] == pn.CLEAN and v["added"] == [] and v["renamed"] == [] + + +@needs_git +def test_a_body_only_change_passes(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/convert.py": + "def ell_from(a, b=1):\n return a * b\n\nSCALE = 3\n"}) + assert v["verdict"] == pn.CLEAN and v["modules_compared"] == 1 + + +@needs_git +def test_a_method_or_class_attribute_is_not_a_module_level_name(tmp_path): + repo = _repo(tmp_path, files={"autogalaxy/__init__.py": "", + "autogalaxy/profile.py": "class P:\n pass\n"}) + v = _change(repo, {"autogalaxy/profile.py": + "class P:\n latent = {}\n\n def new_method(self):\n" + " def inner():\n pass\n"}) + assert v["verdict"] == pn.CLEAN + + +@needs_git +def test_a_rename_is_caught(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/convert.py": + "def ell_comps_from(a):\n return a\n\nSCALE = 2\n"}) + assert v["verdict"] == pn.HIT and v["added"] == [] + assert v["renamed"] == [{"module": "autogalaxy.convert", "old": "ell_from", + "new": "ell_comps_from", "kind": "def"}] + assert "autogalaxy.convert.ell_comps_from (renamed from ell_from)" in pn.reason(v) + + +@needs_git +def test_a_new_init_export_is_caught(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/__init__.py": + "from .convert import ell_from\nfrom .convert import SCALE as scale\n"}) + assert v["verdict"] == pn.HIT + assert v["added"] == [{"module": "autogalaxy", "name": "scale", "kind": "import"}] + + +@needs_git +def test_a_new_all_entry_and_star_import_in_init_are_caught(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/__init__.py": + "from .convert import ell_from\nfrom .extra import *\n" + "__all__ = ['ell_from', 'Extra']\n"}) + assert {e["name"] for e in v["added"]} == {"* from .extra", "Extra"} + + +@needs_git +def test_a_new_module_and_a_module_level_if_block_count(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/new.py": + "try:\n import jax\n HAS_JAX = True\nexcept ImportError:\n" + " HAS_JAX = False\n\nclass Thing:\n pass\n"}) + assert sorted(e["name"] for e in v["added"]) == ["HAS_JAX", "Thing"] + + +@needs_git +def test_a_removal_alone_is_info_not_a_hit(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/convert.py": "def ell_from(a):\n return a\n"}) + assert v["verdict"] == pn.CLEAN + assert v["removed"] == [{"module": "autogalaxy.convert", "name": "SCALE", + "kind": "assign"}] + assert "info — removed" in pn.summary(v) + + +@needs_git +def test_tests_and_files_outside_the_package_are_ignored(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"test_autogalaxy/test_convert.py": "def test_new():\n pass\n", + "autogalaxy/tests/helpers.py": "def helper():\n pass\n", + "autogalaxy/test_more.py": "def thing():\n pass\n", + "scripts/tool.py": "def tool():\n pass\n"}) + assert v["verdict"] == pn.CLEAN and v["modules_compared"] == 0 + + +@needs_git +def test_a_workspace_or_organ_repo_is_ignored(tmp_path): + for name in ("galaxy_workspace", "OrganBrain", "galaxy_assistant"): + repo = _repo(tmp_path, name=name, package="autogalaxy") + v = _change(repo, {"autogalaxy/convert.py": "def brand_new():\n pass\n"}) + assert v["verdict"] == pn.CLEAN and v.get("not_library"), name + assert pn.main(["--repo", str(tmp_path / "OrganBrain"), "--range", "HEAD~1..HEAD"], + libs=LIBS) == 0 + + +@needs_git +def test_a_parse_error_cannot_tell_and_exits_2(tmp_path, capsys): + repo = _repo(tmp_path) + _change(repo, {"autogalaxy/convert.py": "def ell_from(a:\n return a\n"}) + rc = pn.main(["--repo", str(repo), "--range", "HEAD~1..HEAD"], libs=LIBS) + out = capsys.readouterr().out + assert rc == 2 + assert out.startswith("public-name check could not tell: autogalaxy/convert.py (after) " + "does not parse") + assert out.splitlines()[0].endswith("→ human /prm") + + +@needs_git +def test_an_unreadable_range_cannot_tell(tmp_path): + repo = _repo(tmp_path) + v = pn.for_range(repo, "HEAD~1..HEAD", libs=LIBS) # there is no HEAD~1 + assert v["verdict"] == pn.CANNOT + + +def test_usage_errors_exit_64(capsys): + assert pn.main([]) == pn.EXIT_USAGE + assert pn.main(["not-a-ref"]) == pn.EXIT_USAGE + + +def test_the_library_list_is_policy_config_with_body_map_packages(tmp_path): + policy = tmp_path / "policy.yaml" + body = tmp_path / "repos.yaml" + policy.write_text("other: 1\npublic_name_libraries: [LibGalaxy, 'LibLens']\n") + body.write_text("repos:\n LibGalaxy:\n path: g/LibGalaxy\n package: autogalaxy\n" + " LibLens:\n package: \"autolens\" # the lens package\n" + " galaxy_workspace:\n category: workspace\ncategories: {}\n") + libs = pn.load_libraries(policy, body) + assert libs == LIBS + assert pn.library_package("ExampleOrg/LibLens", libs) == "autolens" + assert pn.library_package("/x/LibGalaxy.git", libs) == "autogalaxy" + assert pn.library_package("ExampleOrg/galaxy_workspace", libs) is None + body.write_text("repos:\n LibGalaxy:\n package: autogalaxy\n") + with pytest.raises(pn.LibrariesError, match="LibLens"): + pn.load_libraries(policy, body) # a ruled library with no package: fail closed + policy.write_text("other: 1\n") + with pytest.raises(pn.LibrariesError): + pn.load_libraries(policy, body) + + +def test_an_unreadable_library_list_cannot_tell(monkeypatch, tmp_path): + def boom(*a, **k): + raise pn.LibrariesError("config/policy.yaml unreadable") + monkeypatch.setattr(pn, "ruled_libraries", boom) + v = pn.for_trees(tmp_path, tmp_path, "AnyRepo") + assert v["verdict"] == pn.CANNOT and "policy" in v["cannot_tell"][0] + monkeypatch.setattr(pn, "ruled_libraries", lambda *a, **k: ["LibGalaxy"]) + monkeypatch.setattr(pn, "_body_map", lambda *a, **k: {}) + v = pn.for_trees(tmp_path, tmp_path, "LibGalaxy") # a library with no package + assert v["verdict"] == pn.CANNOT and "package" in v["cannot_tell"][0] + + +def test_the_real_config_rules_the_five_library_packages(): + libs = _real_libs() + assert sorted(libs.values()) == ["autoarray", "autocti", "autofit", "autogalaxy", + "autolens"] + + +# --- the PR read: `gh api`, read-only, behind the `run` seam -------------------------- + +class FakeGh: + def __init__(self, files, sources, fail=None, merge_base="m" * 40, packages=("autolens",)): + self.files, self.sources, self.fail, self.calls = files, sources, fail, [] + self.merge_base, self.packages = merge_base, packages + + def __call__(self, argv, **kw): + self.calls.append(argv) + path = next(a for a in argv[2:] if a.startswith("repos/")) + if self.fail and self.fail in path: + return subprocess.CompletedProcess(argv, 1, "", "HTTP 502") + if path.endswith("/pulls/7"): + out = json.dumps({"base": "b" * 40, "head": "h" * 40}) + elif "/compare/" in path: + out = json.dumps({"sha": self.merge_base}) + elif "/pulls/7/files" in path: + out = "\n".join(json.dumps(f) for f in self.files) + elif "/contents/" in path: + fpath, ref = path.split("/contents/", 1)[1].split("?ref=") + key = (fpath, ref[0]) + if "--jq" in argv and fpath in self.packages and ref[0] == "h": + out = json.dumps({"t": "array"}) # the package directory listing + elif key not in self.sources: + return subprocess.CompletedProcess(argv, 1, "", "HTTP 404") + else: + out = self.sources[key] + else: + raise AssertionError(path) + return subprocess.CompletedProcess(argv, 0, out, "") + + +def test_a_pr_is_read_from_its_merge_base_and_head(): + gh = FakeGh( + files=[{"filename": "autolens/lens.py", "status": "modified"}, + {"filename": "autolens/new.py", "status": "added"}, + {"filename": "docs/x.rst", "status": "modified"}], + sources={("autolens/lens.py", "m"): "def a():\n pass\n", + ("autolens/lens.py", "h"): "def a():\n return 1\n", + ("autolens/new.py", "h"): "class New:\n pass\n"}) + v = pn.for_pr("ExampleOrg/LibLens#7", run=gh, libs=LIBS) + assert v["verdict"] == pn.HIT and v["base"] == "m" * 40 + assert [e["name"] for e in v["added"]] == ["New"] + assert all(c[:2] == ["gh", "api"] for c in gh.calls) # read-only: gh api only + + +def test_an_unreadable_gh_reply_cannot_tell(): + gh = FakeGh(files=[], sources={}, fail="/compare/") + assert pn.for_pr("ExampleOrg/LibLens#7", run=gh, libs=LIBS)["verdict"] == pn.CANNOT + gh = FakeGh(files=[{"filename": "autolens/lens.py", "status": "modified"}], + sources={("autolens/lens.py", "m"): "X = 1\n"}) + v = pn.for_pr("ExampleOrg/LibLens#7", run=gh, libs=LIBS) # head contents 404 + assert v["verdict"] == pn.CANNOT and "could not be read" in v["cannot_tell"][0] + + +def test_a_non_library_pr_asks_github_nothing(): + gh = FakeGh(files=[], sources={}) + assert pn.main(["ExampleOrg/lens_workspace#7"], run=gh, libs=LIBS) == 0 + assert gh.calls == [] + + +# --- wired: the close-out, the tiered merge, the review surface ----------------------- + +def test_the_closeout_prompt_runs_the_check_on_its_pr(tmp_path): + sys.path.insert(0, str(BRAIN_HOME / "tests")) + from test_orchestrator_closeout import PR1, orch + tmpl = (BRAIN_HOME / "agents/conductors/batch/closeout_template.md").read_text() + assert "{public_names_cmd}" in tmpl and "public name added/renamed" in tmpl + prompt = orch.closeout_prompt("t1", PR1, "draft/x/t1.md", tmp_path / "b.md", + tmp_path / "leases") + assert f"pyauto-brain public-names {PR1}" in prompt + + +def test_the_closeout_refusal_reaches_the_digest(tmp_path): + sys.path.insert(0, str(BRAIN_HOME / "tests")) + import test_orchestrator_closeout as tc + before, after = _row08(tmp_path / "row08") + v = pn.for_trees(before, after, "LibGalaxy", libs=LIBS) + why = pn.reason(v) + mind, brief, home, sp = tc._shift(tmp_path) + tc._tick(brief, mind, home, sp, 1) + tc._verdict(home, brief, "named", result="refused", pr=tc.PR1, why=why, gate="", + model="claude-opus-5-5") + tc._tick(brief, mind, home, sp, 2) + slot = tc.orch.slot_dir(brief, home) + c = tc.orch.read_counters(slot) + assert c["closeouts"][tc.PR1] == {**c["closeouts"][tc.PR1], "state": "refused", + "why": why} + assert c["glance_auto_merges"] == 0 + d = tc._digest.build(tc._brief.parse(brief.read_text())["brief"], slot, c, + health=tc.t._health) + assert f"awaiting /prm — close-out refused: {why}" in d + + +def test_the_tiered_merge_and_ship_skills_refuse_on_a_hit(): + ref = (BRAIN_HOME / "skills/prm/reference.md").read_text() + tiered = ref.split("## Tiered merge", 1)[1].split("\n## ", 1)[0] + assert "pyauto-brain public-names" in tiered and "Exit 1" in tiered + for skill in ("ship_library", "ship_workspace"): + text = (BRAIN_HOME / "skills" / skill / f"{skill}.md").read_text() + assert "public-names` exit 1 or 2" in text.replace("\n ", " ") + + +def test_the_cli_is_dispatched_by_pyauto_brain(tmp_path): + libs = _real_libs() + name = next(n for n, pkg in libs.items() if pkg == "autogalaxy") + before, after = _row08(tmp_path) + r = subprocess.run([str(BRAIN_HOME / "bin" / "pyauto-brain"), "public-names", + "--repo-name", name, "--before", str(before), + "--after", str(after)], capture_output=True, text=True) + assert r.returncode == 1 and r.stdout.startswith("public name added/renamed:") + + +@needs_git +def test_the_review_surface_lists_the_public_name_delta(tmp_path, monkeypatch): + sys.path.insert(0, str(BRAIN_HOME / "agents" / "faculties" / "review")) + import _review + monkeypatch.setattr(pn, "ruled_libraries", lambda *a, **k: list(LIBS)) + monkeypatch.setattr(pn, "_body_map", + lambda *a, **k: {k_.casefold(): v for k_, v in LIBS.items()}) + repo = _repo(tmp_path) + _git(repo, "update-ref", "refs/remotes/origin/main", "HEAD") + _change(repo, {"autogalaxy/convert.py": + "def ell_from(a):\n return a\n\ndef latent_from(a):\n pass\n"}) + s = _review.repo_surface(repo) + assert "public-name-added-or-renamed" in s["risk_flags"] + assert s["public_names"]["verdict"] == pn.HIT + assert [e["name"] for e in s["public_names"]["added"]] == ["latent_from"] + assert [e["name"] for e in s["public_names"]["removed"]] == ["SCALE"] + ws = _repo(tmp_path, name="galaxy_workspace") + _git(ws, "update-ref", "refs/remotes/origin/main", "HEAD") + _change(ws, {"autogalaxy/convert.py": "def other():\n pass\n"}) + assert "public_names" not in _review.repo_surface(ws) + + +# --- review round 1 (4605a26): case, the watcher gate, packages, stars, merge-base ---- + +def test_repo_names_match_case_folded_owner_repo_and_list(tmp_path): + assert pn.library_package("examplelabs/libgalaxy#656".split("#")[0], LIBS) == "autogalaxy" + assert pn.library_package("EXAMPLE/LIBLENS", LIBS) == "autolens" + policy, body = tmp_path / "policy.yaml", tmp_path / "repos.yaml" + policy.write_text("public_name_libraries: [libgalaxy]\n") + body.write_text("repos:\n LibGalaxy:\n package: autogalaxy\n") + assert pn.library_package("examplelabs/LIBGALAXY", policy_path=policy, + map_path=body) == "autogalaxy" + gh = FakeGh(files=[{"filename": "autolens/new.py", "status": "added"}], + sources={("autolens/new.py", "h"): "def brand_new():\n pass\n"}) + assert pn.main(["examplelabs/liblens#7"], run=gh, libs=LIBS) == 1 + + +def test_a_non_library_passes_before_the_body_map_is_read(tmp_path): + policy = tmp_path / "policy.yaml" + policy.write_text("public_name_libraries: [LibGalaxy]\n") + gone = tmp_path / "no-mind" / "repos.yaml" + assert pn.library_package("x/galaxy_workspace", policy_path=policy, map_path=gone) is None + with pytest.raises(pn.LibrariesError, match="unreadable"): + pn.library_package("x/LibGalaxy", policy_path=policy, map_path=gone) + + +def test_a_non_library_pr_passes_when_mind_is_unreadable(monkeypatch): + monkeypatch.setattr(pn, "_body_map", lambda map_path=None: (_ for _ in ()).throw( + pn.LibrariesError("the body map is unreadable"))) + gh = FakeGh(files=[], sources={}) + assert pn.main(["ExampleOrg/some_workspace#7"], run=gh) == 0 and gh.calls == [] + + +def test_a_package_directory_missing_at_the_head_cannot_tell(tmp_path): + before, after = tmp_path / "b", tmp_path / "a" + (before / "autogalaxy").mkdir(parents=True) + (after / "galaxy").mkdir(parents=True) # a stale `package:` + v = pn.for_trees(before, after, "LibGalaxy", libs=LIBS) + assert v["verdict"] == pn.CANNOT and "package directory" in v["cannot_tell"][0] + gh = FakeGh(files=[], sources={}, packages=()) + v = pn.for_pr("ExampleOrg/LibLens#7", run=gh, libs=LIBS) + assert v["verdict"] == pn.CANNOT and "package directory" in v["cannot_tell"][0] + + +@needs_git +def test_a_stale_package_in_a_range_cannot_tell(tmp_path): + repo = _repo(tmp_path, package="galaxy", files={"galaxy/__init__.py": ""}) + _change(repo, {"galaxy/x.py": "def y():\n pass\n"}) + v = pn.for_range(repo, "HEAD~1..HEAD", libs=LIBS) # LIBS says autogalaxy + assert v["verdict"] == pn.CANNOT and "package directory" in v["cannot_tell"][0] + + +def test_an_empty_merge_base_cannot_tell(): + gh = FakeGh(files=[], sources={}, merge_base="") + v = pn.for_pr("ExampleOrg/LibLens#7", run=gh, libs=LIBS) + assert v["verdict"] == pn.CANNOT and "merge-base" in v["cannot_tell"][0] + + +@needs_git +def test_all_extend_and_append_in_init_are_read(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/__init__.py": + "from .convert import ell_from\n__all__ = ['ell_from']\n" + "__all__.extend(['Extra'])\n__all__.append('More')\n" + "__all__ += ['Third']\n"}) + assert {e["name"] for e in v["added"]} == {"Extra", "More", "Third"} + + +@needs_git +def test_a_star_import_of_a_changed_module_cannot_tell(tmp_path): + repo = _repo(tmp_path, files={"autogalaxy/__init__.py": "from ._impl import *\n", + "autogalaxy/_impl.py": "def a():\n pass\n"}) + v = _change(repo, {"autogalaxy/_impl.py": "def a():\n pass\n\ndef b():\n pass\n"}) + assert v["verdict"] == pn.CANNOT + assert "autogalaxy/__init__.py star-imports `autogalaxy._impl`, a private" \ + in v["cannot_tell"][0] + + +@needs_git +def test_a_star_import_of_a_changed_public_module_is_compared_directly(tmp_path): + repo = _repo(tmp_path, files={"autogalaxy/__init__.py": "from .agg import *\n", + "autogalaxy/agg.py": "def a():\n pass\n"}) + v = _change(repo, {"autogalaxy/agg.py": "def a():\n return 1\n"}) + assert v["verdict"] == pn.CLEAN and v["cannot_tell"] == [] + v = _change(repo, {"autogalaxy/agg.py": "def a():\n return 1\n\ndef b():\n pass\n"}) + assert v["verdict"] == pn.HIT and [e["name"] for e in v["added"]] == ["b"] + + +@needs_git +def test_a_star_import_that_cannot_be_resolved_cannot_tell(tmp_path): + repo = _repo(tmp_path, files={"autogalaxy/__init__.py": "from ... import *\n", + "autogalaxy/agg.py": "def a():\n pass\n"}) + v = _change(repo, {"autogalaxy/agg.py": "def a():\n return 1\n"}) + assert v["verdict"] == pn.CANNOT and "cannot be resolved" in v["cannot_tell"][0] + + +@needs_git +def test_stub_files_are_skipped(tmp_path): + repo = _repo(tmp_path) + v = _change(repo, {"autogalaxy/convert.pyi": "def stub_only() -> int: ...\n"}) + assert v["verdict"] == pn.CLEAN and v["modules_compared"] == 0 + + +class _Check: + """A stand-in for the public_names module behind the watcher's gate.""" + + def __init__(self, verdict): + self.verdict = verdict + + def for_pr(self, url): + return self.verdict + + reason = staticmethod(pn.reason) + + +def test_the_watcher_gate_says_why_or_nothing(): + gate = sys.modules["test_orchestrator_closeout"].orch.public_names_gate \ + if "test_orchestrator_closeout" in sys.modules else None + if gate is None: + sys.path.insert(0, str(BRAIN_HOME / "tests")) + from test_orchestrator_closeout import orch + gate = orch.public_names_gate + clean = {"verdict": pn.CLEAN, "added": [], "renamed": [], "cannot_tell": []} + assert gate("u", check=_Check(clean)) == "" + hit = {"verdict": pn.HIT, "added": [{"module": "m", "name": "n"}], "renamed": [], + "cannot_tell": []} + assert gate("u", check=_Check(hit)) == "public name added/renamed: m.n → human /prm" + cannot = {"verdict": pn.CANNOT, "added": [], "renamed": [], "cannot_tell": ["x"]} + assert gate("u", check=_Check(cannot)) == "public-name check could not tell: x → human /prm" + + +def test_the_watcher_refuses_a_public_name_pr_before_any_closeout_session(tmp_path): + sys.path.insert(0, str(BRAIN_HOME / "tests")) + import test_orchestrator_closeout as tc + before, after = _row08(tmp_path / "row08") + why = pn.reason(pn.for_trees(before, after, "LibGalaxy", libs=LIBS)) + launched = [] + + def no_claude(argv, **kw): + launched.append(argv) + raise AssertionError("no close-out session may start") + + real = tc.orch.RealSpawner(tmp_path / "b.md", "auto", run=no_claude, + public_names=lambda url: why if url == tc.PR1 else "") + + class Gated(tc.Spawner): + def spawn_closeout(self, task, pr_url, prompt_path, lease_dir): + self.closeouts.append((task, pr_url)) + if pr_url != tc.PR1: + return super().spawn_closeout(task, pr_url, prompt_path, lease_dir) + return real.spawn_closeout(task, pr_url, prompt_path, lease_dir) + + mind = tc.t._mind(tmp_path / "mind") + brief = tmp_path / "shift.md" + brief.write_text(tc.t.BRIEF.format(issue=tc.t.ISSUE, packet="")) + home, sp = tmp_path / "home", Gated() + tc.orch.tick(brief, mind, home=home, now=tc.t.NOW, spawner=sp, agents=tc.Agents(), + health=tc._health({})) + tc._tick(brief, mind, home, sp, 1) # green: the gate refuses PR1 + tc._tick(brief, mind, home, sp, 2) # the refusal is reaped + assert launched == [] + slot = tc.orch.slot_dir(brief, home) + c = tc.orch.read_counters(slot) + co = c["closeouts"][tc.PR1] + assert co["state"] == "refused" and co["why"] == why and co.get("agent_id") is None + assert c["glance_auto_merges"] == 0 + d = tc._digest.build(tc._brief.parse(brief.read_text())["brief"], slot, c, + health=tc.t._health) + assert f"awaiting /prm — close-out refused: {why}" in d