chiron-data / code /population /_definitions.py
henry-yeh's picture htr234234's picture
Chiron data release
1b86964
Raw History Blame Contribute Delete
72.7 kB
"""Build population study definitions from authorized source prompts and human tables. Question parsing and response-scale recovery preserve the published training format. Statistical item mappings are read from source_readout.json; source questionnaire text and human statistics are read from the provider files. """ from __future__ import annotations import copy import csv import json import math import re from dataclasses import dataclass from pathlib import Path from typing import Any, Iterable JSON_BOILERPLATE_RE = re.compile( "(?is)\\n*\\s*(?:your|you) answer\\s+(?:is\\s+)?in the form of json.*$" ) ITEM_RE = re.compile( "(?m)^\\s*(?:[-•\uf06c\uf0d8]\\s*)?\\(?(\\d{1,2})\\)?[.)]\\s*(?!=)" ) BULLET_RE = re.compile("(?m)^\\s*[•\uf06c\uf0d8]\\s*(.+)$") EXPLICIT_VALUE_RE = re.compile("(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s*=") RANGE_PATTERNS = ( re.compile( "(?is)(-?\\d+(?:\\.\\d+)?)\\s*=.{0,160}?(?:to|;|,|and|—|–)\\s*(-?\\d+(?:\\.\\d+)?)\\s*=" ), re.compile( "(?is)(?:scale\\s+)?(?:ranging\\s+|range\\s+)?(?:of\\s+on\\s+|of\\s+|on\\s+)?from\\s+(-?\\d+(?:\\.\\d+)?)\\s*(?:\\([^)]*\\))?\\s*(?:to|through|-)\\s*\\+?(-?\\d+(?:\\.\\d+)?)" ), re.compile( "(?is)(?:scale\\s+)?(?:ranging\\s+|range\\s+)(?:of\\s+on\\s+|of\\s+|on\\s+)?(-?\\d+(?:\\.\\d+)?)\\s*(?:\\([^)]*\\))?\\s*(?:to|through|-)\\s*\\+?(-?\\d+(?:\\.\\d+)?)" ), re.compile( "(?is)(?:on|using|with|of|from)\\s+(?:an?\\s+)?(\\d+)[- ]point\\s+(?:likert\\s+)?scale" ), ) JEP1_BIPOLAR = {"JEP_1_1a", "JEP_1_1b", "JEP_1_3", "JEP_1_6a", "JEP_1_6b"} def clean_source_material(prompts: list[str]) -> str: text = "\n\n".join(prompts).replace("\r", "") text = JSON_BOILERPLATE_RE.sub("", text) text = re.sub( "(?i)\\s+(?:and|&)\\s+(?:please\\s+)?(?:give|explain)\\s+(?:your|the)?\\s*(?:reason|reasons)(?:\\s+respectively)?", "", text, ) text = re.sub("\\n{3,}", "\n\n", text).strip() return text def as_number(value: str) -> int | float: number = float(value) return int(number) if number.is_integer() else number def find_ranges(text: str) -> list[tuple[int, int, int | float, int | float]]: found: list[tuple[int, int, int | float, int | float]] = [] for pattern_index, pattern in enumerate(RANGE_PATTERNS): for match in pattern.finditer(text): if pattern_index == 3: (low, high) = (1, as_number(match.group(1))) else: (low, high) = (as_number(match.group(1)), as_number(match.group(2))) if low <= high: found.append((match.start(), match.end(), low, high)) deduplicated: list[tuple[int, int, int | float, int | float]] = [] for candidate in sorted(found, key=lambda row: (row[0], row[1] - row[0])): if any( ( abs(candidate[0] - prior[0]) < 5 and candidate[2:] == prior[2:] for prior in deduplicated ) ): continue deduplicated.append(candidate) return sorted(deduplicated) def item_segments(text: str, item_count: int) -> list[str]: markers = list(ITEM_RE.finditer(text)) if len(markers) >= item_count: markers = markers[-item_count:] return [ text[ marker.start() : ( markers[index + 1].start() if index + 1 < len(markers) else len(text) ) ].strip() for (index, marker) in enumerate(markers) ] bullets = [match.group(1).strip() for match in BULLET_RE.finditer(text)] if len(bullets) >= item_count: return bullets[-item_count:] return [f"Source response item {index}" for index in range(1, item_count + 1)] def span_range(segment: str) -> tuple[int | float, int | float] | None: explicit = [as_number(value) for value in EXPLICIT_VALUE_RE.findall(segment)] if len(set(explicit)) >= 2: return (min(explicit), max(explicit)) ranges = find_ranges(segment) return ranges[-1][2:] if ranges else None def manual_ranges( study_id: str, item_count: int, material: str ) -> list[tuple[int, int]] | None: if study_id in JEP1_BIPOLAR: return [(-3, 3), *[(1, 7)] * (item_count - 1)] if study_id == "JEP_10_2": return [(0, 10)] * item_count if study_id == "JEP_5_1b": return [(1, 12), (1, 7), (1, 12)] if study_id == "JEP_5_3a": return [*[(1, 7)] * 5, (0, 8)] if study_id == "JEP_2_1": return [*[(1, 7)] * 5, *[(1, 5)] * 7] if study_id in {"JEP_2_2a", "JEP_2_2b"}: return [(1, 7)] * item_count if study_id == "JAP_9_4": return [(1, 5)] * item_count if study_id == "AMJ_3_3": return [*[(1, 7)] * 20, *[(0, 1)] * 3] if study_id == "JPSP_4_7": return [(1, 9)] * item_count if study_id == "JEP_4_2": return [(1, 3) if "3 =" in material else (1, 2)] if study_id == "JEP_4_3": return [(0, 3) if "3=" in material else (0, 2)] return None def build_predictions( study_id: str, material: str, item_count: int ) -> list[dict[str, Any]]: segments = item_segments(material, item_count) overrides = manual_ranges(study_id, item_count, material) global_ranges = find_ranges(material) unique_ranges = [] for row in global_ranges: if row[2:] not in unique_ranges: unique_ranges.append(row[2:]) predictions = [] for index, segment in enumerate(segments): response_range = overrides[index] if overrides else span_range(segment) if response_range is None and len(unique_ranges) == 1: response_range = unique_ranges[0] if response_range is None: position = material.find(segment) prior = [row[2:] for row in global_ranges if row[0] < position] response_range = prior[-1] if prior else None if response_range is None: raise ValueError(f"{study_id} item {index + 1}: no bounded option mapping") (low, high) = response_range if ( not isinstance(low, int) or not isinstance(high, int) or high < low or (high - low > 12) ): raise ValueError( f"{study_id} item {index + 1}: unsupported response range {response_range}" ) options = [ { "id": option_id, "text": f"Source response value {value}", "analysis_value": value, } for (option_id, value) in enumerate(range(low, high + 1), start=1) ] predictions.append( { "prediction_id": f"item_{index + 1}", "question": f"Predict the participant's response to this source item: {segment}", "source_item_index": index + 1, "source_response_range": [low, high], "options": options, } ) return predictions GENERIC_OPTION_RE = re.compile("^Source response value\\s+", re.IGNORECASE) EQUAL_TOKEN_RE = re.compile("(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s*=") PAREN_TOKEN_RE = re.compile( "(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s*\\(\\s*([^()\\n]{1,120}?)\\s*\\)" ) MEANS_TOKEN_RE = re.compile( "(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s+(?:means?|indicates?)\\s+[\\\"“”'‘’]?([^\\n;,.)]{1,120})", re.IGNORECASE, ) COLON_TOKEN_RE = re.compile( "(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s*:\\s*[\\\"“'‘]?([^\\n;()]{1,160}?)[\\\"”'’]?(?=\\s*(?:[;,]\\s*[+-]?\\d+(?:\\.\\d+)?\\s*:|\\)))", re.IGNORECASE, ) REFERENCE_TOKEN_RE = re.compile( "(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s+(?:again\\s+)?(?:referr(?:ing|ed)\\s+to|indicat(?:ing|ed|es))\\s*[,:]?\\s*[\\\"“'‘]?([^\\n;.]{1,180}?)[\\\"”'’]?(?=\\s*(?:and|to)\\s*[+-]?\\d+(?:\\.\\d+)?\\b|\\s*[;.]|$)", re.IGNORECASE, ) QUOTED_TOKEN_RE = re.compile( '(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s*(?:(?::|,)?\\s*(?:again\\s+)?(?:referr(?:ing|ed)\\s+to|indicat(?:ing|ed|es))?\\s*[:,]?)?\\s*[\\"“‘]([^\\"”’\\n]{1,180})[\\"”’]', re.IGNORECASE, ) LABEL_EQUALS_TOKEN_RE = re.compile( "(?<=[(,;])\\s*([^,;()=\\n]{1,120}?)\\s*=\\s*([+-]?\\d+(?:\\.\\d+)?)", re.IGNORECASE ) ITEM_PREFIX_RE = re.compile("^\\s*\\(?\\d{1,2}\\)?[.)]\\s*") CONNECTOR_TAIL_RE = re.compile( "(?:[\\s,;:/—–-]*(?:to|through|and|or|versus|vs\\.?)\\s*)$", re.IGNORECASE ) def clean_label(value: str) -> str: text = re.sub("\\s+", " ", value).strip() text = CONNECTOR_TAIL_RE.sub("", text).strip() text = text.strip(" \t\r\n:;,.-—–/()[]{}\"'“”‘’") text = re.sub("\\s+", " ", text).strip() return text def _last_equal_label(text: str) -> str: tail = text[:180].lstrip() if not tail: return "" quote_pairs = {'"': '"', "'": "'", "“": "”", "‘": "’"} if tail[0] in quote_pairs: closing = quote_pairs[tail[0]] end = tail.find(closing, 1) if end > 1: return clean_label(tail[1:end]) close_paren = tail.find(")") newline = tail.find("\n") candidates = [index for index in (close_paren, newline) if index >= 0] if candidates: tail = tail[: min(candidates)] else: sentence = re.search("[.!?](?:\\s|$)", tail) if sentence: tail = tail[: sentence.start()] return clean_label(tail) @dataclass(frozen=True) class AnchorCandidate: start: int end: int anchors: dict[int | float, str] syntax: str def equal_candidates( text: str, low: int | float, high: int | float ) -> list[AnchorCandidate]: tokens = list(EQUAL_TOKEN_RE.finditer(text)) candidates: list[AnchorCandidate] = [] for left_index, left in enumerate(tokens): if not low <= as_number(left.group(1)) <= high: continue for right_index in range(left_index + 1, min(left_index + 10, len(tokens))): right = tokens[right_index] if right.start() - left.end() > 650: break cluster = tokens[left_index : right_index + 1] if any( ( as_number(token.group(1)) < low or as_number(token.group(1)) > high for token in cluster ) ): break cluster_values = {as_number(token.group(1)) for token in cluster} if low not in cluster_values or high not in cluster_values: continue anchors: dict[int | float, str] = {} for index, token in enumerate(cluster): number = as_number(token.group(1)) if index + 1 < len(cluster): raw = text[token.end() : cluster[index + 1].start()] label = clean_label(raw) else: label = _last_equal_label(text[token.end() :]) if label and len(label) <= 120: anchors[number] = label if low in anchors and high in anchors: candidates.append( AnchorCandidate( left.start(), right.end(), anchors, "numeric_equals" ) ) break return candidates def labelled_token_candidates( text: str, low: int | float, high: int | float ) -> list[AnchorCandidate]: """Parse source-written labels using colon/referring/indicating syntax.""" candidates: list[AnchorCandidate] = [] for pattern, syntax in ( (COLON_TOKEN_RE, "numeric_colon"), (REFERENCE_TOKEN_RE, "numeric_reference"), (QUOTED_TOKEN_RE, "numeric_quoted_label"), ): tokens = [ token for token in pattern.finditer(text) if low <= as_number(token.group(1)) <= high ] if not tokens: continue anchors = { as_number(token.group(1)): clean_label(token.group(2)) for token in tokens if clean_label(token.group(2)) } if low in anchors and high in anchors: candidates.append( AnchorCandidate(tokens[0].start(), tokens[-1].end(), anchors, syntax) ) return candidates def label_equals_candidates( text: str, low: int | float, high: int | float ) -> list[AnchorCandidate]: """Parse source categories written as ``label = numeric code``.""" tokens = [ token for token in LABEL_EQUALS_TOKEN_RE.finditer(text) if low <= as_number(token.group(2)) <= high ] anchors = { as_number(token.group(2)): clean_label(token.group(1)) for token in tokens if clean_label(token.group(1)) } if low not in anchors or high not in anchors: return [] return [ AnchorCandidate( tokens[0].start(), tokens[-1].end(), anchors, "label_equals_numeric" ) ] def parenthetical_candidates( text: str, low: int | float, high: int | float ) -> list[AnchorCandidate]: tokens = list(PAREN_TOKEN_RE.finditer(text)) candidates: list[AnchorCandidate] = [] for left_index, left in enumerate(tokens): if as_number(left.group(1)) != low: continue for right_index in range(left_index + 1, min(left_index + 8, len(tokens))): right = tokens[right_index] if right.start() - left.end() > 650: break if as_number(right.group(1)) != high: continue between = text[left.end() : right.start()] context = text[max(0, left.start() - 80) : right.end() + 20] if not re.search( "\\b(?:to|through|scale|ranging|range)\\b|[-—–]", between + context, re.I, ): continue cluster = tokens[left_index : right_index + 1] anchors = { as_number(token.group(1)): clean_label(token.group(2)) for token in cluster if low <= as_number(token.group(1)) <= high and clean_label(token.group(2)) } if low in anchors and high in anchors: candidates.append( AnchorCandidate( left.start(), right.end(), anchors, "numeric_parentheses" ) ) break return candidates def means_candidates( text: str, low: int | float, high: int | float ) -> list[AnchorCandidate]: tokens = list(MEANS_TOKEN_RE.finditer(text)) candidates: list[AnchorCandidate] = [] for left_index, left in enumerate(tokens): if as_number(left.group(1)) != low: continue for right in tokens[left_index + 1 : left_index + 8]: if right.start() - left.end() > 650: break if as_number(right.group(1)) != high: continue anchors = { low: clean_label(left.group(2)), high: clean_label(right.group(2)), } if anchors[low] and anchors[high]: candidates.append( AnchorCandidate(left.start(), right.end(), anchors, "numeric_means") ) break return candidates def anchor_candidates( text: str, low: int | float, high: int | float ) -> list[AnchorCandidate]: candidates = [ *equal_candidates(text, low, high), *parenthetical_candidates(text, low, high), *means_candidates(text, low, high), *labelled_token_candidates(text, low, high), *label_equals_candidates(text, low, high), ] unique: dict[ tuple[int, int, tuple[tuple[int | float, str], ...]], AnchorCandidate ] = {} for candidate in candidates: key = (candidate.start, candidate.end, tuple(sorted(candidate.anchors.items()))) unique[key] = candidate return sorted( unique.values(), key=lambda candidate: (candidate.start, candidate.end) ) def source_item_text(prediction: dict[str, Any]) -> str: question = str(prediction["question"]) if question.startswith(SOURCE_ITEM_PREFIX): question = question[len(SOURCE_ITEM_PREFIX) :] question = ITEM_PREFIX_RE.sub("", question, count=1).strip() protocol = TRAILING_ITEM_PROTOCOL_RE.search(question) return question[: protocol.start()].rstrip() if protocol else question def preexisting_label(option: dict[str, Any]) -> str: """Remove the already displayed source value from a manual option label.""" text = str(option.get("text", "")).strip() value = str(option["analysis_value"]) for prefix, suffix in ( (f"{value} (", ")"), (f"{value} — ", ""), (f"{value} - ", ""), ): if text.startswith(prefix) and (not suffix or text.endswith(suffix)): return text[len(prefix) : -len(suffix) if suffix else None].strip() return text def render_options( options: list[dict[str, Any]], anchors: dict[int | float, str] ) -> str: """Render fully labelled categories naturally; keep numbers for partial scales.""" all_values_labelled = all( (option["analysis_value"] in anchors for option in options) ) for option in options: value = option["analysis_value"] label = anchors.get(value) if all_values_labelled: option["text"] = label else: option["text"] = f"{value} — {label}" if label else str(value) return ( "semantic_text_only" if all_values_labelled else "numeric_scale_with_source_anchors" ) def item_position(material: str, prediction: dict[str, Any]) -> int: item = source_item_text(prediction) exact = material.find(item) if exact >= 0: return exact compact_item = re.sub("\\s+", " ", item) compact_material = re.sub("\\s+", " ", material) for width in (120, 80, 50, 30): needle = compact_item[:width].strip() if len(needle) < 15: continue position = compact_material.find(needle) if position >= 0: return position return -1 def candidate_distance(candidate: AnchorCandidate, position: int) -> tuple[int, int]: if position < 0: return (1, candidate.start) if candidate.start <= position <= candidate.end + 300: return (0, abs(position - candidate.start)) if candidate.end < position: return (1, position - candidate.end) return (2, candidate.start - position) def restore_prediction_options( prediction: dict[str, Any], *, source_material: str ) -> tuple[dict[str, Any], dict[str, Any]]: restored = copy.deepcopy(prediction) options = restored["options"] generic = [ GENERIC_OPTION_RE.match(str(option.get("text", ""))) is not None for option in options ] if not any(generic): anchors = { option["analysis_value"]: preexisting_label(option) for option in options if preexisting_label(option) } display_policy = render_options(options, anchors) return ( restored, { "method": "preexisting_semantic_options", "syntax": "manual_or_source_exact", "display_policy": display_policy, "anchors": { str(key): value for (key, value) in sorted(anchors.items()) }, }, ) manual_anchors = { option["analysis_value"]: preexisting_label(option) for (option, is_generic) in zip(options, generic, strict=True) if not is_generic and preexisting_label(option) } if manual_anchors: display_policy = render_options(options, manual_anchors) return ( restored, { "method": "manual_source_anchor_recovery", "syntax": "manual_source_exact", "scope": "manual_recovered_item", "display_policy": display_policy, "anchors": { str(key): value for (key, value) in sorted(manual_anchors.items()) }, }, ) values = [option["analysis_value"] for option in options] (low, high) = (min(values), max(values)) question = source_item_text(restored) question_candidates = anchor_candidates(question, low, high) if question_candidates: selected = min( question_candidates, key=lambda candidate: (candidate.end - candidate.start, candidate.start), ) scope = "source_item" else: material_candidates = anchor_candidates(source_material, low, high) position = item_position(source_material, restored) selected = ( min( material_candidates, key=lambda candidate: candidate_distance(candidate, position), ) if material_candidates else None ) scope = "source_material_nearest_item" anchors = selected.anchors if selected is not None else {} display_policy = render_options(options, anchors) return ( restored, { "method": ( "source_anchor_recovery" if anchors else "numeric_only_no_source_anchor" ), "syntax": selected.syntax if selected is not None else None, "scope": scope if selected is not None else None, "display_policy": display_policy, "anchors": {str(key): value for (key, value) in sorted(anchors.items())}, }, ) SYSTEM_PROMPT = "You are a psychometric measurement and prediction model.\n\nYou will receive person-level records, such as statements, behaviors, events, or attributes. Use these records as evidence to answer the prediction questions about that person.\n\nOutput only the final answer(s)." SOURCE_ITEM_PREFIX = "Predict the participant's response to this source item: " ITEM_MARKER_RE = re.compile("^\\s*(?:[-•]\\s*)?\\(?\\d{1,2}\\)?[.)]\\s*") SENTENCE_BOUNDARY_RE = re.compile("(?<=[.!?])\\s+(?=[A-Z0-9\\\"“‘'])") RESPONSE_INSTRUCTION_RE = re.compile( "(?is)^\\s*(?:after (?:reading|reviewing|considering).{0,180})?(?:please\\s+)?(?:rate|answer|respond|indicate|evaluate|complete).{0,220}$" ) TRAILING_ITEM_PROTOCOL_RE = re.compile( "(?is)\\n\\s*(?=(?:still[, ]|additionally[, ]|besides[, ]|also[, ]|then[, ]|please\\s+rate|when\\s+you\\s+give|when\\s+you\\s+answer|now[, ]|according\\s+to|due\\s+to\\s+economic))" ) PROHIBITED_RESPONSE_CLAUSES = ( re.compile( "(?is)\\s*(?:and\\s+)?(?:please\\s+)?(?:give|explain|provide)\\s+(?:your|the)?\\s*(?:reason|reasons|reasoning|rationale)(?:\\s+respectively)?[.!]?" ), re.compile( "(?is)\\s*(?:your|the)\\s+(?:ratings?|answers?)\\s+and\\s+explanations?\\s+should\\s+reflect[^.!?]*[.!]?" ), re.compile( "(?is)\\s*(?:but\\s+)?just\\s+give\\s+one\\s+answer\\s+with\\s+multiple\\s+considerations?[.!]?" ), re.compile( "(?is)\\s*(?:your|you)\\s+answer\\s+(?:is\\s+)?in\\s+the\\s+form\\s+of\\s+json.*$" ), re.compile("(?is)\\s*when\\s+you\\s+give\\s+(?:the\\s+)?(?:ratings?|answers?).*$"), re.compile( "(?is)\\s*(?:try\\s+to\\s+)?simulate\\s+(?:how\\s+)?(?:people|(?:a\\s+)?real\\s+humans?)[^,.!?]*(?:[,!?.]+|$)" ), re.compile( "(?is)\\s*(?:you\\s+should|do)\\s+not\\s+give\\s+answers?\\s+like[^.!?]*(?:[.!?]+|$)" ), re.compile( "(?is)\\s*do\\s+not\\s+judge\\s+with\\s+high\\s+moral\\s+standards?[^.!?]*(?:[.!?]+|$)" ), re.compile( "(?is)\\s*(?:do|don['’]?t)\\s+worry\\s+about\\s+(?:any\\s+)?moral\\s+issues?[^.!?]*(?:[.!?]+|$)" ), ) TERMINAL_SEMANTIC_CODE_RE = re.compile( "(?is)\\s*\\((?=[^()\\n]*(?:[+-]?\\d+(?:\\.\\d+)?\\s*=|=\\s*[+-]?\\d+(?:\\.\\d+)?))[^()\\n]*\\)\\s*[.]?\\s*$" ) TRAILING_QUESTION_SCALE_INSTRUCTION_RE = re.compile( "(?is)\\s+Please\\s+(?:indicate your response|rate your answer)\\s+on\\s+(?:a\\s+)?(?:numeric\\s+)?scale\\b[^.]*\\.{1,2}\\s*$" ) RAW_SOURCE_BULLET_RE = re.compile("[\\uf06c\\uf0b7\\uf0a7\\uf0df\\u25fc\\u25aa\\u25ba]") TRAILING_SETTING_PROTOCOL_RE = re.compile( '(?is)(?:^|(?<=[.!?”’\\"]))\\s+(?:(?:then|now)\\s*,?\\s*(?:(?:based\\s+on|after\\s+(?:reading|reviewing|considering))\\s+[^.!?]{0,180}[,.]?\\s*)?(?:please\\s+)?(?:respond\\s+to|answer|rate|give\\s+(?:your|the)?\\s*ratings?|provide\\s+your\\s+ratings?|indicate\\s+your\\s+(?:level|degree))\\b|based\\s+on\\s+[^.!?]{0,240}[,.]\\s*(?:please\\s+)?(?:respond\\s+to|answer|rate|give\\s+(?:your|the)?\\s*ratings?|indicate)\\b|according\\s+to\\s+[^.!?]{0,240}[,.]\\s*(?:please\\s+)?(?:respond\\s+to|answer|rate|give\\s+(?:your|the)?\\s*ratings?|indicate)\\b|after\\s+(?:reading|reviewing|considering)\\s+[^.!?]{0,240}[,.]\\s*(?:please\\s+)?(?:respond\\s+to|answer|rate|give\\s+(?:your|the)?\\s*ratings?|indicate)\\b|please\\s+focus\\s+on\\s+[^.!?]{0,320}[,.]\\s*answer\\s+(?:the\\s+)?(?:next|below|following)\\s+questionss?\\b)[\\s\\S]*$' ) INLINE_QUESTION_TRANSITION_RE = re.compile( '(?is)(?:^|(?<=[.!?”’\\"]))\\s+now\\s*,?\\s*please\\s+answer\\s+(?:the\\s+)?(?:following|below|next)\\s+questions\\s*[:.]?\\s*' ) KNOWN_TRAILING_SETTING_PROTOCOLS = ( re.compile( "(?is)\\s+Based on what you observed in the meeting,\\s*please give your ratings for each item\\..*$" ), re.compile( "(?is)\\s+Then,\\s*after reading the scenario above,\\s*please indicate your agreement with the following items\\b.*$" ), re.compile( "(?is)\\s+Please keep the above conversations and descriptions about the coworker in mind,\\s*and indicate to what extent you agree with the following statements\\b.*$" ), re.compile( "(?is)\\s+Please based on the content and identity of the final speaker\\.?\\s*$" ), re.compile( "(?is)\\s+In the next screen,\\s*you will be asked a question regarding the scenario you have just read\\.?\\s*$" ), ) TRAILING_ANSWER_CLAUSE_RE = re.compile( "(?is)\\s+(?:to|and)\\s+answer\\s+(?:the\\s+)?(?:next|below|following)\\s+questionss?\\s*[.]?\\s*$" ) SURFACE_TYPO_REPLACEMENTS = ( (re.compile("\\bitemss\\b", re.I), "items"), (re.compile("\\bquestionss\\b", re.I), "questions"), (re.compile("\\bratingss\\b", re.I), "ratings"), (re.compile("\\bproduct\\s+sare\\b", re.I), "products are"), (re.compile("\\bCathywent\\b"), "Cathy went"), (re.compile("\\bEpisodes:\\s*Episodes:\\s*", re.I), "Episodes: "), (re.compile("\\bthe\\s+giving\\s+scenario\\b", re.I), "the given scenario"), (re.compile("\\busing\\s+using\\b", re.I), "using"), (re.compile("\\bU\\.\\s+S\\.\\b"), "U.S."), (re.compile("\\ban bachelor's degree\\b", re.I), "a bachelor's degree"), (re.compile("\\bneither disagree or agree\\b", re.I), "neither disagree nor agree"), (re.compile("\\bthe attention me gave\\b", re.I), "the attention I gave"), ( re.compile("\\bI think this (Eric|Erica)([’'])s comments\\b"), "I think \\1\\2s comments", ), ( re.compile("\\bthe work that needs done\\b", re.I), "the work that needs to be done", ), (re.compile("\\bscale\\s+of\\s+on\\s+", re.I), "scale from "), (re.compile("\\bscales\\s*,s\\b", re.I), "scale"), ( re.compile( "(?i)you\\s+will\\s+read\\s+a\\s+scenario\\s+describe\\s+the\\s+target,\\s*and\\s+give\\s+ratings\\s+accordingly\\.\\s*Here\\s+is\\s+the\\s+scenario\\s+of\\s+target\\s+you\\s+should\\s+read\\s+in\\s+this\\s+study:\\s*" ), "Here is the target described in this study: ", ), (re.compile("\\ba\\s+Individual\\b"), "an individual"), ) def source_segment(prediction: dict[str, Any]) -> str: question = prediction["question"] return ( question[len(SOURCE_ITEM_PREFIX) :] if question.startswith(SOURCE_ITEM_PREFIX) else question ) def clean_item_text(prediction: dict[str, Any]) -> str: if prediction.get("adapted_question"): return re.sub( "\\s+", " ", normalize_surface_text(str(prediction["adapted_question"])) ).strip() text = ITEM_MARKER_RE.sub("", source_segment(prediction), count=1).strip() protocol = TRAILING_ITEM_PROTOCOL_RE.search(text) if protocol: text = text[: protocol.start()].rstrip() return re.sub( "\\s+", " ", normalize_surface_text(sanitize_response_protocol(text)) ).strip() def naturalize_prediction_question( prediction: dict[str, Any], recovery: dict[str, Any], *, study_id: str, condition: dict[str, Any], ) -> None: """Move fully semantic source-code mappings out of the model-facing question.""" text = clean_item_text(prediction) text = TRAILING_QUESTION_SCALE_INSTRUCTION_RE.sub("", text).rstrip() if recovery.get("display_policy") == "semantic_text_only": text = TERMINAL_SEMANTIC_CODE_RE.sub("", text).rstrip() normalized = text.strip().rstrip(".").lower() if study_id in {"JAP_8_2", "JAP_8_4"}: reward_items = { "bonus pay": "To what extent would you recommend this employee for bonus pay?", "salary increase": "To what extent would you recommend this employee for a salary increase?", "high profile": "To what extent would you recommend this employee for a high-profile assignment?", } text = reward_items.get(normalized, text) bipolar_items = { "item_8": "How fair was the target employee's behavior in the episodes?", "item_9": "How fair is the target employee in general?", "item_10": "How would you describe the target employee's behavior in the episodes: disrespectful–respectful?", "item_11": "How would you describe the target employee's behavior in the episodes: inconsiderate–considerate?", "item_12": "How would you describe the target employee's behavior in the episodes: impolite–polite?", "item_13": "How would you describe the target employee's behavior in the episodes: unreasonable–reasonable?", "item_14": "How would you describe the target employee's behavior in the episodes: unethical–ethical?", "item_15": "How would you describe the target employee's behavior in the episodes: biased–unbiased?", } text = bipolar_items.get(prediction.get("prediction_id"), text) elif study_id == "OBHDP_6_3": decision_factors = { "profitability to the company": "To what degree was profitability to the company part of the decision process?", "number of hours worked": "To what degree was number of hours worked part of the decision process?", "client billing": "To what degree was client billing part of the decision process?", "leadership skills": "To what degree were leadership skills part of the decision process?", "attitude toward clients": "To what degree was attitude toward clients part of the decision process?", "potential for productivity": "To what degree was potential for productivity part of the decision process?", } text = decision_factors.get(normalized, text) elif study_id == "JAP_6_4": candidate_traits = { "perceived creativity": "How likely is this person to exhibit creativity?", "assertiveness": "How likely is this person to be assertive?", "competence": "How likely is this person to be competent?", "warmth": "How likely is this person to be warm?", "masculinity": "How likely is this person to be masculine?", "feminine": "How likely is this person to be feminine?", } text = candidate_traits.get(normalized, text) elif study_id == "JEP_5_3a": jim_items = { "item_1": "Given the outcome he reported, how ethical do you think Jim is?", "item_2": "Given the outcome he reported, how moral do you think Jim is?", "item_3": "Given the outcome he reported, how good do you think Jim is?", "item_4": "Do you think Jim is honest?", "item_5": "Do you think Jim is telling the truth?", } text = jim_items.get(prediction.get("prediction_id"), text) elif study_id == "JPSP_10_3" and prediction.get("prediction_id") == "item_12": text = "Which explanation best describes why Pat performed poorly?" elif study_id == "AMJ_10_2": female_condition = "female" in str(condition.get("label", "")).lower() if female_condition: text = re.sub("\\bEric\\b", "Erica", text) text = re.sub("\\bhis\\s+manager\\b", "her manager", text, flags=re.I) text = re.sub("\\bhis\\s+behavior\\b", "her behavior", text, flags=re.I) text = re.sub("\\bhe\\s+did\\b", "she did", text, flags=re.I) text = re.sub("\\b(Erica?|ERIC)\\s+suggest\\b", "\\1 suggests", text) text = re.sub("\\bmakes contributions to\\b", "contributes to", text) text = re.sub("\\bhas a desirability as\\b", "is desirable as", text) text = re.sub( "\\bleads the conversation in team\\b", "leads the team conversation", text ) text = re.sub( "\\bhas a high level of respect in others’ eyes\\b", "is highly respected by others", text, ) text = re.sub("\\braised a suggestion\\b", "made a suggestion", text) text = re.sub( "\\bconsumes a lot of time complaining\\b", "spends a lot of time complaining", text, ) text = text.rstrip(" ,") if study_id == "OBHDP_6_3" and text: text = text[0].upper() + text[1:] prediction["adapted_question"] = text def sanitize_response_protocol(text: str) -> str: """Drop output-format/reasoning requests while preserving scenario content.""" for pattern in PROHIBITED_RESPONSE_CLAUSES: text = pattern.sub("", text) text = re.sub("[ \\t]+\\n", "\n", text) text = re.sub("\\n{3,}", "\n\n", text) return text.strip() def normalize_surface_text(text: str) -> str: """Repair extraction artifacts without paraphrasing experimental content.""" text = RAW_SOURCE_BULLET_RE.sub("; ", text) text = re.sub("([.:!?])\\s*;\\s*", "\\1 ", text) text = re.sub("^\\s*;\\s*|\\s*;\\s*$", "", text) for pattern, replacement in SURFACE_TYPO_REPLACEMENTS: text = pattern.sub(replacement, text) text = re.sub("[ \\t]+([,.;:!?])", "\\1", text) text = re.sub("([,;:])(?=[A-Za-z])", "\\1 ", text) text = re.sub("(?<=[a-z”\\\"'])\\.(?=[A-Z])", ". ", text) text = re.sub("[ \\t]{2,}", " ", text) return text.strip() def sanitize_setting_protocol(text: str) -> str: """Keep stimulus/IV content but remove duplicated final response instructions.""" text = normalize_surface_text(text) text = sanitize_response_protocol(text) text = INLINE_QUESTION_TRANSITION_RE.sub(" ", text) text = TRAILING_ANSWER_CLAUSE_RE.sub(".", text) text = TRAILING_SETTING_PROTOCOL_RE.sub("", text) for pattern in KNOWN_TRAILING_SETTING_PROTOCOLS: text = pattern.sub("", text) return normalize_surface_text(text).rstrip(" ,;:") def naturalize_participant_context(text: str) -> str: """Render the participant persona as first-person evidence, not a model command.""" text = normalize_surface_text(text) text = re.sub( "(?i)^Imagine\\s+(?:that\\s+)?you\\s+are\\s+person\\b", "I am a person", text ) text = re.sub("(?i)^Imagine\\s+(?:that\\s+)?you\\s+are\\b", "I am", text) text = re.sub( "(?i)We\\s+will\\s+present\\s+you\\s+(?:with\\s+)?information\\s+about\\s+Quallex", "I will be presented with information about Quallex", text, ) text = re.sub( "(?i)After\\s+you\\s+are\\s+presented\\s+with\\s+information\\s+about\\s+Quallex,\\s*we\\s+will\\s+ask\\s+you\\s+to\\s+answer\\s+some\\s+questions\\s+about\\s+your\\s+perceptions\\s+of\\s+this\\s+company\\.", "I will then answer questions about my perceptions of this company.", text, ) text = re.sub( "(?i)First,\\s*please\\s+keep\\s+in\\s+mind\\s+that\\s+you\\s+are\\s+typically\\s+", "I am typically ", text, ) text = re.sub("(?i)Please\\s+keep\\s+in\\s+mind\\s+that\\s+you\\s+", "I ", text) text = re.sub( "(?i)Consider\\s+the\\s+balance\\s+of\\s+equity\\s+and\\s+efficiency\\s+in\\s+real\\s+life,\\s*and\\s+simulate\\s+the\\s+response\\s+of\\s+individuals\\s+with\\s+different\\s+perceptions\\s+about\\s+this\\.", "", text, ) text = re.sub( "(?i)We\\s+will\\s+present\\s+you\\s+a\\s+scenario", "I will consider a scenario", text, ) text = re.sub( "(?i)Imagine\\s+that\\s+I\\s+accepted", "In this scenario, I accepted", text ) text = re.sub( "(?i)With\\s+this\\s+in\\s+mind,\\s*please\\s+consider", "With this in mind, I will consider", text, ) text = re.sub( "(?i)Again,\\s*keep\\s+in\\s+mind\\s+what\\s+thoughts\\s+and\\s+feelings\\s+you\\s+would\\s+have\\s+if\\s+this\\s+were\\s+actually\\s+you\\.", "", text, ) text = re.sub( "(?i)so\\s+please\\s+read\\s+each\\s+question\\s+and\\s+set\\s+of\\s+instructions\\s+very\\s+carefully\\.", "I will read each question and set of instructions carefully.", text, ) replacements = ( ("\\bYou are\\b", "I am"), ("\\byou are\\b", "I am"), ("\\bYou will\\b", "I will"), ("\\byou will\\b", "I will"), ("\\bYou have\\b", "I have"), ("\\byou have\\b", "I have"), ("\\bYou accepted\\b", "I accepted"), ("\\byou accepted\\b", "I accepted"), ("\\bYou now work\\b", "I now work"), ("\\byou now work\\b", "I now work"), ("\\bYour\\b", "My"), ("\\byour\\b", "my"), ) for pattern, replacement in replacements: text = re.sub(pattern, replacement, text) text = re.sub( "(?i)Again,\\s*keep\\s+in\\s+mind\\s+what\\s+thoughts\\s+and\\s+feelings\\s+I\\s+would\\s+have\\s+if\\s+this\\s+were\\s+actually\\s+you\\.", "", text, ) text = re.sub( "(?i)Please\\s+read\\s+the\\s+information\\s+I\\s+am\\s+presented\\s+with\\s+carefully\\.", "", text, ) text = re.sub("(?<!\\.)\\.\\.(?!\\.)", ".", text) text = re.sub("\\s+", " ", text).strip() if text and text[-1] not in ".!?": text += "." return text def annotate_options( prediction: dict[str, Any], labels: dict[int | float, str] ) -> None: for option in prediction["options"]: value = option["analysis_value"] label = labels.get(value) option["text"] = ( f"{value} ({label})" if label else f"Source response value {value}" ) def source_manual_items(study_id, observation): text = observation.replace("’", "'") marker = ( "Please focus on the material of employee provided" if study_id == "JAP_8_1" else "After reading the previous scenario" ) if marker not in text: raise ValueError(f"Missing item boundary: {study_id}") tail = text[text.index(marker) :] tail = re.split(r"(?i)(?:you|your) answer in the form of json", tail)[0] def pair(s): m = re.search(r"\(\s*1\s*=\s*(.*?),\s*7\s*=\s*(.*?)\)", s) if not m: raise ValueError(f"Missing scale endpoints: {study_id}") return {1: m[1].strip().capitalize(), 7: m[2].strip().capitalize()} def sentence(s): return s[0].upper() + s[1:].rstrip(". ") + "." if study_id == "JAP_8_1": segments = [v for _, v in re.findall(r"(?m)^\s*\((\d+)\)\s*([^\n]+)", tail)] if len(segments) != 12: raise ValueError("Expected 12 source items for JAP_8_1") raw = [re.sub(r"\s*\(\s*1\s*=.*$", "", v).strip() for v in segments] items = [ raw[0], raw[1].replace("In your opinion, how", "How"), "How likely is this employee to succeed?", raw[3].replace("do you think this employee is", "is this employee"), ] for reward in raw[4:7]: if reward == "high profile": reward = "a high-profile assignment" elif reward == "salary increase": reward = "a " + reward items.append( f"To what extent would you recommend this employee for {reward}?" ) items += [ "How fair was the target employee's behavior in the episodes?", "How fair is the target employee in general?", ] items += [ "How would you describe the target employee's behavior: " + re.sub(r"\s*–\s*", "–", x) + "?" for x in raw[9:] ] labels = [pair(v) for v in segments[:9]] for value in segments[9:]: low, high = value.split("–") labels.append({1: low.strip().capitalize(), 7: high.strip().capitalize()}) return items, labels blocks = tail.split("Still, according to the previous scenario,") if len(blocks) != 2: raise ValueError(f"Expected two item blocks: {study_id}") raw = [] for block in blocks: raw.extend( re.sub(r"^\(?\d+\)\s*", "", line.strip()) for line in block.splitlines()[1:] if line.strip() ) if study_id == "JAP_3_1c": if len(raw) != 9: raise ValueError("Expected nine source items for JAP_3_1c") return ( [sentence(x.replace("attention me gave", "attention I gave")) for x in raw], [pair(blocks[0])] * 9, ) if study_id == "OBHDP_6_3": if len(raw) != 10: raise ValueError("Expected ten source items for OBHDP_6_3") items = [sentence(x) for x in raw[:4]] for factor in raw[4:]: factor = factor.rstrip(". ") verb = "were" if factor == "leadership skills" else "was" items.append( f"To what degree {verb} {factor} part of the decision process?" ) endpoints = { k: v.removeprefix("This consideration was ").capitalize() for k, v in pair(blocks[1]).items() } return items, [pair(blocks[0])] * 4 + [endpoints] * 6 raise ValueError(f"Unsupported item recovery: {study_id}") def source_manual_other(sid, text): text = " ".join(text.replace("’", "'").split()) def case(s): return s[0].upper() + s[1:] def need(pattern, value): match = re.search(pattern, value) if match is None: raise ValueError(f"Missing source question/anchor: {sid}") return match if sid == "AMJ_3_2": m = need(r"\(0\s*=\s*([^,]+),\s*1\s*=\s*([^)]+)\)", text) labels = {0: m[1].strip() + " candidate", 1: m[2].strip() + " candidate"} return ( [ f"Which candidate would you choose as your tournament opponent? (0 = {labels[0]}; 1 = {labels[1]})." ], [labels], ) if sid in {"JEP_1_1a", "JEP_1_1b"}: m = need(r"with -3 referring to a (.*?) and \+3 referring to a ([^.]+)", text) lo, hi = m[1].strip(), m[2].strip() labels = {-3: case(lo), 0: "Neutral", 3: case(hi)} return ( [ f"Make an inference about the actor's underlying personal beliefs on a scale from -3 ({lo}) through 0 (neutral) to +3 ({hi})." ], [labels], ) if sid == "OBHDP_3_3": tail = text[text.index("After reading the scenario") :] parts = re.findall( r"\(\d+\)\s*(.*?)\s*\(1\s*=\s*([^,]+),\s*7\s*=\s*([^)]+)\)", tail ) if len(parts) != 2: raise ValueError("Expected two source items for OBHDP_3_3") return ( [f"To what degree do you perceive {part.strip()}?" for part, _, _ in parts], [{1: case(lo.strip()), 7: case(hi.strip())} for _, lo, hi in parts], ) if sid == "OBHDP_10_4": tail = text[text.index("Based on what you have read") :] company = need(r"Thinking about the structure of (\w+),", tail)[1] endpoints = need(r"\(1\s*=\s*([^,]+),\s*7\s*=\s*([^)]+)\)", tail) return ( [ f"How hierarchical would you expect {company} to be?", f"How many layers of hierarchy would you expect {company} to have?", ], [ {1: endpoints[1].strip(), 7: endpoints[2].strip()}, {n: f"{n} layer" if n == 1 else f"{n} layers" for n in range(1, 8)}, ], ) if sid == "JEP_4_2": tail = text.split("Will you choose from:", 1)[1].split("Please just choose", 1)[ 0 ] labels = { int(k): v.strip() for k, v in re.findall( r"(?:^|;)\s*(\d+)\s*=\s*(.*?)(?=;\s*\d+\s*=|$)", tail ) } for k, value in labels.items(): if "random device" in value: labels[k] = ( "Use the random device and install the upgrade on the selected computer" ) else: labels[k] = value.replace( "not install it on any of the computers", "install it on neither computer", ) return ["Which action would you choose for the upgraded operating system?"], [ labels ] if sid == "JEP_4_3": tail = ( text.split("Now, please give your decision from the following choices:", 1)[ 1 ] .split("Please just choose", 1)[0] .strip() .rstrip(".") ) raw = { int(k): v.strip() for k, v in re.findall( r"(?:^|;)\s*(\d+)\s*=\s*(.*?)(?=;\s*\d+\s*=|$)", tail ) } labels = { 0: case( raw[0] .replace("either of them, mark", "either participant and mark") .replace(" you have received", "") ), 1: case(raw[1].split(",")[0]), 2: case(raw[2].split(",")[0]), } if 3 in raw: a, b = labels[1].split()[-1], labels[2].split()[-1] labels[3] = f"Randomly draw between participants {a} and {b}" return ["Which reward-allocation decision would you make?"], [labels] raise ValueError(f"Unsupported item recovery: {sid}") def manual_generic_item_recovery(study_id, observation, predictions): """Read source items and apply the study's fixed Chiron presentation rules.""" if study_id not in {"JAP_8_1", "JEP_4_3", "OBHDP_10_4"} and not any( source_segment(p).startswith("Source response item") for p in predictions ): return None markers = { "JAP_8_1": "Please focus on the material of employee provided", "OBHDP_10_4": "Based on what you have read", "AMJ_3_2": "Now, please make a choice", "JAP_3_1c": "After reading the previous scenario", "JEP_1_1a": "After reading the material above", "JEP_1_1b": "After reading the material above", "JEP_4_3": "Now, please give your decision", "OBHDP_3_3": "After reading the scenario", "OBHDP_6_3": "After reading the previous scenario", } if study_id == "JEP_4_2": match = re.search( r"Imagine you (?:have to decide on which computer|could choose a random device)", observation, ) cutoff = match.start() if match else -1 elif study_id in markers: cutoff = observation.find(markers[study_id]) else: return None if cutoff < 0: raise ValueError(f"Missing item boundary: {study_id}") if study_id in {"JAP_8_1", "JAP_3_1c", "OBHDP_6_3"}: items, labels = source_manual_items(study_id, observation) else: items, labels = source_manual_other(study_id, observation) recovered = copy.deepcopy(predictions) if len(items) != len(recovered): raise ValueError(f"Item count changed: {study_id}") for prediction, item, option_labels in zip(recovered, items, labels, strict=True): prediction["question"] = SOURCE_ITEM_PREFIX + item annotate_options(prediction, option_labels) return ( sanitize_setting_protocol(observation[:cutoff].rstrip(" \n:-")), recovered, f"source_item_recovery:{study_id}", ) def extract_setting(condition: dict[str, Any]) -> tuple[str, str]: """Separate vignette setting from the final source response-item block.""" original = "\n\n".join(condition.get("observations", [])).strip() predictions = condition.get("predictions", []) if not original or not predictions: return (original, "no_predictions") first_item = source_segment(predictions[0]).strip() position = original.rfind(first_item) if position < 0: return (original, "item_boundary_not_found") setting = original[:position].rstrip() paragraphs = setting.splitlines() while paragraphs and RESPONSE_INSTRUCTION_RE.match(paragraphs[-1]): paragraphs.pop() setting = "\n".join(paragraphs).rstrip(" \n:-") return (sanitize_setting_protocol(setting), "exact_first_item_boundary") def adapt_condition( study_id: str, condition: dict[str, Any] ) -> tuple[str, list[dict[str, Any]], str]: observation = "\n\n".join(condition.get("observations", [])).strip() predictions = copy.deepcopy(condition.get("predictions", [])) manual = manual_generic_item_recovery(study_id, observation, predictions) if manual is not None: return manual (setting, status) = extract_setting({**condition, "predictions": predictions}) return (setting, predictions, status) def chunk_record(text: str, max_chars: int = 420) -> list[str]: text = normalize_surface_text(text) text = re.sub("([.!?])(?=[A-Z])", "\\1 ", text) text = re.sub("\\s+", " ", text).strip() if not text: return [] sentences = SENTENCE_BOUNDARY_RE.split(text) chunks: list[str] = [] current = "" for sentence in sentences: sentence = sentence.strip() if not sentence: continue if current and len(current) + 1 + len(sentence) <= max_chars: current = f"{current} {sentence}" else: if current: chunks.append(current) while len(sentence) > max_chars: boundary = sentence.rfind(" ", 0, max_chars) boundary = boundary if boundary >= max_chars // 2 else max_chars chunks.append(sentence[:boundary].strip()) sentence = sentence[boundary:].strip() current = sentence if current: chunks.append(current) return chunks def adapted_records(condition: dict[str, Any], setting: str) -> list[str]: records: list[str] = [] participant_chunks = [ chunk for record in condition.get("person_records", []) for chunk in chunk_record(naturalize_participant_context(record)) ] setting_chunks = chunk_record(setting) if participant_chunks: records.append(f"Participant context: {' '.join(participant_chunks)}") if setting_chunks: records.append(f"Experimental setting: {' '.join(setting_chunks)}") return records def format_question(prediction: dict[str, Any], index: int) -> str: lines = [ f"Q{index}.", "Please predict this participant's response to the following item:", clean_item_text(prediction), "Choose exactly one option:", ] lines.extend( (f"Option {option['id']}: {option['text']}" for option in prediction["options"]) ) return "\n".join(lines) def format_user_prompt(records: list[str], predictions: list[dict[str, Any]]) -> str: record_block = "\n".join((f"- {record}" for record in records)) question_block = "\n\n".join( ( format_question(prediction, index) for (index, prediction) in enumerate(predictions, start=1) ) ) return f"Below are records describing one participant in an experimental scenario.\n<person_records>\n{record_block}\n</person_records>\n\nQuestions:\n{question_block}" def finite(value: Any) -> float | None: if value is None: return None text = str(value).strip() if not text or text.lower() in {"/", "nan", "na", "none"}: return None try: number = float(text) except ValueError: return None return number if math.isfinite(number) else None def decimal_places(value: Any, *, zero_default: int = 0) -> int: """Return the precision actually retained by the released CSV value. CSV serialization drops the original decimal places for numeric zero. In that one case the caller supplies the documented reporting convention for the statistic family (for example SPSS ``.000`` p-values). """ text = str(value or "").strip().lower() if not text: return zero_default if text in {"0", "+0", "-0"}: return zero_default mantissa = text.split("e", 1)[0] return len(mantissa.rsplit(".", 1)[1]) if "." in mantissa else 0 def rounded_interval( value: Any, *, zero_default: int = 0, lower_bound: float | None = None, upper_bound: float | None = None, ) -> tuple[float | None, list[float] | None, int | None]: """Decode a printed scalar as its exact round-to-nearest interval.""" number = finite(value) if number is None: return (None, None, None) places = decimal_places(value, zero_default=zero_default) half_unit = 0.5 * 10.0 ** (-places) lower = number - half_unit upper = number + half_unit if lower_bound is not None: lower = max(lower, lower_bound) if upper_bound is not None: upper = min(upper, upper_bound) return (number, [lower, upper], places) def effect_target(value: Any, direction: str, indicator: str) -> dict[str, Any]: zero_defaults = {"d": 2, "b": 2, "eta-square": 2, "f": 2, "chi-square": 4} (number, interval, places) = rounded_interval( value, zero_default=zero_defaults.get(indicator.lower(), 2), lower_bound=0.0 ) if number is not None: signed = -number if direction == "neg" else number assert interval is not None signed_interval = ( [-interval[1], -interval[0]] if direction == "neg" else list(interval) ) return { "human_effect": number, "human_effect_interval": interval, "human_signed_effect": signed, "human_signed_effect_interval": signed_interval, "human_effect_censor": None, "human_effect_decimal_places": places, } text = str(value or "").strip() match = re.fullmatch("<\\s*(\\.?\\d+(?:\\.\\d+)?)", text) if not match: return { "human_effect": None, "human_effect_interval": None, "human_signed_effect": None, "human_signed_effect_interval": None, "human_effect_censor": text or None, "human_effect_decimal_places": None, } upper = float(match.group(1)) signed_interval = [-upper, 0.0] if direction == "neg" else [0.0, upper] return { "human_effect": None, "human_effect_interval": [0.0, upper], "human_signed_effect": None, "human_signed_effect_interval": signed_interval, "human_effect_censor": f"<{upper:g}", "human_effect_decimal_places": None, } def p_target(value: Any) -> dict[str, Any]: (number, interval, places) = rounded_interval( value, zero_default=3, lower_bound=0.0, upper_bound=1.0 ) if number is not None: return { "human_p": number, "human_p_interval": interval, "human_p_censor": "rounded_zero" if number == 0.0 else None, "human_p_decimal_places": places, } text = str(value or "").strip().lower().replace(" ", "") match = re.fullmatch("([<>])\\s*(\\.?\\d+(?:\\.\\d+)?)", text) if not match: return { "human_p": None, "human_p_interval": None, "human_p_censor": text or None, "human_p_decimal_places": None, } threshold = float(match.group(2)) interval = [0.0, threshold] if match.group(1) == "<" else [threshold, 1.0] return { "human_p": None, "human_p_interval": interval, "human_p_censor": f"{match.group(1)}{threshold:g}", "human_p_decimal_places": None, } def build_target(row: dict[str, Any], response_width: float | None) -> dict[str, Any]: direction = str(row.get("human_direction") or "").strip().lower() indicator = str(row["indicator"]).lower() if not direction and indicator in {"eta-square", "f", "chi-square"}: direction = "multi-group" group_values = {} group_intervals = {} group_decimal_places = {} for name, column in ( ("mean1", "human_mean_group1"), ("sd1", "human_sd_group1"), ("mean2", "human_mean_group2"), ("sd2", "human_sd_group2"), ): (number, interval, places) = rounded_interval( row.get(column), zero_default=2, lower_bound=0.0 if name.startswith("sd") else None, ) group_values[name] = number group_intervals[name] = interval group_decimal_places[name] = places return { "effect_key": f"{row['study_id']}:{row['effecttype']}:{row['effect_id']}", "study_id": str(row["study_id"]), "family": str(row["effecttype"]), "effect_id": str(row["effect_id"]), "indicator": indicator, "iv": row.get("IV"), "dv": row.get("DV"), "moderator": row.get("moderator") or None, "human_n": finite(row.get("human_size")), **effect_target(row.get("human_effsize"), direction, indicator), "human_direction": direction, **p_target(row.get("human_p_value")), "human_significance": row.get("human_sig"), "human_group_statistics": group_values, "human_group_statistics_intervals": group_intervals, "human_group_statistics_decimal_places": group_decimal_places, "response_scale_width": response_width, } def read_prompt_conditions(path, selected): """Read the selected study/condition rows without importing other studies.""" import openpyxl workbook = openpyxl.load_workbook(path, read_only=True, data_only=True) studies = {} try: rows = iter(workbook.active.values) columns = next(rows) required = { "Journal", "Essay", "Study", "Group", "Group_SampleNum", "ItemNum", "Prompt1", "Prompt2", } if not required <= set(columns): raise ValueError("Source prompt workbook is missing required columns") for values in rows: row = dict(zip(columns, values)) identifiers = [row.get(k) for k in ("Journal", "Essay", "Study")] if any(v is None for v in identifiers): continue study = "_".join( ( str(int(v)) if isinstance(v, (int, float)) and float(v).is_integer() else str(v) ) for v in identifiers ) if study not in selected: continue label = str(row["Group"]).strip() condition = label.split(":", 1)[0].strip() prompts = [ re.sub( r"\n{3,}", "\n\n", re.sub(r"[ \t]+", " ", str(row[f"Prompt{i}"])) ).strip() for i in range(1, 7) if row.get(f"Prompt{i}") not in (None, "") ] if not prompts: raise ValueError(f"Missing source prompts: {study}:{condition}") material = clean_source_material(prompts[1:] or prompts) n, item_count = row["Group_SampleNum"], row["ItemNum"] if ( type(n) not in (int, float) or int(n) != n or n <= 0 or type(item_count) not in (int, float) or int(item_count) != item_count or item_count <= 0 ): raise ValueError( f"Invalid source sample/item count: {study}:{condition}" ) conditions = studies.setdefault(study, {}) if condition in conditions: raise ValueError(f"Duplicate source condition: {study}:{condition}") conditions[condition] = { "condition_id": condition, "label": label, "original_n": int(n), "person_records": [prompts[0]], "observations": [material], "source_prompt_turns": prompts, "predictions": build_predictions(study, material, int(item_count)), } finally: workbook.close() if set(studies) != selected: raise ValueError(f"Missing source studies: {sorted(selected - set(studies))}") return studies def read_human_targets(upstream, selected): rows = {} for filename in ("human_main.csv", "human_interactions.csv"): with (upstream / filename).open(encoding="utf-8-sig", newline="") as handle: for row in csv.DictReader(handle): if row["study_id"] not in selected: continue key = f"{row['study_id']}:{row['effecttype']}:{row['effect_id']}" if key in rows: raise ValueError(f"Duplicate human target: {key}") rows[key] = row return rows def prepare_study(study_id, conditions, recipe, human_targets, split): """Combine source text/statistics with reviewed item and analysis mappings.""" if set(conditions) != set(recipe["condition_order"]): raise ValueError(f"Condition coverage changed: {study_id}") prompts = [] for cid in recipe["condition_order"]: condition = conditions[cid] setting, predictions, _ = adapt_condition(study_id, condition) material = "\n\n".join(condition["observations"]) adapted = [] for pred in predictions: pred, recovery = restore_prediction_options(pred, source_material=material) naturalize_prediction_question( pred, recovery, study_id=study_id, condition=condition ) adapted.append(pred) key = f"{study_id}:{cid}" questions = [] for pred in adapted: pid = pred["prediction_id"] questions.append( { "sample_id": f"population:{key}:{pid}", "cell_id": f"{key}:{pid}", "prediction_id": pid, "source_column": recipe.get("source_columns", {}) .get(cid, {}) .get(pid, pid + "_1"), "options": pred["options"], } ) prompt = { "condition_key": key, "study_id": study_id, "condition_id": cid, "split": split, "original_n": condition["original_n"], "messages": [ {"role": "system", "content": SYSTEM_PROMPT}, { "role": "user", "content": format_user_prompt( adapted_records(condition, setting), adapted ), }, ], "questions": questions, } if split == "test": prompt["_eval_index"] = recipe["evaluation_indices"][cid] prompts.append(prompt) questions = {q["cell_id"]: q for p in prompts for q in p["questions"]} covariates = copy.deepcopy(recipe["condition_covariates"]) for cid, values in covariates.items(): if values.get("Group") == {"source": "condition_label"}: values["Group"] = conditions[cid]["label"] effects = [] for mapping in recipe["effects"]: key = f"{study_id}:{mapping['effect']}" if key not in human_targets: raise ValueError(f"Missing human target: {key}") spec = copy.deepcopy(mapping["statistic_spec"]) target = build_target(human_targets[key], mapping.get("target_width")) target.update(copy.deepcopy(mapping.get("target_corrections", {}))) effect = { "effect_key": key, "study_id": study_id, "indicator": target["indicator"], "human_target": target, "identifiability": copy.deepcopy(mapping["identifiability"]), "statistic_spec": spec, "cells": [], } if "canonical_audit" in mapping: effect["canonical_audit"] = copy.deepcopy(mapping["canonical_audit"]) if "cells" in mapping: cell_order = mapping["cells"] else: condition_order = mapping.get("cell_conditions", recipe["condition_order"]) items = mapping["cell_items"] cell_order = ( [[cid, item] for item in items for cid in condition_order] if mapping.get("cell_order") == "item_major" else [[cid, item] for cid in condition_order for item in items] ) for cell in cell_order: cid, item = cell[:2] pid = f"item_{item}" cell_id = f"{study_id}:{cid}:{pid}" if cell_id not in questions: raise ValueError(f"Mapping references missing source item: {cell_id}") effect["cells"].append( { "cell_id": cell_id, "condition_id": cid, "prediction_id": pid, "condition_covariates": copy.deepcopy( cell[2] if len(cell) == 3 else covariates[cid] ), "analysis_options": [ {"option_id": o["id"], "analysis_value": o["analysis_value"]} for o in questions[cell_id]["options"] ], } ) effects.append(effect) result = {"study": study_id, "prompts": prompts, "effects": effects} if split == "train": result.update(blocks=recipe["blocks"], categorical=recipe["categorical"]) return result def prepare_definitions(upstream, split, readout): """Return training/test definitions using only the declared study split.""" upstream = Path(upstream) train, test = split["train_studies"], split["test_studies"] if ( len(set(train)) != len(train) or len(set(test)) != len(test) or set(train) & set(test) ): raise ValueError("Study split must contain unique, disjoint identifiers") selected = set(train) | set(test) recipes = readout["definitions"] if set(recipes) != selected: raise ValueError("Study readout rules do not match the selected split") conditions = read_prompt_conditions(upstream / "prompt.xlsx", selected) human = read_human_targets(upstream, selected) outputs = [] for group, label in ((train, "train"), (test, "test")): outputs.append( [ prepare_study(sid, conditions[sid], recipes[sid], human, label) for sid in group ] ) return (*outputs, conditions) def prepare_semantic_rules(studies, conditions, facts): """Materialize fixed factual item IDs and source-backed wording adjustments.""" prompts = {p["condition_key"]: p for study in studies for p in study["prompts"]} def question(key, index): text = prompts[key]["messages"][1]["content"] blocks = re.split(r"(?m)^Q\d+\.\n", text)[1:] return ( blocks[index] .split( "Please predict this participant's response to the following item:\n", 1 )[1] .split("\nChoose exactly one option:", 1)[0] ) def material(key): sid, cid = key.rsplit(":", 1) return "\n\n".join(conditions[sid][cid]["observations"]) def one(pattern, text): matches = re.findall(pattern, text) if len(matches) != 1: raise ValueError( f"Expected one source fragment for wording correction: {pattern}" ) return matches[0] result = {"facts": [], "prompt_edits": [], "wording_corrections": []} for key, index, option in facts: prompt = prompts[key] if not 0 <= index < len(prompt["questions"]) or not 1 <= option <= len( prompt["questions"][index]["options"] ): raise ValueError(f"Invalid factual item mapping: {key}/{index}") result["facts"].append( { "rule_id": f"{key}:Q{index + 1}", "condition_key": key, "item_index": index, "question": question(key, index), "expected_option_id": option, "expected_option_text": prompt["questions"][index]["options"][ option - 1 ]["text"], } ) causal = { cid: one( r"You have the distinct impression[^.]*because ([^.]+)\.", material(f"JPSP_10_2:{cid}"), ) for cid in ("C", "D") } for cid in ("A", "B", "C", "D"): key = f"JPSP_10_3:{cid}" before = one(r"You have the distinct impression[^.]*\.", material(key)) if cid == "A": after = before.replace( "effort but because", "effort but does not exert much effort because" ) elif cid == "B": after = before.replace( "effort because", "effort but does not exert much effort because" ) else: prefix = before.split("needs to ", 1)[0] + "needs to " other = "D" if cid == "C" else "C" after = ( prefix + "acquire the knowledge and skills to perform well but did not acquire them because " + causal[cid] + ", not because " + causal[other] + "." ) if before == after: raise ValueError(f"Missing grammar correction boundary: {key}") result["prompt_edits"].append( {"condition_key": key, "before": before, "after": after} ) for cid in ("A", "C"): key = f"OBHDP_9_3:{cid}" before = one(r"Subject: [^\n]+", material(key)).strip() after = before.replace("Conclusions", "Questions") if before == after: raise ValueError(f"Missing source subject correction: {key}") result["prompt_edits"].append( {"condition_key": key, "before": before, "after": after} ) key = "JEP_1_1b:B" text = prompts[key]["messages"][1]["content"] match = one(r"It’s[^.]*masks\.", text) required = one(r"won’t[^.]*mask on", text) result["wording_corrections"].append( { "condition_key": key, "match": match, "before": " " + match, "after": "", "required": [required], "only_if_present": False, } ) key = "JPSP_6_1b:A" first, second, third = [question(key, i) for i in range(3)] before = first.split(" (", 1)[0] scale = one(r"\(([^)]+)\)", first) second, third = second.split(" (", 1)[0], third.split(" (", 1)[0] adjective = scale.split()[-1] words = second.split() words[1] = adjective result["wording_corrections"].append( { "study_id": "JPSP_6_1b", "match": before, "before": before, "after": " ".join(words), "required": [scale, second, third], "only_if_present": True, } ) return result
"""Build population study definitions from authorized source prompts and human tables.
Question parsing and response-scale recovery preserve the published training
format. Statistical item mappings are read from source_readout.json; source
questionnaire text and human statistics are read from the provider files.
"""
from __future__ import annotations
import copy
import csv
import json
import math
import re
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable
JSON_BOILERPLATE_RE = re.compile(
"(?is)\\n*\\s*(?:your|you) answer\\s+(?:is\\s+)?in the form of json.*$"
)
ITEM_RE = re.compile(
"(?m)^\\s*(?:[-•\uf06c\uf0d8]\\s*)?\\(?(\\d{1,2})\\)?[.)]\\s*(?!=)"
)
BULLET_RE = re.compile("(?m)^\\s*[•\uf06c\uf0d8]\\s*(.+)$")
EXPLICIT_VALUE_RE = re.compile("(?<![\\w.])([+-]?\\d+(?:\\.\\d+)?)\\s*=")
RANGE_PATTERNS = (
re.compile(
"(?is)(-?\\d+(?:\\.\\d+)?)\\s*=.{0,160}?(?:to|;|,|and|—|–)\\s*(-?\\d+(?:\\.\\d+)?)\\s*="
),
re.compile(
"(?is)(?:scale\\s+)?(?:ranging\\s+|range\\s+)?(?:of\\s+on\\s+|of\\s+|on\\s+)?from\\s+(-?\\d+(?:\\.\\d+)?)\\s*(?:\\([^)]*\\))?\\s*(?:to|through|-)\\s*\\+?(-?\\d+(?:\\.\\d+)?)"
),
re.compile(
"(?is)(?:scale\\s+)?(?:ranging\\s+|range\\s+)(?:of\\s+on\\s+|of\\s+|on\\s+)?(-?\\d+(?:\\.\\d+)?)\\s*(?:\\([^)]*\\))?\\s*(?:to|through|-)\\s*\\+?(-?\\d+(?:\\.\\d+)?)"
),
re.compile(
"(?is)(?:on|using|with|of|from)\\s+(?:an?\\s+)?(\\d+)[- ]point\\s+(?:likert\\s+)?scale"
),
)
JEP1_BIPOLAR = {"JEP_1_1a", "JEP_1_1b", "JEP_1_3", "JEP_1_6a", "JEP_1_6b"}
def clean_source_material(prompts: list[str]) -> str:
text = "\n\n".join(prompts).replace("\r", "")
text = JSON_BOILERPLATE_RE.sub("", text)
text = re.sub(
"(?i)\\s+(?:and|&)\\s+(?:please\\s+)?(?:give|explain)\\s+(?:your|the)?\\s*(?:reason|reasons)(?:\\s+respectively)?",
"",
text,
)
text = re.sub("\\n{3,}", "\n\n", text).strip()
return text
def as_number(value: str) -> int | float:
number = float(value)
return int(number) if number.is_integer() else number
def find_ranges(text: str) -> list[tuple[int, int, int | float, int | float]]:
found: list[tuple[int, int, int | float, int | float]] = []
for pattern_index, pattern in enumerate(RANGE_PATTERNS):
for match in pattern.finditer(text):
if pattern_index == 3:
(low, high) = (1, as_number(match.group(1)))
else:
(low, high) = (as_number(match.group(1)), as_number(match.group(2)))
if low <= high:
found.append((match.start(), match.end(), low, high))
deduplicated: list[tuple[int, int, int | float, int | float]] = []
for candidate in sorted(found, key=lambda row: (row[0], row[1] - row[0])):
if any(
(
abs(candidate[0] - prior[0]) < 5 and candidate[2:] == prior[2:]
for prior in deduplicated
)
):
continue
deduplicated.append(candidate)
return sorted(deduplicated)
def item_segments(text: str, item_count: int) -> list[str]:
markers = list(ITEM_RE.finditer(text))
if len(markers) >= item_count:
markers = markers[-item_count:]
return [
text[
marker.start() : (
markers[index + 1].start()
if index + 1 < len(markers)
else len(text)
)
].strip()