Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f898644d46 | ||
|
|
04c621986d | ||
|
|
b98e484617 |
@@ -4,6 +4,9 @@
|
||||
service/*
|
||||
!service/scripts
|
||||
|
||||
# Keyword extraction contract, shared with background-jobs/app/llm/client.py.
|
||||
!service/src/main/inse/news/keyword_extraction.py
|
||||
|
||||
# Data-only folders that do not belong in the job image.
|
||||
service/scripts/multipliers
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# Forschungstimeline-Analyse
|
||||
|
||||
Diese Analyse untersucht, welche OpenAlex-Daten sich eignen, um darzustellen, woran eine
|
||||
Person über die Jahre gearbeitet hat und ob sich ihr Themengebiet verschoben hat oder gleich
|
||||
geblieben ist. Das Ergebnis ist die Grundlage für die Forschungstimeline im
|
||||
Frontend (`/api/works/{author_id}/topics-by-time`).
|
||||
|
||||
## Vorgehen
|
||||
|
||||
- **Stichprobe:** vier manuell ausgewählte Personen mit unterschiedlich langer und breiter
|
||||
Publikationshistorie ([research_timeline_sample.csv](research_timeline_sample.csv)):
|
||||
Lucas Davi, Marcus Handte, Arman Arzani, Pedro José Marrón.
|
||||
- **Datenerhebung:** Für jede Person wurden alle Werke über die OpenAlex-API geladen
|
||||
([openalex_client.py](openalex_client.py)) und pro Werk die Felder `keywords`, `topics`
|
||||
und `primary_topic` extrahiert, nach Publikationsjahr gruppiert
|
||||
([timeline_manual_analysis.py](timeline_manual_analysis.py) →
|
||||
[per_person_details/](per_person_details/)).
|
||||
- **Auswertung:** Vergleich von Keywords und Topics hinsichtlich Menge, Wiederholung und
|
||||
inhaltlicher Präzision.
|
||||
|
||||
## Ergebnisse
|
||||
|
||||
### Keywords sind zu unspezifisch
|
||||
|
||||
Die häufigsten Keywords pro Person sind überwiegend generische Fachbereichs-Label statt
|
||||
konkreter Forschungsthemen. Bei Marcus Handte (110 Werke) ist das häufigste Keyword schlicht
|
||||
**"Computer science"** (94 von 110 Werken), gefolgt von "Engineering" (29),
|
||||
"Telecommunications" (23) und "World Wide Web" (22) — Begriffe, die auf praktisch jede
|
||||
Informatik-Publikation zutreffen und nichts über sein tatsächliches Forschungsgebiet
|
||||
aussagen. Bei Lucas Davi (138 Werke) dominieren ähnlich "Computer science" (126),
|
||||
"Computer security" (95) und "Operating system" (74).
|
||||
|
||||
Zusätzlich zeigen sich klare **Begriffs-Fehlzuordnungen**: Die automatische
|
||||
Keyword-Extraktion von OpenAlex ist nicht domänenspezifisch und ordnet englische
|
||||
Alltagswörter teils der falschen Bedeutung zu. Beispiele aus den Daten:
|
||||
|
||||
- Marcus Handte, _context-aware computing_: Keyword **"Context (archaeology)"**
|
||||
(19 Werke) — "Context" wurde der archäologischen statt der informatischen Bedeutung zugeordnet.
|
||||
- Lucas Davi: Keyword **"Code (set theory)"** (32 Werke) — "Code" wurde
|
||||
der mathematischen Mengenlehre statt Programmcode zugeordnet.
|
||||
- Marcus Handte, Keyword **"Key (lock)"** — "Key" wurde als
|
||||
physisches Türschloss statt als technischer Begriff interpretiert.
|
||||
|
||||
Diese drei Beispiele sind keine Einzelfälle, sondern stehen exemplarisch für ein
|
||||
systematisches Problem: Das Keyword-Feld eignet sich nicht als Grundlage für eine
|
||||
Forschungsthemen-Timeline.
|
||||
|
||||
### Topics sind spezifisch und decken sich mit dem bekannten Forschungsprofil
|
||||
|
||||
Die häufigsten Topics bilden dagegen erkennbar die tatsächlichen Forschungsschwerpunkte ab.
|
||||
Bei Marcus Handte: _"Context-Aware Activity Recognition Systems"_ (32), _"Indoor and Outdoor
|
||||
Localization Technologies"_ (17), _"IoT and Edge/Fog Computing"_ (14) — deckt sich mit seinem
|
||||
bekannten Profil in den Networked Embedded Systems. Bei Lucas Davi: _"Security and
|
||||
Verification in Computing"_ (105), _"Advanced Malware Detection Techniques"_ (91),
|
||||
_"Physical Unclonable Functions (PUFs) and Hardware Security"_ (16) — passt zu seiner
|
||||
Sicherheitsforschung.
|
||||
|
||||
Topics sind zusätzlich hierarchisch in Subfield/Field/Domain eingeordnet, was eine
|
||||
konsistente Farbcodierung und Gruppierung in der Timeline-Legende ermöglicht — bei den
|
||||
freien Keyword-Strings ist eine solche Einordnung nicht verfügbar.
|
||||
|
||||
**Einschränkung:** Auch Topics sind nicht fehlerfrei. Bei Lucas Davi erscheint z. B.
|
||||
_"Diamond and Carbon-based Materials Research"_ unter den Top-Topics (21 Werke) — fachfremd zu
|
||||
seiner Sicherheitsforschung und vermutlich auf eine Autor-Namensverwechslung in OpenAlex
|
||||
zurückzuführen. Solche Ausreißer sind in den Daten deutlich seltener als bei Keywords, aber
|
||||
nicht komplett ausgeschlossen.
|
||||
|
||||
### Quantitativer Überblick
|
||||
|
||||
| Person | Werke | Ø Keywords/Werk | Distinkte Keywords | Ø Topics/Werk | Distinkte Topics |
|
||||
| ----------------- | ----: | --------------: | -----------------: | ------------: | ---------------: |
|
||||
| Lucas Davi | 138 | 9,89 | 324 | 2,83 | 59 |
|
||||
| Marcus Handte | 110 | 9,35 | 309 | 2,79 | 109 |
|
||||
| Arman Arzani | 8 | 5,38 | 36 | 2,50 | 19 |
|
||||
| Pedro José Marrón | 286 | 10,02 | 590 | 2,76 | 183 |
|
||||
|
||||
Pro Werk stehen deutlich mehr Keywords als Topics zur Verfügung (Faktor ~3-4), was auf den
|
||||
ersten Blick nach mehr Information aussieht — die obigen Beispiele zeigen aber, dass ein
|
||||
Großteil davon zu generisch oder falsch zugeordnet ist, um für eine Timeline nutzbar zu sein.
|
||||
|
||||
### Beispiel: sichtbare Themenverschiebung über die Jahre (Marcus Handte, Primary Topics)
|
||||
|
||||
Die pro Jahr häufigsten Primary Topics zeigen genau die Art von Verschiebung, die die
|
||||
Timeline sichtbar machen soll — von Distributed Systems über mehrere Jahre stabiles
|
||||
Context-Aware Computing, dann Indoor-Lokalisierung, bis zu einer thematisch breiteren Phase
|
||||
in den letzten Jahren:
|
||||
|
||||
| Jahre | Dominantes Primary Topic |
|
||||
| --------------- | --------------------------------------------------------------------- |
|
||||
| 2004–2005 | Distributed systems and fault tolerance |
|
||||
| 2006–2012 | Context-Aware Activity Recognition Systems (durchgehend über 7 Jahre) |
|
||||
| 2013, 2016–2017 | Indoor and Outdoor Localization Technologies |
|
||||
| 2014, 2024 | Human Mobility and Location-Based Analysis |
|
||||
| 2022 | Privacy, Security, and Data Protection |
|
||||
| 2023 | Robotics and Sensor-Based Localization |
|
||||
|
||||
(vollständige Jahr-für-Jahr-Aufschlüsselung in
|
||||
[per_person_details/Marcus_Handte.json](per_person_details/Marcus_Handte.json))
|
||||
|
||||
## Fazit: finale Entscheidung im Projekt
|
||||
|
||||
Die Forschungstimeline im Backend basiert ausschließlich auf `topics` und `primary_topic`.
|
||||
Das`keywords`-Feld von OpenAlex wird für die Timeline nicht verwendet.
|
||||
@@ -0,0 +1,88 @@
|
||||
# Kompaktansicht: Gruppierung von Jahren
|
||||
|
||||
Nachdem die Entscheidung für `topics`/`primary_topic` als Datengrundlage gefallen war,
|
||||
haben wir uns die Daten der vier Personen noch einmal angesehen, um zu überlegen,
|
||||
wie sich das pro Jahr in der Timeline darstellen lässt. Bei Personen mit langer
|
||||
Publikationshistorie (z. B. Pedro José Marrón mit 28 Jahren) wird eine
|
||||
reine Jahresansicht schnell unübersichtlich. Deshalb ist zusätzlich eine Kompaktansicht
|
||||
geplant, die aufeinanderfolgende Jahre zu einer Phase zusammenfasst, wenn sie thematisch
|
||||
zusammengehören. Für die konkrete Gruppierungsregel haben wir zwei Ansätze gegeneinander
|
||||
getestet, bevor wir uns entschieden haben.
|
||||
|
||||
## Ansatz A: Primary-Topic-Regel
|
||||
|
||||
Zwei **aufeinanderfolgende** Jahre werden zu einer Phase zusammengefasst, wenn sie dasselbe
|
||||
dominante Primary Topic teilen — also das Topic mit der höchsten Werkanzahl in beiden Jahren
|
||||
(bei Gleichstand zählt jedes der gleichauf liegenden Topics als Treffer). Ein fehlendes Jahr
|
||||
oder ein Wechsel des dominanten Themas beendet die Phase sofort, auch wenn später wieder
|
||||
dasselbe Thema auftaucht.
|
||||
|
||||
Beispiel Marcus Handte, Jahre 2006–2012: Da in jedem dieser sieben Jahre "Context-Aware
|
||||
Activity Recognition Systems" das (gleichauf-)dominante Primary Topic ist, entsteht daraus
|
||||
eine einzige Phase "2006–2012". Sobald 2013 "Indoor and Outdoor Localization Technologies"
|
||||
dominiert, beginnt eine neue Phase.
|
||||
|
||||
## Ansatz B: Cosine-Similarity über das gesamte Themenprofil
|
||||
|
||||
Als Alternative haben wir einen Ansatz geprüft, der nicht nur das dominante Thema, sondern
|
||||
das gesamte Themenprofil eines Jahres berücksichtigt:
|
||||
|
||||
- Für jedes Jahr wird ein Vektor aus allen Topics gebildet: reguläre Topics zählen mit
|
||||
Gewicht 1, Primary Topics zusätzlich mit Gewicht 1,5 (jeweils multipliziert mit der Anzahl
|
||||
der Werke, die das Topic in diesem Jahr tragen).
|
||||
- Ein Jahr wird an eine bestehende (aufeinanderfolgende) Phase angehängt, wenn die
|
||||
Kosinus-Ähnlichkeit zwischen dem Phasen-Vektor (Summe aller bisherigen Jahre der Phase) und
|
||||
dem Jahres-Vektor mindestens 0,55 beträgt — unabhängig davon, ob das _dominante_ Thema
|
||||
übereinstimmt.
|
||||
- Das Label einer fertigen Phase ist danach das über alle enthaltenen Jahre am häufigsten
|
||||
vorkommende Primary Topic.
|
||||
|
||||
Beide Ansätze wurden als Prototyp implementiert und an denselben vier Personen ausgewertet.
|
||||
|
||||
## Vergleich
|
||||
|
||||
### 1. Cosine-Similarity verschluckt genau die Verschiebungen, die die Timeline zeigen soll
|
||||
|
||||
Bei **Lucas Davi** fasst die Primary-Topic-Regel 2013 korrekt als eigene, einjährige Phase
|
||||
("Advanced Malware Detection Techniques") zusammen, weil in diesem Jahr ein anderes Thema
|
||||
dominierte als davor und danach:
|
||||
|
||||
| Verfahren | Ergebnis 2009–2026 |
|
||||
| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Primary-Topic-Regel | 2009–2012: Security and Verification in Computing · **2013: Advanced Malware Detection Techniques** · 2014–2026: Security and Verification in Computing |
|
||||
| Cosine-Similarity | **2009–2024: Security and Verification in Computing** (16 Jahre in einer Phase) · 2025: Blockchain Technology Applications and Security · 2026: Security and Verification in Computing |
|
||||
|
||||
Die Cosine-Similarity verschmilzt 16 Jahre zu einer einzigen Phase und lässt dabei den
|
||||
2013er-Ausreißer komplett verschwinden — obwohl genau solche vorübergehenden Themenwechsel
|
||||
für die Timeline interessant wären. Der Grund: Die im Hintergrund mitlaufenden Nebenthemen
|
||||
(z. B. allgemeine Sicherheitsthemen) überlappen Jahr für Jahr stark genug, dass die
|
||||
Ähnlichkeit trotz unterschiedlichem Schwerpunktthema über der Schwelle bleibt.
|
||||
|
||||
Bei **Pedro José Marrón** zeigt sich derselbe Effekt noch deutlicher: Die Primary-Topic-Regel
|
||||
löst 2005–2011, 2012, 2013 und 2014–2015 als vier unterschiedliche, informative Phasen auf;
|
||||
Cosine-Similarity verschmilzt 2004 bis 2016 — **13 Jahre** — zu einer einzigen Phase und
|
||||
verdeckt damit u. a. das 2012er-Jahr zu "Interactive and Immersive Displays" komplett.
|
||||
|
||||
### 2. Cosine-Similarity verhält sich auch gegenteilig unvorhersehbar
|
||||
|
||||
Bei **Arman Arzani** (kurze Historie, 4 Jahre) tritt der umgekehrte Fall auf: 2023 und 2024
|
||||
haben laut Primary-Topic-Regel _dasselbe_ dominante Thema ("Big Data and Business
|
||||
Intelligence") und werden zusammengefasst — Cosine-Similarity trennt die beiden Jahre
|
||||
trotzdem, weil die Nebenthemen zu wenig überlappen. Für Nutzende wäre das schwer
|
||||
nachvollziehbar: Zwei Jahre mit identisch angezeigtem Hauptthema erscheinen als getrennte
|
||||
Phasen, ohne dass ein sichtbarer Grund dafür erkennbar ist.
|
||||
|
||||
### 3. Nachvollziehbarkeit
|
||||
|
||||
Die Primary-Topic-Regel begründet eine Phase immer mit genau dem Label, das auch angezeigt
|
||||
wird ("diese Jahre teilen sich dasselbe Hauptthema"). Die Kosinus-Ähnlichkeit ist dagegen ein
|
||||
unsichtbarer Zahlenwert, der in der Oberfläche nirgends auftaucht — eine Zusammenfassung oder
|
||||
Trennung lässt sich für Nutzende nicht nachvollziehen, wie die Beispiele oben zeigen.
|
||||
|
||||
## Entscheidung
|
||||
|
||||
Auf Basis dieses Vergleichs verwendet die Kompaktansicht die Primary-Topic-Regel. Der
|
||||
Cosine-Similarity-Ansatz bleibt als geprüfte, aber verworfene Alternative dokumentiert: Er
|
||||
neigt auf echten Daten dazu, genau die Themenwechsel zu verschlucken, die die Timeline
|
||||
sichtbar machen soll, und seine Gruppierungsentscheidungen sind für Nutzende nicht
|
||||
nachvollziehbar.
|
||||
@@ -0,0 +1,121 @@
|
||||
{
|
||||
"Arman Arzani": {
|
||||
"year_count": 4,
|
||||
"phases_primary_topic": [
|
||||
"2023-2024: Big Data and Business Intelligence",
|
||||
"2025: Data Mining Algorithms and Applications",
|
||||
"2026: Advanced Software Engineering Methodologies"
|
||||
],
|
||||
"phases_cosine_similarity": [
|
||||
"2023: Big Data and Business Intelligence",
|
||||
"2024: Big Data and Business Intelligence",
|
||||
"2025: Data Mining Algorithms and Applications",
|
||||
"2026: Advanced Software Engineering Methodologies"
|
||||
],
|
||||
"phase_count_primary_topic": 3,
|
||||
"phase_count_cosine_similarity": 4
|
||||
},
|
||||
"Lucas Davi": {
|
||||
"year_count": 18,
|
||||
"phases_primary_topic": [
|
||||
"2009-2012: Security and Verification in Computing",
|
||||
"2013: Advanced Malware Detection Techniques",
|
||||
"2014-2026: Security and Verification in Computing"
|
||||
],
|
||||
"phases_cosine_similarity": [
|
||||
"2009-2024: Security and Verification in Computing",
|
||||
"2025: Blockchain Technology Applications and Security",
|
||||
"2026: Security and Verification in Computing"
|
||||
],
|
||||
"phase_count_primary_topic": 3,
|
||||
"phase_count_cosine_similarity": 3
|
||||
},
|
||||
"Marcus Handte": {
|
||||
"year_count": 23,
|
||||
"phases_primary_topic": [
|
||||
"2004: Data Visualization and Analytics",
|
||||
"2005: Distributed systems and fault tolerance",
|
||||
"2006-2007: Context-Aware Activity Recognition Systems",
|
||||
"2008: Energy Efficient Wireless Sensor Networks",
|
||||
"2009-2012: Context-Aware Activity Recognition Systems",
|
||||
"2013: Indoor and Outdoor Localization Technologies",
|
||||
"2014: Human Mobility and Location-Based Analysis",
|
||||
"2015: Context-Aware Activity Recognition Systems",
|
||||
"2016-2017: Indoor and Outdoor Localization Technologies",
|
||||
"2018: Bluetooth and Wireless Communication Technologies",
|
||||
"2019: Distributed and Parallel Computing Systems",
|
||||
"2020: Advanced Vision and Imaging",
|
||||
"2021: Human Mobility and Location-Based Analysis",
|
||||
"2022: Privacy, Security, and Data Protection",
|
||||
"2023: Energy Harvesting in Wireless Networks",
|
||||
"2024: Big Data and Business Intelligence",
|
||||
"2025: Data Mining Algorithms and Applications",
|
||||
"2026: Advanced Software Engineering Methodologies"
|
||||
],
|
||||
"phases_cosine_similarity": [
|
||||
"2004: Data Visualization and Analytics",
|
||||
"2005: Distributed systems and fault tolerance",
|
||||
"2006-2007: Context-Aware Activity Recognition Systems",
|
||||
"2008: Energy Efficient Wireless Sensor Networks",
|
||||
"2009-2012: Context-Aware Activity Recognition Systems",
|
||||
"2013: Indoor and Outdoor Localization Technologies",
|
||||
"2014: Human Mobility and Location-Based Analysis",
|
||||
"2015: Context-Aware Activity Recognition Systems",
|
||||
"2016-2018: Indoor and Outdoor Localization Technologies",
|
||||
"2019: Distributed and Parallel Computing Systems",
|
||||
"2020: Advanced Vision and Imaging",
|
||||
"2021: Human Mobility and Location-Based Analysis",
|
||||
"2022: Privacy, Security, and Data Protection",
|
||||
"2023: Energy Harvesting in Wireless Networks",
|
||||
"2024: Big Data and Business Intelligence",
|
||||
"2025: Data Mining Algorithms and Applications",
|
||||
"2026: Advanced Software Engineering Methodologies"
|
||||
],
|
||||
"phase_count_primary_topic": 18,
|
||||
"phase_count_cosine_similarity": 17
|
||||
},
|
||||
"Pedro José Marrón": {
|
||||
"year_count": 28,
|
||||
"phases_primary_topic": [
|
||||
"1996: Mathematics, Computing, and Information Processing",
|
||||
"1999: Real-Time Systems Scheduling",
|
||||
"2001: Advanced Database Systems and Queries",
|
||||
"2002: Distributed systems and fault tolerance",
|
||||
"2003: Advanced Database Systems and Queries",
|
||||
"2004: Distributed systems and fault tolerance",
|
||||
"2005-2011: Energy Efficient Wireless Sensor Networks",
|
||||
"2012: Interactive and Immersive Displays",
|
||||
"2013: Indoor and Outdoor Localization Technologies",
|
||||
"2014-2015: Energy Efficient Wireless Sensor Networks",
|
||||
"2016-2017: Indoor and Outdoor Localization Technologies",
|
||||
"2018: Bluetooth and Wireless Communication Technologies",
|
||||
"2019: Indoor and Outdoor Localization Technologies",
|
||||
"2020-2021: Robotics and Sensor-Based Localization",
|
||||
"2022: Advanced Database Systems and Queries",
|
||||
"2023: Energy Harvesting in Wireless Networks",
|
||||
"2024: Big Data and Business Intelligence",
|
||||
"2025: Data Mining Algorithms and Applications",
|
||||
"2026: Face recognition and analysis"
|
||||
],
|
||||
"phases_cosine_similarity": [
|
||||
"1996: Mathematics, Computing, and Information Processing",
|
||||
"1999: Real-Time Systems Scheduling",
|
||||
"2001: Advanced Database Systems and Queries",
|
||||
"2002: Distributed systems and fault tolerance",
|
||||
"2003: Advanced Database Systems and Queries",
|
||||
"2004-2016: Energy Efficient Wireless Sensor Networks",
|
||||
"2017: Indoor and Outdoor Localization Technologies",
|
||||
"2018: Bluetooth and Wireless Communication Technologies",
|
||||
"2019: Indoor and Outdoor Localization Technologies",
|
||||
"2020: Robotics and Sensor-Based Localization",
|
||||
"2021: Human Mobility and Location-Based Analysis",
|
||||
"2022: Advanced Database Systems and Queries",
|
||||
"2023: Energy Harvesting in Wireless Networks",
|
||||
"2024: Big Data and Business Intelligence",
|
||||
"2025: Data Mining Algorithms and Applications",
|
||||
"2026: Face recognition and analysis"
|
||||
],
|
||||
"phase_count_primary_topic": 19,
|
||||
"phase_count_cosine_similarity": 16
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
"""
|
||||
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()
|
||||
@@ -0,0 +1,5 @@
|
||||
name,openalex_author_id,work_count,years_covered,avg_keywords_per_work,distinct_keywords,keyword_distinct_ratio,avg_topics_per_work,distinct_topics,topic_distinct_ratio
|
||||
Lucas Davi,A5089242868,138,18,9.89,324,0.237,2.83,59,0.151
|
||||
Marcus Handte,A5007170803,110,23,9.35,309,0.301,2.79,109,0.355
|
||||
Arman Arzani,A5093075883,8,4,5.38,36,0.837,2.5,19,0.95
|
||||
Pedro José Marrón,A5047117780,286,28,10.02,590,0.206,2.76,183,0.232
|
||||
|
@@ -0,0 +1,104 @@
|
||||
import json
|
||||
from typing import Any
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
OPENALEX_WORKS_URL = "https://api.openalex.org/works"
|
||||
REQUEST_TIMEOUT_SECONDS = 30
|
||||
PER_PAGE = 200
|
||||
|
||||
|
||||
def normalize_author_id(author_id: str) -> str:
|
||||
"""
|
||||
Normalizes OpenAlex author IDs.
|
||||
|
||||
Supported inputs:
|
||||
- A123456789
|
||||
- https://openalex.org/A123456789
|
||||
- https://api.openalex.org/authors/A123456789
|
||||
"""
|
||||
cleaned_author_id = author_id.strip()
|
||||
|
||||
if cleaned_author_id.startswith("https://api.openalex.org/authors/"):
|
||||
return cleaned_author_id.replace(
|
||||
"https://api.openalex.org/authors/",
|
||||
"https://openalex.org/",
|
||||
)
|
||||
|
||||
if cleaned_author_id.startswith("https://openalex.org/"):
|
||||
return cleaned_author_id
|
||||
|
||||
if cleaned_author_id.startswith("A"):
|
||||
return f"https://openalex.org/{cleaned_author_id}"
|
||||
|
||||
return cleaned_author_id
|
||||
|
||||
|
||||
def fetch_openalex_page(
|
||||
author_id: str, cursor: str, select: str | None = None
|
||||
) -> dict[str, Any]:
|
||||
normalized_author_id = normalize_author_id(author_id)
|
||||
|
||||
params = {
|
||||
"filter": f"authorships.author.id:{normalized_author_id}",
|
||||
"per-page": PER_PAGE,
|
||||
"cursor": cursor,
|
||||
"sort": "publication_year:asc",
|
||||
}
|
||||
if select:
|
||||
params["select"] = select
|
||||
|
||||
query_params = urlencode(params)
|
||||
|
||||
url = f"{OPENALEX_WORKS_URL}?{query_params}"
|
||||
|
||||
request = Request(
|
||||
url,
|
||||
headers={
|
||||
"Accept": "application/json",
|
||||
"User-Agent": "AIIS career stage analysis",
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
|
||||
response_body = response.read().decode("utf-8")
|
||||
return json.loads(response_body)
|
||||
|
||||
except HTTPError as error:
|
||||
raise RuntimeError(
|
||||
f"OpenAlex request failed with HTTP status {error.code}: {url}"
|
||||
) from error
|
||||
|
||||
except URLError as error:
|
||||
raise RuntimeError(f"OpenAlex request failed: {error}") from error
|
||||
|
||||
|
||||
def get_all_author_works(
|
||||
author_id: str, select: str | None = None
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
Fetches all works for an OpenAlex author by using cursor pagination.
|
||||
|
||||
`select` restricts the returned fields (comma-separated OpenAlex field
|
||||
names) to keep responses small when only a few fields are needed.
|
||||
"""
|
||||
works: list[dict[str, Any]] = []
|
||||
cursor = "*"
|
||||
|
||||
while cursor:
|
||||
data = fetch_openalex_page(author_id, cursor, select=select)
|
||||
|
||||
page_results = data.get("results", [])
|
||||
works.extend(page_results)
|
||||
|
||||
meta = data.get("meta", {})
|
||||
next_cursor = meta.get("next_cursor")
|
||||
|
||||
if not next_cursor or next_cursor == cursor:
|
||||
break
|
||||
|
||||
cursor = next_cursor
|
||||
|
||||
return works
|
||||
@@ -0,0 +1,134 @@
|
||||
{
|
||||
"2023": [
|
||||
{
|
||||
"year": 2023,
|
||||
"title": "Discovering Potential Founders Based on Academic Background",
|
||||
"keywords": ["Computer science", "Data science"],
|
||||
"topics": ["Education and Critical Thinking Development"],
|
||||
"primary_topic": "Education and Critical Thinking Development"
|
||||
},
|
||||
{
|
||||
"year": 2023,
|
||||
"title": "Challenges in Implementing a University-Based Innovation Search Engine",
|
||||
"keywords": ["Computer science", "Search engine", "World Wide Web"],
|
||||
"topics": ["Big Data and Business Intelligence"],
|
||||
"primary_topic": "Big Data and Business Intelligence"
|
||||
},
|
||||
{
|
||||
"year": 2023,
|
||||
"title": "Exploiting Topic Modelling for the Identification of Untapped Scientific Collaborations",
|
||||
"keywords": [
|
||||
"Data science",
|
||||
"Computer science",
|
||||
"Identification (biology)",
|
||||
"Citation",
|
||||
"Topic model",
|
||||
"Information retrieval",
|
||||
"Knowledge management",
|
||||
"World Wide Web"
|
||||
],
|
||||
"topics": [
|
||||
"Topic Modeling",
|
||||
"Complex Network Analysis Techniques",
|
||||
"Computational and Text Analysis Methods"
|
||||
],
|
||||
"primary_topic": "Topic Modeling"
|
||||
}
|
||||
],
|
||||
"2024": [
|
||||
{
|
||||
"year": 2024,
|
||||
"title": "Ai-Based Pattern Recognition in Limited, Unstructured Information: Improving Joint Value Creation in Mobility as a Service",
|
||||
"keywords": [
|
||||
"Joint (building)",
|
||||
"Service (business)",
|
||||
"Computer science",
|
||||
"Value (mathematics)",
|
||||
"Artificial intelligence",
|
||||
"Pattern recognition (psychology)",
|
||||
"Machine learning",
|
||||
"Business",
|
||||
"Engineering",
|
||||
"Marketing"
|
||||
],
|
||||
"topics": [
|
||||
"Big Data and Business Intelligence",
|
||||
"Customer churn and segmentation",
|
||||
"Semantic Web and Ontologies"
|
||||
],
|
||||
"primary_topic": "Big Data and Business Intelligence"
|
||||
},
|
||||
{
|
||||
"year": 2024,
|
||||
"title": "Discovering potential founders within academic institutions",
|
||||
"keywords": [
|
||||
"Political science",
|
||||
"Mathematics education",
|
||||
"Sociology",
|
||||
"Psychology"
|
||||
],
|
||||
"topics": [
|
||||
"Entrepreneurship Studies and Influences",
|
||||
"Genetics, Bioinformatics, and Biomedical Research",
|
||||
"Biomedical and Engineering Education"
|
||||
],
|
||||
"primary_topic": "Entrepreneurship Studies and Influences"
|
||||
}
|
||||
],
|
||||
"2025": [
|
||||
{
|
||||
"year": 2025,
|
||||
"title": "A Hybrid Approach for Mining the Organizational Structure from University Websites",
|
||||
"keywords": [
|
||||
"Organizational structure",
|
||||
"Key (lock)",
|
||||
"Field (mathematics)",
|
||||
"Information system",
|
||||
"The Internet",
|
||||
"Work (physics)"
|
||||
],
|
||||
"topics": [
|
||||
"Data Mining Algorithms and Applications",
|
||||
"Advanced Text Analysis Techniques",
|
||||
"Web visibility and informetrics"
|
||||
],
|
||||
"primary_topic": "Data Mining Algorithms and Applications"
|
||||
}
|
||||
],
|
||||
"2026": [
|
||||
{
|
||||
"year": 2026,
|
||||
"title": "Technical Architecture of Ecosystems: Customer Application, Middleware and Backend",
|
||||
"keywords": [
|
||||
"Middleware (distributed applications)",
|
||||
"Architecture",
|
||||
"Systems architecture",
|
||||
"Component (thermodynamics)",
|
||||
"Common Object Request Broker Architecture"
|
||||
],
|
||||
"topics": [
|
||||
"Advanced Software Engineering Methodologies",
|
||||
"Green IT and Sustainability",
|
||||
"Sustainable Industrial Ecology"
|
||||
],
|
||||
"primary_topic": "Advanced Software Engineering Methodologies"
|
||||
},
|
||||
{
|
||||
"year": 2026,
|
||||
"title": "Mobility as a Service Transaction Ecosystems Worldwide",
|
||||
"keywords": [
|
||||
"Database transaction",
|
||||
"Service (business)",
|
||||
"Ecosystem",
|
||||
"Key (lock)",
|
||||
"Production (economics)"
|
||||
],
|
||||
"topics": [
|
||||
"Service and Product Innovation",
|
||||
"Transportation and Mobility Innovations",
|
||||
"Information Systems Theories and Implementation"
|
||||
],
|
||||
"primary_topic": "Service and Product Innovation"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
name,role,openalex_author_id
|
||||
Lucas Davi,Professor,A5089242868
|
||||
Marcus Handte,Advisor / Wissenschaftlicher Mitarbeiter,A5007170803
|
||||
Arman Arzani,Advisor / Wissenschaftlicher Mitarbeiter,A5093075883
|
||||
Pedro José Marrón,Professor,A5047117780
|
||||
|
@@ -0,0 +1,186 @@
|
||||
import csv
|
||||
import json
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from openalex_client import get_all_author_works
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent
|
||||
INPUT_FILE = BASE_DIR / "research_timeline_sample.csv"
|
||||
DETAILS_DIR = BASE_DIR / "per_person_details"
|
||||
SUMMARY_FILE = BASE_DIR / "keyword_vs_topic_summary.csv"
|
||||
TOP_TERMS_FILE = BASE_DIR / "top_terms_by_person.csv"
|
||||
|
||||
SELECT_FIELDS = "id,title,publication_year,keywords,topics,primary_topic"
|
||||
TOP_N_TERMS = 15
|
||||
|
||||
|
||||
def extract_work_record(work: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
Reduces one OpenAlex work to the fields relevant for comparing keywords
|
||||
against topics per publication year.
|
||||
"""
|
||||
keywords = [kw.get("display_name") for kw in (work.get("keywords") or [])]
|
||||
topics = [t.get("display_name") for t in (work.get("topics") or [])]
|
||||
primary_topic = (work.get("primary_topic") or {}).get("display_name")
|
||||
|
||||
return {
|
||||
"year": work.get("publication_year"),
|
||||
"title": work.get("title"),
|
||||
"keywords": keywords,
|
||||
"topics": topics,
|
||||
"primary_topic": primary_topic,
|
||||
}
|
||||
|
||||
|
||||
def group_by_year(records: list[dict[str, Any]]) -> dict[int, list[dict[str, Any]]]:
|
||||
by_year: dict[int, list[dict[str, Any]]] = {}
|
||||
|
||||
for record in records:
|
||||
year = record["year"]
|
||||
if not isinstance(year, int):
|
||||
continue
|
||||
by_year.setdefault(year, []).append(record)
|
||||
|
||||
return dict(sorted(by_year.items()))
|
||||
|
||||
|
||||
def summarize_terms(records: list[dict[str, Any]], field: str) -> dict[str, Any]:
|
||||
"""
|
||||
Computes basic descriptive stats for a term field (keywords or topics)
|
||||
across all works of one person.
|
||||
|
||||
`distinct_ratio` = distinct terms / total term mentions. A low ratio
|
||||
means the same terms keep reappearing across many works; a high ratio
|
||||
means most mentions are of a term not seen elsewhere.
|
||||
"""
|
||||
all_terms: list[str] = []
|
||||
per_work_counts: list[int] = []
|
||||
|
||||
for record in records:
|
||||
terms = record[field]
|
||||
per_work_counts.append(len(terms))
|
||||
all_terms.extend(terms)
|
||||
|
||||
total_mentions = len(all_terms)
|
||||
distinct_terms = len(set(all_terms))
|
||||
avg_per_work = total_mentions / len(records) if records else 0.0
|
||||
distinct_ratio = distinct_terms / total_mentions if total_mentions else 0.0
|
||||
|
||||
counter = Counter(all_terms)
|
||||
top_terms = counter.most_common(TOP_N_TERMS)
|
||||
|
||||
return {
|
||||
"total_mentions": total_mentions,
|
||||
"distinct_terms": distinct_terms,
|
||||
"avg_per_work": round(avg_per_work, 2),
|
||||
"distinct_ratio": round(distinct_ratio, 3),
|
||||
"top_terms": top_terms,
|
||||
}
|
||||
|
||||
|
||||
def analyze_sample() -> None:
|
||||
if not INPUT_FILE.exists():
|
||||
raise FileNotFoundError(f"Input file not found: {INPUT_FILE}")
|
||||
|
||||
DETAILS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
summary_rows: list[dict[str, Any]] = []
|
||||
top_terms_rows: list[dict[str, Any]] = []
|
||||
|
||||
with INPUT_FILE.open(mode="r", encoding="utf-8", newline="") as input_file:
|
||||
reader = csv.DictReader(input_file)
|
||||
|
||||
for row in reader:
|
||||
name = row.get("name", "").strip()
|
||||
openalex_author_id = row.get("openalex_author_id", "").strip()
|
||||
|
||||
if not openalex_author_id:
|
||||
print(f"Skipping {name}: missing OpenAlex author ID")
|
||||
continue
|
||||
|
||||
print(f"Fetching works for {name} ({openalex_author_id})...")
|
||||
|
||||
try:
|
||||
works = get_all_author_works(openalex_author_id, select=SELECT_FIELDS)
|
||||
except Exception as error:
|
||||
print(f"Error while processing {name}: {error}")
|
||||
continue
|
||||
|
||||
records = [extract_work_record(work) for work in works]
|
||||
by_year = group_by_year(records)
|
||||
|
||||
details_path = DETAILS_DIR / f"{name.replace(' ', '_')}.json"
|
||||
with details_path.open(mode="w", encoding="utf-8") as details_file:
|
||||
json.dump(by_year, details_file, indent=2, ensure_ascii=False)
|
||||
|
||||
keyword_stats = summarize_terms(records, "keywords")
|
||||
topic_stats = summarize_terms(records, "topics")
|
||||
|
||||
summary_rows.append(
|
||||
{
|
||||
"name": name,
|
||||
"openalex_author_id": openalex_author_id,
|
||||
"work_count": len(records),
|
||||
"years_covered": len(by_year),
|
||||
"avg_keywords_per_work": keyword_stats["avg_per_work"],
|
||||
"distinct_keywords": keyword_stats["distinct_terms"],
|
||||
"keyword_distinct_ratio": keyword_stats["distinct_ratio"],
|
||||
"avg_topics_per_work": topic_stats["avg_per_work"],
|
||||
"distinct_topics": topic_stats["distinct_terms"],
|
||||
"topic_distinct_ratio": topic_stats["distinct_ratio"],
|
||||
}
|
||||
)
|
||||
|
||||
for rank, (term, count) in enumerate(keyword_stats["top_terms"], start=1):
|
||||
top_terms_rows.append(
|
||||
{
|
||||
"name": name,
|
||||
"field": "keyword",
|
||||
"rank": rank,
|
||||
"term": term,
|
||||
"work_count": count,
|
||||
}
|
||||
)
|
||||
for rank, (term, count) in enumerate(topic_stats["top_terms"], start=1):
|
||||
top_terms_rows.append(
|
||||
{
|
||||
"name": name,
|
||||
"field": "topic",
|
||||
"rank": rank,
|
||||
"term": term,
|
||||
"work_count": count,
|
||||
}
|
||||
)
|
||||
|
||||
with SUMMARY_FILE.open(mode="w", encoding="utf-8", newline="") as summary_file:
|
||||
fieldnames = [
|
||||
"name",
|
||||
"openalex_author_id",
|
||||
"work_count",
|
||||
"years_covered",
|
||||
"avg_keywords_per_work",
|
||||
"distinct_keywords",
|
||||
"keyword_distinct_ratio",
|
||||
"avg_topics_per_work",
|
||||
"distinct_topics",
|
||||
"topic_distinct_ratio",
|
||||
]
|
||||
writer = csv.DictWriter(summary_file, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
writer.writerows(summary_rows)
|
||||
|
||||
with TOP_TERMS_FILE.open(mode="w", encoding="utf-8", newline="") as top_terms_file:
|
||||
fieldnames = ["name", "field", "rank", "term", "work_count"]
|
||||
writer = csv.DictWriter(top_terms_file, fieldnames=fieldnames)
|
||||
writer.writeheader()
|
||||
writer.writerows(top_terms_rows)
|
||||
|
||||
print(f"Analysis finished. Summary written to {SUMMARY_FILE}")
|
||||
print(f"Top terms written to {TOP_TERMS_FILE}")
|
||||
print(f"Per-person year/keyword/topic details written to {DETAILS_DIR}/")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
analyze_sample()
|
||||
@@ -0,0 +1,121 @@
|
||||
name,field,rank,term,work_count
|
||||
Lucas Davi,keyword,1,Computer science,126
|
||||
Lucas Davi,keyword,2,Computer security,95
|
||||
Lucas Davi,keyword,3,Operating system,74
|
||||
Lucas Davi,keyword,4,Software,59
|
||||
Lucas Davi,keyword,5,Programming language,54
|
||||
Lucas Davi,keyword,6,Embedded system,45
|
||||
Lucas Davi,keyword,7,Code (set theory),32
|
||||
Lucas Davi,keyword,8,Exploit,30
|
||||
Lucas Davi,keyword,9,Engineering,20
|
||||
Lucas Davi,keyword,10,Control flow,20
|
||||
Lucas Davi,keyword,11,Overhead (engineering),18
|
||||
Lucas Davi,keyword,12,Code reuse,18
|
||||
Lucas Davi,keyword,13,Software engineering,17
|
||||
Lucas Davi,keyword,14,Reuse,17
|
||||
Lucas Davi,keyword,15,Software security assurance,13
|
||||
Lucas Davi,topic,1,Security and Verification in Computing,105
|
||||
Lucas Davi,topic,2,Advanced Malware Detection Techniques,91
|
||||
Lucas Davi,topic,3,Diamond and Carbon-based Materials Research,21
|
||||
Lucas Davi,topic,4,Network Security and Intrusion Detection,17
|
||||
Lucas Davi,topic,5,Physical Unclonable Functions (PUFs) and Hardware Security,16
|
||||
Lucas Davi,topic,6,Cloud Data Security Solutions,13
|
||||
Lucas Davi,topic,7,Blockchain Technology Applications and Security,12
|
||||
Lucas Davi,topic,8,Web Application Security Vulnerabilities,10
|
||||
Lucas Davi,topic,9,Distributed systems and fault tolerance,8
|
||||
Lucas Davi,topic,10,Digital and Cyber Forensics,7
|
||||
Lucas Davi,topic,11,Information and Cyber Security,7
|
||||
Lucas Davi,topic,12,Software Engineering Research,7
|
||||
Lucas Davi,topic,13,Software Testing and Debugging Techniques,6
|
||||
Lucas Davi,topic,14,Adversarial Robustness in Machine Learning,5
|
||||
Lucas Davi,topic,15,Cryptographic Implementations and Security,4
|
||||
Marcus Handte,keyword,1,Computer science,94
|
||||
Marcus Handte,keyword,2,Human–computer interaction,33
|
||||
Marcus Handte,keyword,3,Artificial intelligence,31
|
||||
Marcus Handte,keyword,4,Engineering,29
|
||||
Marcus Handte,keyword,5,Distributed computing,25
|
||||
Marcus Handte,keyword,6,Telecommunications,23
|
||||
Marcus Handte,keyword,7,Ubiquitous computing,22
|
||||
Marcus Handte,keyword,8,World Wide Web,22
|
||||
Marcus Handte,keyword,9,Computer security,20
|
||||
Marcus Handte,keyword,10,Context (archaeology),19
|
||||
Marcus Handte,keyword,11,Wireless,16
|
||||
Marcus Handte,keyword,12,Business,15
|
||||
Marcus Handte,keyword,13,Middleware (distributed applications),15
|
||||
Marcus Handte,keyword,14,Real-time computing,15
|
||||
Marcus Handte,keyword,15,Computer vision,12
|
||||
Marcus Handte,topic,1,Context-Aware Activity Recognition Systems,32
|
||||
Marcus Handte,topic,2,Indoor and Outdoor Localization Technologies,17
|
||||
Marcus Handte,topic,3,IoT and Edge/Fog Computing,14
|
||||
Marcus Handte,topic,4,Distributed systems and fault tolerance,11
|
||||
Marcus Handte,topic,5,Underwater Vehicles and Communication Systems,9
|
||||
Marcus Handte,topic,6,Human Mobility and Location-Based Analysis,9
|
||||
Marcus Handte,topic,7,Energy Efficient Wireless Sensor Networks,8
|
||||
Marcus Handte,topic,8,Robotics and Sensor-Based Localization,8
|
||||
Marcus Handte,topic,9,Advanced Software Engineering Methodologies,6
|
||||
Marcus Handte,topic,10,Service-Oriented Architecture and Web Services,6
|
||||
Marcus Handte,topic,11,Bluetooth and Wireless Communication Technologies,6
|
||||
Marcus Handte,topic,12,Opportunistic and Delay-Tolerant Networks,6
|
||||
Marcus Handte,topic,13,Energy Harvesting in Wireless Networks,6
|
||||
Marcus Handte,topic,14,Mobile Agent-Based Network Management,5
|
||||
Marcus Handte,topic,15,Transportation Planning and Optimization,5
|
||||
Arman Arzani,keyword,1,Computer science,4
|
||||
Arman Arzani,keyword,2,Data science,2
|
||||
Arman Arzani,keyword,3,World Wide Web,2
|
||||
Arman Arzani,keyword,4,Service (business),2
|
||||
Arman Arzani,keyword,5,Key (lock),2
|
||||
Arman Arzani,keyword,6,Search engine,1
|
||||
Arman Arzani,keyword,7,Identification (biology),1
|
||||
Arman Arzani,keyword,8,Citation,1
|
||||
Arman Arzani,keyword,9,Topic model,1
|
||||
Arman Arzani,keyword,10,Information retrieval,1
|
||||
Arman Arzani,keyword,11,Knowledge management,1
|
||||
Arman Arzani,keyword,12,Joint (building),1
|
||||
Arman Arzani,keyword,13,Value (mathematics),1
|
||||
Arman Arzani,keyword,14,Artificial intelligence,1
|
||||
Arman Arzani,keyword,15,Pattern recognition (psychology),1
|
||||
Arman Arzani,topic,1,Big Data and Business Intelligence,2
|
||||
Arman Arzani,topic,2,Education and Critical Thinking Development,1
|
||||
Arman Arzani,topic,3,Topic Modeling,1
|
||||
Arman Arzani,topic,4,Complex Network Analysis Techniques,1
|
||||
Arman Arzani,topic,5,Computational and Text Analysis Methods,1
|
||||
Arman Arzani,topic,6,Customer churn and segmentation,1
|
||||
Arman Arzani,topic,7,Semantic Web and Ontologies,1
|
||||
Arman Arzani,topic,8,Entrepreneurship Studies and Influences,1
|
||||
Arman Arzani,topic,9,"Genetics, Bioinformatics, and Biomedical Research",1
|
||||
Arman Arzani,topic,10,Biomedical and Engineering Education,1
|
||||
Arman Arzani,topic,11,Data Mining Algorithms and Applications,1
|
||||
Arman Arzani,topic,12,Advanced Text Analysis Techniques,1
|
||||
Arman Arzani,topic,13,Web visibility and informetrics,1
|
||||
Arman Arzani,topic,14,Advanced Software Engineering Methodologies,1
|
||||
Arman Arzani,topic,15,Green IT and Sustainability,1
|
||||
Pedro José Marrón,keyword,1,Computer science,264
|
||||
Pedro José Marrón,keyword,2,Computer network,107
|
||||
Pedro José Marrón,keyword,3,Distributed computing,91
|
||||
Pedro José Marrón,keyword,4,Telecommunications,90
|
||||
Pedro José Marrón,keyword,5,Wireless,83
|
||||
Pedro José Marrón,keyword,6,Engineering,80
|
||||
Pedro José Marrón,keyword,7,Artificial intelligence,78
|
||||
Pedro José Marrón,keyword,8,Wireless sensor network,70
|
||||
Pedro José Marrón,keyword,9,Real-time computing,52
|
||||
Pedro José Marrón,keyword,10,Operating system,47
|
||||
Pedro José Marrón,keyword,11,Human–computer interaction,45
|
||||
Pedro José Marrón,keyword,12,World Wide Web,36
|
||||
Pedro José Marrón,keyword,13,Embedded system,33
|
||||
Pedro José Marrón,keyword,14,Computer security,33
|
||||
Pedro José Marrón,keyword,15,Context (archaeology),30
|
||||
Pedro José Marrón,topic,1,Energy Efficient Wireless Sensor Networks,86
|
||||
Pedro José Marrón,topic,2,Context-Aware Activity Recognition Systems,50
|
||||
Pedro José Marrón,topic,3,Mobile Ad Hoc Networks,36
|
||||
Pedro José Marrón,topic,4,Opportunistic and Delay-Tolerant Networks,36
|
||||
Pedro José Marrón,topic,5,Modular Robots and Swarm Intelligence,33
|
||||
Pedro José Marrón,topic,6,Indoor and Outdoor Localization Technologies,29
|
||||
Pedro José Marrón,topic,7,Energy Harvesting in Wireless Networks,20
|
||||
Pedro José Marrón,topic,8,Robotics and Sensor-Based Localization,19
|
||||
Pedro José Marrón,topic,9,IoT and Edge/Fog Computing,17
|
||||
Pedro José Marrón,topic,10,Distributed and Parallel Computing Systems,15
|
||||
Pedro José Marrón,topic,11,Distributed systems and fault tolerance,14
|
||||
Pedro José Marrón,topic,12,Advanced Database Systems and Queries,13
|
||||
Pedro José Marrón,topic,13,Underwater Vehicles and Communication Systems,12
|
||||
Pedro José Marrón,topic,14,Robotic Path Planning Algorithms,12
|
||||
Pedro José Marrón,topic,15,Semantic Web and Ontologies,10
|
||||
|
@@ -1,8 +1,21 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
try:
|
||||
# The job images copy this module next to sync.py, see
|
||||
# service/scripts/jobs-image/Dockerfile.
|
||||
import keyword_extraction
|
||||
except ModuleNotFoundError:
|
||||
# Running from a repo checkout, where it sits in the service package.
|
||||
sys.path.append(
|
||||
str(Path(__file__).resolve().parents[3] / "service/src/main/inse/news")
|
||||
)
|
||||
import keyword_extraction
|
||||
|
||||
load_dotenv()
|
||||
|
||||
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
|
||||
@@ -32,24 +45,33 @@ SYSTEM_PROMPT_NAMES = ("""
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
SYSTEM_PROMPT_KEYWORDS = ("""
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
""")
|
||||
|
||||
_client = OpenAI(
|
||||
base_url=LLM_BASE_URL,
|
||||
api_key=LLM_API_KEY,
|
||||
timeout=30,
|
||||
)
|
||||
|
||||
def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95):
|
||||
def call(
|
||||
system_prompt,
|
||||
user_prompt,
|
||||
model=LLM_MODEL,
|
||||
temperature=1.0,
|
||||
top_p=0.95,
|
||||
top_k=64,
|
||||
json_schema=None,
|
||||
schema_name=None,
|
||||
):
|
||||
response_format = None
|
||||
if json_schema is not None:
|
||||
response_format = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": schema_name or "response",
|
||||
"strict": True,
|
||||
"schema": json_schema,
|
||||
},
|
||||
}
|
||||
|
||||
try:
|
||||
response = _client.chat.completions.create(
|
||||
model=model,
|
||||
@@ -59,7 +81,8 @@ def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.9
|
||||
],
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
extra_body={"top_k": 64},
|
||||
extra_body={"top_k": top_k},
|
||||
response_format=response_format,
|
||||
)
|
||||
except APIConnectionError:
|
||||
return None
|
||||
@@ -83,13 +106,37 @@ def extract_names(text: str) -> list[str]:
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
def extract_keywords(text: str) -> list[str]:
|
||||
result = call(SYSTEM_PROMPT_KEYWORDS, text)
|
||||
def extract_keywords(maintitle: str | None, full_content: str | None) -> list[str]:
|
||||
"""Extracts an article's keywords, identically to the news detail endpoint.
|
||||
|
||||
Prompt, input bound, sampling and normalization all come from
|
||||
keyword_extraction, so both callers write the same keywords into
|
||||
aktuell_postproc regardless of which one reaches an article first.
|
||||
"""
|
||||
user_prompt = keyword_extraction.build_user_prompt(maintitle, full_content)
|
||||
if not user_prompt:
|
||||
return []
|
||||
|
||||
result = call(
|
||||
keyword_extraction.KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt,
|
||||
temperature=keyword_extraction.TEMPERATURE,
|
||||
top_p=keyword_extraction.TOP_P,
|
||||
top_k=keyword_extraction.TOP_K,
|
||||
json_schema=keyword_extraction.RESPONSE_SCHEMA,
|
||||
schema_name=keyword_extraction.SCHEMA_NAME,
|
||||
)
|
||||
if result is None:
|
||||
return []
|
||||
|
||||
try:
|
||||
import json
|
||||
data = json.loads(result)
|
||||
return data.get("keywords", [])
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
candidates = data.get("keywords")
|
||||
if not isinstance(candidates, list):
|
||||
return []
|
||||
|
||||
return keyword_extraction.normalize_keywords(candidates)
|
||||
|
||||
@@ -20,10 +20,11 @@ def sync_single_news(news_id, max_retries=3):
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
article = es_client.get_entry("aktuell", news_id)["_source"]
|
||||
news_text = article["full_content"]
|
||||
is_news_relevant = llm_client.is_news_relevant(news_text)
|
||||
authors = llm_client.extract_names(news_text)
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
keywords = llm_client.extract_keywords(article.get("maintitle"), news_text)
|
||||
new_entry = {
|
||||
"news_id": news_id,
|
||||
"relevant": is_news_relevant,
|
||||
@@ -48,8 +49,10 @@ def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retr
|
||||
attempt = 0
|
||||
while attempt < max_retries:
|
||||
try:
|
||||
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
|
||||
keywords = llm_client.extract_keywords(news_text)
|
||||
article = es_client.get_entry("aktuell", news_id)["_source"]
|
||||
keywords = llm_client.extract_keywords(
|
||||
article.get("maintitle"), article["full_content"]
|
||||
)
|
||||
if not keywords:
|
||||
# Empty article or unparseable LLM answer: writing an empty list
|
||||
# would look like a success and block a later retry.
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
# Master's thesis on the INSE knowledge graph: three research plans
|
||||
|
||||
Status: proposal, 2026-09-17. Supersedes the engineering-oriented outline
|
||||
(`~/.claude/plans/consider-the-context-of-robust-hopcroft.md`) as the basis for choosing a topic.
|
||||
|
||||
Three alternative six-month theses, one per research community. Pick one; they share data and
|
||||
infrastructure but differ in research question, method and evaluation.
|
||||
|
||||
| | Plan | Community | One-line question |
|
||||
|---|---|---|---|
|
||||
| A | [Certain, possible, wrong](plan-a-knowledge-graphs.md) | Knowledge graphs / Semantic Web | What does identity-link error do to answers over a multi-source graph, and can answers carry that uncertainty? |
|
||||
| B | [Learning when not to answer](plan-b-nlp.md) | NLP | Can reinforcement fine-tuning make a small model reliable at text-to-Cypher, including abstaining and qualifying, in German and English? |
|
||||
| C | [Does the graph find the right people?](plan-c-information-retrieval.md) | Information retrieval | Does graph evidence improve expert and industry-partner retrieval when evaluated without temporal leakage? |
|
||||
|
||||
## Why the original outline is no longer a research topic
|
||||
|
||||
The original outline had five parts: build the graph, fix identities, write a benchmark, compare
|
||||
retrieval setups, fine-tune text-to-Cypher. Two things changed.
|
||||
|
||||
**The engineering is done.** `service/scripts/falkordb/bulk_load.py` builds the whole-university graph
|
||||
in about 20 minutes: 6,176 active UDE researchers, 204,110 works, 693,487 authors, 26,246 institutions,
|
||||
3,664 projects, 366 patents, 4,402 news articles, 547 companies and 10 million relationships, in 1.3 GB
|
||||
of FalkorDB memory. A local LLM (LM Studio, qwen3-8b) already queries it through the FalkorDB MCP
|
||||
server, and `service/scripts/falkordb/QUERIES.md` holds a tested query cookbook.
|
||||
|
||||
**The obvious research questions are published.** Literature check, September 2026 (from search
|
||||
results and abstracts; the student must read and verify each before citing):
|
||||
|
||||
| Idea in the original outline | Already covered by |
|
||||
|---|---|
|
||||
| Fine-tune a small model for text-to-Cypher, also with RL and execution feedback | Text2Cypher (Ozsoy et al., GenAIK 2025); "Refining Text2Cypher on Small Language Model with Reinforcement Learning" (Applied Sciences 15(15):8206, 2025, GRPO); Multi-Agent GraphRAG text-to-Cypher (arXiv 2511.08274) |
|
||||
| Generate training and test questions from the graph itself | CypherBench (ACL 2025); PIPE-Cypher (arXiv 2606.08481); KG2Cypher (arXiv 2606.27742); grounded KG data generation (arXiv 2606.14325) |
|
||||
| Non-English text-to-Cypher | Text2Cypher Across Languages (arXiv 2506.21445; Spanish, Turkish); adapter combination (arXiv 2601.16097). German is still missing, but adding a language alone is incremental |
|
||||
| Does the graph beat vector search, and on which question types | "When to use Graphs in RAG" / GraphRAG-Bench (ICLR 2026, arXiv 2506.05690); "RAG vs. GraphRAG" (arXiv 2502.11371); "Do We Still Need GraphRAG?" (arXiv 2604.09666); GraphRAG-Router (arXiv 2604.16401) |
|
||||
| Agentic, multi-step graph retrieval trained with RL | Graph-R1 (arXiv 2507.21892); KG-R1 (arXiv 2509.26383) |
|
||||
| Robustness of KG-augmented LLMs to a noisy graph | OKGQA-P (ACL 2025, arXiv 2410.08085); KG-RAG under incompleteness (2025); "Less is More: Denoising KGs for RAG" (arXiv 2510.14271). All use random perturbations or LLM-extracted graphs |
|
||||
|
||||
## What is still open, and why this project is well placed
|
||||
|
||||
Building and querying the `ude` graph produced five observations that the literature does not
|
||||
address and that the project's data can test:
|
||||
|
||||
1. **The links between sources are inferred, with structured error.** Patents carry no person IDs, so
|
||||
`INVENTOR_OF` rests on name matching (`match_type` institution / name / both). Company officers and
|
||||
news mentions are exact name matches (`common_name_warning`, `ambiguous`). One researcher named
|
||||
Thomas Kaiser matches 92 companies. OpenAlex itself over-merges profiles: a cohort profile
|
||||
"Róbert Langer" carries the MIT chemist's 251 industry partners. Prior robustness work perturbs
|
||||
graphs at random; nobody measures what realistic identity error does to answers.
|
||||
2. **Link semantics change numbers by a factor of six.** Industry co-publications of one researcher:
|
||||
61 with author-level affiliations, 10 when the affiliation must hold on the paper itself. Counting
|
||||
and ranking answers are fragile in a way lookups are not.
|
||||
3. **Observed and inferred edges sit side by side** (`DFG_ROLE` via ORCID is verified, `OFFICER_OF` is a
|
||||
name match), and every inferred edge records its method. That is the raw material for confidence-
|
||||
and provenance-aware answering, which exists in database theory (certain and possible answers,
|
||||
identity-linkage uncertainty) but not in LLM-based graph question answering.
|
||||
4. **A small local model fails silently.** Without the schema, qwen3-8b invented a property
|
||||
(`a.institution`), got nulls, and told the user the information "is not available". Separately, the
|
||||
server's 10,000-row result cap truncated a 206k-row read without any error. Neither failure is
|
||||
visible to the user. Reliability (answer, qualify, or abstain) is unexplored for text-to-Cypher;
|
||||
TrustSQL (arXiv 2403.15879) and GrailQAbility (ACL 2023) cover SQL and Freebase only, and
|
||||
abstention-aware RL (TruthRL, arXiv 2509.25760) covers open-domain QA only.
|
||||
5. **The graph has time.** Works, patents, projects and per-paper affiliations are dated up to 2026, so
|
||||
"who will start working with industry" can be evaluated on events that happened after a language
|
||||
model's knowledge cutoff, which is the only leakage-free way to evaluate LLM-based recommendation.
|
||||
|
||||
## Assets every plan can use
|
||||
|
||||
- The `ude` graph, loader (`bulk_load.py`, twelve idempotent phases), and query cookbook.
|
||||
- Edge-level evidence: `INVENTOR_OF.match_type`, `OFFICER_OF.common_name_warning`,
|
||||
`Author.hr_company_matches`, `MENTIONED_IN.ambiguous`, `DFG_ROLE.source`, `AUTHORED.institution_ids`,
|
||||
`Work.primary_category` (LLM classification of 187k works).
|
||||
- Existing evaluations to build on: `service/scripts/patents/data/author_patent_evaluation/` (three
|
||||
experiments on author-patent matching), `llm_evaluations/news_ident_person/` (50 labelled news
|
||||
articles), `analysis/career_stage/` (60 labelled researchers, 4.6% suspicious profiles),
|
||||
`service/scripts/profiling/founding_potential/`, `llm_evaluations/sentence_transformer/`.
|
||||
- LLM access through `inse.integrations.llm` (any OpenAI-compatible endpoint), a terminal harness that
|
||||
drives an LLM through the FalkorDB MCP tools, and the e5 embedding model in the service image.
|
||||
|
||||
## Fixed conditions (decided 2026-09-17)
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Duration | 26 weeks |
|
||||
| Annotation | Two annotators, about 40 hours each |
|
||||
| Data release | Open sources only: OpenAlex (CC0), CORDIS, patent offices; DFG GEPRIS licence to be checked. Handelsregister and news-person links stay internal; results on them are reported in aggregate |
|
||||
| Compute | One 80 GB GPU: QLoRA supervised fine-tuning and GRPO on 7 to 8B models are feasible |
|
||||
| Tools | FalkorDB, Unsloth (as in the original outline) |
|
||||
| Data protection | One agreed paragraph with the chair before week 3; a section in the thesis |
|
||||
|
||||
## How to choose
|
||||
|
||||
| | A: knowledge graphs | B: NLP | C: information retrieval |
|
||||
|---|---|---|---|
|
||||
| Core novelty | Realistic identity error, certain/possible answers, LLM pipelines that use link confidence | Reliability-aware RL for text-to-Cypher, infeasible and uncertain questions, German | Leakage-free evaluation of graph-augmented expert and partner retrieval, graph-supervised reranker |
|
||||
| Main risk | Gold set quality; possible-worlds cost on aggregates | A close paper appears first; RL instability | Too few post-cutoff events; pooling depth |
|
||||
| Fine-tuning share | Small (one supervised model) | Central (SFT and GRPO, several models) | Medium (reranker) |
|
||||
| Annotation use | 500 to 600 identity links, answer-quality ratings | 400 question validations, German naturalness, error taxonomy | 1,500 to 2,000 relevance judgments |
|
||||
| Value to INSE after the thesis | Confidence on every cross-source link, fixes the biggest data-quality problem | A local model that can be trusted in the UI | A measured answer to "should scouting use the graph" and a reusable test collection |
|
||||
| Student profile | Data management, statistics, some ML | Deep learning, RL, NLP evaluation | IR evaluation, ranking, some graph ML |
|
||||
| Venues | ISWC, ESWC, CIKM, K-CAP; Semantic Web Journal, TGDK | ACL / EMNLP / NAACL Findings; TrustNLP, UncertaiNLP, KnowledgeNLP, GenAIK; LREC-COLING for the dataset | SIGIR (short, resource), ECIR, CIKM, ICTIR; JCDL |
|
||||
|
||||
Recommendation: Plan A is the most defensible against being scooped, because it depends on data only
|
||||
this project has (measured cross-source identity error), and it turns the most valuable part of the
|
||||
original outline (Part 2) into the research question. Plan B is the best fit if the student wants a
|
||||
model-centric thesis and the 80 GB GPU should be used fully. Plan C has the most direct product value.
|
||||
|
||||
Combining is possible but should be resisted: each plan fills 26 weeks. The one sensible overlap is
|
||||
that Plan B may borrow Plan A's "uncertain evidence" question category, and Plan C may report
|
||||
Plan A's robustness-to-identity-error as one ablation.
|
||||
|
||||
## Common first four weeks
|
||||
|
||||
1. Run INSE locally, obtain Elasticsearch read access, rebuild `ude` with `run.sh bulk --graph ude --reset`.
|
||||
2. Read `service/scripts/falkordb/README.md`, `QUERIES.md`, the profiling READMEs.
|
||||
3. Literature chapter skeleton from the reading list in the chosen plan; verify every citation.
|
||||
4. Data-protection paragraph agreed; annotation guidelines drafted; annotators booked.
|
||||
@@ -1,127 +0,0 @@
|
||||
# Plan A (knowledge graphs): Certain, possible, wrong
|
||||
|
||||
**Working title:** Certain, possible, wrong: question answering over a multi-source scholarly knowledge
|
||||
graph with uncertain identity links
|
||||
|
||||
**Target venues:** ISWC or ESWC (research or resources track), CIKM, K-CAP. Journal extension: Semantic
|
||||
Web Journal or TGDK.
|
||||
|
||||
## The problem in one paragraph
|
||||
|
||||
The INSE graph joins researchers to patents, companies, news and projects. Only some of those joins
|
||||
are observed (authorship, ORCID-verified DFG roles, DOI-linked project output). The rest are inferred
|
||||
from names, and OpenAlex's own author identities are partly over-merged. Every question that crosses
|
||||
a source boundary therefore rests on links that may be wrong, and counting or ranking questions can
|
||||
flip on a single false merge. Current work on LLMs and knowledge graphs either assumes a clean graph
|
||||
or perturbs it at random. This thesis measures real identity error, models how it propagates into
|
||||
answers, and tests whether answers can carry that uncertainty instead of hiding it.
|
||||
|
||||
## Gap and closest related work
|
||||
|
||||
- Robustness of KG-augmented LLMs is studied with random node and edge perturbations (OKGQA-P, ACL 2025,
|
||||
arXiv 2410.08085; KG-RAG under incompleteness, 2025) and denoising targets LLM-extracted graphs
|
||||
("Less is More", arXiv 2510.14271). Identity error is neither random nor local: it is concentrated on
|
||||
common names and on hubs, and it changes aggregates.
|
||||
- Database theory defines query answering under identity uncertainty (Moustafa et al., "Subgraph
|
||||
pattern matching over uncertain graphs with identity linkage uncertainty", arXiv 1305.7006;
|
||||
uncertainty-annotated databases, arXiv 1904.00234; combining entity resolution and query answering,
|
||||
arXiv 2303.07469; provenance of result probabilities in uncertain KGs, arXiv 2108.07758). None of it
|
||||
is connected to LLM-based question answering, and none is evaluated on a real multi-source graph of
|
||||
this kind.
|
||||
- Entity-resolution evaluation has matured (entity-centric evaluation for inventor disambiguation,
|
||||
arXiv 2404.05622; OpenAlex author accuracy with an LLM-assisted benchmark, arXiv 2502.11610; LLMs for
|
||||
entity matching, arXiv 2310.11244 and 2409.08185), but stops at precision and recall of the links.
|
||||
What a link error costs downstream is not measured.
|
||||
- A 2026 preprint names a "provenance gap" in incomplete KGQA (arXiv 2606.15833); the student should
|
||||
read it first and position against it.
|
||||
|
||||
## Research questions
|
||||
|
||||
- **RQ1. How wrong are the links?** Precision, recall and calibration of four link types: author to
|
||||
inventor, author to company officer, author to news mention, and OpenAlex over-merged author
|
||||
profiles. Which evidence (name rarity, topic overlap between IPC classes and OpenAlex topics,
|
||||
assignee match, temporal overlap, shared co-authors and co-inventors) predicts correctness?
|
||||
- **RQ2. How does link error reach the answer?** For lookup, multi-hop, counting and ranking queries:
|
||||
how much does the answer change per unit of link error, and does realistic error (sampled from the
|
||||
RQ1 error model) behave differently from the random perturbation used in prior benchmarks?
|
||||
- **RQ3. Can certain and possible answers be computed at interactive cost?** Monte Carlo sampling of
|
||||
possible worlds over link confidence, giving intervals for counts and stable sets for rankings,
|
||||
compared with exact computation on small subgraphs.
|
||||
- **RQ4. Does exposing link confidence make LLM question answering more reliable?** Text-to-Cypher
|
||||
and tool-using pipelines with and without access to confidence and provenance, including one
|
||||
supervised fine-tuned model that writes confidence-aware queries and reports "confirmed" versus
|
||||
"possible" results.
|
||||
|
||||
## Method
|
||||
|
||||
1. **Gold set (weeks 5 to 9).** About 550 candidate links, stratified by link type and by name
|
||||
frequency so that common names are over-sampled. Two annotators label each link independently
|
||||
using the evidence a human scout would check (ORCID, institutional pages, patent assignee, register
|
||||
entry); disagreements are adjudicated. Report Cohen's kappa. Budget: about 60 of the 80 hours.
|
||||
2. **Confidence model.** A small calibrated classifier (logistic regression and gradient boosting)
|
||||
over evidence features, trained on the gold set with cross-validation; reliability diagrams and
|
||||
expected calibration error. Output: a `confidence` and `method` on every inferred edge in the graph.
|
||||
3. **Error model and injection toolkit.** Fit where errors occur (by name frequency, degree, source),
|
||||
then generate corrupted graph variants three ways: uniformly random, degree-preserving, and
|
||||
realistic (sampled from the fitted model), at error rates from 1 to 20 percent.
|
||||
4. **Query set.** About 300 queries in the five types of the original outline (lookup, counting,
|
||||
multi-step, summary, over time), each tagged with the link types it crosses. Gold answers come from
|
||||
executing reference Cypher on a reference graph restricted to verified links.
|
||||
5. **Possible-worlds answering.** Sample link sets according to confidence, execute, aggregate:
|
||||
intervals for counts, inclusion probabilities for set answers, rank stability for top-k. Measure
|
||||
interval coverage against the reference and the cost per query.
|
||||
6. **LLM pipelines.** Four systems (schema-prompted text-to-Cypher, tool-using agent over MCP, the
|
||||
same two with confidence exposed) across three models (local 8B, the fine-tuned 8B, one hosted
|
||||
large model). The fine-tuned model is trained with Unsloth on graph-generated pairs whose target
|
||||
queries filter or split by confidence.
|
||||
|
||||
## Evaluation
|
||||
|
||||
| Question | Measures |
|
||||
|---|---|
|
||||
| RQ1 | Pairwise and entity-centric precision, recall, F1 per link type; kappa; ECE and reliability diagrams; feature ablation |
|
||||
| RQ2 | Answer change versus error rate per query type: exact match, Jaccard for sets, relative error for counts, Kendall tau for rankings; realistic versus random noise; with and without entity resolution (the ablation from the original outline) |
|
||||
| RQ3 | Coverage of 90 percent intervals, interval width, agreement with exact computation on subgraphs up to a tractable size, latency versus number of sampled worlds |
|
||||
| RQ4 | Execution accuracy; penalty-based reliability score in the style of TrustSQL; share of answers that correctly flag uncertain evidence; human rating of answer usefulness on 100 answers (remaining annotation hours); cost and latency |
|
||||
|
||||
Statistics: bootstrap confidence intervals everywhere, paired tests between systems, three seeds for
|
||||
anything trained.
|
||||
|
||||
## What gets released (open sources only)
|
||||
|
||||
- The author-to-inventor gold set (OpenAlex and patent-office data are public) with annotation guidelines.
|
||||
- The noise-injection toolkit and the possible-worlds query layer for FalkorDB.
|
||||
- The query set and reference answers over the open subgraph (OpenAlex, CORDIS, patents; DFG after a
|
||||
licence check). Officer and news results are reported in aggregate only.
|
||||
|
||||
## Schedule
|
||||
|
||||
| Weeks | Work |
|
||||
|---|---|
|
||||
| 1 to 4 | Common start; literature; annotation guidelines |
|
||||
| 5 to 9 | Gold set, agreement, RQ1 numbers |
|
||||
| 10 to 12 | Confidence model, edges annotated in the graph, error model |
|
||||
| 13 to 15 | Query set and reference answers |
|
||||
| 16 to 18 | Injection experiments (RQ2) |
|
||||
| 19 to 21 | Possible-worlds answering (RQ3) |
|
||||
| 22 to 24 | LLM pipelines and fine-tuned model (RQ4) |
|
||||
| 25 to 26 | Writing, paper draft |
|
||||
|
||||
Cut order if late: drop the fine-tuned model in RQ4 first (keep prompting-only pipelines), then reduce
|
||||
RQ3 to counts only. Never cut the gold set.
|
||||
|
||||
## Risks
|
||||
|
||||
- **Gold set too small for rare error types.** Mitigation: stratified sampling, and ORCID-verified
|
||||
links as an additional silver standard.
|
||||
- **Possible-worlds sampling too slow for aggregates over millions of edges.** Mitigation: restrict
|
||||
sampling to the edges a query touches; FalkorDB executes the per-world query in milliseconds.
|
||||
- **Reviewers ask for a second dataset.** Mitigation: run the injection experiments also on STaRK-MAG
|
||||
(arXiv 2404.13207) or a CypherBench graph, where only synthetic error is possible; that contrast is
|
||||
itself a result.
|
||||
|
||||
## Reading list to start from
|
||||
|
||||
arXiv 2410.08085, 2510.14271, 2606.15833, 1305.7006, 1904.00234, 2303.07469, 2108.07758, 2404.05622,
|
||||
2502.11610, 2310.11244, 2409.08185, 2403.15879, 2506.05690. All identifiers come from a literature search
|
||||
on 2026-09-17 and must be verified.
|
||||
@@ -1,121 +0,0 @@
|
||||
# Plan B (NLP): Learning when not to answer
|
||||
|
||||
**Working title:** Learning when not to answer: reliability-aware reinforcement fine-tuning of small
|
||||
language models for text-to-Cypher in German and English
|
||||
|
||||
**Target venues:** ACL, EMNLP or NAACL Findings; workshops TrustNLP, UncertaiNLP, KnowledgeNLP, GenAIK;
|
||||
LREC-COLING for the dataset.
|
||||
|
||||
## The problem in one paragraph
|
||||
|
||||
A local model that translates questions into Cypher fails in ways the user cannot see. In this
|
||||
project, an 8B model without the schema invented a property, received nulls, and reported that the
|
||||
information "is not available"; a server-side result cap silently truncated a count; and a question
|
||||
about a researcher named Thomas Kaiser can only be answered over 92 name-matched companies. Accuracy
|
||||
on answerable questions, which is what text-to-Cypher papers report, does not capture any of this. A
|
||||
deployable model must do one of three things: answer, answer with a qualification, or decline. This
|
||||
thesis builds the benchmark for that behaviour and tests whether reinforcement fine-tuning with
|
||||
execution-verified, penalty-aware rewards can teach it to a small model, in two languages.
|
||||
|
||||
## Gap and closest related work
|
||||
|
||||
- Text-to-Cypher fine-tuning is established, including RL: Text2Cypher (GenAIK 2025), GRPO refinement
|
||||
for small models (Applied Sciences 15(15):8206, 2025), multi-agent text-to-Cypher (arXiv 2511.08274),
|
||||
automatic dataset generation (CypherBench, ACL 2025; arXiv 2606.08481, 2606.27742, 2606.14325). All
|
||||
evaluate answerable questions only.
|
||||
- Reliability with infeasible questions exists for SQL (TrustSQL, arXiv 2403.15879, penalty-based
|
||||
scoring) and for Freebase KBQA (GrailQAbility, ACL 2023; RetinaQA, ACL 2024). Not for property graphs,
|
||||
not for LLM-era text-to-Cypher.
|
||||
- Abstention-aware RL exists for open-domain QA (TruthRL, arXiv 2509.25760, ternary reward; KARL,
|
||||
arXiv 2604.22779; TIAR, arXiv 2605.25850; search agents, arXiv 2607.10738). There the reward needs a
|
||||
judge or a gold string. Text-to-Cypher has a verifiable reward by execution, and a third outcome
|
||||
these papers do not have: the correct answer exists but rests on uncertain evidence.
|
||||
- Multilingual text-to-Cypher covers Spanish and Turkish (arXiv 2506.21445, 2601.16097). German is
|
||||
missing, and German compounds plus English entity names make it a real test, not a translation
|
||||
exercise.
|
||||
|
||||
## Research questions
|
||||
|
||||
- **RQ1. Benchmark.** What kinds of questions should a text-to-Cypher model not answer plainly over a
|
||||
real graph? Proposed categories: schema element missing, value missing, beyond Cypher, ambiguous
|
||||
entity (common names), outside the covered time span, aggregation over inferred links, and unsafe
|
||||
aggregation (result cap or timeout would truncate).
|
||||
- **RQ2. Training.** Does GRPO with an execution-verified, penalty-aware reward beat supervised
|
||||
fine-tuning on reliability, and how does the reward shape (binary, ternary, penalty-weighted,
|
||||
with a "qualified answer" outcome) trade accuracy against over-abstention?
|
||||
- **RQ3. Language.** How large is the German to English gap before and after training; does training
|
||||
in one language transfer; does translated training data suffice?
|
||||
- **RQ4. Generalisation.** Held-out schema regions (patents and companies unseen in training),
|
||||
compositional depth, paraphrases, and transfer to public graphs (a CypherBench graph extended with
|
||||
infeasible questions) so that the main results are reproducible without INSE data.
|
||||
- **RQ5. What changed?** Error taxonomy before and after RL; calibration of the decision to abstain.
|
||||
|
||||
## Method
|
||||
|
||||
1. **Dataset.** Templates filled from the graph, paraphrased by a larger model, in German and
|
||||
English, about 6,000 training and 1,200 test items, half answerable. Test entities and templates
|
||||
never occur in training. The open subgraph (OpenAlex, CORDIS, patents) is the release version; the
|
||||
full graph adds company and news questions for internal results.
|
||||
2. **Human validation (80 hours).** Two annotators validate about 400 test items for correctness of
|
||||
the label, category and German naturalness (kappa reported), and later classify about 300 model
|
||||
errors into the taxonomy.
|
||||
3. **Public counterpart.** The same infeasibility categories constructed on one CypherBench graph,
|
||||
which carries no real identity uncertainty; "aggregation over inferred links" is simulated there.
|
||||
4. **Models.** Qwen3-4B and 8B, Llama-3.1-8B, one Gemma model. Baselines: zero-shot and few-shot, a
|
||||
hosted large model, the public Neo4j text2cypher fine-tune, RL without abstention.
|
||||
5. **Training.** Unsloth QLoRA supervised fine-tuning, then GRPO. Reward from execution: result-set
|
||||
equivalence for answers, category match for abstentions, a graded reward for qualified answers
|
||||
(correct result plus correct flag), and a penalty c for wrong answers. Sweep c. Three seeds each.
|
||||
|
||||
## Evaluation
|
||||
|
||||
| Aspect | Measures |
|
||||
|---|---|
|
||||
| Answerable questions | Execution accuracy by result-set equivalence, by question type and hop count |
|
||||
| Reliability | TrustSQL-style score RS(c) for c in {0, 1, 10}; abstention precision, recall and F1 per category; over-abstention rate; risk-coverage curves |
|
||||
| Qualification | Share of uncertain-evidence questions answered with the correct flag; human usefulness rating on a sample |
|
||||
| Calibration | ECE of the answer-or-abstain decision; selective accuracy |
|
||||
| Language | German minus English gap per model and training regime; transfer matrix |
|
||||
| Generalisation | Held-out schema, depth, paraphrase; transfer to the CypherBench variant |
|
||||
| Cost | Tokens, latency, GPU hours per point of RS gained; data-efficiency curves |
|
||||
|
||||
Statistics: bootstrap intervals, McNemar between systems, three seeds, all prompts and decoding
|
||||
settings released.
|
||||
|
||||
## What gets released
|
||||
|
||||
Benchmark on the open subgraph in two languages, the CypherBench extension, LoRA adapters, reward and
|
||||
evaluation code.
|
||||
|
||||
## Schedule
|
||||
|
||||
| Weeks | Work |
|
||||
|---|---|
|
||||
| 1 to 4 | Common start; literature; category definitions |
|
||||
| 5 to 9 | Dataset generation, German versions, human validation |
|
||||
| 10 to 11 | Public counterpart on CypherBench |
|
||||
| 12 to 14 | Baselines and supervised fine-tuning |
|
||||
| 15 to 19 | GRPO, reward ablations, seeds |
|
||||
| 20 to 22 | Language and generalisation experiments |
|
||||
| 23 to 24 | Error taxonomy, calibration analysis |
|
||||
| 25 to 26 | Writing, paper draft |
|
||||
|
||||
Cut order if late: drop the third and fourth base model, then the qualified-answer outcome (keep
|
||||
answer versus abstain). Never cut the public counterpart; without it the NLP community cannot
|
||||
reproduce the main table.
|
||||
|
||||
## Risks
|
||||
|
||||
- **A close paper appears.** The space moves fast. Mitigation: the combination of uncertain-evidence
|
||||
questions, a real multi-source graph and German is hard to replicate; submit a dataset paper early.
|
||||
- **RL collapses into always abstaining or never abstaining.** Known from TruthRL-style training.
|
||||
Mitigation: balanced batches, penalty sweep, KL control, report the failure honestly if it persists.
|
||||
- **Template artefacts.** Models learn templates rather than semantics. Mitigation: paraphrase
|
||||
diversity, template-held-out test split, human-written subset of 150 questions.
|
||||
|
||||
## Reading list to start from
|
||||
|
||||
arXiv 2403.15879, 2212.10189, 2403.10849, 2509.25760, 2604.22779, 2605.25850, 2607.10738, 2506.21445,
|
||||
2601.16097, 2412.18702, 2511.08274, 2606.08481, 2606.27742, 2606.14325; Applied Sciences 15(15):8206;
|
||||
"Why Uncertainty Estimation Methods Fall Short in RAG" (Findings of ACL 2025). All identifiers come from
|
||||
a literature search on 2026-09-17 and must be verified.
|
||||
@@ -1,129 +0,0 @@
|
||||
# Plan C (information retrieval): Does the graph find the right people?
|
||||
|
||||
**Working title:** Does the graph find the right people? A leakage-free evaluation of graph-augmented
|
||||
expert and industry-partner retrieval for technology transfer
|
||||
|
||||
**Target venues:** SIGIR (short or resource paper), ECIR, CIKM, ICTIR. Alternative: JCDL.
|
||||
|
||||
## The problem in one paragraph
|
||||
|
||||
INSE exists to help scouts find the right researcher for a topic and the right partner for a
|
||||
researcher. Today that is keyword and vector search over profiles. The graph adds collaboration,
|
||||
projects, patents, per-paper industry affiliations and time. Whether that improves ranking is an
|
||||
empirical question, and the usual way to answer it with LLM-based rankers is broken: a model that has
|
||||
read the web up to 2025 already "knows" who collaborated with whom, so evaluating on past events
|
||||
measures memory, not retrieval. This thesis builds a test collection with two kinds of ground truth,
|
||||
human relevance judgments and events that happened after the models' knowledge cutoff, and uses it to
|
||||
compare text, graph and LLM rankers, including a reranker fine-tuned on supervision derived from the
|
||||
graph itself.
|
||||
|
||||
## Gap and closest related work
|
||||
|
||||
- Partner and collaboration recommendation is studied with graph learning on single sources:
|
||||
university-industry recommendation on a topic-institution graph (Scientometrics, 2025), technological
|
||||
partner recommendation from patents with temporal heterogeneous graphs (Information Processing and
|
||||
Management, 2025), hypergraph link prediction for collaboration (2026). They use one data source,
|
||||
institutions rather than people, and no LLM.
|
||||
- "Can LLMs Predict Academic Collaboration?" (arXiv 2604.01379) compares topology heuristics with LLM
|
||||
link prediction on co-authorship only, and temporal leakage is the open issue. Work on LLM
|
||||
backtesting shows how strongly leakage inflates results (arXiv 2602.17234, 2605.03762, 2605.18843).
|
||||
- STaRK-MAG (NeurIPS D&B 2024, arXiv 2404.13207) evaluates retrieval over a scholarly graph with
|
||||
synthetic queries for papers, not people, and without time.
|
||||
- GraphRAG versus RAG comparisons (arXiv 2506.05690, 2502.11371, 2604.09666) use text corpora and
|
||||
question answering, not ranking of people with graded relevance.
|
||||
- Classic expert-finding test collections (W3C, CERC, academic collections) predate LLM rankers and
|
||||
multi-source graphs. There is no current collection for expert finding in a German research setting.
|
||||
|
||||
## Tasks
|
||||
|
||||
- **T1 Expert finding.** Query: a topic or need as a scout would phrase it, in German or English.
|
||||
Result: ranked UDE researchers.
|
||||
- **T2 Partner recommendation.** Query: a researcher. Result: ranked companies (OpenAlex institutions
|
||||
of type `company`) the researcher is likely to start working with.
|
||||
|
||||
## Research questions
|
||||
|
||||
- **RQ1.** Does graph evidence improve ranking beyond text? Which evidence (co-authorship, projects,
|
||||
patents, per-paper industry affiliation, recency) carries the gain, for T1 and T2 separately?
|
||||
- **RQ2.** Can a small reranker fine-tuned on supervision derived from the graph (future links as
|
||||
positives, topic-similar non-links as hard negatives) match a large zero-shot LLM reranker at a
|
||||
fraction of the cost?
|
||||
- **RQ3.** How much of an LLM ranker's quality is parametric memory? Compare events before and after
|
||||
the model's knowledge cutoff, and rankings with researcher names masked.
|
||||
- **RQ4.** Who benefits? Exposure of early-career versus established researchers under each ranker,
|
||||
and sensitivity of rankings to identity errors (junk company institutions, over-merged profiles).
|
||||
|
||||
## Method
|
||||
|
||||
1. **Temporal split.** Freeze the graph at a cut date T (end of 2023 for training signals). Test
|
||||
events after T: first-time per-paper industry affiliations (`INVOLVES` to a company with no earlier
|
||||
joint work), new patents, new CORDIS and DFG project participations. A second, smaller test set uses
|
||||
only events after the newest evaluated model's knowledge cutoff.
|
||||
2. **Topics.** 50 to 60 T1 topics drawn from real material: CORDIS call topics, IPC class
|
||||
descriptions, news themes, and needs phrased by the chair's transfer contacts, each in German and
|
||||
English. T2 uses about 300 researchers with at least one post-T event.
|
||||
3. **Relevance judgments (80 hours).** Pooled top-20 of all systems per T1 topic, graded 0 to 3 by two
|
||||
annotators with an overlap sample for agreement: about 1,500 to 2,000 judgments at two to three
|
||||
minutes each. Profiles shown to annotators come from public OpenAlex data.
|
||||
4. **Systems.** BM25 and dense e5 retrieval over researcher profiles (both exist in INSE), hybrid;
|
||||
graph rankers (personalised PageRank, meta-path counts, a temporal graph neural network); LLM
|
||||
listwise reranker with and without a verbalised evidence subgraph; the fine-tuned reranker
|
||||
(Unsloth, 4 to 8B, trained on graph-derived pairs); an agentic system using the graph through MCP
|
||||
as the high-cost reference.
|
||||
5. **Leakage controls.** Name masking, pre- versus post-cutoff comparison, and a check that no
|
||||
retrieval document postdates T.
|
||||
|
||||
## Evaluation
|
||||
|
||||
| Aspect | Measures |
|
||||
|---|---|
|
||||
| T1 effectiveness | nDCG@10, MAP, Recall@100 on human judgments; German versus English queries |
|
||||
| T2 effectiveness | MRR, Hits@10, nDCG@10 on post-T events; separately on post-cutoff events |
|
||||
| Evidence ablation | Drop one edge type at a time; recency decay on or off |
|
||||
| Fine-tuning | Reranker versus zero-shot large LLM: effectiveness, tokens, latency, GPU hours; training-size curve |
|
||||
| Leakage | Performance difference pre- versus post-cutoff and masked versus unmasked, per ranker |
|
||||
| Exposure and robustness | Share of top-10 exposure by career stage; rank change after removing junk institutions and suspected merged profiles |
|
||||
|
||||
Statistics: paired randomisation tests with Holm correction, confidence intervals by bootstrap over
|
||||
topics, inter-annotator agreement (kappa, and Krippendorff's alpha for graded labels).
|
||||
|
||||
## What gets released
|
||||
|
||||
The test collection (topics in two languages, graded judgments on public OpenAlex author IDs,
|
||||
post-T event lists from open sources), the temporal split protocol, reranker adapters and code.
|
||||
Company-register and news evidence is used internally only.
|
||||
|
||||
## Schedule
|
||||
|
||||
| Weeks | Work |
|
||||
|---|---|
|
||||
| 1 to 4 | Common start; literature; temporal split and event extraction |
|
||||
| 5 to 7 | Topics, annotation guidelines, text baselines |
|
||||
| 8 to 11 | Graph rankers, first pooled runs |
|
||||
| 12 to 15 | Relevance judgments (annotators), agreement |
|
||||
| 16 to 19 | LLM rerankers and the fine-tuned reranker |
|
||||
| 20 to 22 | Leakage, ablation, exposure and robustness analyses |
|
||||
| 23 to 24 | Second pooling round for late systems, significance testing |
|
||||
| 25 to 26 | Writing, paper draft |
|
||||
|
||||
Cut order if late: drop the agentic reference system, then T2's graph neural network (keep PageRank
|
||||
and meta-paths). Never cut the post-cutoff test set; it is the contribution.
|
||||
|
||||
## Risks
|
||||
|
||||
- **Too few post-cutoff events.** UDE alone yields a limited number of first-time industry links per
|
||||
year. Mitigation: add the other two default organisations (Bochum, Dortmund) with the same loader,
|
||||
which triples the cohort at no engineering cost.
|
||||
- **Pooling bias against systems added late.** Mitigation: a second pooling round in weeks 23 to 24,
|
||||
and report condensed-list metrics.
|
||||
- **Identity errors contaminate ground truth.** A "new industry link" may be a mis-resolved
|
||||
institution. Mitigation: per-paper affiliations only (not author-level), a manual check of a sample
|
||||
of test events, and junk-institution filtering documented in the thesis.
|
||||
|
||||
## Reading list to start from
|
||||
|
||||
arXiv 2404.13207, 2604.01379, 2607.04529, 2602.17234, 2605.03762, 2605.18843, 2506.05690, 2502.11371,
|
||||
2604.09666; "Recommending university-industry collaboration: a topic-institution graph-based solution"
|
||||
(Scientometrics, 2025); "From patents to partners" (Information Processing and Management, 2025);
|
||||
"Guiding retrieval using LLM-based listwise rankers" (ECIR 2025). All identifiers come from a
|
||||
literature search on 2026-09-17 and must be verified.
|
||||
@@ -0,0 +1,330 @@
|
||||
"""Arbeitsblatt und Auswertung für die manuelle Bewertung (Layer 2).
|
||||
|
||||
Layer 1 misst Regelkonformität, Layer 2 misst inhaltliche Qualität. Das geht
|
||||
nur von Hand, und zwar in drei Phasen — die Reihenfolge ist Teil der Methode:
|
||||
|
||||
Phase 1 --draw 50
|
||||
Arbeitsblatt ziehen und die *Soll-Begriffe* eintragen, BEVOR die
|
||||
Modellausgabe sichtbar ist. Sonst richtet sich die Annotation an
|
||||
den Vorschlägen des Modells aus und der Recall wird
|
||||
systematisch zu gut.
|
||||
|
||||
Phase 2 --attach --config neu
|
||||
Die extrahierten Keywords ins Arbeitsblatt einspielen und
|
||||
jedes einzeln bewerten.
|
||||
|
||||
Phase 3 --score
|
||||
Precision, Recall und die Verteilung der Urteile berechnen.
|
||||
|
||||
Bewertungsschema (vor der Annotation festgelegt):
|
||||
|
||||
"richtig" inhaltlich zentral für den Artikel und im Text verankert
|
||||
"akzeptabel" kommt vor und ist nicht irreführend, aber randständig, zu
|
||||
allgemein oder zu speziell — würde man selbst nicht wählen
|
||||
"falsch" irreführend, nicht aus dem Artikel, oder klarer Verstoß
|
||||
gegen die Aufgabe (Personenname, Datum, Floskel)
|
||||
|
||||
Soll-Begriffe: die ein bis drei Begriffe, ohne die eine Keywordliste zu
|
||||
diesem Artikel unvollständig wäre. Es geht um das Minimum, nicht
|
||||
um die ideale Liste.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import checks
|
||||
|
||||
ARTICLES_FILE = "data/articles.jsonl"
|
||||
RUNS_DIR = "runs"
|
||||
ANNOTATION_DIR = "annotation"
|
||||
WORKSHEET = os.path.join(ANNOTATION_DIR, "layer2_worksheet.json")
|
||||
RANDOM_SEED = 42
|
||||
|
||||
VERDICTS = ("richtig", "akzeptabel", "falsch")
|
||||
|
||||
|
||||
def load_jsonl(path):
|
||||
records = []
|
||||
with open(path, encoding="utf-8") as input_file:
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line:
|
||||
records.append(json.loads(line))
|
||||
return records
|
||||
|
||||
|
||||
def worksheet_entry(article):
|
||||
return {
|
||||
"_id": article["_id"],
|
||||
"maintitle": article.get("maintitle"),
|
||||
"full_content": article.get("full_content"),
|
||||
# Phase 1: hier die 1-3 Soll-Begriffe eintragen.
|
||||
"essential_keywords": [],
|
||||
# Phase 2 füllt das hier.
|
||||
"judgements": [],
|
||||
# Optional: Begriff -> true/false, falls der automatische
|
||||
# Abgleich in Phase 3 einen Soll-Begriff falsch zuordnet.
|
||||
"essential_overrides": {},
|
||||
}
|
||||
|
||||
|
||||
def replace(worksheet_path):
|
||||
"""Ersetzt nicht annotierte Artikel durch neue aus derselben Stichprobe."""
|
||||
worksheet = json.load(open(worksheet_path, encoding="utf-8"))
|
||||
keep = [article for article in worksheet if article["essential_keywords"]]
|
||||
drop = [article for article in worksheet if not article["essential_keywords"]]
|
||||
|
||||
if not drop:
|
||||
print("Alle Artikel im Arbeitsblatt sind annotiert — nichts zu ersetzen.")
|
||||
return
|
||||
|
||||
excluded_path = os.path.join(ANNOTATION_DIR, "excluded.json")
|
||||
excluded = []
|
||||
if os.path.exists(excluded_path):
|
||||
excluded = json.load(open(excluded_path, encoding="utf-8"))
|
||||
|
||||
for article in drop:
|
||||
excluded.append(
|
||||
{
|
||||
"_id": article["_id"],
|
||||
"maintitle": article.get("maintitle"),
|
||||
"content_length": len(article.get("full_content") or ""),
|
||||
"reason": None,
|
||||
}
|
||||
)
|
||||
|
||||
used = {article["_id"] for article in worksheet} | {item["_id"] for item in excluded}
|
||||
pool = [article for article in load_jsonl(ARTICLES_FILE) if article["_id"] not in used]
|
||||
if len(pool) < len(drop):
|
||||
raise SystemExit(f"Nur noch {len(pool)} unbenutzte Artikel in der Stichprobe.")
|
||||
|
||||
random.seed(RANDOM_SEED + len(excluded))
|
||||
replacements = random.sample(pool, len(drop))
|
||||
|
||||
os.makedirs(ANNOTATION_DIR, exist_ok=True)
|
||||
with open(worksheet_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(
|
||||
keep + [worksheet_entry(article) for article in replacements],
|
||||
output_file,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
with open(excluded_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(excluded, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"{len(drop)} Artikel ersetzt. Arbeitsblatt: {len(keep)} annotiert + {len(drop)} neu.")
|
||||
print(f"Aussortiert dokumentiert in {excluded_path}.\n")
|
||||
print("Neu zu annotieren:")
|
||||
for article in replacements:
|
||||
length = len(article.get("full_content") or "")
|
||||
print(f" {length:>6} Zeichen {article['_id']}")
|
||||
|
||||
|
||||
def draw(count, output):
|
||||
articles = load_jsonl(ARTICLES_FILE)
|
||||
random.seed(RANDOM_SEED)
|
||||
selected = random.sample(articles, min(count, len(articles)))
|
||||
|
||||
worksheet = [worksheet_entry(article) for article in selected]
|
||||
|
||||
os.makedirs(ANNOTATION_DIR, exist_ok=True)
|
||||
with open(output, "w", encoding="utf-8") as output_file:
|
||||
json.dump(worksheet, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
print(f"{len(worksheet)} Artikel -> {output}")
|
||||
print("\nPhase 1: pro Artikel 1-3 Soll-Begriffe in 'essential_keywords' eintragen.")
|
||||
print("Die Modellausgabe dabei NICHT ansehen.")
|
||||
|
||||
|
||||
def attach(config, worksheet_path):
|
||||
worksheet = json.load(open(worksheet_path, encoding="utf-8"))
|
||||
run = {
|
||||
entry["_id"]: entry
|
||||
for entry in load_jsonl(os.path.join(RUNS_DIR, f"{config}.jsonl"))
|
||||
if entry.get("repeat", 0) == 0
|
||||
}
|
||||
|
||||
missing = 0
|
||||
without_essentials = 0
|
||||
for article in worksheet:
|
||||
if not article["essential_keywords"]:
|
||||
without_essentials += 1
|
||||
|
||||
entry = run.get(article["_id"])
|
||||
if entry is None or entry.get("error"):
|
||||
missing += 1
|
||||
continue
|
||||
|
||||
existing = {item["keyword"]: item["verdict"] for item in article["judgements"]}
|
||||
article["judgements"] = [
|
||||
{"keyword": keyword, "verdict": existing.get(keyword)}
|
||||
for keyword in entry.get("keywords") or []
|
||||
]
|
||||
|
||||
with open(worksheet_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(worksheet, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
total = sum(len(article["judgements"]) for article in worksheet)
|
||||
print(f"{total} Keywords aus '{config}' eingespielt -> {worksheet_path}")
|
||||
if missing:
|
||||
print(f" {missing} Artikel ohne Lauf-Eintrag (noch nicht extrahiert?).")
|
||||
if without_essentials:
|
||||
print(
|
||||
f" WARNUNG: {without_essentials} Artikel ohne Soll-Begriffe. "
|
||||
"Phase 1 sollte vor Phase 2 abgeschlossen sein."
|
||||
)
|
||||
print(f"\nPhase 2: 'verdict' je Keyword auf {' / '.join(VERDICTS)} setzen.")
|
||||
|
||||
|
||||
def essential_covered(essential, keywords, overrides):
|
||||
"""Gilt ein Soll-Begriff als abgedeckt?
|
||||
|
||||
Automatischer Abgleich mit derselben flexionstoleranten Phrasenlogik wie
|
||||
L2.
|
||||
"""
|
||||
if essential in overrides:
|
||||
return bool(overrides[essential])
|
||||
|
||||
for keyword in keywords:
|
||||
index = checks.build_article_index(keyword)
|
||||
if checks.literal_l2(essential, index):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def score(worksheet_path):
|
||||
worksheet = json.load(open(worksheet_path, encoding="utf-8"))
|
||||
|
||||
counts = {verdict: 0 for verdict in VERDICTS}
|
||||
unjudged = 0
|
||||
essential_total = 0
|
||||
essential_hit = 0
|
||||
unmatched = []
|
||||
|
||||
for article in worksheet:
|
||||
keywords = [item["keyword"] for item in article["judgements"]]
|
||||
for item in article["judgements"]:
|
||||
verdict = item.get("verdict")
|
||||
if verdict in counts:
|
||||
counts[verdict] += 1
|
||||
else:
|
||||
unjudged += 1
|
||||
|
||||
overrides = article.get("essential_overrides") or {}
|
||||
for essential in article.get("essential_keywords") or []:
|
||||
essential_total += 1
|
||||
if essential_covered(essential, keywords, overrides):
|
||||
essential_hit += 1
|
||||
else:
|
||||
unmatched.append((article["_id"], essential, keywords))
|
||||
|
||||
judged = sum(counts.values())
|
||||
if not judged:
|
||||
raise SystemExit("Keine 'verdict'-Werte gesetzt.")
|
||||
|
||||
print("## Layer 2 — inhaltliche Bewertung\n")
|
||||
print(f"Bewertete Keywords: {judged}" + (f" (offen: {unjudged})" if unjudged else ""))
|
||||
for verdict in VERDICTS:
|
||||
share = 100.0 * counts[verdict] / judged
|
||||
print(f" {verdict:<12} {counts[verdict]:>4} ({share:.1f} %)".replace(".", ","))
|
||||
|
||||
precision = 100.0 * (counts["richtig"] + counts["akzeptabel"]) / judged
|
||||
strict = 100.0 * counts["richtig"] / judged
|
||||
print(f"\nPrecision (richtig + akzeptabel): {precision:.1f} %".replace(".", ","))
|
||||
print(f"Precision (nur richtig): {strict:.1f} %".replace(".", ","))
|
||||
|
||||
if essential_total:
|
||||
recall = 100.0 * essential_hit / essential_total
|
||||
print(
|
||||
f"\nSoll-Begriff-Recall: {essential_hit}/{essential_total} "
|
||||
f"({recall:.1f} %)".replace(".", ",")
|
||||
)
|
||||
if unmatched:
|
||||
print("\nNicht abgedeckte Soll-Begriffe (auf Fehlzuordnung prüfen):")
|
||||
for news_id, essential, keywords in unmatched[:20]:
|
||||
print(f" [{news_id[:35]}] {essential!r} vs {keywords}")
|
||||
else:
|
||||
print("\nKeine Soll-Begriffe eingetragen — Recall nicht berechenbar.")
|
||||
|
||||
results = {
|
||||
"judged": judged,
|
||||
"counts": counts,
|
||||
"precision_incl_acceptable": round(precision, 1),
|
||||
"precision_strict": round(strict, 1),
|
||||
"essential_total": essential_total,
|
||||
"essential_hit": essential_hit,
|
||||
}
|
||||
with open("results_layer2.json", "w", encoding="utf-8") as output_file:
|
||||
json.dump(results, output_file, ensure_ascii=False, indent=2)
|
||||
print("\n-> results_layer2.json")
|
||||
|
||||
|
||||
def kappa(first_path, second_path):
|
||||
"""Cohen's Kappa zwischen zwei unabhängig annotierten Arbeitsblättern."""
|
||||
first = {
|
||||
(article["_id"], item["keyword"]): item.get("verdict")
|
||||
for article in json.load(open(first_path, encoding="utf-8"))
|
||||
for item in article["judgements"]
|
||||
}
|
||||
second = {
|
||||
(article["_id"], item["keyword"]): item.get("verdict")
|
||||
for article in json.load(open(second_path, encoding="utf-8"))
|
||||
for item in article["judgements"]
|
||||
}
|
||||
|
||||
shared = [
|
||||
(first[key], second[key])
|
||||
for key in first.keys() & second.keys()
|
||||
if first[key] in VERDICTS and second[key] in VERDICTS
|
||||
]
|
||||
if not shared:
|
||||
raise SystemExit("Keine gemeinsam bewerteten Keywords gefunden.")
|
||||
|
||||
agreed = sum(1 for left, right in shared if left == right)
|
||||
observed = agreed / len(shared)
|
||||
|
||||
expected = 0.0
|
||||
for verdict in VERDICTS:
|
||||
left_share = sum(1 for left, _ in shared if left == verdict) / len(shared)
|
||||
right_share = sum(1 for _, right in shared if right == verdict) / len(shared)
|
||||
expected += left_share * right_share
|
||||
|
||||
value = (observed - expected) / (1 - expected) if expected < 1 else 1.0
|
||||
print(f"Gemeinsam bewertet: {len(shared)}")
|
||||
print(f"Übereinstimmung: {100 * observed:.1f} %".replace(".", ","))
|
||||
print(f"Cohens Kappa: {value:.3f}".replace(".", ","))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--draw", type=int, metavar="N", help="Phase 1: Arbeitsblatt ziehen.")
|
||||
parser.add_argument(
|
||||
"--replace",
|
||||
action="store_true",
|
||||
help="Nicht annotierte Artikel durch neue aus der Stichprobe ersetzen.",
|
||||
)
|
||||
parser.add_argument("--attach", action="store_true", help="Phase 2: Keywords einspielen.")
|
||||
parser.add_argument("--config", default="neu", help="Lauf für --attach (Default: neu).")
|
||||
parser.add_argument("--score", action="store_true", help="Phase 3: auswerten.")
|
||||
parser.add_argument("--kappa", metavar="ZWEITES_BLATT", help="Cohens Kappa gegen ein zweites Arbeitsblatt.")
|
||||
parser.add_argument("--worksheet", default=WORKSHEET)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.draw:
|
||||
draw(args.draw, args.worksheet)
|
||||
elif args.replace:
|
||||
replace(args.worksheet)
|
||||
elif args.attach:
|
||||
attach(args.config, args.worksheet)
|
||||
elif args.score:
|
||||
score(args.worksheet)
|
||||
elif args.kappa:
|
||||
kappa(args.worksheet, args.kappa)
|
||||
else:
|
||||
parser.print_help()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
[
|
||||
{
|
||||
"_id": "30112023_UlrikeBohnsack_Altrektorverstorben",
|
||||
"maintitle": "Altrektor verstorben",
|
||||
"content_length": 2293,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "11062015__Aufarbeiten,anerkennenunderinnern_archiv",
|
||||
"maintitle": "Aufarbeiten, anerkennen und erinnern",
|
||||
"content_length": 1369,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "27072021_UlrikeEichweber_LehrenziehenausderPandemie",
|
||||
"maintitle": "Lehren ziehen aus der Pandemie",
|
||||
"content_length": 826,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "05042017_ManuelaMnch_Jubilare-April2017",
|
||||
"maintitle": "Jubilare - April 2017",
|
||||
"content_length": 81,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "26072023_UlrikeEichweber_HilfefrdieHausarbeit",
|
||||
"maintitle": "Hilfe für die Hausarbeit",
|
||||
"content_length": 758,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "05112019_ManuelaMnch_Lehrstuhlvertretungen-November2019",
|
||||
"maintitle": "Lehrstuhlvertretungen - November 2019",
|
||||
"content_length": 182,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "07102005_ChristophLindemann_Kraft-Wrme-KopplungimFokus_archiv",
|
||||
"maintitle": "Kraft-Wärme-Kopplung im Fokus",
|
||||
"content_length": 3348,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "11122019_ManuelaMnch_Umhabilitationen-Dezember2019",
|
||||
"maintitle": "Umhabilitationen - Dezember 2019",
|
||||
"content_length": 234,
|
||||
"reason": null
|
||||
},
|
||||
{
|
||||
"_id": "17082018_ManuelaMnch_Seniorprofessuren-September2018",
|
||||
"maintitle": "Seniorprofessuren - September 2018",
|
||||
"content_length": 96,
|
||||
"reason": null
|
||||
}
|
||||
]
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"0": "rrrarr",
|
||||
"1": "rrrrra",
|
||||
"2": "rrrraa",
|
||||
"3": "rraaa",
|
||||
"4": "rrraaa",
|
||||
"5": "rrrrra",
|
||||
"6": "rraaaa",
|
||||
"7": "arraaa",
|
||||
"8": "raarr",
|
||||
"9": "rraaar",
|
||||
"10": "rrrraa",
|
||||
"11": "rrrraa",
|
||||
"12": "rraaaa",
|
||||
"13": "araaaa",
|
||||
"14": "aaaaaa",
|
||||
"15": "raaaaa",
|
||||
"16": "rraaaf",
|
||||
"17": "rraaaa",
|
||||
"18": "rrarar",
|
||||
"19": "rrraaa",
|
||||
"20": "raa",
|
||||
"21": "rraaaa",
|
||||
"22": "raarar",
|
||||
"23": "rarrra",
|
||||
"24": "rrrrar",
|
||||
"25": "rraaaa",
|
||||
"26": "aaaaaa",
|
||||
"27": "rarraa",
|
||||
"28": "rrrafa",
|
||||
"29": "rafraa",
|
||||
"30": "rraaaa",
|
||||
"31": "rrafar",
|
||||
"32": "rraara",
|
||||
"33": "rraaaa",
|
||||
"34": "rrrrfa",
|
||||
"35": "rraraa",
|
||||
"36": "rraaaa",
|
||||
"37": "rrrrra",
|
||||
"38": "rraaaa",
|
||||
"39": "rrrrfa",
|
||||
"40": "rrraaf",
|
||||
"41": "rraaaa",
|
||||
"42": "rraaa",
|
||||
"43": "rraaaa",
|
||||
"44": "rrrraa",
|
||||
"45": "rrrraa",
|
||||
"46": "rrraaa",
|
||||
"47": "raraaa",
|
||||
"48": "rraaaa",
|
||||
"49": "rrrrra"
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
"""Deterministic Layer-1 checks for extracted news keywords.
|
||||
|
||||
Every check mirrors a rule the extraction prompt states, so the result is a
|
||||
compliance rate rather than a quality judgement. A check returns:
|
||||
|
||||
True — rule satisfied
|
||||
False — rule violated
|
||||
None — not determinable (e.g. spaCy missing, or no noun to inspect)
|
||||
|
||||
`None` is counted separately in evaluate.py and never silently folded into the
|
||||
pass or fail bucket.
|
||||
|
||||
Levels of "appears literally in the text" (L0 ⊆ L1 ⊆ L2):
|
||||
|
||||
L0 exact case-folded, word-boundary match in title + content
|
||||
L1 normalized additionally NFKC, collapsed whitespace, hyphens removed
|
||||
L2 lemma every token of the keyword matches a token lemma of the
|
||||
article (requires spaCy)
|
||||
|
||||
L2 is the primary metric: the prompt demands base forms ("Nominativ
|
||||
Singular"), so a keyword may legitimately differ from the inflected surface
|
||||
form in the article. L0 and L1 are reported as stricter bounds.
|
||||
"""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
# --- optional spaCy -------------------------------------------------------
|
||||
|
||||
_NLP = None
|
||||
_SPACY_TRIED = False
|
||||
|
||||
|
||||
def get_nlp():
|
||||
"""Loads de_core_news_sm once; returns None when spaCy is unavailable."""
|
||||
global _NLP, _SPACY_TRIED
|
||||
if _SPACY_TRIED:
|
||||
return _NLP
|
||||
_SPACY_TRIED = True
|
||||
try:
|
||||
import spacy
|
||||
|
||||
_NLP = spacy.load("de_core_news_sm")
|
||||
except Exception:
|
||||
_NLP = None
|
||||
return _NLP
|
||||
|
||||
|
||||
# --- text normalization ---------------------------------------------------
|
||||
|
||||
_WHITESPACE = re.compile(r"\s+")
|
||||
_HYPHENS = re.compile(r"[-‐-―]")
|
||||
|
||||
|
||||
def casefold_text(text):
|
||||
return unicodedata.normalize("NFKC", text or "").casefold()
|
||||
|
||||
|
||||
def normalize_text(text):
|
||||
"""NFKC + casefold + hyphens removed + whitespace collapsed."""
|
||||
text = casefold_text(text)
|
||||
text = _HYPHENS.sub("", text)
|
||||
return _WHITESPACE.sub(" ", text).strip()
|
||||
|
||||
|
||||
def _contains_with_boundaries(haystack, needle):
|
||||
if not needle:
|
||||
return False
|
||||
pattern = r"(?<!\w)" + re.escape(needle) + r"(?!\w)"
|
||||
return re.search(pattern, haystack) is not None
|
||||
|
||||
|
||||
# --- literal occurrence ---------------------------------------------------
|
||||
|
||||
def literal_l0(keyword, article_text):
|
||||
return _contains_with_boundaries(casefold_text(article_text), casefold_text(keyword))
|
||||
|
||||
|
||||
def literal_l1(keyword, article_text):
|
||||
"""L0 oder ein Treffer nach Normalisierung.
|
||||
|
||||
Die L0-Disjunktion ist nötig, damit L0 ⊆ L1 per Konstruktion gilt: das
|
||||
Entfernen der Bindestriche kann Komposita verschmelzen und dadurch eine
|
||||
Wortgrenze zerstören ("S-Bahn" trifft in "S-Bahn-Station", "sbahn" nicht
|
||||
mehr in "sbahnstation"). Ohne die Disjunktion läge L1 in genau diesen
|
||||
Fällen unter L0.
|
||||
"""
|
||||
if literal_l0(keyword, article_text):
|
||||
return True
|
||||
return _contains_with_boundaries(normalize_text(article_text), normalize_text(keyword))
|
||||
|
||||
|
||||
_WORD = re.compile(r"\w+")
|
||||
|
||||
|
||||
def _inflection_tolerance(token):
|
||||
"""How many trailing characters may differ, by token length.
|
||||
|
||||
German inflection is suffixal and short ("-e", "-en", "-er", "-s"), so a
|
||||
small bounded tolerance captures it. The bound also keeps compounds apart:
|
||||
"Forschung" does not match "Forschungsprojekt" (8 extra characters), which
|
||||
is exactly the generalization the prompt forbids.
|
||||
"""
|
||||
length = len(token)
|
||||
if length >= 6:
|
||||
return 3
|
||||
if length >= 4:
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
def _spacy_tokens(text, nlp):
|
||||
"""(lemma, surface) pairs of a text, punctuation and whitespace dropped."""
|
||||
document = nlp(text or "")
|
||||
return [
|
||||
(token.lemma_.casefold(), token.text.casefold())
|
||||
for token in document
|
||||
if not token.is_punct and not token.is_space
|
||||
]
|
||||
|
||||
|
||||
def build_article_index(article_text, nlp=None):
|
||||
"""Prepares an article for the L2 check.
|
||||
|
||||
Both variants keep the token **order**, because L2 requires a multi-word
|
||||
keyword to occur as a contiguous phrase — "Forschung und Entwicklung" must
|
||||
not count merely because all three words appear somewhere in the article.
|
||||
|
||||
With spaCy: lemma/surface pairs, the linguistically correct basis. Without
|
||||
it: normalized surface tokens, matched suffix-tolerantly. The method is
|
||||
part of the index so callers can tell which one produced the numbers.
|
||||
"""
|
||||
nlp = nlp or get_nlp()
|
||||
|
||||
if nlp is None:
|
||||
return {
|
||||
"method": "flexion",
|
||||
"tokens": _WORD.findall(normalize_text(article_text)),
|
||||
}
|
||||
|
||||
return {"method": "lemma", "tokens": _spacy_tokens(article_text, nlp)}
|
||||
|
||||
|
||||
def _tokens_match_with_inflection(keyword_token, article_token):
|
||||
"""One token pair, allowing a short suffix on either side.
|
||||
|
||||
The article may inflect the keyword's base form ("Forschungsprojekt" vs
|
||||
"Forschungsprojekte"), or the keyword may itself be the longer surface
|
||||
form. The bound keeps compounds apart: "Forschung" never matches
|
||||
"Forschungsprojekt".
|
||||
"""
|
||||
if keyword_token == article_token:
|
||||
return True
|
||||
if article_token.startswith(keyword_token):
|
||||
return len(article_token) - len(keyword_token) <= _inflection_tolerance(keyword_token)
|
||||
if keyword_token.startswith(article_token):
|
||||
return len(keyword_token) - len(article_token) <= _inflection_tolerance(article_token)
|
||||
return False
|
||||
|
||||
|
||||
def _lemma_tokens_match(keyword_token, article_token):
|
||||
keyword_lemma, keyword_surface = keyword_token
|
||||
article_lemma, article_surface = article_token
|
||||
return (
|
||||
keyword_lemma == article_lemma
|
||||
or keyword_lemma == article_surface
|
||||
or keyword_surface == article_surface
|
||||
)
|
||||
|
||||
|
||||
def _contiguous_match(keyword_tokens, article_tokens, compare):
|
||||
"""True when the keyword tokens occur as a contiguous run, in order."""
|
||||
span = len(keyword_tokens)
|
||||
if span == 0 or span > len(article_tokens):
|
||||
return False
|
||||
for start in range(len(article_tokens) - span + 1):
|
||||
if all(
|
||||
compare(keyword_tokens[offset], article_tokens[start + offset])
|
||||
for offset in range(span)
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def literal_l2(keyword, index, nlp=None):
|
||||
"""True when the keyword occurs in the article as a contiguous phrase.
|
||||
|
||||
Each token may differ by inflection — identical lemma with spaCy, a short
|
||||
suffix without it — but the tokens must be adjacent and in order. That is
|
||||
the level at which the two prompt rules ("kommt im Text vor" and
|
||||
"Grundform") are satisfiable at the same time: the term is genuinely taken
|
||||
from the text, only its form is normalized.
|
||||
"""
|
||||
if index is None:
|
||||
return None
|
||||
|
||||
if index["method"] == "lemma":
|
||||
nlp = nlp or get_nlp()
|
||||
if nlp is None:
|
||||
return None
|
||||
keyword_tokens = _spacy_tokens(keyword, nlp)
|
||||
return _contiguous_match(keyword_tokens, index["tokens"], _lemma_tokens_match)
|
||||
|
||||
keyword_tokens = _WORD.findall(normalize_text(keyword))
|
||||
return _contiguous_match(keyword_tokens, index["tokens"], _tokens_match_with_inflection)
|
||||
|
||||
|
||||
# --- per-article structure ------------------------------------------------
|
||||
|
||||
def count_ok(raw_keywords, limit):
|
||||
"""At most `limit` keywords in the RAW model output."""
|
||||
if raw_keywords is None:
|
||||
return None
|
||||
return len(raw_keywords) <= limit
|
||||
|
||||
|
||||
def no_duplicates(raw_keywords):
|
||||
"""No case-insensitive duplicates in the RAW model output."""
|
||||
if raw_keywords is None:
|
||||
return None
|
||||
seen = [item.strip().casefold() for item in raw_keywords if isinstance(item, str)]
|
||||
return len(seen) == len(set(seen))
|
||||
|
||||
|
||||
MIN_STEM_LENGTH = 4
|
||||
|
||||
|
||||
def no_stem_redundancy(keywords):
|
||||
"""No keyword is contained in another ("Forschung" next to "Forschungsprojekt").
|
||||
|
||||
Plain containment rather than a stemmer: Snowball maps those two examples
|
||||
to different stems, so stemming would miss the case the prompt names.
|
||||
"""
|
||||
if keywords is None:
|
||||
return None
|
||||
normalized = [normalize_text(item) for item in keywords if isinstance(item, str)]
|
||||
normalized = [item for item in normalized if len(item) >= MIN_STEM_LENGTH]
|
||||
for i, left in enumerate(normalized):
|
||||
for j, right in enumerate(normalized):
|
||||
if i != j and left in right and left != right:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def redundant_pairs(keywords):
|
||||
"""The offending pairs, for qualitative inspection."""
|
||||
pairs = []
|
||||
normalized = {
|
||||
item: normalize_text(item) for item in keywords if isinstance(item, str)
|
||||
}
|
||||
for left, left_norm in normalized.items():
|
||||
if len(left_norm) < MIN_STEM_LENGTH:
|
||||
continue
|
||||
for right, right_norm in normalized.items():
|
||||
if left is not right and left_norm in right_norm and left_norm != right_norm:
|
||||
pairs.append((left, right))
|
||||
return pairs
|
||||
|
||||
|
||||
# --- forbidden content ----------------------------------------------------
|
||||
|
||||
_MONTH_NAMES = {
|
||||
"januar", "februar", "märz", "april", "mai", "juni", "juli",
|
||||
"august", "september", "oktober", "november", "dezember",
|
||||
}
|
||||
_YEAR = re.compile(r"^(19|20)\d{2}$")
|
||||
_FULL_DATE = re.compile(r"(?<!\d)\d{1,2}\.\s?\d{1,2}\.\s?(19|20)?\d{2}(?!\d)")
|
||||
|
||||
|
||||
def no_date(keyword):
|
||||
"""False, wenn das Schlagwort eine Datumsangabe ist.
|
||||
|
||||
Eine Jahreszahl *innerhalb* eines längeren Begriffs zählt nicht: sie
|
||||
gehört dort in aller Regel zu einem Eigennamen ("Horizont 2020",
|
||||
"Agenda 2010", "EUSA Games 2020"), und Programm- und Veranstaltungsnamen
|
||||
verbietet der Prompt nicht. Gemeldet wird deshalb nur, was ausschließlich
|
||||
aus Datumsbestandteilen besteht, sowie ein vollständiges Tagesdatum an
|
||||
beliebiger Stelle.
|
||||
|
||||
Grenzfall: "Sommersemester 2015" gilt damit als konform, obwohl es eine
|
||||
Zeitangabe enthält. Das ist bewusst die vorsichtigere Richtung — falsch
|
||||
gemeldete Eigennamen wären der teurere Fehler.
|
||||
"""
|
||||
if _FULL_DATE.search(casefold_text(keyword)):
|
||||
return False
|
||||
|
||||
tokens = _WORD.findall(normalize_text(keyword))
|
||||
if not tokens:
|
||||
return True
|
||||
|
||||
return not all(
|
||||
_YEAR.match(token) or token in _MONTH_NAMES or token.isdigit()
|
||||
for token in tokens
|
||||
)
|
||||
|
||||
|
||||
MIN_NAME_TOKEN = 3
|
||||
|
||||
|
||||
def no_person_name_authors(keyword, authors):
|
||||
"""False when the keyword is one of the article's own extracted names.
|
||||
|
||||
Uses the `authors` field the pipeline already produces, so this check
|
||||
needs no external model and no annotation.
|
||||
"""
|
||||
if authors is None:
|
||||
return None
|
||||
keyword_norm = normalize_text(keyword)
|
||||
if not keyword_norm:
|
||||
return True
|
||||
|
||||
for author in authors:
|
||||
author_norm = normalize_text(author)
|
||||
if not author_norm:
|
||||
continue
|
||||
if keyword_norm == author_norm:
|
||||
return False
|
||||
parts = [part for part in author_norm.split() if len(part) >= MIN_NAME_TOKEN]
|
||||
if keyword_norm in parts:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def no_person_name_ner(keyword, nlp=None):
|
||||
"""False when spaCy tags the whole keyword as a person entity."""
|
||||
nlp = nlp or get_nlp()
|
||||
if nlp is None:
|
||||
return None
|
||||
document = nlp(keyword or "")
|
||||
for entity in document.ents:
|
||||
if entity.label_ == "PER" and entity.text.strip() == (keyword or "").strip():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
# --- grammatical form -----------------------------------------------------
|
||||
|
||||
def base_form(keyword, nlp=None):
|
||||
"""True when the keyword's head noun is nominative singular.
|
||||
|
||||
German head nouns sit at the end of a phrase, so the last NOUN/PROPN token
|
||||
is inspected. Returns None when the keyword contains no noun at all.
|
||||
"""
|
||||
nlp = nlp or get_nlp()
|
||||
if nlp is None:
|
||||
return None
|
||||
|
||||
document = nlp(keyword or "")
|
||||
nouns = [token for token in document if token.pos_ in ("NOUN", "PROPN")]
|
||||
if not nouns:
|
||||
return None
|
||||
|
||||
head = nouns[-1]
|
||||
numbers = head.morph.get("Number")
|
||||
cases = head.morph.get("Case")
|
||||
if not numbers or not cases:
|
||||
return None
|
||||
return "Sing" in numbers and "Nom" in cases
|
||||
|
||||
|
||||
# --- aggregation helpers --------------------------------------------------
|
||||
|
||||
def check_keyword(keyword, article_text, index, authors, nlp=None):
|
||||
"""All keyword-level checks for one keyword."""
|
||||
l0 = literal_l0(keyword, article_text)
|
||||
l1 = literal_l1(keyword, article_text)
|
||||
|
||||
# L0 ⊆ L1 ⊆ L2, so the expensive pass only runs where L1 already failed.
|
||||
if l1:
|
||||
l2 = True
|
||||
else:
|
||||
l2 = literal_l2(keyword, index, nlp=nlp)
|
||||
|
||||
return {
|
||||
"literal_l0": l0,
|
||||
"literal_l1": l1,
|
||||
"literal_l2": l2,
|
||||
"no_person_name_authors": no_person_name_authors(keyword, authors),
|
||||
"no_person_name_ner": no_person_name_ner(keyword, nlp=nlp),
|
||||
"no_date": no_date(keyword),
|
||||
"base_form": base_form(keyword, nlp=nlp),
|
||||
}
|
||||
|
||||
|
||||
def check_article(raw_keywords, keywords, limit):
|
||||
"""All article-level checks for one article."""
|
||||
return {
|
||||
"count_ok": count_ok(raw_keywords, limit),
|
||||
"no_duplicates": no_duplicates(raw_keywords),
|
||||
"no_stem_redundancy": no_stem_redundancy(keywords),
|
||||
}
|
||||
|
||||
|
||||
def jaccard(left, right):
|
||||
"""Set overlap of two keyword lists, case-insensitive."""
|
||||
left_set = {item.casefold() for item in left if isinstance(item, str)}
|
||||
right_set = {item.casefold() for item in right if isinstance(item, str)}
|
||||
if not left_set and not right_set:
|
||||
return 1.0
|
||||
if not left_set or not right_set:
|
||||
return 0.0
|
||||
return len(left_set & right_set) / len(left_set | right_set)
|
||||
@@ -0,0 +1,251 @@
|
||||
"""Applies the Layer-1 checks to an extraction run and aggregates the counts.
|
||||
|
||||
Separate from extract_keywords.py on purpose: the LLM calls are slow and cost
|
||||
GPU time, the checks are cheap, so a changed check definition must not force a
|
||||
re-extraction.
|
||||
|
||||
Writes
|
||||
results_<config>.json aggregated counts for results.py
|
||||
decisions/<config>.jsonl one record per keyword decision, for manual review
|
||||
|
||||
Usage:
|
||||
python evaluate.py --config neu
|
||||
python evaluate.py --config alt
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import sys
|
||||
from collections import Counter
|
||||
from itertools import combinations
|
||||
from pathlib import Path
|
||||
|
||||
import checks
|
||||
|
||||
sys.path.append(str(Path(__file__).resolve().parents[2] / "service/src/main/inse/news"))
|
||||
import keyword_extraction # noqa: E402
|
||||
|
||||
ARTICLES_FILE = "data/articles.jsonl"
|
||||
RUNS_DIR = "runs"
|
||||
DECISIONS_DIR = "decisions"
|
||||
MAX_EXAMPLES = 25
|
||||
|
||||
KEYWORD_CHECKS = [
|
||||
"literal_l0",
|
||||
"literal_l1",
|
||||
"literal_l2",
|
||||
"no_person_name_authors",
|
||||
"no_person_name_ner",
|
||||
"no_date",
|
||||
"base_form",
|
||||
]
|
||||
ARTICLE_CHECKS = ["count_ok", "no_duplicates", "no_stem_redundancy"]
|
||||
|
||||
|
||||
def load_jsonl(path):
|
||||
records = []
|
||||
with open(path, encoding="utf-8") as input_file:
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line:
|
||||
records.append(json.loads(line))
|
||||
return records
|
||||
|
||||
|
||||
def empty_tally():
|
||||
return {"pass": 0, "fail": 0, "na": 0}
|
||||
|
||||
|
||||
def tally(bucket, value):
|
||||
if value is None:
|
||||
bucket["na"] += 1
|
||||
elif value:
|
||||
bucket["pass"] += 1
|
||||
else:
|
||||
bucket["fail"] += 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", required=True)
|
||||
parser.add_argument("--articles", default=ARTICLES_FILE)
|
||||
parser.add_argument("--run", default=None, help="Default: runs/<config>.jsonl")
|
||||
args = parser.parse_args()
|
||||
|
||||
run_path = args.run or os.path.join(RUNS_DIR, f"{args.config}.jsonl")
|
||||
if not os.path.exists(run_path):
|
||||
raise SystemExit(
|
||||
f"'{run_path}' existiert nicht — für '{args.config}' wurde noch nicht "
|
||||
f"extrahiert.\nZuerst: python extract_keywords.py --config {args.config}"
|
||||
)
|
||||
|
||||
articles = {record["_id"]: record for record in load_jsonl(args.articles)}
|
||||
run_records = load_jsonl(run_path)
|
||||
|
||||
nlp = checks.get_nlp()
|
||||
if nlp is None:
|
||||
print(
|
||||
"Hinweis: spaCy/de_core_news_sm nicht verfügbar.\n"
|
||||
" L2 läuft über den Flexions-Fallback (suffixtolerant, ohne Abhängigkeit).\n"
|
||||
" Grundform- und NER-Prüfung werden als 'n. v.' gezählt."
|
||||
)
|
||||
|
||||
keyword_tallies = {name: empty_tally() for name in KEYWORD_CHECKS}
|
||||
article_tallies = {name: empty_tally() for name in ARTICLE_CHECKS}
|
||||
article_tallies["literal_all"] = empty_tally()
|
||||
|
||||
errors = Counter()
|
||||
keyword_counts = []
|
||||
examples = {name: [] for name in KEYWORD_CHECKS + ARTICLE_CHECKS}
|
||||
decisions = []
|
||||
by_article_repeats = {}
|
||||
|
||||
keywords_total = 0
|
||||
articles_evaluated = 0
|
||||
|
||||
for entry in run_records:
|
||||
news_id = entry["_id"]
|
||||
by_article_repeats.setdefault(news_id, []).append(entry)
|
||||
|
||||
# Only the first repeat feeds the compliance counts; the extra repeats
|
||||
# exist for the reproducibility measure and would otherwise weight
|
||||
# those articles more heavily.
|
||||
if entry.get("repeat", 0) != 0:
|
||||
continue
|
||||
|
||||
if entry.get("error"):
|
||||
errors[entry["error"].split(":")[0]] += 1
|
||||
continue
|
||||
|
||||
article = articles.get(news_id)
|
||||
if article is None:
|
||||
errors["article_missing"] += 1
|
||||
continue
|
||||
|
||||
articles_evaluated += 1
|
||||
raw_keywords = entry.get("raw_keywords")
|
||||
keywords = entry.get("keywords") or []
|
||||
keyword_counts.append(len(raw_keywords) if raw_keywords is not None else 0)
|
||||
|
||||
article_text = " ".join(
|
||||
part for part in (article.get("maintitle"), article.get("full_content")) if part
|
||||
)
|
||||
authors = article.get("authors")
|
||||
|
||||
article_results = checks.check_article(
|
||||
raw_keywords, keywords, keyword_extraction.KEYWORD_LIMIT
|
||||
)
|
||||
for name, value in article_results.items():
|
||||
tally(article_tallies[name], value)
|
||||
if value is False and len(examples[name]) < MAX_EXAMPLES:
|
||||
detail = {"_id": news_id, "keywords": raw_keywords}
|
||||
if name == "no_stem_redundancy":
|
||||
detail["pairs"] = checks.redundant_pairs(keywords)
|
||||
examples[name].append(detail)
|
||||
|
||||
# Building the article index is the expensive part, so do it only when
|
||||
# some keyword actually needs it.
|
||||
index = None
|
||||
index_built = False
|
||||
article_literal_ok = True
|
||||
article_literal_undecided = False
|
||||
|
||||
for keyword in keywords:
|
||||
if not isinstance(keyword, str) or not keyword.strip():
|
||||
continue
|
||||
keywords_total += 1
|
||||
|
||||
if not index_built and not checks.literal_l1(keyword, article_text):
|
||||
index = checks.build_article_index(article_text, nlp=nlp)
|
||||
index_built = True
|
||||
|
||||
results = checks.check_keyword(keyword, article_text, index, authors, nlp=nlp)
|
||||
for name, value in results.items():
|
||||
tally(keyword_tallies[name], value)
|
||||
if value is False and len(examples[name]) < MAX_EXAMPLES:
|
||||
examples[name].append({"_id": news_id, "keyword": keyword})
|
||||
|
||||
if results["literal_l2"] is False:
|
||||
article_literal_ok = False
|
||||
elif results["literal_l2"] is None:
|
||||
article_literal_undecided = True
|
||||
|
||||
decisions.append({"_id": news_id, "keyword": keyword, **results})
|
||||
|
||||
# A single undecidable keyword makes the whole article undecidable —
|
||||
# otherwise a missing spaCy model would silently report every article
|
||||
# as compliant.
|
||||
if article_literal_ok and article_literal_undecided:
|
||||
tally(article_tallies["literal_all"], None)
|
||||
else:
|
||||
tally(article_tallies["literal_all"], article_literal_ok)
|
||||
|
||||
# Reproducibility: mean pairwise Jaccard across repeats of the same article.
|
||||
determinism = None
|
||||
repeated = {
|
||||
news_id: entries
|
||||
for news_id, entries in by_article_repeats.items()
|
||||
if len({entry.get("repeat", 0) for entry in entries}) > 1
|
||||
}
|
||||
if repeated:
|
||||
scores = []
|
||||
for entries in repeated.values():
|
||||
usable = [entry["keywords"] for entry in entries if not entry.get("error")]
|
||||
if len(usable) < 2:
|
||||
continue
|
||||
scores.extend(
|
||||
checks.jaccard(left, right) for left, right in combinations(usable, 2)
|
||||
)
|
||||
if scores:
|
||||
determinism = {
|
||||
"articles": len(repeated),
|
||||
"repeats": max(len(entries) for entries in repeated.values()),
|
||||
"mean_pairwise_jaccard": round(statistics.mean(scores), 4),
|
||||
"identical_share": round(
|
||||
sum(1 for score in scores if score == 1.0) / len(scores), 4
|
||||
),
|
||||
}
|
||||
|
||||
results = {
|
||||
"config": args.config,
|
||||
"l2_method": "lemma" if nlp is not None else "flexion",
|
||||
"articles_evaluated": articles_evaluated,
|
||||
"keywords_total": keywords_total,
|
||||
"errors": dict(errors),
|
||||
"keyword_level": keyword_tallies,
|
||||
"article_level": article_tallies,
|
||||
"descriptive": {
|
||||
"mean_keywords": round(statistics.mean(keyword_counts), 2) if keyword_counts else 0,
|
||||
"median_keywords": statistics.median(keyword_counts) if keyword_counts else 0,
|
||||
"articles_zero_keywords": sum(1 for count in keyword_counts if count == 0),
|
||||
"articles_exactly_six": sum(1 for count in keyword_counts if count == 6),
|
||||
"articles_over_six": sum(
|
||||
1 for count in keyword_counts if count > keyword_extraction.KEYWORD_LIMIT
|
||||
),
|
||||
},
|
||||
"determinism": determinism,
|
||||
"examples": examples,
|
||||
}
|
||||
|
||||
output_path = f"results_{args.config}.json"
|
||||
with open(output_path, "w", encoding="utf-8") as output_file:
|
||||
json.dump(results, output_file, ensure_ascii=False, indent=2)
|
||||
|
||||
os.makedirs(DECISIONS_DIR, exist_ok=True)
|
||||
decisions_path = os.path.join(DECISIONS_DIR, f"{args.config}.jsonl")
|
||||
with open(decisions_path, "w", encoding="utf-8") as decisions_file:
|
||||
for decision in decisions:
|
||||
decisions_file.write(json.dumps(decision, ensure_ascii=False) + "\n")
|
||||
|
||||
print(
|
||||
f"{articles_evaluated} Artikel, {keywords_total} Schlagwörter ausgewertet.\n"
|
||||
f"-> {output_path}\n-> {decisions_path}"
|
||||
)
|
||||
if errors:
|
||||
print(f"Fehler: {dict(errors)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,274 @@
|
||||
"""Runs the keyword extraction under a named configuration and logs raw output.
|
||||
|
||||
Two configurations are defined:
|
||||
|
||||
* `neu` — the production contract, imported from the service module
|
||||
`inse.news.keyword_extraction`, so the evaluation tests what actually ships
|
||||
(title + 20.000-char bound, strict JSON schema, temperature 0.0,
|
||||
normalization).
|
||||
* `alt` — the behaviour of the background job before the paths were unified:
|
||||
full content without the title, no schema, temperature 1.0, and the raw
|
||||
model list persisted without normalization.
|
||||
|
||||
The RAW model response is written out alongside the parsed list, because the
|
||||
count- and duplicate checks have to look at what the model produced, not at
|
||||
what normalize_keywords() left over.
|
||||
|
||||
Output: runs/<config>.jsonl, one object per article and repeat:
|
||||
|
||||
{"_id": ..., "config": ..., "repeat": 0, "raw_response": "...",
|
||||
"raw_keywords": [...], "keywords": [...], "error": null}
|
||||
|
||||
Runs are resumable — (\\_id, repeat) pairs already present are skipped.
|
||||
|
||||
Usage:
|
||||
python extract_keywords.py --config neu
|
||||
python extract_keywords.py --config alt
|
||||
python extract_keywords.py --config neu --repeats 5 --limit 200
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
from openai import APIConnectionError, OpenAI
|
||||
|
||||
# The production contract lives in the service package; import it rather than
|
||||
# restating it, so "neu" cannot silently drift away from what ships.
|
||||
sys.path.append(str(Path(__file__).resolve().parents[2] / "service/src/main/inse/news"))
|
||||
import keyword_extraction # noqa: E402
|
||||
|
||||
load_dotenv()
|
||||
|
||||
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
|
||||
LLM_API_KEY = os.getenv("INSE_LLM_API_KEY")
|
||||
if not LLM_API_KEY:
|
||||
raise SystemExit(
|
||||
"INSE_LLM_API_KEY ist nicht gesetzt. Lege eine .env an oder exportiere die Variable."
|
||||
)
|
||||
LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b")
|
||||
|
||||
_client = OpenAI(base_url=LLM_BASE_URL, api_key=LLM_API_KEY, timeout=120)
|
||||
|
||||
INPUT_FILE = "data/articles.jsonl"
|
||||
OUTPUT_DIR = "runs"
|
||||
|
||||
# Legacy configuration, kept verbatim for the comparison column.
|
||||
ALT_TEMPERATURE = 1.0
|
||||
ALT_TOP_P = 0.95
|
||||
ALT_TOP_K = 64
|
||||
|
||||
|
||||
def build_prompt_neu(record):
|
||||
return keyword_extraction.build_user_prompt(
|
||||
record.get("maintitle"), record.get("full_content")
|
||||
)
|
||||
|
||||
|
||||
def build_prompt_alt(record):
|
||||
"""Legacy: bare full_content, no title, no length bound."""
|
||||
text = (record.get("full_content") or "").strip()
|
||||
return text or None
|
||||
|
||||
|
||||
CONFIGS = {
|
||||
"neu": {
|
||||
"system_prompt": keyword_extraction.KEYWORD_SYSTEM_PROMPT,
|
||||
"build_prompt": build_prompt_neu,
|
||||
"temperature": keyword_extraction.TEMPERATURE,
|
||||
"top_p": keyword_extraction.TOP_P,
|
||||
"top_k": keyword_extraction.TOP_K,
|
||||
"json_schema": keyword_extraction.RESPONSE_SCHEMA,
|
||||
"schema_name": keyword_extraction.SCHEMA_NAME,
|
||||
"normalize": True,
|
||||
},
|
||||
"alt": {
|
||||
"system_prompt": keyword_extraction.KEYWORD_SYSTEM_PROMPT,
|
||||
"build_prompt": build_prompt_alt,
|
||||
"temperature": ALT_TEMPERATURE,
|
||||
"top_p": ALT_TOP_P,
|
||||
"top_k": ALT_TOP_K,
|
||||
"json_schema": None,
|
||||
"schema_name": None,
|
||||
"normalize": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def call_llm(config, user_prompt):
|
||||
response_format = None
|
||||
if config["json_schema"] is not None:
|
||||
response_format = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": config["schema_name"],
|
||||
"strict": True,
|
||||
"schema": config["json_schema"],
|
||||
},
|
||||
}
|
||||
|
||||
response = _client.chat.completions.create(
|
||||
model=LLM_MODEL,
|
||||
messages=[
|
||||
{"role": "system", "content": config["system_prompt"]},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
temperature=config["temperature"],
|
||||
top_p=config["top_p"],
|
||||
extra_body={"top_k": config["top_k"]},
|
||||
response_format=response_format,
|
||||
)
|
||||
return response.choices[0].message.content or ""
|
||||
|
||||
|
||||
def parse_raw(raw_response):
|
||||
"""Parses the model answer without applying any normalization."""
|
||||
try:
|
||||
data = json.loads(raw_response)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
if not isinstance(data, dict):
|
||||
return None
|
||||
candidates = data.get("keywords")
|
||||
if not isinstance(candidates, list):
|
||||
return None
|
||||
return candidates
|
||||
|
||||
|
||||
def extract_one(record, config_name, repeat):
|
||||
config = CONFIGS[config_name]
|
||||
result = {
|
||||
"_id": record["_id"],
|
||||
"config": config_name,
|
||||
"repeat": repeat,
|
||||
"raw_response": None,
|
||||
"raw_keywords": None,
|
||||
"keywords": [],
|
||||
"error": None,
|
||||
}
|
||||
|
||||
user_prompt = config["build_prompt"](record)
|
||||
if not user_prompt:
|
||||
result["error"] = "empty_article"
|
||||
return result
|
||||
|
||||
try:
|
||||
raw_response = call_llm(config, user_prompt)
|
||||
except APIConnectionError as error:
|
||||
result["error"] = f"connection_error: {error}"
|
||||
return result
|
||||
except Exception as error: # noqa: BLE001 - one bad article must not stop the run
|
||||
result["error"] = f"llm_error: {error}"
|
||||
return result
|
||||
|
||||
result["raw_response"] = raw_response
|
||||
raw_keywords = parse_raw(raw_response)
|
||||
|
||||
if raw_keywords is None:
|
||||
result["error"] = "unparseable_response"
|
||||
return result
|
||||
|
||||
result["raw_keywords"] = raw_keywords
|
||||
if config["normalize"]:
|
||||
result["keywords"] = keyword_extraction.normalize_keywords(raw_keywords)
|
||||
else:
|
||||
# Legacy behaviour: whatever the model returned was persisted as-is.
|
||||
result["keywords"] = raw_keywords
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def load_articles(path, limit):
|
||||
records = []
|
||||
with open(path, encoding="utf-8") as input_file:
|
||||
for line in input_file:
|
||||
line = line.strip()
|
||||
if line:
|
||||
records.append(json.loads(line))
|
||||
return records[:limit] if limit else records
|
||||
|
||||
|
||||
def load_done(path):
|
||||
"""Returns the (_id, repeat) pairs already written, so runs can resume."""
|
||||
done = set()
|
||||
if not os.path.exists(path):
|
||||
return done
|
||||
with open(path, encoding="utf-8") as existing:
|
||||
for line in existing:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
done.add((entry.get("_id"), entry.get("repeat")))
|
||||
return done
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--config", choices=sorted(CONFIGS), required=True)
|
||||
parser.add_argument("--input", default=INPUT_FILE)
|
||||
parser.add_argument("--output", default=None, help="Default: runs/<config>.jsonl")
|
||||
parser.add_argument("--threads", type=int, default=4)
|
||||
parser.add_argument("--limit", type=int, default=None, help="Nur die ersten N Artikel.")
|
||||
parser.add_argument(
|
||||
"--repeats",
|
||||
type=int,
|
||||
default=1,
|
||||
help="Wiederholungen je Artikel für die Reproduzierbarkeitsmessung (Default: 1).",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
output_path = args.output or os.path.join(OUTPUT_DIR, f"{args.config}.jsonl")
|
||||
|
||||
records = load_articles(args.input, args.limit)
|
||||
done = load_done(output_path)
|
||||
|
||||
jobs = [
|
||||
(record, repeat)
|
||||
for record in records
|
||||
for repeat in range(args.repeats)
|
||||
if (record["_id"], repeat) not in done
|
||||
]
|
||||
total = len(jobs)
|
||||
print(
|
||||
f"Konfiguration '{args.config}': {len(records)} Artikel x {args.repeats} "
|
||||
f"Wiederholung(en), {total} offen, {len(done)} bereits vorhanden."
|
||||
)
|
||||
if not total:
|
||||
return
|
||||
|
||||
write_lock = threading.Lock()
|
||||
processed = 0
|
||||
failed = 0
|
||||
|
||||
with open(output_path, "a", encoding="utf-8") as output_file:
|
||||
with ThreadPoolExecutor(max_workers=args.threads) as executor:
|
||||
futures = [
|
||||
executor.submit(extract_one, record, args.config, repeat)
|
||||
for record, repeat in jobs
|
||||
]
|
||||
for future in as_completed(futures):
|
||||
result = future.result()
|
||||
with write_lock:
|
||||
output_file.write(json.dumps(result, ensure_ascii=False) + "\n")
|
||||
output_file.flush()
|
||||
processed += 1
|
||||
if result["error"]:
|
||||
failed += 1
|
||||
if processed % 25 == 0 or processed == total:
|
||||
print(f" {processed} / {total} (Fehler: {failed})")
|
||||
|
||||
print(f"Fertig. {processed} Aufrufe, davon {failed} mit Fehler. -> {output_path}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Collects the article sample for the keyword evaluation.
|
||||
|
||||
Reads `aktuell` (title + content) and joins the `authors` field from
|
||||
`aktuell_postproc`, which the person-name check uses as a per-article list of
|
||||
names that must not show up as keywords.
|
||||
|
||||
Writes one JSON object per line to data/articles.jsonl, so a corpus-wide run
|
||||
stays a single file:
|
||||
|
||||
{"_id": ..., "maintitle": ..., "full_content": ..., "date": ...,
|
||||
"authors": [...]}
|
||||
|
||||
Usage:
|
||||
python fetch_articles.py # 500 articles, seed 42
|
||||
python fetch_articles.py --sample 2000
|
||||
python fetch_articles.py --all # every article in the index
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import requests
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
INSE_URL = os.getenv("INSE_ELASTIC_URL", "https://inse.nes.uni-due.de/elastic")
|
||||
INSE_API_KEY = os.getenv("INSE_ELASTIC_API_KEY")
|
||||
if not INSE_API_KEY:
|
||||
raise SystemExit(
|
||||
"INSE_ELASTIC_API_KEY ist nicht gesetzt. Lege eine .env an oder exportiere die Variable."
|
||||
)
|
||||
|
||||
ES_HEADERS = {
|
||||
"Authorization": f"ApiKey {INSE_API_KEY}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
RANDOM_SEED = 42
|
||||
OUTPUT_FILE = "data/articles.jsonl"
|
||||
MGET_CHUNK = 200
|
||||
|
||||
|
||||
def scroll_ids(index):
|
||||
"""Returns every _id of an index via a scrolling search."""
|
||||
ids = []
|
||||
response = requests.post(
|
||||
f"{INSE_URL}/{index}/_search?scroll=2m",
|
||||
json={"query": {"match_all": {}}, "_source": False, "size": 1000},
|
||||
headers=ES_HEADERS,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
scroll_id = data.get("_scroll_id")
|
||||
hits = data["hits"]["hits"]
|
||||
|
||||
while hits:
|
||||
ids.extend(hit["_id"] for hit in hits)
|
||||
response = requests.post(
|
||||
f"{INSE_URL}/_search/scroll",
|
||||
json={"scroll": "2m", "scroll_id": scroll_id},
|
||||
headers=ES_HEADERS,
|
||||
)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
scroll_id = data.get("_scroll_id")
|
||||
hits = data["hits"]["hits"]
|
||||
|
||||
if scroll_id:
|
||||
requests.delete(
|
||||
f"{INSE_URL}/_search/scroll",
|
||||
json={"scroll_id": [scroll_id]},
|
||||
headers=ES_HEADERS,
|
||||
)
|
||||
|
||||
return ids
|
||||
|
||||
|
||||
def mget(index, ids, source_fields):
|
||||
"""Fetches documents by id in chunks.
|
||||
|
||||
The `ids` body form of _mget takes no top-level `_source`; source
|
||||
filtering has to go into the query string, otherwise Elasticsearch
|
||||
answers 400.
|
||||
"""
|
||||
documents = []
|
||||
params = {"_source": ",".join(source_fields)} if source_fields else None
|
||||
for start in range(0, len(ids), MGET_CHUNK):
|
||||
chunk = ids[start:start + MGET_CHUNK]
|
||||
response = requests.post(
|
||||
f"{INSE_URL}/{index}/_mget",
|
||||
json={"ids": chunk},
|
||||
params=params,
|
||||
headers=ES_HEADERS,
|
||||
)
|
||||
response.raise_for_status()
|
||||
documents.extend(response.json()["docs"])
|
||||
return documents
|
||||
|
||||
|
||||
def fetch_authors(news_ids):
|
||||
"""Maps news_id -> extracted author names from aktuell_postproc.
|
||||
|
||||
Searched by the `news_id` field rather than fetched by document id: the
|
||||
sync job POSTs to /_doc without an id, so Elasticsearch assigns a random
|
||||
_id and an _mget on news_id would quietly find nothing. This mirrors how
|
||||
the service resolves postproc entries.
|
||||
"""
|
||||
authors_by_id = {}
|
||||
for start in range(0, len(news_ids), MGET_CHUNK):
|
||||
chunk = news_ids[start:start + MGET_CHUNK]
|
||||
response = requests.post(
|
||||
f"{INSE_URL}/aktuell_postproc/_search",
|
||||
json={
|
||||
"query": {"terms": {"news_id.keyword": chunk}},
|
||||
"_source": ["news_id", "authors"],
|
||||
"size": min(len(chunk) * 2, 10000),
|
||||
},
|
||||
headers=ES_HEADERS,
|
||||
)
|
||||
response.raise_for_status()
|
||||
for hit in response.json().get("hits", {}).get("hits", []):
|
||||
source = hit.get("_source", {})
|
||||
news_id = source.get("news_id")
|
||||
if news_id:
|
||||
authors_by_id[news_id] = source.get("authors") or []
|
||||
return authors_by_id
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--sample", type=int, default=500, help="Stichprobengröße (Default: 500).")
|
||||
parser.add_argument("--all", action="store_true", help="Alle Artikel statt einer Stichprobe.")
|
||||
parser.add_argument("--seed", type=int, default=RANDOM_SEED, help="Zufalls-Seed.")
|
||||
parser.add_argument("--output", default=OUTPUT_FILE)
|
||||
args = parser.parse_args()
|
||||
|
||||
print("Hole alle _id aus dem Index 'aktuell'...")
|
||||
all_ids = scroll_ids("aktuell")
|
||||
print(f"{len(all_ids)} Artikel im Index.")
|
||||
|
||||
if args.all:
|
||||
selected = all_ids
|
||||
else:
|
||||
if len(all_ids) < args.sample:
|
||||
raise SystemExit("Nicht genug Dokumente für die Stichprobe.")
|
||||
random.seed(args.seed)
|
||||
selected = random.sample(all_ids, args.sample)
|
||||
print(f"Ausgewählt: {len(selected)} Artikel (Seed={args.seed}).")
|
||||
|
||||
print("Hole Artikelinhalte...")
|
||||
documents = mget("aktuell", selected, ["maintitle", "full_content", "date"])
|
||||
|
||||
print("Hole Autorennamen aus 'aktuell_postproc'...")
|
||||
authors_by_id = fetch_authors(selected)
|
||||
with_authors = sum(1 for names in authors_by_id.values() if names)
|
||||
print(
|
||||
f" {len(authors_by_id)}/{len(selected)} Artikel haben einen Postproc-Eintrag, "
|
||||
f"davon {with_authors} mit Namen."
|
||||
)
|
||||
|
||||
os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True)
|
||||
written = 0
|
||||
with open(args.output, "w", encoding="utf-8") as output_file:
|
||||
for document in documents:
|
||||
if not document.get("found"):
|
||||
continue
|
||||
source = document.get("_source", {})
|
||||
news_id = document.get("_id")
|
||||
record = {
|
||||
"_id": news_id,
|
||||
"maintitle": source.get("maintitle"),
|
||||
"full_content": source.get("full_content"),
|
||||
"date": source.get("date"),
|
||||
"authors": authors_by_id.get(news_id, []),
|
||||
}
|
||||
output_file.write(json.dumps(record, ensure_ascii=False) + "\n")
|
||||
written += 1
|
||||
|
||||
print(f"Fertig. {written} Datensätze in '{args.output}'.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,8 @@
|
||||
requests==2.34.2
|
||||
openai==2.41.0
|
||||
python-dotenv==1.0.1
|
||||
tabulate==0.9.0
|
||||
|
||||
# Optional, for the lemma-, Grundform- and NER-based checks.
|
||||
# Without it those checks report "n. v." instead of a number:
|
||||
# pip install spacy==3.8.2 && python -m spacy download de_core_news_sm
|
||||
@@ -0,0 +1,157 @@
|
||||
"""Prints the Layer-1 tables.
|
||||
|
||||
Reads results_<config>.json for every configuration given
|
||||
and emits the compliance table, the descriptive table and the error table.
|
||||
|
||||
Usage:
|
||||
python results.py
|
||||
python results.py --configs neu
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
L2_LABELS = {"lemma": "L2, Lemma", "flexion": "L2, Flexion"}
|
||||
|
||||
COMPLIANCE_ROWS = [
|
||||
("Wörtlich im Text ({l2})", "keyword_level", "literal_l2"),
|
||||
(" davon normalisiert (L1)", "keyword_level", "literal_l1"),
|
||||
(" davon exakt (L0)", "keyword_level", "literal_l0"),
|
||||
("Artikel ohne Wörtlichkeitsverstoß", "article_level", "literal_all"),
|
||||
("Höchstens sechs Schlagwörter (roh)", "article_level", "count_ok"),
|
||||
("Keine Duplikate (roh)", "article_level", "no_duplicates"),
|
||||
("Keine Stamm-Redundanz", "article_level", "no_stem_redundancy"),
|
||||
("Keine Personennamen (Autorenfeld)", "keyword_level", "no_person_name_authors"),
|
||||
("Keine Personennamen (NER)", "keyword_level", "no_person_name_ner"),
|
||||
("Keine Datumsangaben", "keyword_level", "no_date"),
|
||||
("Grundform (Nom. Sg.)", "keyword_level", "base_form"),
|
||||
]
|
||||
|
||||
DESCRIPTIVE_ROWS = [
|
||||
("Ausgewertete Artikel", "articles_evaluated"),
|
||||
("Ausgewertete Schlagwörter", "keywords_total"),
|
||||
]
|
||||
|
||||
DESCRIPTIVE_SUB_ROWS = [
|
||||
("Schlagwörter je Artikel (Mittelwert)", "mean_keywords"),
|
||||
("Schlagwörter je Artikel (Median)", "median_keywords"),
|
||||
("Artikel ohne Schlagwörter", "articles_zero_keywords"),
|
||||
("Artikel mit genau sechs", "articles_exactly_six"),
|
||||
("Artikel mit mehr als sechs", "articles_over_six"),
|
||||
]
|
||||
|
||||
|
||||
def format_rate(bucket):
|
||||
"""'x/N (yy,y %)', or a bound when some cases are not determinable.
|
||||
|
||||
Undecidable cases are not dropped from the denominator: doing so would
|
||||
report a flattering rate over exactly the easy cases (without spaCy, only
|
||||
the keywords that already passed L1 are decidable at L2, which would print
|
||||
100 %). With n. v. present the honest statement is an interval — every
|
||||
undetermined case is a pass in the best and a failure in the worst case.
|
||||
"""
|
||||
passed = bucket["pass"]
|
||||
failed = bucket["fail"]
|
||||
not_available = bucket["na"]
|
||||
total = passed + failed + not_available
|
||||
|
||||
if total == 0:
|
||||
return "–"
|
||||
if passed + failed == 0:
|
||||
return f"n. v. ({not_available})"
|
||||
|
||||
if not_available == 0:
|
||||
percentage = f"{100.0 * passed / total:.1f}".replace(".", ",")
|
||||
return f"{passed}/{total} ({percentage} %)"
|
||||
|
||||
lower = f"{100.0 * passed / total:.1f}".replace(".", ",")
|
||||
upper = f"{100.0 * (passed + not_available) / total:.1f}".replace(".", ",")
|
||||
return f"{passed}/{total} ({lower}–{upper} %, {not_available} n. v.)"
|
||||
|
||||
|
||||
def load(config):
|
||||
path = f"results_{config}.json"
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
with open(path, encoding="utf-8") as results_file:
|
||||
return json.load(results_file)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--configs", nargs="+", default=["alt", "neu"])
|
||||
args = parser.parse_args()
|
||||
|
||||
loaded = [(config, load(config)) for config in args.configs]
|
||||
available = [(config, data) for config, data in loaded if data]
|
||||
missing = [config for config, data in loaded if not data]
|
||||
|
||||
if not available:
|
||||
raise SystemExit("Keine results_<config>.json gefunden. Erst evaluate.py laufen lassen.")
|
||||
if missing:
|
||||
print(f"Hinweis: keine Ergebnisse für {', '.join(missing)} — Spalte entfällt.\n")
|
||||
|
||||
labels = {"alt": "Alt-Konfig", "neu": "Neu-Konfig"}
|
||||
headers = ["Kriterium"] + [labels.get(config, config) for config, _ in available]
|
||||
|
||||
methods = {data.get("l2_method", "lemma") for _, data in available}
|
||||
l2_label = " / ".join(sorted(L2_LABELS.get(method, method) for method in methods))
|
||||
|
||||
rows = []
|
||||
for label, section, key in COMPLIANCE_ROWS:
|
||||
row = [label.format(l2=l2_label)]
|
||||
for _, data in available:
|
||||
bucket = data[section].get(key)
|
||||
row.append(format_rate(bucket) if bucket else "–")
|
||||
rows.append(row)
|
||||
|
||||
determinism_row = ["Reproduzierbarkeit (Jaccard, Wiederholungen)"]
|
||||
for _, data in available:
|
||||
determinism = data.get("determinism")
|
||||
if not determinism:
|
||||
determinism_row.append("–")
|
||||
else:
|
||||
value = f"{determinism['mean_pairwise_jaccard']:.4f}".replace(".", ",")
|
||||
determinism_row.append(f"{value} (n={determinism['articles']})")
|
||||
rows.append(determinism_row)
|
||||
|
||||
print("## Regelkonformität (Layer 1)\n")
|
||||
print(tabulate(rows, headers=headers, tablefmt="orgtbl"))
|
||||
|
||||
print("\n\n## Deskriptive Kennzahlen\n")
|
||||
descriptive_rows = []
|
||||
for label, key in DESCRIPTIVE_ROWS:
|
||||
descriptive_rows.append([label] + [str(data[key]) for _, data in available])
|
||||
for label, key in DESCRIPTIVE_SUB_ROWS:
|
||||
descriptive_rows.append(
|
||||
[label] + [str(data["descriptive"][key]).replace(".", ",") for _, data in available]
|
||||
)
|
||||
print(tabulate(descriptive_rows, headers=headers, tablefmt="orgtbl"))
|
||||
|
||||
error_keys = sorted({key for _, data in available for key in data["errors"]})
|
||||
if error_keys:
|
||||
print("\n\n## Fehlerfälle\n")
|
||||
error_rows = [
|
||||
[key] + [str(data["errors"].get(key, 0)) for _, data in available]
|
||||
for key in error_keys
|
||||
]
|
||||
print(tabulate(error_rows, headers=headers, tablefmt="orgtbl"))
|
||||
|
||||
print("\n\n## Beispiele für Verstöße (für den Fließtext)\n")
|
||||
for config, data in available:
|
||||
for check in ("literal_l2", "no_person_name_authors", "no_date"):
|
||||
found = data["examples"].get(check) or []
|
||||
if not found:
|
||||
continue
|
||||
sample = ", ".join(
|
||||
f"\"{item.get('keyword')}\"" for item in found[:5] if item.get("keyword")
|
||||
)
|
||||
if sample:
|
||||
print(f"- [{config}] {check}: {sample}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"judged": 294,
|
||||
"counts": {
|
||||
"richtig": 177,
|
||||
"akzeptabel": 101,
|
||||
"falsch": 16
|
||||
},
|
||||
"precision_incl_acceptable": 94.6,
|
||||
"precision_strict": 60.2,
|
||||
"essential_total": 125,
|
||||
"essential_hit": 96
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"judged": 294,
|
||||
"counts": {
|
||||
"richtig": 141,
|
||||
"akzeptabel": 146,
|
||||
"falsch": 7
|
||||
},
|
||||
"precision_incl_acceptable": 97.6,
|
||||
"precision_strict": 48.0,
|
||||
"essential_total": 125,
|
||||
"essential_hit": 96
|
||||
}
|
||||
@@ -0,0 +1,731 @@
|
||||
{
|
||||
"config": "neu",
|
||||
"l2_method": "flexion",
|
||||
"articles_evaluated": 500,
|
||||
"keywords_total": 2890,
|
||||
"errors": {},
|
||||
"keyword_level": {
|
||||
"literal_l0": {
|
||||
"pass": 2461,
|
||||
"fail": 429,
|
||||
"na": 0
|
||||
},
|
||||
"literal_l1": {
|
||||
"pass": 2464,
|
||||
"fail": 426,
|
||||
"na": 0
|
||||
},
|
||||
"literal_l2": {
|
||||
"pass": 2796,
|
||||
"fail": 94,
|
||||
"na": 0
|
||||
},
|
||||
"no_person_name_authors": {
|
||||
"pass": 2889,
|
||||
"fail": 1,
|
||||
"na": 0
|
||||
},
|
||||
"no_person_name_ner": {
|
||||
"pass": 0,
|
||||
"fail": 0,
|
||||
"na": 2890
|
||||
},
|
||||
"no_date": {
|
||||
"pass": 2890,
|
||||
"fail": 0,
|
||||
"na": 0
|
||||
},
|
||||
"base_form": {
|
||||
"pass": 0,
|
||||
"fail": 0,
|
||||
"na": 2890
|
||||
}
|
||||
},
|
||||
"article_level": {
|
||||
"count_ok": {
|
||||
"pass": 499,
|
||||
"fail": 1,
|
||||
"na": 0
|
||||
},
|
||||
"no_duplicates": {
|
||||
"pass": 500,
|
||||
"fail": 0,
|
||||
"na": 0
|
||||
},
|
||||
"no_stem_redundancy": {
|
||||
"pass": 464,
|
||||
"fail": 36,
|
||||
"na": 0
|
||||
},
|
||||
"literal_all": {
|
||||
"pass": 415,
|
||||
"fail": 85,
|
||||
"na": 0
|
||||
}
|
||||
},
|
||||
"descriptive": {
|
||||
"mean_keywords": 5.78,
|
||||
"median_keywords": 6.0,
|
||||
"articles_zero_keywords": 0,
|
||||
"articles_exactly_six": 439,
|
||||
"articles_over_six": 1
|
||||
},
|
||||
"determinism": null,
|
||||
"examples": {
|
||||
"literal_l0": [
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "internationale Kooperationen"
|
||||
},
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "Wissenschaftler"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Zahnstruktur"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Nano- und Werkstoffwissenschaft"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "mechanische Messung"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "Hochsee-Windpark"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "bipolares Kabelsystem"
|
||||
},
|
||||
{
|
||||
"_id": "07102019__Stipendium–auchohneEinser-Abi",
|
||||
"keyword": "Förderwerke"
|
||||
},
|
||||
{
|
||||
"_id": "22052017_ClaudiaBraczko_RentnerarbeitimBetrieb",
|
||||
"keyword": "Teilzeit- und Minijobs"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Internationale Möbelmesse IMM Cologne"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Wohnobjekt aus Edelstahl"
|
||||
},
|
||||
{
|
||||
"_id": "20112018_DrAlexandraNießen_NanogroßbeiTumorforschung",
|
||||
"keyword": "Implantat"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "kardiovaskuläre Erkrankung"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "romantische Poesie"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Süßwassersystem"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Forschungsprojekt"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Sanierungsstrategie"
|
||||
},
|
||||
{
|
||||
"_id": "16112017_UlrikeEichweber_WiewarendieerstenWochen",
|
||||
"keyword": "UDE-Panel"
|
||||
},
|
||||
{
|
||||
"_id": "08102019_UlrikeEichweber_KIinderFinanzwelt",
|
||||
"keyword": "Banken-Symposium"
|
||||
},
|
||||
{
|
||||
"_id": "21092018_BeateKostka_Zweifacherfolgreich",
|
||||
"keyword": "Deutsche Forschungsgemeinschaft"
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keyword": "regionale Ausdrücke"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Reaktorunglück von Fukushima"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Rotes Kreuz"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Deutsche Science Slam Meisterschaft"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Wirkstoffkombination"
|
||||
}
|
||||
],
|
||||
"literal_l1": [
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "internationale Kooperationen"
|
||||
},
|
||||
{
|
||||
"_id": "08072015_KatrinKoster_beralleGrenzenhinweg_archiv",
|
||||
"keyword": "Wissenschaftler"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Zahnstruktur"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "Nano- und Werkstoffwissenschaft"
|
||||
},
|
||||
{
|
||||
"_id": "27072012__Damitsieauchmorgennochzubeißen_archiv",
|
||||
"keyword": "mechanische Messung"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "Hochsee-Windpark"
|
||||
},
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "bipolares Kabelsystem"
|
||||
},
|
||||
{
|
||||
"_id": "07102019__Stipendium–auchohneEinser-Abi",
|
||||
"keyword": "Förderwerke"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Internationale Möbelmesse IMM Cologne"
|
||||
},
|
||||
{
|
||||
"_id": "18012005_ChristophLindemann_UnterrichtaufderMbelmesse_archiv",
|
||||
"keyword": "Wohnobjekt aus Edelstahl"
|
||||
},
|
||||
{
|
||||
"_id": "20112018_DrAlexandraNießen_NanogroßbeiTumorforschung",
|
||||
"keyword": "Implantat"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "kardiovaskuläre Erkrankung"
|
||||
},
|
||||
{
|
||||
"_id": "10112004_MonikaRgge_DiagnosenfrFrauenundMnner_archiv",
|
||||
"keyword": "romantische Poesie"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Süßwassersystem"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Forschungsprojekt"
|
||||
},
|
||||
{
|
||||
"_id": "06052015_KatrinKoster_WasunserenGewssernhilft_archiv",
|
||||
"keyword": "Sanierungsstrategie"
|
||||
},
|
||||
{
|
||||
"_id": "16112017_UlrikeEichweber_WiewarendieerstenWochen",
|
||||
"keyword": "UDE-Panel"
|
||||
},
|
||||
{
|
||||
"_id": "08102019_UlrikeEichweber_KIinderFinanzwelt",
|
||||
"keyword": "Banken-Symposium"
|
||||
},
|
||||
{
|
||||
"_id": "21092018_BeateKostka_Zweifacherfolgreich",
|
||||
"keyword": "Deutsche Forschungsgemeinschaft"
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keyword": "regionale Ausdrücke"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Reaktorunglück von Fukushima"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Rotes Kreuz"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Deutsche Science Slam Meisterschaft"
|
||||
},
|
||||
{
|
||||
"_id": "25112021_UlrikeEichweber_UDE-DoktorandinimFinale",
|
||||
"keyword": "Wirkstoffkombination"
|
||||
},
|
||||
{
|
||||
"_id": "27102015__NeuesKonzeptsollPflegeerleichtern_archiv",
|
||||
"keyword": "emotionale Belastung"
|
||||
}
|
||||
],
|
||||
"literal_l2": [
|
||||
{
|
||||
"_id": "23032007_AnnikaBingmann_VielWindumEnergie_archiv",
|
||||
"keyword": "bipolares Kabelsystem"
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keyword": "regionale Ausdrücke"
|
||||
},
|
||||
{
|
||||
"_id": "05042011_BeateHKostka_„JapanbrauchtunsereHilfe!“_archiv",
|
||||
"keyword": "Rotes Kreuz"
|
||||
},
|
||||
{
|
||||
"_id": "29112018_BeateKostka_RelevanteInformationenausDatenbergen",
|
||||
"keyword": "Verkehrsvorhersage"
|
||||
},
|
||||
{
|
||||
"_id": "11092015__JemehrMutationen,destowirksamer_archiv",
|
||||
"keyword": "Wirkmechanismus"
|
||||
},
|
||||
{
|
||||
"_id": "19092006__ZweiFliegenmiteinerKlappeschlagen_archiv",
|
||||
"keyword": "Virtueller Weiterbildungsstudiengang Wirtschaftsinformatik"
|
||||
},
|
||||
{
|
||||
"_id": "11042005_UlrikeBohnsack_GroßeFestveranstaltunginBerlin_archiv",
|
||||
"keyword": "Linguistik"
|
||||
},
|
||||
{
|
||||
"_id": "20032026_DrAlexandraNießen_GuteZusammenarbeitmitKI",
|
||||
"keyword": "Arbeitsplatz"
|
||||
},
|
||||
{
|
||||
"_id": "14092021_UlrikeEichweber_IFWW-Frderpreis",
|
||||
"keyword": "wissenschaftlicher Nachwuchs"
|
||||
},
|
||||
{
|
||||
"_id": "14092021_UlrikeEichweber_IFWW-Frderpreis",
|
||||
"keyword": "Trinkwasser"
|
||||
},
|
||||
{
|
||||
"_id": "14092021_UlrikeEichweber_IFWW-Frderpreis",
|
||||
"keyword": "Abwasser"
|
||||
},
|
||||
{
|
||||
"_id": "13122023_DrAlexandraNießen_WasistanderUnilos",
|
||||
"keyword": "Smart City"
|
||||
},
|
||||
{
|
||||
"_id": "21052024_CathrinBecker_Wannmanwenwieanspricht",
|
||||
"keyword": "Spender:in"
|
||||
},
|
||||
{
|
||||
"_id": "05042024_CathrinBecker_10JahreSpitzenfrderung",
|
||||
"keyword": "Leitthema"
|
||||
},
|
||||
{
|
||||
"_id": "02122019_DrAlexandraNießen_EuropaweiterAustausch",
|
||||
"keyword": "Akademisches Auslandsamt"
|
||||
},
|
||||
{
|
||||
"_id": "16062025_UlrikeEichweber_Dalberg-PreisfrtransdisziplinreNachwuchsforschung",
|
||||
"keyword": "Geisteswissenschaften"
|
||||
},
|
||||
{
|
||||
"_id": "09032017_UlrikeBohnsack_DieAngstvormScheitern",
|
||||
"keyword": "Risiko"
|
||||
},
|
||||
{
|
||||
"_id": "08092020_DrAlexandraNießen_Cooperatingrobots",
|
||||
"keyword": "remote-controlled robot arm"
|
||||
},
|
||||
{
|
||||
"_id": "27072021_UlrikeEichweber_LehrenziehenausderPandemie",
|
||||
"keyword": "Lehrkraft"
|
||||
},
|
||||
{
|
||||
"_id": "06112019_DrAlexandraNießen_Typischdeutsch",
|
||||
"keyword": "Kulturwissenschaftliches Institut"
|
||||
},
|
||||
{
|
||||
"_id": "03062019_UlrikeEichweber_EuropischekonomeninGenua",
|
||||
"keyword": "Vortrag"
|
||||
},
|
||||
{
|
||||
"_id": "12102012__Studienstartfr25TeilnehmerInnen_archiv",
|
||||
"keyword": "Stipendium"
|
||||
},
|
||||
{
|
||||
"_id": "12112007_JuliaHarzendorf_LeistungenfrsStudiumanrechnen_archiv",
|
||||
"keyword": "Logistikstudiengang"
|
||||
},
|
||||
{
|
||||
"_id": "16082022_ThomasWittek_ErsterSchnappschusseinesScheibenwinds",
|
||||
"keyword": "Schwarzes Loch"
|
||||
},
|
||||
{
|
||||
"_id": "16082022_ThomasWittek_ErsterSchnappschusseinesScheibenwinds",
|
||||
"keyword": "massereicher Stern"
|
||||
}
|
||||
],
|
||||
"no_person_name_authors": [
|
||||
{
|
||||
"_id": "01092017_CathrinBecker_AlleParteienimberblick",
|
||||
"keyword": "Politikwissenschaftler"
|
||||
}
|
||||
],
|
||||
"no_person_name_ner": [],
|
||||
"no_date": [],
|
||||
"base_form": [],
|
||||
"count_ok": [
|
||||
{
|
||||
"_id": "30042019_UlrikeEichweber_FrwenigerCO",
|
||||
"keywords": [
|
||||
"Stadtradeln",
|
||||
"Klima-Bündnisses e.V.",
|
||||
"CO2",
|
||||
"Radler",
|
||||
"Kilometer",
|
||||
"Duisburg",
|
||||
"Essen"
|
||||
]
|
||||
}
|
||||
],
|
||||
"no_duplicates": [],
|
||||
"no_stem_redundancy": [
|
||||
{
|
||||
"_id": "14022003_MonikaRgge_KonzertinderKreuzeskirche_archiv",
|
||||
"keywords": [
|
||||
"Essener Studentenorchester",
|
||||
"Konzert",
|
||||
"Orchester",
|
||||
"Studenten",
|
||||
"Folkwang-Hochschule Essen",
|
||||
"Musizieren"
|
||||
],
|
||||
"pairs": [
|
||||
["Orchester", "Essener Studentenorchester"],
|
||||
["Studenten", "Essener Studentenorchester"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "22052017_ClaudiaBraczko_RentnerarbeitimBetrieb",
|
||||
"keywords": [
|
||||
"Rentnerarbeit im Betrieb",
|
||||
"Fachkräftemangel",
|
||||
"Teilzeit- und Minijobs",
|
||||
"Wissensverlust",
|
||||
"flexibler Personalpuffer",
|
||||
"Rentner"
|
||||
],
|
||||
"pairs": [["Rentner", "Rentnerarbeit im Betrieb"]]
|
||||
},
|
||||
{
|
||||
"_id": "22122004_UlrikeBohnsack_Neu:VariantenwrterbuchDeutsch_archiv",
|
||||
"keywords": [
|
||||
"Variantenwörterbuch",
|
||||
"Standardsprache",
|
||||
"Linguistik",
|
||||
"Soziolinguistik",
|
||||
"regionale Ausdrücke",
|
||||
"Grammatik"
|
||||
],
|
||||
"pairs": [["Linguistik", "Soziolinguistik"]]
|
||||
},
|
||||
{
|
||||
"_id": "19052009__InallenStudienphasengutberaten_archiv",
|
||||
"keywords": [
|
||||
"Mentoring-System",
|
||||
"Studierendenbetreuung",
|
||||
"Studierende",
|
||||
"Fachbereichen",
|
||||
"persönliche Beratung",
|
||||
"Studienabbrüche"
|
||||
],
|
||||
"pairs": [["Studierende", "Studierendenbetreuung"]]
|
||||
},
|
||||
{
|
||||
"_id": "20112019_ChristineHarrell_EinNichtsmitgroßerWirkung",
|
||||
"keywords": [
|
||||
"chronische Rückenschmerzen",
|
||||
"Open-Label Placebos",
|
||||
"Schmerz",
|
||||
"Beweglichkeit",
|
||||
"klinische Neurowissenschaft",
|
||||
"Schmerztherapie"
|
||||
],
|
||||
"pairs": [
|
||||
["Schmerz", "chronische Rückenschmerzen"],
|
||||
["Schmerz", "Schmerztherapie"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "17042018_BeateKostka_FitfrdieDemokratie",
|
||||
"keywords": [
|
||||
"Demokratie",
|
||||
"Jugendliche",
|
||||
"politische und zivilgesellschaftliche Bildung",
|
||||
"politisches Wissen",
|
||||
"Elternhaus",
|
||||
"demokratiekompetent"
|
||||
],
|
||||
"pairs": [["Demokratie", "demokratiekompetent"]]
|
||||
},
|
||||
{
|
||||
"_id": "21052024_CathrinBecker_Wannmanwenwieanspricht",
|
||||
"keywords": [
|
||||
"Stammzelle",
|
||||
"Blut",
|
||||
"Spendenbereitschaft",
|
||||
"Spender:in",
|
||||
"Information",
|
||||
"Blutkrebs"
|
||||
],
|
||||
"pairs": [["Blut", "Blutkrebs"]]
|
||||
},
|
||||
{
|
||||
"_id": "27112014__DerFallBeloMonte_archiv",
|
||||
"keywords": [
|
||||
"Menschrechte",
|
||||
"Konflikt",
|
||||
"Ureinwohner",
|
||||
"Belo Monte-Wasserkraftwerk",
|
||||
"Amazonasgebiet",
|
||||
"Grundlegende politische Konflikte"
|
||||
],
|
||||
"pairs": [["Konflikt", "Grundlegende politische Konflikte"]]
|
||||
},
|
||||
{
|
||||
"_id": "26062017_CathrinBecker_PionierforschungzuNanopartikeln",
|
||||
"keywords": [
|
||||
"Nanopartikel",
|
||||
"Pionierforschung",
|
||||
"lasergenerierte Nanoteilchen",
|
||||
"Biomedizin- und Energietechnik",
|
||||
"kontinuierlichen laserbasierten Nanopartikelsynthese",
|
||||
"Habilitationsschrift"
|
||||
],
|
||||
"pairs": [
|
||||
[
|
||||
"Nanopartikel",
|
||||
"kontinuierlichen laserbasierten Nanopartikelsynthese"
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "18122023__Pathtosustainablehydrogen",
|
||||
"keywords": [
|
||||
"green hydrogen",
|
||||
"electrocatalysts",
|
||||
"oxygen evolution reaction",
|
||||
"surface transformation",
|
||||
"perovskite",
|
||||
"crystal facet-dependent surface transformation"
|
||||
],
|
||||
"pairs": [
|
||||
[
|
||||
"surface transformation",
|
||||
"crystal facet-dependent surface transformation"
|
||||
]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "01072014_AlexandraNießen_MathematikalsLebenshilfe_archiv",
|
||||
"keywords": [
|
||||
"Mathematik",
|
||||
"Problemlösen",
|
||||
"Didaktik",
|
||||
"Techniken und Strategien des Problemlösens",
|
||||
"Heurismen",
|
||||
"Learning the Science of Education"
|
||||
],
|
||||
"pairs": [
|
||||
["Problemlösen", "Techniken und Strategien des Problemlösens"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "02052017_ManuelaMnch_Berufungen-Mai2017",
|
||||
"keywords": [
|
||||
"Professur",
|
||||
"Juniorprofessur",
|
||||
"Medizinische Onkologie mit Schwerpunkt Gastrointestinale Onkologie",
|
||||
"Informatik",
|
||||
"Experimentelle Physik",
|
||||
"Fakultät für Medizin"
|
||||
],
|
||||
"pairs": [["Professur", "Juniorprofessur"]]
|
||||
},
|
||||
{
|
||||
"_id": "16112011_CarmenTomlik_ZumSchutzezndenderIdeen_archiv",
|
||||
"keywords": [
|
||||
"PatentScouts",
|
||||
"Erfinderberatung",
|
||||
"Forschungsergebnis",
|
||||
"Patent",
|
||||
"Drittmittel",
|
||||
"Biomedizin"
|
||||
],
|
||||
"pairs": [["Patent", "PatentScouts"]]
|
||||
},
|
||||
{
|
||||
"_id": "27112020_DrAlexandraNießen_SpracheverleihtFlgel",
|
||||
"keywords": [
|
||||
"Mehrsprachigkeit",
|
||||
"gesellschaftliche Teilhabe",
|
||||
"Arbeitsmarkt",
|
||||
"Deutsch als Zweitsprache",
|
||||
"Fremdsprachen",
|
||||
"Sprache"
|
||||
],
|
||||
"pairs": [
|
||||
["Sprache", "Deutsch als Zweitsprache"],
|
||||
["Sprache", "Fremdsprachen"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "02112009__NochzehnStipendienzuvergeben_archiv",
|
||||
"keywords": [
|
||||
"Stipendien",
|
||||
"Erstsemester",
|
||||
"Migrationshintergrund",
|
||||
"NRW-Stipendienprogramm",
|
||||
"Diversity Management"
|
||||
],
|
||||
"pairs": [["Stipendien", "NRW-Stipendienprogramm"]]
|
||||
},
|
||||
{
|
||||
"_id": "10082005_ChristophLindemann_1000LernmodulefrdieMedizin_archiv",
|
||||
"keywords": [
|
||||
"Learning Resource Server Medizin",
|
||||
"Lernmodul",
|
||||
"Medizin",
|
||||
"Aus-, Fort- und Weiterbildung",
|
||||
"Datenbank",
|
||||
"Internet-Portal"
|
||||
],
|
||||
"pairs": [["Medizin", "Learning Resource Server Medizin"]]
|
||||
},
|
||||
{
|
||||
"_id": "24092003_DanielaEndrulat_TrauerumlangjhrigenKlinikleiter_archiv",
|
||||
"keywords": [
|
||||
"Unfallchirurgie",
|
||||
"Klinik und Poliklinik für Unfallchirurgie",
|
||||
"Präklinische Unfallrettung",
|
||||
"Klinische Schockforschung",
|
||||
"Tumor-Chirurgie",
|
||||
"Ausbildung von Notarzt"
|
||||
],
|
||||
"pairs": [
|
||||
["Unfallchirurgie", "Klinik und Poliklinik für Unfallchirurgie"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "08042021_UlrikeEichweber_UDE-Lehrpreis",
|
||||
"keywords": [
|
||||
"Duisburg-Essener Lehrpreis",
|
||||
"Lehrpreis",
|
||||
"Fakultäten",
|
||||
"Fachschaftsräte",
|
||||
"Kandidat",
|
||||
"Team"
|
||||
],
|
||||
"pairs": [["Lehrpreis", "Duisburg-Essener Lehrpreis"]]
|
||||
},
|
||||
{
|
||||
"_id": "25052011__NickReillybesuchtUniversitt_archiv",
|
||||
"keywords": [
|
||||
"Elektromobilität",
|
||||
"Automobiltechnik",
|
||||
"Brennstoffzelle",
|
||||
"Automobilindustrie",
|
||||
"Zentrum für BrennstoffzellenTechnik",
|
||||
"Nano-Material"
|
||||
],
|
||||
"pairs": [["Brennstoffzelle", "Zentrum für BrennstoffzellenTechnik"]]
|
||||
},
|
||||
{
|
||||
"_id": "13102005_MonikaRgge_VortragberDemenzen_archiv",
|
||||
"keywords": [
|
||||
"Demenzen",
|
||||
"Früherkennung und Diagnostik von Demenzen",
|
||||
"Klinik für Psychiatrie und Psychotherapie",
|
||||
"Essener Universitätsklinikum"
|
||||
],
|
||||
"pairs": [["Demenzen", "Früherkennung und Diagnostik von Demenzen"]]
|
||||
},
|
||||
{
|
||||
"_id": "19022026__MathematikldtzumTagderoffenenTr",
|
||||
"keywords": [
|
||||
"Mathematik",
|
||||
"Tag der offenen Tür",
|
||||
"Mathematikstudium",
|
||||
"Schnuppervorlesung",
|
||||
"Quantencomputer",
|
||||
"Brettspiel"
|
||||
],
|
||||
"pairs": [["Mathematik", "Mathematikstudium"]]
|
||||
},
|
||||
{
|
||||
"_id": "18122012__BestmglicheHeilung_archiv",
|
||||
"keywords": [
|
||||
"Krebs",
|
||||
"Translationale Krebsforschung",
|
||||
"Therapie",
|
||||
"Diagnostik",
|
||||
"Immunsystem",
|
||||
"individualisierte Therapie"
|
||||
],
|
||||
"pairs": [
|
||||
["Krebs", "Translationale Krebsforschung"],
|
||||
["Therapie", "individualisierte Therapie"]
|
||||
]
|
||||
},
|
||||
{
|
||||
"_id": "28082025_DrAlexandraNießen_Wissenshungerkanngestilltwerden",
|
||||
"keywords": [
|
||||
"Universität Duisburg-Essen",
|
||||
"Gasthörer",
|
||||
"Lehrprogramm",
|
||||
"Gasthörerverzeichnis",
|
||||
"Einschreibung",
|
||||
"Smart Farming"
|
||||
],
|
||||
"pairs": [["Gasthörer", "Gasthörerverzeichnis"]]
|
||||
},
|
||||
{
|
||||
"_id": "15102019_UlrikeEichweber_Einblickein30JahreForschung",
|
||||
"keywords": [
|
||||
"China",
|
||||
"Forschung",
|
||||
"Vorlesungsreihe",
|
||||
"China as a Developmental State",
|
||||
"Theory-based Researcg and Fieldwork",
|
||||
"Chinese Party State"
|
||||
],
|
||||
"pairs": [["China", "China as a Developmental State"]]
|
||||
},
|
||||
{
|
||||
"_id": "20062007_BeateKostka_DatenbertragungmitLicht_archiv",
|
||||
"keywords": [
|
||||
"Datenübertragung mit Licht",
|
||||
"Optoelektronik",
|
||||
"Laser",
|
||||
"Glasfaserkabel",
|
||||
"Halbleiter-Laser",
|
||||
"Medizintechnik"
|
||||
],
|
||||
"pairs": [["Laser", "Halbleiter-Laser"]]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,282 +0,0 @@
|
||||
# Query cookbook for the `ude` graph
|
||||
|
||||
Cypher examples for the whole-university graph built by `bulk_load.py` (FalkorDB Browser at
|
||||
http://localhost:3000, graph `ude`, or `FalkorDB(host="localhost").select_graph("ude").ro_query(...)`).
|
||||
Every example was run against the graph on 2026-09-15; timings are from that run.
|
||||
|
||||
Conventions:
|
||||
|
||||
- `Author` nodes of the university's own researchers carry the extra label `Cohort` (indexed).
|
||||
Start queries there whenever you can.
|
||||
- `CO_AUTHOR` edges are undirected in meaning (stored from the smaller to the larger author id);
|
||||
match them without an arrow: `(a)-[c:CO_AUTHOR]-(b)`.
|
||||
- Aggregations render as tables. To see a graph, return nodes and relationships (or paths).
|
||||
- Queries that touch the whole graph take 2 to 20 s; raise the browser's timeout first
|
||||
(`docker exec pensive_tu redis-cli GRAPH.CONFIG SET TIMEOUT 60000`).
|
||||
- Results are capped at 10,000 rows by the server (`RESULTSET_SIZE`).
|
||||
|
||||
## Overview
|
||||
|
||||
```cypher
|
||||
MATCH (n) RETURN labels(n), count(n) ORDER BY count(n) DESC
|
||||
```
|
||||
```cypher
|
||||
MATCH ()-[r]->() RETURN type(r), count(r) ORDER BY count(r) DESC
|
||||
```
|
||||
|
||||
Everything around one researcher, for the canvas:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort {name: 'Nikolai Axmacher'})-[r]-(n) RETURN a, r, n LIMIT 300
|
||||
```
|
||||
|
||||
Source coverage of the cohort (works, projects, patents, news, companies):
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)
|
||||
OPTIONAL MATCH (a)-[:AUTHORED]->(w:Work) WITH a, count(DISTINCT w) AS works
|
||||
OPTIONAL MATCH (a)-[:CONTRIBUTED_TO|DFG_ROLE]->(p:Project) WITH a, works, count(DISTINCT p) AS projects
|
||||
OPTIONAL MATCH (a)-[:INVENTOR_OF]->(pt:Patent) WITH a, works, projects, count(DISTINCT pt) AS patents
|
||||
OPTIONAL MATCH (a)-[:MENTIONED_IN]->(n:NewsArticle) WITH a, works, projects, patents, count(DISTINCT n) AS news
|
||||
OPTIONAL MATCH (a)-[:OFFICER_OF]->(c:Company) WITH a, works, projects, patents, news, count(DISTINCT c) AS companies
|
||||
RETURN count(a) AS cohort,
|
||||
sum(CASE WHEN works > 0 THEN 1 ELSE 0 END) AS with_works,
|
||||
sum(CASE WHEN projects > 0 THEN 1 ELSE 0 END) AS with_projects,
|
||||
sum(CASE WHEN patents > 0 THEN 1 ELSE 0 END) AS with_patents,
|
||||
sum(CASE WHEN news > 0 THEN 1 ELSE 0 END) AS with_news,
|
||||
sum(CASE WHEN companies > 0 THEN 1 ELSE 0 END) AS with_companies
|
||||
```
|
||||
|
||||
## Topics, subfields, fields and domains of the institution
|
||||
|
||||
The path from the institution: `Institution <-[:REPRESENTS]- Organization <-[:MEMBER_OF]- Cohort`.
|
||||
|
||||
Domains with counts (2.1 s):
|
||||
|
||||
```cypher
|
||||
MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(:Cohort)-[:AUTHORED]->(w:Work)
|
||||
-[:HAS_TOPIC]->(t:Topic)-[:IN_SUBFIELD]->(s:Subfield)-[:IN_FIELD]->(f:Field)-[:IN_DOMAIN]->(d:Domain)
|
||||
RETURN d.name AS domain, count(DISTINCT f) AS fields, count(DISTINCT s) AS subfields,
|
||||
count(DISTINCT t) AS topics, count(DISTINCT w) AS works
|
||||
ORDER BY works DESC
|
||||
```
|
||||
|
||||
Full hierarchy table, strongest topics first (2.4 s; drop `LIMIT` for all 4,336 topics):
|
||||
|
||||
```cypher
|
||||
MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(:Cohort)-[:AUTHORED]->(w:Work)
|
||||
-[:HAS_TOPIC]->(t:Topic)-[:IN_SUBFIELD]->(s:Subfield)-[:IN_FIELD]->(f:Field)-[:IN_DOMAIN]->(d:Domain)
|
||||
RETURN d.name AS domain, f.name AS field, s.name AS subfield, t.name AS topic, count(DISTINCT w) AS works
|
||||
ORDER BY works DESC LIMIT 100
|
||||
```
|
||||
|
||||
Fields by number of researchers, using OpenAlex's author-level topics (0.1 s):
|
||||
|
||||
```cypher
|
||||
MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(a:Cohort)-[:WORKS_ON]->(t:Topic)
|
||||
-[:IN_SUBFIELD]->(s:Subfield)-[:IN_FIELD]->(f:Field)-[:IN_DOMAIN]->(d:Domain)
|
||||
RETURN d.name AS domain, f.name AS field, count(DISTINCT a) AS researchers, count(DISTINCT t) AS topics
|
||||
ORDER BY researchers DESC
|
||||
```
|
||||
|
||||
### Graph versions via the research profile edges
|
||||
|
||||
The `profile` phase materialises `(Institution)-[:ACTIVE_IN {level, works, researchers}]->(Topic|Subfield|Field|Domain)`,
|
||||
so the counts live on drawable edges. Set the node caption of Domain/Field/Subfield/Topic to `name`.
|
||||
|
||||
Domains as a star around the institution, and domains with their fields:
|
||||
|
||||
```cypher
|
||||
MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN]->(d:Domain) RETURN i, r, d
|
||||
```
|
||||
```cypher
|
||||
MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN]->(f:Field)-[c:IN_DOMAIN]->(d:Domain)
|
||||
RETURN i, r, f, c, d
|
||||
```
|
||||
|
||||
Tree of the strongest topics attached to the institution (lower `800` to widen; add
|
||||
`AND d.name = 'Physical Sciences'` for one domain):
|
||||
|
||||
```cypher
|
||||
MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN {level: 'topic'}]->(t:Topic) WHERE r.works >= 800
|
||||
MATCH (t)-[a:IN_SUBFIELD]->(s:Subfield)-[b:IN_FIELD]->(f:Field)-[c:IN_DOMAIN]->(d:Domain)
|
||||
RETURN i, r, t, a, s, b, f, c, d
|
||||
```
|
||||
|
||||
Fields by researchers:
|
||||
|
||||
```cypher
|
||||
MATCH (i:Institution {id: 'I62318514'})-[r:ACTIVE_IN]->(f:Field) WHERE r.researchers >= 300
|
||||
RETURN i, r, f
|
||||
```
|
||||
|
||||
Without materialised edges: aggregate in a `WITH`, keep the top nodes, match the hierarchy again
|
||||
and return nodes and relationships (the counts are not shown, the institution is not connected):
|
||||
|
||||
```cypher
|
||||
MATCH (:Institution {id: 'I62318514'})<-[:REPRESENTS]-(:Organization)<-[:MEMBER_OF]-(:Cohort)-[:AUTHORED]->(w:Work)-[:HAS_TOPIC]->(t:Topic)
|
||||
WITH t, count(DISTINCT w) AS works ORDER BY works DESC LIMIT 40
|
||||
MATCH (t)-[a:IN_SUBFIELD]->(s:Subfield)-[b:IN_FIELD]->(f:Field)-[c:IN_DOMAIN]->(d:Domain)
|
||||
RETURN t, a, s, b, f, c, d
|
||||
```
|
||||
|
||||
## Collaboration
|
||||
|
||||
Strongest collaborations inside the university:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[c:CO_AUTHOR]->(b:Cohort)
|
||||
RETURN a.name, b.name, c.weight, c.first_year, c.last_year ORDER BY c.weight DESC LIMIT 20
|
||||
```
|
||||
|
||||
Top external partner institutions (4 s):
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[:CO_AUTHOR]-(b:Author)-[:AFFILIATED_WITH]->(i:Institution)
|
||||
WHERE NOT b:Cohort AND i.id <> 'I62318514'
|
||||
RETURN i.name, i.country_code, count(DISTINCT b) AS partners ORDER BY partners DESC LIMIT 20
|
||||
```
|
||||
|
||||
## Industry collaborations
|
||||
|
||||
OpenAlex types institutions as `education`, `healthcare`, `company`, `government`, `nonprofit`,
|
||||
`facility`, `funder` or `other`; the value is stored as `Institution.type`. Industry means
|
||||
`type = 'company'`. Two caveats: OpenAlex contains junk "companies" resolved from generic
|
||||
affiliation strings (`Faculty (United Kingdom)`, `Signal Processing (United States)`,
|
||||
`Engineering (Italy)`), and the author-level `AFFILIATED_WITH` edge is not tied to a paper, so a
|
||||
co-author who was ever at a company counts on every shared work. The `affiliations` phase adds the
|
||||
per-work view: `AUTHORED.institution_ids` and `(Work)-[:INVOLVES {authors}]->(Institution)`.
|
||||
Prefer the per-work queries below; the author-level ones are kept as a quick approximation.
|
||||
|
||||
How much it matters (validated 2026-09-15): for Daniel Erni the per-work view gives 10 industry
|
||||
co-publications with 4 companies (IBM, CETC, CSEM, ID Quantique), the author-level view claims 61
|
||||
joint works with 8 companies. University-wide, 15,569 works involve 3,874 companies. A further
|
||||
caveat is OpenAlex author disambiguation: a few cohort profiles are merged with namesakes
|
||||
(`Róbert Langer` carries the MIT chemist's industry ties), so check `orcid` before trusting an outlier.
|
||||
|
||||
### Per work (precise)
|
||||
|
||||
Companies on the papers of one researcher, with the co-authors who were at the company on that paper:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort {name: 'Daniel Erni'})-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'})
|
||||
MATCH (w)<-[e:AUTHORED]-(b:Author) WHERE i.id IN e.institution_ids
|
||||
RETURN i.name AS company, i.country_code AS country, count(DISTINCT w) AS works,
|
||||
collect(DISTINCT b.name)[0..4] AS company_coauthors
|
||||
ORDER BY works DESC
|
||||
```
|
||||
|
||||
The same as a graph (researcher, shared works, companies):
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort {name: 'Daniel Erni'})-[x:AUTHORED]->(w:Work)-[v:INVOLVES]->(i:Institution {type: 'company'})
|
||||
RETURN a, x, w, v, i
|
||||
```
|
||||
|
||||
Industry partners of researchers from a field (author-level OpenAlex topics define the field):
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[:WORKS_ON]->(:Topic)-[:IN_SUBFIELD]->()-[:IN_FIELD]->(:Field {name: 'Engineering'})
|
||||
WITH DISTINCT a
|
||||
MATCH (a)-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'})
|
||||
RETURN i.name AS company, i.country_code AS country,
|
||||
count(DISTINCT a) AS ude_researchers, count(DISTINCT w) AS joint_works
|
||||
ORDER BY ude_researchers DESC LIMIT 25
|
||||
```
|
||||
|
||||
Researchers of a field ranked by industry ties:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[:WORKS_ON]->(:Topic)-[:IN_SUBFIELD]->()-[:IN_FIELD]->(:Field {name: 'Engineering'})
|
||||
WITH DISTINCT a
|
||||
MATCH (a)-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'})
|
||||
RETURN a.name, count(DISTINCT i) AS companies, count(DISTINCT w) AS works, collect(DISTINCT i.name)[0..3] AS sample
|
||||
ORDER BY companies DESC LIMIT 20
|
||||
```
|
||||
|
||||
Industry co-publications per year for one researcher:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort {name: 'Daniel Erni'})-[:AUTHORED]->(w:Work)-[:INVOLVES]->(i:Institution {type: 'company'})
|
||||
RETURN w.year, count(DISTINCT w) AS works, collect(DISTINCT i.name)[0..3] AS companies
|
||||
ORDER BY w.year DESC
|
||||
```
|
||||
|
||||
Graph view for a field: researchers, their industry co-authored works and the companies
|
||||
(the `LIMIT` keeps the canvas readable):
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[:WORKS_ON]->(:Topic)-[:IN_SUBFIELD]->()-[:IN_FIELD]->(:Field {name: 'Engineering'})
|
||||
WITH DISTINCT a
|
||||
MATCH (a)-[x:AUTHORED]->(w:Work)-[v:INVOLVES]->(i:Institution {type: 'company'})
|
||||
WITH a, x, w, v, i ORDER BY w.year DESC LIMIT 200
|
||||
RETURN a, x, w, v, i
|
||||
```
|
||||
|
||||
### Author level (approximate, no `affiliations` phase needed)
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort {name: 'Daniel Erni'})-[c:CO_AUTHOR]-(b:Author)-[:AFFILIATED_WITH]->(i:Institution {type: 'company'})
|
||||
RETURN i.name AS company, i.country_code AS country, collect(DISTINCT b.name)[0..3] AS coauthors, sum(c.weight) AS joint_works
|
||||
ORDER BY joint_works DESC LIMIT 20
|
||||
```
|
||||
```cypher
|
||||
MATCH (a:Cohort {name: 'Daniel Erni'})-[c:CO_AUTHOR]-(b:Author)-[f:AFFILIATED_WITH]->(i:Institution {type: 'company'})
|
||||
RETURN a, c, b, f, i
|
||||
```
|
||||
|
||||
### Handelsregister links (founders and officers, not co-authorship)
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[r:OFFICER_OF]->(c:Company)
|
||||
RETURN a.name, c.name, c.registered_office, r.positions ORDER BY a.name LIMIT 50
|
||||
```
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[r:OFFICER_OF]->(c:Company) RETURN a, r, c LIMIT 200
|
||||
```
|
||||
|
||||
## Projects, funders, patents, news
|
||||
|
||||
Projects per source and link type:
|
||||
|
||||
```cypher
|
||||
MATCH (x)-[r:OUTPUT_OF|CONTRIBUTED_TO|DFG_ROLE|PARTICIPATES_IN]->(p:Project)
|
||||
RETURN p.source, type(r), count(r) ORDER BY p.source, count(r) DESC
|
||||
```
|
||||
|
||||
EU consortium partners of the university:
|
||||
|
||||
```cypher
|
||||
MATCH (:Institution {id: 'I62318514'})-[:PARTICIPATES_IN]->(p:Project)<-[:PARTICIPATES_IN]-(o:EuOrganization)
|
||||
WHERE o.name <> 'UNIVERSITAET DUISBURG-ESSEN'
|
||||
RETURN o.name, o.country, count(DISTINCT p) AS shared ORDER BY shared DESC LIMIT 20
|
||||
```
|
||||
|
||||
Funders of the cohort (author level):
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[r:FUNDED_BY]->(f:Funder)
|
||||
RETURN f.name, count(a) AS researchers, sum(r.publications) AS publications ORDER BY researchers DESC LIMIT 20
|
||||
```
|
||||
|
||||
Patents with their OpenAlex topics:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Author)-[:INVENTOR_OF]->(p:Patent)
|
||||
OPTIONAL MATCH (p)-[:HAS_TOPIC]->(t:Topic)
|
||||
RETURN a.name, p.source, p.year, left(p.title, 60), collect(t.name)[0..2] ORDER BY p.year DESC LIMIT 20
|
||||
```
|
||||
|
||||
News mentions with topics:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Cohort)-[m:MENTIONED_IN]->(n:NewsArticle) OPTIONAL MATCH (n)-[:HAS_TOPIC]->(t:Topic)
|
||||
RETURN a.name, n.title, n.date, m.ambiguous, collect(DISTINCT t.name)[0..3] ORDER BY n.date DESC LIMIT 20
|
||||
```
|
||||
|
||||
Work classifications (LLM):
|
||||
|
||||
```cypher
|
||||
MATCH (w:Work) WHERE w.primary_category IS NOT NULL
|
||||
RETURN w.primary_category, count(w) ORDER BY count(w) DESC
|
||||
```
|
||||
@@ -1,289 +0,0 @@
|
||||
# FalkorDB example: a researcher graph from the INSE sources
|
||||
|
||||
`load_graph.py` builds a small knowledge graph in [FalkorDB](https://www.falkordb.com/) around a
|
||||
couple of researchers from the predefined ("default") organizations in
|
||||
`src/data/predefined_accounts.json`, i.e. Universität Duisburg-Essen (`I62318514`),
|
||||
Ruhr-Universität Bochum (`I904495901`) and TU Dortmund (`I200332995`).
|
||||
|
||||
It does not talk to OpenAlex, EPO or CORDIS directly. Every fact comes from the backend's existing
|
||||
source logic in `src/main/inse`, which reads the INSE Elasticsearch mirrors, so the graph shows
|
||||
exactly what the REST API can already see:
|
||||
|
||||
| Source | Backend function | Graph |
|
||||
| --- | --- | --- |
|
||||
| OpenAlex authors (profile, ORCID, metrics, affiliations, topics) | `authors.v2.service.search_authors` / `get_author_by_id_strict_or_raise` | `Author`, `Institution`, `Topic`, `AFFILIATED_WITH`, `WORKS_ON` |
|
||||
| OpenAlex works incl. co-authors and their institutions | `works.v2.service.get_author_works` | `Work`, `AUTHORED`, `HAS_TOPIC`, co-author `Author`s |
|
||||
| CORDIS (EU) and DFG projects, bridged through publication DOIs | `works.logic.get_publication_dois_of_author`, `projects.projects_search_client.get_cordis_eu_project_ids_by_dois` / `get_dfg_project_ids_by_dois`, `get_enriched_cordis_project_by_id`, `get_dfg_project_by_id` | `Project`, `CONTRIBUTED_TO` |
|
||||
| EPO + USPTO patents (name matching with institution guard) | `patents.authors.logic.get_patents_by_author_id` | `Patent`, `INVENTOR_OF`, `HAS_TOPIC` |
|
||||
| Funders of the author's funded publications | `funders.logic.get_funders_by_author_id` | `Funder`, `FUNDED_BY` (author and work level) |
|
||||
| News mentions (UDE "aktuell", CC-News) | `news.logic.get_news_by_author` | `NewsArticle`, `MENTIONED_IN`, `HAS_TOPIC` |
|
||||
| Handelsregister officer matches | `company_connections.logic.get_company_connections_by_author_id` | `Company`, `OFFICER_OF` |
|
||||
| Predefined organizations | `src/data/predefined_accounts.json`, `institutions.v2.service.get_institution_by_id` | `Organization`, `REPRESENTS`, `MEMBER_OF` |
|
||||
|
||||
Co-authorship is not computed in Python. After loading, one Cypher query derives
|
||||
`(:Author)-[:CO_AUTHOR {weight, first_year, last_year}]->(:Author)` from the `AUTHORED` edges,
|
||||
which is the part the in-service collaboration-graph API currently leaves to the client.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
1. A FalkorDB server. The quickest way is the official image, which also serves a browser UI on
|
||||
port 3000:
|
||||
|
||||
```bash
|
||||
docker run -d --name falkordb -p 6379:6379 -p 3000:3000 falkordb/falkordb:latest
|
||||
```
|
||||
|
||||
2. The service image `inse-service:1.0.0` (built by `./gradlew :service:createImage`, and already
|
||||
present if you ever ran `./gradlew :service:serve`). The script imports the `inse` package, whose
|
||||
`util` module pulls in sentence-transformers/torch, so the image is the easiest runtime that has
|
||||
every dependency. `src/main/inse/.env` must contain the Elasticsearch credentials as usual.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd service
|
||||
scripts/falkordb/run.sh # 2 researchers per default organization
|
||||
scripts/falkordb/run.sh --reset --organization Duisburg --per-org 3
|
||||
scripts/falkordb/run.sh --author-id A5040796987 --author-id A5122994949 # explicit researchers, added incrementally
|
||||
scripts/falkordb/run.sh --no-write --dump /scripts/falkordb/graph.json # collect only, inspect the JSON
|
||||
scripts/falkordb/run.sh --help
|
||||
```
|
||||
|
||||
`run.sh` starts a throwaway container from the service image, mounts `src/main`, `src/data` and
|
||||
`scripts`, installs `falkordb` from `requirements.txt` and reaches the server on the host through
|
||||
`host.docker.internal`. Override the target with `FALKORDB_HOST`, `FALKORDB_PORT`,
|
||||
`FALKORDB_PASSWORD` and `FALKORDB_GRAPH` (default graph name `inse`).
|
||||
|
||||
Loads are idempotent: every node and edge is `MERGE`d on its `id`, so re-running or adding
|
||||
researchers with `--author-id` extends the same graph. `--reset` drops the graph right before
|
||||
writing, after all sources were collected. One failing source is logged and skipped, it does not
|
||||
abort the load.
|
||||
|
||||
A default run (six researchers, 40 works each) takes a few minutes and ends with roughly 2,300 nodes
|
||||
and 9,000 relationships. The slow parts are the DOI-to-project lookups (one detail query per hit)
|
||||
and the EPO/USPTO scans for common names.
|
||||
|
||||
### How the researchers are picked
|
||||
|
||||
For each organization the script reuses the backend's active-cohort membership query
|
||||
(`authors.institution_membership_query.build_institution_membership_query`, last known institution
|
||||
plus an affiliation since the current year minus two) and then narrows the candidates so the graph
|
||||
stays small and well disambiguated:
|
||||
|
||||
- `works_count` within `--min-works`/`--max-works` (default 20 to 300) to skip hyper-authorship
|
||||
profiles from large collaborations,
|
||||
- an ORCID unless `--no-require-orcid` is given,
|
||||
- every last known institution inside the organization's OpenAlex lineage, which drops merged
|
||||
profiles that also "currently" belong to unrelated institutions,
|
||||
- sorted by `works_count`, then `cited_by_count`.
|
||||
|
||||
Works with more than `--max-authors-per-work` authors (default 30) keep their `Work` node but only
|
||||
the seed researcher's own `AUTHORED` edge, so a single CERN paper cannot add a thousand co-authors.
|
||||
|
||||
## Schema
|
||||
|
||||
Node labels, all keyed by `id` (OpenAlex ids are stored without the `https://openalex.org/` prefix,
|
||||
patents as `<source>:<patent_id>`, projects as `cordis:<id>` / `dfg:<id>`):
|
||||
|
||||
| Label | Properties |
|
||||
| --- | --- |
|
||||
| `Organization` | `name`, `openalex_institution_id` |
|
||||
| `Institution` | `name`, `ror`, `country_code`, `type` |
|
||||
| `Author` | `name`, `orcid`, `works_count`, `cited_by_count`, `h_index`, `i10_index`, `seed` (true for the selected researchers, false for co-authors) |
|
||||
| `Work` | `title`, `year`, `type`, `language`, `cited_by_count`, `authors_count`, `hyperauthorship` |
|
||||
| `Topic` | `name`, `subfield`, `field`, `domain` |
|
||||
| `Project` | `source` (`cordis`/`dfg`), `source_id`, `title`, `acronym`, `start`, `end`, `funding_scheme`, `status`, `ec_max_contribution`, `url` |
|
||||
| `Patent` | `patent_id`, `source` (EPO/USPTO), `title`, `year`, `publication_date`, `kind`, `status`, `country`, `ipc[]`, `assignees[]`, `inventors[]` |
|
||||
| `Funder` | `name` |
|
||||
| `NewsArticle` | `title`, `date`, `url` |
|
||||
| `Company` | `name`, `status`, `registered_office`, `register` |
|
||||
|
||||
Relationships:
|
||||
|
||||
| Relationship | Properties |
|
||||
| --- | --- |
|
||||
| `(Organization)-[:REPRESENTS]->(Institution)` | |
|
||||
| `(Author)-[:MEMBER_OF]->(Organization)` | |
|
||||
| `(Author)-[:AFFILIATED_WITH]->(Institution)` | `years[]`, `last_known` (seed profiles only) |
|
||||
| `(Author)-[:WORKS_ON]->(Topic)` | `score` |
|
||||
| `(Author)-[:AUTHORED]->(Work)` | `position`, `corresponding` |
|
||||
| `(Author)-[:CO_AUTHOR]->(Author)` | `weight`, `first_year`, `last_year` (derived in FalkorDB, `a.id < b.id`) |
|
||||
| `(Work)-[:HAS_TOPIC]->(Topic)`, `(Patent)-[:HAS_TOPIC]->(Topic)`, `(NewsArticle)-[:HAS_TOPIC]->(Topic)` | `score` (works) |
|
||||
| `(Author)-[:CONTRIBUTED_TO]->(Project)` | `via` = `publication_doi` |
|
||||
| `(Author)-[:INVENTOR_OF]->(Patent)` | |
|
||||
| `(Author)-[:FUNDED_BY]->(Funder)` | `publications` |
|
||||
| `(Work)-[:FUNDED_BY]->(Funder)` | only for works that are in the graph |
|
||||
| `(Author)-[:MENTIONED_IN]->(NewsArticle)` | `matching` = `display_name` |
|
||||
| `(Author)-[:OFFICER_OF]->(Company)` | `positions[]`, `matching_method`, `common_name_warning` |
|
||||
|
||||
## Example queries
|
||||
|
||||
The queries for the whole-university graph `ude` are collected in [QUERIES.md](QUERIES.md).
|
||||
The ones below target the small `inse` example graph.
|
||||
|
||||
Paste these into the FalkorDB browser (http://localhost:3000, graph `inse`) or run them with the
|
||||
Python client (`FalkorDB(host="localhost").select_graph("inse").ro_query(...)`).
|
||||
|
||||
Everything around one researcher, for the visual explorer:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Author {seed: true})-[r]-(n) WHERE a.name STARTS WITH 'Nikolai' RETURN a, r, n LIMIT 200
|
||||
```
|
||||
|
||||
Seed researchers per organization with counts per source:
|
||||
|
||||
```cypher
|
||||
MATCH (o:Organization)<-[:MEMBER_OF]-(a:Author)
|
||||
OPTIONAL MATCH (a)-[:AUTHORED]->(w:Work)
|
||||
OPTIONAL MATCH (a)-[:CONTRIBUTED_TO]->(p:Project)
|
||||
OPTIONAL MATCH (a)-[:INVENTOR_OF]->(pt:Patent)
|
||||
OPTIONAL MATCH (a)-[:OFFICER_OF]->(c:Company)
|
||||
RETURN o.name, a.name, count(DISTINCT w) AS works, count(DISTINCT p) AS projects,
|
||||
count(DISTINCT pt) AS patents, count(DISTINCT c) AS companies
|
||||
ORDER BY o.name, a.name
|
||||
```
|
||||
|
||||
Strongest co-authors and where they sit:
|
||||
|
||||
```cypher
|
||||
MATCH (s:Author {seed: true})-[c:CO_AUTHOR]-(o:Author)-[:AFFILIATED_WITH]->(i:Institution)
|
||||
WITH s, o, c, collect(DISTINCT i.name) AS insts ORDER BY c.weight DESC
|
||||
RETURN s.name, collect(o.name + ' (' + toString(c.weight) + ') @ ' + insts[0])[0..5] AS top
|
||||
```
|
||||
|
||||
Topics shared by two of the selected researchers:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Author {seed: true})-[:WORKS_ON]->(t:Topic)<-[:WORKS_ON]-(b:Author {seed: true})
|
||||
WHERE a.id < b.id RETURN a.name, b.name, collect(t.name) AS topics
|
||||
```
|
||||
|
||||
Funders that several selected researchers share:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Author {seed: true})-[:FUNDED_BY]->(f:Funder)<-[:FUNDED_BY]-(b:Author {seed: true})
|
||||
WHERE a.id < b.id
|
||||
RETURN f.name, collect(DISTINCT a.name + ' & ' + b.name) AS pairs ORDER BY size(pairs) DESC LIMIT 5
|
||||
```
|
||||
|
||||
Projects per source and patents with their OpenAlex topics:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Author)-[:CONTRIBUTED_TO]->(p:Project) RETURN p.source, count(DISTINCT p), collect(DISTINCT a.name)
|
||||
```
|
||||
|
||||
```cypher
|
||||
MATCH (a:Author)-[:INVENTOR_OF]->(p:Patent)
|
||||
OPTIONAL MATCH (p)-[:HAS_TOPIC]->(t:Topic)
|
||||
RETURN a.name, p.source, p.year, left(p.title, 60), collect(t.name)[0..2] ORDER BY p.year DESC LIMIT 10
|
||||
```
|
||||
|
||||
Company links, showing which ones rest on a common name:
|
||||
|
||||
```cypher
|
||||
MATCH (a:Author)-[r:OFFICER_OF]->(c:Company)
|
||||
RETURN a.name, r.common_name_warning, count(c) AS companies, collect(c.name)[0..3] AS sample
|
||||
```
|
||||
|
||||
Cross-organization paths through up to two co-authorship hops:
|
||||
|
||||
```cypher
|
||||
MATCH path = (o1:Organization)<-[:MEMBER_OF]-(:Author)-[:CO_AUTHOR*1..2]-(:Author)-[:MEMBER_OF]->(o2:Organization)
|
||||
WHERE o1.name < o2.name RETURN o1.name, o2.name, count(path)
|
||||
```
|
||||
|
||||
## Whole-university graph: `bulk_load.py`
|
||||
|
||||
`load_graph.py` is the per-researcher example. `bulk_load.py` builds the graph for a whole
|
||||
organization by scanning each Elasticsearch source once and streaming into FalkorDB:
|
||||
|
||||
```bash
|
||||
scripts/falkordb/run.sh bulk --graph ude --reset # full UDE cohort, all phases
|
||||
scripts/falkordb/run.sh bulk --graph ude_test --reset --limit-authors 25 # smoke test, a few seconds
|
||||
scripts/falkordb/run.sh bulk --graph ude --phases projects derive # re-run selected phases (idempotent)
|
||||
```
|
||||
|
||||
Phases, in order (`--phases` selects a subset; later phases reload cohort and works from the graph):
|
||||
|
||||
| Phase | Source | Adds |
|
||||
| --- | --- | --- |
|
||||
| `cohort` | active researchers via `build_institution_membership_query` (last known institution + affiliation in the last two years) | `Author` with extra label `Cohort`, `MEMBER_OF`, `AFFILIATED_WITH {years, last_known}`, `WORKS_ON`, `Institution` lineage as `PART_OF` |
|
||||
| `works` | one `scan` of the works index for every work of every cohort researcher | `Work` (incl. `doi`, `is_oa`, `fwci`), every authorship as `AUTHORED`, co-author `Author`s, `AFFILIATED_WITH`, `HAS_TOPIC`, `Venue` + `PUBLISHED_IN`, `Funder` + `FUNDED_BY {awards}` |
|
||||
| `institutions` | `openalex-institutions` index | names, countries and types for institutions that only appeared as lineage ancestors |
|
||||
| `affiliations` | second, lighter scan of the works index | `AUTHORED.institution_ids` (institutions on that authorship) and `Work-[:INVOLVES {authors}]->Institution`, the per-work view that author-level `AFFILIATED_WITH` cannot give |
|
||||
| `classifications` | `work-classifications` index (LLM) | `Work.primary_category`, `pasteur_quadrant`, `applied_orientation_score`, `classification_confidence` |
|
||||
| `projects` | CORDIS publications and DFG project publications by DOI; CORDIS organisations and DFG institutes of the organization; DFG persons by ORCID; project details | `Project {source: cordis/dfg}`, `Work-[:OUTPUT_OF]->Project`, `Institution-[:PARTICIPATES_IN {role, ec_contribution}]->Project`, `Author-[:DFG_ROLE {role}]->Project`, `EuOrganization-[:PARTICIPATES_IN]->Project` (consortium partners) |
|
||||
| `patents` | `org_patents` index (pre-matched by `index_org_patents.py`) | `Patent`, `Author-[:INVENTOR_OF {match_type}]->Patent`, `HAS_TOPIC` |
|
||||
| `news` | `aktuell_postproc` author names matched exactly to cohort display names (the rule the news API uses), articles from `aktuell`, topics from `aktuell_openalex_topics` | `NewsArticle`, `MENTIONED_IN {ambiguous}`, `HAS_TOPIC {keyword}` |
|
||||
| `companies` | `get_company_connections_by_author_id` per researcher, 8 in parallel | `Company`, `OFFICER_OF`; common-name matches are only counted on the Author (`hr_company_matches`, `hr_common_name_warning`) unless `--include-ambiguous-companies` |
|
||||
| `hierarchy` | `get_topic_hierarchy()` | `Domain`, `Field`, `Subfield`, `IN_DOMAIN`, `IN_FIELD`, `IN_SUBFIELD` |
|
||||
| `derive` | Cypher inside FalkorDB | `CO_AUTHOR {weight, first_year, last_year}`, `Author-[:FUNDED_BY {publications}]->Funder`, `Author-[:CONTRIBUTED_TO {works}]->Project` for cohort members |
|
||||
| `profile` | aggregation over the cohort's works | `Institution-[:ACTIVE_IN {level, works, researchers}]->Topic/Subfield/Field/Domain`, the drawable research profile |
|
||||
|
||||
Co-author policy: every authorship is an `AUTHORED` edge, including 5,000-author collaboration
|
||||
papers. `CO_AUTHOR` pairs are derived for all author pairs on works with at most `--pair-cap`
|
||||
authors (default 30) and, on larger works, only for pairs that involve a cohort member. All pairs
|
||||
on the UDE cohort's works would be 2.9 billion edges; the anchored policy gives about 10 million.
|
||||
Edges always point from the smaller to the larger author id, so treat them as undirected.
|
||||
|
||||
Writes go through `GraphWriter`: rows are buffered per label / relationship type and flushed with
|
||||
`UNWIND ... MERGE` in batches of 2,000, node buffers before edge buffers. Cohort profiles use
|
||||
`SET`, co-author stubs use `ON CREATE SET`, so a researcher who is both keeps the full profile.
|
||||
One failing phase is logged and the next phase still runs. The script ends with `BGSAVE`.
|
||||
|
||||
### Result for Universität Duisburg-Essen (2026-09-15)
|
||||
|
||||
Cohort of 6,176 active researchers, every work of every cohort member, no author cap. The load
|
||||
ran in about 12 minutes of pipeline time (works scan 6.5 min, derive 100 s, everything else under
|
||||
a minute each); FalkorDB holds it in 1.04 GB and the RDB snapshot is 264 MB.
|
||||
|
||||
| Nodes | | Relationships | |
|
||||
| --- | --- | --- | --- |
|
||||
| Author | 693,487 (6,176 also `:Cohort`) | AUTHORED | 4,112,809 (2,376,034 with `institution_ids`) |
|
||||
| Work | 204,110 | CO_AUTHOR | 3,782,011 |
|
||||
| Institution | 26,246 | AFFILIATED_WITH / INVOLVES | 1,072,837 / 784,212 |
|
||||
| Venue | 16,534 | HAS_TOPIC | 571,906 |
|
||||
| Funder | 7,493 | FUNDED_BY (work + author level) | 229,219 |
|
||||
| EuOrganization | 5,469 | PUBLISHED_IN | 173,495 |
|
||||
| Topic | 4,516 | WORKS_ON | 27,255 |
|
||||
| NewsArticle | 4,402 | PARTICIPATES_IN | 17,046 |
|
||||
| Project | 3,664 | MENTIONED_IN | 11,251 |
|
||||
| Company | 547 | PART_OF | 11,045 |
|
||||
| Patent | 366 | OUTPUT_OF / CONTRIBUTED_TO | 8,292 / 6,723 |
|
||||
| Subfield / Field / Domain | 252 / 26 / 4 | OFFICER_OF / DFG_ROLE / INVENTOR_OF | 700 / 548 / 367 |
|
||||
| | | ACTIVE_IN (institution research profile) | 4,618 |
|
||||
|
||||
Source coverage of the cohort: all 6,176 have works, 1,741 are linked to projects, 1,925 are
|
||||
mentioned in news, 406 have unambiguous company links, 163 hold indexed patents, 164 were matched to
|
||||
DFG persons through their ORCID. 187,000 works carry an LLM classification.
|
||||
|
||||
Two server behaviours matter at this scale and are handled in the script: FalkorDB caps every
|
||||
result set at `RESULTSET_SIZE` rows (10,000 in the default container), so whole-graph reads are
|
||||
paged (`GraphWriter.ro_all`); and write queries ignore timeouts, which is why the co-author
|
||||
derivation computes pairs in Python and bulk-creates edges instead of running
|
||||
`MATCH ... MERGE` inside the graph (that took over a minute per 2,000 works).
|
||||
|
||||
|
||||
## Caveats worth knowing
|
||||
|
||||
- In the whole-university graph, common-name company matches are not written as edges by default
|
||||
(406 researchers have unambiguous links, the rest only carry `hr_company_matches`).
|
||||
- News and Handelsregister links are name matches, exactly as in the REST API. The `OFFICER_OF`
|
||||
edge carries `common_name_warning`; a researcher named Thomas Kaiser gets 92 companies with the
|
||||
flag set, Ahmet Karkar gets one without it.
|
||||
- Patents are matched by inventor name with the institution guard from `patents.authors.logic`;
|
||||
the backend logs `search_completeness=truncated_inconclusive` for common names.
|
||||
- The project bridge is DOI based: a researcher is linked to every CORDIS/DFG project that lists one
|
||||
of their publications, regardless of author position.
|
||||
- OpenAlex profiles can be merged across institutions. The lineage filter above avoids most of
|
||||
them for the automatic selection, `--author-id` takes whatever you give it.
|
||||
- `Author.topics` in the mirror carry a `score` where OpenAlex has a `count`; the value is stored
|
||||
as-is on `WORKS_ON`.
|
||||
|
||||
## Running without Docker
|
||||
|
||||
Create a Python 3.12 environment with the service dependencies (`pip install -e` is not set up, so
|
||||
install `fastapi httpx pydantic pydantic-settings sqlmodel python-dotenv pyyaml pyjwt openai pandas
|
||||
pypdf sentence-transformers torch` matching `pyproject.toml`) plus `falkordb`, then run
|
||||
`python scripts/falkordb/load_graph.py` from `service/`. The script locates `src/main/inse` and its
|
||||
`.env` relative to its own path.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,636 +0,0 @@
|
||||
"""
|
||||
load_graph.py — Minimal FalkorDB example for the INSE backend.
|
||||
|
||||
Builds a small knowledge graph around a couple of researchers from the predefined
|
||||
("default") organizations in src/data/predefined_accounts.json, using only the
|
||||
backend's existing data-source logic (everything reads the INSE Elasticsearch mirrors):
|
||||
|
||||
OpenAlex authors, works, topics, institutions -> inse.authors.v2 / inse.works.v2 / inse.institutions.v2
|
||||
EPO + USPTO patents -> inse.patents.authors.logic
|
||||
CORDIS (EU) + DFG projects, via publication DOIs -> inse.works.logic + inse.projects.*
|
||||
Funders of the author's funded publications -> inse.funders.logic
|
||||
News mentions (UDE "aktuell" + CC-News) -> inse.news.logic
|
||||
Handelsregister company officer matches -> inse.company_connections.logic
|
||||
|
||||
The collected nodes/edges are written to FalkorDB with batched UNWIND ... MERGE
|
||||
queries, and CO_AUTHOR edges are then derived inside the graph with one Cypher query.
|
||||
|
||||
Usage (see run.sh for running inside the service image):
|
||||
python scripts/falkordb/load_graph.py # 2 researchers per default org
|
||||
python scripts/falkordb/load_graph.py --organization "Duisburg" --per-org 3
|
||||
python scripts/falkordb/load_graph.py --author-id A5040796987 --author-id A5119657791
|
||||
python scripts/falkordb/load_graph.py --reset --dump /tmp/graph.json --skip news --skip companies
|
||||
|
||||
FalkorDB connection: --falkordb-host/--falkordb-port/--falkordb-password or the
|
||||
FALKORDB_HOST / FALKORDB_PORT / FALKORDB_PASSWORD environment variables.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# --- locate the backend package (works from the repo checkout and inside the service image) ---
|
||||
_current_dir = Path(__file__).resolve().parent
|
||||
_service_dir = _current_dir.parent.parent
|
||||
_src_main = _service_dir / "src" / "main"
|
||||
if not (_src_main / "inse").is_dir():
|
||||
_src_main = Path(os.environ.get("INSE_SRC_DIR", "/home"))
|
||||
sys.path.insert(0, str(_src_main))
|
||||
|
||||
from dotenv import load_dotenv # noqa: E402
|
||||
|
||||
_env_file = _src_main / "inse" / ".env"
|
||||
if _env_file.exists():
|
||||
load_dotenv(dotenv_path=_env_file)
|
||||
|
||||
# inse.config reads the .env at import time, so these imports must come after load_dotenv.
|
||||
from inse.authors.institution_membership_query import ( # noqa: E402
|
||||
build_institution_membership_query,
|
||||
current_affiliation_year_cutoff,
|
||||
)
|
||||
from inse.authors.v2.service import get_author_by_id_strict_or_raise, search_authors # noqa: E402
|
||||
from inse.company_connections.logic import get_company_connections_by_author_id # noqa: E402
|
||||
from inse.funders.logic import get_funders_by_author_id # noqa: E402
|
||||
from inse.institutions.v2.service import get_institution_by_id # noqa: E402
|
||||
from inse.models.openalex.author import Author # noqa: E402
|
||||
from inse.news.logic import get_news_by_author # noqa: E402
|
||||
from inse.patents.authors.logic import get_patents_by_author_id # noqa: E402
|
||||
from inse.projects.eu_cordis_projects_client import get_enriched_cordis_project_by_id # noqa: E402
|
||||
from inse.projects.projects_search_client import ( # noqa: E402
|
||||
get_cordis_eu_project_ids_by_dois,
|
||||
get_dfg_project_by_id,
|
||||
get_dfg_project_ids_by_dois,
|
||||
)
|
||||
from inse.works.logic import get_publication_dois_of_author # noqa: E402
|
||||
from inse.works.v2.service import get_author_works # noqa: E402
|
||||
|
||||
logger = logging.getLogger("falkordb.load_graph")
|
||||
|
||||
OPENALEX_PREFIX = "https://openalex.org/"
|
||||
PREDEFINED_ACCOUNTS = _src_main.parent / "data" / "predefined_accounts.json"
|
||||
SOURCES = ("works", "projects", "patents", "funders", "news", "companies")
|
||||
_IDENT = re.compile(r"^[A-Z][A-Za-z_]*$")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- helpers
|
||||
def short_id(raw: str | None) -> str | None:
|
||||
"""'https://openalex.org/A123' -> 'A123' (OpenAlex ids are stored as URLs in ES)."""
|
||||
if not raw:
|
||||
return None
|
||||
return raw.strip().removeprefix(OPENALEX_PREFIX)
|
||||
|
||||
|
||||
def raw_doi(doi: str) -> str:
|
||||
for prefix in ("https://doi.org/", "http://doi.org/", "http://dx.doi.org/"):
|
||||
if doi.startswith(prefix):
|
||||
return doi[len(prefix):]
|
||||
return doi
|
||||
|
||||
|
||||
def _scalar(value: Any) -> Any:
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.isoformat()
|
||||
if isinstance(value, str):
|
||||
return value[:2000]
|
||||
if isinstance(value, (bool, int, float)):
|
||||
return value
|
||||
return str(value)
|
||||
|
||||
|
||||
def clean_props(props: dict[str, Any]) -> dict[str, Any]:
|
||||
"""FalkorDB properties must be scalars or lists of scalars; drop None/dicts."""
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key, value in props.items():
|
||||
if value is None or isinstance(value, dict):
|
||||
continue
|
||||
if isinstance(value, (list, tuple, set)):
|
||||
cleaned[key] = [_scalar(v) for v in value if v is not None and not isinstance(v, dict)]
|
||||
else:
|
||||
cleaned[key] = _scalar(value)
|
||||
return cleaned
|
||||
|
||||
|
||||
@dataclass
|
||||
class GraphBatch:
|
||||
"""In-memory node/edge accumulator. First writer of a property wins, so seed
|
||||
authors (hydrated first) keep their full profile when they reappear as co-authors."""
|
||||
|
||||
nodes: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict)
|
||||
edges: dict[tuple[str, str, str, str, str], dict[str, Any]] = field(default_factory=dict)
|
||||
|
||||
def node(self, label: str, node_id: str | None, **props: Any) -> None:
|
||||
if not node_id:
|
||||
return
|
||||
props = clean_props(props)
|
||||
existing = self.nodes.setdefault((label, node_id), {})
|
||||
for key, value in props.items():
|
||||
existing.setdefault(key, value)
|
||||
|
||||
def edge(self, src_label: str, src: str | None, rel: str, dst_label: str, dst: str | None, **props: Any) -> None:
|
||||
if not src or not dst:
|
||||
return
|
||||
props = clean_props(props)
|
||||
existing = self.edges.setdefault((src_label, src, rel, dst_label, dst), {})
|
||||
for key, value in props.items():
|
||||
existing.setdefault(key, value)
|
||||
|
||||
def has_node(self, label: str, node_id: str | None) -> bool:
|
||||
return bool(node_id) and (label, node_id) in self.nodes
|
||||
|
||||
def summary(self) -> tuple[Counter, Counter]:
|
||||
return (
|
||||
Counter(label for label, _ in self.nodes),
|
||||
Counter(rel for _, _, rel, _, _ in self.edges),
|
||||
)
|
||||
|
||||
def to_json(self) -> dict[str, Any]:
|
||||
return {
|
||||
"nodes": [{"label": l, "id": i, "props": p} for (l, i), p in self.nodes.items()],
|
||||
"edges": [
|
||||
{"src_label": sl, "src": s, "rel": r, "dst_label": dl, "dst": d, "props": p}
|
||||
for (sl, s, r, dl, d), p in self.edges.items()
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def add_topic(batch: GraphBatch, topic: Any) -> str | None:
|
||||
"""Topic node from an OpenAlex WorkTopic-like object (works, authors, patents, news)."""
|
||||
tid = short_id(getattr(topic, "id", None))
|
||||
if not tid:
|
||||
return None
|
||||
subfield = getattr(topic, "subfield", None)
|
||||
field_ = getattr(topic, "var_field", None) or getattr(topic, "field", None)
|
||||
domain = getattr(topic, "domain", None)
|
||||
batch.node(
|
||||
"Topic",
|
||||
tid,
|
||||
name=getattr(topic, "display_name", None),
|
||||
subfield=getattr(subfield, "display_name", None),
|
||||
field=getattr(field_, "display_name", None),
|
||||
domain=getattr(domain, "display_name", None),
|
||||
)
|
||||
return tid
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- organizations
|
||||
def load_default_organizations() -> list[dict[str, str]]:
|
||||
"""The predefined organizations seeded at startup (auth.service.create_predefined_accounts)."""
|
||||
with open(PREDEFINED_ACCOUNTS, encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
return [
|
||||
{"name": org["name"], "institution_id": org["openalex_institution_id"]}
|
||||
for org in data.get("organizations", [])
|
||||
if org.get("openalex_institution_id")
|
||||
]
|
||||
|
||||
|
||||
def select_organizations(orgs: list[dict[str, str]], wanted: list[str]) -> list[dict[str, str]]:
|
||||
if not wanted:
|
||||
return orgs
|
||||
selected = []
|
||||
for term in wanted:
|
||||
term_l = term.lower()
|
||||
matches = [o for o in orgs if term_l in o["name"].lower() or term_l == o["institution_id"].lower()]
|
||||
if not matches:
|
||||
raise SystemExit(f"No default organization matches {term!r}. Known: {[o['name'] for o in orgs]}")
|
||||
selected.extend(m for m in matches if m not in selected)
|
||||
return selected
|
||||
|
||||
|
||||
async def ensure_organization_nodes(batch: GraphBatch, org: dict[str, str]) -> None:
|
||||
"""Organization (from predefined_accounts.json) + its OpenAlex institution."""
|
||||
if batch.has_node("Organization", org["name"]):
|
||||
return
|
||||
institution = await get_institution_by_id(org["institution_id"])
|
||||
batch.node("Organization", org["name"], name=org["name"], openalex_institution_id=org["institution_id"])
|
||||
batch.node(
|
||||
"Institution", org["institution_id"],
|
||||
name=getattr(institution, "display_name", None) or org["name"],
|
||||
ror=getattr(institution, "ror", None),
|
||||
country_code=getattr(institution, "country_code", None),
|
||||
type=str(institution.type) if getattr(institution, "type", None) else None,
|
||||
)
|
||||
batch.edge("Organization", org["name"], "REPRESENTS", "Institution", org["institution_id"])
|
||||
|
||||
|
||||
def organization_of(author: Author, orgs: list[dict[str, str]]) -> dict[str, str] | None:
|
||||
"""Default organization whose institution is among the author's last known institutions."""
|
||||
last_known = {short_id(i.id) for i in (author.last_known_institutions or []) if i.id}
|
||||
return next((org for org in orgs if org["institution_id"] in last_known), None)
|
||||
|
||||
|
||||
async def pick_seed_authors(
|
||||
institution_id: str, per_org: int, min_works: int, max_works: int, require_orcid: bool
|
||||
) -> list[Author]:
|
||||
"""Seed researchers of an institution.
|
||||
|
||||
Reuses the backend's active-cohort membership query (last known institution plus an
|
||||
affiliation since the current year minus two, the same rule the app uses for
|
||||
"currently belongs to institution"), then narrows the candidates so the example graph
|
||||
stays small and well disambiguated:
|
||||
* works_count within [min_works, max_works] -> skips hyper-authorship profiles
|
||||
* an ORCID (optional) -> better-disambiguated OpenAlex profiles
|
||||
* every last-known institution inside the institution's OpenAlex lineage
|
||||
-> drops merged profiles that also "currently" belong to unrelated institutions
|
||||
"""
|
||||
institution_url = f"{OPENALEX_PREFIX}{institution_id}"
|
||||
filters: list[dict[str, Any]] = [
|
||||
build_institution_membership_query(institution_id, year_mode="from", year=current_affiliation_year_cutoff()),
|
||||
{"range": {"works_count": {"gte": min_works, "lte": max_works}}},
|
||||
]
|
||||
if require_orcid:
|
||||
filters.append({"exists": {"field": "orcid"}})
|
||||
page = await search_authors(
|
||||
page=0,
|
||||
size=max(20, per_org * 20),
|
||||
query={"bool": {"filter": filters}},
|
||||
sort=[{"works_count": {"order": "desc"}}, {"cited_by_count": {"order": "desc"}}],
|
||||
)
|
||||
|
||||
def within_lineage(author: Author) -> bool:
|
||||
return all(
|
||||
inst.id == institution_url or institution_url in (inst.lineage or [])
|
||||
for inst in (author.last_known_institutions or [])
|
||||
)
|
||||
|
||||
return [author for author in page.elements if within_lineage(author)][:per_org]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- collectors
|
||||
def collect_author_profile(batch: GraphBatch, author: Author, org_name: str | None) -> str:
|
||||
aid = short_id(author.id)
|
||||
stats = author.summary_stats
|
||||
batch.node(
|
||||
"Author",
|
||||
aid,
|
||||
name=author.display_name,
|
||||
orcid=author.orcid,
|
||||
works_count=author.works_count,
|
||||
cited_by_count=author.cited_by_count,
|
||||
h_index=getattr(stats, "h_index", None),
|
||||
i10_index=getattr(stats, "i10_index", None),
|
||||
seed=True,
|
||||
)
|
||||
if org_name:
|
||||
batch.edge("Author", aid, "MEMBER_OF", "Organization", org_name)
|
||||
|
||||
last_known = {short_id(i.id) for i in (author.last_known_institutions or []) if i.id}
|
||||
for affiliation in author.affiliations or []:
|
||||
inst = affiliation.institution
|
||||
iid = short_id(inst.id) if inst else None
|
||||
if not iid:
|
||||
continue
|
||||
batch.node("Institution", iid, name=inst.display_name, country_code=inst.country_code, type=inst.type, ror=inst.ror)
|
||||
batch.edge(
|
||||
"Author", aid, "AFFILIATED_WITH", "Institution", iid,
|
||||
years=sorted(affiliation.years or []),
|
||||
last_known=iid in last_known,
|
||||
)
|
||||
for topic in author.topics or []:
|
||||
tid = add_topic(batch, topic)
|
||||
if tid:
|
||||
batch.edge("Author", aid, "WORKS_ON", "Topic", tid, score=getattr(topic, "score", None))
|
||||
return aid
|
||||
|
||||
|
||||
async def collect_works(batch: GraphBatch, aid: str, max_works: int, max_authors_per_work: int) -> int:
|
||||
page = await get_author_works(aid, page=0, size=max_works)
|
||||
for work in page.elements:
|
||||
wid = short_id(work.id)
|
||||
if not wid:
|
||||
continue
|
||||
authorships = work.authorships or []
|
||||
hyper = len(authorships) > max_authors_per_work
|
||||
batch.node(
|
||||
"Work", wid,
|
||||
title=work.title or work.display_name,
|
||||
year=work.publication_year,
|
||||
type=work.type,
|
||||
language=work.language,
|
||||
cited_by_count=work.cited_by_count,
|
||||
authors_count=len(authorships),
|
||||
hyperauthorship=hyper,
|
||||
)
|
||||
for topic in work.topics or []:
|
||||
tid = add_topic(batch, topic)
|
||||
if tid:
|
||||
batch.edge("Work", wid, "HAS_TOPIC", "Topic", tid, score=topic.score)
|
||||
for authorship in authorships:
|
||||
author = authorship.author
|
||||
cid = short_id(author.id) if author else None
|
||||
if not cid or (hyper and cid != aid):
|
||||
continue # for hyper-authorship works only keep the seed author's own edge
|
||||
batch.node("Author", cid, name=author.display_name, orcid=author.orcid, seed=False)
|
||||
batch.edge(
|
||||
"Author", cid, "AUTHORED", "Work", wid,
|
||||
position=authorship.author_position,
|
||||
corresponding=authorship.is_corresponding,
|
||||
)
|
||||
for inst in authorship.institutions or []:
|
||||
iid = short_id(inst.id)
|
||||
if iid:
|
||||
batch.node("Institution", iid, name=inst.display_name, country_code=inst.country_code, type=inst.type)
|
||||
batch.edge("Author", cid, "AFFILIATED_WITH", "Institution", iid)
|
||||
return len(page.elements)
|
||||
|
||||
|
||||
async def collect_projects(batch: GraphBatch, aid: str) -> int:
|
||||
"""Author -> project bridge used elsewhere in the backend: the author's publication DOIs
|
||||
are looked up in the CORDIS publication index and in the DFG projects' publication lists."""
|
||||
dois = await get_publication_dois_of_author(aid)
|
||||
if not dois:
|
||||
return 0
|
||||
doi_variants = sorted({v for d in dois for v in (d, raw_doi(d), raw_doi(d).lower())})
|
||||
cordis_ids = await get_cordis_eu_project_ids_by_dois(dois)
|
||||
dfg_ids = await get_dfg_project_ids_by_dois(doi_variants)
|
||||
|
||||
for pid in cordis_ids:
|
||||
node_id = f"cordis:{pid}"
|
||||
details = await get_enriched_cordis_project_by_id(str(pid))
|
||||
batch.node(
|
||||
"Project", node_id,
|
||||
source="cordis", source_id=str(pid),
|
||||
title=getattr(details, "title", None),
|
||||
acronym=getattr(details, "acronym", None),
|
||||
start=getattr(details, "start_date", None),
|
||||
end=getattr(details, "end_date", None),
|
||||
funding_scheme=getattr(details, "funding_scheme", None),
|
||||
status=getattr(details, "status", None),
|
||||
ec_max_contribution=getattr(details, "ec_max_contribution", None),
|
||||
)
|
||||
batch.edge("Author", aid, "CONTRIBUTED_TO", "Project", node_id, via="publication_doi")
|
||||
for pid in dfg_ids:
|
||||
node_id = f"dfg:{pid}"
|
||||
details = await get_dfg_project_by_id(str(pid))
|
||||
batch.node(
|
||||
"Project", node_id,
|
||||
source="dfg", source_id=str(pid),
|
||||
title=getattr(details, "title_en", None) or getattr(details, "title_de", None),
|
||||
start=getattr(details, "funding_start", None),
|
||||
end=getattr(details, "funding_end", None),
|
||||
funding_scheme=getattr(details, "funding_type_en", None) or getattr(details, "funding_type_de", None),
|
||||
url=getattr(details, "page_url", None) or getattr(details, "link", None),
|
||||
)
|
||||
batch.edge("Author", aid, "CONTRIBUTED_TO", "Project", node_id, via="publication_doi")
|
||||
return len(cordis_ids) + len(dfg_ids)
|
||||
|
||||
|
||||
async def collect_patents(batch: GraphBatch, aid: str) -> int:
|
||||
response = await get_patents_by_author_id(aid)
|
||||
for patent in response.patents:
|
||||
pid = f"{patent.source}:{patent.patent_id}"
|
||||
year = int(patent.publication_year) if patent.publication_year and patent.publication_year.isdigit() else None
|
||||
batch.node(
|
||||
"Patent", pid,
|
||||
patent_id=patent.patent_id, source=patent.source,
|
||||
title=patent.title or patent.title_en or patent.title_de,
|
||||
year=year, publication_date=patent.publication_date,
|
||||
kind=patent.kind, status=patent.status, country=patent.country,
|
||||
ipc=patent.ipc, assignees=patent.assignees, inventors=patent.inventors,
|
||||
)
|
||||
batch.edge("Author", aid, "INVENTOR_OF", "Patent", pid)
|
||||
for tag in patent.openalex_topics:
|
||||
tid = short_id(tag.topic_id)
|
||||
if tid:
|
||||
batch.node("Topic", tid, name=tag.topic_display_name, field=tag.field_name, domain=tag.domain_name)
|
||||
batch.edge("Patent", pid, "HAS_TOPIC", "Topic", tid)
|
||||
return response.patent_count
|
||||
|
||||
|
||||
async def collect_funders(batch: GraphBatch, aid: str) -> int:
|
||||
response = await get_funders_by_author_id(aid)
|
||||
for funder in response.funders:
|
||||
fid = short_id(funder.funder_id) or f"name:{funder.funder_name}"
|
||||
batch.node("Funder", fid, name=funder.funder_name)
|
||||
batch.edge("Author", aid, "FUNDED_BY", "Funder", fid, publications=funder.publication_count)
|
||||
ids = funder.publication_ids
|
||||
for wid_raw in ids.first + ids.middle + ids.last + ids.unknown:
|
||||
wid = short_id(wid_raw)
|
||||
if batch.has_node("Work", wid): # only link works we already loaded
|
||||
batch.edge("Work", wid, "FUNDED_BY", "Funder", fid)
|
||||
return response.funder_count
|
||||
|
||||
|
||||
async def collect_news(batch: GraphBatch, aid: str, max_news: int) -> int:
|
||||
page = await get_news_by_author(aid, page=1, page_size=max_news)
|
||||
for article in page.results:
|
||||
batch.node("NewsArticle", article.id, title=article.maintitle, date=article.date, url=article.url)
|
||||
batch.edge("Author", aid, "MENTIONED_IN", "NewsArticle", article.id, matching="display_name")
|
||||
for topic in article.topics or []:
|
||||
tid = short_id(topic.id)
|
||||
if tid:
|
||||
batch.node("Topic", tid, name=topic.display_name, subfield=topic.subfield_name, field=topic.field_name, domain=topic.domain_name)
|
||||
batch.edge("NewsArticle", article.id, "HAS_TOPIC", "Topic", tid)
|
||||
return page.total
|
||||
|
||||
|
||||
async def collect_companies(batch: GraphBatch, aid: str) -> int:
|
||||
response = await get_company_connections_by_author_id(aid)
|
||||
for company in response.connections:
|
||||
cid = company.company_number or company.native_company_number or f"name:{company.company_name}"
|
||||
batch.node(
|
||||
"Company", cid,
|
||||
name=company.company_name, status=company.company_status,
|
||||
registered_office=company.registered_office,
|
||||
register=" ".join(p for p in (company.register_art, company.register_nummer) if p) or None,
|
||||
)
|
||||
batch.edge(
|
||||
"Author", aid, "OFFICER_OF", "Company", cid,
|
||||
positions=[o.position for o in company.matched_officers if o.position],
|
||||
matching_method=response.matching_method,
|
||||
common_name_warning=response.common_name_warning,
|
||||
)
|
||||
return response.company_count
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- FalkorDB sink
|
||||
def _chunks(rows: list[dict[str, Any]], size: int):
|
||||
for start in range(0, len(rows), size):
|
||||
yield rows[start:start + size]
|
||||
|
||||
|
||||
def write_to_falkordb(batch: GraphBatch, args: argparse.Namespace) -> None:
|
||||
from falkordb import FalkorDB
|
||||
from redis.exceptions import ResponseError
|
||||
|
||||
db = FalkorDB(host=args.falkordb_host, port=args.falkordb_port, password=args.falkordb_password)
|
||||
if args.reset and args.graph in db.list_graphs():
|
||||
db.select_graph(args.graph).delete()
|
||||
logger.info("Deleted existing graph %r", args.graph)
|
||||
graph = db.select_graph(args.graph)
|
||||
|
||||
labels = sorted({label for label, _ in batch.nodes})
|
||||
for label in labels:
|
||||
try:
|
||||
graph.create_node_range_index(label, "id")
|
||||
except ResponseError as exc:
|
||||
if "already indexed" not in str(exc):
|
||||
raise
|
||||
|
||||
nodes_by_label: dict[str, list[dict[str, Any]]] = defaultdict(list)
|
||||
for (label, node_id), props in batch.nodes.items():
|
||||
nodes_by_label[label].append({"id": node_id, "props": props})
|
||||
for label, rows in nodes_by_label.items():
|
||||
assert _IDENT.match(label), label
|
||||
for chunk in _chunks(rows, args.batch_size):
|
||||
graph.query(f"UNWIND $rows AS r MERGE (n:{label} {{id: r.id}}) SET n += r.props", {"rows": chunk})
|
||||
|
||||
edges_by_type: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list)
|
||||
for (src_label, src, rel, dst_label, dst), props in batch.edges.items():
|
||||
edges_by_type[(src_label, rel, dst_label)].append({"src": src, "dst": dst, "props": props})
|
||||
for (src_label, rel, dst_label), rows in edges_by_type.items():
|
||||
assert _IDENT.match(src_label) and _IDENT.match(rel) and _IDENT.match(dst_label)
|
||||
for chunk in _chunks(rows, args.batch_size):
|
||||
graph.query(
|
||||
f"UNWIND $rows AS r "
|
||||
f"MATCH (a:{src_label} {{id: r.src}}), (b:{dst_label} {{id: r.dst}}) "
|
||||
f"MERGE (a)-[e:{rel}]->(b) SET e += r.props",
|
||||
{"rows": chunk},
|
||||
)
|
||||
|
||||
if not args.no_coauthor_edges:
|
||||
# Derive co-authorship inside the graph instead of in Python (this is the part the
|
||||
# in-service CollaborationGraph API currently leaves to the client).
|
||||
result = graph.query(
|
||||
"MATCH (a:Author)-[:AUTHORED]->(w:Work)<-[:AUTHORED]-(b:Author) "
|
||||
"WHERE a.id < b.id "
|
||||
"WITH a, b, count(DISTINCT w) AS n, min(w.year) AS first_year, max(w.year) AS last_year "
|
||||
"MERGE (a)-[c:CO_AUTHOR]->(b) "
|
||||
"SET c.weight = n, c.first_year = first_year, c.last_year = last_year"
|
||||
)
|
||||
logger.info("CO_AUTHOR edges created: %d", int(result.relationships_created or 0))
|
||||
|
||||
stats = graph.ro_query(
|
||||
"MATCH (n) WITH count(n) AS nodes MATCH ()-[r]->() RETURN nodes, count(r)"
|
||||
).result_set
|
||||
logger.info("Graph %r now holds %s nodes and %s relationships", args.graph, *stats[0])
|
||||
|
||||
seeds = graph.ro_query(
|
||||
"MATCH (s:Author {seed: true}) "
|
||||
"OPTIONAL MATCH (s)-[c:CO_AUTHOR]-(o:Author) "
|
||||
"WITH s, o, c ORDER BY c.weight DESC "
|
||||
"WITH s, collect(o.name + ' (' + toString(c.weight) + ')')[0..3] AS top "
|
||||
"RETURN s.id, s.name, top ORDER BY s.name"
|
||||
).result_set
|
||||
for row in seeds:
|
||||
logger.info(" %s %-32s strongest co-authors: %s", row[0], row[1], ", ".join(row[2]) or "-")
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- main
|
||||
async def run_source(name: str, coro, status: dict[str, str]) -> None:
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
count = await coro
|
||||
status[name] = f"{count} ({(time.perf_counter() - started) * 1000:.0f}ms)"
|
||||
except Exception as exc: # one failing source must not abort the whole load
|
||||
logger.warning("source %-9s failed: %s: %s", name, type(exc).__name__, exc)
|
||||
status[name] = "error"
|
||||
|
||||
|
||||
async def main(args: argparse.Namespace) -> None:
|
||||
batch = GraphBatch()
|
||||
skipped = set(args.skip)
|
||||
seeds: list[tuple[Author, str | None]] = []
|
||||
default_orgs = load_default_organizations()
|
||||
|
||||
if args.author_id:
|
||||
for raw in args.author_id:
|
||||
author = await get_author_by_id_strict_or_raise(short_id(raw))
|
||||
org = organization_of(author, default_orgs)
|
||||
if org:
|
||||
await ensure_organization_nodes(batch, org)
|
||||
seeds.append((author, org["name"] if org else None))
|
||||
else:
|
||||
for org in select_organizations(default_orgs, args.organization):
|
||||
await ensure_organization_nodes(batch, org)
|
||||
authors = await pick_seed_authors(
|
||||
org["institution_id"], args.per_org, args.min_works, args.max_works, args.require_orcid
|
||||
)
|
||||
logger.info("%s (%s): %s", org["name"], org["institution_id"], ", ".join(f"{a.display_name} [{short_id(a.id)}]" for a in authors) or "no authors found")
|
||||
seeds.extend((author, org["name"]) for author in authors)
|
||||
|
||||
if not seeds:
|
||||
raise SystemExit("No seed researchers selected.")
|
||||
|
||||
seed_ids = [collect_author_profile(batch, author, org_name) for author, org_name in seeds]
|
||||
|
||||
for (author, _), aid in zip(seeds, seed_ids):
|
||||
logger.info("Collecting sources for %s [%s] ...", author.display_name, aid)
|
||||
status: dict[str, str] = {}
|
||||
if "works" not in skipped:
|
||||
await run_source("works", collect_works(batch, aid, args.works, args.max_authors_per_work), status)
|
||||
if "projects" not in skipped:
|
||||
await run_source("projects", collect_projects(batch, aid), status)
|
||||
if "patents" not in skipped:
|
||||
await run_source("patents", collect_patents(batch, aid), status)
|
||||
if "funders" not in skipped:
|
||||
await run_source("funders", collect_funders(batch, aid), status)
|
||||
if "news" not in skipped:
|
||||
await run_source("news", collect_news(batch, aid, args.news), status)
|
||||
if "companies" not in skipped:
|
||||
await run_source("companies", collect_companies(batch, aid), status)
|
||||
logger.info(" %s", " ".join(f"{k}={v}" for k, v in status.items()))
|
||||
|
||||
node_counts, edge_counts = batch.summary()
|
||||
logger.info("Collected nodes: %s", dict(node_counts))
|
||||
logger.info("Collected edges: %s", dict(edge_counts))
|
||||
|
||||
if args.dump:
|
||||
Path(args.dump).write_text(json.dumps(batch.to_json(), ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
logger.info("Wrote %s", args.dump)
|
||||
|
||||
if args.no_write:
|
||||
return
|
||||
write_to_falkordb(batch, args)
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sel = parser.add_argument_group("researcher selection")
|
||||
sel.add_argument("--organization", action="append", default=[], metavar="NAME_OR_ID",
|
||||
help="restrict to default organization(s) by name substring or OpenAlex institution id (repeatable)")
|
||||
sel.add_argument("--per-org", type=int, default=2, help="seed researchers per organization (default 2)")
|
||||
sel.add_argument("--min-works", type=int, default=20, help="minimum works_count for seed selection")
|
||||
sel.add_argument("--max-works", type=int, default=300, help="maximum works_count for seed selection (skips hyper-authorship profiles)")
|
||||
sel.add_argument("--require-orcid", action=argparse.BooleanOptionalAction, default=True,
|
||||
help="only seed researchers with an ORCID (default on)")
|
||||
sel.add_argument("--author-id", action="append", default=[], metavar="OPENALEX_ID",
|
||||
help="explicit seed researcher(s), e.g. A5040796987 (repeatable; overrides organization selection)")
|
||||
src = parser.add_argument_group("sources")
|
||||
src.add_argument("--works", type=int, default=40, help="max works per researcher (default 40)")
|
||||
src.add_argument("--max-authors-per-work", type=int, default=30, help="skip co-author edges for works with more authors")
|
||||
src.add_argument("--news", type=int, default=20, help="max news articles per researcher")
|
||||
src.add_argument("--skip", action="append", default=[], choices=SOURCES, help="skip a source (repeatable)")
|
||||
out = parser.add_argument_group("output")
|
||||
out.add_argument("--falkordb-host", default=os.environ.get("FALKORDB_HOST", "localhost"))
|
||||
out.add_argument("--falkordb-port", type=int, default=int(os.environ.get("FALKORDB_PORT", "6379")))
|
||||
out.add_argument("--falkordb-password", default=os.environ.get("FALKORDB_PASSWORD") or None)
|
||||
out.add_argument("--graph", default=os.environ.get("FALKORDB_GRAPH", "inse"), help="graph name (default inse)")
|
||||
out.add_argument("--reset", action="store_true", help="delete the graph before loading")
|
||||
out.add_argument("--no-coauthor-edges", action="store_true", help="do not derive CO_AUTHOR edges")
|
||||
out.add_argument("--batch-size", type=int, default=500)
|
||||
out.add_argument("--dump", metavar="PATH", help="also write the collected nodes/edges as JSON")
|
||||
out.add_argument("--no-write", action="store_true", help="collect only (useful with --dump), do not touch FalkorDB")
|
||||
parser.add_argument("-v", "--verbose", action="store_true", help="show backend/httpx logs")
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cli_args = parse_args()
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
if not cli_args.verbose:
|
||||
# Some backend modules pin their own logger level, so filter at the handler instead.
|
||||
for handler in logging.getLogger().handlers:
|
||||
handler.addFilter(lambda record: record.levelno >= logging.WARNING or record.name.startswith("falkordb"))
|
||||
asyncio.run(main(cli_args))
|
||||
@@ -1,2 +0,0 @@
|
||||
# Extra dependency for scripts/falkordb on top of the service image / pyproject.
|
||||
falkordb~=1.7
|
||||
@@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Run load_graph.py inside the inse-service image, which already has every backend
|
||||
# dependency (torch/sentence-transformers included), and talk to FalkorDB on the host.
|
||||
#
|
||||
# scripts/falkordb/run.sh # 2 researchers per default organization
|
||||
# scripts/falkordb/run.sh --reset --organization Duisburg --per-org 3
|
||||
# scripts/falkordb/run.sh --author-id A5040796987 --author-id A5119657791
|
||||
# scripts/falkordb/run.sh bulk --graph ude --reset # whole-university graph (bulk_load.py)
|
||||
#
|
||||
# Env: INSE_IMAGE (default inse-service:1.0.0, built by ./gradlew :service:createImage),
|
||||
# FALKORDB_HOST (default host.docker.internal), FALKORDB_PORT, FALKORDB_PASSWORD, FALKORDB_GRAPH.
|
||||
set -euo pipefail
|
||||
|
||||
SERVICE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
# First argument "bulk" selects the whole-university loader (bulk_load.py); otherwise load_graph.py runs.
|
||||
SCRIPT="load_graph.py"
|
||||
if [ "${1:-}" = "bulk" ]; then SCRIPT="bulk_load.py"; shift; fi
|
||||
IMAGE="${INSE_IMAGE:-inse-service:1.0.0}"
|
||||
TTY_FLAGS=""
|
||||
if [ -t 0 ] && [ -t 1 ]; then TTY_FLAGS="-it"; fi
|
||||
# Match the image's platform (the Gradle build targets amd64), avoiding Docker's mismatch warning on arm64 hosts.
|
||||
PLATFORM="$(docker image inspect --format '{{.Os}}/{{.Architecture}}' "$IMAGE" 2>/dev/null || true)"
|
||||
PLATFORM_FLAGS=""
|
||||
if [ -n "$PLATFORM" ]; then PLATFORM_FLAGS="--platform $PLATFORM"; fi
|
||||
|
||||
exec docker run --rm $TTY_FLAGS $PLATFORM_FLAGS \
|
||||
-v "$SERVICE_DIR/src/main:/home" \
|
||||
-v "$SERVICE_DIR/src/data:/data" \
|
||||
-v "$SERVICE_DIR/scripts:/scripts" \
|
||||
-w /home \
|
||||
--add-host host.docker.internal:host-gateway \
|
||||
-e FALKORDB_HOST="${FALKORDB_HOST:-host.docker.internal}" \
|
||||
-e FALKORDB_PORT="${FALKORDB_PORT:-6379}" \
|
||||
-e FALKORDB_PASSWORD="${FALKORDB_PASSWORD:-}" \
|
||||
-e FALKORDB_GRAPH="${FALKORDB_GRAPH:-inse}" \
|
||||
-e PRINT_ES_QUERIES=false -e PRINT_ES_TIMINGS=false \
|
||||
-e HF_HUB_DISABLE_PROGRESS_BARS=1 -e TQDM_DISABLE=1 \
|
||||
--entrypoint sh "$IMAGE" -c \
|
||||
'pip install -q --root-user-action=ignore --disable-pip-version-check -r /scripts/falkordb/requirements.txt && exec python "/scripts/falkordb/$0" "$@"' \
|
||||
"$SCRIPT" "$@"
|
||||
@@ -18,4 +18,7 @@ RUN pip install --no-cache-dir -r requirements.txt
|
||||
# Copy the job code.
|
||||
COPY background-jobs/app/ ./
|
||||
|
||||
# Keyword extraction contract shared with the service (inse.news.logic).
|
||||
COPY service/src/main/inse/news/keyword_extraction.py ./keyword_extraction.py
|
||||
|
||||
COPY service/scripts/ ./service/scripts/
|
||||
|
||||
@@ -14,6 +14,9 @@ RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY background-jobs/app/ ./
|
||||
|
||||
# Keyword extraction contract shared with the service (inse.news.logic).
|
||||
COPY service/src/main/inse/news/keyword_extraction.py ./keyword_extraction.py
|
||||
|
||||
# Writes into docker-job_test, leaving production aktuell_postproc untouched.
|
||||
# A non-postproc target re-extracts entries that already have keywords (real
|
||||
# content) and updates them in place, keyed on news_id (re-runs overwrite, no
|
||||
|
||||
Binary file not shown.
@@ -1,406 +0,0 @@
|
||||
{
|
||||
"institution": "I62318514",
|
||||
"cohort": [
|
||||
"I62318514",
|
||||
"I4210119759",
|
||||
"I4210161917",
|
||||
"I127668822",
|
||||
"I4210090139",
|
||||
"I4210092428",
|
||||
"I4210110714",
|
||||
"I4210146441",
|
||||
"I4210154243"
|
||||
],
|
||||
"config_hash": "e56aa52d51c2",
|
||||
"counts": {
|
||||
"focal_authors_scored": 9474,
|
||||
"nodes": 864646,
|
||||
"edges": 5822006,
|
||||
"works_used": 228103,
|
||||
"works_capped": 9238,
|
||||
"tags": {
|
||||
"mentor": 161,
|
||||
"bridger": 133,
|
||||
"amplifier": 10
|
||||
},
|
||||
"suspicious_profiles": 400,
|
||||
"es_docs_written": 9474,
|
||||
"es_network_docs_written": 9474,
|
||||
"founding": {
|
||||
"in_population": 5712,
|
||||
"timing_applicable": 6118,
|
||||
"percentile_ge_90": 270,
|
||||
"with_patents": 152
|
||||
}
|
||||
},
|
||||
"timings": {
|
||||
"extract_s": 0.4,
|
||||
"load_cache_s": 33.3,
|
||||
"founding_features_s": 2.6,
|
||||
"build_graph_s": 74.6,
|
||||
"metrics_s": 363.1,
|
||||
"signals_s": 369.1,
|
||||
"founding_s": 4.5,
|
||||
"scoring_s": 0.1,
|
||||
"index_s": 11.2,
|
||||
"network_s": 93.6
|
||||
},
|
||||
"top_bridgers": [
|
||||
{
|
||||
"author_id": "A5113304257",
|
||||
"name": "Jan Egger",
|
||||
"score": 0.9533,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5051904885",
|
||||
"name": "Feyza Cansiz",
|
||||
"score": 0.9436,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5015256836",
|
||||
"name": "Giebel Bernd",
|
||||
"score": 0.9403,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5029568311",
|
||||
"name": "S. Ugurel-Becker",
|
||||
"score": 0.9395,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5039473892",
|
||||
"name": "D. Schadendorf",
|
||||
"score": 0.9329,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5098748894",
|
||||
"name": "Bahadır Eryılmaz",
|
||||
"score": 0.927,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5120610796",
|
||||
"name": "Ulrich Sure",
|
||||
"score": 0.9263,
|
||||
"bucket": "Early",
|
||||
"active_years": 2,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5007940140",
|
||||
"name": "Amin Dada",
|
||||
"score": 0.9262,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5101839832",
|
||||
"name": "Mohammed-Ali Sheikh",
|
||||
"score": 0.9243,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5074268016",
|
||||
"name": "Anika Grüneboom",
|
||||
"score": 0.922,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 9,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_mentors": [
|
||||
{
|
||||
"author_id": "A5043495754",
|
||||
"name": "Cornelius Deuschl",
|
||||
"score": 0.9613,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5030635588",
|
||||
"name": "Birte Möhlendick",
|
||||
"score": 0.9582,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5029722705",
|
||||
"name": "Freya Droege",
|
||||
"score": 0.95,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5062907808",
|
||||
"name": "Wolfgang P. Fendler",
|
||||
"score": 0.9437,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5048453026",
|
||||
"name": "Alpaslan Tasdogan",
|
||||
"score": 0.9436,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5063064952",
|
||||
"name": "Nora Bruns",
|
||||
"score": 0.9408,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5036496827",
|
||||
"name": "Ramazan Jabbarli",
|
||||
"score": 0.9336,
|
||||
"bucket": "Established",
|
||||
"active_years": 13,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5041276010",
|
||||
"name": "Heiko Wende",
|
||||
"score": 0.9291,
|
||||
"bucket": "Senior",
|
||||
"active_years": 31,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5110823011",
|
||||
"name": "Dagmar Führer",
|
||||
"score": 0.9285,
|
||||
"bucket": "Senior",
|
||||
"active_years": 32,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5047137012",
|
||||
"name": "David Kersting",
|
||||
"score": 0.9284,
|
||||
"bucket": "Established",
|
||||
"active_years": 12,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_amplifiers": [
|
||||
{
|
||||
"author_id": "A5007801159",
|
||||
"name": "Jens Wiltfang",
|
||||
"score": 0.9282,
|
||||
"bucket": "Senior",
|
||||
"active_years": 35,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5049577078",
|
||||
"name": "Stefan Kleine",
|
||||
"score": 0.9121,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5055188384",
|
||||
"name": "Benjamin Zingsem",
|
||||
"score": 0.8991,
|
||||
"bucket": "Established",
|
||||
"active_years": 10,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5036507802",
|
||||
"name": "Martin Schüler",
|
||||
"score": 0.8934,
|
||||
"bucket": "Senior",
|
||||
"active_years": 47,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5123934012",
|
||||
"name": "Karl Sebastian Lang",
|
||||
"score": 0.8883,
|
||||
"bucket": "Early",
|
||||
"active_years": 1,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5016532166",
|
||||
"name": "Adalbert Krawczyk",
|
||||
"score": 0.8779,
|
||||
"bucket": "Senior",
|
||||
"active_years": 16,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5052587248",
|
||||
"name": "Gabi Schierning",
|
||||
"score": 0.8751,
|
||||
"bucket": "Senior",
|
||||
"active_years": 23,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5024191146",
|
||||
"name": "Markus Kaiser",
|
||||
"score": 0.868,
|
||||
"bucket": "Senior",
|
||||
"active_years": 30,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5044921528",
|
||||
"name": "Annette Paschen",
|
||||
"score": 0.862,
|
||||
"bucket": "Senior",
|
||||
"active_years": 29,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5107541231",
|
||||
"name": "Raimund Erbel",
|
||||
"score": 0.8519,
|
||||
"bucket": "Senior",
|
||||
"active_years": 52,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_founder_potential": [
|
||||
{
|
||||
"author_id": "A5039812973",
|
||||
"name": "Hamza Kalisch",
|
||||
"percentile": 99.9,
|
||||
"probability_raw": 0.9974,
|
||||
"p_within_3y_percentile": 99.6,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5084716913",
|
||||
"name": "N Blase",
|
||||
"percentile": 99.9,
|
||||
"probability_raw": 0.9975,
|
||||
"p_within_3y_percentile": 99.7,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5102237308",
|
||||
"name": "Kelsey Hermann",
|
||||
"percentile": 99.9,
|
||||
"probability_raw": 0.9985,
|
||||
"p_within_3y_percentile": 100.0,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5031388574",
|
||||
"name": "HH-J Schmidt",
|
||||
"percentile": 99.9,
|
||||
"probability_raw": 0.9982,
|
||||
"p_within_3y_percentile": 99.9,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5063433003",
|
||||
"name": "H. H. Schmidt",
|
||||
"percentile": 99.9,
|
||||
"probability_raw": 0.9978,
|
||||
"p_within_3y_percentile": 99.8,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5082880950",
|
||||
"name": "Fabian Haut",
|
||||
"percentile": 99.9,
|
||||
"probability_raw": 0.9975,
|
||||
"p_within_3y_percentile": 99.3,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5000155431",
|
||||
"name": "K Herrmann",
|
||||
"percentile": 99.9,
|
||||
"probability_raw": 0.9978,
|
||||
"p_within_3y_percentile": 99.9,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5069143867",
|
||||
"name": "Michael Dominic Harr",
|
||||
"percentile": 99.8,
|
||||
"probability_raw": 0.9969,
|
||||
"p_within_3y_percentile": 99.8,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5090109295",
|
||||
"name": "Johannes Neuhaus",
|
||||
"percentile": 99.8,
|
||||
"probability_raw": 0.9965,
|
||||
"p_within_3y_percentile": 99.9,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
},
|
||||
{
|
||||
"author_id": "A5087082783",
|
||||
"name": "Christopher J. Rastin",
|
||||
"percentile": 99.8,
|
||||
"probability_raw": 0.9965,
|
||||
"p_within_3y_percentile": 99.5,
|
||||
"publications": 4,
|
||||
"patents": 0,
|
||||
"bucket": "Early",
|
||||
"tags": []
|
||||
}
|
||||
]
|
||||
}
|
||||
-269
@@ -1,269 +0,0 @@
|
||||
{
|
||||
"institution": "I62318514",
|
||||
"config_hash": "a49ddd388990",
|
||||
"counts": {
|
||||
"focal_authors_scored": 4921,
|
||||
"nodes": 639544,
|
||||
"edges": 4143499,
|
||||
"works_used": 160396,
|
||||
"works_capped": 4823,
|
||||
"tags": {
|
||||
"amplifier": 609,
|
||||
"mentor": 91,
|
||||
"bridger": 66
|
||||
},
|
||||
"suspicious_profiles": 225
|
||||
},
|
||||
"timings": {
|
||||
"load_cache_s": 15.2,
|
||||
"build_graph_s": 31.3,
|
||||
"metrics_s": 112.2,
|
||||
"scoring_s": 0.0
|
||||
},
|
||||
"top_bridgers": [
|
||||
{
|
||||
"author_id": "A5113304257",
|
||||
"name": "Jan Egger",
|
||||
"score": 0.9488,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5015256836",
|
||||
"name": "Giebel Bernd",
|
||||
"score": 0.9379,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5074268016",
|
||||
"name": "Anika Grüneboom",
|
||||
"score": 0.9277,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 9,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5101839832",
|
||||
"name": "Mohammed-Ali Sheikh",
|
||||
"score": 0.9227,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5093725590",
|
||||
"name": "Ahammed Suhail Odungat",
|
||||
"score": 0.9178,
|
||||
"bucket": "Early",
|
||||
"active_years": 3,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5123321088",
|
||||
"name": "Heiko Wende",
|
||||
"score": 0.9166,
|
||||
"bucket": "Early",
|
||||
"active_years": 2,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5093128319",
|
||||
"name": "Pascal Raszke",
|
||||
"score": 0.9115,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5009410023",
|
||||
"name": "Yossarian Liebsch",
|
||||
"score": 0.9098,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5038988072",
|
||||
"name": "Ulrike Schara‐Schmidt",
|
||||
"score": 0.9095,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5092634227",
|
||||
"name": "Abdelrahman Elwy",
|
||||
"score": 0.9089,
|
||||
"bucket": "Early",
|
||||
"active_years": 4,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_mentors": [
|
||||
{
|
||||
"author_id": "A5043495754",
|
||||
"name": "Cornelius Deuschl",
|
||||
"score": 0.9533,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5063064952",
|
||||
"name": "Nora Bruns",
|
||||
"score": 0.9508,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5062907808",
|
||||
"name": "Wolfgang P. Fendler",
|
||||
"score": 0.9477,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5016126468",
|
||||
"name": "Jassin Rashidi‐Alavijeh",
|
||||
"score": 0.9338,
|
||||
"bucket": "Established",
|
||||
"active_years": 13,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5041276010",
|
||||
"name": "Heiko Wende",
|
||||
"score": 0.9314,
|
||||
"bucket": "Senior",
|
||||
"active_years": 31,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5036496827",
|
||||
"name": "Ramazan Jabbarli",
|
||||
"score": 0.9271,
|
||||
"bucket": "Established",
|
||||
"active_years": 13,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5090806187",
|
||||
"name": "Ivana Kraiselburd",
|
||||
"score": 0.9262,
|
||||
"bucket": "Established",
|
||||
"active_years": 12,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5030635588",
|
||||
"name": "Birte Möhlendick",
|
||||
"score": 0.9244,
|
||||
"bucket": "Established",
|
||||
"active_years": 14,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5052523213",
|
||||
"name": "Ulrich Sure",
|
||||
"score": 0.9229,
|
||||
"bucket": "Senior",
|
||||
"active_years": 32,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5016243200",
|
||||
"name": "Ulf Dittmer",
|
||||
"score": 0.9209,
|
||||
"bucket": "Senior",
|
||||
"active_years": 34,
|
||||
"suspicious": false
|
||||
}
|
||||
],
|
||||
"top_amplifiers": [
|
||||
{
|
||||
"author_id": "A5001941348",
|
||||
"name": "Matthias Rinke",
|
||||
"score": 1.0,
|
||||
"bucket": "Senior",
|
||||
"active_years": 25,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5026928109",
|
||||
"name": "Nicole Stracke",
|
||||
"score": 1.0,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5072469617",
|
||||
"name": "Stefan Esser",
|
||||
"score": 1.0,
|
||||
"bucket": "Established",
|
||||
"active_years": 10,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5045156629",
|
||||
"name": "Mirrasoul J. Mousavi",
|
||||
"score": 0.9991,
|
||||
"bucket": "Senior",
|
||||
"active_years": 20,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5102956234",
|
||||
"name": "Tanja Trarbach",
|
||||
"score": 0.9988,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 6,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5108819622",
|
||||
"name": "Andreas Roos",
|
||||
"score": 0.9982,
|
||||
"bucket": "Senior",
|
||||
"active_years": 15,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5060245622",
|
||||
"name": "Heidi Wiehler",
|
||||
"score": 0.9978,
|
||||
"bucket": "Established",
|
||||
"active_years": 12,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5005113935",
|
||||
"name": "C. L. Munch",
|
||||
"score": 0.9977,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 7,
|
||||
"suspicious": true
|
||||
},
|
||||
{
|
||||
"author_id": "A5014449031",
|
||||
"name": "Boris S. Kerner",
|
||||
"score": 0.9973,
|
||||
"bucket": "Senior",
|
||||
"active_years": 51,
|
||||
"suspicious": false
|
||||
},
|
||||
{
|
||||
"author_id": "A5034381567",
|
||||
"name": "Yannick Beckmann",
|
||||
"score": 0.9965,
|
||||
"bucket": "Emerging",
|
||||
"active_years": 9,
|
||||
"suspicious": false
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
Cohort (9 institutions, affiliation years >= 2023):
|
||||
I62318514 University of Duisburg-Essen
|
||||
I4210119759 Essen University Hospital
|
||||
I4210161917 West German Heart and Vascular Center Essen
|
||||
I127668822 Erwin L. Hahn Institute for Magnetic Resonance Imaging
|
||||
I4210090139 Rhein-Ruhr Institut für Sozialforschung und Politikberatung
|
||||
I4210092428 Deutsches Textilforschungszentrum Nord-West
|
||||
I4210110714 Institute for Advanced Study in the Humanities Essen
|
||||
I4210146441 The Hydrogen and Fuel Cell Center
|
||||
I4210154243 Institut für Energie- und Umwelttechnik
|
||||
Reusing cached extract (use --force-extract to refresh).
|
||||
Loaded 267467 works, 9475 focal authors (19.0s)
|
||||
Graph: 864646 nodes, 5822006 edges, 228103 works used, 9238 capped, ref_year=2026 (46.6s)
|
||||
Metrics for 9474 focal authors (326.0s)
|
||||
Signals: patents scored for 55 authors (name-only evidence: 17), news mentions for 1369 (ambiguous names skipped: 839), CORDIS projects for 1342
|
||||
Signal joins done (522.1s)
|
||||
Scores -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/scores_I62318514.jsonl.gz (0.1s)
|
||||
Deleted 9474 existing docs for I62318514
|
||||
Indexed 9474 docs into multiplicators_v1 (count for I62318514: 9474) (46.8s)
|
||||
{
|
||||
"focal_authors_scored": 9474,
|
||||
"nodes": 864646,
|
||||
"edges": 5822006,
|
||||
"works_used": 228103,
|
||||
"works_capped": 9238,
|
||||
"tags": {
|
||||
"mentor": 161,
|
||||
"bridger": 133,
|
||||
"amplifier": 10
|
||||
},
|
||||
"suspicious_profiles": 400,
|
||||
"es_docs_written": 9474
|
||||
}
|
||||
Summary -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/build_summary_I62318514.json
|
||||
@@ -1,37 +0,0 @@
|
||||
Cohort (9 institutions, affiliation years >= 2023):
|
||||
I62318514 University of Duisburg-Essen
|
||||
I4210119759 Essen University Hospital
|
||||
I4210161917 West German Heart and Vascular Center Essen
|
||||
I127668822 Erwin L. Hahn Institute for Magnetic Resonance Imaging
|
||||
I4210090139 Rhein-Ruhr Institut für Sozialforschung und Politikberatung
|
||||
I4210092428 Deutsches Textilforschungszentrum Nord-West
|
||||
I4210110714 Institute for Advanced Study in the Humanities Essen
|
||||
I4210146441 The Hydrogen and Fuel Cell Center
|
||||
I4210154243 Institut für Energie- und Umwelttechnik
|
||||
Reusing cached extract (use --force-extract to refresh).
|
||||
Loaded 267467 works, 9475 focal authors (18.8s)
|
||||
Graph: 864646 nodes, 5822006 edges, 228103 works used, 9238 capped, ref_year=2026 (45.0s)
|
||||
Metrics for 9474 focal authors (319.0s)
|
||||
Signals: patents scored for 55 authors (name-only evidence: 17), news mentions for 1369 (ambiguous names skipped: 839), CORDIS projects for 1342
|
||||
Signal joins done (389.7s)
|
||||
Scores -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/scores_I62318514.jsonl.gz (0.1s)
|
||||
Deleted 9474 existing docs for I62318514
|
||||
Indexed 9474 docs into multiplicators_v1 (count for I62318514: 9474) (11.4s)
|
||||
Deleted 0 existing docs for I62318514
|
||||
Indexed 9474 network docs into multiplicator_networks_v1 (92.7s)
|
||||
{
|
||||
"focal_authors_scored": 9474,
|
||||
"nodes": 864646,
|
||||
"edges": 5822006,
|
||||
"works_used": 228103,
|
||||
"works_capped": 9238,
|
||||
"tags": {
|
||||
"mentor": 161,
|
||||
"bridger": 133,
|
||||
"amplifier": 10
|
||||
},
|
||||
"suspicious_profiles": 400,
|
||||
"es_docs_written": 9474,
|
||||
"es_network_docs_written": 9474
|
||||
}
|
||||
Summary -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/build_summary_I62318514.json
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,99 +0,0 @@
|
||||
{
|
||||
"institution": {
|
||||
"id": "https://openalex.org/I62318514",
|
||||
"short_id": "I62318514",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
"cohort": [
|
||||
{
|
||||
"id": "I62318514",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
{
|
||||
"id": "I4210119759",
|
||||
"display_name": "Essen University Hospital"
|
||||
},
|
||||
{
|
||||
"id": "I4210161917",
|
||||
"display_name": "West German Heart and Vascular Center Essen"
|
||||
},
|
||||
{
|
||||
"id": "I127668822",
|
||||
"display_name": "Erwin L. Hahn Institute for Magnetic Resonance Imaging"
|
||||
},
|
||||
{
|
||||
"id": "I4210090139",
|
||||
"display_name": "Rhein-Ruhr Institut für Sozialforschung und Politikberatung"
|
||||
},
|
||||
{
|
||||
"id": "I4210092428",
|
||||
"display_name": "Deutsches Textilforschungszentrum Nord-West"
|
||||
},
|
||||
{
|
||||
"id": "I4210110714",
|
||||
"display_name": "Institute for Advanced Study in the Humanities Essen"
|
||||
},
|
||||
{
|
||||
"id": "I4210146441",
|
||||
"display_name": "The Hydrogen and Fuel Cell Center"
|
||||
},
|
||||
{
|
||||
"id": "I4210154243",
|
||||
"display_name": "Institut für Energie- und Umwelttechnik"
|
||||
}
|
||||
],
|
||||
"reproduction": {
|
||||
"author_count": 6583,
|
||||
"work_count": 221603,
|
||||
"group_breakdown": {
|
||||
"backend_compatible": 6360,
|
||||
"empty_last_known_recent": 223
|
||||
}
|
||||
},
|
||||
"field_coverage": {
|
||||
"authorships_total": 4365638,
|
||||
"author_position_pct": 100.0,
|
||||
"is_corresponding_pct": 100.0,
|
||||
"institutions_total": 3934359,
|
||||
"institution_type_pct": 99.9,
|
||||
"company_institutions": 82976
|
||||
},
|
||||
"scale": {
|
||||
"works": 221603,
|
||||
"authors_per_work": {
|
||||
"p50": 5,
|
||||
"p90": 18,
|
||||
"p99": 174,
|
||||
"max": 4839
|
||||
},
|
||||
"hyperauthorship_works_gt_100": 3179,
|
||||
"pair_instances_at_cap": {
|
||||
"20": 4921446,
|
||||
"50": 10209552,
|
||||
"100": 17642513
|
||||
}
|
||||
},
|
||||
"career_quality": {
|
||||
"authors_with_works": 6583,
|
||||
"suspicious_profile_count": 302,
|
||||
"suspicious_profile_pct": 4.59,
|
||||
"active_years": {
|
||||
"p50": 4,
|
||||
"p90": 24,
|
||||
"max": 63,
|
||||
"mean": 8.61
|
||||
}
|
||||
},
|
||||
"signals": {
|
||||
"org_patents_for_institution": 462,
|
||||
"match_type_breakdown": {
|
||||
"name": 339,
|
||||
"both": 65,
|
||||
"institution": 58
|
||||
}
|
||||
},
|
||||
"permissions": {
|
||||
"skipped": "pass --probe-writes to test index create/bulk/delete"
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
{
|
||||
"institution": {
|
||||
"id": "https://openalex.org/I62318514",
|
||||
"short_id": "I62318514",
|
||||
"ror": "https://ror.org/04mz5ra38",
|
||||
"display_name": "University of Duisburg-Essen"
|
||||
},
|
||||
"reproduction": {
|
||||
"author_count": 4921,
|
||||
"work_count": 183661,
|
||||
"group_breakdown": {
|
||||
"backend_compatible": 4740,
|
||||
"empty_last_known_recent": 181
|
||||
}
|
||||
},
|
||||
"field_coverage": {
|
||||
"authorships_total": 3805507,
|
||||
"author_position_pct": 100.0,
|
||||
"is_corresponding_pct": 100.0,
|
||||
"institutions_total": 3482939,
|
||||
"institution_type_pct": 99.91,
|
||||
"company_institutions": 67131
|
||||
},
|
||||
"scale": {
|
||||
"works": 183661,
|
||||
"authors_per_work": {
|
||||
"p50": 5,
|
||||
"p90": 17,
|
||||
"p99": 144,
|
||||
"max": 4839
|
||||
},
|
||||
"hyperauthorship_works_gt_100": 2459,
|
||||
"pair_instances_at_cap": {
|
||||
"20": 3912695,
|
||||
"50": 7962611,
|
||||
"100": 13897380
|
||||
}
|
||||
},
|
||||
"career_quality": {
|
||||
"authors_with_works": 4921,
|
||||
"suspicious_profile_count": 225,
|
||||
"suspicious_profile_pct": 4.57,
|
||||
"active_years": {
|
||||
"p50": 4,
|
||||
"p90": 25,
|
||||
"max": 60,
|
||||
"mean": 8.94
|
||||
}
|
||||
},
|
||||
"signals": {
|
||||
"org_patents_for_institution": 436,
|
||||
"match_type_breakdown": {
|
||||
"name": 313,
|
||||
"both": 65,
|
||||
"institution": 58
|
||||
}
|
||||
},
|
||||
"permissions": {
|
||||
"create_index": 403
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
Sample: 60 people, matched in scores: 51, missing: 9
|
||||
MISSING: Peter Bayer (A5060566345)
|
||||
MISSING: Richard Kosinski (A5014403509)
|
||||
MISSING: Alexandra Dmitrienko (A5042835341)
|
||||
MISSING: Wilhelm Koop (A5019228221)
|
||||
MISSING: Venkata Marella (A5082156768)
|
||||
MISSING: Miriam Böhm (A5037448457)
|
||||
MISSING: Katrin Schuldt (A5002003996)
|
||||
MISSING: Friedrich Scheller (A5072565080)
|
||||
MISSING: Lara Altenstädter (A5070117981)
|
||||
|
||||
=== mentor sub-score by known status ===
|
||||
Professor n=29 median=0.740 mean=0.691 range=[0.153, 0.921]
|
||||
Researcher n=22 median=0.494 mean=0.514 range=[0.242, 0.958]
|
||||
|
||||
=== bridger sub-score by known status ===
|
||||
Professor n=29 median=0.629 mean=0.618 range=[0.291, 0.856]
|
||||
Researcher n=22 median=0.469 mean=0.509 range=[0.224, 0.796]
|
||||
|
||||
=== amplifier sub-score by known status ===
|
||||
Professor n=29 median=0.612 mean=0.584 range=[0.357, 0.840]
|
||||
Researcher n=22 median=0.450 mean=0.529 range=[0.363, 0.772]
|
||||
|
||||
M1 exit check — professors' median mentor score (0.74) > researchers' (0.494): PASS
|
||||
|
||||
=== per-person (sorted by mentor score) ===
|
||||
0.958 Researcher Established juniors= 30 laj= 6 Birte Möhlendick (Medicine)
|
||||
0.921 Professor Senior juniors=110 laj= 11 Oliver Witzke (Medicine)
|
||||
0.908 Professor Senior juniors= 56 laj= 12 Daniel Hoffmann (Biology)
|
||||
0.903 Professor Senior juniors= 92 laj= 7 Matthias Gunzer (Medicine)
|
||||
0.898 Professor Senior juniors= 41 laj= 16 Gerd Bacher (Engineering)
|
||||
0.891 Professor Senior juniors= 48 laj= 23 Ulrike Bingel (Medicine)
|
||||
0.888 Professor Senior juniors= 70 laj= 27 Bernd Sures (Biology)
|
||||
0.879 Professor Senior juniors=116 laj= 6 Boris Hadaschik (Medicine)
|
||||
0.862 Professor Senior juniors=128 laj= 2 Stephan Lang (Medicine)
|
||||
0.848 Professor Senior juniors= 40 laj= 25 Daniel Hering (Biology)
|
||||
0.833 Professor Senior juniors= 28 laj= 31 Stefan Schneegaß (Computer Science)
|
||||
0.786 Professor Senior juniors= 19 laj= 27 Torben Weis (Computer Science)
|
||||
0.781 Professor Senior juniors= 18 laj= 23 Pedro José Marrón (Computer Science)
|
||||
0.777 Professor Senior juniors= 29 laj= 4 Corina Andronescu (Engineering)
|
||||
0.762 Professor Senior juniors= 14 laj= 7 Barbara Saccà (Biology)
|
||||
0.740 Professor Senior juniors= 8 laj= 15 Lucas Davi (Computer Science)
|
||||
0.735 Professor Senior juniors= 13 laj= 24 Burak Atakan (Engineering)
|
||||
0.723 Researcher Senior juniors= 67 laj= 0 Farnusch Kaschani (Biology)
|
||||
0.722 Professor Senior juniors= 12 laj= 11 Barbara König (Computer Science)
|
||||
0.712 Professor Senior juniors= 12 laj= 21 Gregor Schiele (Computer Science)
|
||||
0.707 Professor Senior juniors= 10 laj= 11 Volker Gruhn (Computer Science)
|
||||
0.679 Researcher Senior juniors= 16 laj= 1 Marcus Handte (Computer Science)
|
||||
0.659 Professor Senior juniors= 45 laj= 0 Hartmut Schmidt (Medicine)
|
||||
0.654 Researcher Senior juniors= 22 laj= 0 Daniel Grabner (Biology)
|
||||
0.612 Professor Senior juniors= 13 laj= 0 Tienush Rassaf (Medicine)
|
||||
0.605 Professor Senior juniors= 6 laj= 8 Jens Krüger (Computer Science)
|
||||
0.601 Professor Senior juniors= 9 laj= 3 Andreas Metzger (Computer Science)
|
||||
0.513 Professor Senior juniors= 4 laj= 5 Andreas Vogelsang (Computer Science)
|
||||
0.500 Professor Senior juniors= 3 laj= 2 Frank Kleemann (Sociology)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Bianca Kamba (Biology)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Carina Liebers (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Jonas Keppel (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Carlos Medina Sánchez (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Christian Scholz (Computer Science)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Tobias Mikolas (Engineering)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Julia Schwichtenberg (Medicine)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Antonia Görtz (Sociology)
|
||||
0.494 Researcher Early juniors= 0 laj= 0 Lisa Mansfeld (Sociology)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Simon Janzon (Computer Science)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Christian Niesler (Computer Science)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Pascal Winkler (Computer Science)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Soheil Salighe (Engineering)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Sabrina Guckenbiehl (Medicine)
|
||||
0.488 Researcher Emerging juniors= 0 laj= 0 Zülal Cibir (Medicine)
|
||||
0.418 Researcher Senior juniors= 6 laj= 0 Stefan Hanenberg (Computer Science)
|
||||
0.377 Professor Senior juniors= 2 laj= 0 Ute Klammer (Sociology)
|
||||
0.251 Researcher Senior juniors= 1 laj= 0 Kathrin Januschke (Biology)
|
||||
0.242 Researcher Established juniors= 0 laj= 0 Andreas Jansen (Sociology)
|
||||
0.240 Professor Senior juniors= 1 laj= 0 Helen Baykara-Krumme (Sociology)
|
||||
0.227 Professor Senior juniors= 1 laj= 0 Marcel Erlinghagen (Sociology)
|
||||
0.153 Professor Senior juniors= 0 laj= 0 Gregor Bongaerts (Sociology)
|
||||
|
||||
Report -> /Users/armgdon/University/projects/smart-guide/smart-guide-code/service/scripts/multiplicators/cache/validation_I62318514.json
|
||||
@@ -1,62 +0,0 @@
|
||||
{
|
||||
"missing": [
|
||||
"Peter Bayer (A5060566345)",
|
||||
"Richard Kosinski (A5014403509)",
|
||||
"Alexandra Dmitrienko (A5042835341)",
|
||||
"Wilhelm Koop (A5019228221)",
|
||||
"Venkata Marella (A5082156768)",
|
||||
"Miriam Böhm (A5037448457)",
|
||||
"Katrin Schuldt (A5002003996)",
|
||||
"Friedrich Scheller (A5072565080)",
|
||||
"Lara Altenstädter (A5070117981)"
|
||||
],
|
||||
"by_status": {
|
||||
"Professor": {
|
||||
"mentor": {
|
||||
"n": 29,
|
||||
"median": 0.74,
|
||||
"mean": 0.691,
|
||||
"min": 0.153,
|
||||
"max": 0.921
|
||||
},
|
||||
"bridger": {
|
||||
"n": 29,
|
||||
"median": 0.629,
|
||||
"mean": 0.618,
|
||||
"min": 0.291,
|
||||
"max": 0.856
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 29,
|
||||
"median": 0.612,
|
||||
"mean": 0.584,
|
||||
"min": 0.357,
|
||||
"max": 0.84
|
||||
}
|
||||
},
|
||||
"Researcher": {
|
||||
"mentor": {
|
||||
"n": 22,
|
||||
"median": 0.494,
|
||||
"mean": 0.514,
|
||||
"min": 0.242,
|
||||
"max": 0.958
|
||||
},
|
||||
"bridger": {
|
||||
"n": 22,
|
||||
"median": 0.469,
|
||||
"mean": 0.509,
|
||||
"min": 0.224,
|
||||
"max": 0.796
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 22,
|
||||
"median": 0.45,
|
||||
"mean": 0.529,
|
||||
"min": 0.363,
|
||||
"max": 0.772
|
||||
}
|
||||
}
|
||||
},
|
||||
"m1_exit_mentor_check": "PASS"
|
||||
}
|
||||
-70
@@ -1,70 +0,0 @@
|
||||
{
|
||||
"missing": [
|
||||
"Barbara Saccà (A5075803366)",
|
||||
"Peter Bayer (A5060566345)",
|
||||
"Richard Kosinski (A5014403509)",
|
||||
"Alexandra Dmitrienko (A5042835341)",
|
||||
"Christian Niesler (A5069184110)",
|
||||
"Pascal Winkler (A5081189339)",
|
||||
"Wilhelm Koop (A5019228221)",
|
||||
"Venkata Marella (A5082156768)",
|
||||
"Miriam Böhm (A5037448457)",
|
||||
"Soheil Salighe (A5041884757)",
|
||||
"Tobias Mikolas (A5002909977)",
|
||||
"Oliver Witzke (A5087456839)",
|
||||
"Ulrike Bingel (A5002281474)",
|
||||
"Katrin Schuldt (A5002003996)",
|
||||
"Helen Baykara-Krumme (A5010111732)",
|
||||
"Friedrich Scheller (A5072565080)",
|
||||
"Lara Altenstädter (A5070117981)"
|
||||
],
|
||||
"by_status": {
|
||||
"Professor": {
|
||||
"mentor": {
|
||||
"n": 25,
|
||||
"median": 0.715,
|
||||
"mean": 0.663,
|
||||
"min": 0.153,
|
||||
"max": 0.921
|
||||
},
|
||||
"bridger": {
|
||||
"n": 25,
|
||||
"median": 0.603,
|
||||
"mean": 0.598,
|
||||
"min": 0.229,
|
||||
"max": 0.849
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 25,
|
||||
"median": 0.655,
|
||||
"mean": 0.604,
|
||||
"min": 0.173,
|
||||
"max": 0.957
|
||||
}
|
||||
},
|
||||
"Researcher": {
|
||||
"mentor": {
|
||||
"n": 18,
|
||||
"median": 0.493,
|
||||
"mean": 0.503,
|
||||
"min": 0.153,
|
||||
"max": 0.924
|
||||
},
|
||||
"bridger": {
|
||||
"n": 18,
|
||||
"median": 0.508,
|
||||
"mean": 0.521,
|
||||
"min": 0.181,
|
||||
"max": 0.804
|
||||
},
|
||||
"amplifier": {
|
||||
"n": 18,
|
||||
"median": 0.413,
|
||||
"mean": 0.543,
|
||||
"min": 0.161,
|
||||
"max": 0.971
|
||||
}
|
||||
}
|
||||
},
|
||||
"m1_exit_mentor_check": "PASS"
|
||||
}
|
||||
Binary file not shown.
@@ -1,5 +1,5 @@
|
||||
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
|
||||
LLM_API_KEY=5fc19eb764207e7bec592b3f415ecce650c16ec64344a4db92f74c19ef581154
|
||||
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
|
||||
LLM_MODEL=gemma4-e4b
|
||||
|
||||
# Patent search (EPO + USPTO)
|
||||
@@ -7,10 +7,10 @@ PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
|
||||
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_API_KEY=SVZLSzhhQUIyOHNDLXhyNmh3M3g6R3dlTVlnaTBHM1dnbW1sX0JMQmludw==
|
||||
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
|
||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_INSE_API_KEY=Yl9pSjhhQUJPZ3FnTGZCZVljMEI6Q2N5NDlGX3AzdkNTOHo4c1lfT25QZw==
|
||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
# Debugging: Log every outgoing Elasticsearch query (index + payload)
|
||||
PRINT_ES_QUERIES=false
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Shared contract for the LLM keyword extraction on news articles.
|
||||
|
||||
Two callers extract keywords and write them into the same `keywords` field of
|
||||
`aktuell_postproc`:
|
||||
|
||||
* the background job (`background-jobs/app/sync.py`), which covers the corpus,
|
||||
* the article detail endpoint (`inse.news.logic`), which fills the gap for
|
||||
articles the job has not reached yet.
|
||||
|
||||
The job images
|
||||
install neither pydantic nor the rest of the `inse` package; they copy this
|
||||
single file next to `sync.py`, see `service/scripts/jobs-image/Dockerfile` and
|
||||
`service/scripts/jobs-image/news-keywords/Dockerfile`.
|
||||
"""
|
||||
|
||||
KEYWORD_LIMIT = 6
|
||||
|
||||
# Safety bound on the prompt: articles have about ~2.000
|
||||
# characters, so this limit is practically never reached. It only prevents a
|
||||
# crawl result from overflowing the context window or stalling a page load.
|
||||
KEYWORD_CONTENT_CHARS = 20000
|
||||
|
||||
# The result is persisted once and never recomputed,
|
||||
# so re-running an article has to yield the same keywords.
|
||||
TEMPERATURE = 0.0
|
||||
TOP_P = 0.95
|
||||
TOP_K = 64
|
||||
|
||||
SCHEMA_NAME = "keywords"
|
||||
|
||||
# Mirrors `NewsKeywords.model_json_schema()`. Spelled out so the job can
|
||||
# constrain the response without pulling in pydantic; `NewsKeywords` stays the
|
||||
# parser on the service side.
|
||||
RESPONSE_SCHEMA = {
|
||||
"properties": {
|
||||
"keywords": {
|
||||
"description": "The extracted keywords from the article.",
|
||||
"items": {"type": "string"},
|
||||
"title": "Keywords",
|
||||
"type": "array",
|
||||
}
|
||||
},
|
||||
"required": ["keywords"],
|
||||
"title": "NewsKeywords",
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
"""
|
||||
|
||||
|
||||
def build_user_prompt(maintitle: str | None, full_content: str | None) -> str | None:
|
||||
"""Builds the user message, or None if the article carries no text at all."""
|
||||
text = " ".join(
|
||||
part
|
||||
for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS])
|
||||
if part
|
||||
).strip()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
return f"Artikel:\n{text}"
|
||||
|
||||
|
||||
def normalize_keywords(candidates: list) -> list:
|
||||
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
||||
seen = set()
|
||||
keywords = []
|
||||
for item in candidates:
|
||||
if not isinstance(item, str):
|
||||
continue
|
||||
term = item.strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
@@ -18,6 +18,15 @@ from ..snippets import (
|
||||
snippet_with_context,
|
||||
)
|
||||
from ..topics.logic import vector_search_topics_batch
|
||||
from .keyword_extraction import (
|
||||
KEYWORD_SYSTEM_PROMPT,
|
||||
RESPONSE_SCHEMA,
|
||||
SCHEMA_NAME,
|
||||
TEMPERATURE,
|
||||
TOP_P,
|
||||
build_user_prompt,
|
||||
normalize_keywords,
|
||||
)
|
||||
from .model import (
|
||||
MatchedTopic,
|
||||
MentionedPerson,
|
||||
@@ -49,19 +58,6 @@ CONTENT_HIGHLIGHT = {
|
||||
"require_field_match": False,
|
||||
}
|
||||
|
||||
KEYWORD_LIMIT = 6
|
||||
KEYWORD_CONTENT_CHARS = 4000
|
||||
KEYWORD_SYSTEM_PROMPT = """\
|
||||
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
|
||||
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
|
||||
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
|
||||
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
|
||||
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
|
||||
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
|
||||
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {"keywords": ["Schlagwort", "Schlagwort"]}
|
||||
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
|
||||
"""
|
||||
|
||||
RELATED_BLOCK_SIZE = 5
|
||||
RELATED_TOPIC_K = 1
|
||||
EXACT_ID_CAP = 1000
|
||||
@@ -507,22 +503,21 @@ async def _get_article_keywords(
|
||||
if cached_keywords:
|
||||
return cached_keywords, postproc_id
|
||||
|
||||
text = " ".join(
|
||||
part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
|
||||
).strip()
|
||||
if not text:
|
||||
user_prompt = build_user_prompt(maintitle, full_content)
|
||||
if not user_prompt:
|
||||
return [], postproc_id
|
||||
|
||||
response = await llm.call(
|
||||
system_prompt=KEYWORD_SYSTEM_PROMPT,
|
||||
user_prompt=f"Artikel:\n{text}",
|
||||
json_schema=NewsKeywords.model_json_schema(),
|
||||
schema_name="keywords",
|
||||
temperature=0.3,
|
||||
user_prompt=user_prompt,
|
||||
json_schema=RESPONSE_SCHEMA,
|
||||
schema_name=SCHEMA_NAME,
|
||||
temperature=TEMPERATURE,
|
||||
top_p=TOP_P,
|
||||
)
|
||||
|
||||
try:
|
||||
keywords = _normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
|
||||
keywords = normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
|
||||
except ValidationError:
|
||||
logger.warning(f"Keyword extraction for news {news_id} returned no valid JSON: {response}")
|
||||
keywords = []
|
||||
@@ -549,19 +544,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list:
|
||||
return topics
|
||||
|
||||
|
||||
def _normalize_keywords(candidates: list) -> list:
|
||||
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
|
||||
seen = set()
|
||||
keywords = []
|
||||
for item in candidates:
|
||||
term = item.strip().strip('"').strip()
|
||||
if term and term.lower() not in seen:
|
||||
seen.add(term.lower())
|
||||
keywords.append(term)
|
||||
|
||||
return keywords[:KEYWORD_LIMIT]
|
||||
|
||||
|
||||
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> str | None:
|
||||
"""Caches the keywords and returns the postproc document id they landed in."""
|
||||
try:
|
||||
|
||||
Reference in New Issue
Block a user