""" Reconstructs both compact-view clustering methods that were evaluated for the research timeline and runs them against the same four people used in the keyword-vs-topic analysis (../per_person_details/*.json). Method A ("primary-topic"): the method actually shipped. Two contiguous years belong to the same phase if they share the same dominant (highest-count) primary topic. This mirrors `canExtendPhaseByPrimaryTopic` / `getDominantPrimaryTopicCandidates` in research-timeline.component.ts. Method B ("cosine-similarity"): an alternative that was implemented and tested but not adopted (commit 65ab9d59, "Timeline: Add cosine similarity clustering"). Two contiguous years belong to the same phase if the cosine similarity between their weighted topic vectors is >= 0.55. Each year's vector is built from its `topics` (weight 1) and `primary_topics` (weight 1.5), keyed by normalized topic name, weighted by how many works in that year carry the topic. """ import json import math from pathlib import Path from typing import Any BASE_DIR = Path(__file__).resolve().parent DETAILS_DIR = BASE_DIR.parent / "per_person_details" OUTPUT_FILE = BASE_DIR / "clustering_comparison.json" SIMILARITY_THRESHOLD = 0.55 PRIMARY_TOPIC_WEIGHT = 1.5 def normalize(name: str) -> str: return name.strip().lower() def build_year_aggregates( works_by_year: dict[str, list[dict[str, Any]]], ) -> dict[int, dict[str, Any]]: """ Turns the per-work records for one person into the same shape the real backend produces per year: topic/primary-topic name -> number of works in that year carrying it. """ aggregates: dict[int, dict[str, Any]] = {} for year_str, works in works_by_year.items(): year = int(year_str) topic_counts: dict[str, int] = {} primary_counts: dict[str, int] = {} for work in works: for topic_name in work.get("topics") or []: topic_counts[topic_name] = topic_counts.get(topic_name, 0) + 1 primary = work.get("primary_topic") if primary: primary_counts[primary] = primary_counts.get(primary, 0) + 1 aggregates[year] = { "topics": topic_counts, "primary_topics": primary_counts, } return dict(sorted(aggregates.items())) def dominant_primary_topic_candidates(year_data: dict[str, Any]) -> list[str]: primary_topics = year_data["primary_topics"] if not primary_topics: return [] max_count = max(primary_topics.values()) return [name for name, count in primary_topics.items() if count == max_count] def main_topic_name(year_data: dict[str, Any]) -> str: """ Mirrors getMainTopicItem: highest-count primary topic, falling back to the highest-count regular topic if there is no primary topic at all. """ candidates = dominant_primary_topic_candidates(year_data) if candidates: return sorted(candidates)[0] topics = year_data["topics"] if not topics: return "Keine Topics" max_count = max(topics.values()) top = sorted(name for name, count in topics.items() if count == max_count) return top[0] def build_phases_primary_topic( years: list[tuple[int, dict[str, Any]]], ) -> list[dict[str, Any]]: phases: list[dict[str, Any]] = [] current: dict[str, Any] | None = None for year, data in years: if current is None: current = {"start": year, "end": year, "topic": main_topic_name(data)} continue candidates = dominant_primary_topic_candidates(data) matches = any( normalize(c) == normalize(current["topic"]) for c in candidates ) contiguous = year == current["end"] + 1 if contiguous and matches: current["end"] = year continue phases.append(current) current = {"start": year, "end": year, "topic": main_topic_name(data)} if current is not None: phases.append(current) return phases def make_vector(year_data: dict[str, Any]) -> dict[str, float]: vector: dict[str, float] = {} for name, count in year_data["topics"].items(): key = normalize(name) vector[key] = vector.get(key, 0.0) + count for name, count in year_data["primary_topics"].items(): key = normalize(name) vector[key] = vector.get(key, 0.0) + count * PRIMARY_TOPIC_WEIGHT return vector def add_vector(target: dict[str, float], addition: dict[str, float]) -> None: for key, value in addition.items(): target[key] = target.get(key, 0.0) + value def cosine_similarity(left: dict[str, float], right: dict[str, float]) -> float: left_norm = math.sqrt(sum(v * v for v in left.values())) right_norm = math.sqrt(sum(v * v for v in right.values())) if left_norm == 0 or right_norm == 0: return 0.0 smaller, larger = (left, right) if len(left) < len(right) else (right, left) dot_product = sum(value * larger.get(key, 0.0) for key, value in smaller.items()) return dot_product / (left_norm * right_norm) def build_phases_cosine_similarity( years: list[tuple[int, dict[str, Any]]], ) -> list[dict[str, Any]]: phases: list[dict[str, Any]] = [] current: dict[str, Any] | None = None current_vector: dict[str, float] = {} current_years: list[tuple[int, dict[str, Any]]] = [] def close_phase() -> None: # Final label = most frequent primary topic across the whole phase, # matching aggregateDominantPhasePrimaryTopic in the original commit. primary_totals: dict[str, int] = {} for _, data in current_years: for name, count in data["primary_topics"].items(): primary_totals[name] = primary_totals.get(name, 0) + count if primary_totals: max_count = max(primary_totals.values()) label = sorted( name for name, count in primary_totals.items() if count == max_count )[0] else: label = main_topic_name(current_years[0][1]) phases.append({"start": current["start"], "end": current["end"], "topic": label}) for year, data in years: item_vector = make_vector(data) if current is None: current = {"start": year, "end": year} current_vector = dict(item_vector) current_years = [(year, data)] continue contiguous = year == current["end"] + 1 similarity = cosine_similarity(current_vector, item_vector) if contiguous else 0.0 if contiguous and similarity >= SIMILARITY_THRESHOLD: current["end"] = year add_vector(current_vector, item_vector) current_years.append((year, data)) continue close_phase() current = {"start": year, "end": year} current_vector = dict(item_vector) current_years = [(year, data)] if current is not None: close_phase() return phases def format_phases(phases: list[dict[str, Any]]) -> list[str]: formatted = [] for phase in phases: span = ( f"{phase['start']}" if phase["start"] == phase["end"] else f"{phase['start']}-{phase['end']}" ) formatted.append(f"{span}: {phase['topic']}") return formatted def run() -> None: results: dict[str, Any] = {} for details_file in sorted(DETAILS_DIR.glob("*.json")): name = details_file.stem.replace("_", " ") with details_file.open(encoding="utf-8") as file: works_by_year = json.load(file) # per_person_details stores lists of work records per year; reduce # each work to just its topic names for the aggregation step. simplified: dict[str, list[dict[str, Any]]] = {} for year, works in works_by_year.items(): simplified[year] = [ {"topics": w.get("topics"), "primary_topic": w.get("primary_topic")} for w in works ] year_aggregates = build_year_aggregates(simplified) years_list = list(year_aggregates.items()) phases_simple = build_phases_primary_topic(years_list) phases_cosine = build_phases_cosine_similarity(years_list) results[name] = { "year_count": len(years_list), "phases_primary_topic": format_phases(phases_simple), "phases_cosine_similarity": format_phases(phases_cosine), "phase_count_primary_topic": len(phases_simple), "phase_count_cosine_similarity": len(phases_cosine), } print(f"\n=== {name} ({len(years_list)} Jahre) ===") print(f"Primary-Topic-Regel: {len(phases_simple)} Phasen") for line in format_phases(phases_simple): print(f" {line}") print(f"Cosine-Similarity: {len(phases_cosine)} Phasen") for line in format_phases(phases_cosine): print(f" {line}") with OUTPUT_FILE.open(mode="w", encoding="utf-8") as output_file: json.dump(results, output_file, indent=2, ensure_ascii=False) print(f"\nErgebnisse geschrieben nach {OUTPUT_FILE}") if __name__ == "__main__": run()