"""Source-defined inference and missingness rules for joint responses.""" from __future__ import annotations import copy from itertools import product from typing import Any import numpy as np from scipy import stats def regression_with_inference(module: Any, effect: dict[str, Any], arrays: dict[str, np.ndarray]) -> dict[str, float]: spec = effect["statistic_spec"] by_condition = module.condition_cells(effect) outcome_mapping = module.resolve_outcome_mapping(effect) predictor_mappings = { row["column"]: row for row in effect["identifiability"].get("predictor_mappings") or [] } outcomes, predictors = [], {name: [] for name in spec["predictors"]} for condition_id, cells in by_condition.items(): prototype = next(iter(cells.values())) outcome = module.affine_array(cells, arrays, outcome_mapping) outcomes.append(outcome) for name in spec["predictors"]: descriptor = predictor_mappings.get(name) or {} mapping = descriptor.get("mapping") or {} if mapping.get("type") in {"affine_items", "single_item_lookup"}: value = module.affine_array(cells, arrays, mapping) elif name in (spec.get("derived_condition_columns") or {}): value = np.full(len(outcome), float(spec["derived_condition_columns"][name][condition_id])) else: constant = mapping.get("values", {}).get(condition_id, prototype["condition_covariates"].get(name)) value = np.full(len(outcome), float(constant)) predictors[name].append(value) y = np.concatenate(outcomes) x = {name: np.concatenate(parts) for name, parts in predictors.items()} spss_beta = spec.get("standardization") == "spss_beta" if spec.get("standardized") and not spss_beta: y = (y - np.mean(y)) / max(float(np.std(y, ddof=1)), 1e-12) x = { name: (values - np.mean(values)) / max(float(np.std(values, ddof=1)), 1e-12) for name, values in x.items() } columns, labels = [np.ones(len(y))], [()] for term in spec["formula_terms"]: column = np.ones(len(y)) for name in term: column *= x[name] columns.append(column) labels.append(tuple(term)) design = np.column_stack(columns) coefficient_index = labels.index(tuple(spec["coefficient_term"])) if spec.get("model") == "logit": beta = np.zeros(design.shape[1]) weight = np.ones(len(y)) for _ in range(200): linear = np.clip(design @ beta, -30, 30) probability = 1 / (1 + np.exp(-linear)) weight = np.maximum(probability * (1 - probability), 1e-9) adjusted = linear + (y - probability) / weight updated = np.linalg.pinv(design * np.sqrt(weight)[:, None]) @ (adjusted * np.sqrt(weight)) if np.max(np.abs(updated - beta)) < 1e-10: beta = updated break beta = updated covariance = np.linalg.pinv(design.T @ (weight[:, None] * design)) standard_error = float(np.sqrt(max(covariance[coefficient_index, coefficient_index], 1e-24))) test_statistic = float(beta[coefficient_index] / standard_error) p_value = float(2 * stats.norm.sf(abs(test_statistic))) degrees = float("nan") else: beta = np.linalg.pinv(design) @ y residual = y - design @ beta rank = int(np.linalg.matrix_rank(design)) degrees = float(max(len(y) - rank, 1)) residual_variance = float(residual @ residual) / degrees covariance = residual_variance * np.linalg.pinv(design.T @ design) standard_error = float(np.sqrt(max(covariance[coefficient_index, coefficient_index], 1e-24))) test_statistic = float(beta[coefficient_index] / standard_error) p_value = float(2 * stats.t.sf(abs(test_statistic), degrees)) coefficient = float(beta[coefficient_index]) if spss_beta: beta_scale = float(np.std(design[:, coefficient_index], ddof=1)) / max( float(np.std(y, ddof=1)), 1e-12 ) coefficient *= beta_scale standard_error *= beta_scale output = { "effect": coefficient, "contrast": coefficient, "n_observations": float(len(y)), "design_rank": float(np.linalg.matrix_rank(design)), "coefficient_standard_error": standard_error, "test_statistic": test_statistic, "p_value": p_value, } if np.isfinite(degrees): output["df_residual"] = degrees return output def install_inference_wrappers(module: Any) -> None: """Attach a data-derived p-value and sample-size audit to every effect family.""" original_cohen_d = module.cohen_d original_generic_anova = module.generic_anova original_mixed_two_level = module.mixed_two_level original_chi_square = module.chi_square original_affine_array = module.affine_array original_condition_rows = module.condition_rows original_reconstruct_population_cells = module.reconstruct_population_cells def reconstruct_population_cells( prompts: list[dict[str, Any]], populations: list[dict[str, Any]] ) -> tuple[dict[str, np.ndarray], dict[str, Any]]: arrays, audit = original_reconstruct_population_cells(prompts, populations) population_by_key = {str(row["condition_key"]): row for row in populations} missing_by_cell: dict[str, list[set[str]]] = {} for prompt in prompts: key = str(prompt["condition_key"]) population = population_by_key[key] respondents = population.get("respondents") or [] counts = [int(value) for value in (population.get("source_row_counts") or [1] * len(respondents))] provenance = population.get("respondent_provenance") or [{} for _ in respondents] if len(provenance) != len(respondents): raise ValueError(f"{key}: respondent provenance length mismatch") expanded = [] for row_provenance, count in zip(provenance, counts): # Source-workbook missingness is evidence about the archived # model response only. Once a synthetic population declares # its own analysis missingness, that declaration is # authoritative and the filled final answers remain available # for SFT while handbook complete-case scoring excludes only # the explicitly named canonical prediction IDs. missing = set() if not row_provenance.get("analysis_missingness_authoritative"): missing.update(str(value) for value in row_provenance.get("released_missing_columns") or []) missing.update(str(value) for value in row_provenance.get("analysis_missing_prediction_ids") or []) expanded.extend([missing] * count) for question in prompt["questions"]: missing_by_cell[str(question["cell_id"])] = expanded module._contract_missing_columns_by_cell = missing_by_cell return arrays, audit def condition_rows(effect: dict[str, Any], arrays: dict[str, np.ndarray]) -> list[dict[str, Any]]: """Apply canonical outcome-level complete-case masks to condition rows.""" rows = original_condition_rows(effect, arrays) missing_by_cell = getattr(module, "_contract_missing_columns_by_cell", {}) if not missing_by_cell: return rows spec = effect["statistic_spec"] cells_by_condition = module.condition_cells(effect) mapping = None if spec.get("long_outcomes") else module.resolve_outcome_mapping(effect) long_by_level = { str(row["level"]): [str(value) for value in row["outcome_columns"]] for row in spec.get("long_outcomes") or [] } output = [] for row in rows: condition = str(row["condition_id"]) cells = cells_by_condition[condition] if spec.get("long_outcomes"): level = str(row["covariates"][spec["long_factor"]]) prediction_ids = long_by_level[level] elif mapping.get("type") in {"single_item_lookup", "conditional_single_item_lookup"}: prediction_ids = [str(mapping["item"])] elif mapping.get("type") == "rowwise_mean_available_items": prediction_ids = [str(value) for value in mapping["source_columns"]] elif mapping.get("type") == "conditional_affine_items": matches = [ rule for rule in mapping.get("rules") or [] if all(module.matches(row["covariates"].get(name), value) for name, value in (rule.get("when") or {}).items()) ] if len(matches) != 1: raise ValueError(f"{effect['effect_key']}: conditional missingness mapping is ambiguous") prediction_ids = [str(value) for value in matches[0].get("terms") or {}] else: prediction_ids = [str(value) for value in mapping.get("terms") or {}] if not prediction_ids: output.append(row) continue first = cells[prediction_ids[0]]["cell_id"] missing = missing_by_cell.get(str(first)) or [set() for _ in range(len(row["values"]))] if len(missing) != len(row["values"]): raise ValueError(f"{effect['effect_key']}:{condition}: missingness length mismatch") keep = np.asarray([ not any(prediction_id in omitted for prediction_id in prediction_ids) for omitted in missing ], dtype=bool) values = np.asarray(row["values"], dtype=float)[keep] if not len(values): raise ValueError(f"{effect['effect_key']}:{condition}: complete-case mask removed every row") output.append({**row, "values": values}) return output def apply_respondent_exclusions( effect: dict[str, Any], rows: list[dict[str, Any]] ) -> list[dict[str, Any]]: """Apply audited released-analysis row exclusions without mutating source data.""" requested = effect["statistic_spec"].get("exclude_respondent_indices_by_condition") or {} if not requested or all(row.get("_contract_exclusions_applied") for row in rows): return rows output = [] for row in rows: values = np.asarray(row["values"], dtype=float) indices = requested.get(str(row["condition_id"]), []) normalized = sorted({int(index) for index in indices}) if normalized and (normalized[0] < 0 or normalized[-1] >= len(values)): raise ValueError( f"{effect['effect_key']}: respondent exclusion outside condition " f"{row['condition_id']} length {len(values)}: {normalized}" ) if normalized: keep = np.ones(len(values), dtype=bool) keep[normalized] = False values = values[keep] if not len(values): raise ValueError( f"{effect['effect_key']}: respondent exclusions emptied condition {row['condition_id']}" ) output.append({**row, "values": values, "_contract_exclusions_applied": True}) return output def affine_array( cells: dict[str, dict[str, Any]], arrays: dict[str, np.ndarray], mapping: dict[str, Any] ) -> np.ndarray: if mapping.get("type") == "rowwise_mean_available_items": numerator = None denominator = None missing_by_cell = getattr(module, "_contract_missing_columns_by_cell", {}) for prediction_id, source_column in mapping["source_columns"].items(): cell_id = str(cells[prediction_id]["cell_id"]) values = np.asarray(arrays[cell_id], dtype=float) missing = missing_by_cell.get(cell_id) or [set() for _ in range(len(values))] if len(missing) != len(values): raise ValueError(f"{cell_id}: missingness metadata length mismatch") present = np.asarray([str(source_column) not in row for row in missing], dtype=float) numerator = values * present if numerator is None else numerator + values * present denominator = present if denominator is None else denominator + present if numerator is None or denominator is None or bool((denominator <= 0).any()): raise ValueError("Rowwise available-item mean has an empty row") return numerator / denominator if mapping.get("type") == "conditional_single_item_lookup": prototype = next(iter(cells.values())) covariates = prototype.get("condition_covariates") or {} matches = [ rule for rule in mapping.get("rules") or [] if all(str(covariates.get(name)) == str(value) for name, value in rule.get("when", {}).items()) ] if len(matches) != 1: raise ValueError( f"Conditional lookup matched {len(matches)} rules for covariates {covariates}" ) return original_affine_array( cells, arrays, { "type": "single_item_lookup", "item": str(mapping["item"]), "values": matches[0]["values"], }, ) if mapping.get("type") != "conditional_affine_items": return original_affine_array(cells, arrays, mapping) prototype = next(iter(cells.values())) covariates = prototype.get("condition_covariates") or {} matches = [ rule for rule in mapping.get("rules") or [] if all(str(covariates.get(name)) == str(value) for name, value in rule.get("when", {}).items()) ] if len(matches) != 1: raise ValueError( f"Conditional outcome mapping matched {len(matches)} rules for covariates {covariates}" ) rule = matches[0] return original_affine_array( cells, arrays, { "type": "affine_items", "intercept": float(rule.get("intercept", 0.0)), "terms": rule["terms"], }, ) def cohen_d(effect: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, float]: rows = apply_respondent_exclusions(effect, rows) spec = effect["statistic_spec"] effect_rows = rows if spec.get("effect_subset"): effect_rows = [ row for row in rows if all( module.matches(row["covariates"].get(name), value) for name, value in spec["effect_subset"].items() ) ] if not effect_rows: raise ValueError(f"Effect subset selected no rows: {spec['effect_subset']}") output = original_cohen_d(effect, effect_rows) if spec.get("direction_multiplier") is not None: output["contrast"] *= float(spec["direction_multiplier"]) mean1, variance1, n1 = output["mean1"], output["variance1"], output["n1"] mean2, variance2, n2 = output["mean2"], output["variance2"], output["n2"] p_method = str(spec.get("p_value_method") or "") if p_method == "full_factorial_simple": residual_ss = sum( float(np.sum((row["values"] - np.mean(row["values"])) ** 2)) for row in rows ) residual_df = max(sum(len(row["values"]) - 1 for row in rows), 1) residual_variance = residual_ss / residual_df standard_error = np.sqrt(max(residual_variance * (1.0 / n1 + 1.0 / n2), 1e-24)) degrees = float(residual_df) n_observations = float(sum(len(row["values"]) for row in rows)) test_statistic = abs(output["contrast"]) / standard_error p_value = float(2 * stats.t.sf(test_statistic, degrees)) elif p_method == "factorial_anova": inference_effect = copy.deepcopy(effect) inference_effect["indicator"] = "f" inference_effect["statistic_spec"] = { **copy.deepcopy(spec), "model_factors": list(spec["p_value_model_factors"]), "term_factors": list(spec["p_value_term_factors"]), "formula_terms": [list(term) for term in spec["p_value_formula_terms"]], "ss_type": int(spec.get("p_value_ss_type", 3)), } inference = generic_anova(inference_effect, rows) standard_error = float("nan") degrees = inference["df_residual"] n_observations = inference["n_observations"] test_statistic = inference["test_statistic"] p_value = inference["p_value"] elif p_method == "emmeans_holm": terms = [list(term) for term in spec["posthoc_formula_terms"]] factor = str(spec.get("posthoc_factor") or spec["factor"]) factors = list(dict.fromkeys(name for term in terms for name in term)) levels_by_factor = { name: sorted({row["covariates"][name] for row in rows}, key=str) for name in factors } design, _ = module.design_matrix(rows, terms) means = np.asarray([np.mean(row["values"]) for row in rows], dtype=float) ns = np.asarray([len(row["values"]) for row in rows], dtype=float) variances = np.asarray([ np.var(row["values"], ddof=1) if len(row["values"]) > 1 else 0.0 for row in rows ]) sqrt_n = np.sqrt(ns) beta = np.linalg.pinv(design * sqrt_n[:, None]) @ (means * sqrt_n) residual = means - design @ beta residual_sse = float(np.sum((ns - 1) * variances + ns * residual**2)) rank = int(np.linalg.matrix_rank(design)) degrees = max(int(ns.sum()) - rank, 1) residual_variance = residual_sse / degrees covariance = residual_variance * np.linalg.pinv(design.T @ (ns[:, None] * design)) def design_vector(covariates: dict[str, Any]) -> np.ndarray: columns = [1.0] coded = {} for name in factors: levels = levels_by_factor[name] reference = levels[-1] coded[name] = [ 1.0 if module.matches(covariates[name], level) else -1.0 if module.matches(covariates[name], reference) else 0.0 for level in levels[:-1] ] for term in terms: for combination in product(*(coded[name] for name in term)): columns.append(float(np.prod(combination))) return np.asarray(columns, dtype=float) other_factors = [name for name in factors if name != factor] marginal_vectors = {} for level in levels_by_factor[factor]: combinations = product(*(levels_by_factor[name] for name in other_factors)) vectors = [] for values in combinations: covariates = {factor: level, **dict(zip(other_factors, values))} vectors.append(design_vector(covariates)) marginal_vectors[level] = np.mean(np.vstack(vectors), axis=0) raw_pairs = [] factor_levels = levels_by_factor[factor] for left_index, left in enumerate(factor_levels): for right in factor_levels[left_index + 1 :]: contrast_vector = marginal_vectors[left] - marginal_vectors[right] estimate = float(contrast_vector @ beta) standard_error = float(np.sqrt(max(contrast_vector @ covariance @ contrast_vector, 1e-24))) statistic = abs(estimate) / standard_error raw_p = float(2 * stats.t.sf(statistic, degrees)) raw_pairs.append({"left": left, "right": right, "statistic": statistic, "p": raw_p}) ordered = sorted(range(len(raw_pairs)), key=lambda index: raw_pairs[index]["p"]) running = 0.0 adjusted = [0.0] * len(raw_pairs) total_pairs = len(raw_pairs) for rank_index, pair_index in enumerate(ordered): running = max(running, (total_pairs - rank_index) * raw_pairs[pair_index]["p"]) adjusted[pair_index] = min(running, 1.0) selected = [ (pair, adjusted[index]) for index, pair in enumerate(raw_pairs) if {str(pair["left"]), str(pair["right"])} == {str(spec["level1"]), str(spec["level2"])} ] if len(selected) != 1: raise ValueError(f"Holm contrast not found for {factor}={spec['level1']!r} vs {spec['level2']!r}") pair, p_value = selected[0] test_statistic = pair["statistic"] n_observations = float(ns.sum()) elif p_method == "tukey_hsd": factor = str(spec["factor"]) grouped = { level: np.concatenate([row["values"] for row in rows if module.matches(row["covariates"].get(factor), level)]) for level in sorted({row["covariates"].get(factor) for row in rows}, key=str) } grouped = {level: values for level, values in grouped.items() if len(values)} if len(grouped) < 3: raise ValueError(f"Tukey HSD requires at least three groups; found {sorted(grouped, key=str)}") n_observations = float(sum(len(values) for values in grouped.values())) degrees = float(n_observations - len(grouped)) residual_ss = sum(float(np.sum((values - np.mean(values)) ** 2)) for values in grouped.values()) residual_variance = residual_ss / max(degrees, 1.0) standard_error = np.sqrt(max(residual_variance / 2.0 * (1.0 / n1 + 1.0 / n2), 1e-24)) test_statistic = abs(output["contrast"]) / standard_error p_value = float(stats.studentized_range.sf(test_statistic, len(grouped), degrees)) elif p_method == "anova_bonferroni": factor = str(spec["factor"]) grouped = { level: np.concatenate([ row["values"] for row in effect_rows if module.matches(row["covariates"].get(factor), level) ]) for level in sorted({row["covariates"].get(factor) for row in effect_rows}, key=str) } grouped = {level: values for level, values in grouped.items() if len(values)} if len(grouped) < 3: raise ValueError(f"Bonferroni post-hoc requires at least three groups; found {sorted(grouped, key=str)}") n_observations = float(sum(len(values) for values in grouped.values())) degrees = float(n_observations - len(grouped)) residual_ss = sum(float(np.sum((values - np.mean(values)) ** 2)) for values in grouped.values()) residual_variance = residual_ss / max(degrees, 1.0) standard_error = np.sqrt(max(residual_variance * (1.0 / n1 + 1.0 / n2), 1e-24)) test_statistic = abs(output["contrast"]) / standard_error raw_p = float(2 * stats.t.sf(test_statistic, degrees)) comparisons = int(spec.get("posthoc_comparisons") or (len(grouped) * (len(grouped) - 1) // 2)) p_value = min(raw_p * comparisons, 1.0) elif p_method == "oneway_lsd": # Planned pairwise contrast using the common residual variance of # the one-way ANOVA (Fisher's LSD, with no multiplicity # adjustment). This is distinct from both a pair-only t test and # Tukey HSD: all groups contribute to MSE and residual df. factor = str(spec["factor"]) grouped = { level: np.concatenate([ row["values"] for row in effect_rows if module.matches(row["covariates"].get(factor), level) ]) for level in sorted({row["covariates"].get(factor) for row in effect_rows}, key=str) } grouped = {level: values for level, values in grouped.items() if len(values)} if len(grouped) < 3: raise ValueError(f"One-way LSD requires at least three groups; found {sorted(grouped, key=str)}") n_observations = float(sum(len(values) for values in grouped.values())) degrees = float(n_observations - len(grouped)) residual_ss = sum(float(np.sum((values - np.mean(values)) ** 2)) for values in grouped.values()) residual_variance = residual_ss / max(degrees, 1.0) standard_error = np.sqrt(max(residual_variance * (1.0 / n1 + 1.0 / n2), 1e-24)) test_statistic = abs(output["contrast"]) / standard_error p_value = float(2 * stats.t.sf(test_statistic, degrees)) elif spec.get("one_sample_mu") is not None: standard_error = np.sqrt(max(variance1 / n1, 1e-24)) degrees = max(n1 - 1, 1) n_observations = n1 elif p_method == "levene_adaptive": levels = spec.get("direction_levels") or {} factor = str(levels.get("factor") or spec["factor"]) level1 = levels.get("level1", spec.get("level1")) level2 = levels.get("level2", spec.get("level2")) group1 = np.concatenate([ row["values"] for row in effect_rows if module.matches(row["covariates"].get(factor), level1) ]) group2 = np.concatenate([ row["values"] for row in effect_rows if module.matches(row["covariates"].get(factor), level2) ]) center = str(spec.get("levene_center") or "median") if center not in {"mean", "median", "trimmed"}: raise ValueError(f"Unsupported Levene center {center!r}") if float(np.var(np.concatenate([group1, group2]))) <= 1e-24: levene_p = 1.0 else: levene_p = float(stats.levene(group1, group2, center=center).pvalue) if not np.isfinite(levene_p): raise ValueError(f"Levene test returned a non-finite p-value for {effect['effect_key']}") use_pooled = levene_p > float(spec.get("levene_alpha", 0.05)) if use_pooled: pooled = ((n1 - 1) * variance1 + (n2 - 1) * variance2) / max(n1 + n2 - 2, 1) standard_error = np.sqrt(max(pooled * (1 / n1 + 1 / n2), 1e-24)) degrees = max(n1 + n2 - 2, 1) inference_test = "pooled" else: standard_error_sq = variance1 / n1 + variance2 / n2 denominator = (variance1 / n1) ** 2 / max(n1 - 1, 1) + (variance2 / n2) ** 2 / max(n2 - 1, 1) standard_error = np.sqrt(max(standard_error_sq, 1e-24)) degrees = standard_error_sq**2 / denominator if denominator > 0 else n1 + n2 - 2 inference_test = "welch" n_observations = n1 + n2 output.update( variance_test_p=levene_p, variance_test_center=center, inference_test=inference_test, ) elif p_method == "welch_t" or spec.get("test") == "welch": standard_error_sq = variance1 / n1 + variance2 / n2 denominator = (variance1 / n1) ** 2 / max(n1 - 1, 1) + (variance2 / n2) ** 2 / max(n2 - 1, 1) standard_error = np.sqrt(max(standard_error_sq, 1e-24)) degrees = standard_error_sq**2 / denominator if denominator > 0 else n1 + n2 - 2 n_observations = n1 + n2 else: pooled = ((n1 - 1) * variance1 + (n2 - 1) * variance2) / max(n1 + n2 - 2, 1) standard_error = np.sqrt(max(pooled * (1 / n1 + 1 / n2), 1e-24)) degrees = max(n1 + n2 - 2, 1) n_observations = n1 + n2 if p_method not in { "full_factorial_simple", "factorial_anova", "tukey_hsd", "emmeans_holm", "anova_bonferroni", "oneway_lsd" }: test_statistic = abs(output["contrast"]) / standard_error p_value = float(2 * stats.t.sf(test_statistic, degrees)) output.update( n_observations=float(n_observations), df_residual=float(degrees), test_statistic=float(test_statistic), p_value=p_value, p_value_method=p_method, ) return output def add_anova_inference( output: dict[str, float], effect: dict[str, Any], n_observations: float ) -> dict[str, float]: df_term, df_residual = output["df_term"], output["df_residual"] if effect["indicator"] == "eta-square": eta = output["effect"] statistic = eta / max(1 - eta, 1e-24) * df_residual / df_term else: statistic = output["effect"] output.update( n_observations=float(n_observations), test_statistic=float(statistic), p_value=float(stats.f.sf(statistic, df_term, df_residual)), ) return output def generic_anova(effect: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, float]: rows = apply_respondent_exclusions(effect, rows) spec = effect["statistic_spec"] if int(spec.get("ss_type", 3)) == 1: terms = [list(term) for term in spec["formula_terms"]] tested = tuple(spec["term_factors"]) means = np.asarray([np.mean(row["values"]) for row in rows], dtype=float) ns = np.asarray([len(row["values"]) for row in rows], dtype=float) variances = np.asarray([ np.var(row["values"], ddof=1) if len(row["values"]) > 1 else 0.0 for row in rows ]) within_sse = float(np.sum((ns - 1) * variances)) def fit_sse(selected_terms: list[list[str]]) -> tuple[float, int]: design, _ = module.design_matrix(rows, selected_terms) sqrt_n = np.sqrt(ns) beta = np.linalg.pinv(design * sqrt_n[:, None]) @ (means * sqrt_n) residual = means - design @ beta return within_sse + float(np.sum(ns * residual**2)), int(np.linalg.matrix_rank(design)) previous_sse, previous_rank = fit_sse([]) ss_term = None df_term = None for index, term in enumerate(terms): current_sse, current_rank = fit_sse(terms[: index + 1]) if tuple(term) == tested: ss_term = max(previous_sse - current_sse, 0.0) df_term = max(current_rank - previous_rank, 1) previous_sse, previous_rank = current_sse, current_rank if ss_term is None or df_term is None: raise ValueError(f"Tested Type-I term {tested!r} is absent") residual_sse = previous_sse df_residual = max(int(ns.sum()) - previous_rank, 1) if effect["indicator"] == "eta-square": magnitude = ss_term / max(ss_term + residual_sse, 1e-12) else: magnitude = (ss_term / df_term) / max(residual_sse / df_residual, 1e-12) output = { "effect": float(magnitude), "df_term": float(df_term), "df_residual": float(df_residual), "ss_type": 1.0, } else: output = original_generic_anova(effect, rows) return add_anova_inference(output, effect, sum(len(row["values"]) for row in rows)) def repeated_long_anova(effect: dict[str, Any], rows: list[dict[str, Any]]) -> dict[str, float]: rows = apply_respondent_exclusions(effect, rows) spec = effect["statistic_spec"] if spec.get("repeated_measures_factor"): within = str(spec["repeated_measures_factor"]) between = str(spec["repeated_measures_between_factor"]) levels = sorted({row["covariates"][within] for row in rows}, key=str) condition_ids = sorted({str(row["condition_id"]) for row in rows}) matrices = [] groups = [] indexed = { (str(row["condition_id"]), row["covariates"][within]): np.asarray(row["values"], dtype=float) for row in rows } covariates = {str(row["condition_id"]): row["covariates"] for row in rows} for condition_id in condition_ids: parts = [indexed[(condition_id, level)] for level in levels] if len({len(part) for part in parts}) != 1: raise ValueError(f"Repeated outcomes have unequal n in {condition_id}") matrices.append(np.column_stack(parts)) groups.extend([covariates[condition_id][between]] * len(parts[0])) values = np.vstack(matrices) group = np.asarray(groups, dtype=object) n_subjects, n_levels = values.shape grand_mean = float(np.mean(values)) outcome_means = np.mean(values, axis=0) ss_outcome = float(n_subjects * np.sum((outcome_means - grand_mean) ** 2)) ss_interaction = 0.0 for group_level in sorted(set(groups), key=str): group_values = values[group == group_level] group_mean = float(np.mean(group_values)) group_outcome_means = np.mean(group_values, axis=0) ss_interaction += float( len(group_values) * np.sum((group_outcome_means - group_mean - outcome_means + grand_mean) ** 2) ) subject_means = np.mean(values, axis=1) ss_within = float(np.sum((values - subject_means[:, None]) ** 2)) ss_error = max(ss_within - ss_outcome - ss_interaction, 0.0) effect_kind = str(spec.get("repeated_measures_effect", "within")) if effect_kind == "within": ss_term = ss_outcome df_term = max(n_levels - 1, 1) elif effect_kind == "interaction": ss_term = ss_interaction df_term = max((len(set(groups)) - 1) * (n_levels - 1), 1) else: raise ValueError( f"{effect['effect_key']}: unsupported repeated-measures effect {effect_kind!r}" ) df_residual = max((n_subjects - len(set(groups))) * (n_levels - 1), 1) eta = ss_term / max(ss_term + ss_error, 1e-12) statistic = (ss_term / df_term) / max(ss_error / df_residual, 1e-12) corrected_df_term = float(df_term) corrected_df_residual = float(df_residual) epsilon = 1.0 correction = str(spec.get("p_value_correction") or "none") if correction == "greenhouse_geisser": residualized = values.copy() for group_level in sorted(set(groups), key=str): mask = group == group_level residualized[mask] -= np.mean(values[mask], axis=0) covariance = np.cov(residualized, rowvar=False, ddof=1) centering = np.eye(n_levels) - np.ones((n_levels, n_levels)) / n_levels projected = centering @ covariance @ centering trace = float(np.trace(projected)) denominator = float((n_levels - 1) * np.trace(projected @ projected)) if denominator > 1e-24: epsilon = trace**2 / denominator epsilon = min(1.0, max(1.0 / max(n_levels - 1, 1), epsilon)) corrected_df_term *= epsilon corrected_df_residual *= epsilon elif correction != "none": raise ValueError(f"Unsupported repeated-measures correction {correction!r}") return { "effect": eta, "contrast": 0.0, "df_term": corrected_df_term, "df_residual": corrected_df_residual, "uncorrected_df_term": float(df_term), "uncorrected_df_residual": float(df_residual), "greenhouse_geisser_epsilon": float(epsilon), "p_value_correction": correction, "n_observations": float(n_subjects), "test_statistic": float(statistic), "p_value": float(stats.f.sf(statistic, corrected_df_term, corrected_df_residual)), } # The only released long-outcome contract is AMJ_3_3. Its SPSS source # runs ``UNIANOVA ... BY race`` on the stacked race rows (and repeats # that analysis after splitting by task condition); it is not a paired # difference test despite repeated ID labels in the workbook. output = original_generic_anova(effect, rows) output.update(module.direction_statistics(effect, rows)) return add_anova_inference(output, effect, sum(len(row["values"]) for row in rows)) def mixed_two_level(effect: dict[str, Any], arrays: dict[str, np.ndarray]) -> dict[str, float]: output = original_mixed_two_level(effect, arrays) spec = effect["statistic_spec"] mixed = spec["mixed_two_level"] by_condition = module.condition_cells(effect) if mixed.get("effect") == "between" and spec.get("between_moments") == "stacked_long": factor = mixed["condition_factor"] levels = mixed.get("direction_levels") or {} observed = [] for condition_id, cells in by_condition.items(): prototype = next(iter(cells.values())) value = (spec.get("derived_condition_columns") or {}).get(factor, {}).get( condition_id, prototype["condition_covariates"].get(factor) ) observed.append(value) level1 = levels.get("level1", max(observed)) level2 = levels.get("level2", min(observed)) def stacked(level: Any) -> np.ndarray: parts = [] for condition_id, cells in by_condition.items(): prototype = next(iter(cells.values())) value = (spec.get("derived_condition_columns") or {}).get(factor, {}).get( condition_id, prototype["condition_covariates"].get(factor) ) if module.matches(value, level): parts.extend([arrays[cells[mixed["left"]]["cell_id"]], arrays[cells[mixed["right"]]["cell_id"]]]) return np.concatenate(parts) first = module.sample_statistics(stacked(level1)) second = module.sample_statistics(stacked(level2)) output.update( contrast=first["mean"] - second["mean"], mean1=first["mean"], variance1=first["variance"], sd1=first["sd"], n1=first["n"], mean2=second["mean"], variance2=second["variance"], sd2=second["sd"], n2=second["n"], ) n_observations = sum(len(arrays[next(iter(cells.values()))["cell_id"]]) for cells in by_condition.values()) return add_anova_inference(output, effect, n_observations) def chi_square(effect: dict[str, Any], arrays: dict[str, np.ndarray]) -> dict[str, float]: spec = effect["statistic_spec"] cells = module.selected_cells(effect) # Always resolve canonical overrides here. Reading the embedded legacy # mapping bypasses study-level handbook corrections (for example the # condition-specific coding in JEP_4_2) and made synthesis and audit # disagree even though both imported this wrapper. mapping = module.resolve_outcome_mapping(effect) def mapped_values(cell: dict[str, Any]) -> np.ndarray: if mapping.get("type") != "conditional_single_item_lookup": return module.apply_mapping(arrays[cell["cell_id"]], mapping) covariates = cell.get("condition_covariates") or {} matches = [ rule for rule in mapping.get("rules") or [] if all(str(covariates.get(name)) == str(value) for name, value in rule.get("when", {}).items()) ] if len(matches) != 1: raise ValueError( f"Conditional lookup matched {len(matches)} rules for {cell['cell_id']}: {covariates}" ) return module.apply_mapping( arrays[cell["cell_id"]], {"type": "single_item_lookup", "values": matches[0]["values"]}, ) if mapping.get("type") == "conditional_single_item_lookup" and not spec.get("long_items"): transformed = {str(cell["cell_id"]): mapped_values(cell) for cell in cells} row_keys = sorted( {tuple(module.cell_value(cell, factor) for factor in spec["row_factors"]) for cell in cells}, key=str, ) categories = sorted({float(value) for values in transformed.values() for value in values}) observed = np.zeros((len(row_keys), len(categories)), dtype=float) for cell in cells: row_index = row_keys.index( tuple(module.cell_value(cell, factor) for factor in spec["row_factors"]) ) values = transformed[str(cell["cell_id"])] for category_index, category in enumerate(categories): observed[row_index, category_index] += float(np.sum(values == category)) row_means = observed @ np.asarray(categories) / np.maximum( observed.sum(axis=1), 1e-12 ) levels = spec.get("direction_levels") if levels and len(spec["row_factors"]) == 1: contrast = float( row_means[row_keys.index((levels["level1"],))] - row_means[row_keys.index((levels["level2"],))] ) else: contrast = float(row_means[-1] - row_means[0]) if len(row_means) == 2 else 0.0 expected = ( observed.sum(axis=1, keepdims=True) @ observed.sum(axis=0, keepdims=True) / max(float(observed.sum()), 1e-12) ) effect_value = float(np.sum((observed - expected) ** 2 / np.maximum(expected, 1e-12))) output = {"effect": effect_value, "contrast": contrast} else: output = original_chi_square(effect, arrays) if spec.get("long_items"): df = 1 by_item = {cell["prediction_id"]: cell for cell in cells} n_observations = sum(len(arrays[by_item[item]["cell_id"]]) for item in spec["long_items"]) else: transformed = [mapped_values(cell) for cell in cells] row_keys = { tuple(module.cell_value(cell, factor) for factor in spec["row_factors"]) for cell in cells } categories = {float(value) for values in transformed for value in values} df = int(spec.get("p_dof") or max((len(row_keys) - 1) * (len(categories) - 1), 1)) n_observations = sum(len(values) for values in transformed) if spec.get("yates_correction") and len(row_keys) == 2 and len(categories) == 2: sorted_rows = sorted(row_keys, key=str) sorted_categories = sorted(categories) observed = np.zeros((2, 2), dtype=float) for cell in cells: row_index = sorted_rows.index( tuple(module.cell_value(cell, factor) for factor in spec["row_factors"]) ) values = mapped_values(cell) for category_index, category in enumerate(sorted_categories): observed[row_index, category_index] += float(np.sum(values == category)) expected = ( observed.sum(axis=1, keepdims=True) @ observed.sum(axis=0, keepdims=True) / max(float(observed.sum()), 1e-12) ) adjusted = np.maximum(np.abs(observed - expected) - 0.5, 0.0) output["effect"] = float(np.sum(adjusted**2 / np.maximum(expected, 1e-12))) output.update( n_observations=float(n_observations), df_term=float(df), test_statistic=float(output["effect"]), p_value=float(stats.chi2.sf(output["effect"], df)), ) return output module.affine_array = affine_array module.condition_rows = condition_rows module.reconstruct_population_cells = reconstruct_population_cells module.cohen_d = cohen_d module.generic_anova = generic_anova module.repeated_long_anova = repeated_long_anova module.mixed_two_level = mixed_two_level module.chi_square = chi_square module.regression = lambda effect, arrays: regression_with_inference(module, effect, arrays)