File size: 12,012 Bytes
5d2f3a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
"""
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()