raw_dataset / drift_data /build_concept_drift.py
IoTProber's picture
Add drift_data (BigQuery snapshots, concept_drift CSVs, ip per-class tables)
5d2f3a4 verified
Raw History Blame Contribute Delete
12 kB
"""
Build intra-class concept drift dataset from three time periods:
- BigQuery 20250218 (Feb 2025)
- BigQuery 20250818 (Aug 2025)
- Platform CSV 20260218 (Feb 2026)
Constructs two types of IP pairs per device type:
Pair A: 20250218 vs 20260218 (12-month gap)
Pair B: 20250818 vs 20260218 (6-month gap)
Drift detection logic:
1. Match same IP within same device type across time periods
2. Check OS vendor consistency β€” if vendor changed, discard (device replacement)
3. If vendor unchanged, compare service distribution to label drift/no-drift
4. Output per-device-type pair CSVs and overall statistics
"""
import json
import pandas as pd
import os
import sys
import time
# ─── Paths ───────────────────────────────────────────────────────────────────
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BQ_20250218_DIR = os.path.join(BASE_DIR, "BigQuery", "20250218")
BQ_20250818_DIR = os.path.join(BASE_DIR, "BigQuery", "20250818")
PLATFORM_CSV_DIR = os.path.join(BASE_DIR, "..", "platform_data", "csv")
OUTPUT_DIR = os.path.join(BASE_DIR, "concept_drift")
DEVICE_TYPES = [
"BUILDING_AUTOMATION", "CAMERA", "MEDICAL", "NAS",
"NVR", "POWER_METER", "PRINTER", "ROUTER", "SCADA"
]
# ─── BigQuery loader ────────────────────────────────────────────────────────
def load_bigquery_data(filepath):
"""Load BigQuery JSON-lines file and aggregate per unique IPv4.
Returns:
dict ip -> {'vendor': str|None, 'product': str|None,
'services': set of 'SVC-PORT' strings}
"""
ip_data = {}
with open(filepath, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
rec = json.loads(line)
ip = rec.get("ipv4", "")
if not ip:
continue
if ip not in ip_data:
ip_data[ip] = {"vendor": None, "product": None, "services": set()}
entry = ip_data[ip]
# First non-null OS vendor / product wins
if entry["vendor"] is None and rec.get("vendor"):
entry["vendor"] = rec["vendor"]
if entry["product"] is None and rec.get("product"):
entry["product"] = rec["product"]
# Service distribution: pair service_names_list with ports_list
ports = rec.get("ports_list", [])
svcs = rec.get("service_names_list", [])
for svc, port in zip(svcs, ports):
entry["services"].add(f"{svc}-{port}")
return ip_data
# ─── Platform CSV loader (memory-efficient) ─────────────────────────────────
def load_platform_data_filtered(filepath, ip_filter_set):
"""Read platform CSV in chunks, keep only rows whose IP is in *ip_filter_set*.
Returns:
dict ip -> {'vendor': str|None, 'product': str|None,
'services': set of normalised 'SVC-PORT' strings}
"""
ip_data = {}
usecols = ["ip", "os-vendor", "os-product", "service-distribution"]
for chunk in pd.read_csv(
filepath,
usecols=usecols,
chunksize=50000,
dtype=str,
keep_default_na=False,
on_bad_lines="skip",
encoding="utf-8",
):
mask = chunk["ip"].isin(ip_filter_set)
filtered = chunk[mask]
for _, row in filtered.iterrows():
ip = row["ip"]
vendor = row.get("os-vendor", "")
product = row.get("os-product", "")
svc_dist = row.get("service-distribution", "")
services = _parse_platform_services(svc_dist)
if ip not in ip_data:
ip_data[ip] = {
"vendor": vendor if vendor and vendor != "Unknown" else None,
"product": product if product and product != "Unknown" else None,
"services": services,
}
else:
# Merge duplicates (rare – normally one row per IP)
ip_data[ip]["services"].update(services)
if ip_data[ip]["vendor"] is None and vendor and vendor != "Unknown":
ip_data[ip]["vendor"] = vendor
if ip_data[ip]["product"] is None and product and product != "Unknown":
ip_data[ip]["product"] = product
return ip_data
def _parse_platform_services(svc_dist_str):
"""Parse platform service-distribution field into a normalised set.
Example input: "HTTP-80,HTTP-443,Unknown Protocol-1963,SSDP-1900"
Output: {"HTTP-80", "HTTP-443", "UNKNOWN-1963", "SSDP-1900"}
"""
services = set()
if not svc_dist_str:
return services
for item in str(svc_dist_str).split(","):
item = item.strip()
if not item:
continue
parts = item.rsplit("-", 1)
if len(parts) == 2:
svc, port = parts
svc_norm = svc.strip().upper()
if svc_norm == "UNKNOWN PROTOCOL":
svc_norm = "UNKNOWN"
services.add(f"{svc_norm}-{port.strip()}")
else:
services.add(item.upper())
return services
def _normalize_bq_services(services_set):
"""Upper-case normalise BigQuery service set for fair comparison."""
normalised = set()
for item in services_set:
parts = item.rsplit("-", 1)
if len(parts) == 2:
svc, port = parts
normalised.add(f"{svc.strip().upper()}-{port.strip()}")
else:
normalised.add(item.upper())
return normalised
# ─── Vendor matching ────────────────────────────────────────────────────────
def _norm_vendor(v):
if v is None or v == "" or str(v).lower() == "unknown":
return None
return str(v).lower().strip()
def _vendor_match(v1, v2):
"""True if vendors are considered the same.
- Both None/Unknown β†’ match (indeterminate, keep pair).
- Only one None β†’ match (indeterminate, keep pair).
- Both non-null β†’ compare normalised strings.
"""
nv1 = _norm_vendor(v1)
nv2 = _norm_vendor(v2)
if nv1 is None or nv2 is None:
return True
return nv1 == nv2
# ─── Drift pair builder ─────────────────────────────────────────────────────
def build_drift_pairs(bq_data, plat_data, device_type, bq_snapshot):
"""Match IPs, filter vendor mismatches, detect service drift.
Returns:
pairs : list of dicts (one per valid IP pair)
stats : summary dict
"""
common_ips = set(bq_data.keys()) & set(plat_data.keys())
stats = {
"device_type": device_type,
"pair": f"{bq_snapshot}_vs_20260218",
"total_common_ips": len(common_ips),
"vendor_mismatch": 0,
"drift": 0,
"no_drift": 0,
}
pairs = []
for ip in common_ips:
bq = bq_data[ip]
plat = plat_data[ip]
# Vendor gate
if not _vendor_match(bq["vendor"], plat["vendor"]):
stats["vendor_mismatch"] += 1
continue
# Normalise service sets
bq_svc = _normalize_bq_services(bq["services"])
plat_svc = plat["services"]
is_drift = bq_svc != plat_svc
if is_drift:
stats["drift"] += 1
else:
stats["no_drift"] += 1
pairs.append(
{
"ip": ip,
"device_type": device_type,
"bq_snapshot": bq_snapshot,
"platform_snapshot": "20260218",
"os_vendor_old": bq["vendor"] or "",
"os_product_old": bq["product"] or "",
"os_vendor_new": plat["vendor"] or "",
"os_product_new": plat["product"] or "",
"services_old": "|".join(sorted(bq_svc)),
"services_new": "|".join(sorted(plat_svc)),
"drift": int(is_drift),
}
)
stats["total_valid"] = stats["drift"] + stats["no_drift"]
return pairs, stats
# ─── Main ────────────────────────────────────────────────────────────────────
def main():
os.makedirs(OUTPUT_DIR, exist_ok=True)
all_stats = []
t0 = time.time()
for dev in DEVICE_TYPES:
print(f"\n{'=' * 60}")
print(f"Processing {dev} ...")
bq_file_a = os.path.join(BQ_20250218_DIR, f"{dev}.json")
bq_file_b = os.path.join(BQ_20250818_DIR, f"{dev}.json")
plat_file = os.path.join(PLATFORM_CSV_DIR, f"ipraw_{dev}.csv")
missing = [f for f in (bq_file_a, bq_file_b, plat_file) if not os.path.exists(f)]
if missing:
print(f" SKIP β€” missing files: {missing}")
continue
# 1. Load BigQuery data
print(" Loading BigQuery 20250218 ...")
bq_0218 = load_bigquery_data(bq_file_a)
print(f" -> {len(bq_0218)} unique IPs")
print(" Loading BigQuery 20250818 ...")
bq_0818 = load_bigquery_data(bq_file_b)
print(f" -> {len(bq_0818)} unique IPs")
# 2. Load platform data (only IPs that appear in either BigQuery set)
candidate_ips = set(bq_0218.keys()) | set(bq_0818.keys())
print(f" Loading Platform 20260218 (filtering to {len(candidate_ips)} candidate IPs) ...")
plat = load_platform_data_filtered(plat_file, candidate_ips)
print(f" -> {len(plat)} matched IPs")
# 3. Build drift pairs
print(" Building Pair A (20250218 vs 20260218) ...")
pairs_a, stats_a = build_drift_pairs(bq_0218, plat, dev, "20250218")
all_stats.append(stats_a)
print(" Building Pair B (20250818 vs 20260218) ...")
pairs_b, stats_b = build_drift_pairs(bq_0818, plat, dev, "20250818")
all_stats.append(stats_b)
# 4. Save per-device CSVs
if pairs_a:
out_a = os.path.join(OUTPUT_DIR, f"{dev}_20250218_vs_20260218.csv")
pd.DataFrame(pairs_a).to_csv(out_a, index=False)
print(f" Saved {out_a} ({len(pairs_a)} pairs)")
if pairs_b:
out_b = os.path.join(OUTPUT_DIR, f"{dev}_20250818_vs_20260218.csv")
pd.DataFrame(pairs_b).to_csv(out_b, index=False)
print(f" Saved {out_b} ({len(pairs_b)} pairs)")
# 5. Print summary
for label, s in [
("Pair A (20250218 vs 20260218)", stats_a),
("Pair B (20250818 vs 20260218)", stats_b),
]:
print(f"\n {label}:")
print(f" Common IPs : {s['total_common_ips']}")
print(f" Vendor mismatch : {s['vendor_mismatch']} (discarded)")
print(f" Drift : {s['drift']}")
print(f" No-drift : {s['no_drift']}")
print(f" Total valid : {s['total_valid']}")
del bq_0218, bq_0818, plat
# ── Overall statistics ───────────────────────────────────────────────
stats_df = pd.DataFrame(all_stats)
stats_path = os.path.join(OUTPUT_DIR, "drift_statistics.csv")
stats_df.to_csv(stats_path, index=False)
elapsed = time.time() - t0
print(f"\n{'=' * 60}")
print(f"Done in {elapsed:.1f}s. Statistics saved to {stats_path}\n")
print(stats_df.to_string(index=False))
if __name__ == "__main__":
main()