PREM BABU KANAPARTHI commited on
Commit
e7e1778
·
verified ·
1 Parent(s): c2a986c

Initial release: 204,520 agent-step records, 5 conditions, 6 scenarios

Browse files
README.md CHANGED
@@ -1,3 +1,247 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ tags:
6
+ - generative-agents
7
+ - emotion
8
+ - multi-agent
9
+ - simulation
10
+ - reinforcement-learning
11
+ - cognitive-science
12
+ - occ-theory
13
+ - predictive-processing
14
+ task_categories:
15
+ - reinforcement-learning
16
+ - text-classification
17
+ size_categories:
18
+ - 100K<n<1M
19
+ pretty_name: "Emotion Engine: Emergent Emotional Appraisal in Generative Agents"
20
+ ---
21
+
22
+ # Emotion Engine Dataset
23
+
24
+ **204,520 agent-step records** from a five-condition controlled experiment on emergent
25
+ emotional appraisal in generative agents.
26
+
27
+ > Paper: *Emergent Emotional Appraisal in Generative Agents via Predictive World Modeling*
28
+ > Author: Prem Babu Kanaparthi
29
+ > Code: [github.com/YOUR_USERNAME/emotion-engine](https://github.com/YOUR_USERNAME/emotion-engine)
30
+
31
+ ---
32
+
33
+ ## What This Dataset Is
34
+
35
+ Five emotion-engine architectures were compared in Ghost Town — a 12-agent survival
36
+ simulation across 6 scenario variants and 8 random seeds.
37
+
38
+ The central finding: **Condition D** (trained only to predict future world events)
39
+ independently rediscovers OCC cognitive appraisal signatures (fear, grief, suspicion)
40
+ with zero emotion rules, labels, or reward shaping.
41
+
42
+ Each record is one agent at one timestep: the full observation vector, emotion state,
43
+ latent representation, action taken, 12 future-event prediction probabilities,
44
+ and outcome metadata.
45
+
46
+ ---
47
+
48
+ ## Dataset Structure
49
+
50
+ ### Splits
51
+
52
+ | Split | Condition | Scenario | Seeds | Records |
53
+ |-------|-----------|----------|-------|---------|
54
+ | `baseline` | Baseline (no emotion) | all 6 | 0–7 | 40,907 |
55
+ | `condition_a` | Hand-coded OCC rules | all 6 | 0–7 | 40,921 |
56
+ | `condition_b` | Behavioral cloning | all 6 | 0–7 | 40,838 |
57
+ | `condition_c` | Emotion dynamics model | all 6 | 0–7 | 40,916 |
58
+ | `condition_d` | Predictive world modeling | all 6 | 0–7 | 40,938 |
59
+
60
+ **Total: 204,520 records**
61
+
62
+ ### Scenarios in Every Split
63
+
64
+ | Scenario | Primary OCC Signature | Description |
65
+ |----------|-----------------------|-------------|
66
+ | `standard_night` | Fear | 1 ghost per night, standard threat |
67
+ | `high_ghost_pressure` | Fear (extreme) | 3 simultaneous ghosts per night |
68
+ | `storm_scarcity` | Stress + Grief | Food supply reduced 70% by storm |
69
+ | `ally_death` | Grief | June Carter dies at step 1 (scripted) |
70
+ | `betrayal_refusal` | Suspicion | Rival pairs initialized with negative ties |
71
+ | `crowded_shelter` | Fear + Suspicion | Shelter capacity halved (6 slots / 12 agents) |
72
+
73
+ ---
74
+
75
+ ## Fields
76
+
77
+ Each record contains the following fields:
78
+
79
+ ### Identity
80
+ | Field | Type | Description |
81
+ |-------|------|-------------|
82
+ | `run_id` | string | Unique run identifier, e.g. `condition_d_standard_night_seed0_12-agent` |
83
+ | `step` | int | Timestep within run (0–71, 3 simulated days × 24 steps/day) |
84
+ | `agent_id` | string | Agent name (one of 12 fixed agents) |
85
+ | `condition` | string | `baseline_0`, `condition_a`, `condition_b`, `condition_c`, `condition_d` |
86
+ | `seed` | int | Random seed (0–7) |
87
+ | `scenario` | string | One of the 6 scenario variants |
88
+
89
+ ### Observation (14 dimensions)
90
+ | Field | Type | Description |
91
+ |-------|------|-------------|
92
+ | `obs_visible_ghosts` | int | Number of ghosts within sensor range |
93
+ | `obs_visible_deaths` | int | Number of ally deaths witnessed this step |
94
+ | `obs_nearby_allies` | int | Allies within 5 tiles |
95
+ | `obs_trusted_allies` | int | Allies with positive social tie nearby |
96
+ | `obs_supplies_seen` | int | Supply units visible |
97
+ | `obs_in_shelter` | bool | Agent is inside a safe building |
98
+ | `obs_nearest_refuge_distance` | float | Tiles to closest safe building |
99
+ | `obs_steps_since_ghost_seen` | int | Steps since last ghost sighting (capped at 20) |
100
+ | `obs_steps_since_ally_died` | int | Steps since last witnessed death (capped at 20) |
101
+ | `obs_steps_since_betrayal` | int | Steps since last betrayal received (capped at 20) |
102
+ | `obs_ally_deaths_witnessed` | int | Cumulative ally deaths witnessed |
103
+ | `obs_betrayals_received` | int | Cumulative betrayals received |
104
+ | `obs_average_trust` | float | Mean social tie value across all agents [−1, 1] |
105
+ | `obs_graph_tension` | float | Mean negative tie magnitude |
106
+
107
+ ### Emotion / Affect (Condition D only — zeros for others)
108
+ | Field | Type | Description |
109
+ |-------|------|-------------|
110
+ | `affect_fear` | float | Fear activation [0, 1] |
111
+ | `affect_grief` | float | Grief activation [0, 1] |
112
+ | `affect_trust` | float | Trust activation [0, 1] |
113
+ | `affect_stress` | float | Stress activation [0, 1] |
114
+ | `affect_relief` | float | Relief activation [0, 1] |
115
+ | `affect_suspicion` | float | Suspicion activation [0, 1] |
116
+
117
+ ### Latent Representation (8 dimensions)
118
+ | Field | Type | Description |
119
+ |-------|------|-------------|
120
+ | `latent_0` … `latent_7` | float | Internal learned representation (8-dim) |
121
+
122
+ ### Future-Event Predictions (Condition D only — zeros for others)
123
+ | Field | Type | Description |
124
+ |-------|------|-------------|
125
+ | `pred_ghost_nearby_t3` | float | P(ghost visible in 3 steps) |
126
+ | `pred_my_death_t5` | float | P(this agent dies in 5 steps) |
127
+ | `pred_health_drop_t3` | float | P(health decreases in 3 steps) |
128
+ | `pred_nearby_death_t5` | float | P(an ally dies in 5 steps) |
129
+ | `pred_help_success_t5` | float | P(help action succeeds in 5 steps) |
130
+ | `pred_refusal_received_t5` | float | P(refusal received in 5 steps) |
131
+ | `pred_tie_increase_t5` | float | P(social tie increases in 5 steps) |
132
+ | `pred_shelter_achieved_t2` | float | P(agent in shelter in 2 steps) |
133
+ | `pred_storm_onset_t3` | float | P(storm starts in 3 steps) |
134
+ | `pred_scarcity_t5` | float | P(supply scarcity in 5 steps) |
135
+ | `pred_graph_tension_t3` | float | P(social tension increases in 3 steps) |
136
+ | `pred_valence_t5` | float | P(positive valence in 5 steps) |
137
+
138
+ ### Action & Outcome
139
+ | Field | Type | Description |
140
+ |-------|------|-------------|
141
+ | `action` | string | Action taken: `hide`, `gather_supplies`, `seek_safe_house`, `seek_hospital`, `refuse_help`, `warn`, `patrol` |
142
+ | `goal` | string | Agent goal state at this step |
143
+ | `reward_survival` | float | Survival reward component |
144
+ | `reward_shelter` | float | Shelter reward component |
145
+ | `reward_health` | float | Health reward component |
146
+ | `reward_social` | float | Social reward component |
147
+ | `total_reward` | float | Sum of reward components |
148
+ | `alive` | bool | Agent survived this step |
149
+ | `health` | float | Health percentage (0–100) |
150
+ | `sheltered` | bool | Agent is in a safe building |
151
+ | `time_of_day` | string | `day`, `dusk`, `night`, `dawn` |
152
+
153
+ ---
154
+
155
+ ## Loading the Dataset
156
+
157
+ ### With the `datasets` library (recommended)
158
+
159
+ ```python
160
+ from datasets import load_dataset
161
+
162
+ # Load a specific condition
163
+ ds = load_dataset("YOUR_USERNAME/emotion-engine", "condition_d")
164
+
165
+ # Load all conditions
166
+ ds = load_dataset("YOUR_USERNAME/emotion-engine", "all")
167
+
168
+ # Filter to a specific scenario
169
+ night_only = ds["train"].filter(lambda x: x["scenario"] == "standard_night")
170
+
171
+ # Filter to ghost-present steps
172
+ threat_steps = ds["train"].filter(lambda x: x["obs_visible_ghosts"] > 0)
173
+ ```
174
+
175
+ ### Reproduce the Fear→Shelter result
176
+
177
+ ```python
178
+ from datasets import load_dataset
179
+ import numpy as np
180
+ from scipy.stats import fisher_exact
181
+
182
+ ds = load_dataset("YOUR_USERNAME/emotion-engine", "condition_d", split="train")
183
+ df = ds.to_pandas()
184
+
185
+ ghost_present = df[df["obs_visible_ghosts"] > 0]
186
+ ghost_absent = df[df["obs_visible_ghosts"] == 0]
187
+
188
+ shelter_given_ghost = (ghost_present["action"] == "seek_safe_house").mean()
189
+ shelter_given_no_ghost = (ghost_absent["action"] == "seek_safe_house").mean()
190
+
191
+ # Contingency table
192
+ a = (ghost_present["action"] == "seek_safe_house").sum()
193
+ b = (ghost_present["action"] != "seek_safe_house").sum()
194
+ c = (ghost_absent["action"] == "seek_safe_house").sum()
195
+ d = (ghost_absent["action"] != "seek_safe_house").sum()
196
+
197
+ _, p = fisher_exact([[a, b], [c, d]])
198
+ print(f"Ghost present → shelter: {shelter_given_ghost:.1%}")
199
+ print(f"Ghost absent → shelter: {shelter_given_no_ghost:.1%}")
200
+ print(f"Fisher p = {p:.2e}")
201
+ # Expected: Ghost present → shelter: 99.0%, p = 3.3e-113
202
+ ```
203
+
204
+ ### Reproduce the Suspicion Decay result
205
+
206
+ ```python
207
+ from datasets import load_dataset
208
+
209
+ ds = load_dataset("YOUR_USERNAME/emotion-engine", "condition_d", split="train")
210
+ df = ds.to_pandas()
211
+
212
+ refusals = df[df["action"] == "refuse_help"].copy()
213
+
214
+ def bucket(steps):
215
+ if steps <= 5: return "recent"
216
+ if steps <= 10: return "fading"
217
+ return "forgotten"
218
+
219
+ refusals["bucket"] = refusals["obs_steps_since_betrayal"].apply(bucket)
220
+ all_social = df.copy()
221
+ all_social["bucket"] = all_social["obs_steps_since_betrayal"].apply(bucket)
222
+
223
+ for b in ["recent", "fading", "forgotten"]:
224
+ denom = (all_social["bucket"] == b).sum()
225
+ numer = ((refusals["bucket"] == b)).sum()
226
+ print(f"{b}: {numer/denom:.1%} refusal rate")
227
+ # Expected: recent 64.6%, fading 4.5%, forgotten 35.2%
228
+ ```
229
+
230
+ ---
231
+
232
+ ## Citation
233
+
234
+ ```bibtex
235
+ @article{kanaparthi2026emotion,
236
+ author = {Kanaparthi, Prem Babu},
237
+ title = {Emergent Emotional Appraisal in Generative Agents
238
+ via Predictive World Modeling},
239
+ year = {2026},
240
+ }
241
+ ```
242
+
243
+ ---
244
+
245
+ ## License
246
+
247
+ MIT License.
data/baseline_0.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d8bd4624a6b1d27e7c9e8d5813c4c8716a52d7a3c2c6a47c40cade206bd504f
3
+ size 147175
data/condition_a.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5923d50273086b87927391fa039bf16962285ff44cf6fb46146f54c36d585312
3
+ size 245422
data/condition_b.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:70327994ffd8913affd19a478f7e0994d4f6178474b881db5a2a4608a77e8594
3
+ size 524093
data/condition_c.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f97b09d36f038be0ed962b4a9d722a9eb01db97bf40748badff05ab0ab348ed
3
+ size 291733
data/condition_d.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae82fbbc1b9fe50df5b766f0d8ac707c0970296697809946a5a10047303f5f35
3
+ size 647790
emotion_engine.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ emotion_engine.py — HuggingFace Datasets loading script
3
+
4
+ Registered as the dataset builder for the emotion-engine HF repo.
5
+ Supports loading by condition name or "all" for the full dataset.
6
+
7
+ Usage:
8
+ from datasets import load_dataset
9
+
10
+ # Single condition
11
+ ds = load_dataset("YOUR_USERNAME/emotion-engine", "condition_d")
12
+
13
+ # All conditions concatenated
14
+ ds = load_dataset("YOUR_USERNAME/emotion-engine", "all")
15
+ """
16
+
17
+ import datasets
18
+
19
+ _CITATION = """
20
+ @article{kanaparthi2026emotion,
21
+ author = {Kanaparthi, Prem Babu},
22
+ title = {Emergent Emotional Appraisal in Generative Agents
23
+ via Predictive World Modeling},
24
+ year = {2026},
25
+ }
26
+ """
27
+
28
+ _DESCRIPTION = """
29
+ 204,520 agent-step records from a five-condition controlled experiment comparing
30
+ emotion-engine architectures in a 12-agent ghost-survival simulation (Ghost Town).
31
+
32
+ Five conditions:
33
+ baseline_0 — no emotion system
34
+ condition_a — hand-coded OCC appraisal rules
35
+ condition_b — behavioral cloning from condition_a
36
+ condition_c — emotion dynamics model
37
+ condition_d — predictive world modeling (proposed)
38
+
39
+ Six scenarios per condition:
40
+ standard_night, high_ghost_pressure, storm_scarcity,
41
+ ally_death, betrayal_refusal, crowded_shelter
42
+
43
+ 8 random seeds per scenario.
44
+
45
+ Each record contains: full 14-dim observation, 6-dim emotion vector,
46
+ 8-dim latent representation, 12 future-event predictions (Condition D),
47
+ action taken, and outcome metadata.
48
+ """
49
+
50
+ _HOMEPAGE = "https://github.com/YOUR_USERNAME/emotion-engine"
51
+ _LICENSE = "MIT"
52
+
53
+ _CONDITIONS = [
54
+ "baseline_0",
55
+ "condition_a",
56
+ "condition_b",
57
+ "condition_c",
58
+ "condition_d",
59
+ ]
60
+
61
+ _FEATURES = datasets.Features({
62
+ # Identity
63
+ "run_id": datasets.Value("string"),
64
+ "step": datasets.Value("int32"),
65
+ "agent_id": datasets.Value("string"),
66
+ "condition": datasets.Value("string"),
67
+ "seed": datasets.Value("int32"),
68
+ "scenario": datasets.Value("string"),
69
+
70
+ # Observation (14 dims)
71
+ "obs_visible_ghosts": datasets.Value("int32"),
72
+ "obs_visible_deaths": datasets.Value("int32"),
73
+ "obs_nearby_allies": datasets.Value("int32"),
74
+ "obs_trusted_allies": datasets.Value("int32"),
75
+ "obs_supplies_seen": datasets.Value("int32"),
76
+ "obs_in_shelter": datasets.Value("bool"),
77
+ "obs_nearest_refuge_distance": datasets.Value("float32"),
78
+ "obs_steps_since_ghost_seen": datasets.Value("int32"),
79
+ "obs_steps_since_ally_died": datasets.Value("int32"),
80
+ "obs_steps_since_betrayal": datasets.Value("int32"),
81
+ "obs_ally_deaths_witnessed": datasets.Value("int32"),
82
+ "obs_betrayals_received": datasets.Value("int32"),
83
+ "obs_average_trust": datasets.Value("float32"),
84
+ "obs_graph_tension": datasets.Value("float32"),
85
+
86
+ # Affect / emotion
87
+ "affect_fear": datasets.Value("float32"),
88
+ "affect_grief": datasets.Value("float32"),
89
+ "affect_trust": datasets.Value("float32"),
90
+ "affect_stress": datasets.Value("float32"),
91
+ "affect_relief": datasets.Value("float32"),
92
+ "affect_suspicion": datasets.Value("float32"),
93
+
94
+ # Latent representation (8 dims)
95
+ "latent_0": datasets.Value("float32"),
96
+ "latent_1": datasets.Value("float32"),
97
+ "latent_2": datasets.Value("float32"),
98
+ "latent_3": datasets.Value("float32"),
99
+ "latent_4": datasets.Value("float32"),
100
+ "latent_5": datasets.Value("float32"),
101
+ "latent_6": datasets.Value("float32"),
102
+ "latent_7": datasets.Value("float32"),
103
+
104
+ # Future-event predictions (Condition D; zero for others)
105
+ "pred_ghost_nearby_t3": datasets.Value("float32"),
106
+ "pred_my_death_t5": datasets.Value("float32"),
107
+ "pred_health_drop_t3": datasets.Value("float32"),
108
+ "pred_nearby_death_t5": datasets.Value("float32"),
109
+ "pred_help_success_t5": datasets.Value("float32"),
110
+ "pred_refusal_received_t5": datasets.Value("float32"),
111
+ "pred_tie_increase_t5": datasets.Value("float32"),
112
+ "pred_shelter_achieved_t2": datasets.Value("float32"),
113
+ "pred_storm_onset_t3": datasets.Value("float32"),
114
+ "pred_scarcity_t5": datasets.Value("float32"),
115
+ "pred_graph_tension_t3": datasets.Value("float32"),
116
+ "pred_valence_t5": datasets.Value("float32"),
117
+
118
+ # Action & outcome
119
+ "action": datasets.Value("string"),
120
+ "goal": datasets.Value("string"),
121
+ "reward_survival": datasets.Value("float32"),
122
+ "reward_shelter": datasets.Value("float32"),
123
+ "reward_health": datasets.Value("float32"),
124
+ "reward_social": datasets.Value("float32"),
125
+ "total_reward": datasets.Value("float32"),
126
+ "alive": datasets.Value("bool"),
127
+ "health": datasets.Value("float32"),
128
+ "sheltered": datasets.Value("bool"),
129
+ "time_of_day": datasets.Value("string"),
130
+ })
131
+
132
+
133
+ class EmotionEngineConfig(datasets.BuilderConfig):
134
+ def __init__(self, condition="all", **kwargs):
135
+ super().__init__(**kwargs)
136
+ self.condition = condition
137
+
138
+
139
+ class EmotionEngine(datasets.GeneratorBasedBuilder):
140
+ """Ghost Town emotion engine dataset — 204,520 agent-step records."""
141
+
142
+ VERSION = datasets.Version("1.0.0")
143
+
144
+ BUILDER_CONFIG_CLASS = EmotionEngineConfig
145
+
146
+ BUILDER_CONFIGS = [
147
+ EmotionEngineConfig(
148
+ name="all",
149
+ version=VERSION,
150
+ description="All five conditions concatenated (204,520 records)",
151
+ condition="all",
152
+ ),
153
+ ] + [
154
+ EmotionEngineConfig(
155
+ name=c,
156
+ version=VERSION,
157
+ description=f"Condition {c} only (~40k records, 6 scenarios, 8 seeds)",
158
+ condition=c,
159
+ )
160
+ for c in _CONDITIONS
161
+ ]
162
+
163
+ DEFAULT_CONFIG_NAME = "condition_d"
164
+
165
+ def _info(self):
166
+ return datasets.DatasetInfo(
167
+ description=_DESCRIPTION,
168
+ features=_FEATURES,
169
+ homepage=_HOMEPAGE,
170
+ license=_LICENSE,
171
+ citation=_CITATION,
172
+ )
173
+
174
+ def _split_generators(self, dl_manager):
175
+ if self.config.condition == "all":
176
+ files = {
177
+ c: dl_manager.download(f"data/{c}.parquet")
178
+ for c in _CONDITIONS
179
+ }
180
+ return [
181
+ datasets.SplitGenerator(
182
+ name=datasets.Split.TRAIN,
183
+ gen_kwargs={"filepaths": list(files.values())},
184
+ )
185
+ ]
186
+ else:
187
+ filepath = dl_manager.download(
188
+ f"data/{self.config.condition}.parquet"
189
+ )
190
+ return [
191
+ datasets.SplitGenerator(
192
+ name=datasets.Split.TRAIN,
193
+ gen_kwargs={"filepaths": [filepath]},
194
+ )
195
+ ]
196
+
197
+ def _generate_examples(self, filepaths):
198
+ import pandas as pd
199
+ idx = 0
200
+ for path in filepaths:
201
+ df = pd.read_parquet(path)
202
+ for _, row in df.iterrows():
203
+ yield idx, row.to_dict()
204
+ idx += 1
export_to_parquet.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ export_to_parquet.py
3
+ ====================
4
+ Converts raw Ghost Town simulation outputs into clean Parquet files
5
+ ready for upload to Hugging Face Datasets.
6
+
7
+ Usage:
8
+ python export_to_parquet.py \
9
+ --source path/to/outputs/proof_all_scenarios \
10
+ --out path/to/emotion-engine-dataset/data
11
+
12
+ Output:
13
+ data/
14
+ baseline_0.parquet
15
+ condition_a.parquet
16
+ condition_b.parquet
17
+ condition_c.parquet
18
+ condition_d.parquet
19
+
20
+ Each Parquet file is one condition split (~40k rows).
21
+ Total size after compression: ~30-50 MB.
22
+ """
23
+
24
+ import argparse
25
+ import json
26
+ import os
27
+ import glob
28
+ import pandas as pd
29
+ from pathlib import Path
30
+
31
+
32
+ CONDITION_NAMES = [
33
+ "baseline_0",
34
+ "condition_a",
35
+ "condition_b",
36
+ "condition_c",
37
+ "condition_d",
38
+ ]
39
+
40
+
41
+ def flatten_record(r: dict) -> dict:
42
+ """Flatten one JSONL record into a single-level dict."""
43
+ obs = r.get("observation", {})
44
+ sc = r.get("social_context", {})
45
+ aff = r.get("affect", r.get("affect_vector", {}))
46
+ lat = r.get("latent", [0.0] * 8)
47
+ prd = r.get("predictions", {})
48
+ rew = r.get("reward_components", {})
49
+ meta = r.get("metadata", {})
50
+
51
+ row = {
52
+ # Identity
53
+ "run_id": r.get("run_id", ""),
54
+ "step": int(r.get("step", 0)),
55
+ "agent_id": r.get("agent_id", ""),
56
+ "condition": r.get("condition", ""),
57
+ "seed": int(r.get("seed", 0)),
58
+ "scenario": meta.get("scenario", r.get("scenario", "")),
59
+
60
+ # Observation (14 dims)
61
+ "obs_visible_ghosts": int(obs.get("visible_ghosts", 0)),
62
+ "obs_visible_deaths": int(obs.get("visible_deaths", 0)),
63
+ "obs_nearby_allies": int(obs.get("nearby_allies", 0)),
64
+ "obs_trusted_allies": int(obs.get("trusted_allies", 0)),
65
+ "obs_supplies_seen": int(obs.get("supplies_seen", 0)),
66
+ "obs_in_shelter": bool(obs.get("in_shelter", False)),
67
+ "obs_nearest_refuge_distance": float(obs.get("nearest_refuge_distance", 0)),
68
+ "obs_steps_since_ghost_seen": int(obs.get("steps_since_ghost_seen", 20)),
69
+ "obs_steps_since_ally_died": int(obs.get("steps_since_ally_died", 20)),
70
+ "obs_steps_since_betrayal": int(obs.get("steps_since_betrayal", 20)),
71
+ "obs_ally_deaths_witnessed": int(obs.get("ally_deaths_witnessed", 0)),
72
+ "obs_betrayals_received": int(obs.get("betrayals_received", 0)),
73
+ "obs_average_trust": float(sc.get("average_trust", 0.0)),
74
+ "obs_graph_tension": float(sc.get("graph_tension", 0.0)),
75
+
76
+ # Affect / emotion vector
77
+ "affect_fear": float(aff.get("fear", 0.0)),
78
+ "affect_grief": float(aff.get("grief", 0.0)),
79
+ "affect_trust": float(aff.get("trust", 0.0)),
80
+ "affect_stress": float(aff.get("stress", 0.0)),
81
+ "affect_relief": float(aff.get("relief", 0.0)),
82
+ "affect_suspicion": float(aff.get("suspicion", 0.0)),
83
+
84
+ # Latent representation (8 dims)
85
+ **{f"latent_{i}": float(lat[i]) if i < len(lat) else 0.0
86
+ for i in range(8)},
87
+
88
+ # Future-event predictions (Condition D)
89
+ "pred_ghost_nearby_t3": float(prd.get("ghost_nearby_t3", 0.0)),
90
+ "pred_my_death_t5": float(prd.get("my_death_t5", 0.0)),
91
+ "pred_health_drop_t3": float(prd.get("health_drop_t3", 0.0)),
92
+ "pred_nearby_death_t5": float(prd.get("nearby_death_t5", 0.0)),
93
+ "pred_help_success_t5": float(prd.get("help_success_t5", 0.0)),
94
+ "pred_refusal_received_t5": float(prd.get("refusal_received_t5", 0.0)),
95
+ "pred_tie_increase_t5": float(prd.get("tie_increase_t5", 0.0)),
96
+ "pred_shelter_achieved_t2": float(prd.get("shelter_achieved_t2", 0.0)),
97
+ "pred_storm_onset_t3": float(prd.get("storm_onset_t3", 0.0)),
98
+ "pred_scarcity_t5": float(prd.get("scarcity_t5", 0.0)),
99
+ "pred_graph_tension_t3": float(prd.get("graph_tension_increase_t3",
100
+ prd.get("graph_tension_t3", 0.0))),
101
+ "pred_valence_t5": float(prd.get("valence_t5", 0.0)),
102
+
103
+ # Action & outcome
104
+ "action": r.get("action", ""),
105
+ "goal": r.get("goal", ""),
106
+ "reward_survival": float(rew.get("survival", 0.0)),
107
+ "reward_shelter": float(rew.get("shelter", 0.0)),
108
+ "reward_health": float(rew.get("health", 0.0)),
109
+ "reward_social": float(rew.get("social", 0.0)),
110
+ "total_reward": float(r.get("total_reward", 0.0)),
111
+ "alive": bool(meta.get("alive", True)),
112
+ "health": float(meta.get("health", 100.0)),
113
+ "sheltered": bool(meta.get("sheltered", False)),
114
+ "time_of_day": meta.get("time_of_day", ""),
115
+ }
116
+ return row
117
+
118
+
119
+ def load_run(jsonl_path: str) -> list[dict]:
120
+ records = []
121
+ with open(jsonl_path, encoding="utf-8") as f:
122
+ for line in f:
123
+ line = line.strip()
124
+ if not line:
125
+ continue
126
+ try:
127
+ records.append(flatten_record(json.loads(line)))
128
+ except Exception as e:
129
+ print(f" Warning: skipped malformed record in {jsonl_path}: {e}")
130
+ return records
131
+
132
+
133
+ def export(source_dir: str, out_dir: str):
134
+ source_dir = Path(source_dir)
135
+ out_dir = Path(out_dir)
136
+ out_dir.mkdir(parents=True, exist_ok=True)
137
+
138
+ # Group run folders by condition
139
+ all_runs = sorted(source_dir.glob("*/training_records.jsonl"))
140
+ if not all_runs:
141
+ raise FileNotFoundError(
142
+ f"No training_records.jsonl found under {source_dir}.\n"
143
+ "Make sure --source points to the batch output directory."
144
+ )
145
+
146
+ by_condition: dict[str, list] = {c: [] for c in CONDITION_NAMES}
147
+
148
+ for jsonl_path in all_runs:
149
+ run_name = jsonl_path.parent.name # e.g. condition_d_standard_night_seed0_12-agent
150
+ matched = None
151
+ for cname in CONDITION_NAMES:
152
+ if run_name.startswith(cname):
153
+ matched = cname
154
+ break
155
+ if matched is None:
156
+ print(f" Skipping unrecognised run: {run_name}")
157
+ continue
158
+
159
+ print(f" Loading {run_name} …", end=" ", flush=True)
160
+ rows = load_run(str(jsonl_path))
161
+ by_condition[matched].extend(rows)
162
+ print(f"{len(rows)} records")
163
+
164
+ print()
165
+ for cname, rows in by_condition.items():
166
+ if not rows:
167
+ print(f" No records for {cname} — skipping")
168
+ continue
169
+ df = pd.DataFrame(rows)
170
+ out_path = out_dir / f"{cname}.parquet"
171
+ df.to_parquet(out_path, index=False, compression="snappy")
172
+ size_mb = out_path.stat().st_size / 1e6
173
+ print(f" {cname:15s} {len(df):>7,} records -> {out_path.name} ({size_mb:.1f} MB)")
174
+
175
+ print(f"\nAll splits written to {str(out_dir)}/")
176
+
177
+
178
+ if __name__ == "__main__":
179
+ parser = argparse.ArgumentParser(description="Export Ghost Town outputs to Parquet for HuggingFace.")
180
+ parser.add_argument("--source", required=True,
181
+ help="Path to batch output directory (e.g. outputs/proof_all_scenarios)")
182
+ parser.add_argument("--out", default="data",
183
+ help="Output directory for Parquet files (default: data/)")
184
+ args = parser.parse_args()
185
+ export(args.source, args.out)