File size: 11,620 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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""Pure joint-response coupling and recorded semantic corrections.

Shared empirical ranks are a model prior, not recovered human correlations.
All indices are zero based; answer option IDs are one based. Inputs are never
modified, and this module performs no file or network access.
"""
from __future__ import annotations

import copy
import json
import re

import numpy as np
from scipy.optimize import linear_sum_assignment
from scipy.spatial.distance import cdist
from scipy.stats import rankdata


def components(inp):
    """Keep items used by one canonical statistic in an indivisible group."""
    n = len(inp["prompts"][0]["questions"])
    parent = list(range(n))
    used = set()

    def root(i):
        while parent[i] != i:
            parent[i] = parent[parent[i]]
            i = parent[i]
        return i

    def join(items):
        items = sorted(set(items))
        assert all(0 <= j < n for j in items)
        used.update(items)
        for j in items[1:]:
            parent[root(j)] = root(items[0])

    for effect in inp["effects"]:
        metadata = {"identifiability": effect["identifiability"],
                    "statistic_spec": effect["statistic_spec"]}
        join([int(s) - 1 for s in re.findall(r"item_(\d+)", json.dumps(metadata))])
    for block in inp["blocks"]:
        join([j for j, _ in block])
    join(inp["categorical"])
    groups = {}
    for j in sorted(used):
        groups.setdefault(root(j), []).append(j)
    free = sorted(set(range(n)) - used)
    return sorted(groups.values(), key=lambda x: x[0]), free


def rank_matrix(a):
    return rankdata(a, axis=0, method="average") / (len(a) + 1.)


def joint_diagnostic(a, reference, groups, free):
    blocks = groups + ([free] if free else [])
    owner = {j: k for k, block in enumerate(blocks) for j in block}
    with np.errstate(divide="ignore", invalid="ignore"):
        ca = np.atleast_2d(np.corrcoef(rank_matrix(a), rowvar=False))
        cr = np.atleast_2d(np.corrcoef(rank_matrix(reference), rowvar=False))
    diffs = []
    inversions = 0
    for i in range(a.shape[1]):
        for j in range(i):
            if owner[i] == owner[j]:
                continue
            if np.isfinite(ca[i, j]) and np.isfinite(cr[i, j]):
                diffs.append(abs(float(ca[i, j] - cr[i, j])))
                inversions += ca[i, j] * cr[i, j] < 0 and min(abs(ca[i, j]), abs(cr[i, j])) > .1
    return {"between_component_rank_correlation_MAE": float(np.mean(diffs)) if diffs else None,
            "correlation_pairs": len(diffs),
            "opposite_sign_pairs_above_0_1": int(inversions),
            "unique_joint_vectors": len(np.unique(a, axis=0)),
            "constant_items": int((np.std(a, axis=0) == 0).sum())}


def couple(prompt, a, initial, groups, free, rng):
    """Transport whole fitted components to a shared initial-model rank prior."""
    n, _ = a.shape
    assert initial.shape == a.shape
    proposals = []
    for _ in range(4):
        out = initial.copy()
        permutations = []
        cost = 0.
        for block in groups:
            if len(groups) == 1 and not free:
                ix = np.arange(n)
            else:
                target = rank_matrix(initial[:, block])
                donors = rank_matrix(a[:, block])
                distances = cdist(target, donors, "sqeuclidean") / len(block)
                _, ix = linear_sum_assignment(distances + rng.uniform(0, 1e-10, distances.shape))
                cost += float(distances[np.arange(n), ix].mean())
            out[:, block] = a[ix][:, block]
            permutations.append(ix)
            assert sorted(map(tuple, out[:, block])) == sorted(map(tuple, a[:, block]))
        assert not free or np.array_equal(out[:, free], initial[:, free])
        diag = joint_diagnostic(out, initial, groups, free)
        score = diag["between_component_rank_correlation_MAE"]
        proposals.append((float(score) if score is not None else 0., cost, out, permutations, diag))
    _, _, out, permutations, after = min(proposals, key=lambda x: x[:2])
    before = joint_diagnostic(a, initial, groups, free)
    retained = False
    if (not free and before["between_component_rank_correlation_MAE"] is not None
            and after["between_component_rank_correlation_MAE"]
            > before["between_component_rank_correlation_MAE"] + 1e-10):
        out = a.copy()
        permutations = [np.arange(n) for _ in groups]
        retained = True
    result = {key: copy.deepcopy(prompt[key]) for key in
              ("study_id", "condition_key", "condition_id", "original_n", "questions", "messages")}
    result["respondents"] = out.tolist()
    result["protected_components"] = copy.deepcopy(groups)
    result["free_items"] = list(free)
    result["retained_coupling"] = retained
    result["respondent_provenance"] = []
    for i in range(n):
        parts = [{"items": list(block), "source": "fitted",
                  "condition_key": prompt["condition_key"], "respondent_index": int(ix[i])}
                 for block, ix in zip(groups, permutations)]
        if free:
            parts.append({"items": list(free), "source": "initial",
                          "condition_key": prompt["condition_key"], "respondent_index": i})
        result["respondent_provenance"].append({"components": parts})
    return result


def balance_audience(populations):
    """Preserve pooled response vectors and n; audience balance is a prior."""
    by = {q["condition_id"]: q for q in populations}
    rng = np.random.default_rng(20260908)
    for left, right in [("A", "B"), ("C", "D"), ("E", "F")]:
        p, q = by[left], by[right]
        n1, n2 = p["original_n"], q["original_n"]
        x, y = np.array(p["respondents"]), np.array(q["respondents"])
        x[:, 0] = 4 - x[:, 0]
        y[:, 0] = y[:, 0] - 4
        pool = np.concatenate([x, y])
        provenance = p["respondent_provenance"] + q["respondent_provenance"]
        features = np.column_stack([pool, pool ** 2]).astype(float)
        features /= np.maximum(features.std(0), 1.)
        target = features.sum(0) * n1 / (n1 + n2)
        best = np.arange(n1 + n2)
        best_cost = float("inf")
        for _ in range(1000):
            ix = rng.permutation(n1 + n2)
            err = features[ix[:n1]].sum(0) - target
            cost = float(err @ err)
            if cost < best_cost:
                best, best_cost = ix, cost
        err = features[best[:n1]].sum(0) - target
        for _ in range(20000):
            i = int(rng.integers(n1))
            j = int(rng.integers(n1, n1 + n2))
            trial = err - features[best[i]] + features[best[j]]
            cost = float(trial @ trial)
            if cost < best_cost - 1e-12:
                best[i], best[j] = best[j], best[i]
                err = trial
                best_cost = cost
        a = pool[best[:n1]].copy()
        b = pool[best[n1:]].copy()
        assert sorted(map(tuple, pool)) == sorted(map(tuple, np.concatenate([a, b])))
        a[:, 0] = 4 - a[:, 0]
        b[:, 0] = b[:, 0] + 4
        for dest, values, indices in [(p, a, best[:n1]), (q, b, best[n1:])]:
            dest["respondents"] = values.tolist()
            new_provenance = []
            for ix in indices:
                pr = copy.deepcopy(provenance[int(ix)])
                source_condition = left if ix < n1 else right
                pr["audience_reassignment"] = {
                    "from_condition": source_condition, "to_condition": dest["condition_id"],
                    "recoded_item": 0,
                    "option_mapping": "8-option_id" if source_condition != dest["condition_id"] else "identity"}
                new_provenance.append(pr)
            dest["respondent_provenance"] = new_provenance


def repair_prompts(populations, policy):
    """Apply recorded wording corrections supplied with the study inputs."""
    for row in populations:
        for edit in policy["wording_corrections"]:
            selectors = {key: edit[key] for key in ("condition_key", "study_id") if key in edit}
            if not selectors:
                raise ValueError("A wording correction must identify its study or condition")
            if any(row[key] != value for key, value in selectors.items()):
                continue
            text = row["messages"][1]["content"]
            if edit["only_if_present"] and edit["match"] not in text:
                continue
            assert text.count(edit["match"]) == 1
            assert all(fragment in text for fragment in edit["required"])
            row["messages"][1]["content"] = text.replace(edit["before"], edit["after"])


def semantic_rules(populations, free_items, policy):
    """Correct only explicitly specified free-item facts, not human frequencies."""
    for q in populations:
        key = q["condition_key"]
        for edit in policy["prompt_edits"]:
            if edit["condition_key"] != key:
                continue
            text = q["messages"][1]["content"]
            assert text.count(edit["before"]) == 1, (key, "stimulus source changed")
            q["messages"][1]["content"] = text.replace(edit["before"], edit["after"])
        for rule in policy["facts"]:
            if rule["condition_key"] != key:
                continue
            j, value = rule["item_index"], rule["expected_option_id"]
            assert j in free_items, (key, j, "cannot alter canonical dependency")
            assert rule["question"] in q["messages"][1]["content"]
            assert q["questions"][j]["options"][value - 1]["text"] == rule["expected_option_text"]
            for answer, lineage in zip(q["respondents"], q["respondent_provenance"]):
                if answer[j] == value:
                    continue
                lineage.setdefault("semantic_overrides", []).append({
                    "rule_id": rule["rule_id"], "item_index": j,
                    "before_option_id": answer[j], "after_option_id": value})
                answer[j] = value
        q["semantic_rules"] = [r["rule_id"] for r in policy["facts"] if r["condition_key"] == key]


def finalize_study(inp, respondents, recipe, policy):
    """Finalize fitted responses without reading saved final populations.

    Preserve prompt order and the shared per-study RNG stream. The caller
    supplies integer option matrices after construct/moment transformations.
    """
    groups, free = components(inp)
    rng = np.random.default_rng(int(recipe["transport_seed"]))
    expected_keys = {q["condition_key"] for q in inp["prompts"]}
    assert len(expected_keys) == len(inp["prompts"])
    assert set(respondents) == expected_keys
    populations = []
    for prompt in inp["prompts"]:
        assert prompt["study_id"] == inp["study"]
        key = prompt["condition_key"]
        a = np.array(respondents[key], dtype=int)
        assert np.array_equal(a, np.asarray(respondents[key]))
        assert a.shape == (prompt["original_n"], len(prompt["questions"]))
        initial = np.array(inp["sources"]["Chiron"][key], dtype=int)
        populations.append(couple(prompt, a, initial, groups, free, rng))
    if inp["study"] == "JEP_1_6b":
        balance_audience(populations)
    repair_prompts(populations, policy)
    semantic_rules(populations, free, policy)
    for q in populations:
        a = np.array(q["respondents"])
        assert a.shape == (q["original_n"], len(q["questions"]))
        assert all(1 <= int(value) <= len(q["questions"][j]["options"])
                   for row in a for j, value in enumerate(row))
        assert len(q["respondent_provenance"]) == q["original_n"]
    return populations