flexpyirt 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- flexpyirt/__init__.py +48 -0
- flexpyirt/_compile.py +1594 -0
- flexpyirt/_core.py +1387 -0
- flexpyirt/_dif.py +198 -0
- flexpyirt/_itemfit.py +244 -0
- flexpyirt/_json.py +1539 -0
- flexpyirt/_linking.py +535 -0
- flexpyirt/_m2.py +367 -0
- flexpyirt/_newton.py +96 -0
- flexpyirt/_precision.py +44 -0
- flexpyirt/_scoring.py +789 -0
- flexpyirt/errors.py +57 -0
- flexpyirt/fit.py +389 -0
- flexpyirt/items.py +910 -0
- flexpyirt/latent.py +963 -0
- flexpyirt/linking.py +815 -0
- flexpyirt/method.py +47 -0
- flexpyirt/model.py +621 -0
- flexpyirt/priors.py +275 -0
- flexpyirt/py.typed +0 -0
- flexpyirt/quadrature.py +135 -0
- flexpyirt/result.py +1230 -0
- flexpyirt-0.0.1.dist-info/METADATA +204 -0
- flexpyirt-0.0.1.dist-info/RECORD +26 -0
- flexpyirt-0.0.1.dist-info/WHEEL +4 -0
- flexpyirt-0.0.1.dist-info/licenses/LICENSE +21 -0
flexpyirt/_compile.py
ADDED
|
@@ -0,0 +1,1594 @@
|
|
|
1
|
+
"""Compile layer: Spec + data -> ParameterTable -> CompiledProblem (DESIGN.md §2 ②, §5, §14).
|
|
2
|
+
|
|
3
|
+
All validation happens here, before anything is jit-compiled, with messages naming the offending
|
|
4
|
+
group / item / parameter.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import warnings
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
from typing import TYPE_CHECKING, Any
|
|
14
|
+
|
|
15
|
+
import jax.numpy as jnp
|
|
16
|
+
import numpy as np
|
|
17
|
+
import pandas as pd
|
|
18
|
+
|
|
19
|
+
from flexpyirt._core import (
|
|
20
|
+
CompiledProblem,
|
|
21
|
+
CoupledBlock,
|
|
22
|
+
CoupledMember,
|
|
23
|
+
FamilyBlock,
|
|
24
|
+
LatentBlock,
|
|
25
|
+
PriorBlock,
|
|
26
|
+
)
|
|
27
|
+
from flexpyirt.errors import FlexpyirtWarning, IdentificationError, SpecificationError
|
|
28
|
+
from flexpyirt.items import (
|
|
29
|
+
GPCM,
|
|
30
|
+
GRM,
|
|
31
|
+
PCM,
|
|
32
|
+
FourPL,
|
|
33
|
+
FourPLKernel,
|
|
34
|
+
GradedKernel,
|
|
35
|
+
ItemKernel,
|
|
36
|
+
ItemModel,
|
|
37
|
+
Nominal,
|
|
38
|
+
Rasch,
|
|
39
|
+
ThreePL,
|
|
40
|
+
_asymptote_starts,
|
|
41
|
+
_gpcm_intercept_starts,
|
|
42
|
+
_intercept_start,
|
|
43
|
+
_slope_start,
|
|
44
|
+
)
|
|
45
|
+
from flexpyirt.latent import (
|
|
46
|
+
DavidianCurve,
|
|
47
|
+
EmpiricalHistogram,
|
|
48
|
+
Normal,
|
|
49
|
+
NormalMixture,
|
|
50
|
+
correlation_matrix_is_positive_definite,
|
|
51
|
+
davidian_param_names,
|
|
52
|
+
eh_project_floor,
|
|
53
|
+
latent_param_names,
|
|
54
|
+
mixture_param_names,
|
|
55
|
+
)
|
|
56
|
+
from flexpyirt.model import LATENT_ITEM
|
|
57
|
+
from flexpyirt.priors import (
|
|
58
|
+
PRIOR_TYPES,
|
|
59
|
+
BetaPrior,
|
|
60
|
+
LogNormalPrior,
|
|
61
|
+
NormalPrior,
|
|
62
|
+
Prior,
|
|
63
|
+
encode_prior,
|
|
64
|
+
)
|
|
65
|
+
from flexpyirt.quadrature import Quadrature
|
|
66
|
+
|
|
67
|
+
if TYPE_CHECKING:
|
|
68
|
+
from flexpyirt.model import Model
|
|
69
|
+
|
|
70
|
+
__all__ = [
|
|
71
|
+
"LATENT_ITEM",
|
|
72
|
+
"TABLE_COLUMNS",
|
|
73
|
+
"Compiled",
|
|
74
|
+
"Prepared",
|
|
75
|
+
"build_table",
|
|
76
|
+
"coerce_groups",
|
|
77
|
+
"coerce_responses",
|
|
78
|
+
"compile_problem",
|
|
79
|
+
"eh_param_count",
|
|
80
|
+
"eh_standardization_flags",
|
|
81
|
+
"model_parameter_schema",
|
|
82
|
+
"prepare",
|
|
83
|
+
"validate_table",
|
|
84
|
+
"validate_table_constraints",
|
|
85
|
+
]
|
|
86
|
+
|
|
87
|
+
TABLE_COLUMNS = (
|
|
88
|
+
"group",
|
|
89
|
+
"item",
|
|
90
|
+
"model",
|
|
91
|
+
"param",
|
|
92
|
+
"value",
|
|
93
|
+
"free",
|
|
94
|
+
"lower",
|
|
95
|
+
"upper",
|
|
96
|
+
"prior",
|
|
97
|
+
"free_id",
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
# --------------------------------------------------------------------------------------------
|
|
102
|
+
# Data
|
|
103
|
+
# --------------------------------------------------------------------------------------------
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def coerce_responses(
|
|
107
|
+
data: Any,
|
|
108
|
+
model: Model,
|
|
109
|
+
*,
|
|
110
|
+
item_names: Sequence[str] | None = None,
|
|
111
|
+
) -> np.ndarray:
|
|
112
|
+
"""Return an ``(N, J)`` int array ordered like the model's items, missing coded ``-1``.
|
|
113
|
+
|
|
114
|
+
Accepts a pandas DataFrame, a polars DataFrame (via ``to_pandas``), or a 2-D array-like with
|
|
115
|
+
``item_names``. Responses are integers ``0..K-1`` (``K = n_categories``); NaN is missing (MAR,
|
|
116
|
+
DESIGN.md §14.8).
|
|
117
|
+
|
|
118
|
+
Raises
|
|
119
|
+
------
|
|
120
|
+
SpecificationError
|
|
121
|
+
Missing or extra item columns, or out-of-range / non-integer values.
|
|
122
|
+
"""
|
|
123
|
+
items = model.item_names
|
|
124
|
+
if hasattr(data, "to_pandas") and not isinstance(data, pd.DataFrame):
|
|
125
|
+
data = data.to_pandas()
|
|
126
|
+
if isinstance(data, pd.DataFrame):
|
|
127
|
+
columns = [str(c) for c in data.columns]
|
|
128
|
+
frame = data
|
|
129
|
+
else:
|
|
130
|
+
arr = np.asarray(data, dtype=float)
|
|
131
|
+
if arr.ndim != 2:
|
|
132
|
+
raise SpecificationError(f"Response data must be 2-D, got shape {arr.shape}.")
|
|
133
|
+
if item_names is None:
|
|
134
|
+
if arr.shape[1] != len(items):
|
|
135
|
+
raise SpecificationError(
|
|
136
|
+
f"Response array has {arr.shape[1]} columns but the model has {len(items)} "
|
|
137
|
+
"items; pass item_names= to map columns to items."
|
|
138
|
+
)
|
|
139
|
+
item_names = list(items)
|
|
140
|
+
if len(item_names) != arr.shape[1]:
|
|
141
|
+
raise SpecificationError(
|
|
142
|
+
f"item_names has {len(item_names)} entries but the data has {arr.shape[1]} columns."
|
|
143
|
+
)
|
|
144
|
+
columns = [str(c) for c in item_names]
|
|
145
|
+
frame = pd.DataFrame(arr, columns=columns)
|
|
146
|
+
|
|
147
|
+
if len(set(columns)) != len(columns):
|
|
148
|
+
raise SpecificationError("Response data has duplicated column names.")
|
|
149
|
+
missing = [i for i in items if i not in columns]
|
|
150
|
+
if missing:
|
|
151
|
+
raise SpecificationError(f"Items in the model but not in the data: {missing}.")
|
|
152
|
+
extra = [c for c in columns if c not in set(items)]
|
|
153
|
+
if extra:
|
|
154
|
+
raise SpecificationError(
|
|
155
|
+
f"Columns in the data but not in the model: {extra}. Drop them before fitting."
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
values = frame[list(items)].to_numpy(dtype=float)
|
|
159
|
+
if values.shape[0] == 0:
|
|
160
|
+
raise SpecificationError("Response data has no rows.")
|
|
161
|
+
out = np.full(values.shape, -1, dtype=np.int32)
|
|
162
|
+
for j, (name, item_model) in enumerate(model.items):
|
|
163
|
+
col = values[:, j]
|
|
164
|
+
obs = ~np.isnan(col)
|
|
165
|
+
k = item_model.kernel.n_categories
|
|
166
|
+
ok = np.isin(col[obs], np.arange(k, dtype=float))
|
|
167
|
+
if not ok.all():
|
|
168
|
+
bad = sorted(set(col[obs][~ok].tolist()))[:5]
|
|
169
|
+
raise SpecificationError(
|
|
170
|
+
f"Item {name!r} ({item_model.name}) must have values 0..{k - 1} or NaN; "
|
|
171
|
+
f"found {bad}."
|
|
172
|
+
)
|
|
173
|
+
out[obs, j] = col[obs].astype(np.int32)
|
|
174
|
+
return out
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def coerce_groups(
|
|
178
|
+
group: Any, model: Model, n: int, *, require_all: bool = True
|
|
179
|
+
) -> tuple[np.ndarray, tuple[str, ...]]:
|
|
180
|
+
"""Return integer group codes (``(N,)``) and group names in the model's order.
|
|
181
|
+
|
|
182
|
+
``require_all`` (estimation) demands that every declared group appears in the data.
|
|
183
|
+
"""
|
|
184
|
+
names = tuple(name for name, _ in model.resolved_groups())
|
|
185
|
+
if not model.is_multigroup:
|
|
186
|
+
if group is not None:
|
|
187
|
+
raise SpecificationError(
|
|
188
|
+
"group= was given but the model has no groups; declare them with with_groups()."
|
|
189
|
+
)
|
|
190
|
+
return np.zeros(n, dtype=np.int32), names
|
|
191
|
+
if group is None:
|
|
192
|
+
raise SpecificationError(f"The model has groups {list(names)}; pass group= labels.")
|
|
193
|
+
labels = np.asarray(group.to_numpy() if hasattr(group, "to_numpy") else group).astype(str)
|
|
194
|
+
if labels.shape != (n,):
|
|
195
|
+
raise SpecificationError(f"group= must have one label per row ({n}), got {labels.shape}.")
|
|
196
|
+
unknown = sorted(set(labels.tolist()) - set(names))
|
|
197
|
+
if unknown:
|
|
198
|
+
raise SpecificationError(f"group= has labels not declared in with_groups(): {unknown}.")
|
|
199
|
+
absent = [g for g in names if g not in set(labels.tolist())]
|
|
200
|
+
if absent and require_all:
|
|
201
|
+
raise SpecificationError(f"Groups declared but absent from the data: {absent}.")
|
|
202
|
+
lookup = {g: i for i, g in enumerate(names)}
|
|
203
|
+
return np.array([lookup[v] for v in labels], dtype=np.int32), names
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def compress_patterns(
|
|
207
|
+
y: np.ndarray, group: np.ndarray
|
|
208
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
|
|
209
|
+
"""Return unique (group, pattern) rows, their groups, counts and each row's index (§4.1)."""
|
|
210
|
+
keyed = np.column_stack([group, y])
|
|
211
|
+
uniq, inverse, counts = np.unique(keyed, axis=0, return_inverse=True, return_counts=True)
|
|
212
|
+
return uniq[:, 1:], uniq[:, 0], counts.astype(float), inverse.reshape(-1)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def pad_patterns(
|
|
216
|
+
patterns: np.ndarray, groups: np.ndarray, counts: np.ndarray
|
|
217
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
218
|
+
"""Pad to the next power-of-two bucket (at least 8) with zero-count rows (DESIGN.md §4.1)."""
|
|
219
|
+
n = patterns.shape[0]
|
|
220
|
+
bucket = max(8, 1 << (n - 1).bit_length())
|
|
221
|
+
pad = bucket - n
|
|
222
|
+
return (
|
|
223
|
+
np.vstack([patterns, np.zeros((pad, patterns.shape[1]), dtype=patterns.dtype)]),
|
|
224
|
+
np.concatenate([groups, np.zeros(pad, dtype=groups.dtype)]),
|
|
225
|
+
np.concatenate([counts, np.zeros(pad)]),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
# --------------------------------------------------------------------------------------------
|
|
230
|
+
# Parameter table
|
|
231
|
+
# --------------------------------------------------------------------------------------------
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _non_slope_starts(item_model: ItemModel, item: np.ndarray, a_eff: float) -> list[float]:
|
|
235
|
+
"""Return classical starting values for non-slope parameters given effective slope ``a_eff``."""
|
|
236
|
+
p = float(item.mean())
|
|
237
|
+
if isinstance(item_model, (ThreePL, FourPL)):
|
|
238
|
+
g, u = _asymptote_starts(p, free_upper=isinstance(item_model, FourPL))
|
|
239
|
+
return [_intercept_start((p - g) / (u - g), a_eff), g, u]
|
|
240
|
+
if isinstance(item_model, GRM):
|
|
241
|
+
cum = [float((item >= k).mean()) for k in range(1, item_model.n_categories)]
|
|
242
|
+
d = [_intercept_start(prob, a_eff) for prob in cum]
|
|
243
|
+
for k in range(1, len(d)):
|
|
244
|
+
d[k] = min(d[k], d[k - 1] - 0.05)
|
|
245
|
+
return d
|
|
246
|
+
if isinstance(item_model, (GPCM, PCM)):
|
|
247
|
+
return _gpcm_intercept_starts(item, item_model.n_categories, a_eff)
|
|
248
|
+
if isinstance(item_model, Nominal):
|
|
249
|
+
return [
|
|
250
|
+
*(float(k) for k in range(1, item_model.n_categories - 1)),
|
|
251
|
+
*_gpcm_intercept_starts(item, item_model.n_categories, a_eff),
|
|
252
|
+
]
|
|
253
|
+
return [_intercept_start(p, a_eff)]
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _start_values(model: Model, y: np.ndarray) -> dict[str, np.ndarray]:
|
|
257
|
+
obs = y >= 0
|
|
258
|
+
scores = np.where(obs, y, 0)
|
|
259
|
+
if not model.is_multidimensional:
|
|
260
|
+
total = scores.sum(axis=1)
|
|
261
|
+
out = {}
|
|
262
|
+
for j, (name, item_model) in enumerate(model.items):
|
|
263
|
+
rows = obs[:, j]
|
|
264
|
+
if rows.sum() < 2:
|
|
265
|
+
# Not estimable (reported later by _check_estimable); finite placeholder values
|
|
266
|
+
# (starts for p = 0.5) keep the table valid when the user fixes this item.
|
|
267
|
+
out[name] = item_model.start_values(np.array([0.0, 1.0]), np.zeros(2))
|
|
268
|
+
continue
|
|
269
|
+
item = y[rows, j].astype(float)
|
|
270
|
+
rest = (total - scores[:, j])[rows].astype(float)
|
|
271
|
+
out[name] = item_model.start_values(item, rest)
|
|
272
|
+
return out
|
|
273
|
+
|
|
274
|
+
# Multidimensional confirmatory starts (DESIGN.md §4.10, §15.31): positive slopes on loaded
|
|
275
|
+
# factors (from factor-specific item-rest correlations, scaled by 1/sqrt(n_loaded)) and 0 on
|
|
276
|
+
# unloaded factors; intercepts/asymptotes use the effective slope norm ||a||.
|
|
277
|
+
n_factors = model.n_factors
|
|
278
|
+
col_of = {name: j for j, (name, _) in enumerate(model.items)}
|
|
279
|
+
assert model.factors is not None
|
|
280
|
+
factor_totals = [
|
|
281
|
+
scores[:, [col_of[item_name] for item_name in assigned]].sum(axis=1)
|
|
282
|
+
for _, assigned in model.factors
|
|
283
|
+
]
|
|
284
|
+
out = {}
|
|
285
|
+
for j, (name, item_model) in enumerate(model.items):
|
|
286
|
+
rows = obs[:, j]
|
|
287
|
+
loaded = model.item_factors(name)
|
|
288
|
+
slopes = np.zeros(n_factors, dtype=float)
|
|
289
|
+
if rows.sum() < 2:
|
|
290
|
+
placeholder = np.array([0.0, 1.0])
|
|
291
|
+
for m in loaded:
|
|
292
|
+
slopes[m] = (
|
|
293
|
+
1.0 if isinstance(item_model, (Rasch, PCM)) else 1.0 / math.sqrt(len(loaded))
|
|
294
|
+
)
|
|
295
|
+
a_eff = max(float(np.linalg.norm(slopes)), 0.25)
|
|
296
|
+
out[name] = np.array([*slopes, *_non_slope_starts(item_model, placeholder, a_eff)])
|
|
297
|
+
continue
|
|
298
|
+
item = y[rows, j].astype(float)
|
|
299
|
+
for m in loaded:
|
|
300
|
+
if isinstance(item_model, (Rasch, PCM)):
|
|
301
|
+
slopes[m] = 1.0
|
|
302
|
+
else:
|
|
303
|
+
rest_m = (factor_totals[m] - scores[:, j])[rows].astype(float)
|
|
304
|
+
slopes[m] = float(
|
|
305
|
+
np.clip(_slope_start(item, rest_m) / math.sqrt(len(loaded)), 0.25, 3.0)
|
|
306
|
+
)
|
|
307
|
+
a_eff = max(float(np.linalg.norm(slopes)), 0.25)
|
|
308
|
+
out[name] = np.array([*slopes, *_non_slope_starts(item_model, item, a_eff)])
|
|
309
|
+
return out
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _prior_center(pri: Prior) -> float | None:
|
|
313
|
+
"""Return a representative interior point for ``pri``, or ``None`` if it overflows."""
|
|
314
|
+
if isinstance(pri, NormalPrior):
|
|
315
|
+
return pri.mean
|
|
316
|
+
if isinstance(pri, LogNormalPrior):
|
|
317
|
+
try:
|
|
318
|
+
return math.exp(pri.mean_log)
|
|
319
|
+
except OverflowError:
|
|
320
|
+
return None
|
|
321
|
+
if isinstance(pri, BetaPrior):
|
|
322
|
+
return pri.a / (pri.a + pri.b)
|
|
323
|
+
return None
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _interior_point(lo: float, hi: float, candidate: float | None = None) -> float:
|
|
327
|
+
"""Return a finite point strictly inside ``(lo, hi)`` (assuming ``lo < hi``)."""
|
|
328
|
+
if candidate is not None and math.isfinite(candidate) and lo < candidate < hi:
|
|
329
|
+
return candidate
|
|
330
|
+
if math.isfinite(lo) and math.isfinite(hi):
|
|
331
|
+
return 0.5 * (lo + hi)
|
|
332
|
+
if math.isfinite(lo):
|
|
333
|
+
return lo + 1.0
|
|
334
|
+
if math.isfinite(hi):
|
|
335
|
+
return hi - 1.0
|
|
336
|
+
return 0.0
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _order_grm_intercepts(
|
|
340
|
+
d: np.ndarray,
|
|
341
|
+
is_free: Sequence[bool],
|
|
342
|
+
eff_lo: Sequence[float],
|
|
343
|
+
eff_hi: Sequence[float],
|
|
344
|
+
) -> np.ndarray:
|
|
345
|
+
"""Ensure GRM intercepts are strictly decreasing inside each free parameter's open bounds."""
|
|
346
|
+
m = len(d)
|
|
347
|
+
if m < 2 or all(float(d[j]) > float(d[j + 1]) for j in range(m - 1)):
|
|
348
|
+
return d
|
|
349
|
+
lb = [eff_lo[j] if is_free[j] else float(d[j]) for j in range(m)]
|
|
350
|
+
ub = [eff_hi[j] if is_free[j] else float(d[j]) for j in range(m)]
|
|
351
|
+
for j in range(m - 2, -1, -1):
|
|
352
|
+
if is_free[j]:
|
|
353
|
+
lb[j] = max(lb[j], lb[j + 1])
|
|
354
|
+
for j in range(1, m):
|
|
355
|
+
if is_free[j]:
|
|
356
|
+
ub[j] = min(ub[j], ub[j - 1])
|
|
357
|
+
if any(is_free[j] and not (lb[j] < ub[j]) for j in range(m)):
|
|
358
|
+
return d
|
|
359
|
+
out = d.copy()
|
|
360
|
+
j = 0
|
|
361
|
+
while j < m:
|
|
362
|
+
if not is_free[j]:
|
|
363
|
+
j += 1
|
|
364
|
+
continue
|
|
365
|
+
s = j
|
|
366
|
+
while j < m and is_free[j]:
|
|
367
|
+
j += 1
|
|
368
|
+
e = j - 1
|
|
369
|
+
for idx in range(s, e + 1):
|
|
370
|
+
rem = e - idx + 1
|
|
371
|
+
lo = lb[idx]
|
|
372
|
+
hi = ub[idx] if idx == 0 else min(ub[idx], float(out[idx - 1]))
|
|
373
|
+
if math.isfinite(lo) and math.isfinite(hi):
|
|
374
|
+
out[idx] = lo + (hi - lo) * (rem / (rem + 1.0))
|
|
375
|
+
elif math.isfinite(lo):
|
|
376
|
+
out[idx] = lo + 0.5 * rem
|
|
377
|
+
elif math.isfinite(hi):
|
|
378
|
+
out[idx] = hi - 0.5
|
|
379
|
+
else:
|
|
380
|
+
out[idx] = 0.5 * (rem - 0.5 * (e - s + 2))
|
|
381
|
+
return out
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _mixture_latent_rows(dist: NormalMixture) -> list[tuple[str, float, bool, float, float]]:
|
|
385
|
+
"""Latent ``(param, value, free, lower, upper)`` rows of a ``NormalMixture`` (DESIGN §16.7).
|
|
386
|
+
|
|
387
|
+
``mean`` and ``var`` behave as for ``Normal``; the raw shape parameters ``rmean_c``,
|
|
388
|
+
``rvar_c`` and ``logit_c`` (``c >= 2``) are free, starting at
|
|
389
|
+
:meth:`~flexpyirt.NormalMixture.raw_starts`.
|
|
390
|
+
"""
|
|
391
|
+
rows: list[tuple[str, float, bool, float, float]] = [
|
|
392
|
+
("mean", dist.mean, dist.free_mean, -np.inf, np.inf),
|
|
393
|
+
("var", dist.var, dist.free_var, 0.0, np.inf),
|
|
394
|
+
]
|
|
395
|
+
starts = dist.raw_starts()
|
|
396
|
+
for c in range(2, dist.n_components + 1):
|
|
397
|
+
rmean, rvar, logit = starts[3 * (c - 2) : 3 * (c - 1)]
|
|
398
|
+
rows.append((f"rmean_{c}", rmean, True, -np.inf, np.inf))
|
|
399
|
+
rows.append((f"rvar_{c}", rvar, True, 0.0, np.inf))
|
|
400
|
+
rows.append((f"logit_{c}", logit, True, -np.inf, np.inf))
|
|
401
|
+
return rows
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _davidian_phi_starts(degree: int, y: np.ndarray) -> list[float]:
|
|
405
|
+
"""Return small skewness-aligned starting angles for ``DavidianCurve`` (DESIGN.md §16.4).
|
|
406
|
+
|
|
407
|
+
``phi = 0`` is a stationary point of the standardized likelihood (the scores in ``phi_1`` and
|
|
408
|
+
``phi_2`` vanish there), so the start is moved off it. The sign is chosen so that the
|
|
409
|
+
standardized start density has a third standardized moment with the same sign as the
|
|
410
|
+
total-score skewness: to leading order ``+4 phi_1**3`` for ``degree == 1`` (``+0.0039`` at
|
|
411
|
+
``phi_1 = 0.1``) and ``-8.3 phi_1 phi_2`` for ``degree >= 2`` (``+0.083`` at
|
|
412
|
+
``(phi_1, phi_2) = (-0.1, 0.1)``).
|
|
413
|
+
"""
|
|
414
|
+
obs = y >= 0
|
|
415
|
+
has_obs = obs.any(axis=1)
|
|
416
|
+
sign = 1.0
|
|
417
|
+
if int(has_obs.sum()) >= 3:
|
|
418
|
+
totals = np.where(obs, y, 0).sum(axis=1)[has_obs].astype(float)
|
|
419
|
+
sd = float(np.std(totals))
|
|
420
|
+
if sd > 0.0:
|
|
421
|
+
skew = float(np.mean(((totals - float(np.mean(totals))) / sd) ** 3))
|
|
422
|
+
sign = 1.0 if skew >= 0.0 else -1.0
|
|
423
|
+
if degree == 1:
|
|
424
|
+
return [0.1 * sign]
|
|
425
|
+
return [-0.1 * sign, 0.1, *([0.0] * (degree - 2))]
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def build_table(model: Model, y: np.ndarray) -> pd.DataFrame:
|
|
429
|
+
"""Build the default ParameterTable (DESIGN.md §5.1, §14.1) from the spec and responses."""
|
|
430
|
+
rows: list[dict[str, Any]] = []
|
|
431
|
+
starts = _start_values(model, y)
|
|
432
|
+
fixed = {(item, param): value for item, param, value in model.fixed}
|
|
433
|
+
priors = {(item, param): dist for item, param, dist in model.priors}
|
|
434
|
+
n_factors = model.n_factors
|
|
435
|
+
all_fixed_slope = all(isinstance(m, (Rasch, PCM)) for _, m in model.items)
|
|
436
|
+
for group_name, latent in model.resolved_groups():
|
|
437
|
+
for name, item_model in model.items:
|
|
438
|
+
kernel = model.item_kernel(item_model)
|
|
439
|
+
base_lo, base_hi = item_model.bounds()
|
|
440
|
+
base_free = item_model.default_free()
|
|
441
|
+
lower = (base_lo[0],) * n_factors + base_lo[1:]
|
|
442
|
+
upper = (base_hi[0],) * n_factors + base_hi[1:]
|
|
443
|
+
loaded_set = set(model.item_factors(name))
|
|
444
|
+
free_default = (
|
|
445
|
+
tuple(m in loaded_set and base_free[0] for m in range(n_factors)) + base_free[1:]
|
|
446
|
+
)
|
|
447
|
+
param_names = kernel.param_names
|
|
448
|
+
item_starts = starts[name].copy()
|
|
449
|
+
is_free = [
|
|
450
|
+
free_default[k] and (name, param) not in fixed
|
|
451
|
+
for k, param in enumerate(param_names)
|
|
452
|
+
]
|
|
453
|
+
eff_lo = [float(v) for v in lower]
|
|
454
|
+
eff_hi = [float(v) for v in upper]
|
|
455
|
+
for k, param in enumerate(param_names):
|
|
456
|
+
if not is_free[k]:
|
|
457
|
+
item_starts[k] = fixed.get((name, param), float(item_starts[k]))
|
|
458
|
+
continue
|
|
459
|
+
pri = priors.get((name, param))
|
|
460
|
+
if pri is not None:
|
|
461
|
+
p_lo, p_hi = pri.support
|
|
462
|
+
eff_lo[k] = max(eff_lo[k], p_lo)
|
|
463
|
+
eff_hi[k] = min(eff_hi[k], p_hi)
|
|
464
|
+
lo_k, hi_k = eff_lo[k], eff_hi[k]
|
|
465
|
+
if lo_k < hi_k and not (lo_k < float(item_starts[k]) < hi_k):
|
|
466
|
+
candidate = _prior_center(pri) if pri is not None else None
|
|
467
|
+
item_starts[k] = _interior_point(lo_k, hi_k, candidate)
|
|
468
|
+
if isinstance(kernel, FourPLKernel):
|
|
469
|
+
g_idx = n_factors + 1
|
|
470
|
+
u_idx = n_factors + 2
|
|
471
|
+
g_free = is_free[g_idx]
|
|
472
|
+
u_free = is_free[u_idx]
|
|
473
|
+
if g_free and not u_free:
|
|
474
|
+
hi_g = min(eff_hi[g_idx], float(item_starts[u_idx]))
|
|
475
|
+
if eff_lo[g_idx] < hi_g and not (
|
|
476
|
+
eff_lo[g_idx] < float(item_starts[g_idx]) < hi_g
|
|
477
|
+
):
|
|
478
|
+
item_starts[g_idx] = _interior_point(eff_lo[g_idx], hi_g)
|
|
479
|
+
elif u_free and not g_free:
|
|
480
|
+
lo_u = max(eff_lo[u_idx], float(item_starts[g_idx]))
|
|
481
|
+
if lo_u < eff_hi[u_idx] and not (
|
|
482
|
+
lo_u < float(item_starts[u_idx]) < eff_hi[u_idx]
|
|
483
|
+
):
|
|
484
|
+
item_starts[u_idx] = _interior_point(lo_u, eff_hi[u_idx])
|
|
485
|
+
elif (
|
|
486
|
+
g_free
|
|
487
|
+
and u_free
|
|
488
|
+
and not (float(item_starts[g_idx]) < float(item_starts[u_idx]))
|
|
489
|
+
):
|
|
490
|
+
ov_lo = max(eff_lo[g_idx], eff_lo[u_idx])
|
|
491
|
+
ov_hi = min(eff_hi[g_idx], eff_hi[u_idx])
|
|
492
|
+
if ov_lo < ov_hi and math.isfinite(ov_lo) and math.isfinite(ov_hi):
|
|
493
|
+
item_starts[g_idx] = ov_lo + (ov_hi - ov_lo) / 3.0
|
|
494
|
+
item_starts[u_idx] = ov_lo + 2.0 * (ov_hi - ov_lo) / 3.0
|
|
495
|
+
elif isinstance(kernel, GradedKernel):
|
|
496
|
+
item_starts[n_factors:] = _order_grm_intercepts(
|
|
497
|
+
item_starts[n_factors:],
|
|
498
|
+
is_free[n_factors:],
|
|
499
|
+
eff_lo[n_factors:],
|
|
500
|
+
eff_hi[n_factors:],
|
|
501
|
+
)
|
|
502
|
+
for k, param in enumerate(param_names):
|
|
503
|
+
key = (name, param)
|
|
504
|
+
rows.append(
|
|
505
|
+
{
|
|
506
|
+
"group": group_name,
|
|
507
|
+
"item": name,
|
|
508
|
+
"model": item_model.name,
|
|
509
|
+
"param": param,
|
|
510
|
+
"value": float(item_starts[k]),
|
|
511
|
+
"free": is_free[k],
|
|
512
|
+
"lower": float(lower[k]),
|
|
513
|
+
"upper": float(upper[k]),
|
|
514
|
+
"prior": priors.get(key),
|
|
515
|
+
}
|
|
516
|
+
)
|
|
517
|
+
if isinstance(latent, EmpiricalHistogram):
|
|
518
|
+
continue
|
|
519
|
+
if isinstance(latent, DavidianCurve):
|
|
520
|
+
phi_starts = _davidian_phi_starts(latent.degree, y)
|
|
521
|
+
latent_rows: list[tuple[str, float, bool, float, float]] = [
|
|
522
|
+
("mean", latent.mean, latent.free_mean, -np.inf, np.inf),
|
|
523
|
+
("var", latent.var, latent.free_var, 0.0, np.inf),
|
|
524
|
+
*(
|
|
525
|
+
(f"phi_{j}", phi_starts[j - 1], True, -np.inf, np.inf)
|
|
526
|
+
for j in range(1, latent.degree + 1)
|
|
527
|
+
),
|
|
528
|
+
]
|
|
529
|
+
lat_model = "Davidian"
|
|
530
|
+
elif isinstance(latent, NormalMixture):
|
|
531
|
+
latent_rows = _mixture_latent_rows(latent)
|
|
532
|
+
lat_model = "Mixture"
|
|
533
|
+
elif not model.is_multidimensional:
|
|
534
|
+
latent_rows = [
|
|
535
|
+
("mean", latent.mean, latent.free_mean, -np.inf, np.inf),
|
|
536
|
+
("var", latent.var, latent.free_var, 0.0, np.inf),
|
|
537
|
+
]
|
|
538
|
+
lat_model = "Normal"
|
|
539
|
+
else:
|
|
540
|
+
# Single group: means 0 and variances 1 (free for all-Rasch/PCM). Multiple groups:
|
|
541
|
+
# each group's Normal spec applies to every factor (DESIGN.md §15.43).
|
|
542
|
+
if model.is_multigroup:
|
|
543
|
+
assert isinstance(latent, Normal)
|
|
544
|
+
mean0, free_mean = latent.mean, latent.free_mean
|
|
545
|
+
var0, free_var = latent.var, latent.free_var
|
|
546
|
+
else:
|
|
547
|
+
mean0, free_mean, var0, free_var = 0.0, False, 1.0, all_fixed_slope
|
|
548
|
+
latent_rows = [
|
|
549
|
+
*(
|
|
550
|
+
(f"mean_{m}", mean0, free_mean, -np.inf, np.inf)
|
|
551
|
+
for m in range(1, n_factors + 1)
|
|
552
|
+
),
|
|
553
|
+
*((f"var_{m}", var0, free_var, 0.0, np.inf) for m in range(1, n_factors + 1)),
|
|
554
|
+
*(
|
|
555
|
+
(f"cor_{i}{j}", 0.0, model.correlated_factors, -1.0, 1.0)
|
|
556
|
+
for i in range(1, n_factors + 1)
|
|
557
|
+
for j in range(i + 1, n_factors + 1)
|
|
558
|
+
),
|
|
559
|
+
]
|
|
560
|
+
lat_model = "MVN"
|
|
561
|
+
for param, value, free, lat_lower, lat_upper in latent_rows:
|
|
562
|
+
rows.append(
|
|
563
|
+
{
|
|
564
|
+
"group": group_name,
|
|
565
|
+
"item": LATENT_ITEM,
|
|
566
|
+
"model": lat_model,
|
|
567
|
+
"param": param,
|
|
568
|
+
"value": float(value),
|
|
569
|
+
"free": bool(free),
|
|
570
|
+
"lower": lat_lower,
|
|
571
|
+
"upper": lat_upper,
|
|
572
|
+
"prior": None,
|
|
573
|
+
}
|
|
574
|
+
)
|
|
575
|
+
table = pd.DataFrame(rows)
|
|
576
|
+
table["prior"] = table["prior"].astype(object)
|
|
577
|
+
free_mask = table["free"].to_numpy(dtype=bool)
|
|
578
|
+
item_col = table["item"].to_numpy(dtype=object)
|
|
579
|
+
param_col = table["param"].to_numpy(dtype=object)
|
|
580
|
+
group_col = table["group"].to_numpy(dtype=object)
|
|
581
|
+
# Equalities (across groups, §14.1, and across items, §16.1) merge free rows by union-find.
|
|
582
|
+
parent = np.arange(len(table))
|
|
583
|
+
|
|
584
|
+
def find(i: int) -> int:
|
|
585
|
+
while parent[i] != i:
|
|
586
|
+
parent[i] = parent[parent[i]]
|
|
587
|
+
i = int(parent[i])
|
|
588
|
+
return i
|
|
589
|
+
|
|
590
|
+
def union(rows_eq: np.ndarray) -> None:
|
|
591
|
+
if rows_eq.size < 2:
|
|
592
|
+
return
|
|
593
|
+
root = find(int(rows_eq[0]))
|
|
594
|
+
for r in rows_eq[1:].tolist():
|
|
595
|
+
other = find(int(r))
|
|
596
|
+
if other != root:
|
|
597
|
+
parent[max(root, other)] = min(root, other)
|
|
598
|
+
root = min(root, other)
|
|
599
|
+
|
|
600
|
+
for items, params in model.equal:
|
|
601
|
+
for item in items:
|
|
602
|
+
mask = (item_col == item) & free_mask
|
|
603
|
+
if params is not None:
|
|
604
|
+
mask &= np.isin(param_col, list(params))
|
|
605
|
+
for param in set(param_col[mask].tolist()):
|
|
606
|
+
union(np.flatnonzero(mask & (param_col == param)))
|
|
607
|
+
for items, params in model.equal_items:
|
|
608
|
+
in_items = np.isin(item_col, list(items)) & free_mask
|
|
609
|
+
for group_name in dict.fromkeys(group_col.tolist()):
|
|
610
|
+
for param in params:
|
|
611
|
+
union(np.flatnonzero(in_items & (group_col == group_name) & (param_col == param)))
|
|
612
|
+
|
|
613
|
+
roots = np.array([find(i) for i in range(len(table))])
|
|
614
|
+
# Number the merged rows in order of first appearance (default ids follow the row order).
|
|
615
|
+
ids = np.full(len(table), -1)
|
|
616
|
+
order: dict[int, int] = {}
|
|
617
|
+
for i in np.flatnonzero(free_mask).tolist():
|
|
618
|
+
ids[i] = order.setdefault(int(roots[i]), len(order))
|
|
619
|
+
# A parameter shared across items starts at the mean of its rows' default starting values.
|
|
620
|
+
if model.equal_items:
|
|
621
|
+
values = table["value"].to_numpy(dtype=float).copy()
|
|
622
|
+
for fid in range(len(order)):
|
|
623
|
+
rows_f = np.flatnonzero(ids == fid)
|
|
624
|
+
if np.unique(item_col[rows_f]).size > 1:
|
|
625
|
+
values[rows_f] = float(np.mean(values[rows_f]))
|
|
626
|
+
table["value"] = values
|
|
627
|
+
table["free_id"] = ids
|
|
628
|
+
return table[list(TABLE_COLUMNS)].astype({"free": bool, "free_id": int})
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
def model_parameter_schema(model: Model) -> pd.DataFrame:
|
|
632
|
+
"""Return canonical ``(group, item, param, model, lower, upper)`` bounds for ``model``."""
|
|
633
|
+
rows: list[tuple[str, str, str, str, float, float]] = []
|
|
634
|
+
for group_name, latent in model.resolved_groups():
|
|
635
|
+
for name, item_model in model.items:
|
|
636
|
+
lower, upper = item_model.bounds()
|
|
637
|
+
n_slopes = model.n_factors
|
|
638
|
+
# Multidimensional items repeat the slope bounds for a1..aD (as in build_table).
|
|
639
|
+
lower = (lower[0],) * n_slopes + tuple(lower[1:])
|
|
640
|
+
upper = (upper[0],) * n_slopes + tuple(upper[1:])
|
|
641
|
+
names = model.item_kernel(item_model).param_names
|
|
642
|
+
for param, lo, hi in zip(names, lower, upper, strict=True):
|
|
643
|
+
rows.append((group_name, name, param, item_model.name, float(lo), float(hi)))
|
|
644
|
+
if isinstance(latent, EmpiricalHistogram):
|
|
645
|
+
continue
|
|
646
|
+
if isinstance(latent, DavidianCurve):
|
|
647
|
+
rows.append((group_name, LATENT_ITEM, "mean", "Davidian", -np.inf, np.inf))
|
|
648
|
+
rows.append((group_name, LATENT_ITEM, "var", "Davidian", 0.0, np.inf))
|
|
649
|
+
for j in range(1, latent.degree + 1):
|
|
650
|
+
rows.append((group_name, LATENT_ITEM, f"phi_{j}", "Davidian", -np.inf, np.inf))
|
|
651
|
+
continue
|
|
652
|
+
if isinstance(latent, NormalMixture):
|
|
653
|
+
for lat_param in mixture_param_names(latent.n_components):
|
|
654
|
+
positive = lat_param == "var" or lat_param.startswith("rvar_")
|
|
655
|
+
lo_hi = (0.0, np.inf) if positive else (-np.inf, np.inf)
|
|
656
|
+
rows.append((group_name, LATENT_ITEM, lat_param, "Mixture", *lo_hi))
|
|
657
|
+
continue
|
|
658
|
+
if not model.is_multidimensional:
|
|
659
|
+
rows.append((group_name, LATENT_ITEM, "mean", "Normal", -np.inf, np.inf))
|
|
660
|
+
rows.append((group_name, LATENT_ITEM, "var", "Normal", 0.0, np.inf))
|
|
661
|
+
continue
|
|
662
|
+
for lat_param in latent_param_names(model.n_factors):
|
|
663
|
+
if lat_param.startswith("var_"):
|
|
664
|
+
lo_hi = (0.0, np.inf)
|
|
665
|
+
elif lat_param.startswith("cor_"):
|
|
666
|
+
lo_hi = (-1.0, 1.0)
|
|
667
|
+
else:
|
|
668
|
+
lo_hi = (-np.inf, np.inf)
|
|
669
|
+
rows.append((group_name, LATENT_ITEM, lat_param, "MVN", *lo_hi))
|
|
670
|
+
return pd.DataFrame(rows, columns=["group", "item", "param", "model", "lower", "upper"])
|
|
671
|
+
|
|
672
|
+
|
|
673
|
+
def _validate_value_column(
|
|
674
|
+
t: pd.DataFrame,
|
|
675
|
+
model: Model,
|
|
676
|
+
*,
|
|
677
|
+
value_col: str,
|
|
678
|
+
free_label: str,
|
|
679
|
+
fixed_label: str,
|
|
680
|
+
) -> None:
|
|
681
|
+
"""Validate finiteness, bounds, prior support, and model ordering for one value column."""
|
|
682
|
+
group_col = t["group"].to_numpy(dtype=object)
|
|
683
|
+
item_col = t["item"].to_numpy(dtype=object)
|
|
684
|
+
param_col = t["param"].to_numpy(dtype=object)
|
|
685
|
+
value = t[value_col].to_numpy(dtype=float)
|
|
686
|
+
lower = t["lower"].to_numpy(dtype=float)
|
|
687
|
+
upper = t["upper"].to_numpy(dtype=float)
|
|
688
|
+
free = t["free"].to_numpy(dtype=bool)
|
|
689
|
+
prior_col = t["prior"].to_numpy(dtype=object)
|
|
690
|
+
for i in range(len(t)):
|
|
691
|
+
where = f"(group={group_col[i]!r}, item={item_col[i]!r}, param={param_col[i]!r})"
|
|
692
|
+
if not np.isfinite(value[i]):
|
|
693
|
+
raise SpecificationError(f"Non-finite {value_col} {value[i]} at {where}.")
|
|
694
|
+
if free[i] and not (lower[i] < value[i] < upper[i]):
|
|
695
|
+
raise SpecificationError(
|
|
696
|
+
f"{free_label} {value[i]} is not strictly inside ({lower[i]}, {upper[i]}) "
|
|
697
|
+
f"at {where}."
|
|
698
|
+
)
|
|
699
|
+
if not free[i] and not (lower[i] <= value[i] <= upper[i]):
|
|
700
|
+
raise SpecificationError(
|
|
701
|
+
f"{fixed_label} {value[i]} is outside [{lower[i]}, {upper[i]}] at {where}."
|
|
702
|
+
)
|
|
703
|
+
if (
|
|
704
|
+
item_col[i] == LATENT_ITEM
|
|
705
|
+
and (param_col[i] == "var" or str(param_col[i]).startswith(("var_", "rvar_")))
|
|
706
|
+
and not value[i] > 0
|
|
707
|
+
):
|
|
708
|
+
raise SpecificationError(f"Latent variance must be positive at {where}.")
|
|
709
|
+
if (
|
|
710
|
+
item_col[i] == LATENT_ITEM
|
|
711
|
+
and str(param_col[i]).startswith("cor_")
|
|
712
|
+
and not (-1.0 < value[i] < 1.0)
|
|
713
|
+
):
|
|
714
|
+
raise SpecificationError(
|
|
715
|
+
f"Latent correlation must lie strictly in (-1, 1), got {value[i]} at {where}."
|
|
716
|
+
)
|
|
717
|
+
pri = prior_col[i]
|
|
718
|
+
if pri is not None and free[i]:
|
|
719
|
+
p_lo, p_hi = pri.support
|
|
720
|
+
if not (p_lo < value[i] < p_hi):
|
|
721
|
+
raise SpecificationError(
|
|
722
|
+
f"{free_label} {value[i]} is outside the support ({p_lo}, {p_hi}) "
|
|
723
|
+
f"of {pri!r} at {where}."
|
|
724
|
+
)
|
|
725
|
+
|
|
726
|
+
# Asymptote ordering g < u for 3PL / 4PL items.
|
|
727
|
+
fourpl_items = {name for name, m in model.items if isinstance(m.kernel, FourPLKernel)}
|
|
728
|
+
if fourpl_items:
|
|
729
|
+
sub = t[t["item"].isin(fourpl_items) & t["param"].isin(["g", "u"])]
|
|
730
|
+
for (grp, itm), rows in sub.groupby(["group", "item"], sort=False):
|
|
731
|
+
vals = dict(zip(rows["param"], rows[value_col], strict=True))
|
|
732
|
+
if not vals["g"] < vals["u"]:
|
|
733
|
+
raise SpecificationError(
|
|
734
|
+
f"Lower asymptote g ({vals['g']}) must be < upper asymptote u ({vals['u']}) "
|
|
735
|
+
f"at (group={grp!r}, item={itm!r})."
|
|
736
|
+
)
|
|
737
|
+
|
|
738
|
+
# Intercept ordering d1 > d2 > ... > d_{K-1} for GRM items.
|
|
739
|
+
grm_items = {
|
|
740
|
+
name: m.kernel.intercept_params
|
|
741
|
+
for name, m in model.items
|
|
742
|
+
if isinstance(m.kernel, GradedKernel) and m.kernel.n_categories > 2
|
|
743
|
+
}
|
|
744
|
+
if grm_items:
|
|
745
|
+
sub = t[t["item"].isin(grm_items)]
|
|
746
|
+
for (grp, itm), rows in sub.groupby(["group", "item"], sort=False):
|
|
747
|
+
vals = dict(zip(rows["param"], rows[value_col], strict=True))
|
|
748
|
+
intercepts = grm_items[str(itm)]
|
|
749
|
+
ds = [float(vals[p]) for p in intercepts]
|
|
750
|
+
if not all(ds[k] > ds[k + 1] for k in range(len(ds) - 1)):
|
|
751
|
+
raise SpecificationError(
|
|
752
|
+
f"GRM intercepts ({value_col}) must satisfy "
|
|
753
|
+
f"{' > '.join(intercepts)} at (group={grp!r}, item={itm!r}), got {ds}."
|
|
754
|
+
)
|
|
755
|
+
|
|
756
|
+
|
|
757
|
+
def _validate_shared_free_ids(t: pd.DataFrame) -> None:
|
|
758
|
+
"""Verify rows sharing a ``free_id`` agree in prior and ``(lower, upper)`` (DESIGN §16.1).
|
|
759
|
+
|
|
760
|
+
A ``free_id`` may be shared across groups and across items (also of different item models),
|
|
761
|
+
but within one item it maps to a single parameter. Latent-distribution parameters cannot share
|
|
762
|
+
a ``free_id`` with item parameters.
|
|
763
|
+
"""
|
|
764
|
+
free_rows = t[t["free"]]
|
|
765
|
+
within = free_rows.groupby(["free_id", "item"])["param"].nunique()
|
|
766
|
+
if (within > 1).any():
|
|
767
|
+
fid, item = within[within > 1].index[0]
|
|
768
|
+
raise SpecificationError(
|
|
769
|
+
f"free_id {int(fid)} is shared by different parameters of item {item!r}."
|
|
770
|
+
)
|
|
771
|
+
is_latent = (free_rows["item"] == LATENT_ITEM).to_numpy(dtype=bool)
|
|
772
|
+
fid_col = free_rows["free_id"].to_numpy(dtype=int)
|
|
773
|
+
both = np.intersect1d(fid_col[is_latent], fid_col[~is_latent])
|
|
774
|
+
if both.size:
|
|
775
|
+
raise SpecificationError(
|
|
776
|
+
f"free_id {int(both[0])} is shared by item and latent-distribution parameters."
|
|
777
|
+
)
|
|
778
|
+
for fid_val, rows_f in free_rows.groupby("free_id"):
|
|
779
|
+
priors_f = list(rows_f["prior"])
|
|
780
|
+
first_p = priors_f[0]
|
|
781
|
+
if any(p != first_p for p in priors_f[1:]):
|
|
782
|
+
raise SpecificationError(
|
|
783
|
+
f"Rows sharing free_id {fid_val} have conflicting priors: {priors_f}."
|
|
784
|
+
)
|
|
785
|
+
lowers_f = rows_f["lower"].to_numpy(dtype=float)
|
|
786
|
+
uppers_f = rows_f["upper"].to_numpy(dtype=float)
|
|
787
|
+
if np.any(lowers_f != lowers_f[0]) or np.any(uppers_f != uppers_f[0]):
|
|
788
|
+
raise SpecificationError(f"Rows sharing free_id {fid_val} have conflicting bounds.")
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
def validate_table_constraints(
|
|
792
|
+
table: pd.DataFrame,
|
|
793
|
+
reference: pd.DataFrame,
|
|
794
|
+
model: Model,
|
|
795
|
+
*,
|
|
796
|
+
check_free_ids: bool = True,
|
|
797
|
+
extra_value_cols: Sequence[tuple[str, str, str]] = (),
|
|
798
|
+
) -> pd.DataFrame:
|
|
799
|
+
"""Reorder ``table`` to canonical ``(group, item, param)`` order and check domain invariants."""
|
|
800
|
+
keys = ["group", "item", "param"]
|
|
801
|
+
orig_cols = list(table.columns)
|
|
802
|
+
t = table.set_index(keys).loc[reference.set_index(keys).index].reset_index()[orig_cols]
|
|
803
|
+
|
|
804
|
+
group_col = t["group"].to_numpy(dtype=object)
|
|
805
|
+
item_col = t["item"].to_numpy(dtype=object)
|
|
806
|
+
param_col = t["param"].to_numpy(dtype=object)
|
|
807
|
+
lower = t["lower"].to_numpy(dtype=float)
|
|
808
|
+
upper = t["upper"].to_numpy(dtype=float)
|
|
809
|
+
ref_lower = reference["lower"].to_numpy(dtype=float)
|
|
810
|
+
ref_upper = reference["upper"].to_numpy(dtype=float)
|
|
811
|
+
free = t["free"].to_numpy(dtype=bool)
|
|
812
|
+
prior_col = t["prior"].to_numpy(dtype=object)
|
|
813
|
+
for i in range(len(t)):
|
|
814
|
+
where = f"(group={group_col[i]!r}, item={item_col[i]!r}, param={param_col[i]!r})"
|
|
815
|
+
if not lower[i] < upper[i]:
|
|
816
|
+
raise SpecificationError(f"lower must be < upper at {where}.")
|
|
817
|
+
if lower[i] < ref_lower[i] or upper[i] > ref_upper[i]:
|
|
818
|
+
raise SpecificationError(
|
|
819
|
+
f"Bounds [{lower[i]}, {upper[i]}] exceed model domain "
|
|
820
|
+
f"[{ref_lower[i]}, {ref_upper[i]}] at {where}."
|
|
821
|
+
)
|
|
822
|
+
pri = prior_col[i]
|
|
823
|
+
if pri is not None:
|
|
824
|
+
if item_col[i] == LATENT_ITEM:
|
|
825
|
+
raise SpecificationError(
|
|
826
|
+
f"Priors on latent-distribution parameters are not supported at {where}."
|
|
827
|
+
)
|
|
828
|
+
if not isinstance(pri, PRIOR_TYPES):
|
|
829
|
+
raise SpecificationError(
|
|
830
|
+
f"Invalid prior {pri!r} at {where}; "
|
|
831
|
+
"use NormalPrior, LogNormalPrior, BetaPrior or None."
|
|
832
|
+
)
|
|
833
|
+
if free[i]:
|
|
834
|
+
p_lo, p_hi = pri.support
|
|
835
|
+
if not (max(lower[i], p_lo) < min(upper[i], p_hi)):
|
|
836
|
+
raise SpecificationError(
|
|
837
|
+
f"Bounds [{lower[i]}, {upper[i]}] do not overlap the support "
|
|
838
|
+
f"({p_lo}, {p_hi}) of {pri!r} at {where}."
|
|
839
|
+
)
|
|
840
|
+
|
|
841
|
+
_validate_value_column(
|
|
842
|
+
t, model, value_col="value", free_label="Starting value", fixed_label="Fixed value"
|
|
843
|
+
)
|
|
844
|
+
for col, free_label, fixed_label in extra_value_cols:
|
|
845
|
+
_validate_value_column(
|
|
846
|
+
t, model, value_col=col, free_label=free_label, fixed_label=fixed_label
|
|
847
|
+
)
|
|
848
|
+
if check_free_ids:
|
|
849
|
+
_validate_shared_free_ids(t)
|
|
850
|
+
return t
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def validate_table(
|
|
854
|
+
table: pd.DataFrame, reference: pd.DataFrame, model: Model, y: np.ndarray, group: np.ndarray
|
|
855
|
+
) -> pd.DataFrame:
|
|
856
|
+
"""Validate a (possibly user-edited) table against the default one and normalize ``free_id``.
|
|
857
|
+
|
|
858
|
+
Free rows with ``free_id < 0`` get fresh ids; ids are renumbered to ``0..n-1`` keeping any
|
|
859
|
+
sharing, also across items (DESIGN.md §16.1).
|
|
860
|
+
Also checks estimability from the data and identification (§4.5, §14.5).
|
|
861
|
+
"""
|
|
862
|
+
missing_cols = [c for c in TABLE_COLUMNS if c not in table.columns]
|
|
863
|
+
if missing_cols:
|
|
864
|
+
raise SpecificationError(f"Parameter table is missing columns {missing_cols}.")
|
|
865
|
+
t = table[list(TABLE_COLUMNS)].copy().reset_index(drop=True)
|
|
866
|
+
keys = ["group", "item", "param"]
|
|
867
|
+
if t.duplicated(keys).any():
|
|
868
|
+
dup = t.loc[t.duplicated(keys, keep=False), keys].to_dict("records")
|
|
869
|
+
raise SpecificationError(f"Parameter table has duplicated rows: {dup}.")
|
|
870
|
+
got = set(map(tuple, t[keys].to_numpy().tolist()))
|
|
871
|
+
want = set(map(tuple, reference[keys].to_numpy().tolist()))
|
|
872
|
+
if got != want:
|
|
873
|
+
raise SpecificationError(
|
|
874
|
+
"Parameter table rows do not match the model: "
|
|
875
|
+
f"unexpected {sorted(got - want)}, missing {sorted(want - got)}. "
|
|
876
|
+
"Edit values, free flags, bounds or free_id only."
|
|
877
|
+
)
|
|
878
|
+
t["free"] = t["free"].astype(bool)
|
|
879
|
+
t["prior"] = t["prior"].astype(object)
|
|
880
|
+
for col in ("value", "lower", "upper"):
|
|
881
|
+
t[col] = t[col].astype(float)
|
|
882
|
+
t = validate_table_constraints(t, reference, model, check_free_ids=False)
|
|
883
|
+
t["model"] = reference["model"].to_numpy()
|
|
884
|
+
|
|
885
|
+
free = t["free"].to_numpy(dtype=bool)
|
|
886
|
+
# Positive-definite latent correlation matrix and nonzero starting slopes per factor (D > 1).
|
|
887
|
+
if model.is_multidimensional:
|
|
888
|
+
n_factors = model.n_factors
|
|
889
|
+
cor_names = [
|
|
890
|
+
f"cor_{i}{j}" for i in range(1, n_factors + 1) for j in range(i + 1, n_factors + 1)
|
|
891
|
+
]
|
|
892
|
+
lat_sub = t[t["item"] == LATENT_ITEM]
|
|
893
|
+
for grp_lat, rows_g in lat_sub.groupby("group", sort=False):
|
|
894
|
+
vals_g = dict(zip(rows_g["param"], rows_g["value"], strict=True))
|
|
895
|
+
cors = [float(vals_g[c]) for c in cor_names]
|
|
896
|
+
if not correlation_matrix_is_positive_definite(cors, n_factors):
|
|
897
|
+
raise SpecificationError(
|
|
898
|
+
f"Latent correlation matrix is not positive definite for group {grp_lat!r}: "
|
|
899
|
+
f"{dict(zip(cor_names, cors, strict=True))}."
|
|
900
|
+
)
|
|
901
|
+
items_sub = t[t["item"] != LATENT_ITEM]
|
|
902
|
+
for m, fname in enumerate(model.factor_names, start=1):
|
|
903
|
+
rows_m = items_sub[items_sub["param"] == f"a{m}"]
|
|
904
|
+
slope_vals = rows_m["value"].to_numpy(dtype=float)
|
|
905
|
+
# A factor whose loadings are all fixed at 0 is an identification problem, reported
|
|
906
|
+
# as IdentificationError by _check_identification_mirt; here only starting values.
|
|
907
|
+
if rows_m["free"].any() and not np.any(slope_vals != 0.0):
|
|
908
|
+
raise SpecificationError(
|
|
909
|
+
f"Factor {fname!r} (a{m}) has all starting slopes equal to 0; at least one "
|
|
910
|
+
"loading must have a nonzero starting value."
|
|
911
|
+
)
|
|
912
|
+
|
|
913
|
+
ids = np.where(free, t["free_id"].fillna(-1).to_numpy(dtype=int), -1)
|
|
914
|
+
next_id = int(ids.max()) + 1 if (ids >= 0).any() else 0
|
|
915
|
+
for i in np.flatnonzero(free & (ids < 0)).tolist():
|
|
916
|
+
ids[i] = next_id
|
|
917
|
+
next_id += 1
|
|
918
|
+
_, ids_free = np.unique(ids[ids >= 0], return_inverse=True)
|
|
919
|
+
ids[ids >= 0] = ids_free
|
|
920
|
+
t["free_id"] = ids.astype(int)
|
|
921
|
+
|
|
922
|
+
_validate_shared_free_ids(t)
|
|
923
|
+
_check_estimable(t, model, y, group)
|
|
924
|
+
_check_identification(t, model)
|
|
925
|
+
return t
|
|
926
|
+
|
|
927
|
+
|
|
928
|
+
def _check_estimable(t: pd.DataFrame, model: Model, y: np.ndarray, group: np.ndarray) -> None:
|
|
929
|
+
"""Each free item parameter needs every category observed in the groups that use it."""
|
|
930
|
+
names = [g for g, _ in model.resolved_groups()]
|
|
931
|
+
col = {name: j for j, name in enumerate(model.item_names)}
|
|
932
|
+
n_categories = {name: m.kernel.n_categories for name, m in model.items}
|
|
933
|
+
free_items = t[t["free"] & (t["item"] != LATENT_ITEM)]
|
|
934
|
+
for (item, _fid), rows in free_items.groupby(["item", "free_id"]):
|
|
935
|
+
codes = [names.index(g) for g in rows["group"].unique()]
|
|
936
|
+
resp = y[np.isin(group, codes), col[str(item)]]
|
|
937
|
+
seen = set(np.unique(resp[resp >= 0]).tolist())
|
|
938
|
+
absent = [k for k in range(n_categories[str(item)]) if k not in seen]
|
|
939
|
+
if absent:
|
|
940
|
+
where = (
|
|
941
|
+
"" if not model.is_multigroup else f" in groups {sorted(rows['group'].unique())}"
|
|
942
|
+
)
|
|
943
|
+
raise SpecificationError(
|
|
944
|
+
f"Item {item!r}: categories {absent} are never observed{where}, so its parameters "
|
|
945
|
+
"are not estimable. Collapse categories, fix the item, or constrain it."
|
|
946
|
+
)
|
|
947
|
+
|
|
948
|
+
|
|
949
|
+
def eh_standardization_flags(t: pd.DataFrame, model: Model) -> tuple[bool, bool]:
|
|
950
|
+
"""Return ``(standardize_mean, standardize_var)`` for an EH model (DESIGN.md §4.4, §15.34).
|
|
951
|
+
|
|
952
|
+
The reference group's mean is standardized iff no intercept parameter is fixed in its connected
|
|
953
|
+
component; its variance is standardized iff no nonzero slope parameter is fixed in its
|
|
954
|
+
connected component. Under FIPC (fixed nonzero slopes and fixed intercepts), both are False.
|
|
955
|
+
"""
|
|
956
|
+
if not model.is_empirical_histogram:
|
|
957
|
+
return False, False
|
|
958
|
+
lookup = dict(model.items)
|
|
959
|
+
groups = [g for g, _ in model.resolved_groups()]
|
|
960
|
+
ref = groups[0]
|
|
961
|
+
items = t[t["item"] != LATENT_ITEM]
|
|
962
|
+
role = np.array(
|
|
963
|
+
[
|
|
964
|
+
"slope"
|
|
965
|
+
if p in lookup[i].kernel.slope_params
|
|
966
|
+
else ("intercept" if p in lookup[i].kernel.intercept_params else "other")
|
|
967
|
+
for i, p in zip(items["item"], items["param"], strict=True)
|
|
968
|
+
]
|
|
969
|
+
)
|
|
970
|
+
|
|
971
|
+
flags: dict[str, bool] = {}
|
|
972
|
+
for key, kind in (("var", "slope"), ("mean", "intercept")):
|
|
973
|
+
rows = items[role == kind]
|
|
974
|
+
parent = {g: g for g in groups}
|
|
975
|
+
|
|
976
|
+
def find(g: str, parent: dict[str, str] = parent) -> str:
|
|
977
|
+
while parent[g] != g:
|
|
978
|
+
g = parent[g]
|
|
979
|
+
return g
|
|
980
|
+
|
|
981
|
+
for _, shared in rows[rows["free"]].groupby("free_id"):
|
|
982
|
+
gs = list(shared["group"].unique())
|
|
983
|
+
for other in gs[1:]:
|
|
984
|
+
parent[find(other)] = find(gs[0])
|
|
985
|
+
fixed_rows = rows[~rows["free"]]
|
|
986
|
+
if kind == "slope":
|
|
987
|
+
fixed_rows = fixed_rows[fixed_rows["value"] != 0]
|
|
988
|
+
fixed_roots = {find(g) for g in fixed_rows["group"]}
|
|
989
|
+
flags[key] = find(ref) not in fixed_roots
|
|
990
|
+
return flags["mean"], flags["var"]
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def eh_param_count(t: pd.DataFrame, model: Model, quad: Quadrature) -> int:
|
|
994
|
+
"""Return the number of free EH latent-weight parameters for AIC/BIC (DESIGN.md §4.8, §15.35).
|
|
995
|
+
|
|
996
|
+
Reference group: ``Q - 1 - int(standardize_mean) - int(standardize_var)`` (``Q - 3`` when both
|
|
997
|
+
mean and variance are standardized, ``Q - 2`` for Rasch/PCM, ``Q - 1`` under FIPC). Every
|
|
998
|
+
focal group: ``Q - 1``. Returns ``0`` for ``Normal`` models.
|
|
999
|
+
"""
|
|
1000
|
+
if not model.is_empirical_histogram:
|
|
1001
|
+
return 0
|
|
1002
|
+
std_mean, std_var = eh_standardization_flags(t, model)
|
|
1003
|
+
n_groups = len(model.resolved_groups())
|
|
1004
|
+
q = quad.n_points
|
|
1005
|
+
ref_params = q - 1 - int(std_mean) - int(std_var)
|
|
1006
|
+
focal_params = (n_groups - 1) * (q - 1)
|
|
1007
|
+
return ref_params + focal_params
|
|
1008
|
+
|
|
1009
|
+
|
|
1010
|
+
def _check_identification(t: pd.DataFrame, model: Model) -> None:
|
|
1011
|
+
"""Scale identification rules of DESIGN.md §4.5, §14.5, and §15.31 (necessary conditions)."""
|
|
1012
|
+
if model.is_multidimensional:
|
|
1013
|
+
_check_identification_mirt(t, model)
|
|
1014
|
+
return
|
|
1015
|
+
lookup = dict(model.items)
|
|
1016
|
+
groups = [g for g, _ in model.resolved_groups()]
|
|
1017
|
+
items = t[t["item"] != LATENT_ITEM]
|
|
1018
|
+
role = np.array(
|
|
1019
|
+
[
|
|
1020
|
+
"slope"
|
|
1021
|
+
if p in lookup[i].kernel.slope_params
|
|
1022
|
+
else ("intercept" if p in lookup[i].kernel.intercept_params else "other")
|
|
1023
|
+
for i, p in zip(items["item"], items["param"], strict=True)
|
|
1024
|
+
]
|
|
1025
|
+
)
|
|
1026
|
+
if model.is_empirical_histogram:
|
|
1027
|
+
std_mean, std_var = eh_standardization_flags(t, model)
|
|
1028
|
+
lat_free: dict[tuple[str, str], bool] = {}
|
|
1029
|
+
for idx, g in enumerate(groups):
|
|
1030
|
+
if idx == 0:
|
|
1031
|
+
lat_free[(g, "mean")] = not std_mean
|
|
1032
|
+
lat_free[(g, "var")] = not std_var
|
|
1033
|
+
else:
|
|
1034
|
+
lat_free[(g, "mean")] = True
|
|
1035
|
+
lat_free[(g, "var")] = True
|
|
1036
|
+
else:
|
|
1037
|
+
lat_free = {
|
|
1038
|
+
(g, p): bool(f)
|
|
1039
|
+
for g, i, p, f in zip(t["group"], t["item"], t["param"], t["free"], strict=True)
|
|
1040
|
+
if i == LATENT_ITEM
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
for latent_param, kind, what in (("var", "slope", "scale"), ("mean", "intercept", "location")):
|
|
1044
|
+
rows = items[role == kind]
|
|
1045
|
+
parent = {g: g for g in groups}
|
|
1046
|
+
|
|
1047
|
+
def find(g: str, parent: dict[str, str] = parent) -> str:
|
|
1048
|
+
while parent[g] != g:
|
|
1049
|
+
g = parent[g]
|
|
1050
|
+
return g
|
|
1051
|
+
|
|
1052
|
+
for _, shared in rows[rows["free"]].groupby("free_id"):
|
|
1053
|
+
gs = list(shared["group"].unique())
|
|
1054
|
+
for other in gs[1:]:
|
|
1055
|
+
parent[find(other)] = find(gs[0])
|
|
1056
|
+
fixed_rows = rows[~rows["free"]]
|
|
1057
|
+
if kind == "slope":
|
|
1058
|
+
fixed_rows = fixed_rows[fixed_rows["value"] != 0]
|
|
1059
|
+
anchored = {find(g) for g in fixed_rows["group"]}
|
|
1060
|
+
anchored |= {find(g) for g in groups if not lat_free[(g, latent_param)]}
|
|
1061
|
+
for g in groups:
|
|
1062
|
+
if lat_free[(g, latent_param)] and find(g) not in anchored:
|
|
1063
|
+
where = "" if not model.is_multigroup else f" of group {g!r}"
|
|
1064
|
+
fix_hint = (
|
|
1065
|
+
"fix at least one slope (e.g. Rasch or PCM items)"
|
|
1066
|
+
if kind == "slope"
|
|
1067
|
+
else "fix at least one intercept"
|
|
1068
|
+
)
|
|
1069
|
+
raise IdentificationError(
|
|
1070
|
+
f"The latent {'variance' if latent_param == 'var' else 'mean'}{where} is free "
|
|
1071
|
+
f"but nothing links it to a fixed {what}. Fix it, {fix_hint}, or make items "
|
|
1072
|
+
"equal across groups (anchors)."
|
|
1073
|
+
)
|
|
1074
|
+
if model.is_multigroup and latent_param == "mean":
|
|
1075
|
+
n_groups_per_id = rows[rows["free"]].groupby("free_id")["group"].nunique()
|
|
1076
|
+
for g in groups:
|
|
1077
|
+
if not lat_free[(g, "mean")]:
|
|
1078
|
+
continue
|
|
1079
|
+
own = rows[rows["group"] == g]
|
|
1080
|
+
linked = own.loc[own["free"], "free_id"]
|
|
1081
|
+
n_anchor = int((n_groups_per_id.reindex(linked).fillna(0) > 1).sum())
|
|
1082
|
+
n_anchor += int((~own["free"]).sum())
|
|
1083
|
+
if n_anchor == 1:
|
|
1084
|
+
warnings.warn(
|
|
1085
|
+
f"The latent mean of group {g!r} is linked by a single anchor parameter; "
|
|
1086
|
+
"estimates may be unstable. Consider more anchor items.",
|
|
1087
|
+
FlexpyirtWarning,
|
|
1088
|
+
stacklevel=4,
|
|
1089
|
+
)
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
def _check_identification_mirt(t: pd.DataFrame, model: Model) -> None:
|
|
1093
|
+
"""Identification checks for D > 1 (DESIGN §15.31, §15.43).
|
|
1094
|
+
|
|
1095
|
+
Single group: the per-group checks below. Multiple groups: rotational checks within each
|
|
1096
|
+
group, and scale/location linking per factor across groups (:func:`_check_mirt_group_links`).
|
|
1097
|
+
"""
|
|
1098
|
+
if not model.is_multigroup:
|
|
1099
|
+
_check_identification_mirt_group(t, model, check_scale=True)
|
|
1100
|
+
return
|
|
1101
|
+
for g, _ in model.resolved_groups():
|
|
1102
|
+
_check_identification_mirt_group(t[t["group"] == g], model, check_scale=False)
|
|
1103
|
+
_check_mirt_group_links(t, model)
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
def _check_mirt_group_links(t: pd.DataFrame, model: Model) -> None:
|
|
1107
|
+
"""Per factor, every free ``var_m`` / ``mean_m`` must be linked to a fixed scale / location.
|
|
1108
|
+
|
|
1109
|
+
For factor :math:`m`, groups are connected when they share a free slope ``a{m}`` (scale) or a
|
|
1110
|
+
free intercept of an item loading on :math:`m` (location) through a common ``free_id`` (anchor
|
|
1111
|
+
items). A component is anchored by a fixed nonzero ``a{m}`` (scale), a fixed intercept of an
|
|
1112
|
+
item loading on :math:`m` (location), or a group whose ``var_m`` / ``mean_m`` is fixed
|
|
1113
|
+
(DESIGN.md §4.5, §15.43).
|
|
1114
|
+
"""
|
|
1115
|
+
groups = [g for g, _ in model.resolved_groups()]
|
|
1116
|
+
kernels = {name: model.item_kernel(m) for name, m in model.items}
|
|
1117
|
+
items_df = t[t["item"] != LATENT_ITEM]
|
|
1118
|
+
lat = t[t["item"] == LATENT_ITEM]
|
|
1119
|
+
lat_free = {
|
|
1120
|
+
(g, p): bool(f) for g, p, f in zip(lat["group"], lat["param"], lat["free"], strict=True)
|
|
1121
|
+
}
|
|
1122
|
+
for m, fname in enumerate(model.factor_names, start=1):
|
|
1123
|
+
slope = f"a{m}"
|
|
1124
|
+
s_rows = items_df[items_df["param"] == slope]
|
|
1125
|
+
active = s_rows[s_rows["free"] | (s_rows["value"] != 0.0)]
|
|
1126
|
+
active_pairs = set(zip(active["group"], active["item"], strict=True))
|
|
1127
|
+
int_mask = np.array(
|
|
1128
|
+
[
|
|
1129
|
+
(g, i) in active_pairs and p in kernels[i].intercept_params
|
|
1130
|
+
for g, i, p in zip(
|
|
1131
|
+
items_df["group"], items_df["item"], items_df["param"], strict=True
|
|
1132
|
+
)
|
|
1133
|
+
],
|
|
1134
|
+
dtype=bool,
|
|
1135
|
+
)
|
|
1136
|
+
for latent_param, rows, what in (
|
|
1137
|
+
(f"var_{m}", s_rows, "scale"),
|
|
1138
|
+
(f"mean_{m}", items_df[int_mask], "location"),
|
|
1139
|
+
):
|
|
1140
|
+
parent = {g: g for g in groups}
|
|
1141
|
+
|
|
1142
|
+
def find(g: str, parent: dict[str, str] = parent) -> str:
|
|
1143
|
+
while parent[g] != g:
|
|
1144
|
+
g = parent[g]
|
|
1145
|
+
return g
|
|
1146
|
+
|
|
1147
|
+
for _, shared in rows[rows["free"]].groupby("free_id"):
|
|
1148
|
+
gs = list(shared["group"].unique())
|
|
1149
|
+
for other in gs[1:]:
|
|
1150
|
+
parent[find(other)] = find(gs[0])
|
|
1151
|
+
fixed = rows[~rows["free"]]
|
|
1152
|
+
if what == "scale":
|
|
1153
|
+
fixed = fixed[fixed["value"] != 0.0]
|
|
1154
|
+
anchored = {find(g) for g in fixed["group"]}
|
|
1155
|
+
anchored |= {find(g) for g in groups if not lat_free[(g, latent_param)]}
|
|
1156
|
+
for g in groups:
|
|
1157
|
+
if lat_free[(g, latent_param)] and find(g) not in anchored:
|
|
1158
|
+
raise IdentificationError(
|
|
1159
|
+
f"The latent {latent_param} of group {g!r} (factor {fname!r}) is free but "
|
|
1160
|
+
f"nothing links it to a fixed {what}: make items loading on {fname!r} "
|
|
1161
|
+
"equal across groups (anchors) or fix them."
|
|
1162
|
+
)
|
|
1163
|
+
|
|
1164
|
+
|
|
1165
|
+
def _check_identification_mirt_group(t: pd.DataFrame, model: Model, *, check_scale: bool) -> None:
|
|
1166
|
+
"""Necessary scale, location, and rotational identification checks for D > 1 (DESIGN §15.31)."""
|
|
1167
|
+
n_factors = model.n_factors
|
|
1168
|
+
fnames = model.factor_names
|
|
1169
|
+
lookup = {name: model.item_kernel(m) for name, m in model.items}
|
|
1170
|
+
lat_rows = t[t["item"] == LATENT_ITEM]
|
|
1171
|
+
lat_free = dict(zip(lat_rows["param"], lat_rows["free"].astype(bool), strict=True))
|
|
1172
|
+
items_df = t[t["item"] != LATENT_ITEM]
|
|
1173
|
+
|
|
1174
|
+
free_sets: list[set[str]] = []
|
|
1175
|
+
fixed_nonzero_sets: list[set[str]] = []
|
|
1176
|
+
n_fixed_slopes: list[int] = []
|
|
1177
|
+
fixed_vectors: list[np.ndarray] = []
|
|
1178
|
+
all_items = list(model.item_names)
|
|
1179
|
+
|
|
1180
|
+
for m, fname in enumerate(fnames, start=1):
|
|
1181
|
+
slope = f"a{m}"
|
|
1182
|
+
s_rows = items_df[items_df["param"] == slope]
|
|
1183
|
+
free_items = set(s_rows.loc[s_rows["free"], "item"].tolist())
|
|
1184
|
+
fixed_nz = set(s_rows.loc[(~s_rows["free"]) & (s_rows["value"] != 0.0), "item"].tolist())
|
|
1185
|
+
active_items = free_items | fixed_nz
|
|
1186
|
+
if not active_items:
|
|
1187
|
+
raise IdentificationError(
|
|
1188
|
+
f"Factor {fname!r} ({slope}) has no active loadings (all slopes are fixed at 0)."
|
|
1189
|
+
)
|
|
1190
|
+
if check_scale and lat_free[f"var_{m}"] and not fixed_nz:
|
|
1191
|
+
raise IdentificationError(
|
|
1192
|
+
f"The latent variance of factor {fname!r} (var_{m}) is free, but no slope "
|
|
1193
|
+
f"{slope} is fixed at a nonzero value."
|
|
1194
|
+
)
|
|
1195
|
+
if check_scale and lat_free[f"mean_{m}"]:
|
|
1196
|
+
has_fixed_int = False
|
|
1197
|
+
for itm in active_items:
|
|
1198
|
+
ints = lookup[itm].intercept_params
|
|
1199
|
+
itm_ints = items_df[(items_df["item"] == itm) & (items_df["param"].isin(ints))]
|
|
1200
|
+
if (~itm_ints["free"]).any():
|
|
1201
|
+
has_fixed_int = True
|
|
1202
|
+
break
|
|
1203
|
+
if not has_fixed_int:
|
|
1204
|
+
raise IdentificationError(
|
|
1205
|
+
f"The latent mean of factor {fname!r} (mean_{m}) is free, but no item "
|
|
1206
|
+
"loading on it has a fixed intercept."
|
|
1207
|
+
)
|
|
1208
|
+
free_sets.append(free_items)
|
|
1209
|
+
fixed_nonzero_sets.append(fixed_nz)
|
|
1210
|
+
n_fixed_slopes.append(int((~s_rows["free"]).sum()))
|
|
1211
|
+
fixed_vals = dict(zip(s_rows["item"], s_rows["value"].astype(float), strict=True))
|
|
1212
|
+
fixed_vectors.append(np.array([fixed_vals.get(it, 0.0) for it in all_items]))
|
|
1213
|
+
|
|
1214
|
+
# Necessary confirmatory rotational identification (Bollen, 1989; Reckase, 2009):
|
|
1215
|
+
# each factor involved in c_m free correlations needs at least c_m fixed slopes (typically 0s),
|
|
1216
|
+
# and no two factors may share an identical free-loading set with no fixed nonzero slopes.
|
|
1217
|
+
for m, fname in enumerate(fnames, start=1):
|
|
1218
|
+
free_cors = sum(
|
|
1219
|
+
1
|
|
1220
|
+
for other in range(1, n_factors + 1)
|
|
1221
|
+
if other != m and lat_free[f"cor_{min(m, other)}{max(m, other)}"]
|
|
1222
|
+
)
|
|
1223
|
+
if n_fixed_slopes[m - 1] < free_cors:
|
|
1224
|
+
raise IdentificationError(
|
|
1225
|
+
f"Factor {fname!r} (a{m}) has {free_cors} free correlation(s) but only "
|
|
1226
|
+
f"{n_fixed_slopes[m - 1]} fixed slope(s); confirmatory models need at least "
|
|
1227
|
+
f"{free_cors} fixed loading(s) per correlated factor to prevent rotational "
|
|
1228
|
+
"indeterminacy."
|
|
1229
|
+
)
|
|
1230
|
+
for i in range(n_factors):
|
|
1231
|
+
for j in range(i + 1, n_factors):
|
|
1232
|
+
if (
|
|
1233
|
+
free_sets[i] == free_sets[j]
|
|
1234
|
+
and not fixed_nonzero_sets[i]
|
|
1235
|
+
and not fixed_nonzero_sets[j]
|
|
1236
|
+
):
|
|
1237
|
+
raise IdentificationError(
|
|
1238
|
+
f"Factors {fnames[i]!r} and {fnames[j]!r} have identical free loading "
|
|
1239
|
+
"patterns with no fixed nonzero slopes, which is rotationally unidentified."
|
|
1240
|
+
)
|
|
1241
|
+
# With no free slopes on either factor, proportional fixed loading vectors make the
|
|
1242
|
+
# loading matrix rank deficient (e.g. Rasch/PCM items loading on both factors):
|
|
1243
|
+
# only a combination of the two factors is identified.
|
|
1244
|
+
if not free_sets[i] and not free_sets[j]:
|
|
1245
|
+
vi, vj = fixed_vectors[i], fixed_vectors[j]
|
|
1246
|
+
if np.linalg.matrix_rank(np.vstack([vi, vj])) < 2:
|
|
1247
|
+
raise IdentificationError(
|
|
1248
|
+
f"Factors {fnames[i]!r} and {fnames[j]!r} have proportional fixed loadings "
|
|
1249
|
+
"and no free loadings, so only a combination of them is identified."
|
|
1250
|
+
)
|
|
1251
|
+
|
|
1252
|
+
|
|
1253
|
+
# --------------------------------------------------------------------------------------------
|
|
1254
|
+
# Problem
|
|
1255
|
+
# --------------------------------------------------------------------------------------------
|
|
1256
|
+
|
|
1257
|
+
|
|
1258
|
+
def _coupled_blocks(
|
|
1259
|
+
free_index: Sequence[np.ndarray],
|
|
1260
|
+
slot_bounds: dict[int, tuple[float, float]],
|
|
1261
|
+
) -> tuple[CoupledBlock, ...]:
|
|
1262
|
+
"""Components of items connected by ``free_id``s shared across items (DESIGN.md §16.1).
|
|
1263
|
+
|
|
1264
|
+
``free_index[f]`` is family ``f``'s ``(G, J_f, P_f)`` free-index array and ``slot_bounds``
|
|
1265
|
+
maps each ``free_id`` to its bounds (intersected with its prior's support). Components with a
|
|
1266
|
+
single item are left to the item-wise M-step.
|
|
1267
|
+
"""
|
|
1268
|
+
item_keys = [(f, jj) for f, fi in enumerate(free_index) for jj in range(fi.shape[1])]
|
|
1269
|
+
parent = list(range(len(item_keys)))
|
|
1270
|
+
|
|
1271
|
+
def find(i: int) -> int:
|
|
1272
|
+
while parent[i] != i:
|
|
1273
|
+
parent[i] = parent[parent[i]]
|
|
1274
|
+
i = parent[i]
|
|
1275
|
+
return i
|
|
1276
|
+
|
|
1277
|
+
owner: dict[int, int] = {}
|
|
1278
|
+
for idx, (f, jj) in enumerate(item_keys):
|
|
1279
|
+
for fid in np.unique(free_index[f][:, jj, :]).tolist():
|
|
1280
|
+
if fid < 0:
|
|
1281
|
+
continue
|
|
1282
|
+
if fid in owner:
|
|
1283
|
+
a, b = find(owner[fid]), find(idx)
|
|
1284
|
+
if a != b:
|
|
1285
|
+
parent[max(a, b)] = min(a, b)
|
|
1286
|
+
else:
|
|
1287
|
+
owner[fid] = idx
|
|
1288
|
+
components: dict[int, list[int]] = {}
|
|
1289
|
+
for idx in range(len(item_keys)):
|
|
1290
|
+
components.setdefault(find(idx), []).append(idx)
|
|
1291
|
+
|
|
1292
|
+
blocks: list[CoupledBlock] = []
|
|
1293
|
+
for members_idx in components.values():
|
|
1294
|
+
if len(members_idx) < 2:
|
|
1295
|
+
continue
|
|
1296
|
+
slot_of: dict[int, int] = {}
|
|
1297
|
+
by_family: dict[int, list[int]] = {}
|
|
1298
|
+
for idx in members_idx:
|
|
1299
|
+
f, jj = item_keys[idx]
|
|
1300
|
+
by_family.setdefault(f, []).append(jj)
|
|
1301
|
+
for fid in free_index[f][:, jj, :].ravel().tolist():
|
|
1302
|
+
if fid >= 0 and fid not in slot_of:
|
|
1303
|
+
slot_of[fid] = len(slot_of)
|
|
1304
|
+
members = []
|
|
1305
|
+
for f, positions in by_family.items():
|
|
1306
|
+
sub = free_index[f][:, positions, :]
|
|
1307
|
+
local = np.array([slot_of.get(int(v), -1) for v in sub.ravel()], dtype=np.int32)
|
|
1308
|
+
local = local.reshape(sub.shape)
|
|
1309
|
+
members.append(
|
|
1310
|
+
CoupledMember(
|
|
1311
|
+
positions=jnp.asarray(positions, dtype=jnp.int32),
|
|
1312
|
+
local_index=jnp.asarray(local, dtype=jnp.int32),
|
|
1313
|
+
family=f,
|
|
1314
|
+
)
|
|
1315
|
+
)
|
|
1316
|
+
fids = list(slot_of)
|
|
1317
|
+
blocks.append(
|
|
1318
|
+
CoupledBlock(
|
|
1319
|
+
slot_free_index=jnp.asarray(fids, dtype=jnp.int32),
|
|
1320
|
+
slot_lower=jnp.asarray([slot_bounds[v][0] for v in fids], dtype=jnp.float64),
|
|
1321
|
+
slot_upper=jnp.asarray([slot_bounds[v][1] for v in fids], dtype=jnp.float64),
|
|
1322
|
+
members=tuple(members),
|
|
1323
|
+
)
|
|
1324
|
+
)
|
|
1325
|
+
return tuple(blocks)
|
|
1326
|
+
|
|
1327
|
+
|
|
1328
|
+
@dataclass(frozen=True)
|
|
1329
|
+
class Prepared:
|
|
1330
|
+
"""Coerced data and the validated table."""
|
|
1331
|
+
|
|
1332
|
+
y: np.ndarray
|
|
1333
|
+
group: np.ndarray
|
|
1334
|
+
group_names: tuple[str, ...]
|
|
1335
|
+
table: pd.DataFrame
|
|
1336
|
+
|
|
1337
|
+
|
|
1338
|
+
def prepare(
|
|
1339
|
+
model: Model,
|
|
1340
|
+
data: Any,
|
|
1341
|
+
*,
|
|
1342
|
+
group: Any,
|
|
1343
|
+
item_names: Sequence[str] | None,
|
|
1344
|
+
table: pd.DataFrame | None,
|
|
1345
|
+
) -> Prepared:
|
|
1346
|
+
"""Coerce data and build/validate the parameter table."""
|
|
1347
|
+
y = coerce_responses(data, model, item_names=item_names)
|
|
1348
|
+
codes, names = coerce_groups(group, model, y.shape[0])
|
|
1349
|
+
default = build_table(model, y)
|
|
1350
|
+
final = validate_table(default if table is None else table, default, model, y, codes)
|
|
1351
|
+
return Prepared(y=y, group=codes, group_names=names, table=final)
|
|
1352
|
+
|
|
1353
|
+
|
|
1354
|
+
@dataclass(frozen=True)
|
|
1355
|
+
class Compiled:
|
|
1356
|
+
"""Compiled problem plus what the Result layer needs to map back."""
|
|
1357
|
+
|
|
1358
|
+
problem: CompiledProblem
|
|
1359
|
+
eta0: np.ndarray
|
|
1360
|
+
inverse: np.ndarray
|
|
1361
|
+
n_patterns: int
|
|
1362
|
+
|
|
1363
|
+
|
|
1364
|
+
def compile_problem(
|
|
1365
|
+
model: Model,
|
|
1366
|
+
y: np.ndarray,
|
|
1367
|
+
group: np.ndarray,
|
|
1368
|
+
table: pd.DataFrame,
|
|
1369
|
+
quad: Quadrature,
|
|
1370
|
+
*,
|
|
1371
|
+
eh_weights: np.ndarray | None = None,
|
|
1372
|
+
) -> Compiled:
|
|
1373
|
+
"""Turn a validated table and responses into a :class:`CompiledProblem` (§5.2, §14.1–14.2)."""
|
|
1374
|
+
patterns, pat_groups, counts, inverse = compress_patterns(y, group)
|
|
1375
|
+
n_patterns = patterns.shape[0]
|
|
1376
|
+
patterns, pat_groups, counts = pad_patterns(patterns, pat_groups, counts)
|
|
1377
|
+
n_free = int(table["free_id"].max()) + 1 if table["free"].any() else 0
|
|
1378
|
+
eta0 = np.zeros(n_free)
|
|
1379
|
+
prior_kind = np.zeros(n_free, dtype=np.int32)
|
|
1380
|
+
prior_p1 = np.zeros(n_free, dtype=float)
|
|
1381
|
+
prior_p2 = np.ones(n_free, dtype=float)
|
|
1382
|
+
free_rows = table[table["free"]].drop_duplicates("free_id")
|
|
1383
|
+
free_ids = free_rows["free_id"].to_numpy(dtype=int)
|
|
1384
|
+
eta0[free_ids] = free_rows["value"].to_numpy(dtype=float)
|
|
1385
|
+
for fid_val, pri in zip(free_ids.tolist(), free_rows["prior"].tolist(), strict=True):
|
|
1386
|
+
k_code, p1, p2 = encode_prior(pri)
|
|
1387
|
+
prior_kind[fid_val] = k_code
|
|
1388
|
+
prior_p1[fid_val] = p1
|
|
1389
|
+
prior_p2[fid_val] = p2
|
|
1390
|
+
|
|
1391
|
+
groups = [g for g, _ in model.resolved_groups()]
|
|
1392
|
+
n_groups = len(groups)
|
|
1393
|
+
lookup: dict[tuple[str, str, str], tuple[float, int, float, float, Prior | None]] = {
|
|
1394
|
+
(g, i, p): (v, fid, lo, hi, pri)
|
|
1395
|
+
for g, i, p, v, fid, lo, hi, pri in zip(
|
|
1396
|
+
table["group"],
|
|
1397
|
+
table["item"],
|
|
1398
|
+
table["param"],
|
|
1399
|
+
table["value"].to_numpy(dtype=float),
|
|
1400
|
+
table["free_id"].to_numpy(dtype=int),
|
|
1401
|
+
table["lower"].to_numpy(dtype=float),
|
|
1402
|
+
table["upper"].to_numpy(dtype=float),
|
|
1403
|
+
table["prior"].tolist(),
|
|
1404
|
+
strict=True,
|
|
1405
|
+
)
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
kernels: list[ItemKernel] = []
|
|
1409
|
+
members: dict[ItemKernel, list[int]] = {}
|
|
1410
|
+
for j, (_, item_model) in enumerate(model.items):
|
|
1411
|
+
k = model.item_kernel(item_model)
|
|
1412
|
+
if k not in members:
|
|
1413
|
+
kernels.append(k)
|
|
1414
|
+
members[k] = []
|
|
1415
|
+
members[k].append(j)
|
|
1416
|
+
|
|
1417
|
+
families = []
|
|
1418
|
+
family_free_index: list[np.ndarray] = []
|
|
1419
|
+
slot_bounds: dict[int, tuple[float, float]] = {}
|
|
1420
|
+
for k in kernels:
|
|
1421
|
+
cols = members[k]
|
|
1422
|
+
names = [model.items[j][0] for j in cols]
|
|
1423
|
+
params = list(k.param_names)
|
|
1424
|
+
shape = (n_groups, len(cols), len(params))
|
|
1425
|
+
fixed = np.zeros(shape)
|
|
1426
|
+
free_index = np.full(shape, -1, dtype=np.int32)
|
|
1427
|
+
local_index = np.full(shape, -1, dtype=np.int32)
|
|
1428
|
+
slots: list[list[tuple[int, float, float]]] = []
|
|
1429
|
+
for jj, item in enumerate(names):
|
|
1430
|
+
seen: dict[int, int] = {}
|
|
1431
|
+
item_slots: list[tuple[int, float, float]] = []
|
|
1432
|
+
for gg, g in enumerate(groups):
|
|
1433
|
+
for pp, p in enumerate(params):
|
|
1434
|
+
v, fid, lo, hi, pri = lookup[(g, item, p)]
|
|
1435
|
+
fixed[gg, jj, pp] = v
|
|
1436
|
+
free_index[gg, jj, pp] = fid
|
|
1437
|
+
if fid >= 0:
|
|
1438
|
+
if fid not in seen:
|
|
1439
|
+
seen[fid] = len(item_slots)
|
|
1440
|
+
if pri is not None:
|
|
1441
|
+
p_lo, p_hi = pri.support
|
|
1442
|
+
lo = max(lo, p_lo)
|
|
1443
|
+
hi = min(hi, p_hi)
|
|
1444
|
+
item_slots.append((fid, lo, hi))
|
|
1445
|
+
slot_bounds.setdefault(fid, (lo, hi))
|
|
1446
|
+
local_index[gg, jj, pp] = seen[fid]
|
|
1447
|
+
slots.append(item_slots)
|
|
1448
|
+
n_slots = max(1, max(len(s) for s in slots))
|
|
1449
|
+
slot_free = np.full((len(cols), n_slots), -1, dtype=np.int32)
|
|
1450
|
+
slot_lo = np.full((len(cols), n_slots), -np.inf)
|
|
1451
|
+
slot_hi = np.full((len(cols), n_slots), np.inf)
|
|
1452
|
+
for jj, item_slots in enumerate(slots):
|
|
1453
|
+
for ss, (fid, lo, hi) in enumerate(item_slots):
|
|
1454
|
+
slot_free[jj, ss], slot_lo[jj, ss], slot_hi[jj, ss] = fid, lo, hi
|
|
1455
|
+
family_free_index.append(free_index)
|
|
1456
|
+
families.append(
|
|
1457
|
+
FamilyBlock(
|
|
1458
|
+
columns=jnp.asarray(cols, dtype=jnp.int32),
|
|
1459
|
+
fixed_values=jnp.asarray(fixed, dtype=jnp.float64),
|
|
1460
|
+
free_index=jnp.asarray(free_index),
|
|
1461
|
+
local_index=jnp.asarray(local_index),
|
|
1462
|
+
slot_free_index=jnp.asarray(slot_free),
|
|
1463
|
+
slot_lower=jnp.asarray(slot_lo, dtype=jnp.float64),
|
|
1464
|
+
slot_upper=jnp.asarray(slot_hi, dtype=jnp.float64),
|
|
1465
|
+
kernel=k,
|
|
1466
|
+
)
|
|
1467
|
+
)
|
|
1468
|
+
|
|
1469
|
+
nodes = jnp.asarray(quad.grid(model.n_factors), dtype=jnp.float64)
|
|
1470
|
+
resolved = model.resolved_groups()
|
|
1471
|
+
if model.is_empirical_histogram and quad.kind != "equispaced":
|
|
1472
|
+
raise SpecificationError(
|
|
1473
|
+
"EmpiricalHistogram needs an equispaced quadrature grid (its weights are histogram "
|
|
1474
|
+
"bins); Gauss-Hermite quadrature is for Normal latent distributions."
|
|
1475
|
+
)
|
|
1476
|
+
if model.is_davidian and quad.kind != "equispaced":
|
|
1477
|
+
raise SpecificationError(
|
|
1478
|
+
"DavidianCurve is validated on equispaced quadrature grids only; Gauss-Hermite "
|
|
1479
|
+
"quadrature is for Normal latent distributions."
|
|
1480
|
+
)
|
|
1481
|
+
if model.is_empirical_histogram:
|
|
1482
|
+
min_w_list: list[float] = []
|
|
1483
|
+
for g_name, dist in resolved:
|
|
1484
|
+
assert isinstance(dist, EmpiricalHistogram)
|
|
1485
|
+
mw = float(dist.min_weight)
|
|
1486
|
+
if mw * quad.n_points >= 1.0:
|
|
1487
|
+
raise SpecificationError(
|
|
1488
|
+
f"EmpiricalHistogram min_weight ({mw}) for group {g_name!r} must satisfy "
|
|
1489
|
+
f"min_weight * n_points < 1 (n_points={quad.n_points})."
|
|
1490
|
+
)
|
|
1491
|
+
min_w_list.append(mw)
|
|
1492
|
+
min_w_arr = jnp.asarray(min_w_list, dtype=jnp.float64)
|
|
1493
|
+
if eh_weights is not None:
|
|
1494
|
+
w_arr = np.asarray(eh_weights, dtype=np.float64)
|
|
1495
|
+
if w_arr.shape != (n_groups, quad.n_points):
|
|
1496
|
+
raise SpecificationError(
|
|
1497
|
+
f"eh_weights must have shape ({n_groups}, {quad.n_points}), got {w_arr.shape}."
|
|
1498
|
+
)
|
|
1499
|
+
eh_w = jnp.asarray(w_arr, dtype=jnp.float64)
|
|
1500
|
+
else:
|
|
1501
|
+
base = jnp.exp(-0.5 * nodes[:, 0] ** 2)
|
|
1502
|
+
eh_w = jnp.stack([eh_project_floor(base, min_w_arr[g]) for g in range(n_groups)])
|
|
1503
|
+
std_mean, std_var = eh_standardization_flags(table, model)
|
|
1504
|
+
if std_var and not std_mean:
|
|
1505
|
+
raise IdentificationError(
|
|
1506
|
+
"EmpiricalHistogram with fixed intercepts but no fixed nonzero slope in the "
|
|
1507
|
+
"reference group's linked items is not supported: the variance-only constraint is "
|
|
1508
|
+
"not linear in the weights (DESIGN.md §15.34). Fix at least one slope as well, or "
|
|
1509
|
+
"use a Normal latent distribution."
|
|
1510
|
+
)
|
|
1511
|
+
latent = LatentBlock(
|
|
1512
|
+
fixed_values=jnp.zeros((n_groups, 2), dtype=jnp.float64),
|
|
1513
|
+
free_index=jnp.full((n_groups, 2), -1, dtype=jnp.int32),
|
|
1514
|
+
lower=jnp.full((n_groups, 2), -jnp.inf, dtype=jnp.float64),
|
|
1515
|
+
upper=jnp.full((n_groups, 2), jnp.inf, dtype=jnp.float64),
|
|
1516
|
+
eh_weights=eh_w,
|
|
1517
|
+
eh_min_weight=min_w_arr,
|
|
1518
|
+
is_eh=True,
|
|
1519
|
+
standardize_mean=std_mean,
|
|
1520
|
+
standardize_var=std_var,
|
|
1521
|
+
davidian_degree=0,
|
|
1522
|
+
)
|
|
1523
|
+
elif model.is_mixture:
|
|
1524
|
+
n_comp = model.mixture_components
|
|
1525
|
+
lat_params = mixture_param_names(n_comp)
|
|
1526
|
+
lat_vals = np.array(
|
|
1527
|
+
[[lookup[(g, LATENT_ITEM, p)][:4] for p in lat_params] for g in groups], dtype=float
|
|
1528
|
+
)
|
|
1529
|
+
latent = LatentBlock(
|
|
1530
|
+
fixed_values=jnp.asarray(lat_vals[:, :, 0], dtype=jnp.float64),
|
|
1531
|
+
free_index=jnp.asarray(lat_vals[:, :, 1].astype(np.int32)),
|
|
1532
|
+
lower=jnp.asarray(lat_vals[:, :, 2], dtype=jnp.float64),
|
|
1533
|
+
upper=jnp.asarray(lat_vals[:, :, 3], dtype=jnp.float64),
|
|
1534
|
+
eh_weights=jnp.ones((n_groups, 1), dtype=jnp.float64),
|
|
1535
|
+
eh_min_weight=jnp.zeros((n_groups,), dtype=jnp.float64),
|
|
1536
|
+
is_eh=False,
|
|
1537
|
+
standardize_mean=False,
|
|
1538
|
+
standardize_var=False,
|
|
1539
|
+
davidian_degree=0,
|
|
1540
|
+
mixture_components=n_comp,
|
|
1541
|
+
)
|
|
1542
|
+
elif model.is_davidian:
|
|
1543
|
+
degree = model.davidian_degree
|
|
1544
|
+
lat_params = davidian_param_names(degree)
|
|
1545
|
+
lat_vals = np.array(
|
|
1546
|
+
[[lookup[(g, LATENT_ITEM, p)][:4] for p in lat_params] for g in groups], dtype=float
|
|
1547
|
+
)
|
|
1548
|
+
latent = LatentBlock(
|
|
1549
|
+
fixed_values=jnp.asarray(lat_vals[:, :, 0], dtype=jnp.float64),
|
|
1550
|
+
free_index=jnp.asarray(lat_vals[:, :, 1].astype(np.int32)),
|
|
1551
|
+
lower=jnp.asarray(lat_vals[:, :, 2], dtype=jnp.float64),
|
|
1552
|
+
upper=jnp.asarray(lat_vals[:, :, 3], dtype=jnp.float64),
|
|
1553
|
+
eh_weights=jnp.ones((n_groups, 1), dtype=jnp.float64),
|
|
1554
|
+
eh_min_weight=jnp.zeros((n_groups,), dtype=jnp.float64),
|
|
1555
|
+
is_eh=False,
|
|
1556
|
+
standardize_mean=False,
|
|
1557
|
+
standardize_var=False,
|
|
1558
|
+
davidian_degree=degree,
|
|
1559
|
+
)
|
|
1560
|
+
else:
|
|
1561
|
+
lat_params = latent_param_names(model.n_factors)
|
|
1562
|
+
lat_vals = np.array(
|
|
1563
|
+
[[lookup[(g, LATENT_ITEM, p)][:4] for p in lat_params] for g in groups], dtype=float
|
|
1564
|
+
)
|
|
1565
|
+
latent = LatentBlock(
|
|
1566
|
+
fixed_values=jnp.asarray(lat_vals[:, :, 0], dtype=jnp.float64),
|
|
1567
|
+
free_index=jnp.asarray(lat_vals[:, :, 1].astype(np.int32)),
|
|
1568
|
+
lower=jnp.asarray(lat_vals[:, :, 2], dtype=jnp.float64),
|
|
1569
|
+
upper=jnp.asarray(lat_vals[:, :, 3], dtype=jnp.float64),
|
|
1570
|
+
eh_weights=jnp.ones((n_groups, 1), dtype=jnp.float64),
|
|
1571
|
+
eh_min_weight=jnp.zeros((n_groups,), dtype=jnp.float64),
|
|
1572
|
+
is_eh=False,
|
|
1573
|
+
standardize_mean=False,
|
|
1574
|
+
standardize_var=False,
|
|
1575
|
+
davidian_degree=0,
|
|
1576
|
+
)
|
|
1577
|
+
priors_block = PriorBlock(
|
|
1578
|
+
kind=jnp.asarray(prior_kind, dtype=jnp.int32),
|
|
1579
|
+
param1=jnp.asarray(prior_p1, dtype=jnp.float64),
|
|
1580
|
+
param2=jnp.asarray(prior_p2, dtype=jnp.float64),
|
|
1581
|
+
)
|
|
1582
|
+
problem = CompiledProblem(
|
|
1583
|
+
y=jnp.asarray(patterns, dtype=jnp.int32),
|
|
1584
|
+
counts=jnp.asarray(counts, dtype=jnp.float64),
|
|
1585
|
+
group=jnp.asarray(pat_groups, dtype=jnp.int32),
|
|
1586
|
+
nodes=nodes,
|
|
1587
|
+
node_log_base=jnp.asarray(quad.base_log_weights(model.n_factors), dtype=jnp.float64),
|
|
1588
|
+
families=tuple(families),
|
|
1589
|
+
latent=latent,
|
|
1590
|
+
priors=priors_block,
|
|
1591
|
+
n_groups=n_groups,
|
|
1592
|
+
coupled=_coupled_blocks(family_free_index, slot_bounds),
|
|
1593
|
+
)
|
|
1594
|
+
return Compiled(problem=problem, eta0=eta0, inverse=inverse, n_patterns=n_patterns)
|