diff --git a/connectors/antigravity/agents/register-scripting.md b/connectors/antigravity/agents/register-scripting.md index f0bdb8a9..baea4909 100644 --- a/connectors/antigravity/agents/register-scripting.md +++ b/connectors/antigravity/agents/register-scripting.md @@ -17,6 +17,6 @@ subagent: true model: inherit --- -You are an expert neuroanatomist registering one brain with LangSlice: a stack of histology sections from one brain, placed in a BrainGlobe atlas. The first message gives the job: what to do, the tools, and the facts about this stack and atlas. Work the job with the tools and finish with `submit`. +You are an expert neuroanatomist registering one brain with LangSlice: a stack of histology sections from one brain, placed in a BrainGlobe atlas. The first message gives the job: what to do, the tools, and the facts about this stack and atlas. Work the job with the LangSlice tools, your own scripts and any software you judge best, and finish with `submit`. Run each script on its own with BypassSandbox: it reads the atlas and the images outside the sandbox. diff --git a/connectors/antigravity/skills/placement/SKILL.md b/connectors/antigravity/skills/placement/SKILL.md index cf6359ea..2b972308 100644 --- a/connectors/antigravity/skills/placement/SKILL.md +++ b/connectors/antigravity/skills/placement/SKILL.md @@ -12,8 +12,11 @@ correct a wrong plane. ## Positions -- **Keep the filename order** unless the anatomy clearly says otherwise. - Sections are usually named in cutting order. +- **Keep the order the filenames' section numbers give** unless the + anatomy clearly says otherwise. Sections are usually numbered in cutting + order; when a name holds several numbers (an image id, then `s0132`), + the section number is the one that steps along the stack, and it can run + backwards. - **Fit the positions to the file numbers.** Once each section has a first position (from `deepslice_place` or by eye), list each position beside the section number in its filename. Real stacks fall on one line: its slope is diff --git a/connectors/claude-code/agents/register-scripting.md b/connectors/claude-code/agents/register-scripting.md index eaa894d3..46fd8a93 100644 --- a/connectors/claude-code/agents/register-scripting.md +++ b/connectors/claude-code/agents/register-scripting.md @@ -8,6 +8,6 @@ model: inherit omitClaudeMd: true --- -You are an expert neuroanatomist registering one brain with LangSlice: a stack of histology sections from one brain, placed in a BrainGlobe atlas. The first message gives the job: what to do, the tools, and the facts about this stack and atlas. Work the job with the tools and finish with `submit`. +You are an expert neuroanatomist registering one brain with LangSlice: a stack of histology sections from one brain, placed in a BrainGlobe atlas. The first message gives the job: what to do, the tools, and the facts about this stack and atlas. Work the job with the LangSlice tools, your own scripts and any software you judge best, and finish with `submit`. Run a script that takes long (one that fits sections) as a Bash command with `run_in_background`: Claude Code's sandbox ends a command that outlasts its time limit, and the script with it. diff --git a/connectors/claude-code/skills/placement/SKILL.md b/connectors/claude-code/skills/placement/SKILL.md index cf6359ea..2b972308 100644 --- a/connectors/claude-code/skills/placement/SKILL.md +++ b/connectors/claude-code/skills/placement/SKILL.md @@ -12,8 +12,11 @@ correct a wrong plane. ## Positions -- **Keep the filename order** unless the anatomy clearly says otherwise. - Sections are usually named in cutting order. +- **Keep the order the filenames' section numbers give** unless the + anatomy clearly says otherwise. Sections are usually numbered in cutting + order; when a name holds several numbers (an image id, then `s0132`), + the section number is the one that steps along the stack, and it can run + backwards. - **Fit the positions to the file numbers.** Once each section has a first position (from `deepslice_place` or by eye), list each position beside the section number in its filename. Real stacks fall on one line: its slope is diff --git a/connectors/codex/agents/register_scripting.toml b/connectors/codex/agents/register_scripting.toml index 4495da9d..4208313f 100644 --- a/connectors/codex/agents/register_scripting.toml +++ b/connectors/codex/agents/register_scripting.toml @@ -3,5 +3,5 @@ description = "Registers ONE brain (one LangSlice job folder) with the LangSlice sandbox_mode = "workspace-write" developer_instructions = """ -You are an expert neuroanatomist registering one brain with LangSlice: a stack of histology sections from one brain, placed in a BrainGlobe atlas. The first message gives the job: what to do, the tools, and the facts about this stack and atlas. Work the job with the tools and finish with `submit`. +You are an expert neuroanatomist registering one brain with LangSlice: a stack of histology sections from one brain, placed in a BrainGlobe atlas. The first message gives the job: what to do, the tools, and the facts about this stack and atlas. Work the job with the LangSlice tools, your own scripts and any software you judge best, and finish with `submit`. """ diff --git a/connectors/codex/skills/placement/SKILL.md b/connectors/codex/skills/placement/SKILL.md index cf6359ea..2b972308 100644 --- a/connectors/codex/skills/placement/SKILL.md +++ b/connectors/codex/skills/placement/SKILL.md @@ -12,8 +12,11 @@ correct a wrong plane. ## Positions -- **Keep the filename order** unless the anatomy clearly says otherwise. - Sections are usually named in cutting order. +- **Keep the order the filenames' section numbers give** unless the + anatomy clearly says otherwise. Sections are usually numbered in cutting + order; when a name holds several numbers (an image id, then `s0132`), + the section number is the one that steps along the stack, and it can run + backwards. - **Fit the positions to the file numbers.** Once each section has a first position (from `deepslice_place` or by eye), list each position beside the section number in its filename. Real stacks fall on one line: its slope is diff --git a/docs/reference/tools.md b/docs/reference/tools.md index 99d87808..8b8ff285 100644 --- a/docs/reference/tools.md +++ b/docs/reference/tools.md @@ -233,6 +233,7 @@ Draws pictures of sections and the atlas. Writes nothing. | `registrations` | none | `{filename: number}`: draw a section under an earlier [registration](#restore_registration) of its own, writing nothing. | | `resolution` | 0 (job's size) | Long edge in pixels. Offered only when the job's [`image_resolution`](settings.md#pictures) is `auto`. | | `sheet` | false | Tile the pictures into sheets of up to 16. Agent CLI and library only. | +| `cutting_angles` | the stack's | `{"pitch_deg": number, "yaw_deg": number}`: draw `atlas` mode at `positions_mm` at these angles instead of the stack's, writing nothing; either left out keeps the stack's. Refused with sections or in another mode. | Atlas borders are drawn as cased lines: a black core with a white edge on light tissue, a white core with a black edge on dark tissue; the caption @@ -436,6 +437,7 @@ Writes nothing. |---|---|---| | `regions` | (required) | Regions, descendants included; `"CTX:left"` names one side. | | `positions_mm` | (required) | Positions; one outside the atlas is clamped into its range. | +| `cutting_angles` | the stack's | `{"pitch_deg": number, "yaw_deg": number}`: draw the planes at these angles instead of the stack's, writing nothing; either left out keeps the stack's. | **Switch off:** `grep_atlas_view`. @@ -690,7 +692,9 @@ agent CLI and in the library only. See Sets where sections sit along the slicing axis, and the stack's cutting angles. A value outside the atlas range is clamped into it and reported. The stack's order follows the positions. A changed position or angle clears the -deformation of each section it moves. +deformation of each section it moves. The reply lists the positions +`written` and, when `cutting_angles` was given, the stack's angles as +`cutting_angles_written` (`pitch_deg`, `yaw_deg`). | Argument | Default | What it does | |---|---|---| @@ -766,7 +770,9 @@ core count; below 16 cores they are fitted in turn). A fit that changes the scale along either axis by more than a factor of 0.8 to 1.25 is flagged `SCALE_CHANGED`, one that changes the shear by more than -0.15 `SHEAR`, and one that turns the section more than 45 degrees says so. A +0.15 `SHEAR`, one that scales one axis more than 1.25 times the other +`ANISOTROPIC`, and one that turns the section more than 45 degrees says so. +A flag warns; the fit is written, and `undo` takes it back. A region too small for Elastix is refused (`BAD_ARGUMENT`). **In a run when** Linear is on. **Switch off:** `elastix_affine`. diff --git a/src/langslice/core/fits/flags.py b/src/langslice/core/fits/flags.py index d1a5b152..8de73123 100644 --- a/src/langslice/core/fits/flags.py +++ b/src/langslice/core/fits/flags.py @@ -17,6 +17,7 @@ class FitFlag(TextEnum): FOLDS = "FOLDS" REGION_FOLDED = "REGION_FOLDED" REGION_VANISHED = "REGION_VANISHED" + ANISOTROPIC = "ANISOTROPIC" SCALE_CHANGED = "SCALE_CHANGED" SHEAR = "SHEAR" diff --git a/src/langslice/core/pictures/look.py b/src/langslice/core/pictures/look.py index ba021f7f..e0a7e709 100644 --- a/src/langslice/core/pictures/look.py +++ b/src/langslice/core/pictures/look.py @@ -153,6 +153,7 @@ class LookRequest: masks: tuple[str, ...] = () depth: int = OVERLAY_DEPTH registrations: tuple[tuple[str, int, bool], ...] = () + cutting_angles: tuple[float, float] | None = None def registration_of(self, section: str) -> tuple[int, bool] | None: """``(number, held)`` of the registration *section* is drawn under, @@ -189,6 +190,11 @@ def args(self) -> dict[str, Any]: if self.registrations else {} ), + **( + {"cutting_angles": [float(v) for v in self.cutting_angles]} + if self.cutting_angles is not None + else {} + ), } @classmethod @@ -220,9 +226,17 @@ def from_args(cls, args: dict[str, Any]) -> LookRequest: (str(name), int(number), bool(held)) for name, number, held in args.get("registrations") or () ), + cutting_angles=_angle_pair(args.get("cutting_angles")), ) +def _angle_pair(value: Any) -> tuple[float, float] | None: + """A recipe's ``cutting_angles`` as ``(pitch_deg, yaw_deg)``; None when it has none.""" + if not value: + return None + return float(value[0]), float(value[1]) + + @dataclass(frozen=True) class LookPicture: """One picture: the captioned image, its index caption, its recipe, the @@ -718,9 +732,9 @@ def _overlay_picture( if drawn else "deformation held but not drawable" if drawn is False - else "linear placement only" + else f"linear placement only: {LINEAR_MOVES}" if request.warp == "none" and record.deformation - else "no deformation" + else f"no deformation: {LINEAR_MOVES}" ) atlas_words = " + ".join(layers) or "none" if options.atlas_images and options.atlas_opacity > 0: @@ -968,6 +982,9 @@ def _mask_words(notes: list[dict[str, Any]], record: Section) -> str: ) +LINEAR_MOVES = "the transform moves the section onto the atlas, which keeps its place" + + def _landmark_context(state: Stack, record: Section) -> dict[str, Any]: from langslice.core.fits.landmarks import context @@ -1020,7 +1037,11 @@ def _atlas_picture( picture = framed_atlas(ws, state, position_mm, options, angles=angles, um_per_px=um) base = picture.size section = state.by_id(request.sections[0]) if len(request.sections) == 1 else None - median = state.drawn_at_median(angles) if section is None else False + median = ( + state.drawn_at_median(angles) + if section is None and request.cutting_angles is None + else False + ) label = _zoom_tag(request.zoom, base, picture.size) + atlas_caption( state, position_mm, options, angles=angles, median=median ) @@ -1028,6 +1049,8 @@ def _atlas_picture( plane = ( view_angles_label(angles, median=True) if median + else f"{angles_label(angles)} (the cutting angles asked for, not written)" + if request.cutting_angles is not None else f"{angles_label(angles)} (the stack's cutting angles)" ) if section: @@ -1191,7 +1214,19 @@ def look( if request.warp not in WARP_CHOICES: raise Refused(RefusalCode.BAD_ARGUMENT, f"warp must be one of {', '.join(WARP_CHOICES)}") long_edge = int(request.long_edge or picture_edge(ws)) - plane = angles if angles is not None else state.view_angles + if request.cutting_angles is not None and (request.mode != "atlas" or request.sections): + raise Refused( + RefusalCode.BAD_ARGUMENT, + "cutting_angles draws atlas mode at positions_mm; a section's picture " + "is at its own plane. Nothing was drawn.", + ) + plane = ( + request.cutting_angles + if request.cutting_angles is not None + else angles + if angles is not None + else state.view_angles + ) if request.mode == "positioning": return _positioning(ws, state, request, long_edge, plane, zoom_edge) if request.mode == "atlas": diff --git a/src/langslice/doors/mcp/server.py b/src/langslice/doors/mcp/server.py index eee8f50a..ce8aade9 100644 --- a/src/langslice/doors/mcp/server.py +++ b/src/langslice/doors/mcp/server.py @@ -81,8 +81,7 @@ INSTRUCTIONS = ( "LangSlice places histology sections in a brain atlas. The job comes in the message " "that launched you; call `start_job` with its folder first: it opens the job and gives " - "you its tools. Read every show_stack page before writing. Work only through the " - "LangSlice tools and finish with `submit`." + "you its tools. Read every show_stack page before writing, and finish with `submit`." ) diff --git a/src/langslice/doors/reference_card.py b/src/langslice/doors/reference_card.py index efccbf1f..c3cb95b6 100644 --- a/src/langslice/doors/reference_card.py +++ b/src/langslice/doors/reference_card.py @@ -178,8 +178,9 @@ def card_text(layout: JobLayout) -> str: ## Python `import langslice; job = langslice.open_job("{layout.folder}")`; the verbs are methods -with the same arguments {example}; `help(job)` lists every one and the handle's own -methods, `help(langslice)` the rest of the library. Each returns, once its pictures are +with the tools' arguments and some only a script has {example}; `help(job)` lists every +one and the handle's own methods, `help(job.NAME)` one's arguments, `help(langslice)` +the rest of the library. Each returns, once its pictures are on disk, a JSON-safe dict: the tool's reply in full (status rows with every field, null where unset) plus `artifacts`, the files of its pictures; `reply.images` holds the pictures as PIL images. diff --git a/src/langslice/job/folder/layout.py b/src/langslice/job/folder/layout.py index ea8cc49f..b796cda3 100644 --- a/src/langslice/job/folder/layout.py +++ b/src/langslice/job/folder/layout.py @@ -37,6 +37,7 @@ env/ the job's own Python environment, made by `langslice job FOLDER env` (langslice.doors.commands.job.environment) + scripts/, scratch/ a coding agent's own scripts and other files AGENTS.md, CLAUDE.md the reference card for coding agents TOOLS.md every verb's description and arguments (by `launch`) @@ -74,6 +75,8 @@ VIEWS_INDEX = "views.jsonl" EXPORTS_DIR = "exports" LOGS_DIR = "logs" +SCRIPTS_DIR = "scripts" +SCRATCH_DIR = "scratch" EVENTS_FILE = "events.jsonl" LAUNCHES_DIR = "launches" TRACE_DIR = "trace" @@ -349,6 +352,16 @@ def views_index(self) -> Path: def exports_dir(self) -> Path: return self.folder / EXPORTS_DIR + @property + def scripts_dir(self) -> Path: + """Where a coding agent keeps the scripts it writes for the job.""" + return self.folder / SCRIPTS_DIR + + @property + def scratch_dir(self) -> Path: + """Where a coding agent keeps its other files for the job.""" + return self.folder / SCRATCH_DIR + @property def logs_dir(self) -> Path: return self.folder / LOGS_DIR @@ -471,6 +484,8 @@ def ensure(self) -> None: self.views_dir, self.exports_dir, self.logs_dir, + self.scripts_dir, + self.scratch_dir, ): folder.mkdir(parents=True, exist_ok=True) diff --git a/src/langslice/plugins/frames.py b/src/langslice/plugins/frames.py index a8de32a0..3d4b0dec 100644 --- a/src/langslice/plugins/frames.py +++ b/src/langslice/plugins/frames.py @@ -54,6 +54,14 @@ class FitFrame: ``inputs.section_image``); ``stain`` is the section's ``preprocessed`` image the same way (``stain=True`` is ``image="preprocessed"``), the picture the native fits read by default; each None unless asked for. + ``position_mm`` and ``angles`` ``(pitch_deg, yaw_deg)`` are the placement + the plane was cut at. ``applied_map`` is the applied deformation as a + ``(H, W, 2)`` map giving each ``image`` pixel's native atlas ``(x, y)``; + None without a deformation. ``damage_margin_mm`` is the margin that + widens ``excluded`` into ``damage_zone``. ``atlas_resolved`` maps each + atlas image name asked for to the image it was read as (``"nissl"`` to + ``template`` on an atlas whose template is a Nissl), and + ``atlas_image_note`` says so in words; None otherwise. """ id: str diff --git a/src/langslice/plugins/reads.py b/src/langslice/plugins/reads.py index a74cdd51..2eea9ec3 100644 --- a/src/langslice/plugins/reads.py +++ b/src/langslice/plugins/reads.py @@ -36,7 +36,9 @@ class AffineView: ``plugin:``...), the six normalized numbers ``[a, b, tx, c, d, ty]`` (``docs/reference/file_formats.md``), the knobs they are in (``rotation_deg``, ``scale_x``, ``scale_y``, ``shear``, ``translate_x_mm``, ``translate_y_mm``, - ``pivot``), and whether it mirrors the section.""" + ``pivot``), and whether it mirrors the section: ``kind``, ``matrix`` + (None when it holds no numbers), ``knobs`` (None when it was not made + from them) and ``mirrored``.""" kind: str | None matrix: tuple[float, ...] | None @@ -46,7 +48,39 @@ class AffineView: @dataclass(frozen=True) class SectionView: - """One section as the job holds it now.""" + """One section as the job holds it now (``ctx.reads.section``). + + Attributes + ---------- + id + The section's filename. + index + Its place in the stack's order, from 0. + file_size + The image file's ``(width, height)`` in pixels. + pixel_size_um + Micrometres per file pixel; None when the job knows none. + pixel_size_source + Where that size came from: ``host`` (given when the job was made), + ``file`` (the image file's own tags) or empty (none). + position_mm + Atlas millimetres along the slicing axis from the anterior edge. + angles + The section's cutting angles ``(pitch_deg, yaw_deg)``. + flip, rotation_deg + Its orientation: mirrored left-right, then turned 0, 90, 180 or 270. + affine + Its in-plane transform (:class:`AffineView`); None before it has one. + deformation + The applied deformation's ``key``, ``kind`` and ``steps``; None + without one. + damaged_regions, damage_note + The atlas regions ``mark_damage`` marked as lost, and its note. + layers + The names of the layers it shows. + frozen + The properties the job does not let anyone change on it. + """ id: str index: int @@ -67,6 +101,25 @@ class SectionView: @dataclass(frozen=True) class AtlasView: + """The job's atlas (``ctx.reads.atlas()``). + + Attributes + ---------- + name + The BrainGlobe atlas name, such as ``allen_mouse_25um``. + resolution_um + Micrometres per voxel along each of the atlas's axes. + orientation + BrainGlobe's three-letter axis order (``asr``: anterior to posterior, + superior to inferior, right to left). + species + The atlas's species. + plane + The cutting plane of the job's sections. + shape + The volume's shape in voxels, in the atlas's axis order. + """ + name: str resolution_um: tuple[float, ...] orientation: str @@ -87,7 +140,10 @@ class SectionRaster: :meth:`mask_to_section_px` turns a raster computed on ``array`` into one in the file's orientation (a raster covers the whole file whatever its size, so needs no scaling); ``Layer.labels(mask, frame="oriented")`` does that when - the layer is added. + the layer is added. ``rotation_deg`` and ``flip`` are the orientation + ``array`` was turned by. ``file_size`` is the file's ``(width, height)``, + ``pixel_size_um`` the micrometres of one file pixel (None when the job + knows none) and :attr:`um_per_px` those of one pixel of ``array``. """ id: str @@ -95,6 +151,14 @@ class SectionRaster: file_size: tuple[int, int] rotation_deg: int flip: bool + pixel_size_um: float | None = None + + @property + def um_per_px(self) -> float | None: + """Micrometres of one pixel of ``array``; None without a pixel size.""" + if self.pixel_size_um is None: + return None + return self.pixel_size_um * max(self.file_size) / max(self.array.shape[:2]) def _matrix(self) -> np.ndarray: """3x3: oriented edge fractions to file edge fractions.""" @@ -138,7 +202,12 @@ def unorient_raster(raster: np.ndarray, rotation_deg: int, flip: bool) -> np.nda @dataclass(frozen=True) class LayerRef: - """A layer registered on a section.""" + """A layer registered on a section: its ``id``, the ``section``'s + filename, its ``name`` (what ``look``'s ``layers`` takes), its ``kind`` + (``points``, ``lines``, ``labels``, ``scalar`` or ``picture``), the + ``frame`` its coordinates are in (``section_px``, ``atlas_um`` or + ``oriented``) and the ``file`` that holds it, relative to the job + folder.""" id: str section: str @@ -422,12 +491,14 @@ def section_raster( image = render_slice(workspace, record, long_edge=edge, look=look) except ValueError as exc: raise ToolError(RefusalCode.BAD_ARGUMENT, str(exc)) from exc + pixel_size, _source = workspace.calibration(record.id) return SectionRaster( id=record.id, array=np.asarray(image.convert("RGB")), file_size=render_sizes(workspace, record.id).file_size, rotation_deg=int(record.rotation_deg), flip=bool(record.flip), + pixel_size_um=None if pixel_size is None else float(pixel_size), ) def layers(self, section: object) -> list[LayerRef]: diff --git a/src/langslice/skills/placement/SKILL.md b/src/langslice/skills/placement/SKILL.md index cf6359ea..2b972308 100644 --- a/src/langslice/skills/placement/SKILL.md +++ b/src/langslice/skills/placement/SKILL.md @@ -12,8 +12,11 @@ correct a wrong plane. ## Positions -- **Keep the filename order** unless the anatomy clearly says otherwise. - Sections are usually named in cutting order. +- **Keep the order the filenames' section numbers give** unless the + anatomy clearly says otherwise. Sections are usually numbered in cutting + order; when a name holds several numbers (an image id, then `s0132`), + the section number is the one that steps along the stack, and it can run + backwards. - **Fit the positions to the file numbers.** Once each section has a first position (from `deepslice_place` or by eye), list each position beside the section number in its filename. Real stacks fall on one line: its slope is diff --git a/src/langslice/tools/arguments.py b/src/langslice/tools/arguments.py index 7735d3ab..d75ea3c8 100644 --- a/src/langslice/tools/arguments.py +++ b/src/langslice/tools/arguments.py @@ -27,13 +27,16 @@ import types import typing from collections.abc import Callable, Mapping -from typing import Any +from typing import TYPE_CHECKING, Any from pydantic import ConfigDict, with_config from typing_extensions import TypedDict, is_typeddict from langslice.core.refusal import RefusalCode, Refused +if TYPE_CHECKING: + from langslice.core.stack.stack import Stack + @with_config(ConfigDict(extra="forbid")) class SectionPosition(TypedDict, total=False): @@ -285,3 +288,18 @@ def check_value(name: str, annotation: Any, values: Any) -> None: problems=problems, message=f"{name}: {message} Nothing was done.", ) + + +def asked_angles(state: Stack, given: Mapping[str, Any] | None) -> tuple[float, float] | None: + """The plane a picture is asked for at: ``cutting_angles`` + (``pitch_deg``, ``yaw_deg``, either left out keeping the stack's own) as + ``(pitch_deg, yaw_deg)``; None when none is given.""" + if not given: + return None + pitch, yaw = state.view_angles + try: + return float(given.get("pitch_deg", pitch)), float(given.get("yaw_deg", yaw)) + except (TypeError, ValueError): + raise Refused( + RefusalCode.BAD_ARGUMENT, "cutting_angles takes numbers pitch_deg and yaw_deg." + ) from None diff --git a/src/langslice/tools/changing/positions.py b/src/langslice/tools/changing/positions.py index e4a6a805..c96fd4c1 100644 --- a/src/langslice/tools/changing/positions.py +++ b/src/langslice/tools/changing/positions.py @@ -267,12 +267,17 @@ def position_sections_tool( def _positioned_reply(done: SectionsPositioned, unknown: Refused | None) -> dict[str, Any]: - """Return the positions written, those clamped into the atlas range (with - the range), the unknown names, the order and the sections reordered. + """Return the positions written, the cutting angles written, those + clamped into the atlas range (with the range), the unknown names, the + order and the sections reordered. """ result: dict[str, Any] = { "written": [{"id": name, "position_mm": round(value, 3)} for name, value in done.written], } + if done.cutting_angles is not None: + result["cutting_angles_written"] = { + f"{name}_deg": round(float(value), 3) for name, value in done.cutting_angles.items() + } if done.clamped: result["clamped"] = [ { diff --git a/src/langslice/tools/changing/registrations.py b/src/langslice/tools/changing/registrations.py index a0cc7631..c6f8a873 100644 --- a/src/langslice/tools/changing/registrations.py +++ b/src/langslice/tools/changing/registrations.py @@ -21,7 +21,6 @@ from __future__ import annotations -import dataclasses from collections.abc import Mapping from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast @@ -97,11 +96,12 @@ def _elsewhere(state: Stack, section: Section, entry: Row) -> str | None: deformation = entry.deformation if deformation is None: return None - trial = dataclasses.replace( - section, - flip=entry.flip, - rotation_deg=entry.rotation_deg, - transform=entry.transform, + trial = section.model_copy( + update={ + "flip": entry.flip, + "rotation_deg": entry.rotation_deg, + "transform": entry.transform, + } ) if deformation.linear_key == linear_key(state, trial): return None diff --git a/src/langslice/tools/descriptions/changing.py b/src/langslice/tools/descriptions/changing.py index 05bbeff8..f7d13fe2 100644 --- a/src/langslice/tools/descriptions/changing.py +++ b/src/langslice/tools/descriptions/changing.py @@ -159,7 +159,10 @@ def _mask_section_image(on: ToolsOn) -> str: the size), "shear" (a slant applied before the rotation: each point moves sideways by shear times its distance below the pivot, in units of scale_x), "translate_x_mm" (right) and -"translate_y_mm" (down). A section appears once per call.""", +"translate_y_mm" (down). Each value moves the section on the +atlas, which keeps its place in the picture: a larger scale draws the +section larger, so the atlas borders sit smaller on it. A section +appears once per call.""", ), "view": Argument( bool, diff --git a/src/langslice/tools/descriptions/door_text.py b/src/langslice/tools/descriptions/door_text.py index 2fddf991..2d7f5471 100644 --- a/src/langslice/tools/descriptions/door_text.py +++ b/src/langslice/tools/descriptions/door_text.py @@ -31,21 +31,27 @@ "Opening pictures: read every page with show_stack(page=1) through " "show_stack(page={pages}) before any write. " ) +OPENING_PAGE = "Opening pictures: read show_stack(page=1) before any write. " SCRIPTS = "Scripts:" SCRIPT_PYTHON = ( - "- You also have a shell and file tools, for what no tool does: write a " - 'script and run it as `"{python}" SCRIPT [ARGS ...]`. That is the job\'s ' - "own Python: it imports LangSlice and every package LangSlice is " - "installed with; `{install} PACKAGE [PACKAGE ...]` adds another." + "- You also have a shell and file tools, and you are not limited to " + "LangSlice's tools: use whatever you judge best for this brain, from your " + "own code to any package or published method, beside the tools or in " + 'place of one. Run a script as `"{python}" SCRIPT [ARGS ...]`. That is ' + "the job's own Python: it imports LangSlice and every package LangSlice " + "is installed with; `{install} PACKAGE [PACKAGE ...]` adds another." ) SCRIPT_LIBRARY = ( '- In a script, `langslice.open_job(r"{folder}")` opens this job: every ' - "tool is a method of it with the same arguments (`help(job)` lists them " - "all), without the tools' " + "tool is a method of it (`help(job)` lists them all; `help(job.look)` " + "gives one's arguments, which can be more than the tool's: look's " + "`resolution` and `sheet`), without the tools' " "limit on pictures or sections per call, and `job.context` holds the " "parts for a method of your own (`help(job.context)`: the section " "images and the atlas as arrays, a transform or a deformation of your " - "own, a preview that writes nothing, a section image you computed)." + "own, a preview that writes nothing, a section image you computed). " + "What you compute counts once it is written into the job this way or " + "through a tool." ) SCRIPT_SHARED = ( "- The tools and your scripts work on the one job: each sees what the " @@ -206,7 +212,8 @@ def opening_for_mcp(pages: int) -> list[str]: list of str The paragraph, as statement lines. """ - return [OPENING_PAGES.format(pages=pages) + OPENING_SHOWS] + first = OPENING_PAGE if pages == 1 else OPENING_PAGES.format(pages=pages) + return [first + OPENING_SHOWS] def review_lines(layout: JobLayout, state: Stack, switched_off: Collection[str]) -> list[str]: diff --git a/src/langslice/tools/descriptions/looking.py b/src/langslice/tools/descriptions/looking.py index 0e3b2b1a..b4306595 100644 --- a/src/langslice/tools/descriptions/looking.py +++ b/src/langslice/tools/descriptions/looking.py @@ -11,7 +11,7 @@ from langslice.core.atlas.levels import OVERLAY_DEPTH from langslice.core.sections import images from langslice.job.settings.tools_on import ToolsOn -from langslice.tools.arguments import PicturePoint +from langslice.tools.arguments import CuttingAngles, PicturePoint from langslice.tools.descriptions.description import ( REQUIRED, Argument, @@ -299,6 +299,15 @@ def _review_returns(on: ToolsOn) -> str: _look_sheet, offered=Offered.UNCAPPED, ), + "cutting_angles": Argument( + CuttingAngles, + {}, + """{"pitch_deg": , "yaw_deg": }: draw the +atlas planes at these cutting angles instead of the stack's, to compare +a section with planes at other angles before writing any; either left +out keeps the stack's. Writes nothing. Atlas mode with +positions_mm only: a section's own picture is at its own plane.""", + ), }, returns="${pictures}", slots={ @@ -518,7 +527,8 @@ def _review_returns(on: ToolsOn) -> str: body=( """\ Only the named regions' borders are drawn, at the stack's cutting -angles. Look highlights no regions; this tool does.""", +angles or the cutting_angles given. Look highlights no regions; this +tool does.""", _grep_atlas_view_compare, ), arguments={ @@ -536,6 +546,14 @@ def _review_returns(on: ToolsOn) -> str: Atlas positions in millimetres along the slicing axis; a position outside the atlas is clamped into its range.""", ), + "cutting_angles": Argument( + CuttingAngles, + {}, + """{"pitch_deg": , "yaw_deg": }: draw the +atlas planes at these cutting angles instead of the stack's, to compare +a section with planes at other angles before writing any; either left +out keeps the stack's. Writes nothing.""", + ), }, returns="""\ ${pictures}, and per position diff --git a/src/langslice/tools/descriptions/run_facts.py b/src/langslice/tools/descriptions/run_facts.py index bf62c1c2..433841d6 100644 --- a/src/langslice/tools/descriptions/run_facts.py +++ b/src/langslice/tools/descriptions/run_facts.py @@ -61,6 +61,10 @@ "are missing." ) STACK_ANGLES = "- Stack-wide cutting angles: pitch {pitch:.2f} deg, yaw {yaw:.2f} deg." +STARTING_ANGLES = ( + "- Stack-wide cutting angles as set now: pitch {pitch:.2f} deg, yaw {yaw:.2f} deg; " + "a starting setting, not a measurement of this brain." +) def mixed_angles(on: ToolsOn) -> str: @@ -197,7 +201,7 @@ def run_facts( RANGE.format(axis=axis, low=low, high=high), AXIS_ENDS.format(low=low, low_end=axis_ends[0], high_end=axis_ends[1]), _protocol_fact(state), - _angles_fact(state, spec.tools_on), + _angles_fact(state, spec.tools_on, supplied=bool(spec.inputs.get("angles"))), *_section_facts(spec, state), *_change_facts(spec), ] @@ -219,11 +223,14 @@ def _protocol_fact(state: Stack) -> str: return PROTOCOL.format(interval=interval, thickness=thickness) + tail -def _angles_fact(state: Stack, on: ToolsOn) -> str: +def _angles_fact(state: Stack, on: ToolsOn, *, supplied: bool) -> str: + """The statement's line on the cutting angles: supplied ones as a fact, + the job's own setting as a starting point.""" if state.mixed_angles: return mixed_angles(on) pitch, yaw = state.stack_angles - return STACK_ANGLES.format(pitch=pitch, yaw=yaw) + words = STACK_ANGLES if supplied else STARTING_ANGLES + return words.format(pitch=pitch, yaw=yaw) def _section_facts(spec: JobSpec, state: Stack) -> list[str]: diff --git a/src/langslice/tools/fitting/affine_fit.py b/src/langslice/tools/fitting/affine_fit.py index 1cd9a454..746b25bb 100644 --- a/src/langslice/tools/fitting/affine_fit.py +++ b/src/langslice/tools/fitting/affine_fit.py @@ -121,13 +121,17 @@ def _turn_deg(previous: StoredAffine | None, fit: FittedAffine) -> float: SCALE_CHANGE_LIMITS = (0.8, 1.25) SHEAR_CHANGE_LIMIT = 0.15 +ANISOTROPY_LIMIT = 1.25 def plausibility_flags(previous: StoredAffine | None, fit: FittedAffine) -> list[dict[str, Any]]: """An affine fit's implausible changes from the section's *previous* transform (none: the identity), as the deformable fits' flags are given: - ``SCALE_CHANGED`` (``scale``, ``previous``, ``limits`` per axis ratio) and - ``SHEAR`` (``shear``, ``previous``, ``limit`` on the change).""" + ``SCALE_CHANGED`` (``scale``, ``previous``, ``limits`` per axis ratio), + ``SHEAR`` (``shear``, ``previous``, ``limit`` on the change) and + ``ANISOTROPIC`` (``scale``, ``limit``: one axis scaled more than + :data:`ANISOTROPY_LIMIT` times the other, a fit that collapsed onto the + wrong anatomy more often than a section squashed in cutting).""" before = physical_knobs(previous) after = fit.physical scale = [float(value or 1.0) for value in (after.scale_x, after.scale_y)] @@ -143,6 +147,14 @@ def plausibility_flags(previous: StoredAffine | None, fit: FittedAffine) -> list "limits": [low, high], } ) + if min(scale) > 0 and max(scale) / min(scale) > ANISOTROPY_LIMIT: + flags.append( + { + "code": FitFlag.ANISOTROPIC, + "scale": [round(v, 3) for v in scale], + "limit": ANISOTROPY_LIMIT, + } + ) shear, was = float(after.shear or 0.0), float(before.shear or 0.0) if abs(shear - was) > SHEAR_CHANGE_LIMIT: flags.append( @@ -573,6 +585,13 @@ def affine_flag_text(flag: Mapping[str, Any]) -> str: "stretched the section over atlas it does not hold. Compare its " "picture with the previous one." ) + if flag.get("code") == FitFlag.ANISOTROPIC: + return ( + f"ANISOTROPIC: this fit scales the section by {flag.get('scale')}, one " + f"axis more than {flag.get('limit')} times the other; a section is " + "rarely squashed that much, so the fit may have collapsed onto the " + "wrong anatomy. Look at its picture, and undo it if so." + ) if flag.get("code") == FitFlag.SHEAR: return ( f"SHEAR: this fit shears the section by {flag.get('shear')} (it " diff --git a/src/langslice/tools/looking/atlas.py b/src/langslice/tools/looking/atlas.py index 031512c4..3d8fbfd1 100644 --- a/src/langslice/tools/looking/atlas.py +++ b/src/langslice/tools/looking/atlas.py @@ -44,7 +44,7 @@ from langslice.core.refusal import RefusalCode, Refused from langslice.core.stack.section import Angles from langslice.core.stack.stack import Stack -from langslice.tools.arguments import PicturePoint +from langslice.tools.arguments import PicturePoint, asked_angles from langslice.tools.looking.look import not_shown, save_pictures, split_shown from langslice.tools.refusal import named_section from langslice.tools.run import as_list @@ -513,7 +513,10 @@ def redraw_regions( def grep_atlas_view_tool( - run: Run, regions: list[str], positions_mm: list[float] + run: Run, + regions: list[str], + positions_mm: list[float], + cutting_angles: Mapping[str, Any] | None = None, ) -> dict[str, object]: """Draw the atlas with only named regions' borders; return the reply. @@ -521,7 +524,7 @@ def grep_atlas_view_tool( ---------- run The run the tool is called in. - regions, positions_mm + regions, positions_mm, cutting_angles The declared arguments as the model sent them (``tools/descriptions/looking.py``). @@ -531,7 +534,13 @@ def grep_atlas_view_tool( The regions drawn, the ones absent from each plane, the positions moved into the atlas range, and the pictures with their numbers. """ - done = draw_regions(run.job, run.workspace, as_list(regions), as_list(positions_mm)) + done = draw_regions( + run.job, + run.workspace, + as_list(regions), + as_list(positions_mm), + asked_angles(run.job.state, cutting_angles), + ) reply: dict[str, object] = {"status": "ok", "regions": done.regions} if done.regions_not_in_plane: reply["regions_not_in_plane"] = done.regions_not_in_plane @@ -551,10 +560,11 @@ def draw_regions( workspace: Workspace, regions: Sequence[str], positions_mm: Sequence[float], + angles: tuple[float, float] | None = None, ) -> RegionsView: """The atlas template at each of *positions_mm* (clamped into the atlas - range), at the stack's cutting angles (``Stack.view_angles``), with - only the borders of *regions* drawn. + range), at *angles* ``(pitch_deg, yaw_deg)`` (None: the stack's cutting + angles, ``Stack.view_angles``), with only the borders of *regions* drawn. A region may name a side (``"CTX:left"``, as the section is displayed). Each picture is saved like a ``look`` picture (recipe, caption, number), @@ -576,7 +586,7 @@ def draw_regions( raise Refused(RefusalCode.BAD_ARGUMENT, message="Give at least one position.") low, high = workspace.position_range used = [min(max(v, low), high) for v in asked] - angles = state.view_angles + angles = angles if angles is not None else state.view_angles edge = picture_edge(workspace) with collecting() as notes: drawn = [_region_picture(workspace, state, resolved, mm, edge, angles) for mm in used] diff --git a/src/langslice/tools/looking/look.py b/src/langslice/tools/looking/look.py index 322ad9e8..df1631b7 100644 --- a/src/langslice/tools/looking/look.py +++ b/src/langslice/tools/looking/look.py @@ -40,6 +40,7 @@ ) from langslice.core.refusal import RefusalCode, Refused from langslice.job.pictures import has_frame, view_number +from langslice.tools.arguments import asked_angles from langslice.tools.refusal import named_sections from langslice.tools.run import as_list, pictured @@ -173,6 +174,7 @@ def look_tool( masks: list[str] | None = None, registrations: dict[str, int] | None = None, sheet: bool = False, + cutting_angles: Mapping[str, Any] | None = None, ) -> dict[str, object]: """Draw and save the pictures of one ``look`` call; return its reply. @@ -183,7 +185,7 @@ def look_tool( mode, sections, images, positions_mm, atlas_layers, atlas_opacity, warp The declared arguments as the model sent them (``tools/descriptions/looking.py``). - resolution, layers, depth, masks, registrations, sheet + resolution, layers, depth, masks, registrations, sheet, cutting_angles More of the declared arguments, as sent. Returns @@ -206,6 +208,7 @@ def look_tool( layers=tuple(as_list(layers)), depth=depth, masks=tuple(as_list(masks)), + cutting_angles=asked_angles(run.job.state, cutting_angles), ) edge, note = requested_edge(run, request.long_edge) sheet_edge = int(run.box.max_view_edge) if sheet else None @@ -366,6 +369,7 @@ def look_pictures( masks=mask_names, depth=depth, registrations=shown_under, + cutting_angles=request.cutting_angles, ) with collecting() as notes: drawn = looks.look(workspace, state, request, store=job.deformations) diff --git a/tests/test_script_findings.py b/tests/test_script_findings.py new file mode 100644 index 00000000..ac735ff3 --- /dev/null +++ b/tests/test_script_findings.py @@ -0,0 +1,188 @@ +"""What an agent scripting a real brain stumbled on stays fixed. + +Each test holds one thing a Fable agent registering a Carey brain with +scripts on reported: a crash drawing a section under an earlier +registration, a stored shape copied as a dataclass, objects whose fields +were undocumented, files it was told to keep in folders that did not exist, +a reply that hid the cutting angles it wrote, and wording that misled it. +""" + +from __future__ import annotations + +import ast +import dataclasses +import inspect +from pathlib import Path + +import numpy as np + +import langslice +from langslice.core.stack.part import Shape +from langslice.plugins.frames import AtlasPlane, FitFrame +from langslice.plugins.reads import AffineView, AtlasView, LayerRef, SectionRaster, SectionView +from langslice.tools.descriptions.door_text import opening_for_mcp +from tests.synthetic_job import PIXEL_SIZE_UM, POSITIONS + +SOURCE = Path(__file__).resolve().parents[1] / "src" / "langslice" +VENDORED = SOURCE / "_vendor" +RETURNED_TO_SCRIPTS = (SectionView, AtlasView, AffineView, LayerRef, SectionRaster, FitFrame) +COPY_CALLS = {"replace", "dataclasses.replace"} + + +def shape_names() -> set[str]: + found: set[str] = set() + pending: list[type] = [Shape] + while pending: + cls = pending.pop() + for sub in cls.__subclasses__(): + found.add(sub.__name__) + pending.append(sub) + return found + + +def call_name(node: ast.Call) -> str: + return ast.unparse(node.func) + + +def shape_copies(path: Path, shapes: set[str]) -> list[str]: + tree = ast.parse(path.read_text(encoding="utf-8")) + found: list[str] = [] + for function in ast.walk(tree): + if not isinstance(function, ast.FunctionDef | ast.AsyncFunctionDef): + continue + typed = { + arg.arg: ast.unparse(arg.annotation) + for arg in [*function.args.args, *function.args.kwonlyargs] + if arg.annotation is not None + } + for node in ast.walk(function): + if ( + isinstance(node, ast.Call) + and call_name(node) in COPY_CALLS + and node.args + and isinstance(node.args[0], ast.Name) + and typed.get(node.args[0].id, "").strip("'\"") in shapes + ): + found.append(f"{path.relative_to(SOURCE).as_posix()}:{node.lineno}") + return found + + +def test_no_stored_shape_is_copied_as_a_dataclass() -> None: + shapes = shape_names() + found = [ + where + for path in sorted(SOURCE.rglob("*.py")) + if VENDORED not in path.parents + for where in shape_copies(path, shapes) + ] + assert not found, ( + "A stored shape is a Pydantic model: copy it with model_copy(update=...), " + "not dataclasses.replace:\n" + "\n".join(found) + ) + + +def test_every_object_a_script_gets_back_documents_its_fields() -> None: + missing = [ + f"{cls.__name__}.{field.name}" + for cls in (*RETURNED_TO_SCRIPTS, AtlasPlane) + for field in dataclasses.fields(cls) + if field.name not in (inspect.getdoc(cls) or "") + ] + assert not missing, "Say what each field holds in its class docstring:\n" + "\n".join(missing) + + +def test_one_opening_page_is_not_a_range() -> None: + assert "through" not in " ".join(opening_for_mcp(1)) + assert "page=3" in " ".join(opening_for_mcp(3)) + + +def identity_map(frame: object) -> np.ndarray: + placed = frame.placed_atlas_to_section + assert placed is not None + height, width = frame.image.shape[:2] + cols, rows = np.meshgrid(np.arange(width, dtype=float), np.arange(height, dtype=float)) + points = np.stack([cols, rows, np.ones_like(cols)], axis=-1) + native = points @ np.linalg.inv(placed).T + return native[..., :2].astype(np.float32) + + +def test_a_script_sees_a_section_under_an_earlier_deformed_registration(images: Path) -> None: + with langslice.create_job( + images, + positions=POSITIONS, + pixel_size_um=PIXEL_SIZE_UM, + preprocess="none", + tasks=["transform", "nonlinear"], + ) as job: + assert Path(job.folder, "scripts").is_dir() + assert Path(job.folder, "scratch").is_dir() + section = next(iter(POSITIONS)) + fitted = job.elastix_affine(sections=[section]) + assert fitted["status"] == "ok", fitted + context = job.context + raster = context.reads.section_raster(section) + assert raster.um_per_px is not None + frame = context.frames.fit_frame(section) + warped = context.writes.set_deformations( + [{"id": section, "map": identity_map(frame), "note": "identity"}] + ) + assert section in warped.written, warped + held = job.status()["rows"][0]["registration"] + undone = job.undo() + assert undone["status"] == "ok", undone + looked = job.look(mode="overlay", sections=[section], registrations={section: held}) + assert looked["status"] == "ok", looked + + +def test_writing_only_cutting_angles_says_so(images: Path) -> None: + with langslice.create_job( + images, pixel_size_um=PIXEL_SIZE_UM, preprocess="none", tasks=["position"] + ) as job: + reply = job.position_sections(cutting_angles={"pitch_deg": 1.0, "yaw_deg": 0.0}, view=False) + assert reply["status"] == "ok", reply + assert reply["cutting_angles_written"]["pitch_deg"] == 1.0, reply + + +def test_atlas_pictures_take_cutting_angles_and_write_none(images: Path) -> None: + with langslice.create_job( + images, positions=POSITIONS, pixel_size_um=PIXEL_SIZE_UM, preprocess="none" + ) as job: + before = job.status()["cutting_angles_deg"] + tilted = {"pitch_deg": 4.0, "yaw_deg": -3.0} + looked = job.look(mode="atlas", positions_mm=[0.15], cutting_angles=tilted) + regions = job.grep_atlas_view(regions=["root"], positions_mm=[0.15], cutting_angles=tilted) + refused = job.look(mode="overlay", cutting_angles=tilted) + after = job.status()["cutting_angles_deg"] + assert looked["status"] == "ok", looked + assert "yaw -3" in looked["pictures"][0]["caption"], looked["pictures"][0]["caption"] + assert regions["status"] == "ok", regions + assert refused["status"] == "error", refused + assert before == after + + +def test_a_collapsed_affine_fit_is_flagged() -> None: + from types import SimpleNamespace + + from langslice.core.fits.flags import FitFlag + from langslice.tools.fitting.affine_fit import plausibility_flags + + squashed = SimpleNamespace( + physical=SimpleNamespace(scale_x=1.068, scale_y=1.375, shear=0.0, rotation_deg=0.0) + ) + codes = {flag["code"] for flag in plausibility_flags(None, squashed)} + assert FitFlag.ANISOTROPIC in codes + + +def test_a_scripting_agent_is_told_it_may_use_any_method() -> None: + from langslice.doors.mcp.server import INSTRUCTIONS + from langslice.tools.descriptions.door_text import SCRIPTING + + connectors = Path(__file__).resolve().parents[1] / "connectors" + agents = [ + connectors / "claude-code" / "agents" / "register-scripting.md", + connectors / "antigravity" / "agents" / "register-scripting.md", + connectors / "codex" / "agents" / "register_scripting.toml", + ] + assert "not limited to LangSlice's tools" in SCRIPTING + assert "only" not in INSTRUCTIONS + assert all("any software you judge best" in path.read_text(encoding="utf-8") for path in agents)