File size: 3,713 Bytes
100c616
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Simulate a realistic 'arrival stream' for the cleaning demo.

Takes the (clean) 2024 silver facts for all four vehicles, then plants the
faults a real sensor feed produces: missing readings, out-of-bound values,
unit mix-ups, and duplicate retries. Deterministic (seed 7). Output plus an
exact fault census go to silver-checkable CSV + JSON so the instructor has
an answer key: after cleaning, row and fault counts must match.
"""
import csv, json, random, os
BASE = os.path.expanduser("~/presentations/data/ev_enriched")
random.seed(7)

# ---- load 2024 rows from all profiles (the "clean truth" we corrupt) ----
truth = []
for prof in ["rare_user", "moderate_user", "daily_user", "heavy_user"]:
    with open(f"{BASE}/silver/fact_telemetry_{prof}.csv") as f:
        for r in csv.DictReader(f):
            if r["timestamp"].startswith("2024"):
                truth.append(r)
print("clean truth rows (2024):", len(truth))

def census():
    return {"rows": len(truth), "faults": {}}

c = census()
rows = []
# ---- 1. missing readings (~3.5% of rows, one field each) ----
miss = {"SOC": 0, "Battery_Temp": 0, "Tire_Pressure": 0}
for r in truth:
    x = random.random()
    if x < 0.012:   r["SOC"] = "";            miss["SOC"] += 1
    elif x < 0.024: r["Battery_Temp"] = "";   miss["Battery_Temp"] += 1
    elif x < 0.035: r["Tire_Pressure"] = "";  miss["Tire_Pressure"] += 1
c["faults"]["missing_values"] = sum(miss.values()); c["faults"]["missing_by_field"] = miss
rows.extend(truth)

# ---- 2. out-of-bound values (plausible sensor glitches) ----
def ob(col, lo, hi, frac):
    picks = [r for r in rows if r[col] != ""]
    chosen = random.sample(picks, int(len(picks) * frac))
    for r in chosen:
        v = float(r[col])
        r[col] = round(lo + (hi - lo) * random.random(), 2)
    c["faults"][f"out_of_bound:{col}"] = {"n": len(chosen), "planted_range": [lo, hi]}

ob("SOC", 100.5, 145, 0.008)          # SOC can never exceed 100 %
ob("SOH", 100.0, 104.2, 0.005)        # health % cannot exceed 100
ob("Battery_Temp", -42.0, -25.0, 0.005)  # below thermistor floor
ob("Brake_Pad_Wear", 100.5, 112.0, 0.006)
c["faults"]["out_of_bound:Tire_Pressure_zero"] = {"n": 0}
rowsz = [r for r in rows if r["Tire_Pressure"] != ""]
for r in random.sample(rowsz, 24):
    r["Tire_Pressure"] = "0.0"
c["faults"]["out_of_bound:Tire_Pressure_zero"] = {"n": 24, "planted_range": [0, 0]}

# ---- 3. unit mix-up: tire pressure reported in kPa (PSI × 6.895) by one gateway ----
kpak = [r for r in rows if r["Tire_Pressure"] != "" and float(r["Tire_Pressure"]) > 0]
chosen = random.sample(kpak, int(len(kpak) * 0.015))
for r in chosen:
    r["Tire_Pressure"] = round(float(r["Tire_Pressure"]) * 6.895, 1)   # 34 PSI -> ~234 kPa
c["faults"]["unit_mix:Tire_Pressure_kPa"] = {"n": len(chosen), "rule": "value > 60 implies kPa; /6.895 to PSI"}

# ---- 4. duplicate retries (~1.2%) ----
dup_ct = int(len(rows) * 0.012)
rows.extend([dict(r) for r in random.sample(rows, dup_ct)])
c["faults"]["duplicate_rows"] = dup_ct

# ---- 5. shuffle: arrival order is never sorted ----
random.shuffle(rows)

cols = ["timestamp","vehicle_id","user_profile","district","SOC","SOH","Charging_Cycles",
        "charging_now","Battery_Temp","Motor_RPM","Motor_Torque","Motor_Temp",
        "Brake_Pad_Wear","Charging_Voltage","Tire_Pressure","DTC","grid_carbon_g_per_kwh"]
out = f"{BASE}/bronze/ingest_stream_2024.csv"
with open(out, "w", newline="") as f:
    w = csv.DictWriter(f, cols); w.writeheader(); w.writerows(rows)
c["faults"]["rows_after_fault_injection"] = len(rows)
with open(f"{BASE}/bronze/fault_census.json", "w") as f:
    json.dump(c, f, indent=2)
print(json.dumps(c, indent=2))
print("wrote", out)