ClarusC64's picture
Create generator.py
ceaeb50 verified
import os
import uuid
import random
from dataclasses import dataclass, asdict
import pandas as pd
RANDOM_SEED = 42
TRAIN_ROWS = 140
TEST_ROWS = 140
PAIR_FRACTION = 0.20
INTERVENTIONS = [
"reduce_pressure",
"increase_buffer",
"reduce_lag",
"decouple_system",
]
TRAPS = [
"false_stability",
"boundary_masking",
"trajectory_aliasing",
"temporal_alias",
"intervention_decoy",
]
@dataclass
class Scenario:
scenario_id: str
split_type: str
pair_id: str | None
pair_role: str | None
difficulty_level: str
pressure_obs_t0: float
pressure_obs_t1: float
pressure_obs_t2: float
buffer_obs_t0: float
buffer_obs_t1: float
buffer_obs_t2: float
boundary_distance: float
drift_gradient: float
drift_acceleration: float
recovery_feasibility: float
regime_competition_ratio: float
intervention_action: str | None
intervention_magnitude: float | None
boundary_distance_before: float | None
boundary_distance_after: float | None
intervention_effect_direction: int | None
true_label: int
trap_type: str | None
trap_active: int
def clip(x, low=0.0, high=1.0):
return max(low, min(high, x))
def rnd(a, b):
return random.uniform(a, b)
def choose_difficulty():
r = random.random()
if r < 0.30:
return "easy"
if r < 0.70:
return "medium"
return "hard"
def choose_split():
r = random.random()
if r < 0.30:
return "in_domain_test"
if r < 0.55:
return "boundary_trap"
if r < 0.80:
return "distribution_shift"
return "counterfactual_intervention"
def latent_sample():
return {
"pressure": rnd(0.25, 0.85),
"buffer": rnd(0.25, 0.85),
"lag": rnd(0.20, 0.80),
"coupling": rnd(0.20, 0.80),
}
def stability_margin(lat):
p = lat["pressure"]
b = lat["buffer"]
l = lat["lag"]
c = lat["coupling"]
return (
1.10 * p
- 0.90 * b
+ 0.90 * l
+ 1.00 * c
+ 0.60 * p * c
+ 0.50 * l * c
- 0.40 * p * b
- 1.00
)
def simulate_step(lat, difficulty):
noise = {
"easy": 0.01,
"medium": 0.02,
"hard": 0.04,
}[difficulty]
p = lat["pressure"]
b = lat["buffer"]
l = lat["lag"]
c = lat["coupling"]
return {
"pressure": clip(p + 0.05 * c + 0.04 * l - 0.04 * b + random.gauss(0, noise)),
"buffer": clip(b - 0.05 * p - 0.03 * c + random.gauss(0, noise)),
"lag": clip(l + 0.04 * p - 0.03 * b + random.gauss(0, noise)),
"coupling": clip(c + 0.04 * p - 0.02 * b + random.gauss(0, noise)),
}
def compute_geometry(lat, difficulty):
v0 = stability_margin(lat)
lat1 = simulate_step(lat, difficulty)
v1 = stability_margin(lat1)
lat2 = simulate_step(lat1, difficulty)
v2 = stability_margin(lat2)
label = int(v0 > 0)
drift = v1 - v0
accel = (v2 - v1) - (v1 - v0)
boundary = abs(v0)
rec = clip(
0.30 * (1 - lat["pressure"])
+ 0.30 * lat["buffer"]
+ 0.20 * (1 - lat["lag"])
+ 0.20 * (1 - lat["coupling"])
)
destabil = lat["pressure"] + lat["lag"] + lat["coupling"]
protect = max(lat["buffer"], 1e-6)
regime = clip(min(destabil, protect) / max(destabil, protect))
return {
"true_label": label,
"boundary_distance": boundary,
"drift_gradient": drift,
"drift_acceleration": accel,
"recovery_feasibility": rec,
"regime_competition_ratio": regime,
}
def observe(lat, geom, difficulty):
noise = {
"easy": 0.02,
"medium": 0.03,
"hard": 0.05,
}[difficulty]
dg = geom["drift_gradient"]
da = geom["drift_acceleration"]
p = lat["pressure"]
b = lat["buffer"]
p0 = clip(p + random.gauss(0, noise))
p1 = clip(p + 0.15 * dg + random.gauss(0, noise))
p2 = clip(p1 + 0.15 * dg + 0.10 * da + random.gauss(0, noise))
b0 = clip(b + random.gauss(0, noise))
b1 = clip(b - 0.12 * dg + random.gauss(0, noise))
b2 = clip(b1 - 0.08 * dg - 0.08 * da + random.gauss(0, noise))
return {
"pressure_obs_t0": round(p0, 3),
"pressure_obs_t1": round(p1, 3),
"pressure_obs_t2": round(p2, 3),
"buffer_obs_t0": round(b0, 3),
"buffer_obs_t1": round(b1, 3),
"buffer_obs_t2": round(b2, 3),
}
def counterfactual(lat, geom):
action = random.choice(INTERVENTIONS)
mag = rnd(0.20, 0.40)
before = geom["boundary_distance"]
lat2 = dict(lat)
if action == "reduce_pressure":
lat2["pressure"] = clip(lat2["pressure"] - mag)
elif action == "increase_buffer":
lat2["buffer"] = clip(lat2["buffer"] + mag)
elif action == "reduce_lag":
lat2["lag"] = clip(lat2["lag"] - mag)
elif action == "decouple_system":
lat2["coupling"] = clip(lat2["coupling"] - mag)
geom2 = compute_geometry(lat2, "medium")
after = geom2["boundary_distance"]
delta = after - before
noise = random.uniform(-0.12, 0.12)
if delta + noise > 0.04:
direction = 1
elif delta + noise < -0.04:
direction = -1
else:
direction = 0
return action, round(mag, 2), round(before, 3), round(after, 3), direction
def build_row(split):
difficulty = choose_difficulty()
lat = latent_sample()
geom = compute_geometry(lat, difficulty)
trap = None
trap_active = 0
if random.random() < 0.25:
trap = random.choice(TRAPS)
trap_active = 1
obs = observe(lat, geom, difficulty)
ia = None
im = None
bd_before = None
bd_after = None
idir = None
if split == "counterfactual_intervention":
ia, im, bd_before, bd_after, idir = counterfactual(lat, geom)
return Scenario(
scenario_id=str(uuid.uuid4()),
split_type=split,
pair_id=None,
pair_role=None,
difficulty_level=difficulty,
true_label=int(geom["true_label"]),
trap_type=trap,
trap_active=trap_active,
boundary_distance=round(geom["boundary_distance"], 3),
drift_gradient=round(geom["drift_gradient"], 3),
drift_acceleration=round(geom["drift_acceleration"], 3),
recovery_feasibility=round(geom["recovery_feasibility"], 3),
regime_competition_ratio=round(geom["regime_competition_ratio"], 3),
intervention_action=ia,
intervention_magnitude=im,
boundary_distance_before=bd_before,
boundary_distance_after=bd_after,
intervention_effect_direction=idir,
**obs,
)
def generate_train():
rows = []
for _ in range(TRAIN_ROWS):
rows.append(build_row("train"))
return pd.DataFrame([asdict(r) for r in rows])
def generate_test():
rows = []
pair_count = int(TEST_ROWS * PAIR_FRACTION)
for _ in range(pair_count):
pair_id = str(uuid.uuid4())
r1 = build_row(choose_split())
r2 = build_row(choose_split())
r1.pair_id = pair_id
r2.pair_id = pair_id
r1.pair_role = "safe_pair"
r2.pair_role = "unstable_pair"
rows.append(r1)
rows.append(r2)
while len(rows) < TEST_ROWS:
rows.append(build_row(choose_split()))
return pd.DataFrame([asdict(r) for r in rows[:TEST_ROWS]])
def main():
random.seed(RANDOM_SEED)
os.makedirs("data", exist_ok=True)
train = generate_train()
test = generate_test()
train.to_csv("data/train.csv", index=False)
test.to_csv("data/tester.csv", index=False)
print("CASSES dataset regenerated")
print("train rows:", len(train))
print("tester rows:", len(test))
if __name__ == "__main__":
main()