diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d7d766e..0d076c8b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,120 @@ inventory's, not the Stage 2 MC-1/MC-2 of the experiment description. ### Fixed +- **#514.** The benchmark's fixed-block contrast engine (`candidates/fixed_block.py`) refuses + weights that are not a contrast (`check_weights`: finite real numbers, at least two not 0, + summing to 0) in `regime`, `graph_estimable`, `Layout.contrast`, `fit_model` and + `contrast`: `{"A": 1.0}` was tested as A's mean by the direct test and as A minus the + baseline by the model. Zero-sum weights, rescaled or not, are unchanged. +- **#519.** The benchmark's exact sign-flip tests (`candidates/hd_tests.py`: `sign_flip_u`, + `shrinkage_hotelling`) refuse more than 16 repeats (`MAX_EXACT_REPEATS`) instead of + building all 2**n sign assignments in memory (n = 25 needed more than 800 MB for the signs + alone). Up to 16 repeats, and the benchmark's 3-6, they are enumerated as before. +- **#524.** The benchmark's `semi_synthetic` (`data/simulations/decisions/embedding.py`) + refuses a repeat of fewer than 2 fields (it got no treated field), a shift asked of values + that do not vary (it gave a zero shift), values that are not finite and values and + metadata of different lengths; a draw of two rows that cancel is drawn again instead of + giving a zero direction. Draws that do not cancel are unchanged. +- **#520.** The benchmark's `colab.run` stops with an error when P0 (the deterministic tests) + fails, naming its report, instead of discarding pytest's exit code and running P1-P5 as if + the gate had passed. +- **#569.** `data/crick_idr/jcs_effect_fovs.py` judges two IQR bands as overlapping only when + they intersect (`bands_overlap`, endpoints included), whichever is higher: a band wholly + below the other read as overlapping. Inverted or missing quartiles are refused. The + committed `results/jcs_effect_fovs_pairs.csv` is unchanged (all 400 rows agree). +- **#574.** The glioma dataset card (`data/lab/cct7_cct8_glioma_cdm_tracks/card.toml`) no + longer says that `Unique_ID` and `File_name` are checked by `convert.py`: the converter + never reads them, so the card now says they are not checked; `experiment_nb` is checked + against `Repeat`, as before. Their format was not reconstructed (the owner's source is not + in the repository); the stored tables are unchanged. +- **#640 (part).** The workflows example notebook pairs the positive control's fields by + `repeat_group` (`pair_cols=("repeat_group",)`), not by the folder label + `biological_repeat`, and stops with what to add when the FOV table has no `repeat_group`. + Run on the bundled idr0028 example, the report assesses the positive control. The + notebook's analysis groups are unchanged (the workflows already read each folder label as + its repeat group). +- **#576.** The lab converters read the source's `Repeat`, the glioma `TRACK_ID` and the + filopodia count through `convert_tools.whole_numbers`, which stops, naming the source + rows, unless every value is a finite whole number of at least 1 (repeats) or 0 (track IDs, + counts): `astype(int)` truncated a repeat of 1.8 to 1 and a count of 5.9 to 5. The stored + tables hold only such values (repeats 1-3, track IDs from 1, counts from 7). +- **#577.** The lab converters hash a downloaded source archive in chunks + (`hashlib.file_digest`) instead of reading it whole into memory (381 MB for CCT8 CDM + morphology); the md5 and the member's sha256 are checked as before. +- **#583.** The reference check (`data/reference/reference.py`) refuses a job whose kind is + not one it runs or whose name is not one plain word (a separator, `.` or `..`), and a job + listed twice, before anything runs; the owner's job names are checked the same way, and + `run_job` refuses a target outside `OUT` before removing it. A job list could make it + remove a folder outside `OUT` (`../.. victim`). +- **#591.** The benchmark's Colab notebook (`data/simulations/decisions/benchmark_colab.ipynb`) + no longer puts the GitHub token in the clone URL, where it was in the command, in the + clone's `.git/config` and in the error of a failed clone: git reads it through a + `GIT_ASKPASS` helper from the clone's environment, the remote is checked to be the + token-free URL, and a failed clone raises with git's message (token masked), not the + command. A clone made by the earlier cell keeps the token in + `/content/MorphoCoverage/.git/config` until that Colab session ends. +- **#547.** `BenchmarkRecord.as_row` (and so `records_to_frame`) exports each outcome + metric's config id as `outcome_id.` beside `outcome.`: two metrics given the + same label (`RelativeMeanError("feature_a", label="readout_error")` and the same for + `feature_b`) could not be told apart once exported. The existing columns are unchanged. +- **#449.** The detection-adjusted unseen-state bound names each group by reading its rows by + column name: a group column that is not a Python identifier (`"plate id"`, `"class"`) + raised `AttributeError`, since `itertuples` renames it, whenever an adjusted bound was + available. The bound and its wording are unchanged. +- **#448.** The guided session asks again, instead of keeping only the last condition, when + treatment keys entered for one control repeat or are empty, and when a condition given a + control later finds both its proposed key and its own name taken under that control (the + condition holding the key was overwritten). Every condition assigned to a control is kept. +- **#430.** `plan_objects_to_average` refuses `sample_cols` under which one sample holds + both control and other cells, naming the samples: each was centred on its own mean, so the + treatment's shift entered the within-sample SD (a plan of 107 cells instead of 1 in the + issue's example). Add the column that tells them apart, such as the condition. +- **#581.** A `FrozenDict` or `FrozenList` built by its constructor now freezes what it is + given, so `freeze`, which returns such a container unchanged, no longer keeps a caller's + inner list or dict that could still change a snapshot. Pickling, copying and `freeze` of + plain containers behave as before. +- **#551.** `document` compares the parts' Setups field by field with a contrast table + compared by its values (`DataFrame.equals`): a Setup declared with `contrasts=` raised + "the truth value of a DataFrame is ambiguous" even against itself. Different contrast + tables are still refused as different Setups. +- **#532.** The descriptor-spread resample helpers (`strategies._descriptor_resamples`) + refuse with a `ValueError` what they cannot resample: no value (a `ZeroDivisionError` + before), no FOV, no resample, or positions that are not one FOV of `k` per value. Their + caller, `DescriptorSpreadEstimator`, already reports these cases as not yet possible, so + no result changes. +- **#485.** A complex column of another feature table is refused by `attach_feature_tables` + ("has complex columns"), before any float cast dropped its imaginary part: an infinity in + the imaginary part went unseen and a varying one was listed as constant. Nullable real + columns are read as before. +- **#495.** `ColumnWeights` refuses booleans and text as weights (`True` became 1.0 and + `"2.0"` 2.0 through `float`); `BlockWeights` refuses an `inertia_radius` that is not a + boolean (the text `"False"` turned the radius correction on while its provenance said + `"False"`) and block feature names that are not non-empty text (they were recast with + `str`). Valid settings give the same results. +- **#491.** `whole_table_tests` refuses `permutations` that is not an integer of at least 1 + (0 drew no shuffle and still gave `p_shuffle = 1.0`; negative, fractional, boolean and + text values were not checked) and a `random_state` that is not a non-negative integer. +- **#528.** `repeat_effect` refuses a `level` outside (0, 1) (1 gave an infinite interval, a + negative level an invalid quantile) and an infinite per-repeat contrast (it gave NaN bounds + after runtime warnings). A missing contrast still gives no interval (NaN), as documented. +- **#538.** Stage coordinates a float cannot hold are refused with the contract's + `ValueError`: a Python integer too large for a float (it raised a bare `OverflowError`) as + not finite, and an integer beyond 2**53 that a float would round (`2**53` and `2**53 + 1` + became one position) as not held exactly, in `stage_matrix` and `check_xy` alike. Nothing + is rounded or rescaled. +- **#544.** Imaged areas that are each finite but whose total overflows a float (two fields + of `1e308`) are now a problem of `_areas.area_problem`: `ImagedAreaEstimator` reports the + area `not_applicable` with that reason, so `FixedAreaStrategy` no longer stops on an + infinite total, and a benchmark refuses the dataset instead of recording an infinite + `area`/`total_area`. +- **#418.** `robust_sd(values, "geometry")` of a 1-D sample of one value returns 0 (no + spread) instead of raising `IndexError`: `constant_columns` sized its zero SD by a second + axis that a 1-D sample does not have. +- **#578.** The glossary's "Sign-flip test" no longer calls it "the exact test on the signs": + it is a two-sided paired permutation test on the mean of the per-repeat differences, each + difference keeping its magnitude while its sign is flipped, exact up to 16 repeats and + Monte Carlo (20,000 assignments) above, as `sign_flip_test` computes it. The source is + `glossary.py`; `docs/common/glossary.md` is re-rendered from it. The test is unchanged. - **#90 (part).** A paired test across repeats that gives no p because 3 or more repeats all give the same change is now "not assessed across repeats" (`reading_text.NOT_ASSESSED`), never "not significant": in the reading, the summary, and the page's table across repeats, diff --git a/data/crick_idr/jcs_effect_fovs.py b/data/crick_idr/jcs_effect_fovs.py index 35c96d2b..da4c3a0f 100644 --- a/data/crick_idr/jcs_effect_fovs.py +++ b/data/crick_idr/jcs_effect_fovs.py @@ -134,6 +134,16 @@ def full_wells(name: str) -> dict[str, float]: return {c: jcs_effect_size(np.concatenate(f), ctrl) for c, f in treated.items()} +def bands_overlap(a: tuple[float, float], b: tuple[float, float]) -> bool: + """Whether two IQR bands ``(q25, q75)`` share a point, endpoints included, whichever is + higher: a band wholly below the other does not overlap it (#569). A band with a missing + or inverted quartile is refused.""" + for band in (a, b): + if not band[0] <= band[1]: + raise ValueError(f"an IQR band needs q25 <= q75, not {band}") + return bool(max(a[0], b[0]) <= min(a[1], b[1])) + + def compare(table: pd.DataFrame, name: str) -> pd.DataFrame: """For each compared pair: band overlap, and how often a sample ranks them as the wells do.""" _, _, _, pairs, _ = PAPER[name] @@ -150,7 +160,7 @@ def compare(table: pd.DataFrame, name: str) -> pd.DataFrame: "n_objects": n, "pair": f"{high} > {low}", "full_well_difference": reference[high] - reference[low], - "bands_overlap": bool(a.q25 <= b.q75), + "bands_overlap": bands_overlap((a.q25, a.q75), (b.q25, b.q75)), # draws are independent, so compare every pair of draws "share_ranked_as_full_wells": float( np.mean(a["values"][:, None] > b["values"][None, :]) diff --git a/data/lab/cct7_cct8_glioma_cdm_tracks/card.toml b/data/lab/cct7_cct8_glioma_cdm_tracks/card.toml index 787176ce..3c03ec75 100644 --- a/data/lab/cct7_cct8_glioma_cdm_tracks/card.toml +++ b/data/lab/cct7_cct8_glioma_cdm_tracks/card.toml @@ -89,7 +89,7 @@ duplicated_tracks = 28 [columns] renamed = { Condition = "condition (siCTRL_CCT7 and siCTRL_CCT8 written siCTRL) and source_condition (verbatim)", Repeat = "biological_repeat (as '_')", TRACK_ID = "label_id", File_name_raw = "source_file, and technical_repeat + position_id parsed from it" } -dropped = ["Unique_ID, File_name and experiment_nb: each is a concatenation of kept columns (checked by convert.py)"] +dropped = ["Unique_ID and File_name: source identifiers, not checked by convert.py, which does not read them, so a disagreement with Condition, Repeat, TRACK_ID or File_name_raw would not be found", "experiment_nb: 'R' followed by Repeat (checked by convert.py)"] added = ["target (the gene the siRNA silences; non-targeting for siCTRL)", "experiment (from the siRNA label)", "image_file (unrecorded)", "source_row (file line, 1 = header)"] features = { "Mean Speed" = "mean instantaneous speed along the track (px per 10 min)", "Directionality" = "net displacement / path length (1 = straight)", "Tortuosity" = "path length / net displacement", "Total Distance Traveled" = "path length (px)", "Spatial Coverage" = "area explored by the track (px^2)", "Total Turning Angle" = "sum of turning angles (degrees)", "Rolling" = "the same metric on a rolling window along the track (CellTracksColab)" } diff --git a/data/lab/cct7_cct8_glioma_cdm_tracks/convert.py b/data/lab/cct7_cct8_glioma_cdm_tracks/convert.py index 426d5f68..1636be1c 100644 --- a/data/lab/cct7_cct8_glioma_cdm_tracks/convert.py +++ b/data/lab/cct7_cct8_glioma_cdm_tracks/convert.py @@ -26,7 +26,13 @@ HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE.parent)) # The shared helpers live one folder up. -from convert_tools import check_columns, check_member, sirna_target, write_csv_gz +from convert_tools import ( + check_columns, + check_member, + sirna_target, + whole_numbers, + write_csv_gz, +) MEMBER = "Tracking_data_CCT8_CCT7_silencing_Glioma.csv" MEMBER_SHA256 = "dec991b3fdd52956d01ee64c2348ee4ec64afe4f16b7d0f67c549350b064233e" @@ -92,12 +98,12 @@ def build_tables(source: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: { "experiment": experiment, "condition": source["Condition"].where(~control, "siCTRL"), - "biological_repeat": experiment + "_" + source["Repeat"].astype(int).astype(str), + "biological_repeat": experiment + "_" + whole_numbers(source, "Repeat", 1).astype(str), "technical_repeat": names["well"], "position_id": names["well"] + "_" + names["position"], "image_file": UNRECORDED, "target": source["Condition"].where(~control, "siCTRL").map(sirna_target), - "label_id": source["TRACK_ID"].astype(int), + "label_id": whole_numbers(source, "TRACK_ID", 0), **{metric: source[metric] for metric in METRICS}, "source_condition": source["Condition"], "source_file": source["File_name_raw"], diff --git a/data/lab/cct8_cdm_morphology/convert.py b/data/lab/cct8_cdm_morphology/convert.py index baee6f82..621e4d58 100644 --- a/data/lab/cct8_cdm_morphology/convert.py +++ b/data/lab/cct8_cdm_morphology/convert.py @@ -34,6 +34,7 @@ fetch_zip_member, sirna_target, synthetic_positions, + whole_numbers, write_csv_gz, ) @@ -83,7 +84,7 @@ def build_tables(source: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: """ table = source.rename(columns={"Condition": "condition", **RENAMED}) table["condition"] = table["condition"].astype(str) - table["biological_repeat"] = source["Repeat"].astype(int).astype(str) + table["biological_repeat"] = whole_numbers(source, "Repeat", 1).astype(str) table["technical_repeat"] = SINGLE table["image_file"] = UNRECORDED table["label_id"] = 1 diff --git a/data/lab/cct8_filopodia_screen/convert.py b/data/lab/cct8_filopodia_screen/convert.py index 12b8605a..1b56a9f9 100644 --- a/data/lab/cct8_filopodia_screen/convert.py +++ b/data/lab/cct8_filopodia_screen/convert.py @@ -35,6 +35,7 @@ fetch_zip_member, sirna_target, synthetic_positions, + whole_numbers, write_csv_gz, ) @@ -82,11 +83,11 @@ def build_tables(source: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]: "condition": source["Condition"].astype(str), "biological_repeat": source["dataset"].astype(str) + "_" - + source["Repeat"].astype(int).astype(str), + + whole_numbers(source, "Repeat", 1).astype(str), "technical_repeat": SINGLE, "image_file": UNRECORDED, "label_id": 1, - FEATURE: source[FEATURE].astype(int), + FEATURE: whole_numbers(source, FEATURE, 0), "source_row": source["source_row"].astype(int), } ) diff --git a/data/lab/convert_tools.py b/data/lab/convert_tools.py index d0432945..314790c1 100644 --- a/data/lab/convert_tools.py +++ b/data/lab/convert_tools.py @@ -14,6 +14,7 @@ import zipfile from pathlib import Path +import numpy as np import pandas as pd @@ -22,11 +23,13 @@ def sha256(data: bytes) -> str: def fetch_zip_member(url: str, archive_md5: str, member: str) -> bytes: - """``member``'s bytes from the zip archive at ``url``, the archive's md5 verified.""" + """``member``'s bytes from the zip archive at ``url``, the archive's md5 verified, in + chunks: the archive (hundreds of MB) is never held in memory whole (#577).""" with tempfile.TemporaryDirectory() as tmp: path = Path(tmp) / "archive.zip" urllib.request.urlretrieve(url, path) - md5 = hashlib.md5(path.read_bytes()).hexdigest() + with open(path, "rb") as handle: + md5 = hashlib.file_digest(handle, "md5").hexdigest() if md5 != archive_md5: raise SystemExit(f"{url}: md5 {md5}, expected {archive_md5}") with zipfile.ZipFile(path) as archive: @@ -48,6 +51,25 @@ def check_columns(source: pd.DataFrame, expected: list[str]) -> None: raise SystemExit("the source has missing values") +def whole_numbers(source: pd.DataFrame, column: str, minimum: int) -> pd.Series: + """``source[column]`` as integers; stops unless every value is a finite whole number of at + least ``minimum``, naming the source rows: ``astype(int)`` would truncate a repeat of + 1.8 to 1 or a count of 5.9 to 5 (#576).""" + values = source[column] + if pd.api.types.is_bool_dtype(values) or not pd.api.types.is_numeric_dtype(values): + raise SystemExit(f"{column}: {values.dtype} values, not numbers") + numbers = values.to_numpy(dtype=float) + bad = ~np.isfinite(numbers) | (numbers != np.round(numbers)) | (numbers < minimum) + if bad.any(): + rows = source["source_row"] if "source_row" in source else pd.Series(source.index) + shown = "; ".join( + f"row {row}: {value}" + for row, value in zip(rows.to_numpy()[bad][:3], values.to_numpy()[bad][:3]) + ) + raise SystemExit(f"{column}: not a whole number of at least {minimum} in {shown}") + return values.astype(int) + + def synthetic_positions(table: pd.DataFrame, group: list[str], order: str) -> pd.Series: """A stable field identifier per row, ``|cellNNN``, numbered by ``order``. diff --git a/data/reference/reference.py b/data/reference/reference.py index abc96a09..b6a6d9e9 100644 --- a/data/reference/reference.py +++ b/data/reference/reference.py @@ -20,6 +20,7 @@ import argparse import fnmatch import os +import re import shutil import subprocess import sys @@ -32,6 +33,9 @@ REPOSITORY = HERE.parents[1] JOB_SCRIPT = HERE / "reference_job.py" OWNER_JOBS_VARIABLE = "MORPHOCOVERAGE_OWNER_JOBS" +# The job kinds reference_job.py runs (its BUILT_IN, the owner's jobs and the idr scripts). +KINDS = ("idr", "lab", "synthetic", "morphobricks", "scenario", "owner") +_NAME = re.compile(r"[A-Za-z0-9_.-]+") sys.path.insert(0, str(HERE)) from reference_compare import compare @@ -60,15 +64,32 @@ def export_working_tree(tree: Path) -> None: shutil.copy2(source, target) +def check_job(kind: str, name: str, where: object) -> None: + """Refuse a job whose kind is not one of ``KINDS`` or whose name is not one plain path + component (letters, digits, ``_``, ``.``, ``-``, not ``.`` or ``..``): its output folder + ``OUT/__`` is removed before the job runs, so it must lie in OUT (#583).""" + if kind not in KINDS: + raise ValueError(f"{where}: the job kind {kind!r} is not one of {', '.join(KINDS)}") + if not _NAME.fullmatch(name) or name in (".", ".."): + raise ValueError( + f"{where}: the job name {name!r} is not one plain word (letters, digits, _ . -)" + ) + + def read_jobs(path: Path) -> list[str]: - """The jobs of a job list: `` `` lines, ``#`` comments and blanks skipped.""" + """The jobs of a job list: `` `` lines, ``#`` comments and blanks skipped; + each checked (``check_job``) and listed once.""" jobs = [] for line in path.read_text().splitlines(): line = line.split("#", 1)[0].strip() if line: if len(line.split()) != 2: raise ValueError(f"{path}: {line!r} is not ' '") - jobs.append(" ".join(line.split())) + check_job(*line.split(), path) + job = " ".join(line.split()) + if job in jobs: + raise ValueError(f"{path}: the job {job!r} is listed twice") + jobs.append(job) return jobs @@ -91,8 +112,7 @@ def owner_job_lines(jobs_file: Path, tree: Path) -> list[str]: raise RuntimeError(f"the owner's jobs file {jobs_file} cannot be read:\n{done.stderr}") names = done.stdout.splitlines() for name in names: - if name.split() != [name] or "/" in name: - raise ValueError(f"{jobs_file}: the job name {name!r} is not one word") + check_job("owner", name, jobs_file) return [f"owner {name}" for name in names] @@ -165,6 +185,8 @@ def run_job(job: str, tree: Path, out: Path, owner_jobs: Path | None) -> tuple[s kind, name = job.split() folder = f"{kind}__{name}" target = out / folder + if target.resolve().parent != out.resolve(): # checked again before anything is removed + raise ValueError(f"the job {job!r} would write outside {out}; nothing was removed") shutil.rmtree(target, ignore_errors=True) # fallback: a first run has no earlier output target.mkdir(parents=True) started = time.perf_counter() diff --git a/data/simulations/decisions/benchmark_colab.ipynb b/data/simulations/decisions/benchmark_colab.ipynb index a38eef0a..34c9a580 100644 --- a/data/simulations/decisions/benchmark_colab.ipynb +++ b/data/simulations/decisions/benchmark_colab.ipynb @@ -41,13 +41,42 @@ " subprocess.run([\"unzip\", \"-q\", ZIP, \"-d\", \"/content\"], check=True)\n", " REPO = next(Path(\"/content\").glob(\"MorphoCoverage*/pyproject.toml\")).parent\n", " else:\n", + " import os\n", + " import tempfile\n", + "\n", " from google.colab import userdata\n", "\n", + " # The token never enters the URL, a command or the clone's .git/config: git asks\n", + " # this helper for it, which reads it from the clone's environment alone.\n", " token = userdata.get(\"GITHUB_TOKEN\")\n", - " url = f\"https://{token}@github.com/CellMigrationLab/MorphoCoverage.git\"\n", - " subprocess.run(\n", - " [\"git\", \"clone\", \"--depth\", \"1\", \"-b\", BRANCH, url, str(REPO)], check=True\n", + " helper = Path(tempfile.mkdtemp()) / \"askpass.sh\"\n", + " helper.write_text(\n", + " '#!/bin/sh\\ncase \"$1\" in Username*) echo x-access-token ;; '\n", + " '*) echo \"$MORPHOCOVERAGE_TOKEN\" ;; esac\\n'\n", + " )\n", + " helper.chmod(0o700)\n", + " secret = {\"GIT_ASKPASS\": str(helper), \"MORPHOCOVERAGE_TOKEN\": token}\n", + " url = \"https://github.com/CellMigrationLab/MorphoCoverage.git\"\n", + " clone = subprocess.run(\n", + " [\"git\", \"-c\", \"credential.helper=\", \"clone\", \"--depth\", \"1\", \"-b\", BRANCH]\n", + " + [url, str(REPO)],\n", + " env={**os.environ, \"GIT_TERMINAL_PROMPT\": \"0\", **secret},\n", + " capture_output=True,\n", + " text=True,\n", + " check=False,\n", " )\n", + " helper.unlink()\n", + " if clone.returncode: # git's message, the token masked, never the command\n", + " said = clone.stderr.replace(token, \"***\") if token else clone.stderr\n", + " raise RuntimeError(f\"git clone failed ({clone.returncode}): {said}\")\n", + " remote = subprocess.run(\n", + " [\"git\", \"-C\", str(REPO), \"config\", \"--get\", \"remote.origin.url\"],\n", + " capture_output=True,\n", + " text=True,\n", + " check=True,\n", + " ).stdout.strip()\n", + " if remote != url:\n", + " raise RuntimeError(\"the clone's remote URL is not the token-free one\")\n", " subprocess.run(\n", " [sys.executable, \"-m\", \"pip\", \"install\", \"-q\", \"-e\", f\"{REPO}[validation,dev]\"], check=True\n", " )\n", diff --git a/data/simulations/decisions/candidates/fixed_block.py b/data/simulations/decisions/candidates/fixed_block.py index b9a67d6c..32e247a1 100644 --- a/data/simulations/decisions/candidates/fixed_block.py +++ b/data/simulations/decisions/candidates/fixed_block.py @@ -26,6 +26,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass +from numbers import Real from typing import Any import numpy as np @@ -71,7 +72,9 @@ def matrix(self) -> np.ndarray: def contrast(self, weights: Mapping[Any, float]) -> np.ndarray: """The coefficient vector of ``sum_c w_c alpha_c`` (a condition not held anywhere - cannot be part of an estimable contrast: ``KeyError``).""" + cannot be part of an estimable contrast: ``KeyError``); weights that are not a + contrast are refused (``check_weights``).""" + check_weights(weights) unknown = set(weights) - set(self.conditions) if unknown: raise KeyError(f"conditions held in no repeat: {sorted(map(str, unknown))}") @@ -82,6 +85,23 @@ def contrast(self, weights: Mapping[Any, float]) -> np.ndarray: return vector +def check_weights(weights: Mapping[Any, float]) -> None: + """Refuse weights that are not a contrast (#514): each a finite real number (not a + boolean), at least two of them not 0, and their sum 0 within ``TOLERANCE`` of their + total size. ``{"A": 1.0}`` is A's mean, not a comparison; the direct test and the model + would answer different questions about it. Never rescaled or completed.""" + if not isinstance(weights, Mapping) or not weights: + raise ValueError("contrast weights must map conditions to numbers") + for value in weights.values(): + if isinstance(value, bool) or not isinstance(value, Real) or not np.isfinite(value): + raise ValueError(f"contrast weights must be finite numbers, not {value!r}") + if sum(1 for w in weights.values() if w != 0) < 2: + raise ValueError(f"contrast weights must compare at least two conditions: {weights}") + size = sum(abs(float(w)) for w in weights.values()) + if abs(sum(float(w) for w in weights.values())) > TOLERANCE * size: + raise ValueError(f"contrast weights must sum to 0: {dict(weights)}") + + def estimable(x: np.ndarray, contrast: np.ndarray, tolerance: float = TOLERANCE) -> bool: """Whether ``contrast`` lies in the row space of ``x`` (see the module).""" _, singular, vt = np.linalg.svd(x, full_matrices=False) @@ -102,6 +122,7 @@ def components(presence: Mapping[Any, Sequence[Any]]) -> dict[Any, int]: def graph_estimable(presence: Mapping[Any, Sequence[Any]], weights: Mapping[Any, float]) -> bool: """Whether the weights sum to 0 within every connected component (see the module).""" + check_weights(weights) found = components(presence) if any(c not in found and w != 0 for c, w in weights.items()): return False @@ -118,6 +139,7 @@ def regime( min_repeats: int = MIN_REPEATS, ) -> str: """``direct``, ``model`` or ``not estimable`` for one contrast (see the module).""" + check_weights(weights) involved = [c for c, w in weights.items() if w != 0] shared = [r for r, held in presence.items() if set(involved) <= set(held)] if len(shared) >= min_repeats: @@ -230,6 +252,7 @@ def contrast( "MIN_REPEATS", "NOT_ESTIMABLE", "Layout", + "check_weights", "components", "contrast", "estimable", diff --git a/data/simulations/decisions/candidates/hd_tests.py b/data/simulations/decisions/candidates/hd_tests.py index 373bde25..798e75ce 100644 --- a/data/simulations/decisions/candidates/hd_tests.py +++ b/data/simulations/decisions/candidates/hd_tests.py @@ -89,7 +89,19 @@ def u_statistic(delta: np.ndarray) -> dict[str, float]: return {"u": u, "z": float(z), "p": float(stats.norm.sf(z))} +# The most repeats whose 2**n sign assignments are enumerated (65,536 rows, as +# ``sampling_unit.contrast_repeats``); beyond, the exact tests are refused, not run in +# exponential memory and time (#519). The benchmark's designs have 3-6 repeats. +MAX_EXACT_REPEATS = 16 + + def _signs(n: int) -> np.ndarray: + """Every assignment of signs to ``n`` repeats, the observed (all +1) first.""" + if n > MAX_EXACT_REPEATS: + raise ValueError( + f"the exact sign-flip enumerates 2**n assignments, so it takes at most " + f"{MAX_EXACT_REPEATS} repeats, not {n}" + ) return np.array(list(product((1.0, -1.0), repeat=n))) @@ -212,6 +224,7 @@ def permutation_test( __all__ = [ + "MAX_EXACT_REPEATS", "deltas", "field_means", "min_p", diff --git a/data/simulations/decisions/colab.py b/data/simulations/decisions/colab.py index 182ea97d..608ea086 100644 --- a/data/simulations/decisions/colab.py +++ b/data/simulations/decisions/colab.py @@ -71,11 +71,18 @@ def run( workers: int | None = None, chunk: int = 100, ) -> None: - """Run each of ``modules`` (``"P0"``, ``"P1"`` ... ``"P5"``) at ``size`` into ``out``.""" + """Run each of ``modules`` (``"P0"``, ``"P1"`` ... ``"P5"``) at ``size`` into ``out``. + A failed P0 stops the run: the modules after it are not run on a baseline that failed + its gate (#520).""" out = Path(out) for name in modules: if name.upper() == "P0": - run_p0(out) + code = run_p0(out) + if code: + raise RuntimeError( + f"P0 failed (pytest exit {code}; {out / 'p0' / 'p0.txt'}): the modules " + "after it were not run, and no result of this run is confirmatory" + ) continue runner.run(MODULES[name.upper()], out, size, workers, chunk) diff --git a/data/simulations/decisions/embedding.py b/data/simulations/decisions/embedding.py index 99c31b7b..60a361b3 100644 --- a/data/simulations/decisions/embedding.py +++ b/data/simulations/decisions/embedding.py @@ -227,6 +227,36 @@ def generate(design: Design, spec: EmbeddingSpec, rng: np.random.Generator) -> E return EmbeddingData(objects, fovs, columns, truth, lay) +# The draws of a direction before a data set whose rows all cancel in pairs is refused. +_DRAWS = 100 + + +def _check_semi_synthetic(values: np.ndarray, meta: pd.DataFrame, field_col: str) -> None: + """What ``semi_synthetic`` needs: one finite row of values per row of ``meta``, and at + least 2 fields in every biological repeat, so both conditions are in every repeat.""" + if values.ndim != 2 or len(values) != len(meta) or not len(values): + raise ValueError(f"values must hold one row per row of meta ({len(meta)} rows)") + if not np.isfinite(values).all(): + raise ValueError("the values must be finite") + fields = meta.groupby(REPEAT_COLUMN)[field_col].nunique() + if (fields < 2).any(): + few = ", ".join(map(str, fields.index[fields < 2])) + raise ValueError(f"every repeat needs at least 2 fields to relabel half; not {few}") + + +def _direction_of(centred: np.ndarray, within: float, rng: np.random.Generator) -> np.ndarray: + """A unit direction of the data's own span: the sum of two random centred rows, drawn + again while they cancel (the same draws as before whenever the first pair does not).""" + for _ in range(_DRAWS): + direction = centred[rng.integers(len(centred))] + centred[rng.integers(len(centred))] + norm = float(np.linalg.norm(direction)) + if norm > 1e-9 * within: + return direction / norm + if not within > 0: # no shift asked of values that do not vary: drawn once, as before + return np.zeros(centred.shape[1]) + raise ValueError(f"{_DRAWS} draws of two rows all cancelled: no direction to shift along") + + def semi_synthetic( values: np.ndarray, meta: pd.DataFrame, @@ -237,12 +267,18 @@ def semi_synthetic( """Real control observations made into a two-condition experiment: within each biological repeat, half the fields (at random) relabelled ``treated`` and shifted by ``shift`` within-group SDs along a random direction of the data's own span. Returns the - values, the metadata with the new ``condition`` and the shift vector.""" + values, the metadata with the new ``condition`` and the shift vector. Refused (#524): + values and metadata of different lengths, values that are not finite, a repeat of fewer + than 2 fields (no field to relabel), and a shift asked of values that do not vary; a draw + of two rows that cancel is drawn again (at most ``_DRAWS`` times), never a zero shift.""" + values = np.asarray(values, dtype=float) meta = meta.reset_index(drop=True).copy() + _check_semi_synthetic(values, meta, field_col) centred = values - values.mean(axis=0) within = float(np.sqrt(np.square(centred).sum(axis=1).mean())) - direction = centred[rng.integers(len(centred))] + centred[rng.integers(len(centred))] - direction = direction / max(np.linalg.norm(direction), 1e-12) + if shift and not within > 0: + raise ValueError("the values do not vary, so no shift in within-group SDs exists") + direction = _direction_of(centred, within, rng) vector = shift * within * direction condition = np.full(len(meta), "control", dtype=object) for rows in meta.groupby(REPEAT_COLUMN).groups.values(): diff --git a/docs/common/data_format.md b/docs/common/data_format.md index 782b83a9..377fa359 100644 --- a/docs/common/data_format.md +++ b/docs/common/data_format.md @@ -47,7 +47,7 @@ result. | other group columns | both, or FOV table only | any | Named with `group_cols`, for example `batch`. Each combination of group values is analysed apart. Without a `technical_repeat` column, one nested within condition and biological repeat (a `well` column) is the unit the condition contrast shuffles. | | `z`, `c`, `t` (or `z0`, `z1`) | observations | integer | Plane, channel and time point within one position. Required when one position spans several files, so the files can be told apart. Never new fields, and never features: naming one in `feature_cols` raises. Rows of several planes, channels or time points in one field are refused unless each row measures a whole plane (see [Planes are not fields](#rules-the-validator-enforces) and [Features measured per plane](#features-measured-per-plane)). Read in lowercase only, so a column `Z`, `Metadata_Z`, `plane`, `slice`, `channel` or `frame` raises as a near miss. | | acquisition order | FOV table | numeric, datetime or timedelta | Named with `acquisition_order_col` (MorphoBricks suggests `acquisition_order`). The recorded order in which fields are replayed; text is refused, since it would sort `'10'` before `'2'`, and so is a categorical column (owner, 2026-10-12). Without it only random orders are replayed; the order of the rows or of the file names is never taken for it. | -| stage coordinates | FOV table | numeric, finite | Named with `stage_cols` (MorphoBricks suggests `stage_x`, `stage_y`). Used for dispersed orders, stage travel, redundancy distance and spatial blocks; an infinite coordinate raises. | +| stage coordinates | FOV table | numeric, finite | Named with `stage_cols` (MorphoBricks suggests `stage_x`, `stage_y`). Used for dispersed orders, stage travel, redundancy distance and spatial blocks; an infinite coordinate raises, and so does an integer a float cannot hold exactly (beyond 2**53), which would place two positions at one. | | imaged area | FOV table | numeric, positive | Named on `FixedAreaStrategy`. The physical area of each field, for area-based stopping. A missing, infinite, zero or negative area makes the rule not applicable, and a text column raises; a benchmark record's effort refuses all of them. | | a rare-state label | observations | boolean or 0/1 | Named with `Setup.rare_label`. An independent label of the rare phenotype, so held-back fields can judge whether it was seen. A missing value means unknown: the observation is left out of every share (owner, 2026-10-05). | | `label_id`, `patch_id`, `mask_file`, `patch_file` | observations | any | Provenance, kept for tracing an observation back to its image; never features. `label_id` and `patch_id` also identify an observation within its field for the other feature tables. `check_tables` also reads CellProfiler's `ObjectNumber`, `object_id` or `label` as the object label. | diff --git a/docs/common/function_duplicates.json b/docs/common/function_duplicates.json index 3a1aea29..54aef560 100644 --- a/docs/common/function_duplicates.json +++ b/docs/common/function_duplicates.json @@ -211,6 +211,7 @@ ], "KINDS": [ "_control = (OWN, MASTER_RAW, ACROSS)", + "data.reference.reference = ('idr', 'lab', 'synthetic', 'morphobricks', 'scenario', 'owner')", "data.simulations.decisions.runner = ('core', 'stress', 'screening')", "sampling_unit.populations = ('main', 'group')" ], diff --git a/docs/common/function_index.jsonl b/docs/common/function_index.jsonl index 2c106cfb..2a107434 100644 --- a/docs/common/function_index.jsonl +++ b/docs/common/function_index.jsonl @@ -5,7 +5,8 @@ {"arguments": 1, "called_by": ["_acquisition:check_one_acquisition"], "calls": ["_acquisition:recorded", "getattr", "isinstance"], "complexity": 3, "decorators": [], "hash": "82d5b79cdb746f77", "kind": "function", "lines": 5, "module": "_acquisition", "name": "result_identity", "public": true, "signature": "(result: Any) -> str | None", "summary": "The acquisition identity of one analysis result: its settings' record, or the", "varargs": []} {"arguments": 1, "called_by": ["retrospective.report:microscopist_report"], "calls": ["?.append", "?.items", "?.join", "?.setdefault", "?.values", "ValueError", "_acquisition:result_identity", "len", "set"], "complexity": 5, "decorators": [], "hash": "428a0c250a2f5649", "kind": "function", "lines": 17, "module": "_acquisition", "name": "check_one_acquisition", "public": true, "signature": "(results: Mapping[str, Any]) -> None", "summary": "Refuse results that record no acquisition identity, or that came from different ones.", "varargs": []} {"calls": [], "kind": "module", "module": "_areas", "name": "", "public": false, "summary": "The one check of an FOV table's imaged-area column (private)."} -{"arguments": 3, "called_by": ["_benchmark_data:_area", "strategies.baselines:ImagedAreaEstimator.estimate"], "calls": ["?.any", "?.head", "?.isna", "?.to_dict", "?.to_numpy", "ValueError", "list", "numpy.isfinite", "pandas.api.types.is_bool_dtype", "pandas.api.types.is_numeric_dtype"], "complexity": 5, "decorators": [], "hash": "3ccf422a83f3979b", "kind": "function", "lines": 18, "module": "_areas", "name": "area_problem", "public": true, "signature": "(fovs: pd.DataFrame, area_col: str, fov_key: Sequence[str]) -> str | None", "summary": "Why the areas in ``fovs[area_col]`` cannot be summed, or ``None`` when they can.", "varargs": []} +{"arguments": 3, "called_by": ["_benchmark_data:_area", "strategies.baselines:ImagedAreaEstimator.estimate"], "calls": ["?.any", "?.head", "?.isna", "?.to_dict", "?.to_numpy", "ValueError", "_areas:_total", "len", "list", "math.isfinite", "numpy.isfinite", "pandas.api.types.is_bool_dtype", "pandas.api.types.is_numeric_dtype"], "complexity": 7, "decorators": [], "hash": "e426796384c6f70c", "kind": "function", "lines": 23, "module": "_areas", "name": "area_problem", "public": true, "signature": "(fovs: pd.DataFrame, area_col: str, fov_key: Sequence[str]) -> str | None", "summary": "Why the areas in ``fovs[area_col]`` cannot be summed, or ``None`` when they can.", "varargs": []} +{"arguments": 1, "called_by": ["_areas:area_problem"], "calls": ["?.max", "?.sum", "float"], "complexity": 1, "decorators": [], "hash": "4dc90acd9fd9d71b", "kind": "function", "lines": 2, "module": "_areas", "name": "_total", "public": false, "signature": "(values: np.ndarray) -> float", "summary": "The sum of positive, finite ``values``, infinite when it overflows a float (#544).", "varargs": []} {"calls": [], "kind": "module", "module": "_benchmark_data", "name": "", "public": false, "summary": "The data of a benchmark run (private): the dataset loaded and validated, its analysis"} {"called_by": ["_benchmark_data:_streams"], "calls": ["dataclasses.dataclass"], "decorators": ["dataclass(frozen=True)"], "hash": "8b341345c07ae535", "kind": "class", "module": "_benchmark_data", "name": "_Streams", "public": false, "signature": "()", "summary": "Per analysis group: what the strategies replay (``groups``), what outcomes are scored"} {"arguments": 1, "called_by": ["_benchmark_data:_loaded_groups", "benchmark:_replay_order"], "calls": ["?.items", "tuple"], "complexity": 1, "decorators": [], "hash": "f96d122ce16be25f", "kind": "function", "lines": 1, "module": "_benchmark_data", "name": "_group_key", "public": false, "signature": "(group: Mapping[str, Any]) -> tuple", "summary": "Hashable identity of an analysis group, for matching replay results.", "varargs": []} @@ -27,11 +28,11 @@ {"calls": [], "kind": "module", "module": "_checks", "name": "", "public": false, "summary": "Argument checks shared by the package (private)."} {"arguments": 1, "called_by": ["_checks:as_count", "_checks:check_seed", "_described_shape:_version", "_described_shape:checked_version", "_parallel:check_n_jobs", "_seeds:_seed_label", "_wording:features_counted", "benchmark:AcquisitionOrder.__post_init__", "bounds:_check_counts", "bounds:extra_trials_for_bound", "calibration:_check_settings", "multivariate_outcomes:SlicedWassersteinError.__post_init__", "multivariate_outcomes:_SubsampledOutcome.__post_init__", "objectives:fov_occurrences", "plots:_counts", "policies:EffortPolicy.__post_init__", "reservoir:ReservoirSplit.__post_init__", "reservoir:reference_error_floor", "retrospective.controls:RepresentationControl.__post_init__", "retrospective.controls:_check_declaration", "retrospective.criteria:OutcomeCriterion.__post_init__", "retrospective.effect_preservation:_check_settings", "retrospective.effort:_check_arguments", "retrospective.effort_design:_check_allocations", "retrospective.inspection:_check_numbers", "retrospective.reliability:_check_settings", "retrospective.stage:dispersed_order", "sampling_unit.repeat_plan:_check_plan", "statistics:field_sample", "statistics:fields_holding", "statistics:fovs_to_detect", "statistics:sd_upper_bound_factor", "statistics:small_sample_widening", "strategies._fov_bootstrap_checks:_check_counts", "strategies._fov_bootstrap_checks:_check_summary_settings", "strategies.baselines:_require_positive_int", "strategies.incidence_coverage:_check", "strategies.scalar_precision:_check_configuration", "strategies.stabilization:_check_plateau", "strategies.stabilization:_check_spread", "strategies.support_novelty:_check", "strategies.support_novelty:_check_novel", "sufficiency:_checked_few_fovs", "transforms:PCA.__post_init__", "workflows._live_watch:check_watch", "workflows._setup_parts:check_few_fovs", "workflows._setup_parts:check_positive"], "calls": ["isinstance"], "complexity": 2, "decorators": [], "hash": "f81e4fac807d2f65", "kind": "function", "lines": 1, "module": "_checks", "name": "is_integer", "public": true, "signature": "(value: object) -> bool", "summary": "Whether ``value`` is an integer (Python or numpy), not a boolean.", "varargs": []} {"arguments": 1, "called_by": ["_checks:is_positive_finite", "_checks:is_share", "_seeds:_seed_label", "bounds:check_confidence", "evidence:Quantity.__post_init__", "integrity:integrity_checks", "objectives:_probability", "planes:_label", "policies:ThresholdPolicy.__post_init__", "reservoir:spatial_blocks", "retrospective.criteria:OutcomeCriterion.__post_init__", "retrospective.effect_preservation:_check_settings", "retrospective.effort_design:_check_allocations", "retrospective.inspection:Summary.__post_init__", "retrospective.inspection:_check_numbers", "sampling_unit.discovery:feature_discovery", "sampling_unit.distribution:distribution_contrast", "sampling_unit.ranking:feature_ranking", "sampling_unit.repeat_plan:_check_plan", "statistics:effective_sd_upper_bound_factor", "strategies.stabilization:_check_tolerance", "workflows._live_watch:check_watch", "workflows._setup_parts:check_presets"], "calls": ["isinstance"], "complexity": 2, "decorators": [], "hash": "51240854f7e100cd", "kind": "function", "lines": 1, "module": "_checks", "name": "is_number", "public": true, "signature": "(value: object) -> bool", "summary": "Whether ``value`` is a real number (Python or numpy), not a boolean.", "varargs": []} -{"arguments": 3, "called_by": ["embedding:embed", "integrity:integrity_checks", "plots_pairwise:pairwise_contrasts", "retrospective.effect_preservation:_check_settings", "retrospective.frontier:frontier", "retrospective.protocol:_check", "retrospective.reliability:_check_settings", "retrospective.replay:_check", "retrospective.spatial:redundancy_distance", "sampling_unit._units:check_arguments", "sampling_unit.clustering:fov_clustering", "sampling_unit.contrast:condition_contrast", "sampling_unit.object_rules:descriptor_spread_check", "sampling_unit.object_rules:object_rule_check", "sampling_unit.populations:_clusters", "sampling_unit.populations:find_populations", "sampling_unit.unusual:unusual_objects", "separation:separation", "sequential:_evaluate_prefixes"], "calls": ["ValueError", "_checks:is_integer", "int"], "complexity": 3, "decorators": [], "hash": "06dbe7ed6ee0d694", "kind": "function", "lines": 3, "module": "_checks", "name": "as_count", "public": true, "signature": "(value: object, name: str, minimum: int=1) -> int", "summary": "``value`` as a Python ``int`` of at least ``minimum``, or a ``ValueError`` naming it.", "varargs": []} -{"arguments": 2, "called_by": ["benchmark:AcquisitionOrder.__post_init__", "calibration:_check_settings", "embedding:embed", "plots_pairwise:pairwise_contrasts", "reservoir:ReservoirSplit.__post_init__", "reservoir:reference_error_floor", "retrospective.controls:representation_control", "retrospective.effect_preservation:effect_preservation", "retrospective.effort:_check_arguments", "retrospective.protocol:_check", "retrospective.reliability:_check_settings", "retrospective.replay:_check", "retrospective.spatial:redundancy_distance", "sampling_unit._units:check_arguments", "sampling_unit.clustering:fov_clustering", "sampling_unit.distribution:distribution_contrast", "sampling_unit.object_rules:descriptor_spread_check", "sampling_unit.object_rules:object_rule_check", "sampling_unit.populations:find_populations", "sampling_unit.unusual:unusual_objects", "separation:separation", "strategies._fov_bootstrap_checks:_check_counts", "strategies.stabilization:_check_spread", "workflows._setup_parts:check_presets", "workflows.benchmarks:default_families"], "calls": ["ValueError", "_checks:is_integer", "int"], "complexity": 3, "decorators": [], "hash": "23887c84999d8d7d", "kind": "function", "lines": 3, "module": "_checks", "name": "check_seed", "public": true, "signature": "(value: object, name: str='random_state') -> int", "summary": "A random seed: an integer of at least 0 (numpy integers accepted), as a Python ``int``.", "varargs": []} -{"arguments": 2, "called_by": ["retrospective.effect_preservation:_check_settings", "retrospective.frontier:frontier", "retrospective.protocol:_check", "retrospective.reliability:_check_settings", "retrospective.replay:replay_acquisitions", "retrospective.report:microscopist_report", "retrospective.spatial:redundancy_distance", "workflows.retrospective:optimise"], "calls": ["_checks:is_number", "math.isfinite"], "complexity": 4, "decorators": [], "hash": "89094dd56edc3dfb", "kind": "function", "lines": 3, "module": "_checks", "name": "is_share", "public": true, "signature": "(value: object, *, closed_high: bool=False) -> bool", "summary": "Whether ``value`` is a real number in (0, 1) (``closed_high``: in (0, 1]); strings,", "varargs": []} -{"arguments": 1, "called_by": ["retrospective.spatial:order_efficiency", "workflows._live_watch:check_watch"], "calls": ["_checks:is_number", "math.isfinite"], "complexity": 3, "decorators": [], "hash": "eb05c7b19fb9cd41", "kind": "function", "lines": 1, "module": "_checks", "name": "is_positive_finite", "public": true, "signature": "(value: object) -> bool", "summary": "Whether ``value`` is a real number above 0 and finite (not a string, boolean or NaN).", "varargs": []} -{"arguments": 2, "called_by": ["retrospective.replay:replay_acquisitions", "workflows.live:LiveFolder.__init__"], "calls": ["TypeError", "bool", "isinstance"], "complexity": 2, "decorators": [], "hash": "cbf433dde8c9ffeb", "kind": "function", "lines": 3, "module": "_checks", "name": "check_flag", "public": true, "signature": "(value: object, name: str) -> bool", "summary": "A mode flag: a real boolean (numpy's too), never generic truthiness such as ``1`` or", "varargs": []} +{"arguments": 3, "called_by": ["embedding:embed", "integrity:integrity_checks", "plots_pairwise:pairwise_contrasts", "retrospective.effect_preservation:_check_settings", "retrospective.frontier:frontier", "retrospective.protocol:_check", "retrospective.reliability:_check_settings", "retrospective.replay:_check", "retrospective.spatial:redundancy_distance", "sampling_unit._units:check_arguments", "sampling_unit.clustering:fov_clustering", "sampling_unit.contrast:condition_contrast", "sampling_unit.object_rules:descriptor_spread_check", "sampling_unit.object_rules:object_rule_check", "sampling_unit.populations:_clusters", "sampling_unit.populations:find_populations", "sampling_unit.unusual:unusual_objects", "sampling_unit.whole_table:whole_table_tests", "separation:separation", "sequential:_evaluate_prefixes"], "calls": ["ValueError", "_checks:is_integer", "int"], "complexity": 3, "decorators": [], "hash": "06dbe7ed6ee0d694", "kind": "function", "lines": 3, "module": "_checks", "name": "as_count", "public": true, "signature": "(value: object, name: str, minimum: int=1) -> int", "summary": "``value`` as a Python ``int`` of at least ``minimum``, or a ``ValueError`` naming it.", "varargs": []} +{"arguments": 2, "called_by": ["benchmark:AcquisitionOrder.__post_init__", "calibration:_check_settings", "embedding:embed", "plots_pairwise:pairwise_contrasts", "reservoir:ReservoirSplit.__post_init__", "reservoir:reference_error_floor", "retrospective.controls:representation_control", "retrospective.effect_preservation:effect_preservation", "retrospective.effort:_check_arguments", "retrospective.protocol:_check", "retrospective.reliability:_check_settings", "retrospective.replay:_check", "retrospective.spatial:redundancy_distance", "sampling_unit._units:check_arguments", "sampling_unit.clustering:fov_clustering", "sampling_unit.distribution:distribution_contrast", "sampling_unit.object_rules:descriptor_spread_check", "sampling_unit.object_rules:object_rule_check", "sampling_unit.populations:find_populations", "sampling_unit.unusual:unusual_objects", "sampling_unit.whole_table:whole_table_tests", "separation:separation", "strategies._fov_bootstrap_checks:_check_counts", "strategies.stabilization:_check_spread", "workflows._setup_parts:check_presets", "workflows.benchmarks:default_families"], "calls": ["ValueError", "_checks:is_integer", "int"], "complexity": 3, "decorators": [], "hash": "23887c84999d8d7d", "kind": "function", "lines": 3, "module": "_checks", "name": "check_seed", "public": true, "signature": "(value: object, name: str='random_state') -> int", "summary": "A random seed: an integer of at least 0 (numpy integers accepted), as a Python ``int``.", "varargs": []} +{"arguments": 2, "called_by": ["_repeat_statistics:repeat_effect", "retrospective.effect_preservation:_check_settings", "retrospective.frontier:frontier", "retrospective.protocol:_check", "retrospective.reliability:_check_settings", "retrospective.replay:replay_acquisitions", "retrospective.report:microscopist_report", "retrospective.spatial:redundancy_distance", "workflows.retrospective:optimise"], "calls": ["_checks:is_number", "math.isfinite"], "complexity": 4, "decorators": [], "hash": "89094dd56edc3dfb", "kind": "function", "lines": 3, "module": "_checks", "name": "is_share", "public": true, "signature": "(value: object, *, closed_high: bool=False) -> bool", "summary": "Whether ``value`` is a real number in (0, 1) (``closed_high``: in (0, 1]); strings,", "varargs": []} +{"arguments": 1, "called_by": ["retrospective.spatial:order_efficiency", "transforms:ColumnWeights.__post_init__", "workflows._live_watch:check_watch"], "calls": ["_checks:is_number", "math.isfinite"], "complexity": 3, "decorators": [], "hash": "eb05c7b19fb9cd41", "kind": "function", "lines": 1, "module": "_checks", "name": "is_positive_finite", "public": true, "signature": "(value: object) -> bool", "summary": "Whether ``value`` is a real number above 0 and finite (not a string, boolean or NaN).", "varargs": []} +{"arguments": 2, "called_by": ["retrospective.replay:replay_acquisitions", "transforms:BlockWeights.__post_init__", "workflows.live:LiveFolder.__init__"], "calls": ["TypeError", "bool", "isinstance"], "complexity": 2, "decorators": [], "hash": "cbf433dde8c9ffeb", "kind": "function", "lines": 3, "module": "_checks", "name": "check_flag", "public": true, "signature": "(value: object, name: str) -> bool", "summary": "A mode flag: a real boolean (numpy's too), never generic truthiness such as ``1`` or", "varargs": []} {"arguments": 2, "called_by": ["retrospective.replay:_check"], "calls": ["?.strip", "TypeError", "isinstance"], "complexity": 4, "decorators": [], "hash": "801fc4c4bef76f1d", "kind": "function", "lines": 3, "module": "_checks", "name": "check_column", "public": true, "signature": "(value: object, name: str) -> str | None", "summary": "``None`` or one non-empty column name; a sequence, mapping or empty text is refused.", "varargs": []} {"calls": [], "kind": "module", "module": "_condition_ids", "name": "", "public": false, "summary": "Conditions are named by their ``condition_id``, never by folder label (MC-1, #628)."} {"called_by": ["_condition_ids:_one_to_one", "_condition_ids:checked_condition_ids", "_condition_ids:refuse_folder_names", "_condition_ids:refuse_unmatched", "_repeat_groups:_by_label", "_repeat_groups:_checked_groups", "_repeat_groups:_groups_of", "_repeat_groups:_refuse_disagreeing", "_repeat_groups:_refuse_empty", "_repeat_groups:_refuse_merged", "_repeat_groups:pair_by_repeat_group", "data_check:_named_by_id", "workflows._pairing:paired_inputs", "workflows._scan_rules:named_tables"], "calls": [], "decorators": [], "hash": "6ad209d0cd2b6452", "kind": "class", "module": "_condition_ids", "name": "PairingRefused", "public": true, "signature": "(ValueError)", "summary": "The biological repeats cannot be paired across conditions; ``code`` names the reason"} @@ -152,14 +153,16 @@ {"calls": ["typing.TypeVar"], "kind": "module", "module": "_frozen", "name": "", "public": false, "summary": "Owned, read-only containers for frozen result snapshots (private; issue 108)."} {"arguments": 0, "called_by": ["_frozen:FrozenDict", "_frozen:FrozenList"], "calls": ["TypeError"], "complexity": 1, "decorators": [], "hash": "a35862a1cf1fbb35", "kind": "function", "lines": 1, "module": "_frozen", "name": "_refuse", "public": false, "signature": "(*_: Any, **__: Any) -> NoReturn", "summary": "", "varargs": ["*_", "**__"]} {"called_by": ["_frozen:FrozenDict.__reduce__", "_frozen:freeze"], "calls": ["_frozen:_refuse"], "decorators": [], "hash": "dfb59d790028b464", "kind": "class", "module": "_frozen", "name": "FrozenDict", "public": true, "signature": "(dict[Any, Any])", "summary": "A dict that cannot be changed after construction (equal to, and serialised as, a dict)."} +{"arguments": 0, "called_by": [], "calls": ["?.__init__", "?.items", "_frozen:freeze", "dict"], "complexity": 1, "decorators": [], "hash": "71c36916aff3f906", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenDict.__init__", "public": false, "signature": "(self, *args: Any, **kwargs: Any) -> None", "summary": "", "varargs": ["*args", "**kwargs"]} {"arguments": 0, "called_by": [], "calls": ["_frozen:FrozenDict", "dict"], "complexity": 1, "decorators": [], "hash": "7e7e00196afeda52", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenDict.__reduce__", "public": false, "signature": "(self) -> tuple[Any, ...]", "summary": "", "varargs": []} {"arguments": 1, "called_by": [], "calls": [], "complexity": 1, "decorators": [], "hash": "de363de081c5624a", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenDict.__deepcopy__", "public": false, "signature": "(self, memo: dict[int, Any]) -> FrozenDict", "summary": "", "varargs": []} {"arguments": 0, "called_by": [], "calls": [], "complexity": 1, "decorators": [], "hash": "de363de081c5624a", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenDict.__copy__", "public": false, "signature": "(self) -> FrozenDict", "summary": "", "varargs": []} {"called_by": ["_frozen:FrozenList.__reduce__", "_frozen:freeze"], "calls": ["_frozen:_refuse"], "decorators": [], "hash": "29c6f2e31b2a6272", "kind": "class", "module": "_frozen", "name": "FrozenList", "public": true, "signature": "(list[Any])", "summary": "A list that cannot be changed after construction (equal to, and serialised as, a list)."} +{"arguments": 1, "called_by": [], "calls": ["?.__init__", "_frozen:freeze"], "complexity": 1, "decorators": [], "hash": "a09bbba2c61bf900", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenList.__init__", "public": false, "signature": "(self, items: Iterable[Any]=()) -> None", "summary": "", "varargs": []} {"arguments": 0, "called_by": [], "calls": ["_frozen:FrozenList", "list"], "complexity": 1, "decorators": [], "hash": "3fd6a3d5c9549fcd", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenList.__reduce__", "public": false, "signature": "(self) -> tuple[Any, ...]", "summary": "", "varargs": []} {"arguments": 1, "called_by": [], "calls": [], "complexity": 1, "decorators": [], "hash": "de363de081c5624a", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenList.__deepcopy__", "public": false, "signature": "(self, memo: dict[int, Any]) -> FrozenList", "summary": "", "varargs": []} {"arguments": 0, "called_by": [], "calls": [], "complexity": 1, "decorators": [], "hash": "de363de081c5624a", "kind": "method", "lines": 1, "module": "_frozen", "name": "FrozenList.__copy__", "public": false, "signature": "(self) -> FrozenList", "summary": "", "varargs": []} -{"arguments": 1, "called_by": ["_frozen:own", "_frozen:own_value"], "calls": ["?.items", "_frozen:FrozenDict", "_frozen:FrozenList", "_frozen:freeze", "frozenset", "hasattr", "isinstance", "map", "tuple", "type"], "complexity": 7, "decorators": [], "hash": "bd4fa720701c2ded", "kind": "function", "lines": 15, "module": "_frozen", "name": "freeze", "public": true, "signature": "(value: Any) -> Any", "summary": "``value`` with every container it holds copied into a read-only one (see the module).", "varargs": []} +{"arguments": 1, "called_by": ["_frozen:FrozenDict.__init__", "_frozen:FrozenList.__init__", "_frozen:own", "_frozen:own_value"], "calls": ["?.items", "_frozen:FrozenDict", "_frozen:FrozenList", "_frozen:freeze", "frozenset", "hasattr", "isinstance", "map", "tuple", "type"], "complexity": 7, "decorators": [], "hash": "adb85f249d0757cb", "kind": "function", "lines": 15, "module": "_frozen", "name": "freeze", "public": true, "signature": "(value: Any) -> Any", "summary": "``value`` with every container it holds copied into a read-only one (see the module).", "varargs": []} {"arguments": 1, "called_by": [], "calls": ["?.items", "_frozen:thaw", "isinstance", "tuple"], "complexity": 5, "decorators": [], "hash": "896a3a9ab50a288b", "kind": "function", "lines": 9, "module": "_frozen", "name": "thaw", "public": true, "signature": "(value: Any) -> Any", "summary": "Plain, independent dicts, lists and tuples with the same contents as ``value``.", "varargs": []} {"arguments": 1, "called_by": ["evidence:Evidence.__post_init__", "results:StrategyResult.__post_init__", "results:StrategyResult._decision_words"], "calls": ["_frozen:freeze", "dict"], "complexity": 1, "decorators": [], "hash": "1da9c85ea20293ea", "kind": "function", "lines": 1, "module": "_frozen", "name": "own", "public": true, "signature": "(mapping: Mapping[str, Any] | Iterable[tuple[str, Any]]) -> FrozenDict", "summary": "A frozen copy of a mapping (``freeze`` for the top level a dataclass field holds).", "varargs": []} {"arguments": 1, "called_by": ["_frozen:owned.wrap.__init__"], "calls": ["?.copy", "_frozen:freeze", "isinstance"], "complexity": 2, "decorators": [], "hash": "f037e798e47c2a7b", "kind": "function", "lines": 3, "module": "_frozen", "name": "own_value", "public": true, "signature": "(value: Any) -> Any", "summary": "What a snapshot keeps of one field: containers frozen (``freeze``), a pandas table or", "varargs": []} @@ -338,13 +341,13 @@ {"arguments": 1, "called_by": ["plots_pairwise:_paired", "sampling_unit._discovery_tests:_paired", "sampling_unit.contrast_across:_row", "sampling_unit.contrast_repeats:_condition_row", "sampling_unit.distribution:_rows", "workflows._population_tests:_test_row", "workflows._result_influence:_result"], "calls": ["?.any", "float", "len", "numpy.asarray", "numpy.isnan", "numpy.ptp", "scipy.stats.ttest_1samp"], "complexity": 4, "decorators": [], "hash": "dac7f95431f93b7d", "kind": "function", "lines": 4, "module": "_repeat_statistics", "name": "paired_t", "public": true, "signature": "(differences: np.ndarray) -> float", "summary": "The two-sided paired t-test of ``differences`` (one per biological repeat); NaN when a", "varargs": []} {"arguments": 3, "called_by": ["plots_pairwise:pairwise_contrasts", "sampling_unit._discovery_tests:_pooled", "sampling_unit.acquisition:_logged", "sampling_unit.contrast:_settings", "sampling_unit.contrast_across:across_features", "sampling_unit.contrast_across:across_table", "sampling_unit.distribution:distribution_contrast", "workflows._shared:_check_labels_and_scales", "workflows._unusual_values:ratio_scale"], "calls": ["?.all", "?.min", "ValueError", "bool", "len", "numpy.asarray", "numpy.isnan"], "complexity": 8, "decorators": [], "hash": "5b20f404c0fbb98a", "kind": "function", "lines": 13, "module": "_repeat_statistics", "name": "log_scale", "public": true, "signature": "(values: np.ndarray, declared: str | None=None, feature: str='') -> bool", "summary": "Whether the paired test across repeats reads a feature as log ratios. ``declared``,", "varargs": []} {"arguments": 3, "called_by": ["plots_pairwise:_paired", "sampling_unit._discovery_tests:_effect", "sampling_unit._discovery_tests:_paired", "sampling_unit.contrast_repeats:_described", "sampling_unit.contrast_repeats:_log_ratios", "sampling_unit.legend_text:described_rows", "sampling_unit.reading_text:change_words", "sampling_unit.repeat_plan:_change", "sampling_unit.repeat_plan:_test_values", "workflows._result_influence:_result"], "calls": ["?.all", "?.mean", "bool", "float", "len", "numpy.asarray", "numpy.exp", "numpy.log"], "complexity": 6, "decorators": [], "hash": "666a7d12c3ec6c41", "kind": "function", "lines": 8, "module": "_repeat_statistics", "name": "repeat_values", "public": true, "signature": "(means: np.ndarray, controls: np.ndarray, log: bool | None=None) -> tuple[str, np.ndarray, float]", "summary": "The values the paired test across repeats compares, from each repeat's mean of the", "varargs": []} -{"arguments": 3, "called_by": ["sampling_unit._discovery_tests:_effect", "sampling_unit.contrast_repeats:_described"], "calls": ["?.any", "?.mean", "float", "len", "numpy.asarray", "numpy.exp", "numpy.isnan", "scipy.stats.sem", "scipy.stats.t.ppf"], "complexity": 5, "decorators": [], "hash": "40691532b246de9a", "kind": "function", "lines": 9, "module": "_repeat_statistics", "name": "repeat_effect", "public": true, "signature": "(values: str, compared: np.ndarray, level: float=0.95) -> dict[str, float]", "summary": "The per-repeat contrasts in the feature's own terms (fold changes for ``normalised``", "varargs": []} +{"arguments": 3, "called_by": ["sampling_unit._discovery_tests:_effect", "sampling_unit.contrast_repeats:_described"], "calls": ["?.any", "?.mean", "ValueError", "_checks:is_share", "float", "len", "numpy.asarray", "numpy.exp", "numpy.isinf", "numpy.isnan", "scipy.stats.sem", "scipy.stats.t.ppf"], "complexity": 7, "decorators": [], "hash": "5d85489b4afffd5d", "kind": "function", "lines": 13, "module": "_repeat_statistics", "name": "repeat_effect", "public": true, "signature": "(values: str, compared: np.ndarray, level: float=0.95) -> dict[str, float]", "summary": "The per-repeat contrasts in the feature's own terms (fold changes for ``normalised``", "varargs": []} {"arguments": 2, "called_by": ["sampling_unit._discovery_tests:_effect", "sampling_unit.contrast_repeats:_described"], "calls": ["?.join", "float", "zip"], "complexity": 1, "decorators": [], "hash": "11ca49607fc255aa", "kind": "function", "lines": 1, "module": "_repeat_statistics", "name": "contrasts_text", "public": true, "signature": "(repeats: list, contrasts: np.ndarray) -> str", "summary": "``R1: 0.82; R2: 0.75; R3: 0.91``, each repeat's contrast for a CSV (4 significant", "varargs": []} {"arguments": 1, "called_by": ["sampling_unit.distribution:distribution_contrast"], "calls": ["_repeat_statistics:sarle", "float", "len", "numpy.asarray", "numpy.isfinite", "numpy.ptp", "scipy.stats.kurtosis", "scipy.stats.skew"], "complexity": 3, "decorators": [], "hash": "4d03e4478fdf0111", "kind": "function", "lines": 8, "module": "_repeat_statistics", "name": "bimodality_coefficient", "public": true, "signature": "(values: np.ndarray) -> float", "summary": "Sarle's bimodality coefficient ``(g1**2 + 1) / (G2 + 3 (n-1)**2 / ((n-2)(n-3)))`` with", "varargs": []} {"arguments": 3, "called_by": ["_repeat_statistics:bimodality_coefficient", "strategies._averaging_cv:_shape_warning"], "calls": [], "complexity": 1, "decorators": [], "hash": "80431ccee6f3f55e", "kind": "function", "lines": 1, "module": "_repeat_statistics", "name": "sarle", "public": true, "signature": "(skew: float, kurtosis: float, n: int) -> float", "summary": "Sarle's bimodality coefficient from the bias-corrected skewness and excess kurtosis", "varargs": []} {"arguments": 1, "called_by": ["sampling_unit.distribution:distribution_contrast"], "calls": ["float", "len", "numpy.asarray", "numpy.isfinite", "numpy.ptp", "scipy.stats.kurtosis"], "complexity": 3, "decorators": [], "hash": "e625790c74f19e86", "kind": "function", "lines": 5, "module": "_repeat_statistics", "name": "excess_kurtosis", "public": true, "signature": "(values: np.ndarray) -> float", "summary": "The bias-corrected excess kurtosis (``scipy.stats``, ``bias=False``); NaN below 4", "varargs": []} {"calls": [], "kind": "module", "module": "_robust_sd", "name": "", "public": false, "summary": "The robust SD of a sample or of each column, under one of two rules (private; re-exported"} -{"arguments": 1, "called_by": ["_robust_sd:robust_sd", "multivariate_outcomes:CovarianceError.evaluate", "strategies.support_novelty:_fold_failure", "transforms:_constant_reason"], "calls": ["?.mean", "?.std", "len", "numpy.abs", "numpy.ptp", "numpy.zeros"], "complexity": 2, "decorators": [], "hash": "eacd795d30e0d04f", "kind": "function", "lines": 4, "module": "_robust_sd", "name": "constant_columns", "public": true, "signature": "(matrix: np.ndarray) -> np.ndarray", "summary": "Which columns do not vary: identical values, or a spread that is rounding noise.", "varargs": []} +{"arguments": 1, "called_by": ["_robust_sd:robust_sd", "multivariate_outcomes:CovarianceError.evaluate", "strategies.support_novelty:_fold_failure", "transforms:_constant_reason"], "calls": ["?.mean", "?.std", "len", "numpy.abs", "numpy.ptp", "numpy.zeros"], "complexity": 2, "decorators": [], "hash": "5b7014377afbb11b", "kind": "function", "lines": 5, "module": "_robust_sd", "name": "constant_columns", "public": true, "signature": "(matrix: np.ndarray) -> np.ndarray", "summary": "Which columns do not vary: identical values, or a spread that is rounding noise.", "varargs": []} {"arguments": 3, "called_by": ["embedding:robust_scale", "retrospective.inspection:stands_out", "sampling_unit.acquisition:_scale"], "calls": ["?.std", "ValueError", "_robust_sd:constant_columns", "float", "len", "numpy.abs", "numpy.asarray", "numpy.median", "numpy.where", "numpy.zeros_like"], "complexity": 6, "decorators": [], "hash": "de85ede9cbc6a1a7", "kind": "function", "lines": 12, "module": "_robust_sd", "name": "robust_sd", "public": true, "signature": "(values: np.ndarray, rule: str, mad_to_sd: float=MAD_TO_SD) -> np.ndarray | float", "summary": "The robust SD of ``values`` (a float for one sample, one per column of a matrix", "varargs": []} {"calls": ["?.fromkeys", "_rule_names:_descriptor_plateau", "_rule_names:_descriptor_spread", "_rule_names:_fixed_area", "_rule_names:_fixed_fov", "_rule_names:_fixed_objects", "_rule_names:_fov_bootstrap", "_rule_names:_incidence", "_rule_names:_incidence_plan", "_rule_names:_precision_plan", "_rule_names:_precision_rule", "_rule_names:_rare_incidence", "_rule_names:_support_novelty"], "kind": "module", "module": "_rule_names", "name": "", "public": false, "summary": "The readable names of the known stopping-rule families (private), for _style.rule_label."} {"arguments": 2, "called_by": ["_rule_names:_descriptor_plateau", "_rule_names:_descriptor_spread", "_rule_names:_fixed_area", "_rule_names:_fixed_fov", "_rule_names:_fixed_objects", "_rule_names:_fov_bootstrap", "_rule_names:_incidence", "_rule_names:_precision_rule", "_rule_names:_rare_incidence", "_rule_names:_support_novelty"], "calls": ["?.get", "float", "isinstance"], "complexity": 6, "decorators": [], "hash": "5dc6cd3281822159", "kind": "function", "lines": 8, "module": "_rule_names", "name": "_threshold", "public": false, "signature": "(thresholds: Mapping[str, tuple[str, float]], parameters: Mapping[str, Any], *keys: str) -> float | None", "summary": "The first of ``keys`` among the thresholds, then among the parameters.", "varargs": ["*keys"]} @@ -378,9 +381,11 @@ {"calls": [], "kind": "module", "module": "_stage_coordinates", "name": "", "public": false, "summary": "One strict contract for stage coordinates (private; issue 232)."} {"arguments": 2, "called_by": ["_stage_coordinates:stage_matrix", "retrospective._replay_parts:_check_tables", "retrospective.inspection:_check", "retrospective.spatial:redundancy_distance"], "calls": ["TypeError", "ValueError", "all", "isinstance", "len", "metadata:column_names"], "complexity": 6, "decorators": [], "hash": "55f9309ac76fa854", "kind": "function", "lines": 6, "module": "_stage_coordinates", "name": "stage_names", "public": true, "signature": "(stage_cols: object, name: str='stage_cols') -> tuple[str, str]", "summary": "``stage_cols`` as two distinct column names (x, y), read once.", "varargs": []} {"arguments": 2, "called_by": ["_stage_coordinates:stage_matrix"], "calls": ["TypeError", "pandas.api.types.infer_dtype", "pandas.api.types.is_bool_dtype", "pandas.api.types.is_complex_dtype", "pandas.api.types.is_numeric_dtype"], "complexity": 6, "decorators": [], "hash": "223cd9907c9001cf", "kind": "function", "lines": 17, "module": "_stage_coordinates", "name": "_check_axis", "public": false, "signature": "(values: pd.Series, column: str) -> None", "summary": "A coordinate column is real numbers: never booleans, complex numbers or text. An untyped", "varargs": []} -{"arguments": 4, "called_by": ["order_check:_positions", "reservoir:spatial_blocks", "retrospective._replay_parts:_check_tables", "retrospective._stage_neighbours:neighbour_rows", "retrospective.spatial:_measured", "retrospective.spatial:redundancy_distance", "spatial:fov_semivariogram"], "calls": ["?.to_numpy", "ValueError", "_stage_coordinates:_check_axis", "_stage_coordinates:_check_values", "_stage_coordinates:stage_names"], "complexity": 3, "decorators": [], "hash": "e64e0c4deeaecd6d", "kind": "function", "lines": 11, "module": "_stage_coordinates", "name": "stage_matrix", "public": true, "signature": "(table: pd.DataFrame, stage_cols: object, *, missing: Missing='refuse', name: str='stage_cols') -> np.ndarray", "summary": "The ``(n, 2)`` float positions of the rows of ``table`` (see the module).", "varargs": []} +{"arguments": 4, "called_by": ["order_check:_positions", "reservoir:spatial_blocks", "retrospective._replay_parts:_check_tables", "retrospective._stage_neighbours:neighbour_rows", "retrospective.spatial:_measured", "retrospective.spatial:redundancy_distance", "spatial:fov_semivariogram"], "calls": ["ValueError", "_stage_coordinates:_axis_floats", "_stage_coordinates:_check_axis", "_stage_coordinates:_check_values", "_stage_coordinates:stage_names", "numpy.column_stack"], "complexity": 3, "decorators": [], "hash": "37a3e4493fe7af14", "kind": "function", "lines": 11, "module": "_stage_coordinates", "name": "stage_matrix", "public": true, "signature": "(table: pd.DataFrame, stage_cols: object, *, missing: Missing='refuse', name: str='stage_cols') -> np.ndarray", "summary": "The ``(n, 2)`` float positions of the rows of ``table`` (see the module).", "varargs": []} +{"arguments": 2, "called_by": ["_stage_coordinates:stage_matrix"], "calls": ["?.to_numpy", "ValueError", "_stage_coordinates:_check_exact"], "complexity": 2, "decorators": [], "hash": "8b2d264c76e6aacc", "kind": "function", "lines": 9, "module": "_stage_coordinates", "name": "_axis_floats", "public": false, "signature": "(values: pd.Series, column: str) -> np.ndarray", "summary": "A checked coordinate column as floats: a value too large for a float is refused as", "varargs": []} +{"arguments": 3, "called_by": ["_stage_coordinates:_axis_floats", "_stage_coordinates:check_xy"], "calls": ["ValueError", "int", "isinstance", "numpy.abs", "numpy.flatnonzero", "numpy.nan_to_num"], "complexity": 4, "decorators": [], "hash": "306f19c1991bac3e", "kind": "function", "lines": 8, "module": "_stage_coordinates", "name": "_check_exact", "public": false, "signature": "(raw: np.ndarray, floats: np.ndarray, name: str) -> None", "summary": "Refuse an integer of ``raw`` that its float in ``floats`` does not hold exactly; only", "varargs": []} {"arguments": 2, "called_by": ["_stage_coordinates:check_xy", "_stage_coordinates:stage_matrix"], "calls": ["?.any", "ValueError", "numpy.isinf", "numpy.isnan"], "complexity": 4, "decorators": [], "hash": "5ee498a027e26228", "kind": "function", "lines": 4, "module": "_stage_coordinates", "name": "_check_values", "public": false, "signature": "(xy: np.ndarray, missing: Missing) -> None", "summary": "", "varargs": []} -{"arguments": 3, "called_by": ["retrospective.stage:dispersed_order", "retrospective.stage:stage_travel"], "calls": ["?.astype", "TypeError", "ValueError", "_stage_coordinates:_check_values", "numpy.asarray"], "complexity": 4, "decorators": [], "hash": "02cfb1fe0cf440c8", "kind": "function", "lines": 8, "module": "_stage_coordinates", "name": "check_xy", "public": true, "signature": "(xy: Any, name: str='xy', *, missing: Missing='refuse') -> np.ndarray", "summary": "``xy`` as a float ``(n, 2)`` array of real, finite positions (booleans, complex numbers", "varargs": []} +{"arguments": 3, "called_by": ["retrospective.stage:dispersed_order", "retrospective.stage:stage_travel"], "calls": ["?.astype", "TypeError", "ValueError", "_stage_coordinates:_check_exact", "_stage_coordinates:_check_values", "numpy.asarray"], "complexity": 5, "decorators": [], "hash": "0cc6a73cef64debd", "kind": "function", "lines": 10, "module": "_stage_coordinates", "name": "check_xy", "public": true, "signature": "(xy: Any, name: str='xy', *, missing: Missing='refuse') -> np.ndarray", "summary": "``xy`` as a float ``(n, 2)`` array of real, finite positions (booleans, complex numbers", "varargs": []} {"calls": ["?.join", "_style:Status", "map", "re.compile"], "kind": "module", "module": "_style", "name": "", "public": false, "summary": "Shared style of the text output (private): status markers, labels, tables, wrapping."} {"called_by": ["_fitted:_continues", "_fitted:_inner", "_fitted:fitted", "_style:", "_style:headline", "_style:worst", "retrospective.report_status:", "retrospective.report_status_conditions:", "retrospective.report_status_plan:"], "calls": [], "decorators": [], "hash": "3526d40d8e4b469f", "kind": "class", "module": "_style", "name": "Status", "public": true, "signature": "(Enum)", "summary": "The status of one answer; its ``marker`` opens the answer's line."} {"arguments": 0, "called_by": [], "calls": [], "complexity": 1, "decorators": ["property"], "hash": "afe043325831bba2", "kind": "property", "lines": 1, "module": "_style", "name": "Status.marker", "public": true, "signature": "(self) -> str", "summary": "The emoji marker: ✅, ⚠️, ❌ or ➖.", "varargs": []} @@ -424,7 +429,7 @@ {"arguments": 3, "called_by": ["_copy_rules:check_copies", "_data_check_steps:_understand_sizes", "_data_problems:_examples", "_data_rules:_check_control", "_data_rules:_check_fov_table", "_feature_rules:_check_missing_features", "_input_traps:_check_undeclared_groups", "_input_traps:_check_unimaged_technical_repeats", "_input_traps:warn_invalid_rows", "_integrity_tables:integrity_by_table", "_integrity_text:_capped", "_integrity_text:_checked", "_integrity_text:_coverage", "_integrity_text:_finding_lines", "_integrity_text:_finding_table", "_integrity_text:_verdict", "_observation_keys:match_problems", "_observation_keys:metadata_problems", "_observation_keys:missing_identity", "_observation_keys:observed_keys", "_plane_rules:_check_planes_within_fields", "_plane_rules:_check_positions_within_fields", "_rule_names:_descriptor_plateau", "_rule_names:_fixed_fov", "_rule_names:_fixed_objects", "_rule_names:_precision_plan", "_rule_names:_precision_rule", "_wording:features_counted", "_wording:fields", "data_check:DataCheck.summary", "data_check:check_tables", "feature_tables:FeatureTables.lines", "feature_tables:_column_problems", "order_check:OrderCheck._coverage", "order_check:OrderCheck.caution", "planes:_check_one_row_per_plane", "plots_embedding:embedding_figures", "results:StrategyResult._fovs", "results:StrategyResult._observations", "results:_component_entry", "retrospective._field_reasons:_counts", "retrospective._field_reasons:_novel.detail", "retrospective._stage_neighbours:_neighbour_words", "retrospective._value_checks:alike_fields", "retrospective._value_checks:few_values", "retrospective.controls_text:_empty_line", "retrospective.effect_preservation:_summary", "retrospective.effort_text:_allocation_line", "retrospective.effort_text:_counts_lines", "retrospective.effort_text:effort_short_parts", "retrospective.effort_text:share_caveat", "retrospective.inspection_text:inspection_parts", "retrospective.order_text:_cells", "retrospective.order_text:_order_rows", "retrospective.order_text:_unjudged_caution", "retrospective.order_text:order_parts", "retrospective.overview:DatasetOverview._closing_lines", "retrospective.overview:DatasetOverview._columns_line", "retrospective.overview:DatasetOverview._design_line", "retrospective.overview:DatasetOverview._full", "retrospective.overview:DatasetOverview._grouping_lines", "retrospective.overview:DatasetOverview._technical_line", "retrospective.overview:DatasetOverview._wells", "retrospective.overview:DatasetOverview.short_lines", "retrospective.overview:_sub_experiments", "retrospective.protocol_text:_difficulty", "retrospective.protocol_text:_few", "retrospective.protocol_text:_needed", "retrospective.protocol_text:_validation", "retrospective.protocol_text:protocol_full_parts", "retrospective.reliability:_skip_reason", "retrospective.reliability_text:_basis_line", "retrospective.reliability_text:_repeat_warning", "retrospective.reliability_text:_row_cells", "retrospective.reliability_text:reliability_short_parts", "retrospective.report:opening", "retrospective.report_profile:_redundancy_rows", "retrospective.report_resolved:resolved_headline", "retrospective.report_resolved:resolved_parts", "retrospective.report_sampling:_fields_line", "retrospective.report_sampling:clustered_states", "retrospective.report_sampling:spread_headline", "retrospective.report_status:_count_rule_part", "retrospective.report_status:_data_rules_status", "retrospective.report_status:_rules_said", "retrospective.report_status:data_check_status", "retrospective.report_status:inspect_status", "retrospective.report_status:integrity_status", "retrospective.report_status:order_status", "retrospective.report_status:profile_status", "retrospective.report_status_conditions:_discovery_headline", "retrospective.report_status_conditions:_ranking_answer", "retrospective.report_status_conditions:_reading_parts", "retrospective.report_status_conditions:across_headline", "retrospective.report_status_plan:_reliability_status", "retrospective.report_status_plan:effort_status", "retrospective.report_status_plan:next_time_status", "sampling_unit._state_text:_space", "sampling_unit._state_text:_state_answer", "sampling_unit._state_text:_technical_lines", "sampling_unit._state_text:_unusual_cautions", "sampling_unit._state_text:unusual_parts", "sampling_unit._unit_text:_single_parts", "sampling_unit._unit_text:one_per_field_rows", "sampling_unit._unit_text:variability_parts", "sampling_unit.acquisition:AcquisitionAnomalies._scope", "sampling_unit.acquisition:AcquisitionAnomalies.line", "sampling_unit.across_text:_others", "sampling_unit.cells_text:_pooled_from", "sampling_unit.cells_text:_sparse", "sampling_unit.contrast_text:_test_sentence", "sampling_unit.contrast_text:_tests_short", "sampling_unit.contrast_text:contrast_parts", "sampling_unit.discovery:FeatureDiscovery._head", "sampling_unit.discovery:FeatureDiscovery._of", "sampling_unit.distribution:tests_words", "sampling_unit.distribution:unassessed_words", "sampling_unit.legend_text:_families", "sampling_unit.legend_text:n_sentence", "sampling_unit.ranking:FeatureRanking._head", "sampling_unit.ranking:FeatureRanking._short_head", "sampling_unit.ranking:FeatureRanking._unranked", "sampling_unit.reading_text:_bridged", "sampling_unit.reading_text:_design", "sampling_unit.reading_text:_paired", "sampling_unit.reading_text:_reagents", "sampling_unit.reading_text:readings_headline", "sampling_unit.reading_text:shared_control_line", "sampling_unit.reagents_text:reagents_headline", "sampling_unit.repeat_plan_text:_plan_head", "sampling_unit.repeats_text:_repeat_head", "sampling_unit.repeats_text:_untested_notes", "schema:_validate_input_tables", "separation:Separation.line", "strategies.base:check_order_col", "strategies.novelty_null:not_informative", "sufficiency_full:_few_line", "sufficiency_full:_group_block", "sufficiency_full:_group_table", "sufficiency_full:_needed_line", "sufficiency_full:_next_field_lines", "sufficiency_short:_few_lines", "sufficiency_short:_one_more_field", "sufficiency_short:met_count", "sufficiency_text:_more_fovs", "sufficiency_text:_other_fovs", "sufficiency_text:_stops_clause", "sufficiency_text:_unseen_line", "sufficiency_text:novelty_definition", "workflows._acquisition_block:with_acquisition", "workflows._declaration:_new_words", "workflows._declaration:_positive", "workflows._declaration:_representation", "workflows._declaration:_representation_line", "workflows._declaration_rare:rare_line", "workflows._declaration_rare:rare_short", "workflows._distribution:distribution_text", "workflows._distribution:split_words", "workflows._document:_technical_repeats", "workflows._document:_with_integrity", "workflows._embedding_report:plan_document", "workflows._enough_features:_precision_cell", "workflows._enough_features:_too_small", "workflows._enough_features:features_status", "workflows._enough_features:with_features", "workflows._enough_targets:_left_out", "workflows._enough_targets:fingerprint_lines", "workflows._enough_targets:not_judged", "workflows._enough_targets:partly_undefined", "workflows._enough_targets:rare_lines", "workflows._feature_space:features_words", "workflows._feature_space:table_lines", "workflows._feature_space:unusual_space", "workflows._fingerprint_space:FingerprintSpace.small_groups", "workflows._fingerprint_space:Reading.words", "workflows._fingerprint_space:_read", "workflows._guided_tables:ask_tables", "workflows._html_cards:_condition_words", "workflows._html_cards:significant_summary", "workflows._html_enough:_criterion_line", "workflows._html_enough:_named", "workflows._html_enough:_rare_target", "workflows._html_enough:_single_answer", "workflows._html_enough:compact_table", "workflows._html_enough:few_repeats", "workflows._html_map_text:combined_words", "workflows._html_next:_where", "workflows._html_plan:_declared_goals", "workflows._html_plan:_group_goals", "workflows._html_plan:_live_rare", "workflows._html_sections:_resolution", "workflows._html_sections:what_checked", "workflows._html_tests:_family", "workflows._label_control:_reason", "workflows._label_control:label_answer", "workflows._live_text:_evidence", "workflows._live_text:_read", "workflows._live_text:_short", "workflows._manifest:ManifestReader._changed", "workflows._manifest:write_fov", "workflows._one_per_field:listed_once", "workflows._population_spaces:no_own_control_words", "workflows._population_spaces:spaces_method", "workflows._population_text_parts:no_group_answer", "workflows._population_text_parts:population_method", "workflows._populations:_found_words", "workflows._rare_share:unlabelled_note", "workflows._scan_rules:_balance_findings", "workflows._scan_rules:_copy_finding", "workflows._scan_rules:fields_line", "workflows._scan_rules:questions", "workflows._scan_rules:repeat_lines", "workflows._scan_text:_features_line", "workflows._scan_text:_targets_line", "workflows._scan_text:_title", "workflows._shared:check_workflow_inputs", "workflows._whole_table:_line", "workflows._whole_table:whole_headline", "workflows._whole_table:whole_table_lines", "workflows.benchmarks:Benchmark.summary", "workflows.benchmarks:_short_warnings", "workflows.guided:_run_report", "workflows.setup:Setup.criteria"], "calls": ["?._plural", "_wording:number", "_wording:plural"], "complexity": 3, "decorators": [], "hash": "8c4c0c7fc9a68ff1", "kind": "function", "lines": 3, "module": "_wording", "name": "count", "public": true, "signature": "(n: float, word: str, plural: str | None=None) -> str", "summary": "``1 field``, ``3 fields``, ``2.5 fields`` (``plural`` defaults to ``plural(word)``).", "varargs": []} {"arguments": 3, "called_by": ["sampling_unit._experiments:family_words", "sampling_unit.cells_text:_family_note", "sampling_unit.discovery:FeatureDiscovery._counted", "sampling_unit.legend_text:_families", "sampling_unit.ranking:FeatureRanking._short_head"], "calls": ["_checks:is_integer", "_wording:count", "int", "len", "set"], "complexity": 6, "decorators": [], "hash": "1c124d5118467e07", "kind": "function", "lines": 5, "module": "_wording", "name": "features_counted", "public": true, "signature": "(names: Sequence[Any] | int, share: str | None=None, join: str=' and ') -> str", "summary": "``5 features``, or with a labelled state's ``share`` among ``names`` (a number counts", "varargs": []} {"arguments": 1, "called_by": ["_observation_units:unit_plural", "_rule_names:_fixed_objects", "_rule_names:_precision_plan", "_rule_names:_support_novelty", "_style:among", "_wording:", "_wording:count", "integrity:integrity_checks", "retrospective.controls_text:pooled_over", "retrospective.protocol_text:_words", "retrospective.report_status_plan:effort_status", "retrospective.report_status_plan:next_time_status", "sampling_unit.distribution:_counted", "strategies._precision_steps:_cautions", "strategies._precision_steps:_fov_estimate", "strategies.jcb_planning:plan_objects_to_average", "strategies.scalar_precision:ScalarPrecisionEstimator._evidence", "strategies.scalar_precision:ScalarPrecisionEstimator._precision_from", "strategies.stabilization:_no_spread_reason", "sufficiency_short:uniformity_assumption", "workflows._declaration:_unusual_words", "workflows._enough_targets:rare_lines", "workflows._enough_targets:with_targets", "workflows._html_enough:_fingerprint_tab", "workflows._html_enough:_seen_by_condition", "workflows._html_plan:_fingerprint_note", "workflows._label_control:label_answer", "workflows._live_text:_effort_words", "workflows._live_text:_short", "workflows._shared_parts:unusual_result"], "calls": ["?.endswith", "len"], "complexity": 7, "decorators": [], "hash": "32c38fec51e55c72", "kind": "function", "lines": 9, "module": "_wording", "name": "plural", "public": true, "signature": "(word: str) -> str", "summary": "The plural of a unit's name: ``nuclei``, ``patches``, ``colonies``, ``wells``.", "varargs": []} -{"arguments": 2, "called_by": ["_control:_check_unique", "_control:not_found", "_data_problems:_names", "_integrity_tables:_findings", "_integrity_tables:integrity_by_table", "_integrity_text:_finding_table", "_integrity_text:_skipped", "_observation_keys:_type_problems", "_observation_keys:missing_identity", "_observation_keys:shown_keys", "_within_identity:absent_identity_text", "_wording:contrasts_words", "described:ControlSource.sentences", "described:DescribedExperiment.summary", "described:TargetSuggestions.lines", "described:_missing_reason", "described:_one_description", "described:targets_line", "feature_tables:FeatureTables.lines", "feature_tables:_column_problems", "integrity:integrity_checks", "normalize:control_mean_problem", "normalize:negative_values_sentence", "results:StrategyResult._decision_words", "retrospective._feature_relations:group_sentence", "retrospective._feature_relations:place_sentence", "retrospective._feature_relations:relation_checks", "retrospective._report_assembly:_first_notes", "retrospective._value_checks:alike_fields", "retrospective._value_checks:few_values", "retrospective.adequacy_text:_named", "retrospective.adequacy_text:adequacy_short_parts", "retrospective.calibration:_calibration_head", "retrospective.effort_text:_short_skipped", "retrospective.effort_text:_where", "retrospective.inspection_text:_skipped", "retrospective.order_text:_full", "retrospective.order_text:order_parts", "retrospective.overview:DatasetOverview.arrangement", "retrospective.overview:_sub_experiments", "retrospective.reliability_text:_counts_text", "retrospective.reliability_text:_groups_named", "retrospective.report:MicroscopistReport.at_a_glance", "retrospective.report:opening", "retrospective.report_sampling:_seen_states", "retrospective.report_sampling:_variance_line", "retrospective.report_sampling:skipped_strata", "retrospective.report_sampling:states_lines", "retrospective.report_status:data_check_status", "retrospective.report_status:overview_status", "retrospective.report_status_conditions:_discovery_answer", "retrospective.report_status_conditions:_discovery_headline", "retrospective.report_status_conditions:_trends", "retrospective.report_status_plan:_reliability_status", "sampling_unit._discovery_tests:resting_words", "sampling_unit._experiments:control_only", "sampling_unit._experiments:left_out", "sampling_unit._experiments:not_compared", "sampling_unit._state_text:_clustering_cautions", "sampling_unit._state_text:_state_answer", "sampling_unit._state_text:_unusual_cautions", "sampling_unit._state_text:background", "sampling_unit._unit_text:_by_reason", "sampling_unit._unit_text:_rule_cautions", "sampling_unit._unit_text:_variability_cautions", "sampling_unit._unit_text:descriptor_spread_parts", "sampling_unit._unit_text:object_rule_parts", "sampling_unit._units:opposite_signs", "sampling_unit.acquisition:AcquisitionAnomalies._how", "sampling_unit.acquisition:AcquisitionAnomalies.line", "sampling_unit.across_text:_fallback_lines", "sampling_unit.across_text:_gap_note", "sampling_unit.across_text:_master", "sampling_unit.across_text:_not_compared", "sampling_unit.across_text:_repeat_names", "sampling_unit.cells_text:_control_only", "sampling_unit.cells_text:_pooled_from", "sampling_unit.cells_text:_pooled_note", "sampling_unit.cells_text:_sparse", "sampling_unit.cells_text:_which", "sampling_unit.contrast_text:_cautions", "sampling_unit.contrast_text:_tests_short", "sampling_unit.contrast_text:_untested", "sampling_unit.discovery:FeatureDiscovery._cautions", "sampling_unit.discovery:FeatureDiscovery._confirmed_where", "sampling_unit.discovery:FeatureDiscovery._unranked", "sampling_unit.distribution:_counted", "sampling_unit.distribution:_reasons", "sampling_unit.legend_text:_families", "sampling_unit.reading_text:_design", "sampling_unit.reading_text:_reagents", "sampling_unit.reading_text:readings_headline", "sampling_unit.reading_text:readings_parts", "sampling_unit.reading_text:shared_control_line", "sampling_unit.repeat_plan_text:_unplanned", "sampling_unit.repeats_text:_short_paired_note", "sampling_unit.repeats_text:_untested_notes", "separation:Separation.line", "strategies._fov_bootstrap_checks:_too_few_reason", "strategies.jcb_planning:_samples", "strategies.novelty_null:uninformative_line", "strategies.support_novelty:_fold_failure", "sufficiency_full:_group_notes", "sufficiency_short:_labels", "sufficiency_short:_novelty_lines", "sufficiency_short:_one_more_field", "sufficiency_short:_rule_cautions", "sufficiency_short:_stop_cautions", "sufficiency_short:_warning_cautions", "sufficiency_text:novelty_definition", "transforms:missing_values_reason", "workflows._acquisition_gap:gap_maps_line", "workflows._contrasts:_nothing_under", "workflows._contrasts:controls_sentence", "workflows._contrasts:left_out_sentence", "workflows._declaration:_live_decision_short", "workflows._declaration:_order", "workflows._declaration:_order_short", "workflows._declaration:_positive", "workflows._declaration:_rules", "workflows._declaration:_rules_short", "workflows._described:_chosen_text", "workflows._described:check_described", "workflows._distribution:_condition_line", "workflows._distribution:distribution_headline", "workflows._distribution:split_words", "workflows._document:_left_out", "workflows._document:_with_integrity", "workflows._document:coverage_notes", "workflows._enough_features:_for", "workflows._enough_features:_too_small", "workflows._enough_targets:_left_out", "workflows._exploratory:exploratory_line", "workflows._feature_space:_centre_words", "workflows._feature_space:centring_line", "workflows._feature_space:check_feature_tables", "workflows._feature_space:explainable_line", "workflows._feature_space:unusual_space", "workflows._fingerprint_space:FingerprintSpace.small_groups", "workflows._fingerprint_space:Reading.words", "workflows._fingerprint_space:plain", "workflows._guided_ask:ask_scales", "workflows._guided_ask:ask_tolerance", "workflows._guided_ask:choose_many", "workflows._guided_controls:ask_experiment", "workflows._guided_described:ask_targets", "workflows._html_cards:_condition_words", "workflows._html_cards:readout_summary", "workflows._html_cards:significant_summary", "workflows._html_enough:_named", "workflows._html_enough:_needs", "workflows._html_enough:_seen_by_condition", "workflows._html_next:_repeats_line", "workflows._html_next:_where", "workflows._html_plan:_difference_goal", "workflows._html_plan:_tolerances", "workflows._html_sections:_rules", "workflows._html_sections:what_checked", "workflows._html_tests:_cells_caption", "workflows._html_tests:_other_versions", "workflows._label_control:label_answer", "workflows._live_text:_cautions", "workflows._live_text:headline", "workflows._population_context:few_words", "workflows._population_spaces:found_words", "workflows._population_spaces:no_own_control_words", "workflows._population_spaces:spaces_method", "workflows._population_spaces:undescribed_line", "workflows._population_text_parts:unpaired_lines", "workflows._populations:_finding", "workflows._populations:_groups_table", "workflows._scan_rules:_balance_findings", "workflows._scan_rules:_copy_finding", "workflows._scan_rules:_described_findings", "workflows._scan_rules:_target_suggestion", "workflows._scan_rules:questions", "workflows._scan_rules:repeat_lines", "workflows._scan_rules:suggestions", "workflows._scan_text:_conditions_line", "workflows._scan_text:_features_line", "workflows._scan_text:_options", "workflows._scan_text:_targets_line", "workflows._whole_table:whole_headline", "workflows.benchmarks:_benchmark_settings", "workflows.guided:Answers.lines", "workflows.guided:_saved", "workflows.html_report:_data_card"], "calls": ["?.join", "len", "str"], "complexity": 3, "decorators": [], "hash": "060e6929a532f16d", "kind": "function", "lines": 6, "module": "_wording", "name": "listing", "public": true, "signature": "(items: Sequence[object], limit: int=5) -> str", "summary": "``a, b and c``, or ``a, b, c, d, e and 3 more`` beyond ``limit`` items.", "varargs": []} +{"arguments": 2, "called_by": ["_control:_check_unique", "_control:not_found", "_data_problems:_names", "_integrity_tables:_findings", "_integrity_tables:integrity_by_table", "_integrity_text:_finding_table", "_integrity_text:_skipped", "_observation_keys:_type_problems", "_observation_keys:missing_identity", "_observation_keys:shown_keys", "_within_identity:absent_identity_text", "_wording:contrasts_words", "described:ControlSource.sentences", "described:DescribedExperiment.summary", "described:TargetSuggestions.lines", "described:_missing_reason", "described:_one_description", "described:targets_line", "feature_tables:FeatureTables.lines", "feature_tables:_column_problems", "integrity:integrity_checks", "normalize:control_mean_problem", "normalize:negative_values_sentence", "results:StrategyResult._decision_words", "retrospective._feature_relations:group_sentence", "retrospective._feature_relations:place_sentence", "retrospective._feature_relations:relation_checks", "retrospective._report_assembly:_first_notes", "retrospective._value_checks:alike_fields", "retrospective._value_checks:few_values", "retrospective.adequacy_text:_named", "retrospective.adequacy_text:adequacy_short_parts", "retrospective.calibration:_calibration_head", "retrospective.effort_text:_short_skipped", "retrospective.effort_text:_where", "retrospective.inspection_text:_skipped", "retrospective.order_text:_full", "retrospective.order_text:order_parts", "retrospective.overview:DatasetOverview.arrangement", "retrospective.overview:_sub_experiments", "retrospective.reliability_text:_counts_text", "retrospective.reliability_text:_groups_named", "retrospective.report:MicroscopistReport.at_a_glance", "retrospective.report:opening", "retrospective.report_sampling:_seen_states", "retrospective.report_sampling:_variance_line", "retrospective.report_sampling:skipped_strata", "retrospective.report_sampling:states_lines", "retrospective.report_status:data_check_status", "retrospective.report_status:overview_status", "retrospective.report_status_conditions:_discovery_answer", "retrospective.report_status_conditions:_discovery_headline", "retrospective.report_status_conditions:_trends", "retrospective.report_status_plan:_reliability_status", "sampling_unit._discovery_tests:resting_words", "sampling_unit._experiments:control_only", "sampling_unit._experiments:left_out", "sampling_unit._experiments:not_compared", "sampling_unit._state_text:_clustering_cautions", "sampling_unit._state_text:_state_answer", "sampling_unit._state_text:_unusual_cautions", "sampling_unit._state_text:background", "sampling_unit._unit_text:_by_reason", "sampling_unit._unit_text:_rule_cautions", "sampling_unit._unit_text:_variability_cautions", "sampling_unit._unit_text:descriptor_spread_parts", "sampling_unit._unit_text:object_rule_parts", "sampling_unit._units:opposite_signs", "sampling_unit.acquisition:AcquisitionAnomalies._how", "sampling_unit.acquisition:AcquisitionAnomalies.line", "sampling_unit.across_text:_fallback_lines", "sampling_unit.across_text:_gap_note", "sampling_unit.across_text:_master", "sampling_unit.across_text:_not_compared", "sampling_unit.across_text:_repeat_names", "sampling_unit.cells_text:_control_only", "sampling_unit.cells_text:_pooled_from", "sampling_unit.cells_text:_pooled_note", "sampling_unit.cells_text:_sparse", "sampling_unit.cells_text:_which", "sampling_unit.contrast_text:_cautions", "sampling_unit.contrast_text:_tests_short", "sampling_unit.contrast_text:_untested", "sampling_unit.discovery:FeatureDiscovery._cautions", "sampling_unit.discovery:FeatureDiscovery._confirmed_where", "sampling_unit.discovery:FeatureDiscovery._unranked", "sampling_unit.distribution:_counted", "sampling_unit.distribution:_reasons", "sampling_unit.legend_text:_families", "sampling_unit.reading_text:_design", "sampling_unit.reading_text:_reagents", "sampling_unit.reading_text:readings_headline", "sampling_unit.reading_text:readings_parts", "sampling_unit.reading_text:shared_control_line", "sampling_unit.repeat_plan_text:_unplanned", "sampling_unit.repeats_text:_short_paired_note", "sampling_unit.repeats_text:_untested_notes", "separation:Separation.line", "strategies._fov_bootstrap_checks:_too_few_reason", "strategies.jcb_planning:_refuse_mixed_samples", "strategies.jcb_planning:_samples", "strategies.novelty_null:uninformative_line", "strategies.support_novelty:_fold_failure", "sufficiency_full:_group_notes", "sufficiency_short:_labels", "sufficiency_short:_novelty_lines", "sufficiency_short:_one_more_field", "sufficiency_short:_rule_cautions", "sufficiency_short:_stop_cautions", "sufficiency_short:_warning_cautions", "sufficiency_text:novelty_definition", "transforms:missing_values_reason", "workflows._acquisition_gap:gap_maps_line", "workflows._contrasts:_nothing_under", "workflows._contrasts:controls_sentence", "workflows._contrasts:left_out_sentence", "workflows._declaration:_live_decision_short", "workflows._declaration:_order", "workflows._declaration:_order_short", "workflows._declaration:_positive", "workflows._declaration:_rules", "workflows._declaration:_rules_short", "workflows._described:_chosen_text", "workflows._described:check_described", "workflows._distribution:_condition_line", "workflows._distribution:distribution_headline", "workflows._distribution:split_words", "workflows._document:_left_out", "workflows._document:_with_integrity", "workflows._document:coverage_notes", "workflows._enough_features:_for", "workflows._enough_features:_too_small", "workflows._enough_targets:_left_out", "workflows._exploratory:exploratory_line", "workflows._feature_space:_centre_words", "workflows._feature_space:centring_line", "workflows._feature_space:check_feature_tables", "workflows._feature_space:explainable_line", "workflows._feature_space:unusual_space", "workflows._fingerprint_space:FingerprintSpace.small_groups", "workflows._fingerprint_space:Reading.words", "workflows._fingerprint_space:plain", "workflows._guided_ask:ask_scales", "workflows._guided_ask:ask_tolerance", "workflows._guided_ask:choose_many", "workflows._guided_controls:ask_experiment", "workflows._guided_described:ask_targets", "workflows._html_cards:_condition_words", "workflows._html_cards:readout_summary", "workflows._html_cards:significant_summary", "workflows._html_enough:_named", "workflows._html_enough:_needs", "workflows._html_enough:_seen_by_condition", "workflows._html_next:_repeats_line", "workflows._html_next:_where", "workflows._html_plan:_difference_goal", "workflows._html_plan:_tolerances", "workflows._html_sections:_rules", "workflows._html_sections:what_checked", "workflows._html_tests:_cells_caption", "workflows._html_tests:_other_versions", "workflows._label_control:label_answer", "workflows._live_text:_cautions", "workflows._live_text:headline", "workflows._population_context:few_words", "workflows._population_spaces:found_words", "workflows._population_spaces:no_own_control_words", "workflows._population_spaces:spaces_method", "workflows._population_spaces:undescribed_line", "workflows._population_text_parts:unpaired_lines", "workflows._populations:_finding", "workflows._populations:_groups_table", "workflows._scan_rules:_balance_findings", "workflows._scan_rules:_copy_finding", "workflows._scan_rules:_described_findings", "workflows._scan_rules:_target_suggestion", "workflows._scan_rules:questions", "workflows._scan_rules:repeat_lines", "workflows._scan_rules:suggestions", "workflows._scan_text:_conditions_line", "workflows._scan_text:_features_line", "workflows._scan_text:_options", "workflows._scan_text:_targets_line", "workflows._whole_table:whole_headline", "workflows.benchmarks:_benchmark_settings", "workflows.guided:Answers.lines", "workflows.guided:_saved", "workflows.html_report:_data_card"], "calls": ["?.join", "len", "str"], "complexity": 3, "decorators": [], "hash": "060e6929a532f16d", "kind": "function", "lines": 6, "module": "_wording", "name": "listing", "public": true, "signature": "(items: Sequence[object], limit: int=5) -> str", "summary": "``a, b and c``, or ``a, b, c, d, e and 3 more`` beyond ``limit`` items.", "varargs": []} {"arguments": 1, "called_by": ["retrospective._feature_relations:group_sentence", "retrospective._feature_relations:place_sentence", "workflows._html_enough:_seen_by_condition", "workflows._html_enough:answer_lines"], "calls": ["?.join", "len"], "complexity": 2, "decorators": [], "hash": "28e2c49711060b7a", "kind": "function", "lines": 3, "module": "_wording", "name": "joined_clauses", "public": true, "signature": "(clauses: Sequence[str]) -> str", "summary": "``a``, ``a, and b``, ``a, b, and c``: the clauses hold \"and\" of their own.", "varargs": []} {"arguments": 1, "called_by": ["retrospective.calibration:_never_cell", "retrospective.frontier_text:_baseline_text", "retrospective.frontier_text:_full_lines", "retrospective.frontier_text:_unscored", "retrospective.frontier_text:level_status", "retrospective.inspection_text:inspection_parts", "retrospective.order_text:_cells", "retrospective.order_text:_full", "retrospective.protocol_text:_validation", "retrospective.protocol_text:served_cell", "retrospective.report_status_plan:_reliability_status", "retrospective.report_status_plan:next_time_status", "retrospective.spatial:_group_row", "workflows._document:held_back_text", "workflows.benchmarks:_benchmark_settings"], "calls": ["_wording:count"], "complexity": 1, "decorators": [], "hash": "3fe450619e8c2b12", "kind": "function", "lines": 1, "module": "_wording", "name": "fields", "public": true, "signature": "(n: float) -> str", "summary": "``1 field``, ``12 fields``, ``2.5 fields``.", "varargs": []} {"arguments": 1, "called_by": ["retrospective.order_text:_cells", "retrospective.order_text:_order_rows", "workflows.guided:_run_report"], "calls": ["_wording:number", "float"], "complexity": 3, "decorators": [], "hash": "d45d7d420f356225", "kind": "function", "lines": 6, "module": "_wording", "name": "duration", "public": true, "signature": "(seconds: float) -> str", "summary": "``45 s``, ``12 min``, ``1.5 h``: never ``0 min`` for a short time.", "varargs": []} @@ -453,7 +458,7 @@ {"arguments": 2, "called_by": [], "calls": ["?.assign", "ValueError", "any", "benchmark:permuted_fovs", "len", "list", "numpy.arange", "pandas.concat"], "complexity": 4, "decorators": [], "hash": "99b3ffbcc4449b8f", "kind": "method", "lines": 18, "module": "benchmark", "name": "AcquisitionOrder.apply", "public": true, "signature": "(self, groups: Iterable[tuple[Mapping[str, Any], ValidatedInput]], order_col: str) -> tuple[pd.DataFrame, str]", "summary": "The FOV rows of the analysis ``groups`` with the order to replay, and its column.", "varargs": []} {"arguments": 4, "called_by": ["benchmark:AcquisitionOrder.apply", "retrospective.replay:_ordered_stream"], "calls": ["?.permutation", "_seeds:group_rng", "len", "metadata:sorted_by_key"], "complexity": 1, "decorators": [], "hash": "ff6a0edf627ecdb6", "kind": "function", "lines": 3, "module": "benchmark", "name": "permuted_fovs", "public": true, "signature": "(fovs: pd.DataFrame, fov_key: Sequence[str], random_state: int, group: Mapping[str, Any], *more: int) -> pd.DataFrame", "summary": "One analysis group's FOV rows in a seeded uniformly random order of whole FOVs.", "varargs": ["*more"]} {"called_by": ["benchmark:_record_run"], "calls": ["_frozen:owned", "dataclasses.dataclass"], "decorators": ["owned('group', 'outcomes', 'outcome_ids', 'reservoir')", "dataclass(frozen=True)"], "hash": "94b27c202322e04d", "kind": "class", "module": "benchmark", "name": "BenchmarkRecord", "public": true, "signature": "()", "summary": "One strategy run on one analysis group of one dataset under one acquisition order."} -{"arguments": 0, "called_by": [], "calls": ["?.items", "?.join", "?.update"], "complexity": 4, "decorators": [], "hash": "932994a25b192b64", "kind": "method", "lines": 38, "module": "benchmark", "name": "BenchmarkRecord.as_row", "public": true, "signature": "(self) -> dict[str, Any]", "summary": "A flat dict: group columns as ``group.``, outcomes as ``outcome.``.", "varargs": []} +{"arguments": 0, "called_by": [], "calls": ["?.items", "?.join", "?.update"], "complexity": 4, "decorators": [], "hash": "3574f4250e4ba504", "kind": "method", "lines": 39, "module": "benchmark", "name": "BenchmarkRecord.as_row", "public": true, "signature": "(self) -> dict[str, Any]", "summary": "A flat dict: group columns as ``group.``, outcomes as ``outcome.``,", "varargs": []} {"arguments": 1, "called_by": ["sufficiency_tables:criteria_tables"], "calls": ["?.as_row", "pandas.DataFrame"], "complexity": 1, "decorators": [], "hash": "9f27a7325d9b0713", "kind": "function", "lines": 1, "module": "benchmark", "name": "records_to_frame", "public": true, "signature": "(records: Iterable[BenchmarkRecord]) -> pd.DataFrame", "summary": "One row per record (see ``BenchmarkRecord.as_row``).", "varargs": []} {"arguments": 6, "called_by": ["benchmark:_replay_order"], "calls": ["?.evaluate", "?.get", "?.itertuples", "?.prefix", "?.trained", "_benchmark_data:_area", "benchmark:BenchmarkRecord", "benchmark:_record_run.read", "dict", "enumerate", "float", "len", "list", "max", "next", "numpy.argsort", "numpy.array", "numpy.flatnonzero", "numpy.median", "sequential:_Acquisition", "sum", "tuple"], "complexity": 4, "decorators": [], "hash": "1147cd9b730980c5", "kind": "function", "lines": 55, "module": "benchmark", "name": "_record_run", "public": false, "signature": "(history: Sequence[SequentialResult], full: ValidatedInput, scored_against: ValidatedInput, metrics: Sequence[OutcomeMetric], dataset: BenchmarkDataset, stop_on: str='decision', **provenance: Any) -> BenchmarkRecord", "summary": "Find the stop in one strategy's history on one group and score it against ``scored_against``.", "varargs": ["**provenance"]} {"arguments": 1, "called_by": ["benchmark:_record_run"], "calls": [], "complexity": 2, "decorators": [], "hash": "f3157c216a52ec8f", "kind": "nested", "lines": 1, "module": "benchmark", "name": "_record_run.read", "public": false, "signature": "(result: StrategyResult) -> Decision | None", "summary": "", "varargs": []} @@ -586,7 +591,8 @@ {"arguments": 3, "called_by": ["workflows._feature_space:_declared"], "calls": ["feature_tables:prefixed"], "complexity": 1, "decorators": [], "hash": "d524a84bcde66d26", "kind": "function", "lines": 5, "module": "feature_tables", "name": "shared_column_text", "public": true, "signature": "(column: Any, first: str, second: str) -> str", "summary": "The refusal of one column name declared for two tables, with the names to use.", "varargs": []} {"arguments": 2, "called_by": ["feature_tables:attach_feature_tables"], "calls": ["?.fromkeys", "?.get", "?.items", "?.values", "feature_tables:prefixed", "set"], "complexity": 5, "decorators": [], "hash": "3c98bcd13adb6e0f", "kind": "function", "lines": 9, "module": "feature_tables", "name": "_final_names", "public": false, "signature": "(objects: pd.DataFrame, features: Mapping[str, list[Any]]) -> dict[str, dict[Any, str]]", "summary": "Each table's final column names: a name found in the observation table or in another", "varargs": []} {"arguments": 2, "called_by": ["feature_tables:_usable_tables"], "calls": ["?.casefold", "?.strip", "isinstance"], "complexity": 5, "decorators": [], "hash": "362b8ba8e404ad03", "kind": "function", "lines": 13, "module": "feature_tables", "name": "_name_problems", "public": false, "signature": "(name: object, seen: list[str]) -> list[str]", "summary": "Why ``name`` cannot name a table: empty, reserved, or another table's (any case).", "varargs": []} -{"arguments": 6, "called_by": ["feature_tables:_blocks"], "calls": ["?.all", "?.append", "?.items", "?.setdefault", "?.sum", "?.to_numpy", "_wording:count", "_wording:listing", "int", "len", "numpy.empty", "numpy.isinf", "numpy.isnan", "pandas.api.types.is_bool_dtype", "pandas.api.types.is_numeric_dtype", "str", "zip"], "complexity": 13, "decorators": [], "hash": "8bffac6edc579a0f", "kind": "function", "lines": 50, "module": "feature_tables", "name": "_column_problems", "public": false, "signature": "(name: str, table: pd.DataFrame, columns: list[Any], final: Mapping[Any, str], objects: pd.DataFrame, taken: Mapping[str, str]) -> list[str]", "summary": "Whether the feature columns of ``table`` are numeric, finite, and, by their final", "varargs": []} +{"arguments": 6, "called_by": ["feature_tables:_blocks"], "calls": ["?.all", "?.append", "?.items", "?.setdefault", "?.sum", "?.to_numpy", "_wording:count", "_wording:listing", "feature_tables:_column_kinds", "int", "len", "numpy.empty", "numpy.isinf", "numpy.isnan", "str", "zip"], "complexity": 13, "decorators": [], "hash": "cfae5de2fcc6b20c", "kind": "function", "lines": 50, "module": "feature_tables", "name": "_column_problems", "public": false, "signature": "(name: str, table: pd.DataFrame, columns: list[Any], final: Mapping[Any, str], objects: pd.DataFrame, taken: Mapping[str, str]) -> list[str]", "summary": "Whether the feature columns of ``table`` are numeric, finite, and, by their final", "varargs": []} +{"arguments": 2, "called_by": ["feature_tables:_column_problems"], "calls": ["pandas.api.types.is_bool_dtype", "pandas.api.types.is_complex_dtype", "pandas.api.types.is_numeric_dtype"], "complexity": 4, "decorators": [], "hash": "ba0a69a4e7a8707c", "kind": "function", "lines": 10, "module": "feature_tables", "name": "_column_kinds", "public": false, "signature": "(table: pd.DataFrame, columns: list[Any]) -> tuple[list[Any], list[Any], list[Any]]", "summary": "The ``columns`` of ``table`` that are complex, real numbers, and neither. Complex", "varargs": []} {"arguments": 1, "called_by": ["feature_tables:_blocks"], "calls": ["?.to_numpy", "len", "numpy.nanmax", "numpy.nanmin", "tuple", "zip"], "complexity": 2, "decorators": [], "hash": "1ed2a6cc6e52ce28", "kind": "function", "lines": 5, "module": "feature_tables", "name": "_constant", "public": false, "signature": "(block: pd.DataFrame) -> tuple[str, ...]", "summary": "The columns of ``block`` with one value everywhere (missing values aside).", "varargs": []} {"arguments": 5, "called_by": ["workflows._feature_space:attached", "workflows._guided_tables:ask_tables", "workflows._scan_rules:with_tables"], "calls": ["?.items", "?.join", "TypeError", "ValueError", "_observation_keys:observation_identity", "_observation_keys:observed_keys", "_repeat_alias:refuse_repeat_alias", "_within_identity:duplicate_identity_text", "feature_tables:FeatureTables", "feature_tables:_blocks", "feature_tables:_final_names", "feature_tables:_given_tables", "feature_tables:_usable_tables", "isinstance", "pandas.concat", "str"], "complexity": 6, "decorators": [], "hash": "3417d711f9532d95", "kind": "function", "lines": 28, "module": "feature_tables", "name": "attach_feature_tables", "public": true, "signature": "(objects: pd.DataFrame, fovs: pd.DataFrame | None, feature_tables: Mapping[str, pd.DataFrame | tuple[pd.DataFrame, str]], *, fov_col: str | None=None, group_cols: Sequence[str] | None=None) -> FeatureTables", "summary": "Validate ``feature_tables`` (a name for each table, its DataFrame or ``(DataFrame,", "varargs": []} {"called_by": ["feature_tables:_blocks"], "calls": [], "decorators": [], "hash": "c0819e75b81d146f", "kind": "class", "module": "feature_tables", "name": "_Blocks", "public": false, "signature": "(NamedTuple)", "summary": "The usable tables' columns as blocks of the observation table, and per table its"} @@ -1418,7 +1424,7 @@ {"arguments": 1, "called_by": ["retrospective.report_enough:detection_line", "retrospective.report_profile:_detection_adjusted_bounds"], "calls": ["?.get", "?.set_index", "getattr", "int"], "complexity": 8, "decorators": [], "hash": "6a93b8eeb948df98", "kind": "function", "lines": 7, "module": "retrospective.report_profile", "name": "_detection", "public": false, "signature": "(controls: ControlResult) -> tuple[str, int, int] | None", "summary": "The detection rate the unseen-state bound is adjusted by: kind, recognized, checks.", "varargs": []} {"arguments": 1, "called_by": ["retrospective.report_enough:detection_line", "retrospective.report_profile:_detection_words"], "calls": ["_observation_units:observation_words"], "complexity": 1, "decorators": [], "hash": "967be0ba804de9cd", "kind": "function", "lines": 1, "module": "retrospective.report_profile", "name": "_words", "public": false, "signature": "(controls: ControlResult) -> str", "summary": "The control's observation unit, plural: ``nuclei`` (``objects`` when none declared).", "varargs": []} {"arguments": 3, "called_by": ["retrospective.report_profile:_detection_adjusted_bounds"], "calls": ["_wording:percent", "retrospective.report_profile:_words"], "complexity": 2, "decorators": [], "hash": "54139f0b91ba118a", "kind": "function", "lines": 18, "module": "retrospective.report_profile", "name": "_detection_words", "public": false, "signature": "(controls: ControlResult, kind: str, detection: float) -> tuple[str, str]", "summary": "The detection rate in words (planted objects, or whole positive fields), and what it", "varargs": []} -{"arguments": 3, "called_by": ["retrospective.report_profile:_detection_adjusted_bounds"], "calls": ["?.append", "?.itertuples", "?.join", "_wording:percent", "float", "getattr", "min", "pandas.isna"], "complexity": 5, "decorators": [], "hash": "9adb97a08c5c8156", "kind": "function", "lines": 13, "module": "retrospective.report_profile", "name": "_adjusted_lines", "public": false, "signature": "(frame: pd.DataFrame, keys: list[str], low: float) -> list[str]", "summary": "Each group's unseen-state bound divided by the low end of the detection rate.", "varargs": []} +{"arguments": 3, "called_by": ["retrospective.report_profile:_detection_adjusted_bounds"], "calls": ["?.append", "?.join", "?.to_dict", "_wording:percent", "float", "min", "pandas.isna"], "complexity": 5, "decorators": [], "hash": "e6042de7cb2d5314", "kind": "function", "lines": 13, "module": "retrospective.report_profile", "name": "_adjusted_lines", "public": false, "signature": "(frame: pd.DataFrame, keys: list[str], low: float) -> list[str]", "summary": "Each group's unseen-state bound divided by the low end of the detection rate. Rows are", "varargs": []} {"arguments": 2, "called_by": ["retrospective.report_enough:detection_line", "retrospective.report_enough:enough_full"], "calls": ["?.join", "_wording:percent", "bounds:lower_bound", "float", "getattr", "len", "list", "retrospective._control_rates:_mismatch", "retrospective.controls_text:pooled_over", "retrospective.report_profile:_adjusted_lines", "retrospective.report_profile:_detection", "retrospective.report_profile:_detection_words"], "complexity": 11, "decorators": [], "hash": "885e108070cdc982", "kind": "function", "lines": 38, "module": "retrospective.report_profile", "name": "_detection_adjusted_bounds", "public": false, "signature": "(sufficiency: SufficiencyReport, controls: ControlResult | None) -> str | None", "summary": "The unseen-state bound divided by the low end of the control's detection rate.", "varargs": []} {"arguments": 2, "called_by": ["retrospective.report_profile:sampling_profile"], "calls": ["?.dropna", "?.join", "?.max", "?.median", "?.min", "_style:low_to_high", "_wording:percent", "float", "len", "pandas.to_numeric", "sampling_unit._unit_text:one_per_field_rows"], "complexity": 6, "decorators": [], "hash": "23882dbb1d6d63df", "kind": "function", "lines": 34, "module": "retrospective.report_profile", "name": "_variability_rows", "public": false, "signature": "(variability: FOVVariability | None, observations: str) -> list[dict]", "summary": "Fields against random objects, from ``fov_variability``.", "varargs": []} {"arguments": 2, "called_by": ["retrospective.report_profile:sampling_profile"], "calls": ["?.append", "?.dropna", "?.groupby", "?.median", "?.notna", "?.state_name", "?.sum", "float", "int", "len", "pandas.to_numeric", "sampling_unit._state_text:clustered"], "complexity": 5, "decorators": [], "hash": "5ea046256bcaac93", "kind": "function", "lines": 35, "module": "retrospective.report_profile", "name": "_clustering_rows", "public": false, "signature": "(clustering: FOVClustering | None, observations: str) -> list[dict]", "summary": "Whether labelled rare or unusual objects cluster in a few fields.", "varargs": []} @@ -2094,7 +2100,7 @@ {"arguments": 3, "called_by": ["sampling_unit.whole_table:_pair_row"], "calls": ["?.mean", "?.sum", "float", "len", "max", "numpy.linalg.norm", "numpy.sqrt", "numpy.square", "sampling_unit.whole_table:_mean_by"], "complexity": 2, "decorators": [], "hash": "a87164563385f982", "kind": "function", "lines": 4, "module": "sampling_unit.whole_table", "name": "_effect", "public": false, "signature": "(z: np.ndarray, codes: np.ndarray, deltas: np.ndarray) -> float", "summary": "The mean shift over the repeats, in the pooled within-group SD of the scaled values.", "varargs": []} {"arguments": 3, "called_by": ["sampling_unit.whole_table:_pair_row"], "calls": ["?.items", "?.join", "?.sum", "int"], "complexity": 1, "decorators": [], "hash": "a58c8360b3c1dc5a", "kind": "function", "lines": 2, "module": "sampling_unit.whole_table", "name": "_few_control", "public": false, "signature": "(repeat: np.ndarray, side: np.ndarray, both: list[Any]) -> str", "summary": "The repeats whose control holds fewer than ``FEW_CONTROL`` fields, with the count.", "varargs": []} {"arguments": 1, "called_by": ["sampling_unit.whole_table:whole_table_tests"], "calls": ["?.all", "?.join", "metadata:empty_values"], "complexity": 5, "decorators": [], "hash": "80ed18cc2170928b", "kind": "function", "lines": 8, "module": "sampling_unit.whole_table", "name": "_units", "public": false, "signature": "(data: ValidatedInput) -> tuple[str, list[str]]", "summary": "The unit the shuffle test permutes and the columns naming it with the condition and", "varargs": []} -{"arguments": 10, "called_by": ["workflows._whole_table:whole_table_in_report"], "calls": ["?.agg", "?.any", "?.astype", "?.feature_matrix", "?.get", "?.groupby", "?.items", "?.map", "?.ngroup", "?.reindex", "?.sum", "?.to_dict", "?.to_numpy", "ValueError", "bool", "data_check:validate_input_tables", "int", "len", "list", "numpy.isnan", "pandas.DataFrame", "sampling_unit._experiments:corrected", "sampling_unit._experiments:declared", "sampling_unit._experiments:experiments", "sampling_unit.whole_table:WholeTable", "sampling_unit.whole_table:_table_rows", "sampling_unit.whole_table:_units", "set", "tuple"], "complexity": 6, "decorators": [], "hash": "3404638bc99b5877", "kind": "function", "lines": 53, "module": "sampling_unit.whole_table", "name": "whole_table_tests", "public": true, "signature": "(objects: pd.DataFrame, fovs: pd.DataFrame, *, tables: Mapping[str, Sequence[str]], pairs: Sequence[tuple[Any, Any]], permutations: int=PERMUTATIONS, random_state: int=0, fov_col: str | None=None, group_cols: Sequence[str] | None=None, observation_unit: str | None=None, families: Mapping[Any, Any] | None=None) -> WholeTable", "summary": "The whole-table tests of every table (``tables``: each name and its columns) for each", "varargs": []} +{"arguments": 10, "called_by": ["workflows._whole_table:whole_table_in_report"], "calls": ["?.agg", "?.any", "?.astype", "?.feature_matrix", "?.get", "?.groupby", "?.items", "?.map", "?.ngroup", "?.reindex", "?.sum", "?.to_dict", "?.to_numpy", "ValueError", "_checks:as_count", "_checks:check_seed", "bool", "data_check:validate_input_tables", "int", "len", "list", "numpy.isnan", "pandas.DataFrame", "sampling_unit._experiments:corrected", "sampling_unit._experiments:declared", "sampling_unit._experiments:experiments", "sampling_unit.whole_table:WholeTable", "sampling_unit.whole_table:_table_rows", "sampling_unit.whole_table:_units", "set", "tuple"], "complexity": 6, "decorators": [], "hash": "de39734f951f6ce7", "kind": "function", "lines": 55, "module": "sampling_unit.whole_table", "name": "whole_table_tests", "public": true, "signature": "(objects: pd.DataFrame, fovs: pd.DataFrame, *, tables: Mapping[str, Sequence[str]], pairs: Sequence[tuple[Any, Any]], permutations: int=PERMUTATIONS, random_state: int=0, fov_col: str | None=None, group_cols: Sequence[str] | None=None, observation_unit: str | None=None, families: Mapping[Any, Any] | None=None) -> WholeTable", "summary": "The whole-table tests of every table (``tables``: each name and its columns) for each", "varargs": []} {"calls": [], "kind": "module", "module": "schema", "name": "", "public": true, "summary": "Validation for the representation-agnostic MorphoCoverage input contract."} {"called_by": ["schema:_validate_input_tables"], "calls": ["dataclasses.dataclass", "dataclasses.field"], "decorators": ["dataclass(frozen=True)"], "hash": "3972e851d0bdd665", "kind": "class", "module": "schema", "name": "ValidatedInput", "public": true, "signature": "()", "summary": "Validated FOV metadata and phenotype observations."} {"arguments": 0, "called_by": [], "calls": ["_input_invariants:check_input"], "complexity": 1, "decorators": [], "hash": "f6409c26659e4e11", "kind": "method", "lines": 1, "module": "schema", "name": "ValidatedInput.__post_init__", "public": false, "signature": "(self) -> None", "summary": "", "varargs": []} @@ -2223,8 +2229,9 @@ {"arguments": 4, "called_by": ["strategies._descriptor_resamples:_fov_resamples"], "calls": ["?.ravel", "?.sum", "len", "max", "numpy.append", "numpy.arange", "numpy.argsort", "numpy.bincount", "numpy.cumsum", "numpy.empty_like", "numpy.maximum", "numpy.repeat", "numpy.sort", "numpy.sqrt", "numpy.where", "strategies._descriptor_resamples:_describe_fov_resamples.quantile"], "complexity": 1, "decorators": [], "hash": "9b1442534a4cd222", "kind": "function", "lines": 43, "module": "strategies._descriptor_resamples", "name": "_describe_fov_resamples", "public": false, "signature": "(grouped: np.ndarray, counts: np.ndarray, draws: np.ndarray, descriptors: Sequence[str]) -> dict[str, np.ndarray]", "summary": "Descriptors of each resample of whole FOVs, without a Python loop over resamples.", "varargs": []} {"arguments": 1, "called_by": ["strategies._descriptor_resamples:_describe_fov_resamples"], "calls": ["?.astype", "numpy.floor", "numpy.minimum"], "complexity": 1, "decorators": [], "hash": "bfd50e37c9ab75cd", "kind": "nested", "lines": 5, "module": "strategies._descriptor_resamples", "name": "_describe_fov_resamples.quantile", "public": false, "signature": "(q: float) -> np.ndarray", "summary": "Linearly interpolated quantile of every resample (``np.percentile``'s default).", "varargs": []} {"arguments": 2, "called_by": ["strategies._descriptor_resamples:_object_resamples"], "calls": ["min", "range"], "complexity": 1, "decorators": [], "hash": "7cdad6f133f5089f", "kind": "function", "lines": 1, "module": "strategies._descriptor_resamples", "name": "_chunk_sizes", "public": false, "signature": "(total: int, chunk: int) -> list[int]", "summary": "``total`` split into consecutive parts of at most ``chunk``.", "varargs": []} -{"arguments": 4, "called_by": ["strategies.stabilization:DescriptorSpreadEstimator._resampled_descriptors"], "calls": ["?.integers", "int", "len", "max", "numpy.concatenate", "strategies._descriptor_resamples:_chunk_sizes", "strategies._descriptor_resamples:_describe_many"], "complexity": 1, "decorators": [], "hash": "59e6cb783e4df03e", "kind": "function", "lines": 6, "module": "strategies._descriptor_resamples", "name": "_object_resamples", "public": false, "signature": "(values: np.ndarray, n_resamples: int, rng: np.random.Generator, descriptors: Sequence[str]) -> dict[str, np.ndarray]", "summary": "Descriptors of ``n_resamples`` resamples of the objects, with replacement, at full size.", "varargs": []} -{"arguments": 6, "called_by": ["strategies.stabilization:DescriptorSpreadEstimator._resampled_descriptors"], "calls": ["?.integers", "int", "len", "max", "numpy.bincount", "numpy.concatenate", "numpy.lexsort", "range", "strategies._descriptor_resamples:_describe_fov_resamples"], "complexity": 1, "decorators": [], "hash": "358b257599f379af", "kind": "function", "lines": 9, "module": "strategies._descriptor_resamples", "name": "_fov_resamples", "public": false, "signature": "(values: np.ndarray, positions: np.ndarray, k: int, n_resamples: int, rng: np.random.Generator, descriptors: Sequence[str]) -> dict[str, np.ndarray]", "summary": "Descriptors of ``n_resamples`` resamples of all ``k`` FOVs, whole FOVs with replacement.", "varargs": []} +{"arguments": 1, "called_by": ["strategies._descriptor_resamples:_fov_resamples", "strategies._descriptor_resamples:_object_resamples"], "calls": ["ValueError"], "complexity": 2, "decorators": [], "hash": "1174ab8fdc07b1ab", "kind": "function", "lines": 2, "module": "strategies._descriptor_resamples", "name": "_check_resamples", "public": false, "signature": "(n_resamples: int) -> None", "summary": "At least one resample: none would describe nothing.", "varargs": []} +{"arguments": 4, "called_by": ["strategies.stabilization:DescriptorSpreadEstimator._resampled_descriptors"], "calls": ["?.integers", "ValueError", "int", "len", "max", "numpy.concatenate", "strategies._descriptor_resamples:_check_resamples", "strategies._descriptor_resamples:_chunk_sizes", "strategies._descriptor_resamples:_describe_many"], "complexity": 2, "decorators": [], "hash": "9d6891c22c20372a", "kind": "function", "lines": 9, "module": "strategies._descriptor_resamples", "name": "_object_resamples", "public": false, "signature": "(values: np.ndarray, n_resamples: int, rng: np.random.Generator, descriptors: Sequence[str]) -> dict[str, np.ndarray]", "summary": "Descriptors of ``n_resamples`` resamples of the objects, with replacement, at full size.", "varargs": []} +{"arguments": 6, "called_by": ["strategies.stabilization:DescriptorSpreadEstimator._resampled_descriptors"], "calls": ["?.integers", "?.max", "?.min", "ValueError", "int", "len", "max", "numpy.bincount", "numpy.concatenate", "numpy.lexsort", "range", "strategies._descriptor_resamples:_check_resamples", "strategies._descriptor_resamples:_describe_fov_resamples"], "complexity": 6, "decorators": [], "hash": "158e2feecce73c93", "kind": "function", "lines": 16, "module": "strategies._descriptor_resamples", "name": "_fov_resamples", "public": false, "signature": "(values: np.ndarray, positions: np.ndarray, k: int, n_resamples: int, rng: np.random.Generator, descriptors: Sequence[str]) -> dict[str, np.ndarray]", "summary": "Descriptors of ``n_resamples`` resamples of all ``k`` FOVs, whole FOVs with replacement.", "varargs": []} {"calls": [], "kind": "module", "module": "strategies._fov_bootstrap_checks", "name": "", "public": false, "summary": "The checks of the FOV bootstrap (``fov_bootstrap``): its settings and its data."} {"arguments": 7, "called_by": ["strategies.fov_bootstrap:FOVBootstrapEstimator.__post_init__", "strategies.fov_bootstrap:FOVBootstrapStrategy.__post_init__"], "calls": ["TypeError", "ValueError", "isinstance", "strategies._fov_bootstrap_checks:_check_counts", "strategies._fov_bootstrap_checks:_check_summary_settings", "transforms:FeatureTransform"], "complexity": 4, "decorators": [], "hash": "e9cda68f4cea7702", "kind": "function", "lines": 6, "module": "strategies._fov_bootstrap_checks", "name": "_check", "public": false, "signature": "(summary: str, n_resamples: int, random_state: int, min_fovs: int, quantiles: Sequence[float] | None, transform: FeatureTransform | None, n_components: int | None) -> None", "summary": "Validate the settings shared by the estimator and the strategy.", "varargs": []} {"arguments": 3, "called_by": ["strategies._fov_bootstrap_checks:_check"], "calls": ["TypeError", "ValueError", "_checks:check_seed", "_checks:is_integer"], "complexity": 5, "decorators": [], "hash": "6b9d3a327fb48a6c", "kind": "function", "lines": 8, "module": "strategies._fov_bootstrap_checks", "name": "_check_counts", "public": false, "signature": "(n_resamples: int, min_fovs: int, random_state: int) -> None", "summary": "The resamples and the fewest fields: integers of at least 2; the seed an integer.", "varargs": []} @@ -2359,7 +2366,8 @@ {"arguments": 0, "called_by": [], "calls": ["list"], "complexity": 1, "decorators": ["property"], "hash": "37577b6c1e6faae5", "kind": "property", "lines": 15, "module": "strategies.jcb_planning", "name": "ObjectCountPlan.parameters", "public": true, "signature": "(self) -> dict[str, Any]", "summary": "Everything that defines the plan, JSON-serializable, for provenance.", "varargs": []} {"arguments": 5, "called_by": ["strategies.jcb_planning:plan_objects_to_average"], "calls": ["?.any", "?.feature_values", "?.isna", "ValueError", "data_check:validate_input_tables", "numpy.isnan", "strategies.base:unsupported_observation_unit"], "complexity": 6, "decorators": [], "hash": "eef4b7389587388f", "kind": "function", "lines": 24, "module": "strategies.jcb_planning", "name": "_pilot_values", "public": false, "signature": "(objects: pd.DataFrame, feature: str, sample_cols: tuple[str, ...], observation_unit: str | None, validation: Mapping[str, Any]) -> tuple[ValidatedInput, np.ndarray]", "summary": "Validated pilot data and its feature values, or a clear error.", "varargs": []} {"arguments": 7, "called_by": [], "calls": ["?.append", "?.items", "?.mean", "TypeError", "ValueError", "_repeat_alias:refuse_repeat_alias", "_seeds:plain", "_wording:plural", "float", "isinstance", "len", "statistics:spread_is_zero", "strategies._averaging_cv:_central_sums", "strategies._averaging_cv:_shape_warning", "strategies._averaging_cv:required_objects", "strategies.jcb_planning:ObjectCountPlan", "strategies.jcb_planning:_pilot_values", "strategies.jcb_planning:_samples", "strategies.jcb_planning:_within_sample_cv", "tuple"], "complexity": 14, "decorators": [], "hash": "36e0c6d2c15f8ee2", "kind": "function", "lines": 56, "module": "strategies.jcb_planning", "name": "plan_objects_to_average", "public": true, "signature": "(objects: pd.DataFrame, *, feature: str, target_cv: float, sd_estimate: str, sample_cols: Sequence[str], control: Mapping[str, Any], observation_unit: str | None=None, **validation: Any) -> ObjectCountPlan", "summary": "Plan the number of objects to average from pilot samples (see the module docstring).", "varargs": ["**validation"]} -{"arguments": 4, "called_by": ["strategies.jcb_planning:plan_objects_to_average"], "calls": ["?.assign", "?.drop_duplicates", "?.eq", "?.groupby", "?.items", "?.join", "?.mean", "?.to_numpy", "ValueError", "_wording:listing", "dict", "float", "list", "numpy.logical_and.reduce", "repr"], "complexity": 6, "decorators": [], "hash": "d5407783a95b5847", "kind": "function", "lines": 29, "module": "strategies.jcb_planning", "name": "_samples", "public": false, "signature": "(data: ValidatedInput, values: np.ndarray, sample_cols: tuple[str, ...], control: Mapping[str, Any]) -> tuple[Any, pd.Series, float]", "summary": "The pilot values grouped by sample, the control samples' means and the control's", "varargs": []} +{"arguments": 4, "called_by": ["strategies.jcb_planning:plan_objects_to_average"], "calls": ["?.assign", "?.drop_duplicates", "?.eq", "?.groupby", "?.items", "?.join", "?.mean", "?.to_numpy", "ValueError", "_wording:listing", "dict", "float", "list", "numpy.logical_and.reduce", "repr", "strategies.jcb_planning:_refuse_mixed_samples"], "complexity": 6, "decorators": [], "hash": "c3eda9d91c73f682", "kind": "function", "lines": 30, "module": "strategies.jcb_planning", "name": "_samples", "public": false, "signature": "(data: ValidatedInput, values: np.ndarray, sample_cols: tuple[str, ...], control: Mapping[str, Any]) -> tuple[Any, pd.Series, float]", "summary": "The pilot values grouped by sample, the control samples' means and the control's", "varargs": []} +{"arguments": 4, "called_by": ["strategies.jcb_planning:_samples"], "calls": ["?.groupby", "?.nunique", "ValueError", "_wording:listing", "isinstance", "len", "list", "pandas.Series", "repr"], "complexity": 4, "decorators": [], "hash": "b203d15679369dab", "kind": "function", "lines": 13, "module": "strategies.jcb_planning", "name": "_refuse_mixed_samples", "public": false, "signature": "(table: pd.DataFrame, is_control: np.ndarray, sample_cols: tuple[str, ...], control: Mapping[str, Any]) -> None", "summary": "Refuse a sample that holds both control and other cells: centring it on its own mean", "varargs": []} {"arguments": 4, "called_by": ["strategies.jcb_planning:plan_objects_to_average"], "calls": ["?.to_numpy", "?.transform", "ValueError", "float", "len", "numpy.std", "statistics:sd_upper_bound_factor"], "complexity": 2, "decorators": [], "hash": "2506d80fd39a5207", "kind": "function", "lines": 12, "module": "strategies.jcb_planning", "name": "_within_sample_cv", "public": false, "signature": "(values: np.ndarray, by_sample: Any, n_samples: int, control_mean: float) -> tuple[np.ndarray, float, float, float]", "summary": "The values centred on their sample's mean, their SD, as a CV of the control mean, and", "varargs": []} {"arguments": 2, "called_by": ["strategies.jcb_planning:PlannedObjectCountEstimator.estimate"], "calls": ["?.itertuples", "_seeds:plain", "all", "list", "tuple"], "complexity": 3, "decorators": [], "hash": "ac3a326ae0e11f37", "kind": "function", "lines": 5, "module": "strategies.jcb_planning", "name": "_samples_seen", "public": false, "signature": "(data: ValidatedInput, sample_cols: tuple[str, ...]) -> set[tuple] | None", "summary": "The samples present in the evaluated data, or ``None`` if they cannot be identified.", "varargs": []} {"called_by": ["strategies.jcb_planning:PlannedObjectCountStrategy.estimators"], "calls": ["dataclasses.dataclass", "strategies.base:Estimator"], "decorators": ["dataclass(frozen=True)"], "hash": "f36f194e232b8a90", "kind": "class", "module": "strategies.jcb_planning", "name": "PlannedObjectCountEstimator", "public": true, "signature": "(Estimator)", "summary": "Reports a plan's required object count as evidence, if the plan applies to the group."} @@ -2617,14 +2625,14 @@ {"arguments": 2, "called_by": [], "calls": ["?.argmax", "?.max", "?.mean", "?.sum", "float", "math.sqrt", "max", "numpy.abs", "numpy.arange", "numpy.finfo", "numpy.linalg.svd", "numpy.sign", "range", "transforms:_floats", "transforms:missing_values_reason", "tuple"], "complexity": 6, "decorators": [], "hash": "335fc9584670c318", "kind": "method", "lines": 30, "module": "transforms", "name": "PCA.fit_matrix", "public": true, "signature": "(self, matrix: np.ndarray, names: tuple[str, ...]) -> tuple[dict[str, Any], tuple[str, ...]] | str", "summary": "Visible mean, leading components and their explained-variance ratios.", "varargs": []} {"arguments": 2, "called_by": [], "calls": ["numpy.asarray"], "complexity": 1, "decorators": [], "hash": "72a4b67a4e302679", "kind": "method", "lines": 1, "module": "transforms", "name": "PCA.apply_matrix", "public": true, "signature": "(self, state: Mapping[str, Any], matrix: np.ndarray) -> np.ndarray", "summary": "Scores on the fitted components.", "varargs": []} {"called_by": [], "calls": ["dataclasses.dataclass", "transforms:FeatureTransform"], "decorators": ["dataclass(frozen=True)"], "hash": "c9250ca308d6b7a8", "kind": "class", "module": "transforms", "name": "ColumnWeights", "public": true, "signature": "(FeatureTransform)", "summary": "Multiply each feature by a fixed, declared weight: nothing is fitted."} -{"arguments": 0, "called_by": [], "calls": ["?.__setattr__", "ValueError", "all", "float", "numpy.isfinite", "tuple"], "complexity": 4, "decorators": [], "hash": "9d78b451394fcd0d", "kind": "method", "lines": 4, "module": "transforms", "name": "ColumnWeights.__post_init__", "public": false, "signature": "(self) -> None", "summary": "", "varargs": []} +{"arguments": 0, "called_by": [], "calls": ["?.__setattr__", "ValueError", "_checks:is_positive_finite", "all", "float", "tuple"], "complexity": 3, "decorators": [], "hash": "0f2c2393d24107bf", "kind": "method", "lines": 4, "module": "transforms", "name": "ColumnWeights.__post_init__", "public": false, "signature": "(self) -> None", "summary": "", "varargs": []} {"arguments": 0, "called_by": [], "calls": [], "complexity": 1, "decorators": ["property"], "hash": "c21f7457093c5c41", "kind": "property", "lines": 1, "module": "transforms", "name": "ColumnWeights.name", "public": true, "signature": "(self) -> str", "summary": "``column_weights``.", "varargs": []} {"arguments": 0, "called_by": [], "calls": ["list"], "complexity": 1, "decorators": ["property"], "hash": "a5c44de3360865f2", "kind": "property", "lines": 1, "module": "transforms", "name": "ColumnWeights.parameters", "public": true, "signature": "(self) -> dict[str, Any]", "summary": "The weights, in the order of the features.", "varargs": []} {"arguments": 1, "called_by": [], "calls": ["len"], "complexity": 2, "decorators": [], "hash": "a1e343f222ce5abb", "kind": "method", "lines": 1, "module": "transforms", "name": "ColumnWeights.output_width", "public": true, "signature": "(self, n_inputs: int) -> int | None", "summary": "One output per feature, when there is one weight per feature.", "varargs": []} {"arguments": 2, "called_by": [], "calls": ["len"], "complexity": 2, "decorators": [], "hash": "e720480d0d90207b", "kind": "method", "lines": 3, "module": "transforms", "name": "ColumnWeights.fit_matrix", "public": true, "signature": "(self, matrix: np.ndarray, names: tuple[str, ...]) -> tuple[dict[str, Any], tuple[str, ...]] | str", "summary": "Nothing to fit: only the number of features is checked.", "varargs": []} {"arguments": 2, "called_by": [], "calls": ["numpy.asarray"], "complexity": 1, "decorators": [], "hash": "21774c614c695529", "kind": "method", "lines": 1, "module": "transforms", "name": "ColumnWeights.apply_matrix", "public": true, "signature": "(self, state: Mapping[str, Any], matrix: np.ndarray) -> np.ndarray", "summary": "Each feature times its weight.", "varargs": []} {"called_by": ["workflows._feature_space:novelty_space"], "calls": ["dataclasses.dataclass", "transforms:FeatureTransform"], "decorators": ["dataclass(frozen=True)"], "hash": "07dbed4e137b6511", "kind": "class", "module": "transforms", "name": "BlockWeights", "public": true, "signature": "(FeatureTransform)", "summary": "Weigh each block of features (each explainable feature table) as multiple factor"} -{"arguments": 0, "called_by": [], "calls": ["?.__setattr__", "ValueError", "any", "str", "tuple"], "complexity": 3, "decorators": [], "hash": "b97286c4c4687933", "kind": "method", "lines": 4, "module": "transforms", "name": "BlockWeights.__post_init__", "public": false, "signature": "(self) -> None", "summary": "", "varargs": []} +{"arguments": 0, "called_by": [], "calls": ["?.__setattr__", "?.strip", "TypeError", "ValueError", "_checks:check_flag", "all", "any", "isinstance", "tuple"], "complexity": 5, "decorators": [], "hash": "086334a6cf1bdb83", "kind": "method", "lines": 10, "module": "transforms", "name": "BlockWeights.__post_init__", "public": false, "signature": "(self) -> None", "summary": "", "varargs": []} {"arguments": 0, "called_by": [], "calls": [], "complexity": 1, "decorators": ["property"], "hash": "a4d5276e35b05a84", "kind": "property", "lines": 1, "module": "transforms", "name": "BlockWeights.name", "public": true, "signature": "(self) -> str", "summary": "``block_weights``.", "varargs": []} {"arguments": 0, "called_by": [], "calls": ["list"], "complexity": 1, "decorators": ["property"], "hash": "f0091e4febec26cc", "kind": "property", "lines": 4, "module": "transforms", "name": "BlockWeights.parameters", "public": true, "signature": "(self) -> dict[str, Any]", "summary": "The blocks, each its feature names, and whether the radius follows the inertia.", "varargs": []} {"arguments": 1, "called_by": [], "calls": [], "complexity": 1, "decorators": [], "hash": "3e72aca320d42462", "kind": "method", "lines": 1, "module": "transforms", "name": "BlockWeights.output_width", "public": true, "signature": "(self, n_inputs: int) -> int", "summary": "One output per feature.", "varargs": []} @@ -2876,7 +2884,7 @@ {"arguments": 2, "called_by": ["workflows._guided_ask:choose_many"], "calls": ["?.add", "?.isdigit", "?.lower", "?.split", "?.strip", "?.update", "enumerate", "int", "len", "list", "range", "re.fullmatch", "set", "sorted", "str"], "complexity": 10, "decorators": [], "hash": "391935cff47ec140", "kind": "function", "lines": 22, "module": "workflows._guided_ask", "name": "_selection", "public": false, "signature": "(answer: str, options: Sequence[Any]) -> list[Any] | str", "summary": "The options an answer names (``all``, ``1,3-5``, names separated by commas), in the", "varargs": []} {"arguments": 6, "called_by": ["workflows._guided_ask:ask_features", "workflows._guided_controls:ask_several"], "calls": ["?.ask", "?.say", "?.strip", "_wording:listing", "isinstance", "list", "str", "workflows._guided_ask:_again", "workflows._guided_ask:_numbered", "workflows._guided_ask:_selection"], "complexity": 10, "decorators": [], "hash": "3e79bc7e937f3ab6", "kind": "function", "lines": 17, "module": "workflows._guided_ask", "name": "choose_many", "public": true, "signature": "(ask: Ask, say: Say, prompt: str, options: Sequence[Any], default: Sequence[Any] | None=None, *, enter_all: bool=True) -> list[Any]", "summary": "Several of ``options``: numbers, ranges or names; Enter takes ``default`` (all of them", "varargs": []} {"arguments": 6, "called_by": ["workflows._guided_ask:_numbered", "workflows._guided_ask:ask_tolerance"], "calls": ["?.ask", "?.endswith", "?.rstrip", "?.strip", "float", "workflows._guided_ask:_again"], "complexity": 6, "decorators": [], "hash": "792a1f531bfbd539", "kind": "function", "lines": 12, "module": "workflows._guided_ask", "name": "number", "public": true, "signature": "(ask: Ask, say: Say, prompt: str, default: float, low: float, high: float) -> float", "summary": "A number in ``(low, high]``; a percentage (``10%``) is read as a share.", "varargs": []} -{"arguments": 3, "called_by": ["workflows._guided_ask:_again", "workflows._guided_controls:_keys", "workflows._guided_controls:_parent", "workflows._guided_described:ask_targets", "workflows._guided_tables:ask_tables", "workflows.guided:_load", "workflows.guided:guide"], "calls": ["?.ask", "?.strip"], "complexity": 4, "decorators": [], "hash": "4741819b413da540", "kind": "function", "lines": 3, "module": "workflows._guided_ask", "name": "text", "public": true, "signature": "(ask: Ask, prompt: str, default: str | None=None) -> str", "summary": "Free text; Enter takes the default.", "varargs": []} +{"arguments": 3, "called_by": ["workflows._guided_ask:_again", "workflows._guided_controls:_keys", "workflows._guided_controls:_parent", "workflows._guided_controls:_unlinked", "workflows._guided_described:ask_targets", "workflows._guided_tables:ask_tables", "workflows.guided:_load", "workflows.guided:guide"], "calls": ["?.ask", "?.strip"], "complexity": 4, "decorators": [], "hash": "4741819b413da540", "kind": "function", "lines": 3, "module": "workflows._guided_ask", "name": "text", "public": true, "signature": "(ask: Ask, prompt: str, default: str | None=None) -> str", "summary": "Free text; Enter takes the default.", "varargs": []} {"arguments": 3, "called_by": ["workflows._guided_controls:ask_controls"], "calls": ["?.get", "?.say", "list", "workflows._guided_ask:choose"], "complexity": 4, "decorators": [], "hash": "fff59282b5714147", "kind": "function", "lines": 14, "module": "workflows._guided_ask", "name": "ask_control", "public": true, "signature": "(ask: Ask, say: Say, scan: Any) -> dict[str, Any] | None", "summary": "The negative control, by condition (or none), the scan's suggestion as the default.", "varargs": []} {"arguments": 4, "called_by": ["workflows.guided:_questions"], "calls": ["?.get", "?.say", "isinstance", "set", "workflows._guided_ask:choose"], "complexity": 5, "decorators": [], "hash": "792c0530ecf53bcc", "kind": "function", "lines": 15, "module": "workflows._guided_ask", "name": "ask_positive", "public": true, "signature": "(ask: Ask, say: Say, scan: Any, control: dict[str, Any] | None) -> Any", "summary": "An optional positive control: a condition known to change the phenotype, so the report", "varargs": []} {"arguments": 2, "called_by": ["workflows.guided:_questions"], "calls": ["workflows._guided_ask:choose"], "complexity": 1, "decorators": [], "hash": "d43b0ef8cc3a002b", "kind": "function", "lines": 2, "module": "workflows._guided_ask", "name": "ask_aim", "public": true, "signature": "(ask: Ask, say: Say) -> str", "summary": "``population`` (the average), ``fingerprint`` (the whole distribution) or ``both``.", "varargs": []} @@ -2899,9 +2907,9 @@ {"arguments": 1, "called_by": ["workflows._guided_controls:ask_gate"], "calls": ["?.reindex", "_style:table", "int", "map", "pandas.crosstab", "workflows._guided_controls:_fields"], "complexity": 4, "decorators": [], "hash": "e665e5bec79de626", "kind": "function", "lines": 7, "module": "workflows._guided_controls", "name": "image_table", "public": true, "signature": "(scan: Any) -> str", "summary": "The fields imaged per condition and biological repeat, as a table.", "varargs": []} {"arguments": 2, "called_by": ["workflows._guided_controls:ask_gate"], "calls": ["pandas.unique", "set", "workflows._guided_controls:_fields"], "complexity": 3, "decorators": [], "hash": "dee4821e85b2682a", "kind": "function", "lines": 5, "module": "workflows._guided_controls", "name": "_missing_repeats", "public": false, "signature": "(scan: Any, condition: Any) -> list[Any]", "summary": "The repeats where other conditions are imaged and ``condition`` is not.", "varargs": []} {"arguments": 3, "called_by": ["workflows._guided_controls:ask_controls"], "calls": ["?.get", "?.say", "iter", "next", "workflows._guided_ask:yes_no", "workflows._guided_controls:_missing_repeats", "workflows._guided_controls:image_table", "workflows._guided_controls:proposed_controls"], "complexity": 4, "decorators": [], "hash": "1919705223a5fabc", "kind": "function", "lines": 7, "module": "workflows._guided_controls", "name": "ask_gate", "public": true, "signature": "(ask: Ask, say: Say, scan: Any) -> bool", "summary": "Whether every condition is compared with the same control; No is proposed (after the", "varargs": []} -{"arguments": 4, "called_by": ["workflows._guided_controls:ask_several"], "calls": ["?.join", "?.say", "dict", "len", "set", "str", "workflows._guided_ask:text", "workflows._guided_ask:yes_no", "workflows._guided_controls:treatment_key", "zip"], "complexity": 3, "decorators": [], "hash": "2c8077a808b51025", "kind": "function", "lines": 7, "module": "workflows._guided_controls", "name": "_keys", "public": false, "signature": "(ask: Ask, say: Say, control: Any, members: list[Any]) -> dict[Any, Any]", "summary": "", "varargs": []} +{"arguments": 4, "called_by": ["workflows._guided_controls:ask_several"], "calls": ["?.join", "?.say", "all", "dict", "len", "set", "str", "workflows._guided_ask:text", "workflows._guided_ask:yes_no", "workflows._guided_controls:treatment_key", "zip"], "complexity": 5, "decorators": [], "hash": "1791d6fbf823ca03", "kind": "function", "lines": 11, "module": "workflows._guided_controls", "name": "_keys", "public": false, "signature": "(ask: Ask, say: Say, control: Any, members: list[Any]) -> dict[Any, Any]", "summary": "", "varargs": []} {"arguments": 4, "called_by": ["workflows._guided_controls:ask_several"], "calls": ["?.startswith", "len", "max", "re.match", "str", "workflows._guided_ask:text", "workflows._guided_ask:yes_no"], "complexity": 5, "decorators": [], "hash": "51294a610bd95c29", "kind": "function", "lines": 9, "module": "workflows._guided_controls", "name": "_parent", "public": false, "signature": "(ask: Ask, say: Say, control: Any, conditions: list[Any]) -> Any", "summary": "The parent proposed when the control's name extends another condition's, confirmed;", "varargs": []} -{"arguments": 6, "called_by": ["workflows._guided_controls:ask_several"], "calls": ["?.setdefault", "?.update", "str", "workflows._guided_ask:choose", "workflows._guided_controls:treatment_key"], "complexity": 6, "decorators": [], "hash": "e1adda2d0e5552cf", "kind": "function", "lines": 14, "module": "workflows._guided_controls", "name": "_unlinked", "public": false, "signature": "(ask: Ask, say: Say, conditions: list[Any], controls: list[Any], found: dict[Any, dict], assigned: set[Any]) -> list[Any]", "summary": "Each condition not yet compared with anything asked for its control (default none):", "varargs": []} +{"arguments": 6, "called_by": ["workflows._guided_controls:ask_several"], "calls": ["?.say", "?.setdefault", "?.update", "str", "workflows._guided_ask:choose", "workflows._guided_ask:text", "workflows._guided_controls:treatment_key"], "complexity": 9, "decorators": [], "hash": "78b0bba91f038472", "kind": "function", "lines": 19, "module": "workflows._guided_controls", "name": "_unlinked", "public": false, "signature": "(ask: Ask, say: Say, conditions: list[Any], controls: list[Any], found: dict[Any, dict], assigned: set[Any]) -> list[Any]", "summary": "Each condition not yet compared with anything asked for its control (default none):", "varargs": []} {"arguments": 2, "called_by": ["workflows._guided_controls:ask_several"], "calls": ["?.get", "?.groupby", "?.nunique", "int", "max", "workflows._guided_controls:_fields"], "complexity": 3, "decorators": [], "hash": "390bb2edb29bff85", "kind": "function", "lines": 5, "module": "workflows._guided_controls", "name": "most_imaged", "public": true, "signature": "(scan: Any, controls: list[Any]) -> Any", "summary": "The control imaged in the most biological repeats, ties to the first declared: the", "varargs": []} {"arguments": 3, "called_by": ["workflows._guided_controls:ask_controls"], "calls": ["?.say", "?.startswith", "?.update", "len", "list", "set", "sorted", "str", "workflows._guided_ask:choose", "workflows._guided_ask:choose_many", "workflows._guided_controls:_keys", "workflows._guided_controls:_parent", "workflows._guided_controls:_stem", "workflows._guided_controls:_unlinked", "workflows._guided_controls:most_imaged", "workflows._guided_controls:proposed_controls", "workflows.setup:Setup"], "complexity": 12, "decorators": [], "hash": "9416334a9e20d0b1", "kind": "function", "lines": 42, "module": "workflows._guided_controls", "name": "ask_several", "public": true, "signature": "(ask: Ask, say: Say, scan: Any) -> tuple[dict, dict | None, Any]", "summary": "Several controls: ``(control, control_parents, master_control)`` (see the module).", "varargs": []} {"arguments": 3, "called_by": ["workflows._guided_described:ask_any_controls"], "calls": ["workflows._guided_ask:ask_control", "workflows._guided_controls:ask_gate", "workflows._guided_controls:ask_several"], "complexity": 3, "decorators": [], "hash": "51d8049be3e8d87d", "kind": "function", "lines": 3, "module": "workflows._guided_controls", "name": "ask_controls", "public": true, "signature": "(ask: Ask, say: Say, scan: Any) -> tuple[dict | None, dict | None, Any]", "summary": "The gate, then one control or several: ``(control, control_parents, master)``.", "varargs": []} @@ -3588,7 +3596,8 @@ {"arguments": 7, "called_by": ["workflows.retrospective:report"], "calls": ["?.get", "bool", "retrospective.inspection:Summary", "retrospective.inspection:inspect_fovs", "workflows._one_per_field:listed_once", "workflows._result_influence:influence_on_result", "workflows._result_influence:with_result_influence"], "complexity": 7, "decorators": [], "hash": "e7378ec40f25c4e8", "kind": "function", "lines": 22, "module": "workflows.retrospective", "name": "_inspection", "public": false, "signature": "(novel: pd.DataFrame, objects: pd.DataFrame, fovs: pd.DataFrame, setup: Setup, space: tuple[Any, list[str]], results: dict[str, Any], per_field: bool) -> Any", "summary": "R5: the fields to inspect, every reason at once: new states on the declared", "varargs": []} {"arguments": 11, "called_by": [], "calls": ["?.compared_values", "?.items", "?.resolved_effort_strata", "?.resolved_hierarchy", "?.stopping_rules", "?.update", "ValueError", "_checks:is_share", "_observation_units:resolve_observation_unit", "dataclasses.replace", "list", "workflows._document:assemble", "workflows._embedding_report:embedding_plan", "workflows._embedding_report:plan_document", "workflows._fingerprint_space:fingerprint_space", "workflows._one_per_field:field_setup", "workflows._one_per_field:one_per_field", "workflows._pairing:paired_inputs", "workflows._report_steps:check_criteria", "workflows._report_steps:reliability", "workflows._report_steps:replay_results", "workflows._results:Plan", "workflows._shared:check_workflow_inputs", "workflows._shared:orders", "workflows._shared:replay_rules", "workflows._shared:reservoir_sizes", "workflows._source:source_identity", "workflows.retrospective:_protocol", "workflows.retrospective:document"], "complexity": 5, "decorators": [], "hash": "6f023eaa1b90cc9f", "kind": "function", "lines": 60, "module": "workflows.retrospective", "name": "optimise", "public": true, "signature": "(objects: pd.DataFrame, fovs: pd.DataFrame, setup: Setup, *, fov_counts: Sequence[int], reservoir_fraction: float, n_splits: int=5, draws: int=50, permuted_orders: int=10, dispersed_orders: int=5, protocol_threshold: float=0.9, redundancy_bins: Sequence[float] | None=None) -> Plan", "summary": "OPTIMISE: what the next experiment should do, from what this one preserved.", "varargs": []} {"arguments": 7, "called_by": ["workflows.retrospective:optimise"], "calls": ["?.update", "retrospective.protocol:protocol_reliability", "workflows._document:no_hierarchy_reasons", "workflows._document:protocol_reason"], "complexity": 3, "decorators": [], "hash": "99bfa80bc72b47e0", "kind": "function", "lines": 15, "module": "workflows.retrospective", "name": "_protocol", "public": false, "signature": "(fovs: pd.DataFrame, setup: Setup, hierarchy: SamplingHierarchy | None, strata: Sequence[str], threshold: float, results: dict[str, Any], reasons: dict[str, str]) -> None", "summary": "P2: protocol reliability across samples, added to ``results`` (in place), when the", "varargs": []} -{"arguments": 2, "called_by": ["workflows.retrospective:_check_parts"], "calls": ["all", "dataclasses.fields", "getattr", "workflows.setup:Setup"], "complexity": 1, "decorators": [], "hash": "d8d01234e6a17529", "kind": "function", "lines": 5, "module": "workflows.retrospective", "name": "_same_setup", "public": false, "signature": "(first: Setup, other: Setup) -> bool", "summary": "Whether two setups declare the same analysis (``n_jobs`` changes no result).", "varargs": []} +{"arguments": 2, "called_by": ["workflows.retrospective:_check_parts"], "calls": ["all", "dataclasses.fields", "getattr", "workflows.retrospective:_same_value", "workflows.setup:Setup"], "complexity": 1, "decorators": [], "hash": "be1eed16c4f29a19", "kind": "function", "lines": 5, "module": "workflows.retrospective", "name": "_same_setup", "public": false, "signature": "(first: Setup, other: Setup) -> bool", "summary": "Whether two setups declare the same analysis (``n_jobs`` changes no result).", "varargs": []} +{"arguments": 2, "called_by": ["workflows.retrospective:_same_setup"], "calls": ["?.equals", "bool", "isinstance"], "complexity": 5, "decorators": [], "hash": "d6582e2461b54af2", "kind": "function", "lines": 7, "module": "workflows.retrospective", "name": "_same_value", "public": false, "signature": "(first: Any, other: Any) -> bool", "summary": "Whether two values of a Setup field are the same: a contrast table by its values", "varargs": []} {"arguments": 1, "called_by": ["workflows.retrospective:document"], "calls": ["TypeError", "ValueError", "isinstance", "sum", "workflows._results:Plan", "workflows._results:Report", "workflows._source:same_source", "workflows.retrospective:_same_setup"], "complexity": 9, "decorators": [], "hash": "b25b0111301f6b6a", "kind": "function", "lines": 23, "module": "workflows.retrospective", "name": "_check_parts", "public": false, "signature": "(parts: tuple[Report | Plan, ...]) -> None", "summary": "The parts ``document`` merges: results of ``report``/``optimise``, at most one of each,", "varargs": []} {"arguments": 0, "called_by": ["workflows.retrospective:optimise", "workflows.retrospective:report"], "calls": ["?.append", "?.update", "?.writer", "ValueError", "isinstance", "set", "sorted", "workflows._document:assemble", "workflows._document:plan_settings", "workflows._document:report_settings", "workflows._document:with_reasons", "workflows._document:with_settings", "workflows._results:Report", "workflows.retrospective:_check_parts"], "complexity": 6, "decorators": [], "hash": "78158bf84ee883b0", "kind": "function", "lines": 17, "module": "workflows.retrospective", "name": "document", "public": true, "signature": "(*parts: Report | Plan) -> MicroscopistReport", "summary": "The full microscopist's report from a ``report`` and a ``plan`` of the same data.", "varargs": ["*parts"]} {"calls": ["re.compile", "typing.TypeVar"], "kind": "module", "module": "workflows.scan", "name": "", "public": true, "summary": "Scan the experimental design before any analysis: what the dataset is, whether it was"} diff --git a/docs/common/glossary.md b/docs/common/glossary.md index 04f26f94..618328b2 100644 --- a/docs/common/glossary.md +++ b/docs/common/glossary.md @@ -88,7 +88,7 @@ Every test, rule and term the report uses, in plain words, with where it appears *Where:* Do the conditions differ?: the test behind 'significant across repeats', the result to report. *See:* [Lord SJ, Velle KB, Mullins RD, Fritz-Laylin LK. SuperPlots: communicating reproducibility and variability in cell biology. J Cell Biol. 2020;219(6):e202001064.](https://doi.org/10.1083/jcb.202001064) -**Sign-flip test.** The exact test on the signs of the per-repeat differences; given only from 6 repeats, where its smallest p can reach 0.05 after the correction. +**Sign-flip test.** A two-sided paired permutation test on the mean of the per-repeat differences: each difference keeps its magnitude while its sign is flipped under the null. The p is exact up to 16 repeats (every sign assignment enumerated) and Monte Carlo above (20,000 random assignments). Given only where its smallest p can reach 0.05 after the correction (from 6 repeats for one condition). *Where:* Do the conditions differ?, full detail. diff --git a/notebooks/MorphoCoverage_Workflows_Example/MorphoCoverage_Workflows_Example.ipynb b/notebooks/MorphoCoverage_Workflows_Example/MorphoCoverage_Workflows_Example.ipynb index 58336a62..97b96154 100644 --- a/notebooks/MorphoCoverage_Workflows_Example/MorphoCoverage_Workflows_Example.ipynb +++ b/notebooks/MorphoCoverage_Workflows_Example/MorphoCoverage_Workflows_Example.ipynb @@ -540,13 +540,20 @@ "if positive_control and not use_positive:\n", " print(\"⚠️ The positive control needs a negative control and 'Assess novelty': \"\n", " \"it is left out, and question 2 will be 'Not assessed'.\")\n", + "# Positive and reference fields are paired within each biological repeat by its canonical\n", + "# repeat_group, never by the folder label (biological_repeat), which two conditions may share\n", + "# for different repeats.\n", + "if use_positive and \"repeat_group\" not in fovs.columns:\n", + " raise ValueError(\"The positive control is paired by repeat_group, which the FOV table \"\n", + " \"lacks: add it (one value per biological repeat), or leave the positive \"\n", + " \"control box empty.\")\n", "\n", "setup = Setup(\n", " readout=readout,\n", " features=features,\n", " control={\"condition\": negative_control} if negative_control else None,\n", " positive=(\n", - " PositiveControl({\"condition\": positive_control}, fovs_seen=10, pair_cols=(\"biological_repeat\",),\n", + " PositiveControl({\"condition\": positive_control}, fovs_seen=10, pair_cols=(\"repeat_group\",),\n", " planted_objects=5)\n", " if use_positive else None\n", " ),\n", diff --git a/src/morphocoverage/_areas.py b/src/morphocoverage/_areas.py index 4a5ba1f4..be913d29 100644 --- a/src/morphocoverage/_areas.py +++ b/src/morphocoverage/_areas.py @@ -8,6 +8,7 @@ from __future__ import annotations +import math from collections.abc import Sequence import numpy as np @@ -17,8 +18,9 @@ def area_problem(fovs: pd.DataFrame, area_col: str, fov_key: Sequence[str]) -> str | None: """Why the areas in ``fovs[area_col]`` cannot be summed, or ``None`` when they can. - An imaged area is a positive, finite number, recorded for every field: - a missing area summed as zero would understate the effort, and an + An imaged area is a positive, finite number, recorded for every field, and their + total must be finite too (one that overflows a float would read as an infinite + effort, #544): a missing area summed as zero would understate the effort, and an infinite, zero or negative one is impossible. The problem names up to three such fields by ``fov_key``; each caller raises it or reports it. Areas that are not numbers (text such as ``"100"`` would be concatenated, @@ -41,7 +43,23 @@ def area_problem(fovs: pd.DataFrame, area_col: str, fov_key: Sequence[str]) -> s f"area_col {area_col!r} has infinite, zero or negative areas for some fields, " f"e.g. {where}; an imaged area is a positive, finite number" ) + if len(values) and not math.isfinite(_total(values)): + return ( + f"area_col {area_col!r}: the fields' areas are each finite but their total " + "overflows a float; express them in larger units" + ) return None +def _total(values: np.ndarray) -> float: + """The sum of positive, finite ``values``, infinite when it overflows a float (#544). + + Summed as the largest value times the sum of the values divided by it (each at most + 1), so the sum itself cannot overflow and only the final product, a Python float, can + become infinite, without a numpy overflow warning. + """ + largest = float(values.max()) + return largest * float((values / largest).sum()) + + __all__ = ["area_problem"] diff --git a/src/morphocoverage/_frozen.py b/src/morphocoverage/_frozen.py index 72e758e0..42603a28 100644 --- a/src/morphocoverage/_frozen.py +++ b/src/morphocoverage/_frozen.py @@ -32,7 +32,11 @@ def _refuse(*_: Any, **__: Any) -> NoReturn: class FrozenDict(dict[Any, Any]): - """A dict that cannot be changed after construction (equal to, and serialised as, a dict).""" + """A dict that cannot be changed after construction (equal to, and serialised as, a dict). + Built directly, it freezes what it is given, so ``freeze`` may trust any one (#581).""" + + def __init__(self, *args: Any, **kwargs: Any) -> None: + dict.__init__(self, {k: freeze(v) for k, v in dict(*args, **kwargs).items()}) __setitem__ = __delitem__ = __ior__ = _refuse clear = pop = popitem = setdefault = update = _refuse @@ -48,7 +52,11 @@ def __copy__(self) -> FrozenDict: class FrozenList(list[Any]): - """A list that cannot be changed after construction (equal to, and serialised as, a list).""" + """A list that cannot be changed after construction (equal to, and serialised as, a list). + Built directly, it freezes what it is given, so ``freeze`` may trust any one (#581).""" + + def __init__(self, items: Iterable[Any] = ()) -> None: + list.__init__(self, (freeze(v) for v in items)) __setitem__ = __delitem__ = __iadd__ = __imul__ = _refuse append = extend = insert = remove = pop = clear = sort = reverse = _refuse @@ -68,9 +76,9 @@ def freeze(value: Any) -> Any: if isinstance(value, FrozenDict | FrozenList): return value if isinstance(value, Mapping): - return FrozenDict({k: freeze(v) for k, v in value.items()}) + return FrozenDict(value.items()) if isinstance(value, list): - return FrozenList(freeze(v) for v in value) + return FrozenList(value) if isinstance(value, tuple): return ( type(value)(*map(freeze, value)) diff --git a/src/morphocoverage/_repeat_statistics.py b/src/morphocoverage/_repeat_statistics.py index 6895c828..0710e278 100644 --- a/src/morphocoverage/_repeat_statistics.py +++ b/src/morphocoverage/_repeat_statistics.py @@ -17,6 +17,8 @@ import numpy as np from scipy import stats +from ._checks import is_share + def paired_t(differences: np.ndarray) -> float: """The two-sided paired t-test of ``differences`` (one per biological repeat); NaN when a @@ -79,8 +81,13 @@ def repeat_effect(values: str, compared: np.ndarray, level: float = 0.95) -> dic log ratios, else differences) and the t-based ``level`` interval of their mean effect (``n - 1`` degrees of freedom, back-transformed for fold changes): ``ci_low`` and ``ci_high``, NaN below 2 repeats or with a missing value (plan v2, owner, 2026-10-06: with - 3 repeats each verdict shows them).""" + 3 repeats each verdict shows them). ``level`` must be in (0, 1), and an infinite + contrast is refused: it has no mean to give an interval of (#528).""" + if not is_share(level): + raise ValueError(f"level must be a number in (0, 1), not {level!r}") compared = np.asarray(compared, dtype=float) + if np.isinf(compared).any(): + raise ValueError("the per-repeat contrasts must be finite or missing, not infinite") shown = np.exp(compared) if values == "normalised" else compared low = high = float("nan") if len(compared) >= 2 and not np.isnan(compared).any(): diff --git a/src/morphocoverage/_robust_sd.py b/src/morphocoverage/_robust_sd.py index c7c9186c..9e26d371 100644 --- a/src/morphocoverage/_robust_sd.py +++ b/src/morphocoverage/_robust_sd.py @@ -52,7 +52,8 @@ def constant_columns(matrix: np.ndarray) -> np.ndarray: (1e-7) of its absolute mean. """ spread = np.ptp(matrix, axis=0) - sd = matrix.std(axis=0, ddof=1) if len(matrix) > 1 else np.zeros(matrix.shape[1]) + # matrix.shape[1:]: one value per column, or one value for a 1-D sample (#418). + sd = matrix.std(axis=0, ddof=1) if len(matrix) > 1 else np.zeros(matrix.shape[1:]) scale = np.abs(matrix.mean(axis=0)) return (spread == 0) | (sd <= CONSTANT_RELATIVE_SPREAD * scale) diff --git a/src/morphocoverage/_stage_coordinates.py b/src/morphocoverage/_stage_coordinates.py index 59b625b9..e627b194 100644 --- a/src/morphocoverage/_stage_coordinates.py +++ b/src/morphocoverage/_stage_coordinates.py @@ -6,6 +6,8 @@ - two distinct column names (one axis cannot stand for two); - real numeric columns: booleans, complex numbers, text and untyped (object) columns are refused, never converted (no ``float()`` of text, no ``errors="coerce"``); +- values a float cannot hold refused: too large (as infinite) or an integer beyond 2**53 + that would lose digits, so two positions never become one (#538); - infinite values always refused; missing values refused (``"refuse"``) or kept as NaN where an analysis handles missing positions explicitly (``"keep"``). @@ -22,6 +24,8 @@ from .metadata import column_names Missing = Literal["refuse", "keep"] +# Every integer up to this magnitude is held exactly by a float64 (its 53-bit significand). +_EXACT_INTEGERS = 2**53 def stage_names(stage_cols: object, name: str = "stage_cols") -> tuple[str, str]: @@ -76,11 +80,39 @@ def stage_matrix( ) for column in (x_col, y_col): _check_axis(table[column], column) - xy = table[[x_col, y_col]].to_numpy(dtype=float, na_value=np.nan) + xy = np.column_stack([_axis_floats(table[column], column) for column in (x_col, y_col)]) _check_values(xy, missing) return xy +def _axis_floats(values: pd.Series, column: str) -> np.ndarray: + """A checked coordinate column as floats: a value too large for a float is refused as + not finite, and an integer a float cannot hold exactly (beyond 2**53) is refused, so + two positions never become one (#538).""" + try: + floats = values.to_numpy(dtype=float, na_value=np.nan) + except OverflowError: + raise ValueError( + f"stage coordinates must be finite: column {column!r} holds a value too large " + "for a float" + ) from None + _check_exact(values.to_numpy(dtype=object), floats, f"stage column {column!r}") + return floats + + +def _check_exact(raw: np.ndarray, floats: np.ndarray, name: str) -> None: + """Refuse an integer of ``raw`` that its float in ``floats`` does not hold exactly; only + magnitudes from 2**53 can lose digits, so only those are compared.""" + for index in np.flatnonzero(np.abs(np.nan_to_num(floats)) >= _EXACT_INTEGERS): + value = raw.flat[index] + if isinstance(value, int | np.integer) and int(floats.flat[index]) != int(value): + raise ValueError( + f"{name} holds {value}, which a float cannot hold exactly (integers beyond " + "2**53), so distinct positions could coincide; express the coordinates in " + "larger units" + ) + + def _check_values(xy: np.ndarray, missing: Missing) -> None: if np.isinf(xy).any(): raise ValueError("stage coordinates must be finite: correct or drop the infinite ones") @@ -90,15 +122,17 @@ def _check_values(xy: np.ndarray, missing: Missing) -> None: def check_xy(xy: Any, name: str = "xy", *, missing: Missing = "refuse") -> np.ndarray: """``xy`` as a float ``(n, 2)`` array of real, finite positions (booleans, complex numbers - and text are refused, not converted).""" + and text are refused, not converted; integers a float cannot hold exactly too).""" array = np.asarray(xy) if array.dtype.kind not in "fiu": raise TypeError(f"{name} must hold real numbers, not {array.dtype}") if array.ndim != 2 or array.shape[1] != 2: raise ValueError(f"{name} must have shape (n, 2), not {array.shape}") - array = array.astype(float) - _check_values(array, missing) - return array + floats = array.astype(float) + if array.dtype.kind in "iu": + _check_exact(array, floats, name) + _check_values(floats, missing) + return floats __all__ = ["Missing", "check_xy", "stage_matrix", "stage_names"] diff --git a/src/morphocoverage/benchmark.py b/src/morphocoverage/benchmark.py index 75c88bfb..e8f89e96 100644 --- a/src/morphocoverage/benchmark.py +++ b/src/morphocoverage/benchmark.py @@ -297,7 +297,9 @@ class BenchmarkRecord: stop_on: str = "decision" def as_row(self) -> dict[str, Any]: - """A flat dict: group columns as ``group.``, outcomes as ``outcome.``.""" + """A flat dict: group columns as ``group.``, outcomes as ``outcome.``, + each beside its metric's config id as ``outcome_id.``, so two metrics given one + label stay apart once exported (#547).""" row: dict[str, Any] = { "dataset": self.dataset, "role": self.role.value, @@ -335,6 +337,7 @@ def as_row(self) -> dict[str, Any]: row[f"reservoir.{key}"] = value row.update({f"group.{column}": value for column, value in self.group.items()}) row.update({f"outcome.{name}": value for name, value in self.outcomes.items()}) + row.update({f"outcome_id.{name}": value for name, value in self.outcome_ids.items()}) return row diff --git a/src/morphocoverage/feature_tables.py b/src/morphocoverage/feature_tables.py index fbad3c2d..9e1d224c 100644 --- a/src/morphocoverage/feature_tables.py +++ b/src/morphocoverage/feature_tables.py @@ -301,12 +301,12 @@ def _column_problems( f"{other!r} and {name!r} share columns {listing(both, _SHOWN)}; rename them, as " "each feature must have one name" ) - numeric = [ - c - for c in columns - if pd.api.types.is_numeric_dtype(table[c]) and not pd.api.types.is_bool_dtype(table[c]) - ] - words = [c for c in columns if c not in numeric] + complex_, numeric, words = _column_kinds(table, columns) + if complex_: + problems.append( + f"{name!r} has complex columns: {listing(complex_, _SHOWN)} (a feature holds real " + "numbers)" + ) if words: problems.append( f"{name!r} has columns that are not numbers: {listing(words, _SHOWN)} (a feature " @@ -328,6 +328,24 @@ def _column_problems( return problems +def _column_kinds( + table: pd.DataFrame, columns: list[Any] +) -> tuple[list[Any], list[Any], list[Any]]: + """The ``columns`` of ``table`` that are complex, real numbers, and neither. Complex + columns are told apart before any float cast, which would drop their imaginary part (an + infinity in it unseen, a varying one read as constant; #485).""" + complex_ = [c for c in columns if pd.api.types.is_complex_dtype(table[c])] + numeric = [ + c + for c in columns + if pd.api.types.is_numeric_dtype(table[c]) + and not pd.api.types.is_bool_dtype(table[c]) + and c not in complex_ + ] + words = [c for c in columns if c not in numeric and c not in complex_] + return complex_, numeric, words + + def _constant(block: pd.DataFrame) -> tuple[str, ...]: """The columns of ``block`` with one value everywhere (missing values aside).""" values = block.to_numpy(dtype=float) diff --git a/src/morphocoverage/glossary.py b/src/morphocoverage/glossary.py index 169ba14d..476e1c11 100644 --- a/src/morphocoverage/glossary.py +++ b/src/morphocoverage/glossary.py @@ -220,8 +220,11 @@ class Term: Term( "Do the conditions differ?", "Sign-flip test", - "The exact test on the signs of the per-repeat differences; given only from 6 repeats, " - "where its smallest p can reach 0.05 after the correction.", + "A two-sided paired permutation test on the mean of the per-repeat differences: each " + "difference keeps its magnitude while its sign is flipped under the null. The p is " + "exact up to 16 repeats (every sign assignment enumerated) and Monte Carlo above " + "(20,000 random assignments). Given only where its smallest p can reach 0.05 after " + "the correction (from 6 repeats for one condition).", "Do the conditions differ?, full detail", ), Term( diff --git a/src/morphocoverage/retrospective/report_profile.py b/src/morphocoverage/retrospective/report_profile.py index 220d342f..9cdfc601 100644 --- a/src/morphocoverage/retrospective/report_profile.py +++ b/src/morphocoverage/retrospective/report_profile.py @@ -92,14 +92,16 @@ def _detection_words(controls: ControlResult, kind: str, detection: float) -> tu def _adjusted_lines(frame: pd.DataFrame, keys: list[str], low: float) -> list[str]: - """Each group's unseen-state bound divided by the low end of the detection rate.""" + """Each group's unseen-state bound divided by the low end of the detection rate. Rows are + read by column name, so a group column that is not a Python identifier (``"plate id"``, + which ``itertuples`` renames) names its group too (#449).""" lines = [] - for row in frame.itertuples(index=False): - bound = row.unseen_state_max_frequency + for row in frame.to_dict("records"): + bound = row["unseen_state_max_frequency"] if bound is None or pd.isna(bound): continue adjusted = min(1.0, float(bound) / low) - label = ", ".join(f"{k}={getattr(row, k)}" for k in keys) or "all FOVs (pooled)" + label = ", ".join(f"{k}={row[k]}" for k in keys) or "all FOVs (pooled)" lines.append( f" {label}: up to {percent(adjusted)} of FOVs (the {percent(float(bound))} " f"bound above divided by {percent(low)}), if detection is independent " diff --git a/src/morphocoverage/sampling_unit/whole_table.py b/src/morphocoverage/sampling_unit/whole_table.py index c96b67ce..98888193 100644 --- a/src/morphocoverage/sampling_unit/whole_table.py +++ b/src/morphocoverage/sampling_unit/whole_table.py @@ -71,6 +71,7 @@ import pandas as pd from scipy import stats +from .._checks import as_count, check_seed from .._frozen import owned from .._seeds import group_rng from ..embedding import robust_scale @@ -393,7 +394,11 @@ def whole_table_tests( ) -> WholeTable: """The whole-table tests of every table (``tables``: each name and its columns) for each ``(condition, control)`` of ``pairs`` (see the module); ``families``, each condition's - declared experiment (``Setup.experiment``), sets the correction families.""" + declared experiment (``Setup.experiment``), sets the correction families. + ``permutations`` is a count of at least 1 and ``random_state`` a seed: no draws would + print a p of 1 that no shuffle computed (#491).""" + permutations = as_count(permutations, "permutations") + random_state = check_seed(random_state) rows: list[dict[str, Any]] = [] left: dict[str, int] = {} for name, columns in tables.items(): diff --git a/src/morphocoverage/strategies/_descriptor_resamples.py b/src/morphocoverage/strategies/_descriptor_resamples.py index 06fc3869..337e1417 100644 --- a/src/morphocoverage/strategies/_descriptor_resamples.py +++ b/src/morphocoverage/strategies/_descriptor_resamples.py @@ -92,6 +92,12 @@ def _chunk_sizes(total: int, chunk: int) -> list[int]: return [min(chunk, total - start) for start in range(0, total, chunk)] +def _check_resamples(n_resamples: int) -> None: + """At least one resample: none would describe nothing.""" + if n_resamples < 1: + raise ValueError(f"n_resamples must be at least 1, not {n_resamples}") + + def _object_resamples( values: np.ndarray, n_resamples: int, rng: np.random.Generator, descriptors: Sequence[str] ) -> dict[str, np.ndarray]: @@ -100,8 +106,11 @@ def _object_resamples( ``values`` come in the caller's canonical order (sorted), which the draws index. Memory is bounded as for whole FOVs: each chunk holds its resamples' values at once, and drawing chunk by chunk from one generator - gives the same draws as all at once. + gives the same draws as all at once. No value, or no resample, is refused (#532). """ + if not len(values): + raise ValueError("object resamples need at least one value; there is no value") + _check_resamples(n_resamples) chunk = max(1, int(_MAX_RESAMPLED_VALUES // len(values))) parts = [ _describe_many(values[rng.integers(0, len(values), size=(size, len(values)))], descriptors) @@ -123,8 +132,17 @@ def _fov_resamples( ``positions`` gives each value's FOV in the caller's canonical FOV order, which the draws index; within a FOV the values are ordered by value, so the table's row order cannot change a resample. Memory is bounded: each - chunk materializes its resamples' values at once. + chunk materializes its resamples' values at once. FOVs without values are kept + (a resample of them only has NaN descriptors); no FOV, no resample, or a position that + is not one of the ``k`` FOVs or one per value, is refused (#532). """ + if k < 1: + raise ValueError(f"FOV resamples need at least one FOV, not k={k}") + _check_resamples(n_resamples) + if len(positions) != len(values) or ( + len(positions) and (positions.min() < 0 or positions.max() >= k) + ): + raise ValueError(f"positions must give each value's FOV, one of 0 to {k - 1}") by_fov = np.lexsort((values, positions)) # values grouped by FOV, each FOV by value counts = np.bincount(positions, minlength=k) draws = rng.integers(0, k, size=(n_resamples, k)) diff --git a/src/morphocoverage/strategies/jcb_planning.py b/src/morphocoverage/strategies/jcb_planning.py index dbd97ece..2c1ce2f1 100644 --- a/src/morphocoverage/strategies/jcb_planning.py +++ b/src/morphocoverage/strategies/jcb_planning.py @@ -272,6 +272,7 @@ def _samples( if column not in table.columns: table[column] = data.objects[column] is_control = np.logical_and.reduce([table[c].eq(v).to_numpy() for c, v in control.items()]) + _refuse_mixed_samples(table, is_control, sample_cols, control) # observed=True: with categorical sample columns, only the samples present in the # pilot, never unobserved combinations of categories (pandas 2 defaults to all). by_sample = table.groupby(list(sample_cols), sort=True, observed=True)["_value"] @@ -292,6 +293,29 @@ def _samples( return by_sample, control_means, control_mean +def _refuse_mixed_samples( + table: pd.DataFrame, + is_control: np.ndarray, + sample_cols: tuple[str, ...], + control: Mapping[str, Any], +) -> None: + """Refuse a sample that holds both control and other cells: centring it on its own mean + would put the treatment's shift into the within-sample SD (#430).""" + kinds = ( + pd.Series(is_control, index=table.index) + .groupby([table[c] for c in sample_cols], observed=True) + .nunique() + ) + mixed = [key if isinstance(key, tuple) else (key,) for key in kinds.index[kinds > 1]] + if mixed: + named = listing([repr(key[0]) if len(key) == 1 else repr(key) for key in mixed], limit=5) + raise ValueError( + f"samples by {list(sample_cols)} hold both control and other cells: {named}; a " + "sample must be one kind, so add the column telling them apart (for example the " + f"condition, {list(control)}) to sample_cols" + ) + + def _within_sample_cv( values: np.ndarray, by_sample: Any, n_samples: int, control_mean: float ) -> tuple[np.ndarray, float, float, float]: diff --git a/src/morphocoverage/transforms.py b/src/morphocoverage/transforms.py index ae6444fb..8373cc52 100644 --- a/src/morphocoverage/transforms.py +++ b/src/morphocoverage/transforms.py @@ -39,7 +39,7 @@ import numpy as np -from ._checks import is_integer +from ._checks import check_flag, is_integer, is_positive_finite from ._frozen import owned from ._robust_sd import CONSTANT_RELATIVE_SPREAD, constant_columns from ._wording import listing @@ -368,10 +368,11 @@ class ColumnWeights(FeatureTransform): weights: tuple[float, ...] def __post_init__(self) -> None: - values = tuple(float(w) for w in self.weights) - if not values or not all(np.isfinite(w) and w > 0 for w in values): + # Checked before any float(): True would become 1.0 and "2.0" 2.0 (#495). + weights = tuple(self.weights) + if not weights or not all(is_positive_finite(w) for w in weights): raise ValueError("weights must be one positive finite number per feature") - object.__setattr__(self, "weights", values) + object.__setattr__(self, "weights", tuple(float(w) for w in weights)) @property def name(self) -> str: @@ -421,10 +422,16 @@ class BlockWeights(FeatureTransform): inertia_radius: bool = False def __post_init__(self) -> None: - blocks = tuple(tuple(str(c) for c in block) for block in self.blocks) + blocks = tuple(tuple(block) for block in self.blocks) if not blocks or any(not block for block in blocks): raise ValueError("blocks must be one or more non-empty tuples of feature names") + # Names are taken as given, never recast with str() (#495). + if not all(isinstance(c, str) and c.strip() for block in blocks for c in block): + raise TypeError("blocks must hold feature names (non-empty text)") object.__setattr__(self, "blocks", blocks) + object.__setattr__( + self, "inertia_radius", check_flag(self.inertia_radius, "inertia_radius") + ) @property def name(self) -> str: diff --git a/src/morphocoverage/workflows/_guided_controls.py b/src/morphocoverage/workflows/_guided_controls.py index d82ca4d1..7f9de6da 100644 --- a/src/morphocoverage/workflows/_guided_controls.py +++ b/src/morphocoverage/workflows/_guided_controls.py @@ -125,6 +125,10 @@ def _keys(ask: Ask, say: Say, control: Any, members: list[Any]) -> dict[Any, Any say(" Treatment keys: " + "; ".join(f"{k}: {m}" for k, m in zip(keys, members, strict=True))) if not yes_no(ask, say, f"Use these keys for {control}?", True): keys = [text(ask, f"Treatment key of {m}:", k) for k, m in zip(keys, members, strict=True)] + # Keys entered twice would keep only the last condition of the key (#448). + while len(set(keys)) < len(keys) or not all(keys): + say(f" Each condition of {control} needs its own treatment key. Please answer again.") + keys = [text(ask, f"Treatment key of {m}:") for m in members] return dict(zip(keys, members, strict=True)) @@ -163,7 +167,12 @@ def _unlinked( continue members = found.setdefault(chosen, {}) key = treatment_key(chosen, condition) - members[str(condition) if key in members else key] = condition + key = str(condition) if key in members else key + while not key or key in members: # never overwrite the condition holding it (#448) + taken = f"is taken under {chosen} by {members[key]}" if key else "is empty" + say(f" The treatment key {key!r} {taken}. Please answer again.") + key = text(ask, f"Treatment key of {condition} under {chosen}:") + members[key] = condition assigned.update((condition, chosen)) controls += [] if chosen in controls else [chosen] return controls diff --git a/src/morphocoverage/workflows/retrospective.py b/src/morphocoverage/workflows/retrospective.py index 2fa0196a..3d789b61 100644 --- a/src/morphocoverage/workflows/retrospective.py +++ b/src/morphocoverage/workflows/retrospective.py @@ -417,12 +417,24 @@ def _protocol( def _same_setup(first: Setup, other: Setup) -> bool: """Whether two setups declare the same analysis (``n_jobs`` changes no result).""" return all( - getattr(first, f.name) == getattr(other, f.name) + _same_value(getattr(first, f.name), getattr(other, f.name)) for f in fields(Setup) if f.name != "n_jobs" ) +def _same_value(first: Any, other: Any) -> bool: + """Whether two values of a Setup field are the same: a contrast table by its values + (``DataFrame.equals``), since a DataFrame's ``==`` has no truth value (#551).""" + if isinstance(first, pd.DataFrame) or isinstance(other, pd.DataFrame): + return ( + isinstance(first, pd.DataFrame) + and isinstance(other, pd.DataFrame) + and first.equals(other) + ) + return bool(first == other) + + def _check_parts(parts: tuple[Report | Plan, ...]) -> None: """The parts ``document`` merges: results of ``report``/``optimise``, at most one of each, of one setup and of one acquisition (the digest of the tables each was computed on).""" diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index ef8b05b1..82933e44 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -575,6 +575,7 @@ def test_b4_permuted_orders_are_per_group_and_ignore_row_order(): [100.0, -100.0, 100.0, 100.0], [100.0, 0.0, 100.0, 100.0], [100.0, np.inf, 100.0, 100.0], + [1e308] * 4, # each finite, their total overflows (#544) ["100"] * 4, ], ) @@ -815,3 +816,21 @@ def test_the_order_comparison_is_one_table_per_order_kind_and_every_median_in_fu assert "min" in full # the timing was given with pytest.raises(ValueError, match="short"): result.summary(detail="brief") + + +def test_the_flat_rows_keep_each_outcome_metrics_config_id_547(tmp_path): + # Two metrics of different features under one label: after records_to_frame and a CSV, + # only the config id tells what each outcome.readout_error measured. + runs = { + feature: _run(_registry(), metrics=[RelativeMeanError(feature, label="readout_error")]) + for feature in ("feature_a", "feature_b") + } + frames = [] + for feature, records in runs.items(): + path = tmp_path / f"{feature}.csv" + records_to_frame(records).to_csv(path, index=False) + frames.append(pd.read_csv(path)) + ids = [set(frame["outcome_id.readout_error"]) for frame in frames] + expected = [{RelativeMeanError(f, label="readout_error").config_id} for f in runs] + assert ids == expected and ids[0] != ids[1] + assert "outcome.readout_error" in frames[0].columns diff --git a/tests/test_crick_idr.py b/tests/test_crick_idr.py index 03c6480b..ffc6c67a 100644 --- a/tests/test_crick_idr.py +++ b/tests/test_crick_idr.py @@ -339,3 +339,20 @@ def test_the_held_out_tables_carry_their_ceilings_and_denominators(): # stream would have preserved it) or not preserved by the stream at all (F-8). failed = calibration["premature"] + calibration["not_preserved_by_stream"] assert failed.max() == 1.0 and (calibration["premature"] <= failed).all() + + +def test_jcs_iqr_bands_overlap_only_when_they_intersect_either_way_569(): + # Only a.q25 <= b.q75 was tested: a band wholly below the other read as overlapping. + import sys + + sys.path.insert(0, str(DATA)) + from jcs_effect_fovs import bands_overlap + + assert not bands_overlap((-3.0, -2.0), (1.0, 2.0)) # high's band wholly below + assert not bands_overlap((1.0, 2.0), (-3.0, -2.0)) # wholly above + assert bands_overlap((0.0, 2.0), (1.0, 3.0)) and bands_overlap((1.0, 3.0), (0.0, 2.0)) + assert bands_overlap((0.0, 1.0), (1.0, 2.0)) # touching counts as overlapping + assert bands_overlap((1.0, 1.0), (1.0, 1.0)) + for bad in (((2.0, 1.0), (0.0, 3.0)), ((float("nan"), 1.0), (0.0, 3.0))): + with pytest.raises(ValueError, match="band"): + bands_overlap(*bad) diff --git a/tests/test_document.py b/tests/test_document.py index 1a0bfd06..df222950 100644 --- a/tests/test_document.py +++ b/tests/test_document.py @@ -206,3 +206,18 @@ def test_a_text_added_to_a_short_section_goes_before_its_caveats_each_once(): " ⚠️ Second caveat.", " ⚠️ Third caveat.", ] + + +def test_setups_with_contrast_tables_are_compared_by_their_values_551(): + # A DataFrame's == is a DataFrame, whose truth value raised: one Setup was not itself. + from morphocoverage.workflows.retrospective import _same_setup + + declared = {"condition": {"ctrl": ["drug"], "ctrl2": ["drug2"]}} + table = Setup(readout="x", control=declared).contrast_table + setup = Setup(readout="x", contrasts=table) + assert _same_setup(setup, setup) + assert _same_setup(setup, Setup(readout="x", contrasts=table.copy())) + changed = table.copy() + changed.loc[1, "label"] = "drug2 against ctrl2" + assert not _same_setup(setup, Setup(readout="x", contrasts=changed)) + assert not _same_setup(setup, Setup(readout="x", control=declared)) diff --git a/tests/test_feature_tables.py b/tests/test_feature_tables.py index 0aa52d4b..d81e9489 100644 --- a/tests/test_feature_tables.py +++ b/tests/test_feature_tables.py @@ -641,3 +641,27 @@ def test_attach_feature_tables_refusals(): assert str(error.value) == ( "the other feature tables cannot be used: the table 't' must be a pandas DataFrame" ) + + +@pytest.mark.parametrize( + "values", + [ + lambda n: 1 + 1j * np.arange(n), # a varying imaginary part read as constant 1 + lambda n: np.full(n, 2 + 1j * np.inf), # an infinity in the imaginary part unseen + lambda n: np.arange(n) + 0j, # complex, even with no imaginary part + ], + ids=["varying imaginary", "infinite imaginary", "zero imaginary"], +) +def test_a_complex_column_is_refused_before_any_float_cast_485(values): + objects, fovs, embedding = _tables() + with warnings.catch_warnings(): + warnings.simplefilter("error") # no ComplexWarning from a discarded imaginary part + message = _message(objects, fovs, {"DINO": embedding.assign(e1=values(len(embedding)))}) + assert "complex" in message and "e1" in message and "'DINO'" in message + + +def test_nullable_real_columns_are_still_read_485(): + objects, fovs, embedding = _tables() + column = pd.array([1, None] + list(range(len(embedding) - 2)), dtype="Int64") + result = attach_feature_tables(objects, fovs, {"DINO": embedding.assign(e1=column)}) + assert result.missing == {"DINO": 1} diff --git a/tests/test_fixed_area.py b/tests/test_fixed_area.py index d3eb6296..e3418de0 100644 --- a/tests/test_fixed_area.py +++ b/tests/test_fixed_area.py @@ -1,5 +1,7 @@ """Tests for the fixed imaged-area baseline.""" +import warnings + import numpy as np import pandas as pd import pytest @@ -90,3 +92,21 @@ def test_c4_an_infinite_field_area_is_not_summed(): result = _run_one([[1.0], [2.0]], FixedAreaStrategy(10.0, "area_um2"), area_um2=[np.inf, 1.0]) assert result.decision is not Decision.STOP assert result.evidence.quantities["imaged_area"].availability is Availability.NOT_APPLICABLE + + +def test_a_total_area_that_overflows_is_not_applicable_never_a_stop_544(): + # Every area finite and positive, their float64 sum infinite: no measured total, no stop. + built = SCENARIOS["homogeneous"]() + fovs = built.fovs.copy() + fovs["area_um2"] = 1e308 + data = validate_input_tables(built.objects, fovs=fovs, feature_cols=list(FEATURE_COLS)) + estimator = ImagedAreaEstimator("area_um2") + with warnings.catch_warnings(): + warnings.simplefilter("error") # no overflow warning either + quantity = estimator.estimate(data, objective=POPULATION).quantities["imaged_area"] + assert quantity.availability.value == "not_applicable" + assert "overflow" in quantity.reason + fovs["area_um2"] = 1e300 # an ordinary finite total is summed as before + data = validate_input_tables(built.objects, fovs=fovs, feature_cols=list(FEATURE_COLS)) + quantity = estimator.estimate(data, objective=POPULATION).quantities["imaged_area"] + assert quantity.value == pytest.approx(1e300 * len(fovs)) diff --git a/tests/test_frozen.py b/tests/test_frozen.py index effb864e..157f348e 100644 --- a/tests/test_frozen.py +++ b/tests/test_frozen.py @@ -35,3 +35,24 @@ def test_frozen_containers_serialise_pickle_and_copy_like_plain_ones(): plain = thaw(frozen) plain["a"].append(3) # a thawed copy is editable and independent assert frozen["a"] == [1, 2] and type(plain) is dict + + +def test_a_frozen_container_built_directly_freezes_what_it_holds_581(): + # freeze trusts a FrozenDict/FrozenList as already frozen; built by its constructor + # it kept the caller's inner list and dict, which could still change the snapshot. + inner = [1] + snapshot = freeze({"science": FrozenDict({"nested": inner})}) + inner.append(2) + assert snapshot["science"]["nested"] == [1] + with pytest.raises(TypeError): + snapshot["science"]["nested"].append(3) + threshold = {"threshold": 1} + listed = freeze([FrozenList([threshold])]) + threshold["threshold"] = 2 + assert listed[0][0] == {"threshold": 1} + with pytest.raises(TypeError): + listed[0][0]["threshold"] = 3 + keyword = FrozenDict(values=[1, 2]) + assert isinstance(keyword["values"], FrozenList) + restored = pickle.loads(pickle.dumps(FrozenDict({"a": [1, {"b": [2]}]}))) + assert restored == {"a": [1, {"b": [2]}]} and isinstance(restored["a"][1]["b"], FrozenList) diff --git a/tests/test_glossary.py b/tests/test_glossary.py index f08a4f37..bfccb9d2 100644 --- a/tests/test_glossary.py +++ b/tests/test_glossary.py @@ -9,3 +9,12 @@ def test_the_glossary_says_unusual_apart_from_nothing_new_a24(): terms = {term.name: term for term in GLOSSARY} assert "definition of new" not in terms["Unusual cells"].meaning assert "definition of new" in terms["'Nothing new'"].meaning + + +def test_the_sign_flip_entry_says_magnitudes_and_exact_or_monte_carlo_578(): + # The test flips the signs of the per-repeat differences and keeps their magnitudes + # (not a test on the signs alone); it enumerates up to 16 repeats, Monte Carlo beyond. + meaning = {term.name: term for term in GLOSSARY}["Sign-flip test"].meaning + assert "test on the signs" not in meaning + assert "magnitude" in meaning and "mean" in meaning + assert "exact up to 16" in meaning and "Monte Carlo" in meaning diff --git a/tests/test_guided_controls.py b/tests/test_guided_controls.py index 29c4ceca..58f80667 100644 --- a/tests/test_guided_controls.py +++ b/tests/test_guided_controls.py @@ -224,3 +224,31 @@ def test_b3_the_guided_controls_question_has_no_all_default_and_asks_again(): assert NOTHING_UNDER in text assert control == {"condition": {"cA": {"a1": "a1"}, "cB": {"b1": "b1"}}} assert parents is None and master == "cA" + + +def test_treatment_keys_entered_twice_are_asked_again_not_overwritten_448(): + # Two conditions given the key KD made {"KD": "drugB"}: drugA vanished silently. + from morphocoverage.workflows._guided_controls import _keys + + script = Script(["n", "KD", "KD", "KDa", "KDb"]) + keys = _keys(script.ask, script.say, "ctrl", ["drugA", "drugB"]) + assert keys == {"KDa": "drugA", "KDb": "drugB"} + assert "its own treatment key" in script.text + script = Script(["n", "", "KDb"]) # Enter keeps the proposed key + assert _keys(script.ask, script.say, "ctrl", ["drugA", "drugB"]) == { + "drugA": "drugA", + "KDb": "drugB", + } + + +def test_a_taken_key_and_a_taken_condition_name_ask_for_a_key_448(): + # The fallback to the condition's name overwrote the condition already holding it. + from morphocoverage.workflows._guided_controls import _unlinked + + found = {"ctrl": {"drugA": "drugB"}} + script = Script(["ctrl", "drugA2"]) + controls = _unlinked( + script.ask, script.say, ["ctrl", "drugA", "drugB"], [], found, {"ctrl", "drugB"} + ) + assert controls == ["ctrl"] + assert found == {"ctrl": {"drugA": "drugB", "drugA2": "drugA"}} diff --git a/tests/test_jcb_planning.py b/tests/test_jcb_planning.py index 2898036e..32a0fc7f 100644 --- a/tests/test_jcb_planning.py +++ b/tests/test_jcb_planning.py @@ -614,3 +614,22 @@ def test_c2_planning_refuses_a_pilot_of_one_object_per_sample(): sample_cols=("condition", "biological_repeat"), control={"condition": "control"}, ) + + +def test_a_sample_key_holding_control_and_treated_cells_is_refused_430(): + # Keyed by repeat alone, each sample mixed control (10) and treated (20) cells, so the + # treatment shift entered the within-sample SD: a plan of 107 cells instead of 1. + values = {"control": [9.8, 9.9, 10.1, 10.2], "treated": [19.8, 19.9, 20.1, 20.2]} + rows = [ + {"condition": c, "biological_repeat": r, "image_file": f"{c}_{r}.tif", "area": v} + for r in ("r1", "r2") + for c, vs in values.items() + for v in vs + ] + objects = pd.DataFrame(rows) + fovs = objects.drop_duplicates("image_file").drop(columns="area").reset_index(drop=True) + with pytest.raises(ValueError, match="both control and other") as error: + _plan(objects, fovs, target_cv=0.05, sample_cols=("biological_repeat",)) + assert "'r1'" in str(error.value) and "'r2'" in str(error.value) + right = _plan(objects, fovs, target_cv=0.05) # condition and repeat: one kind each + assert right.required_objects == 1 diff --git a/tests/test_lab_datasets.py b/tests/test_lab_datasets.py index eca5703d..40ba6d53 100644 --- a/tests/test_lab_datasets.py +++ b/tests/test_lab_datasets.py @@ -168,3 +168,93 @@ def test_convert_rebuilds_the_stored_tables_from_the_pinned_source(dataset_id): io.StringIO(frame.to_csv(index=False)), dtype=str, keep_default_na=False ) pd.testing.assert_frame_equal(stored, rebuilt) + + +def _served_zip(tmp_path, monkeypatch, member: str, data: bytes) -> tuple[str, str]: + """A zip archive served in place of the download: its URL and md5.""" + import hashlib + import shutil + import urllib.request + import zipfile + + archive = tmp_path / "source.zip" + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr(member, data) + monkeypatch.setattr( + urllib.request, "urlretrieve", lambda url, path: shutil.copyfile(archive, path) + ) + return "https://example.org/source.zip", hashlib.md5(archive.read_bytes()).hexdigest() + + +def test_the_archive_is_hashed_in_chunks_never_read_whole_577(tmp_path, monkeypatch): + # The md5 read the whole archive into memory (381 MB for CCT8 CDM morphology). + import convert_tools + + url, md5 = _served_zip(tmp_path, monkeypatch, "data/table.csv", b"a,b\n1,2\n") + + def whole(self): + raise AssertionError(f"{self} read whole") + + monkeypatch.setattr(Path, "read_bytes", whole) + assert convert_tools.fetch_zip_member(url, md5, "data/table.csv") == b"a,b\n1,2\n" + with pytest.raises(SystemExit, match="expected"): + convert_tools.fetch_zip_member(url, "0" * 32, "data/table.csv") + + +def _filopodia_source(**changed) -> pd.DataFrame: + """A small source of the filopodia screen, as read_source returns it.""" + source = pd.DataFrame( + { + "Condition": ["siCTRL", "siCTRL", "siCCT8#5", "siCCT8#5"], + "Filopodia number": [3.0, 5.0, 1.0, 0.0], + "Repeat": [1.0, 2.0, 1.0, 2.0], + "dataset": "CCT8", + "source_row": range(2, 6), + } + ) + for column, (row, value) in changed.items(): + source.loc[row, column.replace("_", " ")] = value + return source + + +@pytest.mark.parametrize( + ("change", "column"), + [ + ({"Repeat": (1, 1.8)}, "Repeat"), # truncated to repeat 1, merged with it + ({"Repeat": (1, 0.0)}, "Repeat"), + ({"Filopodia_number": (2, 5.9)}, "Filopodia number"), # a count truncated to 5 + ({"Filopodia_number": (2, -1.0)}, "Filopodia number"), + ({"Filopodia_number": (2, np.inf)}, "Filopodia number"), + ], +) +def test_fractional_or_impossible_ids_and_counts_are_refused_not_truncated_576(change, column): + module = _convert_module("cct8_filopodia_screen") + objects, _ = module.build_tables(_filopodia_source()) # whole numbers: converted + assert sorted(objects["Filopodia number"]) == [0, 1, 3, 5] + with pytest.raises(SystemExit, match=f"{column}.*row") as error: + module.build_tables(_filopodia_source(**change)) + assert "whole number" in str(error.value) + + +def test_whole_numbers_name_the_source_rows_576(): + import convert_tools + + source = pd.DataFrame({"TRACK_ID": [0, 10.7, 3], "source_row": [2, 3, 4]}) + with pytest.raises(SystemExit, match="TRACK_ID.*row 3: 10.7"): + convert_tools.whole_numbers(source, "TRACK_ID", minimum=0) + assert convert_tools.whole_numbers(source.drop(1), "TRACK_ID", 0).tolist() == [0, 3] + with pytest.raises(SystemExit, match="not numbers"): + convert_tools.whole_numbers(source.assign(TRACK_ID="1"), "TRACK_ID", 0) + + +def test_the_glioma_card_claims_no_check_convert_does_not_make_574(): + # The card said Unique_ID and File_name were checked by convert.py, which never reads + # them; only experiment_nb is checked (against Repeat). + dropped = catalog.read_card("cct7_cct8_glioma_cdm_tracks")["columns"]["dropped"] + source = (LAB / "cct7_cct8_glioma_cdm_tracks" / "convert.py").read_text() + for column in ("Unique_ID", "File_name"): + entry = next(e for e in dropped if e.startswith(column) or f" {column}" in e) + assert f'source["{column}"]' not in source + assert "not checked" in entry, entry + checked = next(e for e in dropped if "experiment_nb" in e) + assert 'source["experiment_nb"]' in source and "checked by convert.py" in checked diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py index 26acd22b..852251e6 100644 --- a/tests/test_notebooks.py +++ b/tests/test_notebooks.py @@ -74,3 +74,20 @@ def test_notebooks_run_in_both_colab_and_jupyterlab(path): stripped = line.lstrip() if "/content" in line or "from google.colab" in line or stripped.startswith(("!", "%")): assert guarded, line + + +def test_the_workflows_example_pairs_the_positive_control_by_repeat_group_640(): + # The folder label (biological_repeat) is never a pairing (#617): the example taught it. + path = next(p for p in NOTEBOOKS if p.stem == "MorphoCoverage_Workflows_Example") + declaration = next(s for s in _code_cells(path) if "PositiveControl(" in s and "Setup(" in s) + calls = [ + node + for node in ast.walk(ast.parse(_python(declaration))) + if isinstance(node, ast.Call) and getattr(node.func, "id", None) == "PositiveControl" + ] + assert calls + for call in calls: + pair_cols = next(k.value for k in call.keywords if k.arg == "pair_cols") + assert ast.literal_eval(pair_cols) == ("repeat_group",) + # Without the column the declaration stops, never falling back to the folder label. + assert '"repeat_group" not in fovs.columns' in declaration and "raise ValueError" in declaration diff --git a/tests/test_reference.py b/tests/test_reference.py index d9b45407..448baf36 100644 --- a/tests/test_reference.py +++ b/tests/test_reference.py @@ -141,3 +141,40 @@ def test_two_runs_of_the_same_code_give_the_same_files(tmp_path, capsys): def test_the_idr_job_never_writes_into_a_checkout(tmp_path): with pytest.raises(ValueError, match="export only"): reference.run_idr(ROOT, tmp_path / "idr", tmp_path / "idr.log") + + +@pytest.mark.parametrize( + "line", + [ + "../.. victim", + "scenario ../../victim", + "scenario /tmp/victim", + "scenario a/b", + "scenario a\\b", + "scenario ..", + "nosuchkind e01", + "owner ..", + ], +) +def test_a_job_that_could_name_a_folder_outside_the_output_is_refused_583(tmp_path, line): + # read_jobs took any two words and run_job removed OUT/__ first: "../.." + # reached a folder outside OUT. + jobs = tmp_path / "jobs.txt" + jobs.write_text(line + "\n") + with pytest.raises(ValueError, match="kind|name"): + reference.read_jobs(jobs) + + +def test_run_job_never_removes_a_folder_outside_the_output_583(tmp_path): + out, victim = tmp_path / "out", tmp_path / "victim__x" + (victim / "keep").mkdir(parents=True) + with pytest.raises(ValueError, match="outside"): + reference.run_job("../victim x", tmp_path, out, None) # OUT/../victim__x + assert (victim / "keep").is_dir() + + +def test_a_job_listed_twice_is_refused_583(tmp_path): + jobs = tmp_path / "jobs.txt" + jobs.write_text("scenario e01\nscenario e01\n") + with pytest.raises(ValueError, match="twice"): + reference.read_jobs(jobs) diff --git a/tests/test_retrospective_report.py b/tests/test_retrospective_report.py index d38aff78..fa183fe9 100644 --- a/tests/test_retrospective_report.py +++ b/tests/test_retrospective_report.py @@ -828,3 +828,19 @@ def test_the_report_gives_questions_4_5_and_7_short_with_their_markers(): assert section.count("conservative by construction") == 1 assert section.count("the field count is a guide") == 1 assert OK not in report.short["next_time"] and PROBLEM not in report.short["next_time"] + + +def test_detection_adjusted_lines_name_groups_whose_column_is_not_an_identifier_449(): + # itertuples renames "plate id" to _0, so getattr(row, "plate id") raised. + from morphocoverage.retrospective.report_profile import _adjusted_lines + + frame = pd.DataFrame( + { + "plate id": ["A", "B"], + "class": [1, 2], + "unseen_state_max_frequency": [0.2, np.nan], + } + ) + lines = _adjusted_lines(frame, ["plate id", "class"], 0.5) + assert len(lines) == 1 and lines[0].startswith(" plate id=A, class=1: up to 40") + assert _adjusted_lines(frame, [], 0.5)[0].startswith(" all FOVs (pooled): up to 40") diff --git a/tests/test_robust_sd.py b/tests/test_robust_sd.py index 9a276c78..083b739d 100644 --- a/tests/test_robust_sd.py +++ b/tests/test_robust_sd.py @@ -76,3 +76,12 @@ def test_stands_out_falls_back_to_the_sd_where_the_mad_is_zero(): def test_an_unknown_rule_is_refused(): with pytest.raises(ValueError, match="rule must be 'detector' or 'geometry'"): robust_sd(np.ones(3), "floor") + + +def test_one_value_has_no_spread_under_either_rule_418(): + # A 1-D sample of one value: the geometry rule indexed a second axis that is not there. + for rule in ("detector", "geometry"): + assert robust_sd(np.array([3.0]), rule) == 0.0 + assert robust_sd(np.array([[3.0]]), "geometry").tolist() == [0.0] + assert robust_sd(np.array([[3.0, 4.0]]), "geometry").tolist() == [0.0, 0.0] + assert robust_sd(np.array([2.0, 2.0, 2.0]), "geometry") == 0.0 diff --git a/tests/test_stabilization.py b/tests/test_stabilization.py index 62b1fb83..a9c98e13 100644 --- a/tests/test_stabilization.py +++ b/tests/test_stabilization.py @@ -656,3 +656,25 @@ def test_p9_4_object_row_order_within_fields_does_not_change_the_live_stop(): r.result.evidence.quantities for r in again ] assert [r.result.rule_decision for r in base] == [r.result.rule_decision for r in again] + + +def test_the_resample_helpers_refuse_inputs_they_cannot_resample_532(): + # Their callers guard these cases; the helpers now say so themselves instead of a + # ZeroDivisionError, draws over no FOV or an index beyond the FOVs. + rng = np.random.default_rng(0) + values = np.array([1.0, 2.0, 3.0]) + with pytest.raises(ValueError, match="no value"): + _descriptor_resamples._object_resamples(np.array([]), 5, rng, ("mean",)) + with pytest.raises(ValueError, match="n_resamples"): + _descriptor_resamples._object_resamples(values, 0, rng, ("mean",)) + fov = _descriptor_resamples._fov_resamples + for positions, k, n, match in ( + (np.array([0, 0, 1]), 0, 5, "k"), + (np.array([0, 1, 2]), 2, 5, "positions"), + (np.array([0, -1, 1]), 2, 5, "positions"), + (np.array([0, 1]), 2, 5, "positions"), + (np.array([0, 1, 1]), 2, 0, "n_resamples"), + ): + with pytest.raises(ValueError, match=match): + fov(values, positions, k, n, rng, ("mean",)) + assert fov(np.array([]), np.array([], dtype=int), 3, 4, rng, ("mean",))["mean"].shape == (4,) diff --git a/tests/test_stage_coordinates.py b/tests/test_stage_coordinates.py index 6a35a404..d0787be5 100644 --- a/tests/test_stage_coordinates.py +++ b/tests/test_stage_coordinates.py @@ -163,3 +163,27 @@ def test_f10_infinite_stage_coordinates_are_refused(): orders=[AcquisitionOrder.dispersed(0)], stage_cols=("x", "y"), ) + + +@pytest.mark.parametrize("path", ["inspect_fovs", "fov_semivariogram", "spatial_blocks"]) +def test_coordinates_a_float_cannot_hold_are_refused_538(path): + # A Python integer beyond float range overflowed with a bare OverflowError; 2**53 and + # 2**53 + 1 became one float, two positions silently at the same place. + huge = pd.Series([10**400] + list(range(1, 12)), dtype=object) + objects, fovs = _tables(sx=huge) + with pytest.raises(ValueError, match="finite"): + _quiet(lambda: PATHS[path](fovs, objects)) + objects, fovs = _tables(sx=np.arange(12, dtype=np.int64) + 2**53) + with pytest.raises(ValueError, match="exactly"): + _quiet(lambda: PATHS[path](fovs, objects)) + + +def test_check_xy_refuses_integers_a_float_cannot_hold_538(): + for bad in ( + np.array([[2**53, 0], [2**53 + 1, 0]], dtype=np.int64), + np.array([[2**63 + 1, 0]], dtype=np.uint64), + ): + with pytest.raises(ValueError, match="exactly"): + stage_travel(bad) + exact = np.array([[2**53, 0], [-(2**53), 1]], dtype=np.int64) # held exactly: kept + assert stage_travel(exact)[-1] == pytest.approx(np.hypot(2.0**54, 1)) diff --git a/tests/test_statistics.py b/tests/test_statistics.py index e45c4d3c..12b3aba1 100644 --- a/tests/test_statistics.py +++ b/tests/test_statistics.py @@ -509,3 +509,17 @@ def test_benjamini_hochberg_keeps_nan_and_matches_the_definition(): q = benjamini_hochberg(p) assert np.isnan(q[1]) assert np.allclose(q[[0, 2, 3, 4]], [0.04, 0.04 * 4 / 3, 0.04 * 4 / 3, 1.0]) + + +def test_repeat_effect_refuses_a_level_outside_0_1_and_infinite_contrasts_528(): + # level=1 gave an infinite interval and a negative level an invalid quantile; an + # infinite contrast gave NaN bounds after runtime warnings. + contrasts = np.array([0.1, 0.3, 0.2]) + for level in (0, 1, -0.5, 1.5, float("nan"), True, "0.95"): + with pytest.raises(ValueError, match="level"): + repeat_effect("raw", contrasts, level=level) + with pytest.raises(ValueError, match="finite"): + repeat_effect("raw", np.array([0.1, np.inf, 0.2])) + missing = repeat_effect("raw", np.array([0.1, np.nan, 0.2])) # missing: no interval, kept + assert np.isnan(missing["ci_low"]) and np.isnan(missing["ci_high"]) + assert repeat_effect("raw", contrasts, level=0.9)["ci_low"] < 0.2 diff --git a/tests/test_transforms.py b/tests/test_transforms.py index 61cfae62..e070025b 100644 --- a/tests/test_transforms.py +++ b/tests/test_transforms.py @@ -21,7 +21,14 @@ SupportNoveltyEstimator, SupportNoveltyStrategy, ) -from morphocoverage.transforms import PCA, BlockWeights, Chain, RobustStandardize, Standardize +from morphocoverage.transforms import ( + PCA, + BlockWeights, + Chain, + ColumnWeights, + RobustStandardize, + Standardize, +) from morphocoverage.workflows import default_novelty @@ -309,3 +316,18 @@ def test_d2_pca_refuses_components_beyond_the_data_rank(): reason = PCA(2).fit_matrix(np.c_[a, 2 * a, -a], ("x", "y", "z")) assert isinstance(reason, str) and "fewer than 2 dimensions" in reason assert not isinstance(PCA(1).fit_matrix(np.c_[a, 2 * a, -a], ("x", "y", "z")), str) + + +def test_weight_settings_are_refused_not_coerced_495(): + # float(True) is 1.0 and float("2.0") is 2.0; bool("False") is True. + for bad in ((True,), ("2.0",), (np.bool_(True),), (1.0, "1")): + with pytest.raises(ValueError, match="weights"): + ColumnWeights(bad) + assert ColumnWeights((1, np.float32(0.5), np.int64(2))).weights == (1.0, 0.5, 2.0) + for flag in ("False", 1, None): + with pytest.raises(TypeError, match="inertia_radius"): + BlockWeights((("a", "b"),), inertia_radius=flag) + assert BlockWeights((("a",),), inertia_radius=np.bool_(True)).inertia_radius is True + for blocks in (((1, "b"),), (("",),), ((" ",),)): + with pytest.raises(TypeError, match="feature names"): + BlockWeights(blocks) diff --git a/tests/test_validation_p0.py b/tests/test_validation_p0.py index f6ca77b3..f8e57913 100644 --- a/tests/test_validation_p0.py +++ b/tests/test_validation_p0.py @@ -344,3 +344,38 @@ def test_the_package_never_imports_the_validation_extra(): if n.split(".")[0] in {"statsmodels", "harmonypy"} ] assert not found + + +@pytest.mark.parametrize( + "weights", + [ + {"A": 1.0}, # A against nothing: direct tested A's mean, the model A minus baseline + {"A": 1.0, "control": -0.5}, + {"A": 0.0, "control": 0.0}, + {}, + {"A": np.nan, "control": -1.0}, + {"A": np.inf, "control": -np.inf}, + {"A": True, "control": -1.0}, + ], +) +def test_a_contrast_whose_weights_do_not_sum_to_zero_is_refused_514(weights): + presence = {f"R{r}": ("control", "A", "B") for r in range(4)} + values = pd.DataFrame( + [ + {"repeat": r, "condition": c, "value": float(i + j)} + for i, r in enumerate(presence) + for j, c in enumerate(presence[r]) + ] + ) + layout = fixed_block.Layout.from_presence(presence) + for call in ( + lambda: fixed_block.regime(presence, weights), + lambda: fixed_block.graph_estimable(presence, weights), + lambda: layout.contrast(weights), + lambda: fixed_block.fit_model(values, weights), + lambda: fixed_block.contrast(values, weights), + ): + with pytest.raises(ValueError, match="weights"): + call() + # A zero-sum contrast, rescaled, is the same question in every regime. + assert fixed_block.regime(presence, {"A": 2.0, "control": -2.0}) == "direct" diff --git a/tests/test_validation_smoke.py b/tests/test_validation_smoke.py index 7f560b5c..a45ebb46 100644 --- a/tests/test_validation_smoke.py +++ b/tests/test_validation_smoke.py @@ -261,3 +261,119 @@ def test_the_notebook_is_thin_guards_colab_and_runs_locally_at_smoke_size(tmp_pa exec(source, namespace) # noqa: S102 assert (tmp_path / "decisions_results" / "p5" / "summary.md").exists() assert (tmp_path / "decisions_results.zip").exists() + + +def _colab_clone(monkeypatch, tmp_path, clone_code: int) -> tuple[list, list, RuntimeError | None]: + """Run the notebook's first cell as on Colab with a fake token, ``subprocess.run`` only + recorded (the clone answering ``clone_code``); the commands, their environments and the + error raised, if any.""" + import subprocess + import types + + token = "ghp_FAKE0123456789" + userdata = types.SimpleNamespace(get=lambda name: token) + colab_module = types.ModuleType("google.colab") + colab_module.userdata = userdata + monkeypatch.setitem(sys.modules, "google", types.ModuleType("google")) + monkeypatch.setitem(sys.modules, "google.colab", colab_module) + monkeypatch.setattr(sys, "path", list(sys.path)) + commands, environments = [], [] + + def run(command, **kwargs): + commands.append(list(map(str, command))) + environments.append(kwargs.get("env") or {}) + if "clone" in command: + return subprocess.CompletedProcess(command, clone_code, "", "fatal: no access\n") + url = "https://github.com/CellMigrationLab/MorphoCoverage.git\n" + return subprocess.CompletedProcess(command, 0, url, "") + + monkeypatch.setattr(subprocess, "run", run) + error = None + try: + exec(_cells()[0], {}) # noqa: S102 - the notebook's own code, its commands recorded + except RuntimeError as raised: # fallback: the test inspects the error itself + error = raised + for text in [*map(" ".join, commands), str(error or "")]: + assert token not in text, text + return commands, environments, error + + +def test_the_colab_clone_keeps_the_token_out_of_urls_commands_and_errors_591(monkeypatch, tmp_path): + # The token was in the clone URL: in the command, the clone's .git/config and the + # CalledProcessError of a failed clone. + commands, environments, error = _colab_clone(monkeypatch, tmp_path, 0) + assert error is None + clone = next(c for c in commands if "clone" in c) + assert "https://github.com/CellMigrationLab/MorphoCoverage.git" in clone + assert environments[commands.index(clone)]["GIT_ASKPASS"] + assert any("remote.origin.url" in c for c in commands) # the clone's remote is checked + commands, _, error = _colab_clone(monkeypatch, tmp_path, 128) + assert isinstance(error, RuntimeError) and "git clone failed" in str(error) + assert not any("pip" in c for c in commands) + + +def test_a_failed_p0_stops_the_run_before_any_other_module_520(tmp_path, monkeypatch): + # run discarded P0's exit code and went on to P1-P5 as if the gate had passed. + calls = [] + monkeypatch.setattr(colab, "run_p0", lambda out: 1) + monkeypatch.setattr(runner, "run", lambda *args: calls.append(args)) + with pytest.raises(RuntimeError, match="P0"): + colab.run(["P0", "P5"], "smoke", tmp_path) + assert calls == [] + monkeypatch.setattr(colab, "run_p0", lambda out: 0) + colab.run(["P0", "P5"], "smoke", tmp_path) + assert len(calls) == 1 + + +def _semi_inputs(fields_per_repeat: int = 4, values: np.ndarray | None = None): + meta = pd.DataFrame( + { + "biological_repeat": np.repeat(["R1", "R2"], fields_per_repeat * 3), + "position_id": np.repeat(np.arange(2 * fields_per_repeat), 3).astype(str), + } + ) + if values is None: + values = np.random.default_rng(0).normal(size=(len(meta), 3)) + return values, meta + + +def test_semi_synthetic_splits_every_repeat_and_shifts_by_the_requested_amount_524(): + from decisions.embedding import semi_synthetic + + values, meta = _semi_inputs() + _, labelled, vector = semi_synthetic(values, meta, 0.5, np.random.default_rng(1)) + centred = values - values.mean(axis=0) + within = np.sqrt(np.square(centred).sum(axis=1).mean()) + assert np.linalg.norm(vector) == pytest.approx(0.5 * within) + assert (labelled.groupby("biological_repeat")["condition"].nunique() == 2).all() + # Two exactly opposite rows: every draw of two different rows cancels, never a zero shift. + opposite = np.tile([[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0]], (12, 1)) + _, _, vector = semi_synthetic(opposite, meta, 0.5, np.random.default_rng(1)) + assert np.linalg.norm(vector) == pytest.approx(0.5) + + +@pytest.mark.parametrize( + ("inputs", "shift", "match"), + [ + (_semi_inputs(fields_per_repeat=1), 0.5, "2 fields"), # no treated field at all + (_semi_inputs(values=np.ones((24, 3))), 0.5, "vary"), # a zero shift asked as 0.5 + ((np.ones((5, 3)), _semi_inputs()[1]), 0.5, "rows"), + ((np.full((24, 3), np.nan), _semi_inputs()[1]), 0.5, "finite"), + ], +) +def test_semi_synthetic_refuses_what_it_cannot_split_or_shift_524(inputs, shift, match): + # One field per repeat gave no treated field; constant values a zero shift for 0.5. + from decisions.embedding import semi_synthetic + + with pytest.raises(ValueError, match=match): + semi_synthetic(*inputs, shift, np.random.default_rng(1)) + + +def test_the_exact_sign_flip_tests_refuse_more_repeats_than_they_can_enumerate_519(): + # 2**n assignments as one dense array: n=25 needed >800 MB for the signs alone. + deltas = np.random.default_rng(0).normal(size=(17, 3)) + with pytest.raises(ValueError, match="16"): + hd_tests.sign_flip_u(deltas) + with pytest.raises(ValueError, match="16"): + hd_tests.shrinkage_hotelling(deltas, deltas) + assert 0 < hd_tests.sign_flip_u(deltas[:16]) <= 1 # up to 16, enumerated as before diff --git a/tests/test_whole_table.py b/tests/test_whole_table.py index 79ab83e0..1c001161 100644 --- a/tests/test_whole_table.py +++ b/tests/test_whole_table.py @@ -339,3 +339,17 @@ def _whole_table_edges(): def test_whole_table_edges(): assert _whole_table_edges() == EXPECTED_WHOLE_TABLE_EDGES + + +@pytest.mark.parametrize("permutations", [0, -1, 2.5, True, "999"]) +def test_the_permutations_are_a_positive_count_never_a_p_of_no_draws_491(permutations): + # permutations=0 drew no null labelling and still printed p_shuffle = 1.0. + objects, fovs, names = _images() + with pytest.raises(ValueError, match="permutations"): + _tests(objects, fovs, names, permutations=permutations) + + +def test_the_seed_is_a_non_negative_integer_491(): + objects, fovs, names = _images() + with pytest.raises(ValueError, match="random_state"): + _tests(objects, fovs, names, random_state=-1)