Datasets:
Formats:
csv
Languages:
English
Size:
10M - 100M
Tags:
cybersecurity
intrusion-detection
network-security
vanet
vehicular-networks
federated-learning
License:
| """ | |
| Create a deployment-realistic VANET-IDS26 test split with a strict 99:1 | |
| benign-to-attack ratio. | |
| The public VANET-IDS26 release is intentionally attack-heavy for research | |
| coverage. A deployed NIDS usually sees benign safety traffic dominate the | |
| stream, so this script builds an operational test split where attacks are rare | |
| but still represented across all 26 attack families. | |
| Examples | |
| -------- | |
| Quick schema/sampler path for the public sample file: | |
| python scripts/create_realistic_vanet_ids26_test_split.py --sample | |
| Chunked path for the full master file: | |
| python scripts/create_realistic_vanet_ids26_test_split.py ^ | |
| --input research_ready/vanet_ids26_master.csv.gz ^ | |
| --output research_ready/vanet_ids26_test_99_1.csv.gz ^ | |
| --mode chunked ^ | |
| --attack-rows 2600 | |
| Note: the bundled sample has only 1,000 benign rows. A strict 99:1 split that | |
| also includes all 26 attack classes requires at least 2,574 benign rows | |
| (26 attacks * 99 benign per attack), so use the master file for the final split. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import gzip | |
| import json | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Dict, Iterable, Mapping | |
| import pandas as pd | |
| from sklearn.utils import check_random_state | |
| ROOT = Path(__file__).resolve().parents[1] | |
| DEFAULT_MASTER = ROOT / "research_ready" / "vanet_ids26_master.csv.gz" | |
| DEFAULT_SAMPLE = ROOT / "release" / "github" / "VANET-IDS26" / "samples" / "vanet_ids26_sample.csv.gz" | |
| DEFAULT_OUTPUT = ROOT / "research_ready" / "vanet_ids26_test_99_1.csv.gz" | |
| DEFAULT_MANIFEST_DIR = ROOT / "dataset" / "manifests" | |
| BINARY_LABEL = "binary_label" | |
| MULTICLASS_LABEL = "multiclass_label" | |
| BENIGN_LABEL = 0 | |
| ATTACK_LABELS = tuple(range(1, 27)) | |
| BENIGN_TO_ATTACK_RATIO = 99 | |
| ATTACK_TYPES = { | |
| 1: "constant_position", | |
| 2: "position_offset", | |
| 3: "random_position", | |
| 4: "speed_manipulation", | |
| 5: "acceleration_manipulation", | |
| 6: "heading_manipulation", | |
| 7: "lane_spoofing", | |
| 8: "impossible_kinematics", | |
| 9: "eventual_stop", | |
| 10: "false_brake_event", | |
| 11: "false_emergency_vehicle", | |
| 12: "false_hazard_event", | |
| 13: "replay", | |
| 14: "delayed_message", | |
| 15: "timestamp_shift", | |
| 16: "stale_message_replay", | |
| 17: "sybil", | |
| 18: "impersonation", | |
| 19: "pseudonym_abuse", | |
| 20: "flooding_ddos", | |
| 21: "beacon_rate_abuse", | |
| 22: "gnss_spoofing", | |
| 23: "map_location_spoofing", | |
| 24: "ghost_vehicle", | |
| 25: "false_object_injection", | |
| 26: "object_position_shift", | |
| } | |
| ATTACK_TYPE_TO_LABEL = {name: label for label, name in ATTACK_TYPES.items()} | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser( | |
| description="Build a strict 99:1 benign/attack VANET-IDS26 test split." | |
| ) | |
| parser.add_argument( | |
| "--input", | |
| type=Path, | |
| default=DEFAULT_MASTER, | |
| help=f"Input CSV/CSV.GZ path. Default: {DEFAULT_MASTER}", | |
| ) | |
| parser.add_argument( | |
| "--output", | |
| type=Path, | |
| default=DEFAULT_OUTPUT, | |
| help=f"Output CSV/CSV.GZ path. Default: {DEFAULT_OUTPUT}", | |
| ) | |
| parser.add_argument( | |
| "--sample", | |
| action="store_true", | |
| help=f"Use the small public sample file with in-memory loading: {DEFAULT_SAMPLE}", | |
| ) | |
| parser.add_argument( | |
| "--mode", | |
| choices=("chunked", "memory"), | |
| default="chunked", | |
| help="Use chunked two-pass sampling for massive files or memory mode for small files.", | |
| ) | |
| parser.add_argument( | |
| "--chunksize", | |
| type=int, | |
| default=250_000, | |
| help="Rows per chunk for chunked mode.", | |
| ) | |
| parser.add_argument( | |
| "--attack-rows", | |
| type=int, | |
| default=2_600, | |
| help=( | |
| "Exact number of attack rows to include. Benign rows are set to " | |
| "attack_rows * 99. Default: 2600, which is 100 rows per attack " | |
| "family with --attack-strategy balanced." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--use-largest-feasible", | |
| action="store_true", | |
| help=( | |
| "Ignore --attack-rows and build the largest strict 99:1 split supported " | |
| "by the input. Use carefully on the full master file." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--attack-strategy", | |
| choices=("balanced", "proportional"), | |
| default="balanced", | |
| help=( | |
| "balanced gives each attack family nearly equal support; proportional " | |
| "preserves the source attack-family distribution as closely as possible." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--random-state", | |
| type=int, | |
| default=42, | |
| help="Random seed for reproducible sampling.", | |
| ) | |
| parser.add_argument( | |
| "--count-source", | |
| choices=("auto", "manifests", "scan"), | |
| default="auto", | |
| help=( | |
| "Where to get source label counts. auto uses local manifests when present " | |
| "and falls back to scanning the input." | |
| ), | |
| ) | |
| parser.add_argument( | |
| "--manifest-dir", | |
| type=Path, | |
| default=DEFAULT_MANIFEST_DIR, | |
| help=f"Directory containing local source manifests. Default: {DEFAULT_MANIFEST_DIR}", | |
| ) | |
| return parser.parse_args() | |
| def label_counts_from_memory(df: pd.DataFrame) -> Dict[int, int]: | |
| _require_label_columns(df.columns) | |
| counts = df[MULTICLASS_LABEL].astype("int64").value_counts().sort_index() | |
| return {int(label): int(count) for label, count in counts.items()} | |
| def label_counts_from_chunks(path: Path, chunksize: int) -> Dict[int, int]: | |
| counts: Dict[int, int] = {} | |
| for chunk in pd.read_csv( | |
| path, | |
| usecols=[BINARY_LABEL, MULTICLASS_LABEL], | |
| chunksize=chunksize, | |
| low_memory=False, | |
| ): | |
| _require_label_columns(chunk.columns) | |
| chunk_counts = chunk[MULTICLASS_LABEL].astype("int64").value_counts() | |
| for label, count in chunk_counts.items(): | |
| counts[int(label)] = counts.get(int(label), 0) + int(count) | |
| return dict(sorted(counts.items())) | |
| def label_counts_from_manifests(manifest_dir: Path) -> Dict[int, int]: | |
| benign_manifest = manifest_dir / "big_benign_runs_manifest.csv" | |
| attack_manifest = manifest_dir / "overlay_manifest.csv" | |
| if not benign_manifest.exists() or not attack_manifest.exists(): | |
| missing = [ | |
| str(path) | |
| for path in (benign_manifest, attack_manifest) | |
| if not path.exists() | |
| ] | |
| raise FileNotFoundError("Missing source manifest(s): " + ", ".join(missing)) | |
| benign = pd.read_csv(benign_manifest) | |
| attacks = pd.read_csv(attack_manifest) | |
| required_benign_cols = {"records_mobility"} | |
| required_attack_cols = {"attack_type", "overlay_rows"} | |
| if not required_benign_cols.issubset(benign.columns): | |
| raise ValueError(f"{benign_manifest} is missing {required_benign_cols}") | |
| if not required_attack_cols.issubset(attacks.columns): | |
| raise ValueError(f"{attack_manifest} is missing {required_attack_cols}") | |
| counts = {BENIGN_LABEL: int(benign["records_mobility"].sum())} | |
| grouped = attacks.groupby("attack_type")["overlay_rows"].sum() | |
| for attack_type, rows in grouped.items(): | |
| if attack_type not in ATTACK_TYPE_TO_LABEL: | |
| raise ValueError(f"Unknown attack_type in manifest: {attack_type}") | |
| counts[ATTACK_TYPE_TO_LABEL[attack_type]] = int(rows) | |
| return dict(sorted(counts.items())) | |
| def get_source_counts(path: Path, chunksize: int, count_source: str, manifest_dir: Path) -> tuple[Dict[int, int], str]: | |
| if count_source in ("auto", "manifests"): | |
| try: | |
| return label_counts_from_manifests(manifest_dir), "manifests" | |
| except (FileNotFoundError, ValueError): | |
| if count_source == "manifests": | |
| raise | |
| return label_counts_from_chunks(path, chunksize), "scan" | |
| def make_attack_quotas( | |
| label_counts: Mapping[int, int], | |
| attack_rows: int | None, | |
| strategy: str, | |
| ) -> Dict[int, int]: | |
| _validate_source_counts(label_counts) | |
| benign_rows_available = label_counts.get(BENIGN_LABEL, 0) | |
| max_attack_by_benign = benign_rows_available // BENIGN_TO_ATTACK_RATIO | |
| max_attack_by_attacks = sum(label_counts[label] for label in ATTACK_LABELS) | |
| max_attack_rows = min(max_attack_by_benign, max_attack_by_attacks) | |
| if attack_rows is None: | |
| attack_rows = max_attack_rows | |
| if attack_rows < len(ATTACK_LABELS): | |
| minimum_benign = len(ATTACK_LABELS) * BENIGN_TO_ATTACK_RATIO | |
| raise ValueError( | |
| "Cannot satisfy strict 99:1 and all 26 attack classes with " | |
| f"{attack_rows} attack rows. Need at least {len(ATTACK_LABELS)} " | |
| f"attack rows and {minimum_benign} benign rows." | |
| ) | |
| if attack_rows > max_attack_rows: | |
| raise ValueError( | |
| f"Requested {attack_rows} attack rows, but this input supports at most " | |
| f"{max_attack_rows} with a strict 99:1 ratio. Available benign rows: " | |
| f"{benign_rows_available}; available attack rows: {max_attack_by_attacks}." | |
| ) | |
| if strategy == "balanced": | |
| return _balanced_attack_quotas(label_counts, attack_rows) | |
| if strategy == "proportional": | |
| return _proportional_attack_quotas(label_counts, attack_rows) | |
| raise ValueError(f"Unknown attack strategy: {strategy}") | |
| def _balanced_attack_quotas(label_counts: Mapping[int, int], attack_rows: int) -> Dict[int, int]: | |
| quotas = {label: 1 for label in ATTACK_LABELS} | |
| remaining = attack_rows - len(ATTACK_LABELS) | |
| while remaining: | |
| progressed = False | |
| for label in ATTACK_LABELS: | |
| if quotas[label] >= label_counts[label]: | |
| continue | |
| quotas[label] += 1 | |
| remaining -= 1 | |
| progressed = True | |
| if remaining == 0: | |
| break | |
| if not progressed: | |
| raise ValueError("Attack quotas exceed available rows for the 26 attack classes.") | |
| return quotas | |
| def _proportional_attack_quotas(label_counts: Mapping[int, int], attack_rows: int) -> Dict[int, int]: | |
| total_available = sum(label_counts[label] for label in ATTACK_LABELS) | |
| raw = { | |
| label: (label_counts[label] / total_available) * attack_rows | |
| for label in ATTACK_LABELS | |
| } | |
| quotas = { | |
| label: min(label_counts[label], max(1, int(raw[label]))) | |
| for label in ATTACK_LABELS | |
| } | |
| while sum(quotas.values()) > attack_rows: | |
| candidates = [label for label in ATTACK_LABELS if quotas[label] > 1] | |
| label = max(candidates, key=lambda item: (quotas[item] - raw[item], quotas[item])) | |
| quotas[label] -= 1 | |
| while sum(quotas.values()) < attack_rows: | |
| candidates = [label for label in ATTACK_LABELS if quotas[label] < label_counts[label]] | |
| if not candidates: | |
| raise ValueError("Attack quotas exceed available rows for the 26 attack classes.") | |
| label = max(candidates, key=lambda item: (raw[item] - quotas[item], label_counts[item])) | |
| quotas[label] += 1 | |
| return quotas | |
| def build_split_in_memory( | |
| input_path: Path, | |
| output_path: Path, | |
| attack_rows: int | None, | |
| attack_strategy: str, | |
| random_state: int, | |
| ) -> pd.DataFrame: | |
| df = pd.read_csv(input_path, low_memory=False) | |
| counts = label_counts_from_memory(df) | |
| attack_quotas = make_attack_quotas(counts, attack_rows, attack_strategy) | |
| benign_rows = sum(attack_quotas.values()) * BENIGN_TO_ATTACK_RATIO | |
| rng = check_random_state(random_state) | |
| sampled_frames = [ | |
| df.loc[df[MULTICLASS_LABEL].astype("int64") == BENIGN_LABEL].sample( | |
| n=benign_rows, | |
| random_state=int(rng.randint(0, 2**31 - 1)), | |
| replace=False, | |
| ) | |
| ] | |
| for label, quota in attack_quotas.items(): | |
| sampled_frames.append( | |
| df.loc[df[MULTICLASS_LABEL].astype("int64") == label].sample( | |
| n=quota, | |
| random_state=int(rng.randint(0, 2**31 - 1)), | |
| replace=False, | |
| ) | |
| ) | |
| final_df = _shuffle(pd.concat(sampled_frames, ignore_index=True), rng) | |
| write_output(final_df, output_path) | |
| print_evaluation(final_df, counts, attack_quotas, output_path) | |
| return final_df | |
| def build_split_chunked( | |
| input_path: Path, | |
| output_path: Path, | |
| chunksize: int, | |
| attack_rows: int | None, | |
| attack_strategy: str, | |
| random_state: int, | |
| count_source: str, | |
| manifest_dir: Path, | |
| ) -> None: | |
| counts, resolved_count_source = get_source_counts(input_path, chunksize, count_source, manifest_dir) | |
| attack_quotas = make_attack_quotas(counts, attack_rows, attack_strategy) | |
| benign_rows = sum(attack_quotas.values()) * BENIGN_TO_ATTACK_RATIO | |
| rng = check_random_state(random_state) | |
| reservoirs: Dict[int, pd.DataFrame] = {} | |
| final_counts = {label: 0 for label in (BENIGN_LABEL, *ATTACK_LABELS)} | |
| tmp_output_path = output_path.with_name(output_path.name + ".tmp") | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| if tmp_output_path.exists(): | |
| tmp_output_path.unlink() | |
| print(f"Source counts loaded from: {resolved_count_source}") | |
| print(f"Target benign rows: {benign_rows:,}") | |
| print(f"Target attack rows: {sum(attack_quotas.values()):,}") | |
| print(f"Writing temporary output: {tmp_output_path}") | |
| with _open_text_output(tmp_output_path) as out_f: | |
| wrote_header = False | |
| for chunk_number, chunk in enumerate( | |
| pd.read_csv(input_path, chunksize=chunksize, low_memory=False), | |
| start=1, | |
| ): | |
| _require_label_columns(chunk.columns) | |
| labels = chunk[MULTICLASS_LABEL].astype("int64") | |
| benign_remaining = benign_rows - final_counts[BENIGN_LABEL] | |
| if benign_remaining > 0: | |
| benign_chunk = chunk.loc[labels == BENIGN_LABEL] | |
| if len(benign_chunk) > benign_remaining: | |
| benign_chunk = benign_chunk.iloc[:benign_remaining] | |
| if not benign_chunk.empty: | |
| benign_chunk.to_csv(out_f, index=False, header=not wrote_header) | |
| wrote_header = True | |
| final_counts[BENIGN_LABEL] += len(benign_chunk) | |
| attack_labels_in_chunk = sorted( | |
| label for label in labels.unique() if int(label) in ATTACK_LABELS | |
| ) | |
| for label in attack_labels_in_chunk: | |
| label = int(label) | |
| quota = attack_quotas[label] | |
| subset = chunk.loc[labels == label].copy() | |
| if subset.empty: | |
| continue | |
| subset["_sample_key"] = rng.random_sample(len(subset)) | |
| if label in reservoirs: | |
| subset = pd.concat([reservoirs[label], subset], ignore_index=True) | |
| reservoirs[label] = subset.nsmallest(quota, "_sample_key") | |
| if chunk_number % 100 == 0: | |
| sampled_attack_rows = sum(len(frame) for frame in reservoirs.values()) | |
| print( | |
| f"chunks={chunk_number:,} benign_written={final_counts[BENIGN_LABEL]:,} " | |
| f"attack_reservoir={sampled_attack_rows:,}" | |
| ) | |
| attack_frames = [] | |
| for label, quota in attack_quotas.items(): | |
| sampled = reservoirs.get(label) | |
| if sampled is None or len(sampled) != quota: | |
| found = 0 if sampled is None else len(sampled) | |
| raise RuntimeError(f"Sampled {found} rows for label {label}; expected {quota}.") | |
| clean_sample = sampled.drop(columns="_sample_key") | |
| final_counts[label] = len(clean_sample) | |
| attack_frames.append(clean_sample) | |
| attack_df = _shuffle(pd.concat(attack_frames, ignore_index=True), rng) | |
| with _open_text_output(tmp_output_path, append=True) as out_f: | |
| attack_df.to_csv(out_f, index=False, header=False) | |
| if output_path.exists(): | |
| output_path.unlink() | |
| tmp_output_path.replace(output_path) | |
| print_evaluation_from_counts(final_counts, counts, attack_quotas, output_path) | |
| write_split_manifest( | |
| output_path=output_path, | |
| input_path=input_path, | |
| source_counts=counts, | |
| final_counts=final_counts, | |
| attack_quotas=attack_quotas, | |
| attack_strategy=attack_strategy, | |
| random_state=random_state, | |
| chunksize=chunksize, | |
| count_source=resolved_count_source, | |
| ) | |
| def write_output(df: pd.DataFrame, output_path: Path) -> None: | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| df.to_csv(output_path, index=False) | |
| def print_evaluation( | |
| df: pd.DataFrame, | |
| source_counts: Mapping[int, int], | |
| expected_attack_quotas: Mapping[int, int], | |
| output_path: Path, | |
| ) -> None: | |
| final_binary = df[BINARY_LABEL].astype("int64").value_counts().sort_index() | |
| final_multi = df[MULTICLASS_LABEL].astype("int64").value_counts().sort_index() | |
| benign_rows = int(final_binary.get(BENIGN_LABEL, 0)) | |
| attack_rows = int(final_binary.get(1, 0)) | |
| total_rows = len(df) | |
| benign_pct = benign_rows / total_rows * 100 | |
| attack_pct = attack_rows / total_rows * 100 | |
| print() | |
| print("WROTE REALISTIC VANET-IDS26 TEST SPLIT") | |
| print(f"Output: {output_path}") | |
| print() | |
| print("Source multiclass counts:") | |
| print(pd.Series(source_counts, name="source_rows").sort_index().to_string()) | |
| print() | |
| print("Final binary distribution:") | |
| print(f"benign rows: {benign_rows:,} ({benign_pct:.2f}%)") | |
| print(f"attack rows: {attack_rows:,} ({attack_pct:.2f}%)") | |
| print(f"total rows: {total_rows:,}") | |
| print(f"benign:attack ratio: {benign_rows}:{attack_rows} = {benign_rows / attack_rows:.0f}:1") | |
| print() | |
| print("Final attack-family distribution:") | |
| attack_distribution = pd.DataFrame( | |
| { | |
| "expected_rows": pd.Series(expected_attack_quotas), | |
| "actual_rows": final_multi.reindex(ATTACK_LABELS, fill_value=0), | |
| } | |
| ) | |
| attack_distribution["attack_pct"] = ( | |
| attack_distribution["actual_rows"] / attack_rows * 100 | |
| ).round(4) | |
| print(attack_distribution.to_string()) | |
| assert benign_rows == attack_rows * BENIGN_TO_ATTACK_RATIO | |
| assert attack_rows == sum(expected_attack_quotas.values()) | |
| assert set(final_multi.loc[final_multi.index > 0].index) == set(ATTACK_LABELS) | |
| assert all( | |
| int(final_multi.get(label, 0)) == quota | |
| for label, quota in expected_attack_quotas.items() | |
| ) | |
| print() | |
| print("Verification: PASS - strict 99% benign / 1% attack with all 26 attacks represented.") | |
| def print_evaluation_from_counts( | |
| final_counts: Mapping[int, int], | |
| source_counts: Mapping[int, int], | |
| expected_attack_quotas: Mapping[int, int], | |
| output_path: Path, | |
| ) -> None: | |
| benign_rows = int(final_counts.get(BENIGN_LABEL, 0)) | |
| attack_rows = sum(int(final_counts.get(label, 0)) for label in ATTACK_LABELS) | |
| total_rows = benign_rows + attack_rows | |
| benign_pct = benign_rows / total_rows * 100 | |
| attack_pct = attack_rows / total_rows * 100 | |
| print() | |
| print("WROTE REALISTIC VANET-IDS26 TEST SPLIT") | |
| print(f"Output: {output_path}") | |
| print() | |
| print("Source multiclass counts:") | |
| print(pd.Series(source_counts, name="source_rows").sort_index().to_string()) | |
| print() | |
| print("Final binary distribution:") | |
| print(f"benign rows: {benign_rows:,} ({benign_pct:.2f}%)") | |
| print(f"attack rows: {attack_rows:,} ({attack_pct:.2f}%)") | |
| print(f"total rows: {total_rows:,}") | |
| print(f"benign:attack ratio: {benign_rows}:{attack_rows} = {benign_rows / attack_rows:.0f}:1") | |
| print() | |
| print("Final attack-family distribution:") | |
| attack_distribution = pd.DataFrame( | |
| { | |
| "attack_type": pd.Series(ATTACK_TYPES), | |
| "expected_rows": pd.Series(expected_attack_quotas), | |
| "actual_rows": pd.Series( | |
| {label: int(final_counts.get(label, 0)) for label in ATTACK_LABELS} | |
| ), | |
| } | |
| ) | |
| attack_distribution["attack_pct"] = ( | |
| attack_distribution["actual_rows"] / attack_rows * 100 | |
| ).round(4) | |
| print(attack_distribution.to_string()) | |
| assert benign_rows == attack_rows * BENIGN_TO_ATTACK_RATIO | |
| assert attack_rows == sum(expected_attack_quotas.values()) | |
| assert set(label for label in ATTACK_LABELS if final_counts.get(label, 0) > 0) == set(ATTACK_LABELS) | |
| assert all( | |
| int(final_counts.get(label, 0)) == quota | |
| for label, quota in expected_attack_quotas.items() | |
| ) | |
| print() | |
| print("Verification: PASS - strict 99% benign / 1% attack with all 26 attacks represented.") | |
| def write_split_manifest( | |
| output_path: Path, | |
| input_path: Path, | |
| source_counts: Mapping[int, int], | |
| final_counts: Mapping[int, int], | |
| attack_quotas: Mapping[int, int], | |
| attack_strategy: str, | |
| random_state: int, | |
| chunksize: int, | |
| count_source: str, | |
| ) -> None: | |
| manifest_path = output_path.with_name(output_path.name + ".manifest.json") | |
| attack_distribution_path = output_path.with_name( | |
| output_path.name + ".attack_distribution.csv" | |
| ) | |
| benign_rows = int(final_counts[BENIGN_LABEL]) | |
| attack_rows = sum(int(final_counts[label]) for label in ATTACK_LABELS) | |
| total_rows = benign_rows + attack_rows | |
| attack_distribution = pd.DataFrame( | |
| [ | |
| { | |
| "multiclass_label": label, | |
| "attack_type": ATTACK_TYPES[label], | |
| "source_rows": int(source_counts[label]), | |
| "sampled_rows": int(final_counts[label]), | |
| "attack_pct": int(final_counts[label]) / attack_rows * 100, | |
| } | |
| for label in ATTACK_LABELS | |
| ] | |
| ) | |
| attack_distribution.to_csv(attack_distribution_path, index=False) | |
| manifest = { | |
| "dataset_name": "VANET-IDS26 realistic 99:1 operational test split", | |
| "created_at_utc": datetime.now(timezone.utc).isoformat(), | |
| "input_path": str(input_path), | |
| "output_path": str(output_path), | |
| "attack_distribution_path": str(attack_distribution_path), | |
| "output_format": "csv.gz" if output_path.name.endswith(".csv.gz") else output_path.suffix.lstrip("."), | |
| "output_file_bytes": output_path.stat().st_size if output_path.exists() else None, | |
| "count_source": count_source, | |
| "random_state": random_state, | |
| "chunksize": chunksize, | |
| "benign_to_attack_ratio": BENIGN_TO_ATTACK_RATIO, | |
| "attack_strategy": attack_strategy, | |
| "source_counts": {str(label): int(count) for label, count in source_counts.items()}, | |
| "attack_quotas": {str(label): int(count) for label, count in attack_quotas.items()}, | |
| "final_counts": {str(label): int(count) for label, count in final_counts.items()}, | |
| "final_binary_counts": { | |
| "benign": benign_rows, | |
| "attack": attack_rows, | |
| "total": total_rows, | |
| }, | |
| "final_percentages": { | |
| "benign": benign_rows / total_rows * 100, | |
| "attack": attack_rows / total_rows * 100, | |
| }, | |
| "notes": [ | |
| "This split is designed for deployed NIDS evaluation where benign traffic dominates.", | |
| "The benign portion uses the maximum strict 99:1 size and drops only surplus benign rows that do not fit the exact ratio.", | |
| "Attack rows are under-sampled with stratification across multiclass_label 1..26.", | |
| "Rows are written as benign stream followed by sampled attacks; shuffle downstream before order-sensitive evaluation.", | |
| ], | |
| } | |
| manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8") | |
| print(f"Manifest: {manifest_path}") | |
| print(f"Attack distribution CSV: {attack_distribution_path}") | |
| def _open_text_output(path: Path, append: bool = False): | |
| mode = "at" if append else "wt" | |
| if ".gz" in path.suffixes: | |
| return gzip.open(path, mode, newline="", encoding="utf-8", compresslevel=1) | |
| return path.open(mode, newline="", encoding="utf-8") | |
| def _shuffle(df: pd.DataFrame, rng) -> pd.DataFrame: | |
| return df.sample( | |
| frac=1.0, | |
| random_state=int(rng.randint(0, 2**31 - 1)), | |
| ).reset_index(drop=True) | |
| def _validate_source_counts(label_counts: Mapping[int, int]) -> None: | |
| missing = [label for label in (BENIGN_LABEL, *ATTACK_LABELS) if label_counts.get(label, 0) <= 0] | |
| if missing: | |
| raise ValueError( | |
| "Input does not contain all required labels. Missing/empty multiclass labels: " | |
| + ", ".join(str(label) for label in missing) | |
| ) | |
| def _require_label_columns(columns: Iterable[str]) -> None: | |
| columns = set(columns) | |
| missing = [col for col in (BINARY_LABEL, MULTICLASS_LABEL) if col not in columns] | |
| if missing: | |
| raise ValueError(f"Input is missing required label column(s): {missing}") | |
| def main() -> None: | |
| args = parse_args() | |
| input_path = DEFAULT_SAMPLE if args.sample else args.input | |
| mode = "memory" if args.sample else args.mode | |
| if not input_path.exists(): | |
| raise FileNotFoundError(f"Input file not found: {input_path}") | |
| attack_rows = None if args.use_largest_feasible else args.attack_rows | |
| if mode == "memory": | |
| build_split_in_memory( | |
| input_path=input_path, | |
| output_path=args.output, | |
| attack_rows=attack_rows, | |
| attack_strategy=args.attack_strategy, | |
| random_state=args.random_state, | |
| ) | |
| else: | |
| build_split_chunked( | |
| input_path=input_path, | |
| output_path=args.output, | |
| chunksize=args.chunksize, | |
| attack_rows=attack_rows, | |
| attack_strategy=args.attack_strategy, | |
| random_state=args.random_state, | |
| count_source=args.count_source, | |
| manifest_dir=args.manifest_dir, | |
| ) | |
| if __name__ == "__main__": | |
| main() | |