Cyber / impl /src /pipeline /lib_data.py
pramodkachare's picture
Upload project files (excluding raw/derived dataset and venv)
aefa98b verified
Raw History Blame Contribute Delete
5.12 kB
"""Data access for steps 08-11: load train/val/test frames for a protocol, feature set and label level, with per-label caps."""
import csv
import numpy as np, pandas as pd
from .common import *
SPLITS = os.path.join(DATA, "splits.parquet")
FLAGS = os.path.join(DATA, "split_flags.parquet")
MATRIX = os.path.join(ART, "step07", "evaluability_matrix.csv")
S = f"read_parquet('{PARQUET_SRC}')"
KEYS = f"read_parquet('{os.path.join(DATA, 'dedup_keys.parquet')}')"
def label_level(protocol):
return {"p4b": "binary", "p5": "family_v1", "p5v0": "family_v0"}.get(protocol.split("_")[0], "attack")
def label_sql(level):
if level == "attack": return "s.Attack"
if level == "binary": return "CASE WHEN s.Attack = 'Benign' THEN 'Benign' ELSE 'Attack' END"
return None # families need the taxonomy join (see families())
def families(version):
path = {"v1": os.path.join(ART, "step07a", "taxonomy_v1.csv"), "v0": os.path.join(ART, "step07", "taxonomy_v0.csv")}[version]
with open(path) as f:
m = {r["Attack"]: r["family"] for r in csv.DictReader(f)}
m["Benign"] = "BENIGN"; return m
def evaluable_labels(protocol, featset):
col = "evaluable_B" if featset == "B" else "evaluable_A"
with open(MATRIX) as f:
labs = [r["label"] for r in csv.DictReader(f) if r["protocol"] == protocol and r[col] == "1"]
if protocol.startswith("p4b"): # step 07 stores the binary label as 0/1 (1 = attack)
labs = [{"0": "Benign", "1": "Attack"}[l] for l in labs]
return labs
def load(con, protocol, featset, split, cap_per_label, seed=SEED, extra_cols=(), clean=True):
"""Rows of `split` ('train'|'val'|'test') of `protocol`, restricted to evaluable labels, at most cap_per_label per label (hash-ordered).
For test rows with featset B the leak-flagged rows (same-label B duplicates and cross-label conflicts) are excluded when clean=True."""
level = label_level(protocol); code = {"train": 0, "val": 1, "test": 2}[split]
labs = evaluable_labels(protocol, featset)
if not labs: return None, labs
feats = features_A(con) if featset == "A" else features_B(con)
if level in ("attack", "binary"):
lab_expr, join = label_sql(level), ""
else:
fam = families("v1" if level == "family_v1" else "v0")
con.execute("CREATE OR REPLACE TEMP TABLE famtab(Attack VARCHAR, fam VARCHAR)")
con.executemany("INSERT INTO famtab VALUES (?, ?)", list(fam.items()))
lab_expr, join = "f.fam", "JOIN famtab f ON f.Attack = s.Attack"
labsql = ", ".join("'" + l.replace("'", "''") + "'" for l in labs)
flag = (f"LEFT JOIN (SELECT row_id FROM read_parquet('{FLAGS}') WHERE protocol = '{protocol}') fl ON fl.row_id = s.row_id" if (split == "test" and featset == "B" and clean) else "")
flagw = "AND fl.row_id IS NULL" if flag else ""
extra = "".join(f", s.{c}" for c in extra_cols)
if isinstance(cap_per_label, dict): # per-label caps; labels missing from the dict get no rows
capx = "CASE label " + " ".join("WHEN '" + k.replace("'", "''") + f"' THEN {int(v)}" for k, v in cap_per_label.items()) + " ELSE 0 END"
else:
capx = str(int(cap_per_label))
q = f"""SELECT * FROM (SELECT s.row_id, s.source, {lab_expr} AS label, {feat_select(feats, 's.')}{extra},
row_number() OVER (PARTITION BY {lab_expr} ORDER BY hash(s.row_id, {seed})) rk
FROM {S} s JOIN read_parquet('{SPLITS}') sp ON sp.row_id = s.row_id {join} {flag}
WHERE sp.{protocol} = {code} {flagw} AND {lab_expr} IN ({labsql})) WHERE rk <= {capx} ORDER BY row_id""" # deterministic row order (step 08b: order alone moves P2 macro-F1 by sd 0.005-0.008)
return con.execute(q).df(), labs
def xy(df, featset_cols):
X = df[featset_cols].astype("float32").replace([np.inf, -np.inf], np.nan)
return X
def label_counts(con, protocol, featset, split, clean=True):
"""Rows per evaluable label in a split (SQL only; nothing is loaded into memory)."""
level = label_level(protocol); code = {"train": 0, "val": 1, "test": 2}[split]
labs = evaluable_labels(protocol, featset)
if level in ("attack", "binary"):
lab_expr, join = label_sql(level), ""
else:
fam = families("v1" if level == "family_v1" else "v0")
con.execute("CREATE OR REPLACE TEMP TABLE famtab(Attack VARCHAR, fam VARCHAR)")
con.executemany("INSERT INTO famtab VALUES (?, ?)", list(fam.items()))
lab_expr, join = "f.fam", "JOIN famtab f ON f.Attack = s.Attack"
labsql = ", ".join("'" + l.replace("'", "''") + "'" for l in labs)
flag = (f"LEFT JOIN (SELECT row_id FROM read_parquet('{FLAGS}') WHERE protocol = '{protocol}') fl ON fl.row_id = s.row_id" if (split == "test" and featset == "B" and clean) else "")
flagw = "AND fl.row_id IS NULL" if flag else ""
rows = con.execute(f"""SELECT {lab_expr}, count(*) FROM {S} s JOIN read_parquet('{SPLITS}') sp ON sp.row_id = s.row_id {join} {flag}
WHERE sp.{protocol} = {code} {flagw} AND {lab_expr} IN ({labsql}) GROUP BY 1""").fetchall()
return {a: int(b) for a, b in rows}