File size: 6,596 Bytes
1b86964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""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