Download code/population/_transform.py from chiron-group/chiron-data: direct link, hf CLI and curl.
- Browser
- Download file 6.6 kB
-
https://huggingface.co/datasets/chiron-group/chiron-data/resolve/main/code/population/_transform.py
- Command line
-
hf download hf://datasets/chiron-group/chiron-data/code/population/_transform.py
-
curl -L -o _transform.py https://huggingface.co/datasets/chiron-group/chiron-data/resolve/main/code/population/_transform.py
6.6 kB
| """Replay fitted population transforms from source answers and saved parameters. | |
| This module performs no file access. Condition order, block order, source row | |
| order, and the saved seed determine the shared noise and rounding priorities. | |
| """ | |
| from __future__ import annotations | |
| from typing import Any | |
| import numpy as np | |
| def physical(prompts: list[dict[str, Any]], ids: dict[str, np.ndarray]) -> dict[str, np.ndarray]: | |
| """Map integer option IDs to each question's numeric analysis values.""" | |
| return { | |
| prompt["condition_key"]: np.column_stack([ | |
| np.array([float(option["analysis_value"]) for option in question["options"]])[ | |
| ids[prompt["condition_key"]][:, j].astype(int) - 1 | |
| ] | |
| for j, question in enumerate(prompt["questions"]) | |
| ]) | |
| for prompt in prompts | |
| } | |
| class Transform: | |
| """Shared location, scale, and noise transforms with balanced rounding.""" | |
| def __init__(self, inp: dict[str, Any], model: str, seed: int): | |
| self.pp = inp["prompts"] | |
| self.ids = {key: np.array(value, int) for key, value in inp["sources"][model].items()} | |
| self.bb: list[dict[str, Any]] = [] | |
| self.cats: list[dict[str, Any]] = [] | |
| rng = np.random.default_rng(seed) | |
| for prompt in self.pp: | |
| key = prompt["condition_key"] | |
| answers = self.ids[key] | |
| for pattern in inp["blocks"]: | |
| columns = np.array([j for j, _ in pattern]) | |
| signs = np.array([sign for _, sign in pattern]) | |
| levels = len(prompt["questions"][int(columns[0])]["options"]) | |
| if not all(len(prompt["questions"][int(j)]["options"]) == levels for j in columns): | |
| raise ValueError("Transform block contains incompatible response grids") | |
| old = np.where(signs > 0, answers[:, columns], levels + 1 - answers[:, columns]) | |
| z = (old.mean(1) - 1) / (levels - 1) | |
| noise = rng.normal(size=len(answers)) | |
| noise = (noise - noise.mean()) / max(noise.std(), 1e-8) | |
| self.bb.append({ | |
| "key": key, "jj": columns, "sgn": signs, "K": levels, | |
| "old": old, "z": z, "center": z.mean(), "noise": noise, | |
| "u": (rng.permutation(len(answers)) + .5) / len(answers), | |
| }) | |
| for j in inp["categorical"]: | |
| levels = len(prompt["questions"][j]["options"]) | |
| counts = np.bincount(answers[:, j] - 1, minlength=levels) | |
| self.cats.append({ | |
| "key": key, "j": j, "K": levels, "base": counts, | |
| "order": rng.permutation(len(answers)), | |
| }) | |
| def initial(self) -> np.ndarray: | |
| return np.tile([0., 1., 0.], (len(self.bb), 1)) | |
| def values(self, theta: np.ndarray, continuous: bool = False) -> tuple[dict[str, np.ndarray], dict[str, np.ndarray]]: | |
| ids = {key: value.astype(float) for key, value in self.ids.items()} | |
| for block, parameters in zip(self.bb, theta): | |
| delta = ( | |
| parameters[0] | |
| + (parameters[1] - 1) * (block["z"] - block["center"]) | |
| + parameters[2] * block["noise"] | |
| ) * (block["K"] - 1) | |
| if continuous: | |
| values = np.clip(block["old"] + delta[:, None], 1, block["K"]) | |
| else: | |
| low = np.floor(delta) | |
| lower = np.clip(block["old"] + low[:, None], 1, block["K"]) | |
| upper = np.clip(block["old"] + low[:, None] + 1, 1, block["K"]) | |
| increments = (upper - lower).mean(1) | |
| desired = np.sum( | |
| np.clip(block["old"] + delta[:, None], 1, block["K"]).mean(1) | |
| - lower.mean(1) | |
| ) | |
| order = np.argsort(-(delta - low - block["u"]), kind="stable") | |
| totals = np.r_[0, np.cumsum(increments[order])] | |
| count = int(np.argmin(abs(totals - desired))) | |
| round_up = np.zeros(len(low), bool) | |
| round_up[order[:count]] = True | |
| values = np.where(round_up[:, None], upper, lower) | |
| ids[block["key"]][:, block["jj"]] = np.where( | |
| block["sgn"] > 0, values, block["K"] + 1 - values | |
| ) | |
| matrices = { | |
| prompt["condition_key"]: np.column_stack([ | |
| np.interp( | |
| ids[prompt["condition_key"]][:, j], | |
| np.arange(1, len(question["options"]) + 1), | |
| [float(option["analysis_value"]) for option in question["options"]], | |
| ) | |
| for j, question in enumerate(prompt["questions"]) | |
| ]) | |
| for prompt in self.pp | |
| } | |
| return matrices, {key: value.astype(int) for key, value in ids.items()} | |
| def replay_fit(inp: dict[str, Any], parameters: dict[str, Any]) -> dict[str, np.ndarray]: | |
| """Replay saved model, seed, theta, and optional category odds into IDs.""" | |
| transform = Transform(inp, parameters["model"], parameters["seed"]) | |
| theta = np.asarray(parameters["theta"], dtype=float).reshape(-1, 3) | |
| if len(theta) != len(transform.bb): | |
| raise ValueError("Saved theta does not match the ordered transform blocks") | |
| _, ids = transform.values(theta) | |
| category_parameters = parameters.get("categorical_parameters") | |
| if category_parameters is None: | |
| return ids | |
| odds = np.asarray(category_parameters, dtype=float) | |
| expected_size = sum(block["K"] - 1 for block in transform.cats) | |
| if odds.ndim != 1 or len(odds) != expected_size: | |
| raise ValueError("Saved category odds do not match the ordered categorical questions") | |
| position = 0 | |
| for block in transform.cats: | |
| values = np.r_[odds[position:position + block["K"] - 1], 1.] | |
| position += block["K"] - 1 | |
| probabilities = values / values.sum() | |
| expected = probabilities * len(block["order"]) | |
| counts = np.floor(expected).astype(int) | |
| counts[np.argsort(-(expected - counts))[:len(block["order"]) - counts.sum()]] += 1 | |
| remaining = counts.copy() | |
| unassigned = [] | |
| for i in block["order"]: | |
| old = int(ids[block["key"]][i, block["j"]]) - 1 | |
| if remaining[old] > 0: | |
| remaining[old] -= 1 | |
| else: | |
| unassigned.append(i) | |
| labels = np.repeat(np.arange(1, block["K"] + 1), remaining) | |
| for i, label in zip(unassigned, labels): | |
| ids[block["key"]][i, block["j"]] = label | |
| return ids | |