From d6f9deebfb8f94e55616185a77830c6a07b067d5 Mon Sep 17 00:00:00 2001 From: Bijan Date: Mon, 4 Aug 2025 19:43:48 +0200 Subject: [PATCH] Adapted code for new visualizations for evaluation --- project/__pycache__/config.cpython-310.pyc | Bin 1769 -> 1769 bytes project/config.py | 6 +- project/main.py | 37 ++-- project/visualization/vizualizer4.py | 238 +++++++++++++++++++++ 4 files changed, 260 insertions(+), 21 deletions(-) create mode 100644 project/visualization/vizualizer4.py diff --git a/project/__pycache__/config.cpython-310.pyc b/project/__pycache__/config.cpython-310.pyc index c6d6cb692b6331600c5b4c7ac8629958f96e9561..0e6181f5092597b6281ea630b633c0cd3d882298 100644 GIT binary patch delta 51 zcmaFK`;wP8pO=@50SF>4O~?q^$ji^nXfRop*#b<8PtIiyW str: + # Allow letters, digits, dot, underscore, plus, hyphen; replace everything else with "_" + s = re.sub(r'[^A-Za-z0-9._+\-]+', '_', s) + s = re.sub(r'_+', '_', s).strip('._ ') + return s + +def rsplit_dataset_technique(filename: str): + # Given 'results_{dataset}_{technique}.json' -> (dataset, technique) + if not (filename.startswith("results_") and filename.endswith(".json")): + return None, None + stem = filename[len("results_"):-len(".json")] + if "_" not in stem or "NO_OP" in filename: + return None, None + dataset, technique = stem.rsplit("_", 1) + return dataset, technique + +def load_values_for_threshold(root: Path, threshold: int, scope: str, metric_latex: str): + """Return: + datasets: sorted list + techniques: sorted list + values[technique][dataset] = number (0..100) or math.nan if missing + """ + folder = root / f"evaluation_results_{threshold}" + if not folder.is_dir(): + raise FileNotFoundError(f"Folder not found: {folder}") + + scope_keys = {scope, scope.lower(), scope.capitalize()} # be tolerant about case + techniques_set, datasets_set = set(), set() + values = defaultdict(dict) # technique -> dataset -> value + + for fname in os.listdir(folder): + dataset, technique = rsplit_dataset_technique(fname) + if not dataset or not technique: + continue + fpath = folder / fname + try: + with open(fpath, "r", encoding="utf-8") as f: + obj = json.load(f) + except Exception as e: + print(f"[WARN] Skipping {fpath}: {e}") + continue + + # find scope block (prefer exact, but allow simple case variations) + scope_block = None + for k in obj.keys(): + if k in scope_keys: + scope_block = obj[k] + break + if not isinstance(scope_block, dict): + continue + + if metric_latex in scope_block: + try: + v = float(scope_block[metric_latex]) + except Exception: + v = math.nan + else: + v = math.nan + + datasets_set.add(dataset) + techniques_set.add(technique) + values[technique][dataset] = v + + datasets = sorted(datasets_set) + techniques = sorted(techniques_set) + + # Ensure every (technique, dataset) has an entry + for t in techniques: + for d in datasets: + values[t].setdefault(d, math.nan) + + return datasets, techniques, values + +# Distinct hatch patterns for datasets (cycled if there are many datasets) +def grouped_bar_chart(datasets, techniques, values, scope, threshold, metric_latex, out_dir: Path, dpi=140): + if not techniques or not datasets: + print("[WARN] Nothing to plot (no techniques or datasets discovered).") + return False + + # dynamic width for readability + fig_w = max(8, 0.8 * len(techniques) + 3) + fig, ax = plt.subplots(figsize=(fig_w, 5.5)) # a touch taller to make room for legend + + n_groups = len(techniques) + n_bars = len(datasets) + group_x = list(range(n_groups)) + total_width = 0.8 # fraction of space per group occupied by bars + bar_w = total_width / max(1, n_bars) + offsets = [(i - (n_bars - 1) / 2) * bar_w for i in range(n_bars)] + + # Draw bars dataset-by-dataset so legend matches dataset order + for j, dataset in enumerate(datasets): + heights = [values[t][dataset] for t in techniques] + x_pos = [x + offsets[j] for x in group_x] + bars = ax.bar(x_pos, heights, width=bar_w, label=dataset) + + # Apply hatch pattern + clearer edges for visibility + hatch = HATCHES[j % len(HATCHES)] + rects = bars.patches if hasattr(bars, "patches") else list(bars) + for r in rects: + r.set_hatch(hatch) + r.set_edgecolor("black") + r.set_linewidth(0.6) + + # Labels on bars (percentages), version-safe + labels = [f"{h:.0f}" if not math.isnan(h) else "" for h in heights] + if hasattr(ax, "bar_label") and isinstance(bars, BarContainer): + ax.bar_label(bars, labels=labels, padding=2, fontsize=8) + else: + for rect, lab in zip(rects, labels): + if not lab: + continue + ax.text( + rect.get_x() + rect.get_width() / 2.0, + rect.get_height(), + lab, + ha="center", + va="bottom", + fontsize=8, + ) + + # X axis: technique names at group centers + ax.set_xticks(group_x) + ax.set_xticklabels(techniques) + + # Y axis: 0–100 with % labels + ax.set_ylim(0, 105) + ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y:.0f}%")) + + # Labels (y uses the LaTeX metric key) + ax.set_ylabel(f"${metric_latex}$", fontsize=14) + + ax.grid(axis="y", linestyle="--", alpha=0.4) + + # --- Legend BELOW the plot --- + handles, labels = ax.get_legend_handles_labels() + ncols = min(len(datasets), 4) if len(datasets) > 1 else 1 + leg = ax.legend( + handles, + labels, + loc="upper center", + bbox_to_anchor=(0.5, -0.05), # push below axes + ncol=ncols, + frameon=True, + ) + + # Make some extra bottom space for the legend + fig.subplots_adjust(bottom=0.22) + + out_dir.mkdir(parents=True, exist_ok=True) + outfile = out_dir / sanitize_filename(f"grouped_{scope}_IoU{threshold}_{metric_latex}.pdf") + fig.tight_layout() + fig.savefig(outfile, dpi=dpi, bbox_inches="tight") + plt.close(fig) + print(f"[OK] Saved {outfile}") + return True + + +def main(): + args = parse_args() + root = Path(args.root).expanduser().resolve() + out_dir = Path(args.out).expanduser().resolve() + + datasets, techniques, values = load_values_for_threshold( + root=root, + threshold=args.threshold, + scope=args.scope, + metric_latex=args.metric_latex, + ) + + ok = grouped_bar_chart( + datasets=datasets, + techniques=techniques, + values=values, + scope=args.scope, + threshold=args.threshold, + metric_latex=args.metric_latex, + out_dir=out_dir, + dpi=args.dpi, + ) + if not ok: + print("[WARN] No plot generated. Check the folder/JSON contents and the metric key.") + +if __name__ == "__main__": + main()