i-badas / scripts /cooccurrence_matrix.py
moiaraya's picture
modify data and scripts
b6f22ac
Raw History Blame Contribute Delete
11.1 kB
#!/usr/bin/env python3
"""
Anomaly-type co-occurrence matrix for I-BADAS.
Reads the per-scene COCO annotation files, pools them, and counts per-image
PRESENCE of each anomaly type (an image with three separate oil patches counts
once for nuisance_oil). Produces:
(a) an NxN co-occurrence heatmap; diagonal = images containing that type,
off-diagonal = images containing both types
(b) a bar chart of the number of distinct anomaly types per anomalous image
"""
import argparse
import json
import re
import sys
from collections import Counter, defaultdict
from itertools import combinations
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.gridspec import GridSpec
plt.rcParams.update({
"font.family": "serif",
"font.serif": ["Times New Roman", "DejaVu Serif"],
"font.size": 7,
"axes.linewidth": 0.6,
})
DEFAULT_DROP_SUPERCAT = {"box"}
def file_stem(path):
stem = Path(path).name
for suffix in (".coco.json", ".json"):
if stem.endswith(suffix):
return stem[: -len(suffix)]
return stem
def scene_labels(paths):
labels = {p: file_stem(p) for p in paths}
for depth in range(1, 8):
clash = {lab for lab, c in Counter(labels.values()).items() if c > 1}
if not clash:
break
for p in paths:
if labels[p] in clash:
parts = Path(p).resolve().parts[:-1]
prefix = parts[-depth:] if len(parts) >= depth else parts
labels[p] = "/".join([*prefix, file_stem(p)])
return labels
def sort_key(path):
return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", str(path))]
def load_scene(path, scene, level, keep_supercat, drop_names, keep_names,
subset, min_area, audit):
with open(path, "r", encoding="utf-8") as f:
coco = json.load(f)
id2name, id2cat = {}, {}
for c in coco.get("categories", []):
name = str(c["name"]).strip()
supercat = str(c.get("supercategory", "")).strip()
id2name[c["id"]] = name
id2cat[c["id"]] = c
audit["supercat"][name].add(supercat)
keep_ids = set()
for cid, c in id2cat.items():
name = id2name[cid]
sc = str(c.get("supercategory", "")).strip()
if name in drop_names:
audit["excluded"][name] = f"dropped by name ({sc})"
elif name in keep_names:
keep_ids.add(cid)
elif sc in keep_supercat:
keep_ids.add(cid)
else:
audit["excluded"][name] = sc
images = {}
for im in coco.get("images", []):
meta = {
"file_name": im.get("file_name", ""),
"classification": im.get("classification"),
"width": im.get("width"),
"height": im.get("height"),
}
images[im["id"]] = meta
per_unit = {}
for iid in images:
if subset and images[iid]["classification"] != subset:
continue
key = scene if level == "scene" else f"{scene}::{iid}"
per_unit.setdefault(key, set())
for ann in coco.get("annotations", []):
cid = ann.get("category_id")
iid = ann.get("image_id")
if cid not in keep_ids or iid not in images:
continue
if subset and images[iid]["classification"] != subset:
continue
if min_area and ann.get("area", float("inf")) < min_area:
audit["tiny"] += 1
continue
key = scene if level == "scene" else f"{scene}::{iid}"
per_unit[key].add(id2name[cid])
unit_meta = {}
if level == "image":
for iid, m in images.items():
if not subset or m["classification"] == subset:
unit_meta[f"{scene}::{iid}"] = m
return per_unit, unit_meta
def build_counts(per_unit, categories):
n = len(categories)
idx = {c: i for i, c in enumerate(categories)}
M = np.zeros((n, n), dtype=int)
mult = Counter()
for types in per_unit.values():
types = {t for t in types if t in idx}
mult[len(types)] += 1
for t in types:
M[idx[t], idx[t]] += 1
for a, b in combinations(types, 2):
i, j = idx[a], idx[b]
M[i, j] += 1
M[j, i] += 1
return M, mult
def short(name):
return name.replace("nuisance_", "").replace("_", " ")
def plot(M, categories, mult, out_stem, level):
n = len(categories)
labels = [short(c) for c in categories]
fig = plt.figure(figsize=(7.5, 3.4), dpi=300)
gs = GridSpec(1, 2, width_ratios=[1.35, 1.0], wspace=0.35,
left=0.18, right=0.96, top=0.90, bottom=0.22)
ax0 = fig.add_subplot(gs[0])
vmax = int(M.max()) if M.size else 1
im = ax0.imshow(M, cmap="magma", vmin=0, vmax=vmax)
for i in range(n):
for j in range(n):
val = M[i, j]
if val == 0:
continue
bright = val / vmax > 0.55
col = "black" if bright else "white"
fw = "bold" if i == j else "normal"
ax0.text(j, i, str(val), ha="center", va="center",
fontsize=5.5, color=col, fontweight=fw)
ax0.set_xticks(range(n))
ax0.set_yticks(range(n))
ax0.set_xticklabels(labels, rotation=45, ha="right")
ax0.set_yticklabels(labels)
ax0.set_title(f"Co-occurrence ({level} count)", fontsize=8, pad=6)
ax0.set_xticks(np.arange(-0.5, n, 1), minor=True)
ax0.set_yticks(np.arange(-0.5, n, 1), minor=True)
ax0.grid(which="minor", color="white", linestyle="-", linewidth=0.5)
ax0.tick_params(which="minor", bottom=False, left=False)
cb = fig.colorbar(im, ax=ax0, fraction=0.046, pad=0.04)
cb.ax.tick_params(labelsize=6)
ax1 = fig.add_subplot(gs[1])
ks = sorted(k for k in mult if k > 0)
if not ks:
ks = [0]
vals = [mult[k] for k in ks]
bars = ax1.bar(ks, vals, color="#3b528b", edgecolor="none", width=0.65)
ax1.set_xlabel(f"Distinct anomaly types per {level}", fontsize=7.5)
ax1.set_ylabel(f"Number of {level}s", fontsize=7.5)
ax1.set_title(f"Anomaly multiplicity (total {sum(vals)})", fontsize=8, pad=6)
ax1.set_xticks(ks)
ax1.grid(axis="y", linestyle=":", alpha=0.5, linewidth=0.5)
ax1.set_axisbelow(True)
for b in bars:
h = b.get_height()
if h > 0:
ax1.text(b.get_x() + b.get_width() / 2, h + max(vals) * 0.015,
str(h), ha="center", va="bottom", fontsize=6)
if vals:
ax1.set_ylim(0, max(vals) * 1.15)
for ext in ("png", "pdf"):
fig.savefig(f"{out_stem}.{ext}", bbox_inches="tight")
plt.close(fig)
print(f"wrote {out_stem}.png and {out_stem}.pdf")
def default_search():
candidates = [
Path("test"),
Path("../test"),
Path(__file__).resolve().parent.parent / "test",
Path("train"),
Path("../train"),
Path(__file__).resolve().parent.parent / "train",
Path("."),
Path(".."),
Path(__file__).resolve().parent.parent,
]
for c in candidates:
if c.is_dir() and list(c.rglob("annotations*.coco.json")):
return [str(c)]
return ["."]
def default_out_stem():
if Path("checkpoint_data").is_dir():
return "checkpoint_data/fig_cooccurrence"
if (Path(__file__).resolve().parent.parent / "checkpoint_data").is_dir():
return str(Path(__file__).resolve().parent.parent / "checkpoint_data" / "fig_cooccurrence")
return "./fig_cooccurrence"
def main():
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("paths", nargs="*", default=None,
help="annotation files or folders to scan (auto-detected if omitted)")
p.add_argument("--root", nargs="+", default=None,
help="directories to search recursively for --pattern")
p.add_argument("--pattern", default="annotations*.coco.json")
p.add_argument("--keep-supercat", default=None)
p.add_argument("--drop-supercat", default="box")
p.add_argument("--drop", default="", help="comma-separated category names to drop")
p.add_argument("--keep", default="", help="comma-separated category names to keep")
p.add_argument("--min-area", type=float, default=0)
p.add_argument("--subset", default=None)
p.add_argument("--expect", type=int, default=0)
p.add_argument("--level", choices=("image", "scene"), default="image")
p.add_argument("--out", default=None, help="output file stem")
a = p.parse_args()
files = []
if a.paths:
for item in a.paths:
path = Path(item)
if path.is_file():
files.append(str(path))
elif path.is_dir():
files.extend(str(q) for q in path.rglob(a.pattern))
elif a.root:
for r in a.root:
files.extend(str(q) for q in Path(r).rglob(a.pattern))
else:
for r in default_search():
files.extend(str(q) for q in Path(r).rglob(a.pattern))
files = sorted(set(files), key=sort_key)
if not files:
sys.exit("no annotation files found")
labels = scene_labels(files)
print(f"Found {len(files)} annotation file(s):")
for f in files:
print(f" {labels[f]:<35} -> {f}")
drop_names = {x.strip() for x in a.drop.split(",") if x.strip()}
keep_names = {x.strip() for x in a.keep.split(",") if x.strip()}
drop_supercat = {x.strip() for x in a.drop_supercat.split(",") if x.strip()}
all_supercat = set()
for f in files:
with open(f, "r", encoding="utf-8") as fp:
data = json.load(fp)
for c in data.get("categories", []):
all_supercat.add(str(c.get("supercategory", "")).strip())
if a.keep_supercat:
keep_supercat = {x.strip() for x in a.keep_supercat.split(",") if x.strip()}
else:
keep_supercat = all_supercat - drop_supercat
out_stem = a.out if a.out is not None else default_out_stem()
Path(out_stem).parent.mkdir(parents=True, exist_ok=True)
audit = {"supercat": defaultdict(set), "excluded": {}, "tiny": 0}
per_unit, meta = {}, {}
for f in files:
pu, mt = load_scene(f, labels[f], a.level, keep_supercat, drop_names,
keep_names, a.subset, a.min_area, audit)
for k, v in pu.items():
per_unit.setdefault(k, set()).update(v)
meta.update(mt)
categories = sorted({t for s in per_unit.values() for t in s})
if not categories:
sys.exit("no categories left after exclusion")
M, mult = build_counts(per_unit, categories)
with open(f"{out_stem}_counts.csv", "w", encoding="utf-8") as f:
f.write("," + ",".join(categories) + "\n")
for i, c in enumerate(categories):
f.write(c + "," + ",".join(str(v) for v in M[i]) + "\n")
print(f"wrote {out_stem}_counts.csv")
plot(M, categories, mult, out_stem, a.level)
if __name__ == "__main__":
main()