File size: 11,432 Bytes
81b8593 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | """Deterministic standalone exporter. Python 3.10+, standard library only."""
import json
from pathlib import Path
BASE = Path(__file__).resolve().parents[1]
SNAPSHOT = json.loads((BASE / 'source/snapshot.json').read_text(encoding='utf-8'))
IDS = [s['id'] for s in SNAPSHOT['dimensions']]
def classify(scores):
ranked = sorted(scores, key=lambda s: -s['value']) # stable source order
top = ranked[0]['value']
if all(s['value'] < 25 for s in scores):
return {'title': 'A quieter side', 'leaders': []}
if all(s['value'] >= 75 for s in scores):
return {'title': 'Many sides, strongly felt', 'leaders': []}
if top - ranked[-1]['value'] <= 12.5:
return {'title': 'An even constellation', 'leaders': []}
if top < 50:
return {'title': 'No strong leading side', 'leaders': []}
leaders = [s['id'] for s in ranked if top - s['value'] <= 6.25]
return {'title': 'A little more complex' if len(leaders) > 2 else ' + '.join(x.title() for x in leaders), 'leaders': leaders}
def score(items, answers, minimum):
scores, ranges = [], []
for sid in IDS:
group = [q for q in items if q['dimension_id'] == sid]
values = [4-answers[q['question_id']] if q['reverse'] else answers[q['question_id']]
for q in group if type(answers.get(q['question_id'])) is int and 0 <= answers[q['question_id']] <= 4]
count, total = len(values), sum(values)
scores.append({'id': sid, 'value': total/count*25 if count else 0, 'count': count})
ranges.append({'id': sid, 'low': total/len(group)*25,
'high': (total+4*(len(group)-count))/len(group)*25})
coverage = all(s['count'] >= minimum for s in scores)
checked = changed = 0
profile = classify(scores)
if coverage:
for q in items:
raw = answers.get(q['question_id'])
if type(raw) is not int or not 0 <= raw <= 4:
continue
for delta in [-1, 1]:
if 0 <= raw+delta <= 4:
candidate = [dict(s) for s in scores]
j = IDS.index(q['dimension_id'])
# Recompute the affected mean, preserving JS arithmetic order.
group = [x for x in items if x['dimension_id'] == q['dimension_id']]
changed_answers = {**answers, q['question_id']: raw+delta}
vals = [4-changed_answers[x['question_id']] if x['reverse'] else changed_answers[x['question_id']]
for x in group if type(changed_answers.get(x['question_id'])) is int and 0 <= changed_answers[x['question_id']] <= 4]
candidate[j]['value'] = sum(vals)/len(vals)*25
checked += 1
changed += classify(candidate)['title'] != profile['title']
top = max(s['value'] for s in scores)
tied = [s for s in scores if abs(s['value']-top) < 1e-8]
character_id = 'quiet' if top == 0 else tied[0]['id'] if len(tied) == 1 else 'balanced' if profile['title'] in ['An even constellation', 'No strong leading side'] else 'mixed'
character = {'id': character_id, 'name': SNAPSHOT['characters'][character_id]['name'],
'title': character_id.title() if character_id in IDS else 'Drama-free' if character_id == 'quiet' else 'A glorious mix'}
return {'scores': scores, 'computed_profile': profile, 'computed_character':character, 'coverage_complete': coverage,
'possible_completed_ranges': ranges, 'sensitivity': {'checked': checked, 'changed': changed}}
def write_jsonl(name, rows):
target = BASE / 'data' / f'{name}.jsonl'
target.parent.mkdir(exist_ok=True)
target.write_text(''.join(json.dumps(row, ensure_ascii=False, separators=(',', ':'), allow_nan=False)+'\n' for row in rows), encoding='utf-8', newline='\n')
def build():
taxonomy = [dict(s, character_name=SNAPSHOT['characters'][s['id']]['name'], source_path='src/shared/quiz/quiz.ts') for s in SNAPSHOT['dimensions']]
rules = [
('answer-domain', 'input', 'integer 0 through 4; null is an addressed skip', 'Exclude missing or invalid values from means.'),
('direct', 'item', 'reverse == false', 'adjusted = raw'),
('reverse', 'item', 'reverse == true', 'adjusted = 4 - raw'),
('mean', 'dimension', 'count > 0', 'value = sum(adjusted) / count * 25; preserve precision'),
('empty', 'dimension', 'count == 0', 'value = 0; count = 0; not an observed low tendency'),
('quiet', 'classification', 'all values < 25', 'A quieter side'),
('broad', 'classification', 'all values >= 75', 'Many sides, strongly felt'),
('even', 'classification', 'max - min <= 12.5', 'An even constellation'),
('weak', 'classification', 'max < 50', 'No strong leading side'),
('leaders', 'classification', 'otherwise', 'Select every dimension within 6.25 of max; stable descending sort'),
('complex', 'classification', 'more than two selected leaders', 'A little more complex; retain all leader IDs'),
('coverage', 'eligibility', 'quick >= 2; full >= 8 usable answers per dimension', 'Require every dimension to reach its minimum'),
('full-visited', 'eligibility', 'full mode', 'Also require all 70 questions addressed; null counts as addressed'),
('range', 'explanation', 'N items; n usable; adjusted sum S', 'low = S/N*25; high = (S+4*(N-n))/N*25; not confidence intervals'),
('sensitivity', 'explanation', 'coverage complete', 'Change each valid raw answer by one permitted step separately; count title changes, not probabilities'),
('character', 'presentation', 'zero maximum -> quiet; unique exact maximum -> dimension; otherwise title mapping', 'UI character uses exact top ties (tolerance 1e-8), separately from the analytical 6.25 leader window'),
]
rules = [{'id': rid, 'position': i+1, 'scope': scope, 'condition': cond, 'action': action,
'source_path': 'src/shared/quiz/characters.ts' if rid == 'character' else 'src/components/seven-sides/FullTest.tsx' if rid == 'full-visited' else 'src/shared/quiz/analysis.ts' if rid in ['range','sensitivity'] else 'src/shared/quiz/full-quiz.ts' if rid == 'coverage' else 'src/shared/quiz/quiz.ts',
'classification_precedence': ['quiet','broad','even','weak','leaders','complex'].index(rid)+1 if rid in ['quiet','broad','even','weak','leaders','complex'] else 0}
for i, (rid, scope, cond, action) in enumerate(rules)]
cases = []
for mode in SNAPSHOT['modes']:
items = [q for q in SNAPSHOT['questions'] if q['mode'] == mode['id']]
def fixture(values):
return {q['question_id']: 4-values[IDS.index(q['dimension_id'])] if q['reverse'] else values[IDS.index(q['dimension_id'])] for q in items}
def add(name, purpose, answers):
out = score(items, answers, mode['minimum'])
addressed = sum(q['question_id'] in answers for q in items)
cases.append({'id': f"{mode['id']}:{name}", 'mode': mode['id'], 'version': mode['version'],
'purpose': purpose, 'synthetic': True,
'answers': [{'question_id': q['question_id'], 'raw': answers[q['question_id']]} for q in items if q['question_id'] in answers],
'addressed_count': addressed, 'minimum_per_dimension': mode['minimum'],
**out, 'result_eligible': out['coverage_complete'] and (mode['id'] == 'quick' or addressed == len(items))})
for value in range(5):
add(f'adjusted-uniform-{value}', 'Uniform adjusted response; exercises low, even or broad classification.', fixture([value]*7))
for j, sid in enumerate(IDS):
values = [1]*7
values[j] = 4
add(f'leader-{sid}', 'Each dimension can be a unique leader.', fixture(values))
values[(j+1) % 7] = 4
add(f'tie-{sid}-{IDS[(j+1)%7]}', 'Two equal leaders retain taxonomy order.', fixture(values))
add('three-leaders', 'More than two leaders has a descriptive complex title.', fixture([4,4,4,1,1,1,1]))
add('no-strong-leader', 'Uneven scores can remain below the leading threshold.', fixture([1,0,0,0,0,0,0]))
for value in range(5):
if value == 2: # midpoint already represented by adjusted-uniform-2
continue
a = fixture([2]*7)
a[items[0]['question_id']] = value
add(f'direct-sweep-{value}', 'Direct item sensitivity across the entire response scale.', a)
a = fixture([2]*7)
a[next(q['question_id'] for q in items if q['reverse'])] = value
add(f'reverse-sweep-{value}', 'Reverse item sensitivity across the entire response scale.', a)
a = fixture([2]*7)
pride = [q for q in items if q['dimension_id'] == 'pride']
a[pride[0]['question_id']] = 4
a[pride[1]['question_id']] = 0
add('same-mean-mixed', 'Same mean as midpoint responses; different item evidence.', a)
a = fixture([2]*7)
for sid in IDS:
group = [q for q in items if q['dimension_id'] == sid]
for q in group[mode['minimum']:]:
a[q['question_id']] = None
add('minimum-with-skips', 'Exactly sufficient coverage in every group; missing-answer ranges.', a)
a[items[0]['question_id']] = None
add('below-minimum', 'One dimension lacks coverage; no eligible result or sensitivity checks.', a)
a = fixture([2]*7)
del a[pride[-1]['question_id']]
add('unaddressed', 'Distinguish an omitted question from an explicit null skip.', a)
add('empty', 'Zero placeholder scores never constitute an eligible observed profile.', {})
add('all-skipped', 'All questions addressed but no usable responses.', {q['question_id']:None for q in items})
if mode['id'] == 'quick':
add('website-sample', 'Existing website sample, not a real respondent.', SNAPSHOT['sample_answers'])
classifier = []
vectors = [
('below-25', [24.999]*7), ('at-25', [25]*7),
('below-75', [74.999]*7), ('at-75', [75]*7),
('spread-at-12-5', [62.5,50,50,50,50,50,50]),
('spread-above-12-5', [62.501,50,50,50,50,50,50]),
('top-below-50', [49.999,0,0,0,0,0,0]), ('top-at-50', [50,0,0,0,0,0,0]),
('tie-at-6-25', [75,68.75,0,0,0,0,0]), ('tie-outside-6-25', [75,68.749,0,0,0,0,0]),
('stable-source-order', [0,80,80,0,0,0,0]), ('three-leaders', [80,80,80,0,0,0,0]),
('quiet-before-even', [10]*7), ('broad-before-even', [90]*7),
]
for name, values in vectors:
scores = [{'id':sid,'value':value,'count':0} for sid,value in zip(IDS, values)]
classifier.append({'id': f'classifier:{name}', 'synthetic':True, 'input_space':'arbitrary_score_vectors_not_questionnaire_attempts',
'scores': scores, 'expected_profile': classify(scores)})
return {'taxonomy':taxonomy, 'questions':SNAPSHOT['questions'], 'rules':rules, 'scoring_cases':cases, 'classification_cases':classifier}
if __name__ == '__main__':
from schema_types import DOCUMENT
for name, rows in build().items():
write_jsonl(name, rows)
print(f'{name}: {len(rows)} rows')
(BASE / 'schema.json').write_text(json.dumps(DOCUMENT, indent=2)+'\n', encoding='utf-8', newline='\n')
|