Compare commits

..
Author SHA1 Message Date
genja 7ce86d2f19 added eu project calls script to the background jobs
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-12-01 01:55:25 +01:00
genja 59fd8cd17f feat(scripts): add UDE publications topic model training and prediction 2026-11-30 17:19:09 +01:00
genja 93e1148bea feat(scripts): add UDE publications Elasticsearch dataset builder 2026-11-30 17:18:52 +01:00
genja 73ef00be8c Merge pull request 'Feature/standardize layout' (#325) from feature/standardize-layout into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #325
2026-11-25 11:52:16 +01:00
genja cf9cf16a77 feat(navigation): section-aware page skeletons and accessible navigation
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-11-24 23:25:21 +01:00
genja a8b7c63897 (fix): fetch the right field from ude_verified_persons index 2026-11-24 14:33:49 +01:00
genja 4ebf1df32a choose the users organization on dashboard per default
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-11-24 13:25:00 +01:00
genja 3645069ded stretched the multipler nertwok component and made it responsive 2026-11-24 13:07:01 +01:00
genja 977cf442a8 changed the multipliers network route to "collaboration-network:id" 2026-11-24 13:03:22 +01:00
genja 9b0783b80a (fix): Fixed wrong adding nodes to breadcrumb 2026-11-23 22:23:06 +01:00
genja e8c7488489 disable the organization badge view for users not from own org 2026-11-19 23:13:28 +01:00
genja 3d5ed7dd2d added organization information to ude verified staff script 2026-11-19 21:40:35 +01:00
genja 00f54d117d Merge pull request 'Feature/standardize layout' (#324) from feature/standardize-layout into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #324
2026-11-18 18:35:06 +01:00
genja d90bf9b837 navigate to founders with no threshold per default
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-11-18 18:21:55 +01:00
genja ea5e3ca942 added filter params to founders resolver 2026-11-18 18:21:34 +01:00
genja 722f95fad1 added founder table filters to the founder dashboard 2026-11-18 18:21:07 +01:00
genja eb2fa92225 show all founder profiles per default 2026-11-18 18:20:45 +01:00
genja e2be1fc57d added filters for founder table 2026-11-18 18:18:53 +01:00
genja e9a72f88c1 moved selected row to table detail row 2026-11-18 15:12:27 +01:00
genja 48a10dbca3 threshold is opt-in now 2026-11-18 15:10:58 +01:00
genja dc79d16dfb removed "suspicious profile" note next to person names 2026-11-18 15:10:22 +01:00
genja d1827cf86b new model files added
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-11-17 23:07:34 +01:00
genja 728d8c9646 added to_person_profile navigation 2026-11-17 23:07:21 +01:00
genja d60c17abf4 added highlighting for organization on navigation 2026-11-17 21:28:42 +01:00
genja 6b6a5c7cff added organization badge to person profile 2026-11-17 21:25:51 +01:00
genja 41cc3a7ac6 tests for verified organization and institution helper added 2026-11-17 21:20:28 +01:00
genja a1317810c9 added verified organization endpoint with models 2026-11-17 21:20:13 +01:00
genja 22997f6a16 added normalize org uri helper 2026-11-17 21:16:10 +01:00
genja 8322fea036 reused existing normalize org uri function 2026-11-17 21:10:51 +01:00
genja 492987100c added verified persons job 2026-11-16 14:43:12 +01:00
genja cb4e7465b1 added helper function to transfer NES credentials to the container/ added persistent directory for verified persons script 2026-11-16 14:42:45 +01:00
genja ef6df95b54 fixed verification helper for stop creating Edge/CollaborationGraph objects, added new helper function 2026-11-16 14:34:24 +01:00
genja a9e7a0f3ab optimized route-scroll behaviour 2026-11-15 00:03:59 +01:00
genja 23b112beb9 optimized charts rendering 2026-11-15 00:03:52 +01:00
genja 739669021b added explain panel to founder-dashobard component 2026-11-15 00:03:22 +01:00
genja 4c39933b8d minor layout fixes 2026-11-13 12:02:35 +01:00
genja e6e8d192cc fixed bug where the page title was shown as tooltip on mouse hover 2026-11-12 23:07:52 +01:00
genja 9535bfedf5 standartized "goBack" button 2026-11-12 23:01:38 +01:00
genja faa22e0a8f added skeleton loading to person-card's university display 2026-11-12 22:53:07 +01:00
genja 83e0bc3e01 minor ui fixes 2026-11-12 22:43:23 +01:00
genja 30eea4aa22 prevented hierarchy to reresolbe on node click 2026-11-12 22:35:38 +01:00
genja 8b374681c2 added page title service for displaying page title 2026-11-12 22:25:42 +01:00
genja e984372259 made the "Zurück" button visible only within components 2026-11-12 21:58:55 +01:00
genja 8c45c29fc6 standartized resolving state of components 2026-11-12 21:55:44 +01:00
genja 0775f3efc7 fixed hierarchy chart render warning 2026-11-12 21:17:36 +01:00
genja 5153e5876d adjusted tooltips for better explanability 2026-11-12 21:02:39 +01:00
genja 90c6fa56c8 research-wordcloud component replaced by the shared keywords-component 2026-11-12 14:26:13 +01:00
genja e63f2e99d8 created utils for research wordcloud to enable compatibility to the shared keywords-wordcloud component 2026-11-12 14:24:26 +01:00
genja 34c0235112 updated keywords-wordcloud component. Adde more optional fields for reusability 2026-11-12 14:22:57 +01:00
genja 50350fcc12 Merge pull request 'Feature/multipliers frontend' (#323) from feature/multipliers-frontend into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #323
2026-11-12 13:13:34 +01:00
136 changed files with 11184 additions and 1508 deletions
+6
View File
@@ -1,3 +1,4 @@
# Root-context job images only need service code, never the webapp or repo data.
*
!background-jobs
!service
@@ -7,6 +8,11 @@ service/*
# Keyword extraction contract, shared with background-jobs/app/llm/client.py.
!service/src/main/inse/news/keyword_extraction.py
# UDE verified-persons job image imports the full service package and one
# institution hierarchy, so these are the only extra paths it needs.
!service/src/main/inse
!service/src/data/hierarchies/I62318514/hierarchy.json
# Data-only folders that do not belong in the job image.
service/scripts/multipliers
+8
View File
@@ -26,3 +26,11 @@ service/sentence_transformer/models/
llm_evaluations/bio_generation/.venv
.devcontainer
# Runtime checkpoint for the UDE OrgMiner verified-person uploader.
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json
service/scripts/upload_orgminer_verified_persons_ude/orgminer_verified_persons_ude_progress.json.tmp
# Runtime progress for the UDE publications dataset builder.
service/scripts/ude_publications_dataset/data_all_ude/
# Training cache and generated artifacts for the UDE publications topic model.
service/scripts/ude_publications_hdbscan/.cache/
service/scripts/ude_publications_hdbscan/model/
+132
View File
@@ -0,0 +1,132 @@
# EU Project Calls Fetcher
Fetches Horizon Europe funding opportunities from the European Commission Funding & Tenders API and uploads them into Elasticsearch.
## Install
```bash
pip install requests elasticsearch
```
## Step 1: Fetch Calls
Execute:
```bash
python fetch_calls.py
```
Output:
```text
eu_tenders_raw.json
```
### Query Filters
Only calls matching the following criteria are fetched:
* Status:
* Forthcoming
* Open for Submission
* Type of Grant Call:
* Direct calls for proposals (issued by the EU)
* Programme:
* Horizon Europe (2021–2027)
* Programme Part:
* Global Challenges and European Industrial Competitiveness
The filter corresponds to the url: https://ec.europa.eu/info/funding-tenders/opportunities/portal/screen/opportunities/calls-for-proposals?order=DESC&pageNumber=1&pageSize=50&sortBy=startDate&isExactMatch=true&type=1&status=31094502,31094501&programmePart=43108557,43118846,43118971,43120193,43120821,43121563,43108541&frameworkProgramme=43108390
## Step 2: Upload to Elasticsearch
The uploader reads the connection from the environment (the background job
runner injects `ELASTICSEARCH_INSE_URL` and `ELASTICSEARCH_INSE_API_KEY`).
Override the target index with `EU_PROJECT_CALLS_INDEX`.
Execute:
```bash
python upload_calls.py
```
Use `--fresh` to delete all existing documents in the target index, then refill
it from the fetched calls. The index and its mapping must already exist:
```bash
python upload_calls.py --fresh
```
Input:
```text
eu_tenders_raw.json
```
Output:
```text
Elasticsearch index
```
Default index:
```text
eu_project_calls
```
Documents are keyed by the call identifier, so re-runs overwrite instead of
duplicating.
Upload log:
```text
eu_upload_log.json
```
## Indexed Fields
```text
id
title
link
state
programm
call
work_programm_part
description
type_of_action
type_of_mga
open_date
deadline_date
deadline_model
full_title
agr_number
acronym
keywords
```
## Run as a Background Job
The image at `service/scripts/jobs-image/eu-project-calls` fetches and uploads in
one run:
```bash
docker build -f service/scripts/jobs-image/eu-project-calls/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest .
docker push docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest
```
Then create a job in the Jobs UI with that image. The runner injects the
Elasticsearch credentials for registry images. Set the job's **Command** to
`--fresh` to clear and refill the existing index on every run; leave it empty to
upsert into the existing index. The index and its mapping must already exist.
## Data Source
European Commission Funding & Tenders Portal Search API
https://api.tech.ec.europa.eu/search-api/
@@ -0,0 +1,83 @@
import json
import os
import requests
import time
# === CONFIG ===
PAGE_SIZE = 50
OUTPUT_FILE = os.getenv("EU_PROJECT_CALLS_INPUT_FILE", "eu_tenders_raw.json")
url = "https://api.tech.ec.europa.eu/search-api/prod/rest/search"
sort_data = {"order": "DESC", "field": "startDate"}
query_data = {
"bool": {
"must": [
{"terms": {"type": ["1"]}},
{"terms": {"status": ["31094502", "31094501"]}},
{"terms": {"DATASOURCE": ["SEDIA"]}},
{"terms": {"frameworkProgramme": ["43108390"]}},
{"terms": {"programmeDivision": ["43108557", "43118846", "43118971", "43120193", "43120821", "43121563", "43108541"]}},
{"terms": {"language": ["en"]}},
]
}
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Cache-Control": "No-Cache",
"X-Requested-With": "XMLHttpRequest",
"Origin": "https://ec.europa.eu",
"Referer": "https://ec.europa.eu/",
}
# === FETCH ===
all_results = []
page = 1
fetch_failed = False
while True:
params = {
"apiKey": "SEDIA",
"text": "***",
"pageSize": PAGE_SIZE,
"pageNumber": page
}
files = {
"sort": ("blob", json.dumps(sort_data), "application/json"),
"query": ("blob", json.dumps(query_data), "application/json"),
"languages": ("blob", json.dumps(["en"]), "application/json"),
}
try:
response = requests.post(url, params=params, files=files, headers=headers, timeout=30)
response.raise_for_status()
data = response.json()
except Exception as e:
print(f"Error on page {page}: {e}")
fetch_failed = True
break
results = data.get("results", [])
total = data.get("totalResults", 0)
all_results.extend(results)
print(f"Page {page}: got {len(results)} results — total so far: {len(all_results)}/{total}")
if len(all_results) >= total or len(results) < PAGE_SIZE:
break
page += 1
time.sleep(0.5)
print(f"\nDone. Total fetched: {len(all_results)}")
# === SAVE ===
with open(OUTPUT_FILE, "w", encoding="utf-8") as f:
json.dump(all_results, f, ensure_ascii=False, indent=2)
print(f"Saved to {OUTPUT_FILE}")
# Fail the job (and skip the upload) instead of reporting a partial fetch as success.
if fetch_failed:
raise SystemExit(1)
@@ -0,0 +1,155 @@
import argparse
import json
import os
import traceback
from datetime import datetime
from elasticsearch import Elasticsearch
# config — the background job runner injects ELASTICSEARCH_INSE_* for registry images.
ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200")
ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY")
es = Elasticsearch(
ES_URL,
api_key=ES_API_KEY or None,
request_timeout=60,
max_retries=5,
retry_on_timeout=True,
)
index_name = os.getenv("EU_PROJECT_CALLS_INDEX", "eu_project_calls")
INPUT_FILE = os.getenv("EU_PROJECT_CALLS_INPUT_FILE", "eu_tenders_raw.json")
LOG_FILE = os.getenv("EU_PROJECT_CALLS_LOG_FILE", "eu_upload_log.json")
# helpers
def get(metadata, field):
val = metadata.get(field)
if isinstance(val, list):
return val[0] if val else ""
return val or ""
def get_state(metadata):
val = metadata.get("status")
if isinstance(val, list):
if val[0]== "31094502":
return "open for submission"
if val[0] == "31094501":
return "forthcoming"
if val[0] == "31094503":
return "closed"
return val or ""
def parse_date(date_str):
if not date_str:
return None
try:
return datetime.strptime(date_str[:10], "%Y-%m-%d").strftime("%d.%m.%Y")
except Exception:
return None
def map_result(result):
m = result.get("metadata", {})
return {
"id": get(m, "identifier"),
"title": get(m, "title"),
"link": result.get("url") or get(m, "url"),
"state": get_state(m),
"programm": get(m, "frameworkProgramme"),
"call": get(m, "callIdentifier"),
"work_programm_part": get(m, "programmeDivision"),
"description": get(m, "descriptionByte"),
"type_of_action": get(m, "typesOfAction"),
"type_of_mga": get(m, "typeOfMGAs"),
"open_date": parse_date(get(m, "startDate")),
"deadline_date": parse_date(get(m, "deadlineDate")),
"deadline_model": get(m, "deadlineModel"),
"full_title": get(m, "callTitle"),
"agr_number": get(m, "callccm2Id"),
"acronym": get(m, "projectAcronym"),
"funding": "",
"participation_time": "",
"topic": "",
"agr_number": get(m, "ccm2Id"),
"keywords": m.get("keywords",[])
}
# elastic setup
def clear_index():
# The index and its mapping are managed outside this script; --fresh only
# removes the documents so the index can be refilled.
es.delete_by_query(
index=index_name,
body={"query": {"match_all": {}}},
conflicts="proceed",
refresh=True,
)
print(f"Cleared all documents from INDEX {index_name} (--fresh)...")
# logs
def load_log():
if os.path.exists(LOG_FILE):
with open(LOG_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
log = {"done": [], "failed": []}
with open(LOG_FILE, 'w', encoding='utf-8') as f:
json.dump(log, f)
return log
def save_log(log):
with open(LOG_FILE, 'w', encoding='utf-8') as f:
json.dump(log, f, indent=2)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Upload EU project calls to Elasticsearch.")
parser.add_argument(
"--fresh",
action="store_true",
help="Delete the target index first, then recreate and refill it.",
)
args = parser.parse_args()
print("Starting upload...")
if args.fresh:
clear_index()
with open(INPUT_FILE, 'r', encoding='utf-8') as f:
raw_results = json.load(f)
log = load_log()
if args.fresh:
log = {"done": [], "failed": []}
done_set = set(log["done"])
total = len(raw_results)
uploaded = 0
failed = 0
for i, result in enumerate(raw_results):
try:
doc = map_result(result)
identifier = doc["id"]
if not identifier:
raise ValueError("missing call identifier")
# Keyed on the call identifier so scheduled re-runs overwrite
# instead of duplicating every document.
es.index(index=index_name, id=identifier, body=doc)
log["done"].append(identifier)
done_set.add(identifier)
uploaded += 1
print(f" [{i+1}/{total}] ✓ {identifier}")
except Exception as e:
identifier = result.get("metadata", {}).get("identifier", ["unknown"])[0]
print(f" [{i+1}/{total}] ✗ Failed {identifier}: {e}")
traceback.print_exc()
log["failed"].append(identifier)
failed += 1
# save log every 10 items
if i % 10 == 0:
save_log(log)
save_log(log)
print(f"\nDone. Uploaded: {uploaded} | Failed: {failed}")
+30
View File
@@ -82,6 +82,8 @@ differ only by their `command`.
| Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend |
| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend |
| News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index |
| UDE OrgMiner Verified Persons | `jobs/orgminer-verified-persons-ude` | `upload_orgminer_verified_persons_ude.py --progress-file /state/orgminer_verified_persons_ude_progress.json` | Writes `orgminer_verified_persons_ude`; image-scoped NES creds; persistent checkpoint |
| EU Project Calls | `jobs/eu-project-calls` | `fetch_calls.py && upload_calls.py` | Horizon Europe calls; writes `eu_project_calls`; `--fresh` clears+refills index |
| Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows |
Each image is its own repository under the `jobs/` path namespace, prefixed
@@ -106,6 +108,30 @@ docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
Each image's Dockerfile header lists its own build command.
### UDE OrgMiner verified persons
```bash
docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest .
docker push docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest
```
Create a manual-only job in the Jobs UI with this image and set **Persistent
directory** to `/state`. The image's entrypoint writes its JSON checkpoint to
`/state/orgminer_verified_persons_ude_progress.json`; the runner mounts a task-specific Docker volume there so
separate runs resume. Keep the job definition if you need to keep its checkpoint
(deleting the definition also removes its volume). Leave **Command** empty for a
full resumable run, or set it to `--limit 5` for a small first run. Set **Command**
to `--fresh` if every invocation should delete the checkpoint and start at the
first organization. Organizations are processed sequentially; no concurrency
flags exist. The target index is `orgminer_verified_persons_ude`.
If the run stops without a `Finished:` line and reports exit `137`, the
container was killed (usually by the host's out-of-memory killer) and no Python
traceback exists. The run log then gets a `[system] ... ran out of memory ...`
note from the runner. A job without a **Persistent directory** always starts
from the first organization, which makes such a restart look identical.
## Running locally without pushing
Before each run the backend pulls the job's image from the registry when it is a
@@ -127,6 +153,10 @@ is enough for local runs.
Because every tag lives under the `docker.nes.uni-due.de` registry host, the
backend treats these as registry images and injects the INSE Elasticsearch / LLM
credentials automatically (plus any per-job `env`).
The `orgminer-verified-persons-ude` image also receives `ELASTICSEARCH_URL` and
`ELASTICSEARCH_API_KEY` from backend settings, and only that exact repository
gets those NES credentials. Other job images continue to receive INSE/LLM
credentials only.
Most images write to the test index by default: the crawlers upload into the
index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to
@@ -0,0 +1,25 @@
# EU project calls fetcher + uploader (Horizon Europe -> eu_project_calls).
# Build from the repo root:
# docker build -f service/scripts/jobs-image/eu-project-calls/Dockerfile \
# -t docker.nes.uni-due.de/inse/jobs/eu-project-calls:latest .
#
# Fetches the EC Funding & Tenders API, then uploads to Elasticsearch. The
# runner injects ELASTICSEARCH_INSE_URL/API_KEY for registry images.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/eu-project-calls/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Only the scripts: the local raw JSON (15 MB) and upload log stay out of the image.
COPY service/scripts/eu-project-calls/fetch_calls.py \
service/scripts/eu-project-calls/upload_calls.py \
./service/scripts/eu-project-calls/
WORKDIR /app/service/scripts/eu-project-calls
# One run fetches all calls, then uploads them (keyed by call id, so re-runs
# overwrite instead of duplicating). The job's command field is appended here
# and forwarded to the uploader, e.g. --fresh to rebuild the index from scratch.
ENTRYPOINT ["sh", "-c", "python fetch_calls.py && exec python upload_calls.py \"$@\"", "--"]
@@ -0,0 +1,2 @@
requests~=2.32
elasticsearch>=7.17,<8
@@ -0,0 +1,27 @@
# UDE OrgMiner staff verification using the collaboration graph.
# Build from the repository root:
# docker build -f service/scripts/jobs-image/orgminer-verified-persons-ude/Dockerfile \
# -t docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:latest .
#
# The runner injects INSE credentials for registry images and NES credentials
# only for this image. The persistent /state volume holds the JSON checkpoint.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1 \
PYTHONPATH=/app/service/src/main
COPY service/scripts/jobs-image/orgminer-verified-persons-ude/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/src/main/inse/ ./service/src/main/inse/
COPY service/src/data/hierarchies/I62318514/hierarchy.json \
./service/src/data/hierarchies/I62318514/hierarchy.json
COPY service/scripts/upload_orgminer_verified_persons_ude/ \
./service/scripts/upload_orgminer_verified_persons_ude/
# Fail the image build if the service verification/author code is missing a dependency.
RUN python -c "import inse.orgminer.logic, inse.authors.v2.service"
ENTRYPOINT ["python", "/app/service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py", \
"--progress-file", "/state/orgminer_verified_persons_ude_progress.json"]
@@ -0,0 +1,5 @@
fastapi~=0.115.0
httpx~=0.27.0
pydantic-settings~=2.2.1
python-dotenv~=1.0
sqlmodel~=0.0.33
@@ -0,0 +1,165 @@
# UDE publications dataset (Elasticsearch)
Builds a publication-level dataset of **active UDE persons** and indexes it into
an Elasticsearch index on the INSE cluster — one document per publication.
## What it builds
1. Finds active UDE authors in `openalex-authors` (NES) with
`build_active_institution_membership_query("I62318514")` (affiliation year ≥
current UTC year − 2).
2. Loads `orgminer_verified_persons_ude` (INSE) as a lookup by OpenAlex ID. An
author found there has `verified: true` plus verified organization, faculty,
chair and institute metadata.
3. Splits the active authors into batches (default 50). For each batch it fetches
the publications from `openalex-works*`, builds one document per publication,
bulk-indexes them, and only then records the batch as done.
4. Creates the output index (default `ude_oa_works_dataset`) on the first run.
A fresh run requires the index **not** to exist. On a resumed run the index must
exist; progress files in `--output-dir` identify the run. To start over: delete
the index on INSE **and** pass `--reset-progress`.
## Requirements
Run from the repository root with the service environment:
```bash
python service/scripts/ude_publications_dataset/create_ude_publications_dataset.py
```
Required environment variables (normally in `service/src/main/inse/.env`):
```text
ELASTICSEARCH_URL
ELASTICSEARCH_API_KEY
ELASTICSEARCH_INSE_URL
ELASTICSEARCH_INSE_API_KEY
```
## Usage
Full run:
```bash
python service/scripts/ude_publications_dataset/create_ude_publications_dataset.py
```
Restrict to a minimum year / test with two batches:
```bash
python service/scripts/ude_publications_dataset/create_ude_publications_dataset.py \
--year-from 2015 --max-batches 2
```
Useful options:
```text
--output-dir DIR # default: service/scripts/ude_publications_dataset/data_all_ude
--output-index NAME # default: ude_oa_works_dataset
--year-from 0 # default: all years
--batch-size 50 # authors fetched/indexed per batch and checkpoint
--limit-persons N # use at most N active UDE authors (testing)
--max-batches N # process at most N new batches in this run
--reset-progress # delete local progress (also delete the index first)
```
Interrupted runs (Ctrl+C, crash, network loss) resume by rerunning the same
command: finished batches are skipped, the first unfinished batch is redone.
Redoing is safe because each document has a fixed `_id`.
## Index document
Each document is keyed by its short OpenAlex work ID and contains:
```text
id, doi, title, abstract, genre, type, language, publication_year,
publication_date, cited_by_count,
ude_authors, other_ude_authors, other_authors,
primary_topic_id, primary_topic_name, topics, keywords, keyword_names,
verified_person_ids, organizations, faculties, chairs, institutes,
organization_types, organization_levels, org_hierarchy_paths,
oa_organization_ids, work_institution_ids, work_institution_names,
has_ude_affiliation
```
### Author arrays
Every author of the publication is kept, split into three arrays (authorship
order within each):
- `ude_authors` — authors in the active UDE cohort (verified or not).
- `other_ude_authors` — not in the active cohort, but either found in the
verified-persons index or affiliated with UDE (`I62318514`) on this
publication (verified or not).
- `other_authors` — everyone else.
Each entry is a full author object:
```python
{
"author_id": "A5034736701",
"name": "Florian Ziel",
"raw_name": "F. Ziel",
"orcid": "https://orcid.org/...",
"position": "last",
"is_corresponding": False,
"institutions": [...], # merged from the OpenAlex author document
"institution_ids": ["I62318514"],
"raw_affiliation_strings": ["..."],
"countries": ["DE"],
"verified": True, # found in orgminer_verified_persons_ude
"organizations": ["Umweltökonomik, ..."],
"faculties": ["Wirtschaftswissenschaften"],
"chairs": ["Umweltökonomik, ..."], # "Lehrstühle"/"chairs"
"institutes": [], # "Institut*"/"institutes"
}
```
The three arrays are mapped as plain `object` fields (not `nested`), so large
publications cannot hit Elasticsearch's nested-document limit. The trade-off is
that ES flattens arrays of objects: you can filter by a field value, but not
require two fields to belong to the same array element. Publication-level lists
(`organizations`, `faculties`, `chairs`, `institutes`, `verified_person_ids`, ...)
are unions over the verified authors of the publication.
### Author-level institutions
For every publication, the authors are looked up in `openalex-authors` (NES) with
a `terms` query on their IDs (one batched lookup per batch; the cache is dropped
after the batch to bound memory). From each
author document, `last_known_institutions` and `affiliations[].institution` are
merged by OpenAlex institution ID into `institutions`, following the same
shape as the verified-persons upload:
```python
{
"id": "I62318514",
"openalex_url": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen",
"ror": "https://ror.org/...",
"country_code": "DE",
"type": "education",
"lineage": ["https://openalex.org/I62318514", "..."],
"years": [2019, 2020, 2024], # union of all affiliation years
"last_known": True,
}
```
Last-known institutions come first; `institution_ids` is the deduplicated
short-ID list. This replaces the work-level institution array on each author;
work-level institution IDs/names remain on the publication itself as
`work_institution_ids` / `work_institution_names`. If an author is not found in
the author index, both arrays are empty.
`topics` and `keywords` keep the full OpenAlex objects (`id`, `display_name`,
`score`, plus `subfield`/`field`/`domain` where present), deduplicated by display
name and ordered by score; IDs are shortened. `keyword_names` is the same list
as plain display-name strings. `topics` and `keywords` are plain `object` fields.
## Notes
- The active cohort shifts each January as the year cutoff changes.
- Works already indexed are not rebuilt on a resumed run; verified-index changes
only appear after a full restart.
- There are no LLM keywords, embeddings or pickle outputs.
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,4 @@
pandas>=2.2
httpx>=0.27
python-dotenv>=1.0
pydantic-settings>=2.2
@@ -0,0 +1,501 @@
"""Tests for the UDE publications dataset builder."""
from __future__ import annotations
import asyncio
import importlib.util
import json
import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
SCRIPT_PATH = Path(__file__).with_name("create_ude_publications_dataset.py")
_SPEC = importlib.util.spec_from_file_location(
"create_ude_publications_dataset", SCRIPT_PATH
)
assert _SPEC and _SPEC.loader
dataset = importlib.util.module_from_spec(_SPEC)
sys.modules[_SPEC.name] = dataset
_SPEC.loader.exec_module(dataset)
UDE_IDS = ["A1", "A2"]
def _person(openalex_id: str = "A1", org: str = "Applied Analytical Chemistry"):
person = dataset.PersonAggregate(openalex_id=openalex_id)
person.names = {"Alice" if openalex_id == "A1" else "Carol"}
person.org_names = {org}
person.faculties = {"Chemie"}
person.organization_types = {"Lehrstühle"}
person.organization_levels = {"leaf"}
person.org_hierarchy_paths = {("Chemie", "Lehrstühle", org)}
person.oa_organization_ids = {"I62318514"}
person.group_names = {org}
person.institute_names = {"Institut für Chemie"}
return person
def _work() -> dict:
return {
"id": "https://openalex.org/W1",
"doi": "https://doi.org/10.1/example",
"title": "Test title",
"abstract": "Test abstract",
"type": "article",
"language": "en",
"publication_year": 2024,
"cited_by_count": 3,
"primary_topic": {
"id": "https://openalex.org/T1",
"display_name": "Topic One",
"score": 0.9,
},
"topics": [
{
"id": "https://openalex.org/T1",
"display_name": "Topic One",
"score": 0.9,
"subfield": {
"id": "https://openalex.org/subfields/2505",
"display_name": "Materials Chemistry",
},
},
{"id": "https://openalex.org/T2", "display_name": "Topic Two", "score": 0.8},
],
"keywords": [
{"id": "https://openalex.org/K1", "display_name": "machine learning", "score": 0.9},
{"id": "https://openalex.org/K2", "display_name": "Machine Learning", "score": 0.8},
{"id": "https://openalex.org/K3", "display_name": "sensors", "score": 0.7},
],
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Alice",
"orcid": "https://orcid.org/0000-0001-0000-0001",
},
"author_position": "first",
"is_corresponding": True,
"raw_author_name": "A. Alice",
"raw_affiliation_strings": ["University of Duisburg-Essen"],
"countries": ["DE"],
"institutions": [
{
"id": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen",
"type": "education",
"country_code": "DE",
"ror": "https://ror.org/04mz5ra38",
}
],
},
{
"author": {"id": "https://openalex.org/A2", "display_name": "Bob"},
"author_position": "middle",
"institutions": [],
},
{
"author": {"id": "https://openalex.org/A3", "display_name": "Carol"},
"author_position": "last",
"institutions": [],
},
{
"author": {"id": "https://openalex.org/A4", "display_name": "Dave"},
"author_position": "last",
"institutions": [
{
"id": "https://openalex.org/I2",
"display_name": "Other University",
}
],
},
],
}
def _people() -> dict:
return {
"a1": _person("A1"),
"a3": _person("A3", org="Institut für Chemie"),
}
def test_normalize_openalex_id() -> None:
assert dataset.normalize_openalex_id("https://openalex.org/A1") == "A1"
assert dataset.normalize_openalex_id("A1") == "A1"
assert dataset.normalize_openalex_id(None) is None
def test_flatten_named_items_sorts_and_deduplicates() -> None:
items = [
{"display_name": "Beta", "score": 0.4},
{"display_name": "alpha", "score": 0.9},
{"display_name": "Alpha", "score": 0.8},
"gamma",
]
assert dataset.flatten_named_items(items) == ["alpha", "Beta", "gamma"]
def test_named_item_objects_keep_full_objects_and_deduplicate() -> None:
items = [
{"id": "https://openalex.org/K1", "display_name": "Beta", "score": 0.4, "extra": 1},
{"id": "https://openalex.org/K2", "display_name": "alpha", "score": 0.9},
{"id": "https://openalex.org/K3", "display_name": "Alpha", "score": 0.8},
]
objects = dataset.named_item_objects(items)
assert [item["id"] for item in objects] == ["K2", "K1"]
assert objects[1]["extra"] == 1
def test_build_works_query_contains_filters() -> None:
query = dataset.build_works_query(["https://openalex.org/A1"], 2020)
filters = query["bool"]["filter"]
assert {"exists": {"field": "title"}} in filters
assert {"range": {"publication_year": {"gte": 2020}}} in filters
assert query["bool"]["must_not"] == [
{"term": {"is_retracted": True}},
{"term": {"is_paratext": True}},
]
def test_load_ude_persons_uses_active_membership_query(
monkeypatch: pytest.MonkeyPatch,
) -> None:
calls: list[dict] = []
async def fake_scan(**kwargs: object):
calls.append(kwargs)
yield {"_source": {"id": "https://openalex.org/A1"}}
yield {"_source": {"id": "A2"}}
monkeypatch.setattr(dataset.elasticsearch, "scan", fake_scan)
authors = asyncio.run(dataset.load_ude_persons())
assert authors == ["A1", "A2"]
assert calls[0]["index"] == "openalex-authors"
assert calls[0]["cluster"] == "nes"
assert calls[0]["query"] == dataset.build_active_institution_membership_query(
dataset.UDE_INSTITUTION_ID
)
def test_build_document_splits_authors_into_three_arrays() -> None:
row = dataset.build_document(_people(), _work(), UDE_IDS)
assert row is not None
assert [a["author_id"] for a in row["ude_authors"]] == ["A1", "A2"]
assert [a["author_id"] for a in row["other_ude_authors"]] == ["A3"]
assert [a["author_id"] for a in row["other_authors"]] == ["A4"]
alice = row["ude_authors"][0]
assert alice["name"] == "Alice"
assert alice["verified"] is True
assert alice["organizations"] == ["Applied Analytical Chemistry"]
assert alice["faculties"] == ["Chemie"]
assert alice["chairs"] == ["Applied Analytical Chemistry"]
assert alice["institutes"] == ["Institut für Chemie"]
assert alice["institutions"] == [] # no author document in this test
bob = row["ude_authors"][1]
assert bob["verified"] is False
assert bob["organizations"] == []
carol = row["other_ude_authors"][0]
assert carol["verified"] is True
assert carol["organizations"] == ["Institut für Chemie"]
dave = row["other_authors"][0]
assert dave["verified"] is False
assert dave["organizations"] == []
assert "authors" not in row
assert "authors_structured" not in row
assert "researchers" not in row
def test_build_document_other_ude_author_without_verification() -> None:
work = _work()
# Carol drops out of the verified index but keeps her UDE institution.
work["authorships"][2]["institutions"] = [
{"id": "https://openalex.org/I62318514", "display_name": "University of Duisburg-Essen"}
]
row = dataset.build_document({}, work, UDE_IDS)
assert [a["author_id"] for a in row["other_ude_authors"]] == ["A3"]
assert row["other_ude_authors"][0]["verified"] is False
def test_build_document_keeps_publication_metadata() -> None:
row = dataset.build_document(_people(), _work(), UDE_IDS)
assert row["id"] == "https://openalex.org/W1"
assert row["title"] == "Test title"
assert row["abstract"] == "Test abstract"
assert row["publication_year"] == 2024
assert row["cited_by_count"] == 3
assert [topic["id"] for topic in row["topics"]] == ["T1", "T2"]
assert row["topics"][0]["subfield"]["display_name"] == "Materials Chemistry"
assert [keyword["id"] for keyword in row["keywords"]] == ["K1", "K3"]
assert row["keyword_names"] == ["machine learning", "sensors"]
assert row["verified_person_ids"] == ["A1", "A3"]
assert row["organizations"] == ["Applied Analytical Chemistry", "Institut für Chemie"]
assert bool(row["has_ude_affiliation"]) is True
def test_build_document_skips_empty_or_out_of_range_works() -> None:
assert dataset.build_document({}, {"title": None}, UDE_IDS) is None
assert (
dataset.build_document({}, _work(), UDE_IDS, year_from=2025) is None
)
assert dataset.build_document({}, _work(), UDE_IDS, year_from=2024) is not None
def test_build_documents_returns_all_works(monkeypatch: pytest.MonkeyPatch) -> None:
async def no_details(ids): # pragma: no cover - no network in tests
return {}
monkeypatch.setattr(dataset, "fetch_author_details", no_details)
older = _work()
older["id"] = "https://openalex.org/W0"
older["publication_year"] = 2000
documents = asyncio.run(
dataset.build_documents({}, {"W0": older, "W1": _work()}, UDE_IDS)
)
assert {doc_id for doc_id, _ in documents} == {"W0", "W1"}
def test_extract_openalex_institutions_merges_by_id() -> None:
author = dataset.Author.from_dict(
{
"id": "https://openalex.org/A1",
"last_known_institutions": [
{
"id": "https://openalex.org/I1",
"display_name": "UDE",
"ror": "https://ror.org/1",
"type": "education",
"lineage": ["https://openalex.org/I1"],
}
],
"affiliations": [
{
"institution": {
"id": "I1",
"display_name": "Universität Duisburg-Essen",
"country_code": "DE",
},
"years": [2023, 2024, 2023],
},
{
"institution": {"id": "https://openalex.org/I2", "display_name": "Other"},
"years": [1999],
},
],
}
)
institutions = dataset.extract_openalex_institutions(author)
assert [item["id"] for item in institutions] == ["I1", "I2"]
first = institutions[0]
assert first["last_known"] is True
assert first["display_name"] == "UDE"
assert first["country_code"] == "DE"
assert first["years"] == [2023, 2024]
assert first["lineage"] == ["https://openalex.org/I1"]
assert first["openalex_url"] == "https://openalex.org/I1"
assert dataset.openalex_institution_ids(institutions) == ["I1", "I2"]
def test_fetch_author_details_uses_terms_query(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[dict] = []
async def fake_search(**kwargs: object) -> dict:
calls.append(kwargs)
return {
"hits": {
"hits": [
{
"_source": {
"id": "https://openalex.org/A1",
"last_known_institutions": [
{"id": "https://openalex.org/I1", "display_name": "UDE"}
],
"affiliations": [],
}
}
]
}
}
monkeypatch.setattr(dataset.elasticsearch, "search", fake_search)
authors = asyncio.run(dataset.fetch_author_details(["a1"]))
assert list(authors) == ["a1"]
assert calls[0]["index"] == "openalex-authors"
assert calls[0]["query"] == {"terms": {"id": ["https://openalex.org/A1"]}}
assert calls[0]["source"] == dataset.AUTHOR_SOURCE_FIELDS
assert authors["a1"].last_known_institutions[0].display_name == "UDE"
def test_build_documents_fetches_wanted_authors_once(
monkeypatch: pytest.MonkeyPatch,
) -> None:
queried: list[set[str]] = []
async def fake_fetch(ids):
queried.append(set(ids))
return {
author_id.casefold(): dataset.Author.from_dict(
{"id": f"https://openalex.org/{author_id}"}
)
for author_id in ids
}
monkeypatch.setattr(dataset, "fetch_author_details", fake_fetch)
first = _work()
second = _work()
second["id"] = "https://openalex.org/W2"
asyncio.run(dataset.build_documents({}, {"W1": first, "W2": second}, UDE_IDS))
# Only the UDE cohort is fetched (no verified/UDE-affiliated authors here);
# the shared cache means the second work does not query again.
assert queried == [{"A1", "A2"}]
def test_author_arrays_carry_merged_institution_fields() -> None:
author = dataset.Author.from_dict(
{
"id": "https://openalex.org/A1",
"last_known_institutions": [
{"id": "https://openalex.org/I1", "display_name": "UDE"}
],
"affiliations": [
{
"institution": {"id": "https://openalex.org/I2", "display_name": "Other"},
"years": [2020],
}
],
}
)
row = dataset.build_document(
_people(), _work(), UDE_IDS, {"a1": author}
)
alice = row["ude_authors"][0]
assert [item["id"] for item in alice["institutions"]] == ["I1", "I2"]
assert alice["institution_ids"] == ["I1", "I2"]
assert alice["institutions"][0]["last_known"] is True
assert alice["institutions"][1]["years"] == [2020]
assert "oa_institutions" not in alice
for group in ("other_ude_authors", "other_authors"):
for entry in row[group]:
assert entry["institutions"] == []
assert entry["institution_ids"] == []
def test_add_person_context_accepts_legacy_organization_field() -> None:
record = dataset.PersonAggregate(openalex_id="A1")
dataset._add_person_context(
record,
{
"name": "Alice",
"organization": "Legacy Org",
"faculty": "Chemie",
"organization_type": "Lehrstühle",
"organization_level": "leaf",
"oa_organization_ids": ["I1"],
},
)
assert record.org_names == {"Legacy Org"}
assert record.group_names == {"Legacy Org"}
dataset._add_person_context(record, {"org_name": "New Org"})
assert record.org_names == {"Legacy Org", "New Org"}
def test_batch_hash_is_order_independent() -> None:
assert dataset.batch_hash(["b", "a"]) == dataset.batch_hash(["a", "b"])
def test_source_fingerprint_changes_with_work_fields(
monkeypatch: pytest.MonkeyPatch,
) -> None:
digest = dataset.source_fingerprint(None)
monkeypatch.setattr(
dataset, "WORK_SOURCE_FIELDS", [*dataset.WORK_SOURCE_FIELDS, "new_field"]
)
assert dataset.source_fingerprint(None) != digest
def test_progress_roundtrip_and_year_guard(tmp_path: Path) -> None:
progress = dataset.Progress.load(tmp_path, None, "idx")
progress.record_batch("digest", ["W1", "W2"])
reloaded = dataset.Progress.load(tmp_path, None, "idx")
assert reloaded.completed_batches == {"digest"}
assert reloaded.indexed_ids == {"W1", "W2"}
assert reloaded.has_progress is True
with pytest.raises(SystemExit):
dataset.Progress.load(tmp_path, 2020, "idx")
def test_reset_progress_removes_files(tmp_path: Path) -> None:
progress = dataset.Progress.load(tmp_path, None, "idx")
progress.record_batch("digest", ["W1"])
dataset.reset_progress(tmp_path)
assert not (tmp_path / dataset.PROGRESS_FILENAME).exists()
assert not (tmp_path / dataset.INDEXED_IDS_FILENAME).exists()
def test_create_index_sends_mapping(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[tuple] = []
async def fake_request(*args: object, **kwargs: object) -> object:
calls.append((args, kwargs))
return SimpleNamespace(json=lambda: {})
monkeypatch.setattr(dataset.elasticsearch, "_request", fake_request)
asyncio.run(dataset.create_index("ude_publications"))
args, kwargs = calls[0]
assert args[0] == "PUT"
assert args[2] == "ude_publications"
assert kwargs["json_body"] == {"mappings": dataset.INDEX_MAPPING}
assert dataset.INDEX_MAPPING["properties"]["ude_authors"]["type"] == "object"
assert (
dataset.AUTHOR_PROPERTIES["institutions"]["type"] == "object"
)
assert "nested" not in json.dumps(dataset.INDEX_MAPPING)
def test_bulk_chunks_writes_ndjson(monkeypatch: pytest.MonkeyPatch) -> None:
chunks = list(dataset.bulk_chunks("idx", [("W1", {"title": "One"}), ("W2", {"title": "Two"})]))
assert len(chunks) == 1
body = "".join(text for _, _, text in chunks[0])
lines = body.splitlines()
assert len(lines) == 4
assert json.loads(lines[0]) == {"index": {"_index": "idx", "_id": "W1"}}
assert json.loads(lines[1]) == {"title": "One"}
assert json.loads(lines[2])["index"]["_id"] == "W2"
def test_bulk_index_reports_failures(monkeypatch: pytest.MonkeyPatch) -> None:
async def fake_send(chunk, semaphore):
return chunk, {
"errors": True,
"items": [{"index": {"status": 400, "error": "bad"}}],
}
monkeypatch.setattr(dataset, "_send_chunk", fake_send)
with pytest.raises(SystemExit, match="Failed to index 1 publications"):
asyncio.run(dataset.bulk_index("idx", [("W1", {})]))
@@ -0,0 +1,123 @@
# UDE publications topic model (BERTopic + HDBSCAN)
Trains a topic model on the `keyword_names` of the
`ude_openalex_works_dataset` index (INSE) and provides a `predict.py` that
returns the organizations and persons of the most similar publications.
## Data model
Authors are the single source of truth:
- `persons` come from `ude_authors` and `other_ude_authors`.
- `institutions` are the OpenAlex institutions referenced by those persons'
profiles (never the work-level institution fields).
- `orgminer_faculties`, `orgminer_chairs`, `orgminer_institutes` come only from
the `ude_authors` entries (verified organization metadata).
## Training
From the repository root:
```bash
python service/scripts/ude_publications_hdbscan/train.py
```
Required environment variables (normally in `service/src/main/inse/.env`):
```text
ELASTICSEARCH_INSE_URL
ELASTICSEARCH_INSE_API_KEY
```
Useful options:
```text
--index NAME # default: ude_openalex_works_dataset
--output-dir DIR # default: service/scripts/ude_publications_hdbscan/model
--embedding-model NAME # default: sentence-transformers/paraphrase-multilingual-mpnet-base-v2
--batch-size 64
--device cpu|cuda|mps
--embedding-shard-size 2000 # resumable embedding shards
--refresh-cache # discard cached embeddings
--limit N # smoke test
--min-cluster-size 10
--min-samples 2 # lower = fewer HDBSCAN noise points
--umap-neighbors 15
--umap-components 10
--reduce-outliers / --no-reduce-outliers # default: on
--outlier-strategy embeddings|c-tf-idf
--outlier-threshold 0.0 # 0 reassigns all outliers
```
The pipeline matches the old trainer: `UMAP` (cosine, 10 components) →
`HDBSCAN` (`eom`, `prediction_data=True`) wrapped in `BERTopic`, with
`CountVectorizer` over the keyword text. HDBSCAN chooses the number of clusters.
After fitting, HDBSCAN noise (`-1`) is reassigned to the nearest topic with
BERTopic's `reduce_outliers` (default strategy `embeddings`), and topic
representations are refreshed. `metadata.json` records the noise count before and
after.
Embeddings are memory-mapped to `embeddings_keywords.npy` in shards; progress is
recorded in `embeddings_progress.json`, so an interrupted run resumes.
## Artifacts
Default output `model/`:
```text
bertopic_model/ # native BERTopic save
embeddings_keywords.npy # row-aligned with training_table.pkl
training_table.pkl # id, title, keyword_text, ude_author_ids, other_ude_author_ids, topic
persons.pkl # author_id -> profile
institutions.pkl # institution_id -> OpenAlex institution
topic_centroids.npy # mean embedding per non-noise topic
topic_ids.json # topic id per centroid row
cluster_summaries.json # topic size + top keywords
metadata.json # index, counts, model/params, artifact names
```
Each person profile contains `author_id`, `name`, `orcid`, `verified`,
`organizations`, `faculties`, `chairs`, `institutes`, `institution_ids`.
## Prediction
```bash
python service/scripts/ude_publications_hdbscan/predict.py --text "cancer therapy"
python service/scripts/ude_publications_hdbscan/predict.py --embedding-file vector.npy
```
Options: `--top-n 15` (per list), `--top-topics 3`, `--device`, `--model-dir`.
Workflow: encode the query (or use the given vector), rank topics by cosine
similarity to the saved centroids, rank the documents in those topics by cosine
similarity to the query, then walk the ranked documents and collect unique
entities until each list reaches `top_n`.
Output:
```json
{
"institutions": [
{"id": "I62318514", "openalex_url": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen", "ror": "...",
"country_code": "DE", "type": "education"}
],
"persons": [
{"author_id": "A...", "name": "...", "orcid": "...", "verified": true,
"organizations": ["..."], "faculties": ["..."], "chairs": ["..."],
"institutes": ["..."], "institution_ids": ["I..."]}
],
"orgminer_faculties": ["..."],
"orgminer_chairs": ["..."],
"orgminer_institutes": ["..."]
}
```
Each list is unique and capped at `top_n`. HDBSCAN noise topic `-1` is not used
for topic selection; if no topic matches, all documents are ranked.
## Tests
```bash
python -m pytest service/scripts/ude_publications_hdbscan/tests -q
```
@@ -0,0 +1,288 @@
#!/usr/bin/env python3
"""Predict organizations and persons for a text or embedding.
Loads the artifacts written by ``train.py`` and returns the most similar
publications' entities:
* ``institutions`` - unique OpenAlex institutions from the persons
* ``persons`` - unique ``ude_authors`` + ``other_ude_authors``
* ``orgminer_faculties`` - unique faculties from ``ude_authors``
* ``orgminer_chairs`` - unique chairs from ``ude_authors``
* ``orgminer_institutes``- unique institutes from ``ude_authors``
Each list is capped at ``top_n`` (default 15).
Usage
-----
python service/scripts/ude_publications_hdbscan/predict.py --text "cancer therapy"
python service/scripts/ude_publications_hdbscan/predict.py --embedding-file vector.npy
"""
from __future__ import annotations
import argparse
import json
import logging
import pickle
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
DEFAULT_MODEL_DIR = Path(__file__).resolve().parent / "model"
METADATA_FILENAME = "metadata.json"
TRAINING_TABLE_FILENAME = "training_table.pkl"
PERSONS_FILENAME = "persons.pkl"
INSTITUTIONS_FILENAME = "institutions.pkl"
EMBEDDINGS_FILENAME = "embeddings_keywords.npy"
CENTROIDS_FILENAME = "topic_centroids.npy"
TOPIC_IDS_FILENAME = "topic_ids.json"
logger = logging.getLogger("ude_publications_hdbscan.predict")
# =============================================================================
# Artifacts
# =============================================================================
def load_artifacts(model_dir: Path) -> dict[str, Any]:
metadata = json.loads(
(model_dir / METADATA_FILENAME).read_text(encoding="utf-8")
)
with (model_dir / PERSONS_FILENAME).open("rb") as handle:
persons = pickle.load(handle)
with (model_dir / INSTITUTIONS_FILENAME).open("rb") as handle:
institutions = pickle.load(handle)
return {
"metadata": metadata,
"persons": persons,
"institutions": institutions,
"table": pd.read_pickle(model_dir / TRAINING_TABLE_FILENAME),
"embeddings": np.load(model_dir / EMBEDDINGS_FILENAME),
"centroids": np.load(model_dir / CENTROIDS_FILENAME),
"topic_ids": json.loads(
(model_dir / TOPIC_IDS_FILENAME).read_text(encoding="utf-8")
),
}
def load_encoder(metadata: dict[str, Any], device: str | None = None) -> Any:
from sentence_transformers import SentenceTransformer
return SentenceTransformer(metadata["embedding_model"], device=device)
# =============================================================================
# Scoring
# =============================================================================
def _normalize(matrix: np.ndarray) -> np.ndarray:
matrix = np.asarray(matrix, dtype=np.float32)
if matrix.ndim == 1:
matrix = matrix.reshape(1, -1)
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return matrix / norms
def cosine_scores(query: np.ndarray, matrix: np.ndarray) -> np.ndarray:
if matrix.size == 0:
return np.empty(0, dtype=np.float32)
return (_normalize(query) @ _normalize(matrix).T)[0]
def select_topics(
query_embedding: np.ndarray,
centroids: np.ndarray,
topic_ids: list[int],
top_topics: int,
) -> list[int]:
if centroids.size == 0 or not topic_ids:
return []
scores = cosine_scores(query_embedding, centroids)
order = np.argsort(scores)[::-1][: max(1, top_topics)]
return [int(topic_ids[index]) for index in order]
def rank_positions(
table: pd.DataFrame,
query_embedding: np.ndarray,
embeddings: np.ndarray,
topics: list[int],
) -> list[int]:
if topics:
positions = np.flatnonzero(table["topic"].isin(topics).to_numpy())
else:
positions = np.arange(len(table))
if positions.size == 0:
positions = np.arange(len(table))
scores = cosine_scores(query_embedding, embeddings[positions])
return positions[np.argsort(scores)[::-1]].tolist()
# =============================================================================
# Entity collection
# =============================================================================
def _dedupe(values: Any) -> list[str]:
if not isinstance(values, list):
return []
return list(dict.fromkeys(value for value in values if isinstance(value, str)))
def collect_predictions(
table: pd.DataFrame,
ranked_positions: list[int],
persons: dict[str, dict[str, Any]],
institutions: dict[str, dict[str, Any]],
top_n: int = 15,
) -> dict[str, list[Any]]:
result: dict[str, list[Any]] = {
"institutions": [],
"persons": [],
"orgminer_faculties": [],
"orgminer_chairs": [],
"orgminer_institutes": [],
}
seen: dict[str, set[str]] = {key: set() for key in result}
orgminer_fields = {
"orgminer_faculties": "faculties",
"orgminer_chairs": "chairs",
"orgminer_institutes": "institutes",
}
def full() -> bool:
return all(len(result[key]) >= top_n for key in result)
for position in ranked_positions:
row = table.iloc[position]
ude_ids = _dedupe(row.get("ude_author_ids"))
other_ids = _dedupe(row.get("other_ude_author_ids"))
for author_id in list(dict.fromkeys([*ude_ids, *other_ids])):
profile = persons.get(author_id.casefold())
if not profile:
continue
key = profile["author_id"].casefold()
if key not in seen["persons"] and len(result["persons"]) < top_n:
result["persons"].append(profile)
seen["persons"].add(key)
if len(result["institutions"]) < top_n:
for institution_id in _dedupe(profile.get("institution_ids")):
institution_key = institution_id.casefold()
institution = institutions.get(institution_key)
if (
institution is not None
and institution_key not in seen["institutions"]
):
result["institutions"].append(institution)
seen["institutions"].add(institution_key)
if len(result["institutions"]) >= top_n:
break
for author_id in ude_ids:
profile = persons.get(author_id.casefold())
if not profile:
continue
for output_key, field in orgminer_fields.items():
for value in _dedupe(profile.get(field)):
value_key = value.casefold()
if (
value_key not in seen[output_key]
and len(result[output_key]) < top_n
):
result[output_key].append(value)
seen[output_key].add(value_key)
if full():
break
return result
# =============================================================================
# Public API
# =============================================================================
def predict(
text: str | None = None,
embedding: Any | None = None,
top_n: int = 15,
top_topics: int = 3,
model_dir: Path = DEFAULT_MODEL_DIR,
device: str | None = None,
artifacts: dict[str, Any] | None = None,
encoder: Any | None = None,
) -> dict[str, list[Any]]:
if (text is None) == (embedding is None):
raise ValueError("Provide exactly one of text or embedding.")
artifacts = artifacts or load_artifacts(model_dir)
if text is not None:
encoder = encoder or load_encoder(artifacts["metadata"], device=device)
query = encoder.encode([text], convert_to_numpy=True)[0]
else:
query = np.asarray(embedding, dtype=np.float32).ravel()
centroids = artifacts["centroids"]
if centroids.size and query.shape[0] != centroids.shape[1]:
raise ValueError(
f"Embedding has dimension {query.shape[0]}, expected "
f"{centroids.shape[1]}."
)
topics = select_topics(
query, centroids, artifacts["topic_ids"], top_topics
)
ranked = rank_positions(
artifacts["table"], query, artifacts["embeddings"], topics
)
return collect_predictions(
artifacts["table"],
ranked,
artifacts["persons"],
artifacts["institutions"],
top_n=top_n,
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--model-dir", type=Path, default=DEFAULT_MODEL_DIR)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--text")
group.add_argument("--embedding-file", type=Path)
parser.add_argument("--top-n", type=int, default=15)
parser.add_argument("--top-topics", type=int, default=3)
parser.add_argument("--device", default=None)
parser.add_argument("--log-level", default="INFO")
return parser.parse_args()
def main() -> int:
args = parse_args()
logging.basicConfig(
level=getattr(logging, args.log_level.upper(), logging.INFO)
)
embedding = None
if args.embedding_file is not None:
embedding = np.load(args.embedding_file)
result = predict(
text=args.text,
embedding=embedding,
top_n=args.top_n,
top_topics=args.top_topics,
model_dir=args.model_dir,
device=args.device,
)
print(json.dumps(result, ensure_ascii=False, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,12 @@
bertopic>=0.16
nbformat>=4.2.0
sentence-transformers>=5.5
umap-learn>=0.5
hdbscan>=0.8
scikit-learn>=1.5
nltk>=3.8
numpy>=1.26
pandas>=2.2
httpx>=0.27
python-dotenv>=1.0
pydantic-settings>=2.2
@@ -0,0 +1,717 @@
#!/usr/bin/env python3
"""Train a UMAP/HDBSCAN topic model on UDE publications.
Input is the ``keyword_names`` array of each publication in the
``ude_openalex_works_dataset`` Elasticsearch index. Authors are the single
source of truth for the prediction payload:
* ``persons`` - authors from ``ude_authors`` and ``other_ude_authors``
* ``institutions`` - OpenAlex institutions referenced by those persons
``predict.py`` assigns a query to topics by cosine similarity to the topic
centroids, so only the artifacts it reads are written to ``model/``:
metadata.json, persons.pkl, institutions.pkl, training_table.pkl,
embeddings_keywords.npy, topic_centroids.npy, topic_ids.json
Everything that is only useful for re-running training (the Elasticsearch
dataset and the resumable embedding cache) lives in ``.cache/`` instead.
Usage
-----
From the repository root::
python service/scripts/ude_publications_hdbscan/train.py
The service ``.env`` must provide the INSE Elasticsearch credentials (only
needed when the dataset is actually fetched, not when it is cached).
"""
from __future__ import annotations
import argparse
import functools
import hashlib
import json
import logging
import pickle
import shutil
import sys
from collections.abc import AsyncIterator, Iterable, Iterator
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
SERVICE_DIR = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SERVICE_DIR / "src" / "main"))
from inse import config # noqa: E402
from inse.integrations import elasticsearch # noqa: E402
from inse.model import ESCluster # noqa: E402
SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_INDEX = "ude_openalex_works_dataset"
DEFAULT_EMBEDDING_MODEL = (
"sentence-transformers/paraphrase-multilingual-mpnet-base-v2"
)
DEFAULT_OUTPUT_DIR = SCRIPT_DIR / "model"
DEFAULT_CACHE_DIR = SCRIPT_DIR / ".cache"
PAGE_SIZE = 500
# --- model artifacts (read by predict.py) ---
EMBEDDINGS_FILENAME = "embeddings_keywords.npy"
TRAINING_TABLE_FILENAME = "training_table.pkl"
PERSONS_FILENAME = "persons.pkl"
INSTITUTIONS_FILENAME = "institutions.pkl"
CENTROIDS_FILENAME = "topic_centroids.npy"
TOPIC_IDS_FILENAME = "topic_ids.json"
METADATA_FILENAME = "metadata.json"
# --- cache files (training only, never read by predict.py) ---
DATASET_CACHE_FILENAME = "dataset.pkl"
EMBEDDING_CACHE_FILENAME = "embeddings_cache.npy"
PROGRESS_FILENAME = "embeddings_progress.json"
# Columns predict.py actually reads from the training table.
TABLE_COLUMNS = ["topic", "ude_author_ids", "other_ude_author_ids"]
# Leftovers from older runs that predict.py never loads.
OBSOLETE_ARTIFACTS = (
"bertopic_model",
"cluster_summaries.json",
"embeddings_progress.json",
)
SOURCE_FIELDS = [
"id",
"title",
"keyword_names",
"keywords",
"ude_authors",
"other_ude_authors",
]
PERSON_ORGMINER_FIELDS = ("organizations", "faculties", "chairs", "institutes")
logger = logging.getLogger("ude_publications_hdbscan")
# =============================================================================
# Small helpers
# =============================================================================
def setup_logging(level: str) -> None:
logging.basicConfig(
level=getattr(logging, level.upper(), logging.INFO),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
)
def clean_text(value: Any) -> str | None:
if not isinstance(value, str):
return None
value = value.strip()
return value or None
def normalize_openalex_id(value: Any) -> str | None:
if not isinstance(value, str):
return None
value = value.strip().rstrip("/")
marker = "openalex.org/"
if marker in value:
value = value.split(marker, 1)[1]
value = value.strip()
return value or None
def as_str_list(value: Any) -> list[str]:
if value is None:
return []
if isinstance(value, str):
value = [value]
if not isinstance(value, list):
return []
return [item.strip() for item in value if isinstance(item, str) and item.strip()]
def load_json(path: Path, default: Any) -> Any:
if not path.exists():
return default
try:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
logger.warning("Ignoring unreadable %s.", path)
return default
def save_json_atomic(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
temporary.write_text(
json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
temporary.replace(path)
def save_pickle_atomic(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_suffix(path.suffix + ".tmp")
with temporary.open("wb") as handle:
pickle.dump(payload, handle, protocol=pickle.HIGHEST_PROTOCOL)
temporary.replace(path)
def texts_hash(texts: Iterable[str]) -> str:
payload = "\0".join(texts).encode("utf-8")
return hashlib.sha256(payload).hexdigest()
def normalize_rows(matrix: np.ndarray) -> np.ndarray:
matrix = np.asarray(matrix, dtype=np.float32)
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return matrix / norms
@asynccontextmanager
async def closing_scan(**kwargs: Any) -> AsyncIterator[Any]:
generator = elasticsearch.scan(**kwargs)
try:
yield generator
finally:
close = getattr(generator, "aclose", None)
if close is not None:
await close()
# =============================================================================
# Dataset / profiles
# =============================================================================
def keyword_text(source: dict[str, Any]) -> str | None:
"""Join the publication's keyword names into the embedding input."""
names = as_str_list(source.get("keyword_names"))
if not names:
names = [
name
for item in source.get("keywords") or []
if isinstance(item, dict)
for name in [clean_text(item.get("display_name"))]
if name
]
unique = list(dict.fromkeys(name.strip() for name in names if name.strip()))
return ", ".join(unique) or None
def _merge_person(
persons: dict[str, dict[str, Any]], author: dict[str, Any]
) -> str | None:
author_id = normalize_openalex_id(author.get("author_id"))
if not author_id:
return None
key = author_id.casefold()
profile = persons.get(key)
if profile is None:
profile = {
"author_id": author_id,
"name": None,
"orcid": None,
"verified": False,
**{field: set() for field in PERSON_ORGMINER_FIELDS},
"institution_ids": set(),
}
persons[key] = profile
profile["name"] = profile["name"] or clean_text(author.get("name"))
profile["orcid"] = profile["orcid"] or clean_text(author.get("orcid"))
profile["verified"] = profile["verified"] or bool(author.get("verified"))
for field in PERSON_ORGMINER_FIELDS:
profile[field].update(as_str_list(author.get(field)))
profile["institution_ids"].update(
filter(
None,
(
normalize_openalex_id(item)
for item in author.get("institution_ids") or []
),
)
)
return author_id
def _add_institution(
institutions: dict[str, dict[str, Any]], institution: dict[str, Any]
) -> None:
institution_id = normalize_openalex_id(institution.get("id"))
if not institution_id:
return
institutions.setdefault(
institution_id.casefold(),
{
"id": institution_id,
"openalex_url": f"https://openalex.org/{institution_id}",
"display_name": clean_text(institution.get("display_name")),
"ror": clean_text(institution.get("ror")),
"country_code": clean_text(institution.get("country_code")),
"type": clean_text(institution.get("type")),
},
)
def extract_profiles(
source: dict[str, Any],
persons: dict[str, dict[str, Any]],
institutions: dict[str, dict[str, Any]],
) -> tuple[list[str], list[str]]:
"""Add this publication's UDE authors to the profile maps.
Returns ``(ude_author_ids, other_ude_author_ids)``. Institutions are taken
only from these author profiles - never from work-level fields.
"""
groups: list[list[str]] = []
for field in ("ude_authors", "other_ude_authors"):
ids: list[str] = []
seen: set[str] = set()
for author in source.get(field) or []:
if not isinstance(author, dict):
continue
author_id = _merge_person(persons, author)
if not author_id:
continue
if author_id.casefold() not in seen:
seen.add(author_id.casefold())
ids.append(author_id)
for institution in author.get("institutions") or []:
if isinstance(institution, dict):
_add_institution(institutions, institution)
groups.append(ids)
return groups[0], groups[1]
def build_training_row(
source: dict[str, Any],
persons: dict[str, dict[str, Any]],
institutions: dict[str, dict[str, Any]],
) -> dict[str, Any] | None:
text = keyword_text(source)
if not text:
return None
ude_ids, other_ude_ids = extract_profiles(source, persons, institutions)
return {
"id": normalize_openalex_id(source.get("id")),
"keyword_text": text,
"ude_author_ids": ude_ids,
"other_ude_author_ids": other_ude_ids,
}
async def fetch_dataset(index: str, limit: int | None = None) -> tuple[
list[dict[str, Any]],
dict[str, dict[str, Any]],
dict[str, dict[str, Any]],
]:
rows: list[dict[str, Any]] = []
persons: dict[str, dict[str, Any]] = {}
institutions: dict[str, dict[str, Any]] = {}
async with closing_scan(
index=index,
query={"match_all": {}},
source=SOURCE_FIELDS,
page_size=PAGE_SIZE,
keep_alive="10m",
cluster=ESCluster.INSE.value,
) as hits:
async for hit in hits:
row = build_training_row(hit.get("_source") or {}, persons, institutions)
if row is not None:
rows.append(row)
if limit is not None and len(rows) >= limit:
break
# Stable order keeps the embedding cache hash reproducible between runs.
rows.sort(key=lambda row: row["id"] or "")
for profile in persons.values():
for field in PERSON_ORGMINER_FIELDS:
profile[field] = sorted(profile[field], key=str.casefold)
profile["institution_ids"] = sorted(
profile["institution_ids"], key=str.casefold
)
logger.info(
"Fetched %d publications with keywords (%d persons, %d institutions).",
len(rows),
len(persons),
len(institutions),
)
return rows, persons, institutions
def validate_credentials() -> None:
if not config.settings.elasticsearch_inse_url:
raise SystemExit("Missing ELASTICSEARCH_INSE_URL.")
if not config.settings.elasticsearch_inse_api_key:
raise SystemExit("Missing ELASTICSEARCH_INSE_API_KEY.")
def load_dataset(args: argparse.Namespace) -> tuple[
list[dict[str, Any]],
dict[str, dict[str, Any]],
dict[str, dict[str, Any]],
]:
"""Return the dataset from the local cache, or fetch it from Elasticsearch."""
import asyncio
path = args.cache_dir / DATASET_CACHE_FILENAME
key = {"index": args.index, "limit": args.limit}
if path.exists() and not args.refresh_data:
try:
with path.open("rb") as handle:
cached = pickle.load(handle)
if cached.get("key") == key:
logger.info("Using cached dataset from %s.", path)
return cached["rows"], cached["persons"], cached["institutions"]
logger.info("Dataset cache was built for another index/limit; refetching.")
except Exception: # corrupt or incompatible cache
logger.warning("Dataset cache unreadable; refetching.", exc_info=True)
validate_credentials()
rows, persons, institutions = asyncio.run(
fetch_dataset(args.index, limit=args.limit)
)
save_pickle_atomic(
path,
{"key": key, "rows": rows, "persons": persons, "institutions": institutions},
)
return rows, persons, institutions
# =============================================================================
# Embeddings
# =============================================================================
def compute_embeddings(
texts: list[str], args: argparse.Namespace
) -> np.ndarray:
"""Encode texts into a resumable, shard-filled ``.npy`` cache.
The encoder is loaded lazily, so a fully cached run never loads the model.
"""
path = args.cache_dir / EMBEDDING_CACHE_FILENAME
progress_path = args.cache_dir / PROGRESS_FILENAME
progress = load_json(progress_path, {})
shard_size = max(1, args.embedding_shard_size)
shard_count = (len(texts) + shard_size - 1) // shard_size
current_hash = texts_hash(texts)
@functools.cache
def get_encoder() -> Any:
from sentence_transformers import SentenceTransformer
logger.info("Loading embedding model %s.", args.embedding_model)
return SentenceTransformer(args.embedding_model, device=args.device)
can_resume = (
path.exists()
and progress.get("rows") == len(texts)
and progress.get("model") == args.embedding_model
and progress.get("text_hash") == current_hash
and progress.get("shard_size") == shard_size
)
matrix = None
if can_resume:
matrix = np.load(path, mmap_mode="r+")
if matrix.shape != (len(texts), progress.get("dimensions")):
matrix = None
if matrix is not None:
completed = set(progress.get("completed_shards") or [])
logger.info(
"Resuming embeddings: %d/%d shards already encoded.",
len(completed),
shard_count,
)
else:
encoder = get_encoder()
dimensions = encoder.get_sentence_embedding_dimension()
if dimensions is None:
dimensions = encoder.encode(["dimension probe"]).shape[1]
dimensions = int(dimensions)
args.cache_dir.mkdir(parents=True, exist_ok=True)
matrix = np.lib.format.open_memmap(
path, mode="w+", dtype=np.float32, shape=(len(texts), dimensions)
)
completed = set()
progress = {
"rows": len(texts),
"dimensions": dimensions,
"model": args.embedding_model,
"text_hash": current_hash,
"shard_size": shard_size,
"completed_shards": [],
}
save_json_atomic(progress_path, progress)
for start in range(0, len(texts), shard_size):
end = min(start + shard_size, len(texts))
shard_key = f"{start}:{end}"
if shard_key in completed:
continue
matrix[start:end] = get_encoder().encode(
texts[start:end],
batch_size=args.batch_size,
show_progress_bar=False,
convert_to_numpy=True,
)
matrix.flush()
completed.add(shard_key)
progress["completed_shards"] = sorted(completed)
save_json_atomic(progress_path, progress)
logger.info(
"Embeddings shard %s complete (%d/%d).",
shard_key,
len(completed),
shard_count,
)
matrix.flush()
del matrix
return np.load(path)
# =============================================================================
# Clustering (UMAP + HDBSCAN, no BERTopic needed)
# =============================================================================
def cluster_embeddings(embeddings: np.ndarray, args: argparse.Namespace) -> list[int]:
from hdbscan import HDBSCAN
from umap import UMAP
logger.info("Reducing dimensions with UMAP.")
reduced = UMAP(
n_neighbors=args.umap_neighbors,
n_components=args.umap_components,
metric="cosine",
random_state=args.seed,
).fit_transform(embeddings)
logger.info("Clustering with HDBSCAN.")
labels = HDBSCAN(
min_cluster_size=args.min_cluster_size,
min_samples=args.min_samples,
metric="euclidean",
cluster_selection_method="eom",
).fit_predict(reduced)
return [int(label) for label in labels]
def topic_centroids(
embeddings: np.ndarray, topics: list[int]
) -> tuple[np.ndarray, list[int]]:
"""Mean embedding per non-noise topic, used by predict.py for ranking."""
labels = np.asarray(topics)
topic_ids = sorted(int(topic) for topic in set(labels.tolist()) if topic != -1)
if not topic_ids:
return np.empty((0, embeddings.shape[1]), dtype=np.float32), []
centroids = np.vstack(
[embeddings[labels == topic].mean(axis=0) for topic in topic_ids]
).astype(np.float32)
return centroids, topic_ids
def reassign_noise(
embeddings: np.ndarray, topics: list[int], threshold: float
) -> list[int]:
"""Move HDBSCAN noise (-1) documents to the nearest topic centroid.
Uses the same cosine-to-centroid logic as predict.py. With a threshold
of 0 every noise document is reassigned; otherwise only those whose
similarity reaches the threshold.
"""
labels = np.asarray(topics)
noise = np.flatnonzero(labels == -1)
if noise.size == 0:
return topics
centroids, topic_ids = topic_centroids(embeddings, topics)
if not topic_ids:
logger.warning("No clusters found; nothing to reassign noise to.")
return topics
scores = normalize_rows(embeddings[noise]) @ normalize_rows(centroids).T
best = scores.argmax(axis=1)
best_scores = scores[np.arange(noise.size), best]
accept = np.ones(noise.size, dtype=bool) if threshold <= 0 else best_scores >= threshold
ids = np.asarray(topic_ids)
labels[noise[accept]] = ids[best[accept]]
return labels.tolist()
# =============================================================================
# Main
# =============================================================================
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--index", default=DEFAULT_INDEX)
parser.add_argument("--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR)
parser.add_argument(
"--cache-dir",
type=Path,
default=DEFAULT_CACHE_DIR,
help="Training-only cache (dataset + embeddings); not needed by predict.py.",
)
parser.add_argument("--embedding-model", default=DEFAULT_EMBEDDING_MODEL)
parser.add_argument("--batch-size", type=int, default=64)
parser.add_argument("--device", default=None)
parser.add_argument(
"--embedding-shard-size",
type=int,
default=2000,
help="Rows encoded per resumable shard.",
)
parser.add_argument(
"--embedding-dtype",
default="float16",
choices=["float16", "float32"],
help="Precision of the saved embeddings_keywords.npy (default: float16, "
"half the size, no practical effect on cosine ranking).",
)
parser.add_argument(
"--refresh-data",
action="store_true",
help="Ignore the cached dataset and re-fetch from Elasticsearch.",
)
parser.add_argument(
"--refresh-cache",
action="store_true",
help="Discard cached embeddings and re-encode.",
)
parser.add_argument("--limit", type=int, default=None)
parser.add_argument("--min-cluster-size", type=int, default=10)
parser.add_argument(
"--min-samples",
type=int,
default=2,
help="Lower values label fewer points as HDBSCAN noise (default: 2).",
)
parser.add_argument("--umap-neighbors", type=int, default=15)
parser.add_argument("--umap-components", type=int, default=10)
parser.add_argument(
"--seed",
type=int,
default=None,
help="UMAP random seed for reproducible topics (disables UMAP parallelism).",
)
parser.add_argument(
"--reduce-outliers",
action=argparse.BooleanOptionalAction,
default=True,
help="Reassign HDBSCAN noise (-1) documents to the nearest topic "
"centroid after clustering (default: on).",
)
parser.add_argument(
"--outlier-threshold",
type=float,
default=0.0,
help="Minimum cosine similarity for reassignment (0 assigns all outliers).",
)
parser.add_argument("--log-level", default="INFO")
return parser.parse_args()
def main() -> int:
args = parse_args()
setup_logging(args.log_level)
args.output_dir.mkdir(parents=True, exist_ok=True)
args.cache_dir.mkdir(parents=True, exist_ok=True)
if args.refresh_cache:
for name in (EMBEDDING_CACHE_FILENAME, PROGRESS_FILENAME):
(args.cache_dir / name).unlink(missing_ok=True)
rows, persons, institutions = load_dataset(args)
if not rows:
logger.error("No publications with keywords found.")
return 1
texts = [row["keyword_text"] for row in rows]
embeddings = compute_embeddings(texts, args)
topics = cluster_embeddings(embeddings, args)
noise_before = sum(1 for topic in topics if topic == -1)
if args.reduce_outliers and noise_before:
logger.info("Reassigning %d noise documents to nearest centroid.", noise_before)
topics = reassign_noise(embeddings, topics, args.outlier_threshold)
centroids, topic_ids = topic_centroids(embeddings, topics)
# Slim table: only what predict.py needs (no id/title/keyword_text).
training_table = pd.DataFrame(rows).assign(topic=topics)[TABLE_COLUMNS]
training_table.to_pickle(args.output_dir / TRAINING_TABLE_FILENAME)
save_pickle_atomic(args.output_dir / PERSONS_FILENAME, persons)
save_pickle_atomic(args.output_dir / INSTITUTIONS_FILENAME, institutions)
np.save(args.output_dir / EMBEDDINGS_FILENAME, embeddings.astype(args.embedding_dtype))
np.save(args.output_dir / CENTROIDS_FILENAME, centroids)
save_json_atomic(args.output_dir / TOPIC_IDS_FILENAME, topic_ids)
save_json_atomic(
args.output_dir / METADATA_FILENAME,
{
"created_at": datetime.now(UTC).isoformat(),
"index": args.index,
"embedding_model": args.embedding_model, # required by predict.py
"embedding_dtype": args.embedding_dtype,
"documents": len(rows),
"persons": len(persons),
"institutions": len(institutions),
"topics": len(topic_ids),
"noise_before_reduction": noise_before,
"noise_documents": sum(1 for topic in topics if topic == -1),
"reduce_outliers": args.reduce_outliers,
"outlier_threshold": args.outlier_threshold,
"min_cluster_size": args.min_cluster_size,
"min_samples": args.min_samples,
"umap_neighbors": args.umap_neighbors,
"umap_components": args.umap_components,
},
)
# Remove files from older runs that predict.py does not load.
for name in OBSOLETE_ARTIFACTS:
target = args.output_dir / name
if target.is_dir():
shutil.rmtree(target)
else:
target.unlink(missing_ok=True)
(args.output_dir / EMBEDDINGS_FILENAME.replace(".npy", "_progress.json")).unlink(
missing_ok=True
)
logger.info(
"Saved model: %d documents, %d topics, %d persons, %d institutions.",
len(rows),
len(topic_ids),
len(persons),
len(institutions),
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,94 @@
# Upload verified UDE OrgMiner persons
Run from the repository root:
```bash
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py
```
The script reads `ude_organization_content_august_2025_draft`, applies the
OrgMiner collaboration-graph verification rule, and upserts one document per
verified OpenAlex person and organization into `orgminer_verified_persons_ude`
on the INSE Elasticsearch cluster.
For the background-job image and persistent checkpoint setup, see
[`../jobs-image/README.md`](../jobs-image/README.md#ude-orgminer-verified-persons).
INSE credentials must be available as `ELASTICSEARCH_INSE_URL` and
`ELASTICSEARCH_INSE_API_KEY` for reading/writing OrgMiner data. NES credentials
must also be available as `ELASTICSEARCH_URL` and `ELASTICSEARCH_API_KEY` for
OpenAlex author resolution during verification. They can be set in the
environment or the service `.env` file.
The default checkpoint is `orgminer_verified_persons_ude_progress.json` next to
the script. It records completed source organization document IDs and the last
completed organization URI. On restart the scan resumes from that URI, skips
completed organizations, and safely retries upserts if an interrupted request did
not get checkpointed. Use `--progress-file PATH` to keep the checkpoint elsewhere.
Each document also exposes the organization context explicitly:
- `faculty`: root hierarchy node, for example `Chemie`
- `organization_type`: immediate parent label, for example `Lehrstühle` or
`Instituten`
- `organization_level`: hierarchy node type code (`leaf`, `chairs`,
`institutes`, `faculty`)
Each person document also carries the person's OpenAlex organizations, loaded
from `openalex-authors`:
- `oa_organization_ids`: deduplicated short OpenAlex organization IDs
(`I62318514`), used for filtering and joins
- `oa_organization`: deduplicated OpenAlex organization objects with `id`,
`openalex_url`, `display_name`, `ror`, `country_code`, `type`, `lineage`,
`years`, and `last_known`
`last_known_institutions` and `affiliations` are merged by institution ID;
affiliation years are unioned and institutions without an OpenAlex ID are
skipped. Missing author documents do not drop the person; the document is written
with empty institution fields and a warning is logged.
The script processes one organization at a time, so a run needs no concurrency
flags.
Useful options:
```bash
# Run verification without writing to Elasticsearch or changing the checkpoint
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --dry-run
# Smoke-test a limited number of pending organizations
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --limit 5
# Delete the checkpoint and scan from the first organization again
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh
```
Verification requests only the collaboration weights towards the organization's
other staff candidates. It does not materialize every co-author pair, which is
unbounded for works with hundreds or thousands of authors. The progress log ends
each line with the process's peak `rss` so memory growth is visible.
`--fresh` removes the selected checkpoint and its temporary atomic-write file,
but does not clear the output index. Existing person/organization IDs are
upserted; output documents that are no longer produced are left in the index.
When configured on a background-job task, `--fresh` applies on every run, so the
task always restarts from the first source organization. If the checkpoint
directory is not a mounted volume, a warning is logged because progress cannot
survive the container.
## Rebuilding after a mapping change
The script creates the output index with its mapping only when the index does
not exist. After changing the document fields, delete the old index first and
then run a full upload:
```bash
curl -X DELETE "$ELASTICSEARCH_INSE_URL/orgminer_verified_persons_ude" \
-H "Authorization: ApiKey $ELASTICSEARCH_INSE_API_KEY"
python service/scripts/upload_orgminer_verified_persons_ude/upload_orgminer_verified_persons_ude.py --fresh
```
`--fresh` also removes the checkpoint so every source organization is processed
again.
@@ -0,0 +1,277 @@
"""Tests for the institution projection helpers in the upload script."""
from __future__ import annotations
import importlib.util
import sys
from pathlib import Path
from types import SimpleNamespace
from inse.models.openalex.author import Author
from inse.models.openalex.author_affiliations_inner import AuthorAffiliationsInner
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
SCRIPT_PATH = Path(__file__).with_name("upload_orgminer_verified_persons_ude.py")
_SPEC = importlib.util.spec_from_file_location(
"upload_orgminer_verified_persons_ude", SCRIPT_PATH
)
assert _SPEC and _SPEC.loader
upload = importlib.util.module_from_spec(_SPEC)
sys.modules[_SPEC.name] = upload
_SPEC.loader.exec_module(upload)
def _institution(
institution_id: str | None,
display_name: str | None,
*,
ror: str | None = None,
country_code: str | None = None,
institution_type: str | None = None,
lineage: list[str] | None = None,
) -> DehydratedInstitution:
return DehydratedInstitution(
id=institution_id,
display_name=display_name,
ror=ror,
country_code=country_code,
type=institution_type,
lineage=lineage,
)
def test_extract_merges_last_known_and_historical_institutions() -> None:
ude_last_known = _institution(
"https://openalex.org/I62318514",
"University of Duisburg-Essen",
country_code="DE",
institution_type="education",
lineage=["https://openalex.org/I1", "https://openalex.org/I62318514"],
)
ude_affiliation = _institution(
"I62318514",
"University of Duisburg-Essen",
ror="https://ror.org/021ft7s37",
)
previous = _institution(
"https://openalex.org/I999",
"Previous University",
country_code="NL",
institution_type="education",
)
author = Author(
id="https://openalex.org/A1",
last_known_institutions=[ude_last_known],
affiliations=[
AuthorAffiliationsInner(institution=ude_affiliation, years=[2020, 2021]),
AuthorAffiliationsInner(institution=previous, years=[2017, 2018]),
AuthorAffiliationsInner(institution=ude_affiliation, years=[2019]),
],
)
institutions = upload.extract_openalex_institutions(author)
assert [item["id"] for item in institutions] == ["I62318514", "I999"]
assert institutions[0] == {
"id": "I62318514",
"openalex_url": "https://openalex.org/I62318514",
"display_name": "University of Duisburg-Essen",
"ror": "https://ror.org/021ft7s37",
"country_code": "DE",
"type": "education",
"lineage": ["https://openalex.org/I1", "https://openalex.org/I62318514"],
"years": [2019, 2020, 2021],
"last_known": True,
}
assert institutions[1]["last_known"] is False
assert institutions[1]["years"] == [2017, 2018]
assert upload.openalex_institution_ids(institutions) == ["I62318514", "I999"]
def test_extract_skips_institutions_without_an_openalex_id() -> None:
author = Author(
id="https://openalex.org/A1",
last_known_institutions=[
_institution(None, "Unknown Institute"),
_institution("", "Empty Id Institute"),
],
affiliations=[
AuthorAffiliationsInner(
institution=_institution("I123", "Known Institute"),
years=[2021],
)
],
)
institutions = upload.extract_openalex_institutions(author)
assert [item["id"] for item in institutions] == ["I123"]
assert institutions[0]["last_known"] is False
assert institutions[0]["years"] == [2021]
def test_extract_handles_missing_author_and_empty_institutions() -> None:
assert upload.extract_openalex_institutions(None) == []
assert (
upload.extract_openalex_institutions(Author(id="https://openalex.org/A1"))
== []
)
assert upload.openalex_institution_ids([]) == []
def _node(
name: str,
*,
node_type: str,
link: str | None = None,
children: list[SimpleNamespace] | None = None,
) -> SimpleNamespace:
return SimpleNamespace(
name_de=name,
name_en=None,
link_de=link,
link_en=None,
type=node_type,
children=children or [],
)
def test_organization_details_splits_faculty_type_and_organization() -> None:
hierarchy = [
_node(
"Chemie",
node_type="faculty",
link="https://example.org/chemie",
children=[
_node(
"Lehrstühle",
node_type="chairs",
link="https://example.org/chemie/lehrstuehle",
children=[
_node(
"Applied Analytical Chemistry",
node_type="leaf",
link="https://example.org/chemie/aac",
)
],
)
],
)
]
lookup = upload.build_hierarchy_lookup(hierarchy)
details = upload.organization_details(
{"uri": "https://example.org/chemie/aac"}, lookup
)
assert details.faculty == "Chemie"
assert details.organization_type == "Lehrstühle"
assert details.name == "Applied Analytical Chemistry"
assert details.organization_level == "leaf"
assert details.hierarchy_path == [
"Chemie",
"Lehrstühle",
"Applied Analytical Chemistry",
]
def test_organization_details_uses_immediate_parent_for_deep_paths() -> None:
hierarchy = [
_node(
"Chemie",
node_type="faculty",
link="https://example.org/chemie",
children=[
_node(
"Instituten",
node_type="institutes",
link="https://example.org/chemie/institute",
children=[
_node(
"ACTIVE SITES",
node_type="leaf",
link="https://example.org/chemie/active-sites",
children=[
_node(
"Lehrstühle",
node_type="chairs",
link="https://example.org/chemie/active-sites/chairs",
children=[
_node(
"Applied Analytical Chemistry",
node_type="leaf",
link="https://example.org/chemie/active-sites/aac",
)
],
)
],
)
],
)
],
)
]
lookup = upload.build_hierarchy_lookup(hierarchy)
details = upload.organization_details(
{"uri": "https://example.org/chemie/active-sites/aac"}, lookup
)
assert details.faculty == "Chemie"
assert details.organization_type == "Lehrstühle"
assert details.name == "Applied Analytical Chemistry"
def test_organization_details_describes_aggregator_nodes() -> None:
hierarchy = [
_node(
"Chemie",
node_type="faculty",
link="https://example.org/chemie",
children=[
_node(
"Lehrstühle",
node_type="chairs",
link="https://example.org/chemie/lehrstuehle",
)
],
)
]
lookup = upload.build_hierarchy_lookup(hierarchy)
details = upload.organization_details(
{"uri": "https://example.org/chemie/lehrstuehle"}, lookup
)
assert details.faculty == "Chemie"
assert details.organization_type == "Lehrstühle"
assert details.name == "Lehrstühle"
assert details.organization_level == "chairs"
def test_extract_merges_lineage_and_metadata_from_multiple_sources() -> None:
author = Author(
id="https://openalex.org/A1",
last_known_institutions=[
_institution("I42", "Example University", lineage=["I1"])
],
affiliations=[
AuthorAffiliationsInner(
institution=_institution(
"I42",
"Example University",
ror="https://ror.org/example",
lineage=["I1", "I42"],
),
years=[2022],
)
],
)
institutions = upload.extract_openalex_institutions(author)
assert len(institutions) == 1
assert institutions[0]["ror"] == "https://ror.org/example"
assert institutions[0]["lineage"] == ["I1", "I42"]
assert institutions[0]["years"] == [2022]
@@ -28,6 +28,9 @@ settings = config.get_settings()
RUN_STATE_LOCK = RLock()
ORGMINER_DEFAULT_PERSISTENT_DIR = "/app/orgminer_pipeline/runs"
ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY = (
"inse/jobs/orgminer-verified-persons-ude"
)
_client: docker.DockerClient | None = None
@@ -131,6 +134,22 @@ def is_registry_image(image: str | None) -> bool:
return bool(image) and image.split("/", 1)[0] == registry_host()
def uses_nes_credentials(image: str | None) -> bool:
"""Only the OrgMiner verified-person job needs direct NES access."""
if not image or not is_registry_image(image):
return False
registry, _, image_path = image.partition("/")
image_path = image_path.split("@", 1)[0]
path_parts = image_path.rsplit("/", 1)
repository_name = path_parts[-1].split(":", 1)[0]
repository = "/".join([*path_parts[:-1], repository_name])
return (
registry == registry_host()
and repository == ORGMINER_VERIFIED_PERSONS_UDE_REPOSITORY
)
def container_name(definition: JobDefinition, run: JobRun) -> str:
slug = definition.name.lower()
slug = (
@@ -198,7 +217,20 @@ def is_orgminer(definition: JobDefinition) -> bool:
def resolve_environment(definition: JobDefinition) -> dict[str, str]:
base = job_environment() if is_registry_image(resolve_image(definition)) else {}
image = resolve_image(definition)
base = job_environment() if is_registry_image(image) else {}
if uses_nes_credentials(image):
nes_environment = {
"ELASTICSEARCH_URL": settings.elasticsearch_url,
"ELASTICSEARCH_API_KEY": settings.elasticsearch_api_key,
}
base.update(
{
key: value
for key, value in nes_environment.items()
if value
}
)
return {**base, **(definition.env or {})}
@@ -399,7 +431,16 @@ def _reconcile_runs(session: Session) -> None:
container.reload()
if container.status in ("exited", "dead"):
exit_code = container.attrs["State"]["ExitCode"]
state = container.attrs.get("State", {})
exit_code = state["ExitCode"]
logs = container.logs().decode("utf-8", errors="replace")
if state.get("OOMKilled"):
logs = append_system_log(
logs,
"The container ran out of memory and was killed by the kernel "
f"(exit {exit_code}). No Python traceback is written for this; "
"the log above simply stops.",
)
new_status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
)
@@ -408,7 +449,7 @@ def _reconcile_runs(session: Session) -> None:
run,
new_status=new_status,
exit_code=exit_code,
logs=container.logs().decode("utf-8", errors="replace"),
logs=logs,
)
if applied:
session.commit()
@@ -0,0 +1,49 @@
from types import SimpleNamespace
from . import runner
from .model import JobDefinition
def _settings():
return SimpleNamespace(
background_jobs_image="docker.nes.uni-due.de/inse/background-jobs:latest",
elasticsearch_url="https://nes.example/elastic",
elasticsearch_api_key="nes-api-key",
elasticsearch_inse_url="https://inse.example/elastic",
elasticsearch_inse_api_key="inse-api-key",
llm_api_url="https://llm.example",
llm_api_key="llm-api-key",
llm_model="test-model",
sentence_transformers_model_name="test-embedding-model",
)
def _job(image: str) -> JobDefinition:
return JobDefinition(name="test", image=image)
def test_nes_credentials_are_injected_only_for_verified_person_image(monkeypatch):
monkeypatch.setattr(runner, "settings", _settings())
verified_image = (
"docker.nes.uni-due.de/inse/jobs/orgminer-verified-persons-ude:v1"
)
regular_image = "docker.nes.uni-due.de/inse/jobs/news-topics:latest"
verified_environment = runner.resolve_environment(_job(verified_image))
regular_environment = runner.resolve_environment(_job(regular_image))
assert verified_environment["ELASTICSEARCH_URL"] == "https://nes.example/elastic"
assert verified_environment["ELASTICSEARCH_API_KEY"] == "nes-api-key"
assert regular_environment["ELASTICSEARCH_INSE_API_KEY"] == "inse-api-key"
assert "ELASTICSEARCH_URL" not in regular_environment
assert "ELASTICSEARCH_API_KEY" not in regular_environment
def test_nes_credentials_are_not_injected_for_non_registry_copy(monkeypatch):
monkeypatch.setattr(runner, "settings", _settings())
local_image = "localhost/inse/jobs/orgminer-verified-persons-ude:dev"
environment = runner.resolve_environment(_job(local_image))
assert "ELASTICSEARCH_URL" not in environment
assert "ELASTICSEARCH_API_KEY" not in environment
@@ -12,10 +12,16 @@ from .model import JobRun, JobRunStatus, JobTriggeredBy
class FakeContainer:
def __init__(
self, *, status: str, exit_code: int, logs: str, stop_error=None
self,
*,
status: str,
exit_code: int,
logs: str,
stop_error=None,
oom_killed: bool = False,
):
self.status = status
self.attrs = {"State": {"ExitCode": exit_code}}
self.attrs = {"State": {"ExitCode": exit_code, "OOMKilled": oom_killed}}
self._logs = logs
self.stop_calls = 0
self.removed = False
@@ -126,6 +132,26 @@ def test_reconciler_keeps_running_container_after_backend_restart(
assert container.removed is False
def test_reconciler_annotates_container_killed_by_oom(session, monkeypatch):
run = _run(session)
container = FakeContainer(
status="exited",
exit_code=137,
logs="last org: https://www.uni-due.de/zmb",
oom_killed=True,
)
_use_container(monkeypatch, container)
runner.reconcile_runs(session)
session.refresh(run)
assert run.status == JobRunStatus.FAILED
assert run.exit_code == 137
assert "last org: https://www.uni-due.de/zmb" in run.logs
assert "ran out of memory" in run.logs
assert container.removed is True
def test_failed_docker_stop_leaves_database_run_running(session, monkeypatch):
run = _run(session)
container = FakeContainer(
@@ -122,10 +122,10 @@ async def search_founder_candidates(
in_population: Annotated[
bool | None,
Query(
description="Restrict to researchers the model can score (default). "
"Pass false for the unscored, or leave unset for everyone."
description="Restrict to researchers the model can score. "
"Pass true for the scored, false for the unscored, or leave unset for everyone."
),
] = True,
] = None,
min_external_percentile: Annotated[
float | None,
Query(description="Minimum founder percentile (0-100, vs the external reference cohort).", ge=0, le=100),
@@ -39,6 +39,21 @@ def strip_openalex_prefix(institution_id: str) -> str:
return institution_id.rsplit("/", 1)[-1]
def normalize_org_uri(uri: str | None) -> str | None:
"""Normalize an organization URL so hierarchy links compare reliably.
Trims whitespace, drops a trailing slash and the common ``/index`` suffix,
so ``https://www.example.org/x/``, ``https://www.example.org/x/index`` and
``https://www.example.org/x`` all map to the same value.
"""
if not uri:
return None
normalized = uri.strip().rstrip("/")
if normalized.endswith("/index"):
normalized = normalized[: -len("/index")].rstrip("/")
return normalized or None
def full_institution_url(institution_id: str) -> str:
"""Normalize any institution id form to the full OpenAlex URL form."""
return f"https://openalex.org/{strip_openalex_prefix(institution_id)}"
+185 -56
View File
@@ -2,11 +2,14 @@
from collections import defaultdict
import asyncio
from typing import Any, Callable, Optional
from typing import Any, Awaitable, Callable, Optional
from inse.integrations.elasticsearch import search
from inse.utils import normalize_name
from inse.model import ESCluster, ESIndex
from inse.authors.v2.service import _build_collaboration_graph
from inse.authors.v2.service import (
_build_collaboration_graph,
_build_collaboration_graph_query,
)
from inse.auth.model import Account, Organization
from inse import config
from .model import (
@@ -134,6 +137,180 @@ async def get_person_collaborator_weights(
return weights
async def get_collaborator_weights_for_targets(
author_id: str,
institution_id: str,
target_ids: set[str] | frozenset[str] | list[str],
) -> dict[str, float]:
"""Return ``{collaborator_id: shared_work_weight}`` only for ``target_ids``.
The collaboration-graph builder expands every pair of authors on every work,
which explodes for works with hundreds or thousands of authors. Verification
only needs the weights towards the other staff candidates in the same
organization, so this asks Elasticsearch for those counts directly.
"""
targets = sorted(set(target_ids) - {author_id})
if not targets:
return {}
query = _build_collaboration_graph_query(
raw_oa_author_id=author_id,
institution_ids=[institution_id],
)
body = {
"size": 0,
"query": query,
"aggs": {
"collaborators": {
"nested": {"path": "authorships"},
"aggs": {
"targets": {
"terms": {
"field": "authorships.author.id",
"include": targets,
"size": len(targets),
}
}
},
}
},
}
results = await search(
body=body,
index=ESIndex.OPENALEX_WORKS_WILDCARD,
cluster=ESCluster.NES,
)
buckets = (
results.get("aggregations", {})
.get("collaborators", {})
.get("targets", {})
.get("buckets", [])
)
return {
bucket["key"]: float(bucket["doc_count"])
for bucket in buckets
if bucket.get("key")
}
async def get_verified_staff_with_collab_graph(
staff_list: list[dict[str, Any]],
institution_id: str = DEFAULT_INSTITUTION_ID,
max_concurrent_queries: int | None = None,
) -> list[dict[str, Any]]:
"""Return verified staff entries with the OpenAlex IDs and edges proving verification.
A staff entry is verified when at least one of its OpenAlex author candidates
has a collaboration edge to a candidate belonging to a different staff entry
in the same organization.
Only collaborator weights towards the organization's other staff candidates
are fetched, so verification memory does not grow with the size of an
author's full co-author network.
``max_concurrent_queries`` bounds the OpenAlex candidate and graph searches.
It is useful for batch jobs processing organizations with large staff lists.
"""
if max_concurrent_queries is not None and max_concurrent_queries < 1:
raise ValueError("max_concurrent_queries must be at least 1.")
query_semaphore = (
asyncio.Semaphore(max_concurrent_queries)
if max_concurrent_queries is not None
else None
)
async def _run_query(operation: Callable[[], Awaitable[Any]]) -> Any:
if query_semaphore is None:
return await operation()
async with query_semaphore:
return await operation()
async def _resolve_staff(staff: dict[str, Any]) -> set[str]:
name = staff.get("name")
if not name:
return set()
candidate_ids = await _run_query(
lambda: resolve_author_candidates(
normalize_name(name),
institution_id,
)
)
return set(candidate_ids)
async def _get_neighbor_weights(
author_id: str, target_ids: set[str]
) -> dict[str, float]:
return await _run_query(
lambda: get_collaborator_weights_for_targets(
author_id,
institution_id,
target_ids,
)
)
candidate_sets = await asyncio.gather(
*(_resolve_staff(staff) for staff in staff_list)
)
async def _verify_staff(
staff_index: int, own_ids: set[str]
) -> dict[str, Any] | None:
if not own_ids:
return None
other_ids = (
set().union(
*(
candidate_ids
for index, candidate_ids in enumerate(candidate_sets)
if index != staff_index
)
)
- own_ids
)
if not other_ids:
return None
# ``other_ids`` only contains OpenAlex candidates of the other staff
# entries in this organization, and every candidate set was resolved
# against ``institution_id``. Collaborator weights are therefore
# restricted to same-university colleagues; no external co-author can
# contribute evidence.
author_ids = sorted(own_ids)
neighbor_weights = await asyncio.gather(
*(_get_neighbor_weights(author_id, other_ids) for author_id in author_ids)
)
evidence = [
{
"openalex_id": author_id,
"collaborator_openalex_id": collaborator_id,
"shared_work_weight": weights[collaborator_id],
}
for author_id, weights in zip(author_ids, neighbor_weights)
for collaborator_id in sorted(weights.keys() & other_ids)
]
if not evidence:
return None
return {
"staff_index": staff_index,
"staff": staff_list[staff_index],
"openalex_ids": sorted({item["openalex_id"] for item in evidence}),
"collaboration_evidence": evidence,
}
checked_entries = await asyncio.gather(
*(
_verify_staff(staff_index, candidate_ids)
for staff_index, candidate_ids in enumerate(candidate_sets)
)
)
return [entry for entry in checked_entries if entry is not None]
async def find_org_for_person(
name: str,
institution_id: str = None,
@@ -567,62 +744,14 @@ async def get_orgminer_content_verified_by_collab_graph(
orgminer_content = hits[0]["_source"]
staff_list = orgminer_content.get("staff") or []
async def _resolve_staff(staff: dict) -> set[str]:
name = staff.get("name")
if not name:
return set()
candidate_ids = await resolve_author_candidates(
normalize_name(name),
institution_id,
)
return set(candidate_ids)
async def _get_neighbor_ids(author_id: str) -> set[str]:
collaborator_weights = await get_person_collaborator_weights(
author_id,
institution_id,
)
return set(collaborator_weights.keys())
candidate_sets = await asyncio.gather(
*(_resolve_staff(staff) for staff in staff_list)
)
async def _is_verified(staff_index: int) -> bool:
own_ids = candidate_sets[staff_index]
if not own_ids:
return False
# Candidates belonging to other staff members only.
other_ids = (
set().union(
*(
candidate_ids
for index, candidate_ids in enumerate(candidate_sets)
if index != staff_index
)
)
- own_ids
)
if not other_ids:
return False
neighbor_sets = await asyncio.gather(
*(_get_neighbor_ids(author_id) for author_id in own_ids)
)
return any(neighbor_ids & other_ids for neighbor_ids in neighbor_sets)
verified_flags = await asyncio.gather(
*(_is_verified(index) for index in range(len(staff_list)))
verified_entries = await get_verified_staff_with_collab_graph(
staff_list,
institution_id,
)
orgminer_content["verified_staff"] = [
staff
for staff, is_verified in zip(staff_list, verified_flags)
if is_verified
entry["staff"]
for entry in verified_entries
]
return OrgminerContent.from_elastic_hit(orgminer_content)
@@ -704,4 +833,4 @@ async def get_classified_pages(org_url: str,institution_id: str = DEFAULT_INSTIT
return ClassifiedPageResponse(
total=response["hits"]["total"]["value"],
pages=classified_pages
)
)
@@ -0,0 +1,32 @@
from inse.orgminer.institutions_helper import (
normalize_org_uri,
strip_openalex_prefix,
)
def test_normalize_org_uri_matches_equivalent_hierarchy_links():
assert (
normalize_org_uri(" https://www.uni-due.de/zmb/ ")
== "https://www.uni-due.de/zmb"
)
assert (
normalize_org_uri("https://www.uni-due.de/zmb/index")
== "https://www.uni-due.de/zmb"
)
assert (
normalize_org_uri("https://www.uni-due.de/zmb/index/")
== "https://www.uni-due.de/zmb"
)
def test_normalize_org_uri_returns_none_for_missing_values():
assert normalize_org_uri(None) is None
assert normalize_org_uri(" ") is None
def test_strip_openalex_prefix_accepts_raw_and_full_author_ids():
assert strip_openalex_prefix("A5018971503") == "A5018971503"
assert (
strip_openalex_prefix("https://openalex.org/A5018971503")
== "A5018971503"
)
@@ -1,8 +1,170 @@
import asyncio
import json
from inse.orgminer import logic
def test_get_verified_staff_with_collab_graph_returns_matching_ids_and_edges(
monkeypatch,
):
staff = [
{"name": "Person One", "email": "one@example.org"},
{"name": "Person Two"},
]
resolved = {
"person one": ["https://openalex.org/A1", "https://openalex.org/A2"],
"person two": ["https://openalex.org/B1"],
}
neighbors = {
"https://openalex.org/A1": {"https://openalex.org/B1": 2.5},
"https://openalex.org/A2": {},
"https://openalex.org/B1": {},
}
async def resolve_author_candidates(name, institution_id):
return resolved[name]
async def get_collaborator_weights_for_targets(
author_id, institution_id, target_ids
):
return {
collaborator_id: weight
for collaborator_id, weight in neighbors[author_id].items()
if collaborator_id in target_ids
}
monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates)
monkeypatch.setattr(
logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets
)
result = asyncio.run(
logic.get_verified_staff_with_collab_graph(staff, "I123")
)
assert result == [
{
"staff_index": 0,
"staff": staff[0],
"openalex_ids": ["https://openalex.org/A1"],
"collaboration_evidence": [
{
"openalex_id": "https://openalex.org/A1",
"collaborator_openalex_id": "https://openalex.org/B1",
"shared_work_weight": 2.5,
}
],
}
]
def test_get_verified_staff_with_collab_graph_respects_query_concurrency(
monkeypatch,
):
staff = [{"name": "Person One"}, {"name": "Person Two"}]
active_queries = 0
peak_queries = 0
async def tracked(result):
nonlocal active_queries, peak_queries
active_queries += 1
peak_queries = max(peak_queries, active_queries)
try:
await asyncio.sleep(0.001)
return result
finally:
active_queries -= 1
async def resolve_author_candidates(name, institution_id):
author_id = "https://openalex.org/A1" if name == "person one" else "https://openalex.org/A2"
return await tracked([author_id])
async def get_collaborator_weights_for_targets(
author_id, institution_id, target_ids
):
neighbor_id = (
"https://openalex.org/A2"
if author_id == "https://openalex.org/A1"
else "https://openalex.org/A1"
)
return await tracked(
{neighbor_id: 1.0} if neighbor_id in target_ids else {}
)
monkeypatch.setattr(logic, "resolve_author_candidates", resolve_author_candidates)
monkeypatch.setattr(
logic, "get_collaborator_weights_for_targets", get_collaborator_weights_for_targets
)
result = asyncio.run(
logic.get_verified_staff_with_collab_graph(
staff,
"I123",
max_concurrent_queries=1,
)
)
assert len(result) == 2
assert peak_queries == 1
def test_get_collaborator_weights_for_targets_uses_bounded_aggregation(
monkeypatch,
):
captured = {}
async def fake_search(**kwargs):
captured.update(kwargs)
return {
"aggregations": {
"collaborators": {
"targets": {
"buckets": [
{"key": "https://openalex.org/B1", "doc_count": 7},
]
}
}
}
}
monkeypatch.setattr(logic, "search", fake_search)
result = asyncio.run(
logic.get_collaborator_weights_for_targets(
"https://openalex.org/A1",
"I123",
{"https://openalex.org/B1", "https://openalex.org/A1"},
)
)
assert result == {"https://openalex.org/B1": 7.0}
body = captured["body"]
assert body["size"] == 0
nested = body["aggs"]["collaborators"]
assert nested["nested"] == {"path": "authorships"}
assert nested["aggs"]["targets"]["terms"]["include"] == [
"https://openalex.org/B1"
]
assert "query" in body
def test_get_collaborator_weights_for_targets_without_targets_skips_request(
monkeypatch,
):
async def fail_search(**kwargs):
raise AssertionError("search must not be called")
monkeypatch.setattr(logic, "search", fail_search)
result = asyncio.run(
logic.get_collaborator_weights_for_targets(
"https://openalex.org/A1", "I123", set()
)
)
assert result == {}
def test_update_hierarchy_removes_deleted_nodes_and_edit_markers(tmp_path, monkeypatch):
monkeypatch.setattr(logic, "HIERARCHIES_DIR", tmp_path)
+81 -1
View File
@@ -15,14 +15,20 @@ from inse.exceptions import (
NotFoundException,
)
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.model import ESCluster, ESIndex
from inse.models.openalex.author import Author
from inse.models.openalex.authors_list_response import AuthorsListResponse
from inse.models.openalex.meta import Meta
from inse.orgminer.institutions_helper import (
DEFAULT_INSTITUTION_ID,
normalize_org_uri,
strip_openalex_prefix,
)
from inse.persons.model import (
CareerMetrics,
CustomAuthor,
CustomAuthorsListResponse,
VerifiedOrganization,
)
from inse.persons.query_builder import build_authors_search_rescored
from inse.works.logic import enrich_topic_descriptions
@@ -32,6 +38,80 @@ from .. import config, util
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
UDE_INSTITUTION_ID = "https://openalex.org/I62318514" # Universität Duisburg-Essen
VERIFIED_PERSONS_INDEX = "orgminer_verified_persons_ude"
VERIFIED_PERSONS_INSTITUTION_ID = DEFAULT_INSTITUTION_ID
VERIFIED_PERSON_FIELDS = [
"openalex_id",
"organization",
"org_name",
"org_uri",
"org_hierarchy_path",
"verified_at",
]
async def get_verified_organizations(author_id: str) -> list[VerifiedOrganization]:
"""Return organizations where ``author_id`` is a verified staff member.
Reads the OrgMiner verified-persons index on the INSE cluster. Documents are
keyed by the person's OpenAlex id field (both raw and full-URL forms are
accepted), so the lookup does not depend on the index's ``_id`` scheme.
An unavailable index must not break the person page, so failures are logged
and reported as "not verified".
"""
short_id = strip_openalex_prefix(author_id.strip().rstrip("/"))
if not short_id:
return []
query = {
"_source": VERIFIED_PERSON_FIELDS,
"size": 50,
"query": {
"terms": {
"openalex_id": [short_id, f"https://openalex.org/{short_id}"]
}
},
"sort": [
{"verified_at": {"order": "desc", "missing": "_last"}},
{"organization.keyword": {"order": "asc", "missing": "_last"}},
],
}
try:
data = await elasticsearch.search(
body=query, index=VERIFIED_PERSONS_INDEX, cluster=ESCluster.INSE
)
except Exception:
logger.exception(
"Verified-organization lookup failed for author %r.", author_id
)
return []
organizations: dict[str, VerifiedOrganization] = {}
for hit in data.get("hits", {}).get("hits", []):
source = hit.get("_source") or {}
org_uri = normalize_org_uri(source.get("org_uri"))
org_name = (
source.get("organization") or source.get("org_name") or ""
).strip()
key = org_uri or org_name.casefold()
if not key:
continue
# Old sha256-ID and new person-level documents can coexist until the
# index is rebuilt. The newest document wins because of the sort above.
organizations.setdefault(
key,
VerifiedOrganization(
org_name=org_name or org_uri or "Unbekannte Organisation",
org_uri=org_uri,
org_hierarchy_path=source.get("org_hierarchy_path") or [],
verified_at=source.get("verified_at"),
),
)
return list(organizations.values())
async def find_ude_author_by_name(display_name: str) -> dict | None:
+27
View File
@@ -4,6 +4,8 @@ Data models for persons / authors.
"""
from datetime import datetime
from pydantic import BaseModel, Field
from inse.models.openalex.author import Author
@@ -71,6 +73,31 @@ class PersonBio(BaseModel):
bio: str = Field(description="The generated biography.")
class VerifiedOrganization(BaseModel):
org_name: str = Field(description="Display name of the verified organization.")
org_uri: str | None = Field(
default=None, description="Organization URL, normalized for hierarchy matching."
)
org_hierarchy_path: list[str] = Field(
default_factory=list,
description="Path from the hierarchy root to the organization node.",
)
verified_at: datetime | None = Field(
default=None, description="When the organization membership was verified."
)
class VerifiedOrganizationsResponse(BaseModel):
institution_id: str | None = Field(
default=None,
description="OpenAlex institution ID that the verified memberships belong to.",
)
organizations: list[VerifiedOrganization] = Field(
default_factory=list,
description="Organizations where the person has verified staff membership.",
)
class PersonFilters(BaseModel):
institution: str | None = None
cited_by_count: int | None = None
+19
View File
@@ -75,6 +75,25 @@ async def get_person_by_id(
return await logic.get_person_by_id(author_id=id, include=include)
@router.get(
"/person/{id}/verified-organizations",
operation_id="getVerifiedOrganizations",
response_model=model.VerifiedOrganizationsResponse,
summary="Returns the organizations where a person is a verified staff member.",
tags=["Persons"],
)
async def get_verified_organizations(
id: Annotated[
str, Path(description="OpenAlex author ID", example=["A5093075883"])
],
):
organizations = await logic.get_verified_organizations(author_id=id)
return model.VerifiedOrganizationsResponse(
institution_id=logic.VERIFIED_PERSONS_INSTITUTION_ID,
organizations=organizations,
)
@router.get(
"/persons/searchByName",
operation_id="searchPersonsByName",
@@ -0,0 +1,119 @@
import asyncio
from inse.model import ESCluster
from inse.persons import logic, service
def _hit(
*,
org_name: str,
org_uri: str | None,
verified_at: str | None = "2026-01-02T03:04:05Z",
) -> dict:
return {
"_source": {
"openalex_id": "https://openalex.org/A5018971503",
"org_name": org_name,
"org_uri": org_uri,
"org_hierarchy_path": ["Fakultät", org_name],
"verified_at": verified_at,
}
}
def test_get_verified_organizations_uses_person_id_field_and_deduplicates(monkeypatch):
calls: list[dict] = []
async def fake_search(**kwargs):
calls.append(kwargs)
return {
"hits": {
"hits": [
_hit(
org_name="Zentrum für Mikroskopie",
org_uri="https://www.uni-due.de/zmb/",
),
# Same organization from an older sha256-ID document.
_hit(
org_name="Zentrum für Mikroskopie",
org_uri="https://www.uni-due.de/zmb/index",
),
_hit(org_name="Institut für Physik", org_uri=None),
_hit(org_name="Institut für Physik", org_uri=None),
]
}
}
monkeypatch.setattr(logic.elasticsearch, "search", fake_search)
result = asyncio.run(
logic.get_verified_organizations("https://openalex.org/A5018971503")
)
assert len(calls) == 1
assert calls[0]["index"] == logic.VERIFIED_PERSONS_INDEX
assert calls[0]["cluster"] == ESCluster.INSE
assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [
"A5018971503",
"https://openalex.org/A5018971503",
]
assert [organization.org_name for organization in result] == [
"Zentrum für Mikroskopie",
"Institut für Physik",
]
assert result[0].org_uri == "https://www.uni-due.de/zmb"
assert result[0].org_hierarchy_path == [
"Fakultät",
"Zentrum für Mikroskopie",
]
assert result[0].verified_at is not None
def test_get_verified_organizations_accepts_raw_author_id(monkeypatch):
calls: list[dict] = []
async def fake_search(**kwargs):
calls.append(kwargs)
return {"hits": {"hits": []}}
monkeypatch.setattr(logic.elasticsearch, "search", fake_search)
assert asyncio.run(logic.get_verified_organizations(" A5018971503/ ")) == []
assert calls[0]["body"]["query"]["terms"]["openalex_id"] == [
"A5018971503",
"https://openalex.org/A5018971503",
]
def test_get_verified_organizations_returns_empty_on_search_failure(monkeypatch):
async def failing_search(**kwargs):
raise RuntimeError("INSE is unavailable")
monkeypatch.setattr(logic.elasticsearch, "search", failing_search)
assert asyncio.run(logic.get_verified_organizations("A5018971503")) == []
def test_get_verified_organizations_skips_search_without_author_id(monkeypatch):
async def unexpected_search(**kwargs):
raise AssertionError("search must not be called without an author id")
monkeypatch.setattr(logic.elasticsearch, "search", unexpected_search)
assert asyncio.run(logic.get_verified_organizations(" ")) == []
def test_service_response_includes_verified_data_institution(monkeypatch):
async def fake_get_verified_organizations(author_id: str):
return []
monkeypatch.setattr(
logic, "get_verified_organizations", fake_get_verified_organizations
)
response = asyncio.run(
service.get_verified_organizations(id="A5018971503")
)
assert response.institution_id == logic.VERIFIED_PERSONS_INSTITUTION_ID
assert response.organizations == []
@@ -356,6 +356,8 @@ model/userRole.ts
model/validationError.ts
model/validationErrorLocInner.ts
model/value.ts
model/verifiedOrganization.ts
model/verifiedOrganizationsResponse.ts
model/work.ts
model/workBiblio.ts
model/workCitationNormalizedPercentile.ts
+57
View File
@@ -24,6 +24,8 @@ import { CustomAuthorsListResponse } from '../model/customAuthorsListResponse';
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { PersonBio } from '../model/personBio';
// @ts-ignore
import { VerifiedOrganizationsResponse } from '../model/verifiedOrganizationsResponse';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -747,4 +749,59 @@ export class PersonsService extends BaseService {
);
}
/**
* Returns the organizations where a person is a verified staff member.
* @endpoint get /api/inse-service/person/{id}/verified-organizations
* @param id OpenAlex author ID
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getVerifiedOrganizations(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<VerifiedOrganizationsResponse>;
public getVerifiedOrganizations(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<VerifiedOrganizationsResponse>>;
public getVerifiedOrganizations(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<VerifiedOrganizationsResponse>>;
public getVerifiedOrganizations(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getVerifiedOrganizations.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/verified-organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<VerifiedOrganizationsResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+2
View File
@@ -319,6 +319,8 @@ export * from './userRole';
export * from './validationError';
export * from './validationErrorLocInner';
export * from './value';
export * from './verifiedOrganization';
export * from './verifiedOrganizationsResponse';
export * from './work';
export * from './workBiblio';
export * from './workCitationNormalizedPercentile';
@@ -0,0 +1,24 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface VerifiedOrganization {
/**
* Display name of the verified organization.
*/
org_name: string;
org_uri?: string | null;
/**
* Path from the hierarchy root to the organization node.
*/
org_hierarchy_path?: Array<string>;
verified_at?: string | null;
}
@@ -0,0 +1,23 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { VerifiedOrganization } from './verifiedOrganization';
export interface VerifiedOrganizationsResponse {
/**
* OpenAlex institution ID that the verified memberships belong to.
*/
institution_id?: string | null;
/**
* Organizations where the person has verified staff membership.
*/
organizations?: Array<VerifiedOrganization>;
}
+30 -11
View File
@@ -151,9 +151,9 @@ export const routes: Routes = [
]),
],
loadComponent: () =>
import(
'./modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component'
).then((mod) => mod.MultipliersDashboardComponent),
import('./modules/founder-potential/multipliers-dashboard/multipliers-dashboard.component').then(
(mod) => mod.MultipliersDashboardComponent,
),
resolve: {
researchers: multiplicatorResearchersResolver,
},
@@ -170,9 +170,9 @@ export const routes: Routes = [
]),
],
loadComponent: () =>
import(
'./modules/founder-potential/founder-dashboard/founder-dashboard.component'
).then((mod) => mod.FounderDashboardComponent),
import('./modules/founder-potential/founder-dashboard/founder-dashboard.component').then(
(mod) => mod.FounderDashboardComponent,
),
resolve: {
statistics: founderStatisticsResolver,
candidates: founderCandidatesResolver,
@@ -180,7 +180,7 @@ export const routes: Routes = [
runGuardsAndResolvers: 'paramsOrQueryParamsChange',
},
{
path: 'founders/:authorId',
path: 'collaboration-network/:authorId',
canActivate: [
roleGuard([
UserRole.User,
@@ -190,9 +190,9 @@ export const routes: Routes = [
]),
],
loadComponent: () =>
import(
'./modules/founder-potential/researcher-network/researcher-network.component'
).then((mod) => mod.ResearcherNetworkComponent),
import('./modules/founder-potential/researcher-network/researcher-network.component').then(
(mod) => mod.ResearcherNetworkComponent,
),
resolve: {
page: multiplierResearcherPageResolver,
},
@@ -284,7 +284,26 @@ export const routes: Routes = [
hierarchyData: hierarchyResolver,
suggestions: suggestionResolver,
},
runGuardsAndResolvers: 'always',
// Chart navigation only changes `path`/`lang`; do not refetch the whole
// hierarchy on every node click. An explicit same-URL reload (used by
// `reloadSuggestions`) still re-runs the resolvers.
runGuardsAndResolvers: (from, to) => {
if (from.routeConfig !== to.routeConfig) return true;
const keys = new Set([
...from.queryParamMap.keys,
...to.queryParamMap.keys,
]);
const changedKeys = [...keys].filter(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
// No query change at all -> explicit same-URL reload.
if (changedKeys.length === 0) return true;
// Only the chart's own state changed -> keep the loaded hierarchy.
return changedKeys.some((key) => key !== 'path' && key !== 'lang');
},
loadComponent: () =>
import('./modules/hierarchy/hierarchy.component').then(
(mod) => mod.HierarchyComponent,
@@ -8,7 +8,7 @@ import {
effect,
inject,
} from '@angular/core';
import { ResolverStateService } from '../../app/shared/services/resolver-state.service';
import { NavigationStateService } from '../../app/shared/services/navigation-state.service';
@Directive({
selector: 'span, [skText]',
@@ -19,11 +19,11 @@ export class SkTextDirective implements OnChanges {
private readonly el = inject(ElementRef<HTMLElement>);
private readonly renderer = inject(Renderer2);
private readonly resolverStateService = inject(ResolverStateService);
private readonly navigationState = inject(NavigationStateService);
constructor() {
effect(() => {
const loading = this.skText || this.resolverStateService.isResolving();
const loading = this.skText || this.navigationState.isResolving();
if (loading) {
this.showSkeleton();
@@ -38,7 +38,7 @@ export class SkTextDirective implements OnChanges {
return;
}
if (this.skText || this.resolverStateService.isResolving()) {
if (this.skText || this.navigationState.isResolving()) {
this.showSkeleton();
} else {
this.hideSkeleton();
@@ -0,0 +1,58 @@
import { Directive, ElementRef, inject } from '@angular/core';
const PASSIVE_WHEEL_SELECTOR = '[data-passive-wheel]';
let wheelPatchInstalled = false;
/**
* Chrome flags non-passive `wheel`/`mousewheel` listeners as scroll-blocking.
* zrender (ECharts) mounts them on the chart's inner viewport without listener
* options. The hierarchy tree only uses `roam: 'move'` and never calls
* `preventDefault()` on wheel events, so marking them passive is safe.
*
* The patch is global but only affects wheel listeners inside an element that
* carries this directive.
*/
function installPassiveWheelPatch(): void {
if (wheelPatchInstalled) return;
wheelPatchInstalled = true;
const nativeAddEventListener = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function (
this: EventTarget,
type: string,
listener: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions,
): void {
const isWheelEvent = type === 'wheel' || type === 'mousewheel';
const hasOptions = options !== undefined && typeof options !== 'boolean';
if (
isWheelEvent &&
!hasOptions &&
this instanceof Element &&
this.closest(PASSIVE_WHEEL_SELECTOR)
) {
nativeAddEventListener.call(this, type, listener, {
capture: options === true,
passive: true,
});
return;
}
nativeAddEventListener.call(this, type, listener, options);
};
}
@Directive({
selector: '[appPassiveWheel]',
standalone: true,
})
export class PassiveWheelDirective {
private readonly host = inject<ElementRef<HTMLElement>>(ElementRef);
constructor() {
this.host.nativeElement.setAttribute('data-passive-wheel', '');
installPassiveWheelPatch();
}
}
@@ -69,7 +69,7 @@
<button
mat-icon-button
type="button"
aria-label="Impersonate"
aria-label="Als diesen Account anmelden"
matTooltip="Als dieser Account anmelden (Impersonation)"
[disabled]="!canImpersonate(row)"
(click)="impersonate(row)">
@@ -44,10 +44,17 @@ export class DashboardComponent implements OnInit {
ngOnInit() {
this.restoreTreemapNodeState();
this.dashboard.initialize((institutionId) => {
if (institutionId === this.selectedAnalyticalInstitutionId) return;
this.dashboard.initialize((institutionId, source) => {
const changed = institutionId !== this.selectedAnalyticalInstitutionId;
this.selectedAnalyticalInstitutionId = institutionId;
this.reloadAnalyticalData();
// When the organization was auto-selected from the account (no explicit
// URL parameter), persist it so the URL reflects the current state.
if (source === 'default' && institutionId) {
this.updateDashboardPeriodUrl();
}
if (changed) {
this.reloadAnalyticalData();
}
});
}
@@ -21,6 +21,10 @@ import {
TopAuthorStatistics,
} from '../dashboard-statistics.service';
import { mapProjectTopicsToTreemap } from './dashboard-topic-treemap.mapper';
import { CredentialService } from '../../../shared/services/credential.service';
/** Where the initially selected institution came from. */
export type InstitutionRestoreSource = 'url' | 'default';
@Injectable()
export class DashboardFacade {
@@ -88,9 +92,15 @@ export class DashboardFacade {
constructor(
private readonly statisticsService: DashboardStatisticsService,
private readonly route: ActivatedRoute,
private readonly credentials: CredentialService,
) {}
initialize(onInstitutionRestored: (institutionId: string) => void): void {
initialize(
onInstitutionRestored: (
institutionId: string,
source: InstitutionRestoreSource,
) => void,
): void {
this.restorePeriodState();
this.loadStatistics();
this.loadInstitutions(onInstitutionRestored);
@@ -191,7 +201,10 @@ export class DashboardFacade {
}
private loadInstitutions(
onInstitutionRestored: (institutionId: string) => void,
onInstitutionRestored: (
institutionId: string,
source: InstitutionRestoreSource,
) => void,
): void {
this.institutionsLoading = true;
this.institutionsError = false;
@@ -202,18 +215,23 @@ export class DashboardFacade {
next: (institutions) => {
this.institutions = institutions;
const requestedInstitution =
this.route.snapshot.queryParamMap.get('institution') ?? 'all';
const restoredInstitution = institutions.some(
(institution) => institution.id === requestedInstitution,
)
? requestedInstitution
: 'all';
this.route.snapshot.queryParamMap.get('institution');
// An explicit URL parameter wins; otherwise start with the logged-in
// person's organization (the effective institution, which follows
// impersonation) and fall back to all institutions.
const restoredInstitution = requestedInstitution
? this.findInstitution(institutions, requestedInstitution) ?? 'all'
: this.findInstitution(
institutions,
this.credentials.effectiveInstitutionId(),
) ?? 'all';
if (restoredInstitution !== this.selectedInstitutionId) {
this.selectedInstitutionId = restoredInstitution;
this.loadStatistics();
}
onInstitutionRestored(
restoredInstitution === 'all' ? '' : restoredInstitution,
requestedInstitution ? 'url' : 'default',
);
},
error: () => {
@@ -223,6 +241,16 @@ export class DashboardFacade {
});
}
private findInstitution(
institutions: DashboardInstitution[],
institutionId: string | null | undefined,
): string | undefined {
if (!institutionId) return undefined;
return institutions.some((institution) => institution.id === institutionId)
? institutionId
: undefined;
}
private loadDfgProjectTopics(
period: DashboardPeriodBounds,
institutionId: string,
@@ -3,8 +3,17 @@
title="Wer hat Gründungspotenzial?"
subtitle="Kandidat:innen für Gründungsgespräche und -angebote."
[titleTooltip]="pageTooltip">
<button
pageActions
mat-stroked-button
color="primary"
type="button"
(click)="openExplainer()">
<mat-icon>{{ INSIGHTS_ICON }}</mat-icon>
Erklären
</button>
<div class="founder-dashboard">
@if (hasData() && hasScores()) {
@if (hasData()) {
<section class="statistics-grid" aria-label="Kennzahlen">
<app-dashboard-statistic-card
label="Forschende gesamt"
@@ -25,27 +34,18 @@
[detail]="scoreableDetail()" />
<app-dashboard-statistic-card
label="Unauffällige Profile"
[value]="kpis().passed"
[icon]="VERIFIED_ICON"
variant="quality"
[ariaLabel]="'Unauffällige Profile: ' + fmtInt(kpis().passed)"
[tooltip]="qualityTooltip()"
[detail]="qualityDetail()" />
<app-dashboard-statistic-card
label="Auf der Shortlist"
label="Top Kandidat:innen"
[value]="kpis().shortlisted"
[icon]="STAR_ICON"
variant="shortlist"
[ariaLabel]="'Auf der Shortlist: ' + fmtInt(kpis().shortlisted)"
[ariaLabel]="'Top Kandidat:innen: ' + fmtInt(kpis().shortlisted)"
[tooltip]="shortlistTooltip()"
[detail]="shortlistDetail()" />
</section>
<section class="shortlist-section">
<div class="section-heading">
<h2>Shortlist: Top-Kandidat:innen</h2>
<h2>Top-Kandidat:innen</h2>
<mat-icon
class="info-icon"
[matTooltip]="shortlistSectionTooltip"
@@ -55,6 +55,8 @@
</mat-icon>
</div>
<app-founder-filters [statistics]="statistics()" />
<div class="controls">
<span class="controls__range">
Mindestwert
@@ -66,20 +68,29 @@
{{ INFO_OUTLINE_ICON }}
</mat-icon>
</span>
<mat-slide-toggle
[checked]="thresholdEnabled()"
(change)="onThresholdEnabledChange($event.checked)"
[matTooltip]="thresholdToggleTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
Aktiv
</mat-slide-toggle>
<mat-slider
class="controls__slider"
[min]="50"
[max]="100"
[step]="1"
[discrete]="true"
[displayWith]="formatThreshold">
[displayWith]="formatThreshold"
[disabled]="!thresholdEnabled()">
<input
matSliderThumb
[value]="thresholdDraft()"
(valueChange)="onSliderInput($event)"
(dragEnd)="onSliderCommit($event.value)"
(keyup)="onSliderCommit()"
aria-label="Mindestwert für die Shortlist" />
aria-label="Mindestwert für die Liste der Top-Kandidat:innen" />
</mat-slider>
<span class="controls__value">{{ thresholdDraft() }}</span>
<mat-slide-toggle
@@ -101,14 +112,13 @@
<app-data-table
[columns]="columns()"
[data]="rows()"
[selectedRow]="selectedRow()"
[detailTemplate]="detailTemplate()"
queryParamSortKey="sortBy"
queryParamSortDirectionKey="sortOrder"
(rowClick)="selectCandidate($event.candidate.author_id)" />
queryParamSortDirectionKey="sortOrder" />
} @else {
<div class="list__empty">
<p>{{ emptyListMessage() }}</p>
@if (threshold() > 50) {
@if (thresholdEnabled() && threshold() > 50) {
<button
mat-stroked-button
color="primary"
@@ -122,153 +132,10 @@
</mat-card-content>
</mat-card>
@if (selectedRow(); as row) {
<mat-card appearance="outlined" class="card">
<mat-card-content>
<div class="card__head">
<div>
<span class="card__eyebrow">Ausgewählt</span>
<h3>{{ row.name }}</h3>
<div class="card__meta">
<span
class="card__career"
[matTooltip]="careerBucketTooltip(row.candidate.career_bucket)"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
{{ row.candidate.career_bucket ?? '–' }}
</span>
@if (row.areaLabel) {
· {{ row.areaLabel }}
}
· {{ fmtInt(row.candidate.active_years) }} Jahre mit
Publikationen
@if (!row.candidate.screen.passed && row.flagLabel) {
·
<span
class="card__flag"
[matTooltip]="flagTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
auffällig: {{ row.flagLabel }}
</span>
}
</div>
</div>
</div>
<p class="score-caption">
Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten.
90 heißt: stärker als 90 % der Vergleichsgruppe.
</p>
<div class="score-tiles">
<div
class="score-tile score-tile--primary"
[matTooltip]="scoreTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Potenzial</span>
<strong>{{ fmt1(row.score) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 1 Jahr</span>
<strong>{{ fmt1(row.within[0]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 3 Jahre</span>
<strong>{{ fmt1(row.within[1]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 5 Jahre</span>
<strong>{{ fmt1(row.within[2]) }}</strong>
</div>
</div>
<div class="facts">
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Publikationen der Person."
matTooltipClass="sg-tooltip-wide">
Publikationen
<b>{{
fmtInt(row.candidate.founder_features?.publications)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Patente mit Bezug zur Einrichtung."
matTooltipClass="sg-tooltip-wide">
Patente
<b>{{
fmtInt(row.candidate.founder_features?.patents)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Arbeiten mit Beteiligung aus Unternehmen."
matTooltipClass="sg-tooltip-wide">
Arbeiten mit Industrie
<b>{{
fmtInt(
row.candidate.founder_features?.industry_collab_papers
)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Förderprojekte."
matTooltipClass="sg-tooltip-wide">
Förderprojekte
<b>{{
fmtInt(row.candidate.founder_features?.grants)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Jahre mit mindestens einer Publikation."
matTooltipClass="sg-tooltip-wide">
Aktive Jahre
<b>{{ fmtInt(row.candidate.active_years) }}</b>
</app-chip>
</div>
</mat-card-content>
</mat-card>
}
<app-query-param-paginator
[total]="total()"
[pageSizeOptions]="[10, 25, 50]" />
</section>
} @else if (hasData()) {
<mat-card appearance="outlined" class="empty-state">
<mat-card-content>
<mat-icon class="empty-state__icon">{{ FOUNDER_ICON }}</mat-icon>
<h2>Noch keine Gründungspotenzial-Scores</h2>
<p>
Für die <strong>{{ universityName() }}</strong> liegen Forschungsdaten
vor, aber die Gründungspotenzial-Auswertung wurde noch nicht
berechnet. Sobald sie vorliegt, erscheinen hier die Kandidat:innen und
ihre Werte.
</p>
</mat-card-content>
</mat-card>
} @else {
<mat-card appearance="outlined" class="empty-state">
<mat-card-content>
@@ -305,7 +172,17 @@
</ng-template>
<ng-template #scoreTemplate let-row>
<span class="list__score-value">{{ fmt1(row.score) }}</span>
@if (row.score === null) {
<span
class="list__score-missing"
[matTooltip]="row.notScoredReason"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
(nicht bewertet)
</span>
} @else {
<span class="list__score-value">{{ fmt1(row.score) }}</span>
}
</ng-template>
<ng-template #withinTemplate let-row>
@@ -366,3 +243,124 @@
</mat-icon>
</span>
</ng-template>
<ng-template #rowDetailTemplate let-row>
<div class="row-detail">
<div class="row-detail__head">
<span class="row-detail__eyebrow">Details</span>
<a
class="author-name author-link"
[routerLink]="['/person', row.candidate.author_id, 'overview']"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: row.candidate.author_id }"
tooltipMaxWidth="500px"
[title]="row.name"
(click)="$event.stopPropagation()">
<h3>{{ row.name }}</h3>
</a>
<div class="row-detail__meta">
<span
class="row-detail__career"
[matTooltip]="careerBucketTooltip(row.candidate.career_bucket)"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
{{ row.candidate.career_bucket ?? '–' }}
</span>
@if (row.areaLabel) {
· {{ row.areaLabel }}
}
· {{ fmtInt(row.candidate.active_years) }} Jahre mit Publikationen
</div>
</div>
<p class="score-caption">
Alle Werte sind Ränge von 0 bis 100 – keine Wahrscheinlichkeiten. 90
heißt: stärker als 90 % der Vergleichsgruppe.
</p>
<div class="score-tiles">
<div
class="score-tile score-tile--primary"
[matTooltip]="row.notScoredReason ?? scoreTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Potenzial</span>
@if (row.score === null) {
<strong class="score-tile__missing">(nicht bewertet)</strong>
} @else {
<strong>{{ fmt1(row.score) }}</strong>
}
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 1 Jahr</span>
<strong>{{ fmt1(row.within[0]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 3 Jahre</span>
<strong>{{ fmt1(row.within[1]) }}</strong>
</div>
<div
class="score-tile"
[matTooltip]="withinTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<span class="score-tile__label">Signal 5 Jahre</span>
<strong>{{ fmt1(row.within[2]) }}</strong>
</div>
</div>
<div class="facts">
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Publikationen der Person."
matTooltipClass="sg-tooltip-wide">
Publikationen
<b>{{ fmtInt(row.candidate.founder_features?.publications) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Patente mit Bezug zur Einrichtung."
matTooltipClass="sg-tooltip-wide">
Patente
<b>{{ fmtInt(row.candidate.founder_features?.patents) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Arbeiten mit Beteiligung aus Unternehmen."
matTooltipClass="sg-tooltip-wide">
Arbeiten mit Industrie
<b>{{
fmtInt(row.candidate.founder_features?.industry_collab_papers)
}}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Zahl der Förderprojekte."
matTooltipClass="sg-tooltip-wide">
Förderprojekte
<b>{{ fmtInt(row.candidate.founder_features?.grants) }}</b>
</app-chip>
<app-chip
variant="outlined"
color="secondary"
matTooltip="Jahre mit mindestens einer Publikation."
matTooltipClass="sg-tooltip-wide">
Aktive Jahre
<b>{{ fmtInt(row.candidate.active_years) }}</b>
</app-chip>
</div>
</div>
</ng-template>
@@ -142,6 +142,10 @@
color: var(--sg-text);
}
tr.detail-row .mat-mdc-cell {
padding: 0;
}
.mat-column-name {
width: 32%;
}
@@ -205,7 +209,7 @@
}
.list__career,
.card__career {
.row-detail__career {
cursor: help;
text-decoration: underline dotted;
text-underline-offset: 2px;
@@ -220,6 +224,14 @@
text-align: right;
}
.list__score-missing {
color: var(--sg-text-soft);
font-size: 11.5px;
font-style: italic;
cursor: help;
white-space: nowrap;
}
.list__within-nums {
color: var(--sg-text-muted);
font-size: 12px;
@@ -238,32 +250,28 @@
font-size: 13.5px;
}
// -- Detail card --------------------------------------------------------
// -- Detail row ---------------------------------------------------------
.card {
margin-top: 16px;
.row-detail {
padding: 18px 20px 20px;
border-top: 1px solid var(--sg-border);
background: var(--sg-surface-muted);
.mat-mdc-card-content {
padding: 20px;
}
h3 {
margin: 0 0 2px;
color: var(--sg-text);
font-size: 20px;
font-size: 18px;
}
}
.card__head {
.row-detail__head {
display: flex;
flex-wrap: wrap;
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
gap: 2px;
}
.card__eyebrow {
.row-detail__eyebrow {
display: block;
margin-bottom: 2px;
color: var(--sg-text-soft);
@@ -273,17 +281,12 @@
text-transform: uppercase;
}
.card__meta {
margin-bottom: 16px;
.row-detail__meta {
margin-bottom: 14px;
color: var(--sg-text-soft);
font-size: 12.5px;
}
.card__flag {
color: var(--sg-error);
cursor: help;
}
.score-caption {
margin: 0 0 12px;
color: var(--sg-text-soft);
@@ -325,6 +328,13 @@
&--primary strong {
color: var(--sg-blue-highlight);
}
&__missing {
color: var(--sg-text-soft);
font-size: 15px;
font-weight: 600;
font-style: italic;
}
}
.facts {
@@ -13,11 +13,14 @@ import { ActivatedRoute, Router } from '@angular/router';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatCardModule } from '@angular/material/card';
import { MatButtonModule } from '@angular/material/button';
import { MatDialog } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatTooltipModule } from '@angular/material/tooltip';
import { RouterLink } from '@angular/router';
import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component';
import {
FounderCandidate,
FounderCandidatePage,
@@ -42,18 +45,21 @@ import {
FOUNDER_ICON,
HELP_OUTLINE_ICON,
INFO_OUTLINE_ICON,
INSIGHTS_ICON,
PERSONS_ICON,
STAR_ICON,
VERIFIED_ICON,
} from '../../../shared/ui/icons';
import { CredentialService } from '../../../shared/services/credential.service';
import { FounderExplainerPanelComponent } from './founder-explainer-panel/founder-explainer-panel.component';
import { FounderFiltersComponent } from '../founder-filters/founder-filters.component';
const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen';
const DEFAULT_THRESHOLD = 90;
/**
* A shortlist row: the generated candidate plus only the values that the
* table derives from it (display name, the 1/3/5-year slice, the headline
* screen reason). Everything else is read from `candidate` directly.
* table derives from it (display name, the 1/3/5-year slice, and the reason a
* profile has no score).
*/
interface FounderRow {
candidate: FounderCandidate;
@@ -61,7 +67,8 @@ interface FounderRow {
areaLabel: string | null;
score: number | null;
within: (number | null)[];
flagLabel: string | null;
/** Explanation shown in the "(nicht bewertet)" tooltip; null when scored. */
notScoredReason: string | null;
}
@Component({
@@ -72,31 +79,36 @@ interface FounderRow {
MatCardModule,
MatButtonModule,
MatIconModule,
MatSlideToggleModule,
MatSliderModule,
MatSlideToggleModule,
MatTooltipModule,
QueryParamPaginatorComponent,
ChipComponent,
DataTableComponent,
DashboardStatisticCardComponent,
PageContainerComponent,
RouterLink,
ComponentTooltipDirective,
FounderFiltersComponent,
],
templateUrl: './founder-dashboard.component.html',
styleUrl: './founder-dashboard.component.scss',
})
export class FounderDashboardComponent {
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly FOUNDER_ICON = FOUNDER_ICON;
readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON;
readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON;
readonly INSIGHTS_ICON = INSIGHTS_ICON;
readonly PERSONS_ICON = PERSONS_ICON;
readonly STAR_ICON = STAR_ICON;
readonly VERIFIED_ICON = VERIFIED_ICON;
readonly statistics = input.required<FounderStatistics>();
readonly candidates = input.required<FounderCandidatePage>();
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly dialog = inject(MatDialog);
private readonly credentials = inject(CredentialService, { optional: true });
/** The university whose cohort is shown; comes from the account profile. */
@@ -113,22 +125,22 @@ export class FounderDashboardComponent {
initialValue: this.route.snapshot.queryParamMap,
});
readonly threshold = computed(
() => Math.max(50, Math.min(100, toNumber(this.queryParams().get('threshold')) ?? 90)),
/** The threshold is opt-in: it only applies when the URL param is present. */
readonly thresholdEnabled = computed(
() => toNumber(this.queryParams().get('threshold')) !== null,
);
readonly threshold = computed(() => {
const value = toNumber(this.queryParams().get('threshold'));
return value === null
? DEFAULT_THRESHOLD
: Math.max(50, Math.min(100, value));
});
readonly screened = computed(
() => this.queryParams().get('screened') === 'true',
);
/** Live value while dragging the slider; committed to the URL on release. */
readonly thresholdDraft = signal<number>(90);
constructor() {
effect(() => this.thresholdDraft.set(this.threshold()), {
allowSignalWrites: true,
});
}
// -- Explanations (tooltips only) --------------------------------------
readonly pageTooltip =
@@ -140,28 +152,18 @@ export class FounderDashboardComponent {
readonly scoreableTooltip =
'Nur diese Personen haben genug Publikationen (mindestens 4), um vom Modell bewertet zu werden. Für alle anderen gibt es keinen Score.';
readonly qualityTooltip = computed(
() =>
`${this.kpis().passed.toLocaleString('de-DE')} von ${this.kpis().total.toLocaleString('de-DE')} Forschenden (${this.kpis().share} %) haben ein vollständiges und plausibles Profil. Nur diese Werte sind gut belastbar.`,
);
readonly shortlistTooltip = computed(
() =>
`Personen mit dem stärksten Gründungspotenzial. Angezeigt werden alle ab einem Rang von ${this.threshold()}. ${
this.screened()
? 'Auffällige Profile sind ausgeblendet.'
: 'Auffällige Profile sind enthalten.'
}`,
);
readonly shortlistTooltip = computed(() => {
const thresholdPart = this.thresholdEnabled()
? `Ab einem Rang von ${this.threshold()}.`
: 'Ohne Mindestwert werden alle Profile angezeigt.';
const screenPart = this.screened()
? 'Auffällige Profile sind ausgeblendet.'
: 'Auffällige Profile sind enthalten.';
return `Personen mit dem stärksten Gründungspotenzial. ${thresholdPart} ${screenPart}`;
});
readonly shortlistSectionTooltip =
'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Regler legt fest, ab welchem Rang jemand in die Liste kommt.';
readonly thresholdTooltip =
'Legt fest, ab welchem Rang Personen in der Shortlist erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte.';
readonly screeningTooltip =
'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Scores dieser Personen sind weniger verlässlich.';
'Hier stehen die Personen mit dem stärksten Gründungspotenzial. Der Mindestwert ist optional: ohne ihn werden alle Profile angezeigt.';
readonly scoreTooltip =
'Rang des Gründungspotenzials von 0 bis 100. 90 heißt: stärker als 90 % der rund 9.000 vergleichbaren Wissenschaftler:innen anderer Universitäten. Kein Wahrscheinlichkeitswert.';
@@ -172,45 +174,52 @@ export class FounderDashboardComponent {
readonly evidenceTooltip =
'Die Signale, auf denen die Einschätzung beruht: Publikationen, Patente, Förderungen und gemeinsame Arbeiten mit der Industrie. Die Werte sind Zählungen, keine Bewertung der Person.';
readonly flagTooltip =
'Möglicherweise wurden mehrere Personen mit gleichem Namen zusammengeführt oder die Karriereangaben sind unplausibel. Die Werte sind dann unsicher. Bitte Identität und Profil prüfen, bevor Sie die Person ansprechen.';
readonly careerBucketTooltip = careerBucketDescription;
readonly thresholdTooltip =
'Legt fest, ab welchem Rang Personen in der Liste erscheinen. 90 ist streng und zeigt nur die obersten 10 % der Vergleichsgruppe; 50 zeigt die obere Hälfte. Ohne Mindestwert werden alle Profile angezeigt.';
readonly thresholdToggleTooltip =
'Standardmäßig werden alle Profile angezeigt. Aktiviere den Mindestwert, um nur Personen ab einem bestimmten Rang zu sehen.';
readonly screeningTooltip =
'Blendet Profile aus, die vermutlich unvollständig, falsch datiert oder mit anderen Personen vermischt sind. Die Werte dieser Personen sind weniger verlässlich. Ist die Option aus, werden alle Profile angezeigt.';
// -- KPIs ---------------------------------------------------------------
readonly kpis = computed(() => {
const stats = this.statistics();
const total = stats.provenance?.document_count ?? 0;
const scoreable = stats.overall?.in_population ?? 0;
const passed = stats.overall?.screened ?? 0;
const share = total ? Math.round((passed / total) * 100) : 0;
const shortlisted = this.candidates().total ?? 0;
return { total, scoreable, passed, share, shortlisted };
return { total, scoreable, shortlisted };
});
/** True when the pipeline has produced at least one score for this university. */
readonly hasScores = computed(
() => (this.statistics().overall?.in_population ?? 0) > 0,
);
readonly scoreableShare = computed(() => {
const { total, scoreable } = this.kpis();
return total ? Math.round((scoreable / total) * 100) : 0;
});
readonly qualityDetail = computed(
() => `${this.kpis().share} % der Forschenden`,
);
readonly scoreableDetail = computed(
() => `${this.scoreableShare()} % der Forschenden`,
);
readonly shortlistDetail = computed(() => `ab Rang ${this.threshold()}`);
readonly shortlistDetail = computed(() =>
this.thresholdEnabled() ? `ab Rang ${this.threshold()}` : 'alle Profile',
);
readonly emptyListMessage = computed(() =>
this.screened()
? `Niemand erreicht den Mindestwert von ${this.threshold()} und hat zugleich ein unauffälliges Profil. Senken Sie den Mindestwert oder blenden Sie auffällige Profile wieder ein.`
: `Niemand erreicht den Mindestwert von ${this.threshold()}. Senken Sie den Mindestwert, um mehr Personen zu sehen.`,
this.thresholdEnabled()
? `Niemand erreicht den Mindestwert von ${this.threshold()}${
this.screened() ? ' und hat zugleich ein unauffälliges Profil' : ''
}. Senken Sie den Mindestwert${
this.screened()
? ' oder blenden Sie auffällige Profile wieder ein'
: ' oder deaktivieren Sie ihn'
}, um mehr Profile zu sehen.`
: this.screened()
? 'Mit ausgeblendeten auffälligen Profilen wurde niemand gefunden. Blenden Sie auffällige Profile wieder ein, um mehr zu sehen.'
: 'Für diese Auswahl wurden keine Personen gefunden. Setzen Sie die Filter zurück, um mehr Profile zu sehen.',
);
// -- Shortlist ----------------------------------------------------------
@@ -229,6 +238,8 @@ export class FounderDashboardComponent {
viewChild.required<TemplateRef<void>>('withinHeader');
private readonly evidenceHeader =
viewChild.required<TemplateRef<void>>('evidenceHeader');
readonly detailTemplate =
viewChild.required<TemplateRef<FounderRow>>('rowDetailTemplate');
readonly columns = computed<GenericColumn<FounderRow>[]>(() => [
{
@@ -267,32 +278,36 @@ export class FounderDashboardComponent {
(this.candidates().elements ?? []).map((c) => toRow(c)),
);
readonly selectedId = signal<string | null>(null);
readonly selectedRow = computed<FounderRow | null>(() => {
const id = this.selectedId();
const rows = this.rows();
if (id) {
return rows.find((r) => r.candidate.author_id === id) ?? null;
}
return rows[0] ?? null;
});
selectCandidate(id: string): void {
this.selectedId.set(id);
}
// -- Controls -----------------------------------------------------------
/** Discrete label inside the Material slider thumb. */
/** Live slider value while dragging; committed to the URL on release. */
readonly thresholdDraft = signal<number>(DEFAULT_THRESHOLD);
constructor() {
effect(() => this.thresholdDraft.set(this.threshold()));
}
readonly formatThreshold = (value: number): string => String(value);
/** Enables or disables the threshold filter (writes/removes the URL param). */
onThresholdEnabledChange(enabled: boolean): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: {
threshold: enabled ? this.thresholdDraft() : null,
page: 0,
},
queryParamsHandling: 'merge',
});
}
onSliderInput(value: number): void {
if (Number.isFinite(value)) this.thresholdDraft.set(value);
}
/** Commits the threshold value to the URL. */
onSliderCommit(value = this.thresholdDraft()): void {
if (!Number.isFinite(value)) return;
if (!this.thresholdEnabled() || !Number.isFinite(value)) return;
this.thresholdDraft.set(value);
if (value === this.threshold()) return;
void this.router.navigate([], {
@@ -302,17 +317,40 @@ export class FounderDashboardComponent {
});
}
/**
* `screened=false` means "only rejected profiles" on the backend, so turning
* the toggle off must REMOVE the param (everyone), not set false.
*/
onScreenedChange(checked: boolean): void {
void this.router.navigate([], {
relativeTo: this.route,
queryParams: { screened: checked ? 'true' : 'false', page: 0 },
queryParams: { screened: checked ? 'true' : null, page: 0 },
queryParamsHandling: 'merge',
});
}
onLowerThreshold(): void {
const next = Math.max(50, this.threshold() - 10);
this.onSliderCommit(next);
void this.router.navigate([], {
relativeTo: this.route,
queryParams: { threshold: next, page: 0 },
queryParamsHandling: 'merge',
});
}
/** Opens the global model explanation; independent of the selection. */
openExplainer(): void {
this.dialog.open(FounderExplainerPanelComponent, {
panelClass: 'sg-side-panel',
position: { right: '0', top: '0' },
height: '100dvh',
width: 'min(520px, 100vw)',
maxWidth: '100vw',
maxHeight: '100dvh',
ariaLabel: 'Modell-Erklärung zum Gründungspotenzial',
autoFocus: 'first-tabbable',
restoreFocus: true,
});
}
// -- Formatting helpers for the template --------------------------------
@@ -323,24 +361,32 @@ export class FounderDashboardComponent {
function toRow(c: FounderCandidate): FounderRow {
const fp = c.founder_potential;
const reasons = c.screen.reasons ?? [];
const score = fp?.external_percentile ?? null;
return {
candidate: c,
name: c.display_name ?? c.author_id,
areaLabel: c.founder_features?.publication_research_area_label ?? null,
score: fp?.external_percentile ?? null,
score,
within: [
fp?.external_percentile_within_1y ?? null,
fp?.external_percentile_within_3y ?? null,
fp?.external_percentile_within_5y ?? null,
],
flagLabel:
reasons.length > 0
? (SCREEN_REASON_LABELS[reasons[0]] ?? reasons[0])
: null,
notScoredReason: score === null ? notScoredReason(c) : null,
};
}
/** Plain-language explanation for why a profile has no score. */
function notScoredReason(c: FounderCandidate): string {
const reasons = (c.screen.reasons ?? []).map(
(reason) => SCREEN_REASON_LABELS[reason] ?? reason,
);
const detail = reasons.length
? ` Gründe: ${reasons.join(', ')}.`
: '';
return `Für dieses Profil liegt kein Score vor. Das Modell braucht mindestens 4 Publikationen und ein vollständiges, plausibles Profil.${detail}`;
}
function toNumber(value: string | null): number | null {
if (value === null || value === '') return null;
const parsed = Number(value);
@@ -0,0 +1,116 @@
<div class="explainer">
<header class="explainer__head">
<div class="explainer__heading">
<p class="explainer__eyebrow">Modell-Erklärung</p>
<h2 class="explainer__title">Woher kommt das Gründungspotenzial?</h2>
</div>
<button
mat-icon-button
type="button"
class="explainer__close"
aria-label="Erklärung schließen"
(click)="close()">
<mat-icon>{{ CLOSE_ICON }}</mat-icon>
</button>
</header>
<div class="explainer__body">
@if (loading()) {
<div class="explainer__state">
<mat-spinner diameter="32" />
<p>Modellinformationen werden geladen …</p>
</div>
} @else if (error()) {
<div class="explainer__state explainer__state--error">
<mat-icon>{{ ERROR_OUTLINE_ICON }}</mat-icon>
<p>Die Modellinformationen konnten nicht geladen werden.</p>
<button mat-stroked-button type="button" (click)="load()">
Erneut versuchen
</button>
</div>
} @else {
<p class="explainer__lead">
Das Modell schätzt aus Publikationen, Patenten, Förderungen und
Industriekontakten, wie wahrscheinlich eine Person gründet. Die Balken
zeigen, auf welche Merkmale sich das Modell insgesamt am stärksten
stützt.
</p>
<div class="explainer__metrics" aria-label="Modellgüte">
<span>
ROC-AUC <strong>{{ fmtAuc(modelInfo()?.oof_roc_auc) }}</strong>
</span>
<span>
PR-AUC <strong>{{ fmtAuc(modelInfo()?.oof_pr_auc) }}</strong>
</span>
@if (modelInfo()?.reference_cohort_size) {
<span>
Referenz
<strong>{{ fmtInt(modelInfo()?.reference_cohort_size) }}</strong>
Profile
</span>
}
@if (modelInfo()?.reference_founders) {
<span>
<strong>{{ fmtInt(modelInfo()?.reference_founders) }}</strong>
Gründer:innen
</span>
}
</div>
@if (entries().length) {
<div
echarts
[options]="chartOptions()"
[autoResize]="true"
class="explainer__chart"
[style.height.px]="chartHeight()"
role="img"
aria-label="Balkendiagramm: Einfluss der Merkmale auf die Gründungsprognose"></div>
<section
class="explainer__origin"
aria-labelledby="explainer-origin-title">
<h3 id="explainer-origin-title">Woher kommen die Zahlen?</h3>
<p>
Für jedes Merkmal – zum Beispiel Publikationen pro Jahr, Patente
oder Industriekontakte – macht das Modell denselben Test:
</p>
<ol class="explainer__steps">
<li>
Ein Merkmal wird zufällig vertauscht, alle anderen bleiben gleich.
</li>
<li>Das Modell bewertet dieselben Personen erneut.</li>
<li>
Je stärker die Trefferqualität danach sinkt, desto größer ist der
Balken.
</li>
</ol>
<p>
Ein großer Balken heißt also: Das Modell verlässt sich stark auf
dieses Merkmal. Die Prozentwerte sind der Anteil an der
Gesamtbedeutung der angezeigten Merkmale. Sie sind keine Punkte,
keine Wahrscheinlichkeit und kein Beitrag einer einzelnen Person.
Die Werte gelten für das Modell insgesamt und sind für alle Personen
gleich.
</p>
</section>
<p class="explainer__note">
Ausgeblendet: Das wichtigste Trainingsmerkmal (Patent-Fachgebiet) ist
im aktuellen Datenbestand für alle gleich und trennt daher niemanden.
Institutionsmerkmale sind im Produktionsmodell nicht enthalten.
</p>
} @else {
<p class="explainer__note">
Für dieses Modell sind keine darstellbaren Merkmale verfügbar.
</p>
}
<p class="explainer__caveat">
Die Werte beschreiben das trainierte Modell, nicht die einzelne Person.
Sie belegen keinen Ursache-Wirkungs-Zusammenhang.
</p>
}
</div>
</div>
@@ -0,0 +1,161 @@
:host {
display: block;
height: 100%;
}
.explainer {
display: flex;
flex-direction: column;
height: 100%;
background: var(--sg-card-bg);
color: var(--sg-text);
}
.explainer__head {
display: flex;
flex: none;
align-items: flex-start;
gap: 12px;
padding: 20px 18px 14px 24px;
border-bottom: 1px solid var(--sg-border);
}
.explainer__heading {
flex: 1;
min-width: 0;
}
.explainer__eyebrow {
margin: 0 0 4px;
color: var(--sg-text-soft);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.explainer__title {
margin: 0;
color: var(--sg-text);
font-size: 19px;
font-weight: 700;
line-height: 1.3;
}
.explainer__close {
flex: none;
margin: -4px -4px 0 0;
color: var(--sg-text-muted);
}
.explainer__body {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 18px 24px 24px;
}
.explainer__lead {
margin: 0 0 14px;
color: var(--sg-text-muted);
font-size: 13px;
line-height: 1.55;
}
.explainer__metrics {
display: flex;
flex-wrap: wrap;
gap: 6px 14px;
margin-bottom: 18px;
padding: 10px 12px;
border: 1px solid var(--sg-border);
border-radius: 10px;
background: var(--sg-surface-muted);
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.4;
strong {
color: var(--sg-text);
font-variant-numeric: tabular-nums;
}
}
.explainer__chart {
width: 100%;
}
.explainer__origin {
margin-top: 18px;
padding: 14px 16px 16px;
border: 1px solid var(--sg-border);
border-radius: 12px;
background: var(--sg-surface-muted);
h3 {
margin: 0 0 8px;
color: var(--sg-text);
font-size: 13px;
font-weight: 700;
}
p {
margin: 0;
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.5;
}
}
.explainer__steps {
margin: 10px 0;
padding-left: 18px;
color: var(--sg-text-muted);
font-size: 12px;
line-height: 1.5;
li + li {
margin-top: 4px;
}
li::marker {
color: var(--sg-primary);
font-weight: 700;
}
}
.explainer__note,
.explainer__caveat {
margin: 10px 0 0;
color: var(--sg-text-soft);
font-size: 11.5px;
line-height: 1.5;
}
.explainer__caveat {
margin-top: 16px;
padding-top: 12px;
border-top: 1px solid var(--sg-border);
}
.explainer__state {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 48px 12px;
color: var(--sg-text-muted);
font-size: 13px;
text-align: center;
p {
margin: 0;
}
&--error mat-icon {
width: 30px;
height: 30px;
color: var(--sg-error);
font-size: 30px;
}
}
@@ -0,0 +1,242 @@
import {
ChangeDetectionStrategy,
Component,
computed,
inject,
signal,
} from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogRef } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { FounderModelInfo, MultiplicatorsService } from '../../../../api';
import { ChartThemeService } from '../../../../shared/services/chart-theme.service';
import { CLOSE_ICON, ERROR_OUTLINE_ICON } from '../../../../shared/ui/icons';
import { fmtInt } from '../../founder-potential.utils';
/**
* German labels for the features the founder classifier exposes. Features
* missing here fall back to a readable version of their technical name.
*/
const FEATURE_LABELS: Record<string, string> = {
pub_rate: 'Publikationen pro Jahr',
first_publication_year: 'Jahr der ersten Publikation',
industry_collab_at_index: 'Publikationen mit Industriebeteiligung',
career_age_at_index: 'Karrierealter',
patents_at_index: 'Patente',
patent_rate: 'Patente pro Jahr',
patent_research_area_46: 'Patent-Fachgebiet: Informatik',
publication_research_area_32: 'Fachgebiet: Biomedizin & Klinik',
years_since_first_grant: 'Jahre seit erster Förderung',
grant_research_area_51: 'Förder-Fachgebiet: Physik',
};
/** One bar in the chart, with the share of the displayed total. */
interface ImportanceEntry {
label: string;
share: number;
importance: number;
std: number | null;
}
function isVisibleFeature(feature: string): boolean {
// Constant in this deployment (no IPC-to-FOR mapping) and dropped from the
// production bundle, respectively. Showing them would mislead locally.
return (
feature !== 'patent_research_area_n.' &&
!feature.startsWith('institution_')
);
}
function featureLabel(feature: string): string {
return (
FEATURE_LABELS[feature] ??
feature
.replace(/_/g, ' ')
.replace(/\b\w/g, (letter) => letter.toUpperCase())
);
}
function fmtShare(value: number): string {
return value.toLocaleString('de-DE', {
minimumFractionDigits: 1,
maximumFractionDigits: 1,
});
}
function fmtImportance(value: number): string {
return value.toLocaleString('de-DE', {
minimumFractionDigits: 3,
maximumFractionDigits: 3,
});
}
function fmtAuc(value: number | null | undefined): string {
if (value === null || value === undefined) return '—';
return value.toLocaleString('de-DE', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
/**
* Right-hand overlay that explains where the founder score comes from.
*
* It shows the model's global permutation importances, not per-person
* contributions: the API exposes only raw feature values per candidate.
*/
@Component({
selector: 'app-founder-explainer-panel',
standalone: true,
imports: [
MatButtonModule,
MatIconModule,
MatProgressSpinnerModule,
NgxEchartsDirective,
],
templateUrl: './founder-explainer-panel.component.html',
styleUrl: './founder-explainer-panel.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FounderExplainerPanelComponent {
readonly CLOSE_ICON = CLOSE_ICON;
readonly ERROR_OUTLINE_ICON = ERROR_OUTLINE_ICON;
private readonly service = inject(MultiplicatorsService);
private readonly dialogRef = inject(
MatDialogRef<FounderExplainerPanelComponent>,
);
private readonly chartTheme = inject(ChartThemeService);
readonly modelInfo = signal<FounderModelInfo | null>(null);
readonly loading = signal(false);
readonly error = signal(false);
readonly fmtInt = fmtInt;
readonly fmtAuc = fmtAuc;
readonly entries = computed<ImportanceEntry[]>(() => {
const importances = (this.modelInfo()?.importances ?? []).filter((item) =>
isVisibleFeature(item.feature),
);
const total = importances.reduce(
(sum, item) => sum + item.importance_mean,
0,
);
if (total <= 0) return [];
return [...importances]
.sort((a, b) => b.importance_mean - a.importance_mean)
.map((item) => ({
label: featureLabel(item.feature),
share: (item.importance_mean / total) * 100,
importance: item.importance_mean,
std: item.importance_std ?? null,
}));
});
/** Enough vertical room for every bar; the panel body scrolls if needed. */
readonly chartHeight = computed(() =>
Math.max(240, this.entries().length * 44 + 24),
);
readonly chartOptions = computed<EChartsOption>(() => {
const colors = this.chartTheme.colors();
const entries = this.entries();
return {
animationDuration: 350,
grid: { left: 4, right: 50, top: 8, bottom: 4, containLabel: true },
tooltip: {
trigger: 'item',
confine: true,
backgroundColor: colors.tooltipBg,
borderColor: colors.tooltipBorder,
textStyle: { color: colors.tooltipTextColor, fontSize: 12 },
formatter: (params: any) => {
const entry = entries[params.dataIndex];
if (!entry) return '';
const std =
entry.std !== null
? ` ± ${fmtImportance(entry.std)}`
: '';
return [
`<strong>${entry.label}</strong>`,
`Anteil an der Gesamtbedeutung: <strong>${fmtShare(entry.share)} %</strong>`,
`Beitrag zur Trefferqualität: ${fmtImportance(entry.importance)}${std}`,
].join('<br/>');
},
},
xAxis: {
type: 'value',
axisLabel: {
color: colors.mutedTextColor,
fontSize: 11,
formatter: (value: any) =>
`${value.toLocaleString('de-DE', { maximumFractionDigits: 0 })} %`,
},
axisLine: { show: false },
axisTick: { show: false },
splitLine: { lineStyle: { color: colors.splitLine } },
},
yAxis: {
type: 'category',
inverse: true,
data: entries.map((entry) => entry.label),
axisLabel: {
color: colors.text,
fontSize: 12,
width: 170,
overflow: 'break',
lineHeight: 15,
},
axisLine: { show: false },
axisTick: { show: false },
},
series: [
{
type: 'bar',
data: entries.map((entry) => entry.share),
barMaxWidth: 20,
itemStyle: {
color: colors.primary,
borderRadius: [0, 4, 4, 0],
},
label: {
show: true,
position: 'right',
color: colors.text,
fontSize: 11,
formatter: (params: any) => `${fmtShare(params.value)} %`,
},
},
],
};
});
constructor() {
this.load();
}
load(): void {
this.loading.set(true);
this.error.set(false);
this.service.getFounderModelInfo().subscribe({
next: (info) => {
this.modelInfo.set(info);
this.loading.set(false);
},
error: () => {
this.error.set(true);
this.loading.set(false);
},
});
}
close(): void {
this.dialogRef.close();
}
}
@@ -0,0 +1,28 @@
<div class="content">
<app-query-param-input
queryParamKey="name"
label="Name suchen"
[debounceTime]="300" />
<div class="filter-grid">
<app-query-param-selector
[options]="careerOptions"
queryParamKey="careerBucket"
label="Karrierestufe"
[multiple]="true"
matTooltip="Early: 1–4 aktive Publikationsjahre, Emerging: 5–9, Established: 10–14, Senior: 15 oder mehr."
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above" />
<app-query-param-selector
[options]="researchAreaOptions()"
queryParamKey="researchArea"
label="Forschungsgebiet"
[multiple]="true"
matTooltip="Filtert nach dem Fachgebiet der Publikationen (2-stelliger FOR-Code)."
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above" />
</div>
<app-selected-filters [observers]="observers" />
</div>
@@ -0,0 +1,12 @@
.content {
display: flex;
flex-direction: column;
gap: 1rem;
}
.filter-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
gap: 1rem;
align-items: start;
}
@@ -0,0 +1,89 @@
import { Component, computed, input } from '@angular/core';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CareerBucket, FounderStatistics } from '../../../api';
import { QueryParamInputComponent } from '../../../shared/ui/query-param-input/query-param-input.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../../shared/ui/query-param-selector/query-param-selector.component';
import {
FilterObserver,
SelectedFiltersComponent,
} from '../../../shared/ui/selected-filters/selected-filters.component';
import { PERSON_ICON, SEARCH_ICON } from '../../../shared/ui/icons';
@Component({
selector: 'app-founder-filters',
standalone: true,
imports: [
MatTooltipModule,
QueryParamInputComponent,
QueryParamSelectorComponent,
SelectedFiltersComponent,
],
templateUrl: './founder-filters.component.html',
styleUrl: './founder-filters.component.scss',
})
export class FounderFiltersComponent {
/** Stats carry the research-area codes/labels that the backend filters on. */
readonly statistics = input.required<FounderStatistics>();
readonly careerOptions: SelectorOption[] = [
{ value: CareerBucket.Early, display_name: 'Early (1–4 Jahre)' },
{ value: CareerBucket.Emerging, display_name: 'Emerging (5–9 Jahre)' },
{
value: CareerBucket.Established,
display_name: 'Established (10–14 Jahre)',
},
{ value: CareerBucket.Senior, display_name: 'Senior (15+ Jahre)' },
];
/**
* The backend filters research areas by the 2-digit FOR division code
* (`founding_features.publication_research_area`), so the selector must use
* the code as its value, not the human-readable label.
*/
readonly researchAreaOptions = computed<SelectorOption[]>(() =>
(this.statistics().research_areas ?? [])
.filter((area) => !!area.code)
.map((area) => ({
value: area.code,
display_name: area.label ? `${area.label} (${area.code})` : area.code,
}))
.sort((a, b) => a.display_name.localeCompare(b.display_name, 'de')),
);
readonly observers: FilterObserver[] = [
{
id: 'name',
queryParamKey: 'name',
icon: SEARCH_ICON,
removable: true,
template: undefined,
},
{
id: 'researchArea',
queryParamKey: 'researchArea',
icon: SEARCH_ICON,
valueFormatter: (value) =>
value
.split(',')
.map((code) => {
const area = this.statistics().research_areas?.find(
(a) => a.code === code,
);
return area?.label ? `${area.label} (${code})` : code;
})
.join(', '),
removable: true,
},
{
id: 'career',
queryParamKey: 'careerBucket',
icon: PERSON_ICON,
valueFormatter: (value) => value.split(',').join(', '),
removable: true,
},
];
}
@@ -92,15 +92,6 @@ export const METRIC_GROUP_META: Record<
},
};
/** German labels for the funnel stages, keyed by their stable key. */
export const FUNNEL_STAGE_LABELS: Record<string, string> = {
ALL: 'Alle Forschenden im Index',
IN_POPULATION: 'Vom Modell bewertbar (mind. 4 Publikationen)',
NOT_SUSPICIOUS: 'Kein zusammengeführtes Profil',
CAREER_AGE_PLAUSIBLE: 'Plausible Karrieredauer (max. 40 Jahre)',
MIN_PUBLICATIONS: 'Mind. 7 Publikationen',
};
/** Ordered metric definitions for the researcher detail table. */
export interface MetricDef {
key: keyof ResearcherMetrics;
@@ -78,20 +78,6 @@
}
}
.warning {
display: inline-flex;
align-items: center;
gap: 3px;
color: var(--sg-warning);
cursor: help;
&__icon {
width: 13px;
height: 13px;
font-size: 13px;
}
}
.th-help {
display: inline-flex;
align-items: center;
@@ -12,7 +12,6 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
MultiplierTag,
ResearcherSummary,
@@ -206,6 +205,9 @@ export class MultipliersDashboardComponent {
};
openNetwork(row: MultiplierRow): void {
void this.router.navigate(['/founders', row.researcher.author_id]);
void this.router.navigate([
'/collaboration-network',
row.researcher.author_id,
]);
}
}
@@ -1,13 +1,22 @@
<app-page-container
[eyebrow]="'Multiplikatoren · ' + universityName()"
[title]="unavailable()?.title ?? name()"
[subtitle]="unavailable()?.body ?? null"
[titleTooltip]="unavailable() ? null : pageTooltip">
<div pageMeta class="meta-block">
<a class="back-link" routerLink="/multipliers">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Zurück zur Multiplikatoren-Übersicht
</a>
<h3 class="author-name">
@if (researcher()?.author_id; as authorId) {
<a
class="author-name__link"
[routerLink]="['/person', authorId, 'overview']"
[appComponentTooltip]="AuthorTooltipComponent"
[tooltipInputs]="{ authorId: authorId }"
tooltipMaxWidth="500px">
{{ name() }}
</a>
} @else {
{{ name() }}
}
</h3>
@if (!unavailable()) {
<div class="meta-line">
@if (careerBucket()) {
@@ -20,17 +29,6 @@
{{ fmtInt(nWorks()) }} Publikationen ·
{{ fmtInt(activeYears()) }} aktive Jahre
</span>
@if (suspicious()) {
<span
class="suspicious"
[matTooltip]="suspiciousTooltip"
matTooltipClass="sg-tooltip-wide"
matTooltipPosition="above">
<mat-icon>{{ WARNING_ICON }}</mat-icon>
Zusammengeführtes Profil · Daten vorsichtig interpretieren
<mat-icon class="help-icon">{{ HELP_OUTLINE_ICON }}</mat-icon>
</span>
}
</div>
@if (tags().length) {
<div class="tags">
@@ -88,18 +86,19 @@
<span class="legend__item">Knotengröße = aktive Jahre</span>
</div>
<p class="graph-hint">
Personen anklicken, um ihr Profil zu öffnen · ziehen zum Verschieben ·
scrollen zum Zoomen
<span class="graph-hint__desktop">
Personen anklicken, um ihr Profil zu öffnen · ziehen zum Verschieben ·
scrollen zum Zoomen
</span>
</p>
<div class="case-grid">
<mat-card appearance="outlined" class="netbox">
<mat-card-content>
<mat-card-content class="netbox__content">
@if (network(); as net) {
@if ((net.nodes?.length ?? 0) > 0) {
<app-multiplier-network-graph
[network]="net"
[height]="640"
(nodeClick)="onNodeClick($event)" />
} @else {
<div class="netbox__empty">Kein Netzwerk verfügbar.</div>
@@ -147,8 +146,8 @@
</mat-icon>
</h2>
<p class="metrics-caption">
Rang 0–100 im Vergleich zu Personen derselben Karrierestufe.
Ab 85 % wird ein Rollen-Badge vergeben.
Rang 0–100 im Vergleich zu Personen derselben Karrierestufe. Ab
85 % wird ein Rollen-Badge vergeben.
</p>
@for (group of metricGroups(); track group.key) {
<div class="metric-group">
@@ -3,26 +3,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 4px;
margin-bottom: 6px;
color: var(--sg-text-muted);
font-size: 13px;
text-decoration: none;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
&:hover {
color: var(--sg-blue-highlight);
}
}
.meta-block {
margin-top: 8px;
}
@@ -47,28 +27,6 @@
margin: 2px 0 8px;
}
.suspicious {
display: inline-flex;
align-items: center;
gap: 4px;
color: var(--sg-error);
font-size: 12.5px;
cursor: help;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
.help-icon {
color: var(--sg-text-soft);
font-size: 15px;
width: 15px;
height: 15px;
}
}
.tags {
display: flex;
flex-wrap: wrap;
@@ -86,6 +44,20 @@
margin: 8px 0 0;
color: var(--sg-text-soft);
font-size: 12px;
&__touch {
display: none;
}
}
@media (hover: none), (pointer: coarse) {
.graph-hint__desktop {
display: none;
}
.graph-hint__touch {
display: inline;
}
}
.legend {
@@ -143,22 +115,45 @@
}
.netbox {
display: flex;
flex-direction: column;
background: var(--sg-surface-muted);
overflow: hidden;
height: 100%;
// Keep the chart usable even when the surrounding grid row has no
// definite height (single-column phone layout).
min-height: clamp(420px, 58vh, 760px);
.mat-mdc-card-content {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
padding: 0;
}
&__empty {
height: 640px;
display: flex;
flex: 1 1 auto;
align-items: center;
justify-content: center;
color: var(--sg-text-soft);
}
}
.netbox__content {
display: flex;
flex: 1 1 auto;
flex-direction: column;
min-height: 0;
}
app-multiplier-network-graph {
display: block;
flex: 1 1 auto;
min-height: 0;
}
.detail-card {
overflow: hidden;
@@ -236,7 +231,25 @@
line-height: 1.4;
}
}
.author-name {
margin: 0;
color: var(--sg-text);
}
.author-name__link {
color: inherit;
text-decoration: none;
&:hover {
text-decoration: underline;
}
&:focus-visible {
border-radius: 2px;
outline: 2px solid var(--sg-blue-highlight);
outline-offset: 2px;
}
}
.metric-label {
cursor: help;
text-decoration: underline dotted;
@@ -312,9 +325,49 @@
@media (max-width: 1000px) {
.case-grid {
grid-template-columns: 1fr;
gap: 20px;
}
.netbox {
// The grid row no longer gives the card a definite height here, so give
// the chart an explicit viewport-based height instead of collapsing.
height: auto;
min-height: 0;
}
// The legend sits directly above the graph in the single-column layout, so
// it does not need to stick, and the narrower column needs tighter wrapping.
.legend {
position: static;
margin-top: 16px;
padding: 6px 0;
gap: 6px 12px;
font-size: 11.5px;
line-height: 1.35;
}
app-multiplier-network-graph,
.netbox__empty {
height: 420px;
flex: none;
height: clamp(340px, 52vh, 500px);
}
}
@media (max-width: 700px) {
.case-grid {
gap: 16px;
margin-top: 18px;
}
.detail-card .mat-mdc-card-content {
padding: 14px;
}
.network-footer {
margin-top: 28px;
}
.unavailable .mat-mdc-card-content {
padding: 20px;
}
}
@@ -1,6 +1,13 @@
import { Component, computed, inject, input, TemplateRef, viewChild } from '@angular/core';
import {
Component,
computed,
inject,
input,
TemplateRef,
viewChild,
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, RouterModule } from '@angular/router';
import { Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
@@ -36,8 +43,9 @@ import {
HELP_OUTLINE_ICON,
INFO_OUTLINE_ICON,
PERSON_OFF_ICON,
WARNING_ICON,
} from '../../../shared/ui/icons';
import { ComponentTooltipDirective } from '../../../directives/component-tooltip.directive';
import { AppAuthorTooltipComponent } from '../../../shared/ui/app-author-tooltip/app-author-tooltip.component';
const ROLE_ORDER = ['ego', 'cohort', 'mentee', 'industry', 'external'];
const FALLBACK_UNIVERSITY = 'Universität Duisburg-Essen';
@@ -70,7 +78,6 @@ interface MetricGroup {
standalone: true,
imports: [
CommonModule,
RouterModule,
MatButtonModule,
MatCardModule,
MatIconModule,
@@ -81,17 +88,18 @@ interface MetricGroup {
ChipComponent,
MultiplierRoleScoresComponent,
PageContainerComponent,
RouterLink,
ComponentTooltipDirective,
],
templateUrl: './researcher-network.component.html',
styleUrl: './researcher-network.component.scss',
})
export class ResearcherNetworkComponent {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly WARNING_ICON = WARNING_ICON;
readonly PERSON_OFF_ICON = PERSON_OFF_ICON;
readonly HELP_OUTLINE_ICON = HELP_OUTLINE_ICON;
readonly INFO_OUTLINE_ICON = INFO_OUTLINE_ICON;
readonly AuthorTooltipComponent = AppAuthorTooltipComponent;
readonly page = input.required<ResearcherPageState>();
private readonly router = inject(Router);
@@ -146,10 +154,11 @@ export class ResearcherNetworkComponent {
this.researcher()?.author_id ??
'Unbekannt',
);
readonly careerBucket = computed(() => this.researcher()?.career_bucket ?? null);
readonly careerBucket = computed(
() => this.researcher()?.career_bucket ?? null,
);
readonly activeYears = computed(() => this.researcher()?.active_years ?? 0);
readonly nWorks = computed(() => this.researcher()?.n_works ?? 0);
readonly suspicious = computed(() => this.researcher()?.suspicious_profile ?? false);
readonly tags = computed(() => this.researcher()?.tags ?? []);
readonly tagLabel = tagLabel;
readonly tagDescription = tagDescription;
@@ -159,9 +168,6 @@ export class ResearcherNetworkComponent {
readonly pageTooltip =
'Das Netzwerk zeigt, mit wem diese Person gemeinsam publiziert hat. Je dicker die Linie, desto häufiger haben die beiden zusammengearbeitet.';
readonly suspiciousTooltip =
'Bei diesem Profil wurden vermutlich mehrere Personen vermischt, zum Beispiel wegen gleicher Namen oder einer unplausibel langen Karriere. Die Angaben zu Publikationen, Netzwerk und Rollen sind deshalb unsicher.';
readonly rolesTooltip =
'Wie stark die drei Rollen ausgeprägt sind. Ab 85 % wird ein Badge vergeben.';
@@ -189,8 +195,9 @@ export class ResearcherNetworkComponent {
private readonly metricTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricTemplate');
private readonly metricValueTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricValueTemplate');
private readonly metricValueTemplate = viewChild.required<
TemplateRef<MetricRow>
>('metricValueTemplate');
private readonly metricRankTemplate =
viewChild.required<TemplateRef<MetricRow>>('metricRankTemplate');
private readonly metricHeader =
@@ -88,13 +88,13 @@
</div>
<mat-card-content class="uh-chart-viewport">
<div
echarts
[options]="level.options"
[autoResize]="true"
(chartClick)="onNodeClick($event, i)"
class="uh-chart"
[style.height.px]="level.height"></div>
@if (expanded()) {
<div
#chartHost
appPassiveWheel
class="uh-chart"
[style.height.px]="level.height"></div>
}
</mat-card-content>
</mat-card>
}
@@ -66,11 +66,14 @@
.uh-row {
display: flex;
flex-grow: 1;
flex-grow: 0;
flex-shrink: 0;
flex-basis: auto;
flex-direction: row;
flex-wrap: nowrap;
align-items: stretch;
gap: var(--uh-gap);
height: var(--uh-row-height);
overflow-x: auto;
overflow-y: hidden;
padding-bottom: 2px;
@@ -132,6 +135,7 @@
flex: 1 1 100%;
display: flex;
flex-direction: column;
min-height: 0;
overflow: hidden;
}
@@ -167,13 +171,14 @@
}
.uh-chart-viewport {
flex: 1 1 auto;
min-height: 0;
overflow-x: hidden;
overflow-y: auto;
height: 100%;
padding: 0 !important;
}
.uh-chart {
height: 100% !important;
width: 100%;
height: 100% !important;
}
@@ -1,6 +1,7 @@
import {
Component,
DestroyRef,
ElementRef,
OnInit,
signal,
inject,
@@ -10,10 +11,10 @@ import {
EventEmitter,
effect,
untracked,
viewChild,
} from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Router, ActivatedRoute } from '@angular/router';
import { NgxEchartsDirective } from 'ngx-echarts';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatCardModule } from '@angular/material/card';
@@ -21,7 +22,8 @@ import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatChipsModule } from '@angular/material/chips';
import { MatTooltipModule } from '@angular/material/tooltip';
import type { EChartsOption } from 'echarts';
import type { ECharts, EChartsOption } from 'echarts';
import { PassiveWheelDirective } from '../../../directives/passive-wheel.directive';
import { CredentialService } from '../../../shared/services/credential.service';
import { ChartThemeService } from '../../../shared/services/chart-theme.service';
import { HierarchyEditDialogComponent } from './hierarchy-edit-dialog/hierarchy-edit-dialog.component';
@@ -48,6 +50,9 @@ interface TreeLevel {
const QUERY_PARAM_PATH = 'path';
const QUERY_PARAM_LANG = 'lang';
const QUERY_PARAM_ORGANIZATION_FOCUS = 'orgFocus';
const QUERY_PARAM_ORGANIZATION_FOCUS_PATH = 'orgFocusPath';
const QUERY_PARAM_ORGANIZATION_URL = 'orgUrl';
const LEAF_ROW_HEIGHT = 22;
const MIN_TREE_HEIGHT = 200;
@@ -64,7 +69,7 @@ const MIN_TREE_HEIGHT = 200;
selector: 'app-hierarchy-chart',
standalone: true,
imports: [
NgxEchartsDirective,
PassiveWheelDirective,
MatProgressSpinnerModule,
MatToolbarModule,
MatCardModule,
@@ -92,12 +97,27 @@ export class HierarchyChartComponent implements OnInit {
private readonly credentialService = inject(CredentialService);
private readonly orgminerService = inject(OrgminerService);
private readonly chartTheme = inject(ChartThemeService);
/** Reference of the theme colors used for the current chart options. */
private lastChartTheme = this.chartTheme.colors();
readonly loading = signal<boolean>(true);
readonly lang = signal<'de' | 'en'>('de');
readonly levels = signal<TreeLevel[]>([]);
/** Node highlighted after a badge navigation or an analysis click. */
readonly highlightedId = signal<string | null>(null);
private readonly chartHost =
viewChild<ElementRef<HTMLDivElement>>('chartHost');
private chart: ECharts | null = null;
private chartHostElement: HTMLDivElement | null = null;
private chartResizeObserver: ResizeObserver | null = null;
private chartInitToken = 0;
private readonly snackBar = inject(MatSnackBar);
private readonly idMap = new Map<string, RawNode>();
/** Several hierarchy nodes can share one URL; keep every candidate. */
private readonly urlToNodeIds = new Map<string, string[]>();
/** Last `orgFocus` value + path that was applied, so unrelated query changes don't re-focus. */
private lastFocusKey: string | null = null;
universityRoot: RawNode | null = null;
/**
@@ -109,6 +129,8 @@ export class HierarchyChartComponent implements OnInit {
private isOwnNavigation = false;
hierarchyData = input.required<HierarchyResponse>();
/** False while the parent expansion panel is collapsed. */
readonly expanded = input<boolean>(true);
pendingSuggestion = input<HierarchySuggestion | null>(null);
can_edit = computed(() => this.hierarchyData().can_edit ?? false);
can_suggest = computed(() => this.hierarchyData().can_suggest ?? false);
@@ -133,7 +155,10 @@ export class HierarchyChartComponent implements OnInit {
});
});
effect(() => {
this.chartTheme.colors();
const colors = this.chartTheme.colors();
if (colors === this.lastChartTheme) return;
this.lastChartTheme = colors;
untracked(() => {
if (!this.universityRoot) return;
this.levels.update((levels) =>
@@ -148,6 +173,15 @@ export class HierarchyChartComponent implements OnInit {
const suggestion = this.pendingSuggestion();
untracked(() => this.loadPendingSuggestionIntoEditor(suggestion));
});
effect(() => {
const levels = this.levels();
const expanded = this.expanded();
const host = this.chartHost()?.nativeElement ?? null;
const level = expanded ? (levels[levels.length - 1] ?? null) : null;
untracked(() => this.syncChart(host, level));
});
this.destroyRef.onDestroy(() => this.disposeChart());
}
ngOnInit(): void {
@@ -162,7 +196,37 @@ export class HierarchyChartComponent implements OnInit {
this.isOwnNavigation = false;
return;
}
const langParam = params.get(QUERY_PARAM_LANG);
if (langParam === 'de' || langParam === 'en') {
this.lang.set(langParam);
}
const focus = this.normalizeOrgUrl(
params.get(QUERY_PARAM_ORGANIZATION_FOCUS),
);
const focusPath = this.parseFocusPath(
params.get(QUERY_PARAM_ORGANIZATION_FOCUS_PATH),
);
const focusKey = focus
? `${focus}\u0000${focusPath.join('\u0000')}`
: null;
if (
focus &&
focusKey !== this.lastFocusKey &&
this.focusOrganization(focus, focusPath)
) {
this.lastFocusKey = focusKey;
return;
}
if (!focus) {
this.lastFocusKey = null;
}
this.restoreFromUrl(params);
this.highlightAnalyzedOrganization(
params.get(QUERY_PARAM_ORGANIZATION_URL),
);
});
this.initialized = true;
}
@@ -216,6 +280,7 @@ export class HierarchyChartComponent implements OnInit {
const copy = structuredClone(children ?? []) as RawNode[];
this.idMap.clear();
this.urlToNodeIds.clear();
this.assignIds(copy, 'root');
this.universityRoot = {
@@ -242,6 +307,16 @@ export class HierarchyChartComponent implements OnInit {
node.id = id;
if (registerInMap) {
this.idMap.set(id, node);
for (const link of [node.link_de, node.link_en]) {
const normalized = this.normalizeOrgUrl(link);
if (!normalized) continue;
const candidates = this.urlToNodeIds.get(normalized);
if (candidates) {
if (!candidates.includes(id)) candidates.push(id);
} else {
this.urlToNodeIds.set(normalized, [id]);
}
}
}
if (node.children?.length) {
this.assignIds(node.children, id, registerInMap);
@@ -276,6 +351,184 @@ export class HierarchyChartComponent implements OnInit {
this.updateQueryParams();
}
/* --------------------------- organization focus --------------------------- */
/**
* Normalizes a hierarchy organization URL the same way the backend does:
* trim, drop trailing slashes and the common `/index` suffix.
*/
private normalizeOrgUrl(value: string | null | undefined): string | null {
if (!value) return null;
const normalized = value.trim().replace(/\/+$/, '');
const withoutIndex = normalized.endsWith('/index')
? normalized.slice(0, -'/index'.length).replace(/\/+$/, '')
: normalized;
return withoutIndex || null;
}
private findNodeIdByUrl(
value: string | null | undefined,
expectedPath: string[] = [],
preferVisible = false,
): string | null {
const normalized = this.normalizeOrgUrl(value);
const candidates = normalized
? (this.urlToNodeIds.get(normalized) ?? [])
: [];
if (!candidates.length) return null;
// Hierarchy URLs are not unique (several nodes can link to the same site),
// so the index-provided name path decides which node is meant.
if (expectedPath.length) {
const pathMatch = candidates.find((id) =>
this.matchesNamePath(id, expectedPath),
);
if (pathMatch) return pathMatch;
}
// Reloads only carry `orgUrl`; prefer the candidate on the open path.
if (preferVisible) {
const visible = candidates.find((id) => this.isNodeVisible(id));
if (visible) return visible;
}
return candidates[0];
}
/** Parses the hierarchy path (`orgFocusPath`) sent by the person badge. */
private parseFocusPath(value: string | null | undefined): string[] {
if (!value) return [];
try {
const parsed: unknown = JSON.parse(value);
if (!Array.isArray(parsed)) return [];
return parsed
.filter((segment): segment is string => typeof segment === 'string')
.map((segment) => segment.trim())
.filter(Boolean);
} catch {
return [];
}
}
/** Ancestor + node names from the faculty down (synthetic `root` excluded). */
private nodeNamePath(nodeId: string): RawNode[] {
return [...this.ancestorIds(nodeId).slice(1), nodeId]
.map((id) => this.idMap.get(id))
.filter((node): node is RawNode => !!node);
}
private matchesNamePath(nodeId: string, expectedPath: string[]): boolean {
if (!expectedPath.length) return false;
const actual = this.nodeNamePath(nodeId);
if (actual.length !== expectedPath.length) return false;
return expectedPath.every((name, index) =>
this.nodeMatchesName(actual[index], name),
);
}
private nodeMatchesName(node: RawNode, expected: string): boolean {
const normalize = (value: string | null | undefined) =>
(value ?? '').replace(/\s+/g, ' ').trim().toLocaleLowerCase();
const wanted = normalize(expected);
return (
normalize(node.name_de) === wanted || normalize(node.name_en) === wanted
);
}
/** Mirrors `buildLevel`: a level shows its children and group grandchildren. */
private levelRendersNode(levelId: string, nodeId: string): boolean {
const level = this.idMap.get(levelId);
if (!level) return false;
if (level.id === nodeId) return true;
for (const child of level.children ?? []) {
if (child.id === nodeId) return true;
const isGroup = child.type === 'institutes' || child.type === 'chairs';
if (
isGroup &&
child.children?.some((grandchild) => grandchild.id === nodeId)
) {
return true;
}
}
return false;
}
private isNodeVisible(nodeId: string): boolean {
return this.levels().some((level) =>
this.levelRendersNode(level.id, nodeId),
);
}
/** Positional parent ids of a node, e.g. `root-2-0-5` -> `root`, `root-2`, `root-2-0`. */
private ancestorIds(nodeId: string): string[] {
const ids = ['root'];
const parts = nodeId.split('-');
for (let index = 2; index < parts.length; index++) {
ids.push(parts.slice(0, index).join('-'));
}
return ids;
}
/**
* Opens the levels that display the requested organization and highlights
* its node. Used by the person-page badge (`orgFocus` query param).
*/
private focusOrganization(
orgUrl: string,
expectedPath: string[] = [],
): boolean {
const nodeId = this.findNodeIdByUrl(orgUrl, expectedPath);
if (!nodeId) return false;
// Open the faculty level, not the group directly above the target: the
// faculty chart shows the organization inside the full faculty subtree.
// For deeper nodes, keep opening levels until the target is rendered.
const fullPath = [...this.ancestorIds(nodeId), nodeId];
let lastLevelIndex = fullPath.findIndex(
(id) => this.idMap.get(id)?.type === 'faculty',
);
if (lastLevelIndex < 0) {
lastLevelIndex = Math.max(0, fullPath.length - 2);
}
while (
lastLevelIndex < fullPath.length - 1 &&
!this.levelRendersNode(fullPath[lastLevelIndex], nodeId)
) {
lastLevelIndex++;
}
const levels = fullPath
.slice(0, lastLevelIndex + 1)
.map((id) => this.idMap.get(id))
.filter((node): node is RawNode => !!node)
.map((node) => this.buildLevel(node));
if (!levels.length) return false;
this.highlightedId.set(nodeId);
this.levels.set(levels);
this.updateQueryParams();
return true;
}
/** Keeps the analyzed organization highlighted after query-param navigation. */
private highlightAnalyzedOrganization(orgUrl: string | null): void {
const nodeId = this.findNodeIdByUrl(orgUrl, [], true);
if (!nodeId || nodeId === this.highlightedId()) return;
this.highlightedId.set(nodeId);
if (this.universityRoot) {
this.rebuildLevelsKeepingPath();
}
}
private setHighlightedNode(nodeId: string | null): void {
if (this.highlightedId() === nodeId) return;
this.highlightedId.set(nodeId);
if (this.universityRoot) {
this.rebuildLevelsKeepingPath();
}
}
/** Writes the current levels path + language into the URL as query params. */
private updateQueryParams(): void {
const path = this.levels()
@@ -351,9 +604,18 @@ export class HierarchyChartComponent implements OnInit {
if (hasChildren) {
const newLevel = this.buildLevel(raw);
// if the user clicks a different branch, drop any deeper levels first
const truncated = this.levels().slice(0, levelIndex + 1);
this.levels.set([...truncated, newLevel]);
const currentLevels = this.levels();
const existingIndex = currentLevels.findIndex(
(level) => level.id === raw.id,
);
if (existingIndex >= 0) {
this.levels.set(currentLevels.slice(0, existingIndex + 1));
} else {
// If the user clicks a different branch, drop any deeper levels first.
const truncated = currentLevels.slice(0, levelIndex + 1);
this.levels.set([...truncated, newLevel]);
}
this.updateQueryParams();
} else {
this.onLeafSelect(raw);
@@ -361,6 +623,7 @@ export class HierarchyChartComponent implements OnInit {
}
private onLeafSelect(raw: RawNode): void {
this.setHighlightedNode(raw.id);
this.analyzeOrgEvent.emit({
name: raw.name_de ?? raw.name_en ?? '',
url: raw.link_de ?? raw.link_en ?? '',
@@ -369,6 +632,18 @@ export class HierarchyChartComponent implements OnInit {
/* ------------------------------ tree building ----------------------------- */
/** Extra ECharts item style that marks the focused/analyzed node. */
private highlightStyle(nodeId: string): Record<string, unknown> {
if (this.highlightedId() !== nodeId) return {};
const warning = this.chartTheme.colors().warning;
return {
borderColor: warning,
borderWidth: 1,
shadowBlur: 10,
shadowColor: warning,
};
}
private getLink(raw: RawNode): string | null | undefined {
return this.lang() === 'en'
? (raw.link_en ?? raw.link_de)
@@ -403,6 +678,7 @@ export class HierarchyChartComponent implements OnInit {
(isGroup
? this.chartTheme.colors().blueHighlight
: this.chartTheme.colors().success),
...this.highlightStyle(raw.id),
},
};
@@ -426,7 +702,13 @@ export class HierarchyChartComponent implements OnInit {
}
private buildLevel(raw: RawNode): TreeLevel {
const children = (raw.children || []).map((c) => this.toChartNode(c, true));
// Leaves inherit the icon of the group that contains them, including the
// direct children of a group that is itself the root of this level.
const parentType =
raw.type === 'institutes' || raw.type === 'chairs' ? raw.type : undefined;
const children = (raw.children || []).map((c) =>
this.toChartNode(c, true, parentType),
);
const rootData = {
id: raw.id,
@@ -434,7 +716,10 @@ export class HierarchyChartComponent implements OnInit {
nodeType: raw.type,
hasChildren: true,
link: this.getLink(raw),
itemStyle: { color: raw['color'] || this.chartTheme.colors().primary },
itemStyle: {
color: raw['color'] || this.chartTheme.colors().primary,
...this.highlightStyle(raw.id),
},
children,
};
@@ -472,7 +757,7 @@ export class HierarchyChartComponent implements OnInit {
const colors = this.chartTheme.colors();
return {
backgroundColor: this.chartTheme.colors().backgroundColor,
backgroundColor: '#ffffff',
tooltip: {
trigger: 'item',
triggerOn: 'mousemove',
@@ -499,20 +784,29 @@ export class HierarchyChartComponent implements OnInit {
verticalAlign: 'middle',
align: 'right',
fontSize: 11,
color: colors.text,
color: 'black',
formatter: (params: any) => {
if (params.data.hasChildren) {
return '{bold|' + params.name + '}';
const isHighlighted = params.data.id === this.highlightedId();
let style = 'normal';
if (isHighlighted) {
style = 'highlighted';
} else if (params.data.hasChildren) {
style = 'bold';
}
return '{normal|' + params.name + '}';
return `{${style}|${params.name}}`;
},
rich: {
bold: {
highlighted: {
fontWeight: 'bold',
color: colors.warning,
},
normal: {
fontWeight: 'normal',
},
bold: {
fontWeight: 'bold',
},
},
},
leaves: {
@@ -539,6 +833,70 @@ export class HierarchyChartComponent implements OnInit {
};
}
/* ------------------------------ chart instance ---------------------------- */
/**
* Owns the ECharts instance directly instead of delegating to ngx-echarts.
* This avoids two async `init()` calls racing when the options change while
* the chart is still being created (the "already initialized" warning).
*/
private syncChart(
host: HTMLDivElement | null,
level: TreeLevel | null,
): void {
if (!host || !level) {
this.disposeChart();
return;
}
if (this.chart && this.chartHostElement === host) {
this.chart.setOption(level.options, true);
return;
}
this.disposeChart();
this.chartHostElement = host;
const token = ++this.chartInitToken;
requestAnimationFrame(() => {
if (token !== this.chartInitToken || this.chartHostElement !== host) {
return;
}
void import('echarts').then(({ init }) => {
if (token !== this.chartInitToken || this.chartHostElement !== host) {
return;
}
const chart = init(host);
this.chart = chart;
chart.setOption(level.options, true);
chart.on('click', (params) => this.onChartNodeClick(params));
this.observeChartSize(host);
});
});
}
private onChartNodeClick(params: unknown): void {
const levelIndex = Math.max(0, this.levels().length - 1);
this.onNodeClick(params, levelIndex);
}
private observeChartSize(host: HTMLDivElement): void {
this.chartResizeObserver?.disconnect();
this.chartResizeObserver = new ResizeObserver(() => this.chart?.resize());
this.chartResizeObserver.observe(host);
}
private disposeChart(): void {
this.chartInitToken++;
this.chartResizeObserver?.disconnect();
this.chartResizeObserver = null;
this.chart?.dispose();
this.chart = null;
this.chartHostElement = null;
}
/* --------------------------------- saving -------------------------------- */
/**
@@ -551,7 +909,7 @@ export class HierarchyChartComponent implements OnInit {
this.orgminerService.saveHierarchy(children as any).subscribe({
next: (response) => {
this.snackBar.open('Hierarchy saved successfully', 'Close', {
this.snackBar.open('Hierarchie gespeichert.', 'OK', {
duration: 3000,
});
@@ -573,9 +931,13 @@ export class HierarchyChartComponent implements OnInit {
}
},
error: (error) => {
this.snackBar.open('Error saving hierarchy', 'Close', {
duration: 3000,
});
this.snackBar.open(
'Hierarchie konnte nicht gespeichert werden.',
'OK',
{
duration: 4000,
},
);
console.error('[HierarchyChart] error saving hierarchy:', error);
this.hierarchySaved.set(false);
},
@@ -25,9 +25,12 @@
</mat-expansion-panel-header>
<app-hierarchy-chart
[hierarchyData]="hierarchyData()"
[expanded]="hierarchyExpanded()"
[pendingSuggestion]="
suggestions().find((suggestion) => suggestion.status === 'new') ?? null
"
suggestions().find(
(suggestion) => suggestion.status === 'new'
) ?? null
"
(analyzeOrgEvent)="analyzeOrg($event)"
(suggestionSaved)="reloadSuggestions()" />
</mat-expansion-panel>
@@ -21,6 +21,8 @@ import { HierarchySuggestion } from '../../api/model/hierarchySuggestion';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
const ORGANIZATION_URL_PARAM = 'orgUrl';
const ORGANIZATION_NAME_PARAM = 'orgName';
const ORGANIZATION_FOCUS_PARAM = 'orgFocus';
const ORGANIZATION_FOCUS_PATH_PARAM = 'orgFocusPath';
const ORGMINER_EXPANDED_PARAM = 'orgExpanded';
const ORGMINER_SELECTION_CATEGORY_PARAM = 'orgSelectionCategory';
const ORGMINER_SELECTION_INDEX_PARAM = 'orgSelectionIndex';
@@ -119,6 +121,8 @@ export class HierarchyComponent implements OnInit {
queryParams: {
[ORGANIZATION_URL_PARAM]: organizationUrl,
[ORGANIZATION_NAME_PARAM]: org.name,
[ORGANIZATION_FOCUS_PARAM]: null,
[ORGANIZATION_FOCUS_PATH_PARAM]: null,
[ORGMINER_EXPANDED_PARAM]: null,
[ORGMINER_SELECTION_CATEGORY_PARAM]: null,
[ORGMINER_SELECTION_INDEX_PARAM]: null,
@@ -4,6 +4,7 @@
subtitle="Suche nach Hochschulen, Forschungszentren und weiteren Einrichtungen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardMinWidth]="550"
[cardTmp]="cardTmp"
[observers]="observers"
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core';
import { Component, computed, inject, input } from '@angular/core';
import { InstitutionPage } from '../../api';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
@@ -14,6 +14,7 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter
import { AppInstitutionCardComponent } from '../../shared/ui/app-institution-card/app-institution-card.component';
import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({
selector: 'app-institutions',
@@ -32,6 +33,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class InstitutionsComponent {
institutionPage = input.required<InstitutionPage>();
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/institutions'),
);
observers: FilterObserver[] = [
{
id: 'name',
@@ -1,14 +1,5 @@
<app-page-container>
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Nachrichten">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Alle Nachrichten
</button>
@if (loading) {
<app-loading
text="Nachricht wird geladen..."
@@ -3,29 +3,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 6px;
background: none;
border: none;
cursor: pointer;
font-size: 14px;
color: var(--sg-text-muted);
padding: 0;
margin-bottom: 32px;
&:hover {
color: var(--sg-text);
}
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
.state {
display: flex;
flex-direction: column;
@@ -20,7 +20,6 @@ import { WorksService } from '../../api';
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import {
ARROW_BACK_ICON,
CANCEL_ICON,
CHECK_CIRCLE_ICON,
CHEVRON_LEFT_ICON,
@@ -80,7 +79,6 @@ interface NewsArticleDetail {
styleUrl: './news-detail.component.scss',
})
export class NewsDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly NEWS_ICON = NEWS_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly CHECK_CIRCLE_ICON = CHECK_CIRCLE_ICON;
@@ -182,10 +180,6 @@ export class NewsDetailComponent implements OnInit {
});
}
navigateBack(): void {
this.router.navigate(['/news']);
}
formatDate(dateStr?: string | null): string {
if (!dateStr) return '-';
const date = new Date(dateStr);
@@ -1,14 +1,5 @@
<app-page-container>
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
aria-label="Zurück zu den Patenten">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
Alle Patente
</button>
@if (loading) {
<app-loading
text="Patent wird geladen..."
@@ -8,27 +8,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) 420px;
@@ -1,4 +1,3 @@
import { Location } from '@angular/common';
import { Component, DestroyRef, OnInit, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
@@ -16,7 +15,6 @@ import {
} from '../../resolvers/utils/topic-colors';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import {
ARROW_BACK_ICON,
BUSINESS_ICON,
CATEGORY_ICON,
ENGINEERING_ICON,
@@ -58,7 +56,6 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
styleUrl: './patent-detail.component.scss',
})
export class PatentDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly PATENT_ICON = PATENT_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
@@ -76,7 +73,6 @@ export class PatentDetailComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly patentsService = inject(PatentsService);
private readonly location = inject(Location);
patent: PatentEntry | null = null;
loading = true;
@@ -104,10 +100,6 @@ export class PatentDetailComponent implements OnInit {
});
}
navigateBack(): void {
this.location.back();
}
formatDate(date: string | null | undefined): string {
return formatPatentDate(date);
}
@@ -10,17 +10,6 @@
? null
: 'Suche Patente aus EPO und USPTO und filtere nach Zeitraum, Themen und Klassifikationen.'
">
@if (showDetail && selectedPatent) {
<button
pageActions
mat-stroked-button
color="primary"
type="button"
(click)="closeDetail()">
← Zurück zu den Patenten
</button>
}
@if (error) {
<p class="state-message error">Fehler beim Laden der Patente.</p>
} @else if (showDetail && selectedPatent) {
@@ -24,6 +24,7 @@ import {
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
import { HELP_ICON, PATENT_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { BackNavigationService } from '../../shared/services/back-navigation.service';
type PatentSource = 'EPO' | 'USPTO';
@@ -69,6 +70,8 @@ export class PatentsComponent {
private route = inject(ActivatedRoute);
private patentsApi = inject(PatentsService);
private destroyRef = inject(DestroyRef);
private backNavigation = inject(BackNavigationService);
private unregisterLocalBack: (() => void) | null = null;
patents: PatentEntry[] = [];
total = 0;
@@ -92,6 +95,8 @@ export class PatentsComponent {
readonly expandedClassificationKeys = new Set<string>();
constructor() {
this.destroyRef.onDestroy(() => this.unregisterLocalBack?.());
this.route.queryParams
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((qp) => {
@@ -181,12 +186,20 @@ export class PatentsComponent {
}
selectPatent(patent: PatentEntry): void {
this.unregisterLocalBack?.();
this.unregisterLocalBack = this.backNavigation.registerLocalBack(() =>
this.closeDetail(),
);
this.selectedPatent = patent;
this.showDetail = true;
this.expandedClassificationKeys.clear();
}
closeDetail(): void {
this.unregisterLocalBack?.();
this.unregisterLocalBack = null;
this.showDetail = false;
this.selectedPatent = null;
this.expandedClassificationKeys.clear();
@@ -53,6 +53,7 @@
<div class="institution-row">
<app-institution-chip
[institution]="inst"
[skText]="loading()"
size="mini"
[showIcon]="true"
[isClickable]="true"
@@ -114,6 +114,8 @@
</div>
}
<app-live-region [text]="resultAnnouncement" />
<div class="toolbar">
<span [skText]="loading" class="result-count">{{
resultRange()
@@ -151,11 +153,15 @@
<!--><span>Sortiert nach Publikationen und Zitierungen</span>-->
</div>
@if (getPersons().length) {
@if (loading) {
<app-page-skeleton
variant="cards-plain"
[compact]="true"
[cardMinWidth]="280" />
} @else if (getPersons().length) {
<div class="person-grid">
@for (person of getPersons(); track person.id) {
<app-person-card
[loading]="loading"
[person]="person"
[isBookmarked]="isBookmarked(person)"
[selectedTopics]="selectedTopics()"
@@ -12,8 +12,7 @@ import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatRadioModule } from '@angular/material/radio';
import { MatTooltipModule } from '@angular/material/tooltip';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
import {
CustomAuthor,
DehydratedInstitution,
@@ -48,6 +47,8 @@ import { BookmarkService } from '../../shared/services/bookmark.service';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { LiveRegionComponent } from '../../shared/ui/live-region/live-region.component';
import { PageSkeletonComponent } from '../../shared/ui/page-skeleton/page-skeleton.component';
import {
CLOSE_ICON,
FILTER_ICON,
@@ -81,6 +82,8 @@ type InstitutionYearFilterMode = 'in' | 'from' | 'between';
SkTextDirective,
ComponentTooltipDirective,
PageContainerComponent,
LiveRegionComponent,
PageSkeletonComponent,
],
templateUrl: './person-list.component.html',
styleUrl: './person-list.component.scss',
@@ -105,9 +108,9 @@ export class PersonListComponent {
private readonly bookmarkService = inject(BookmarkService);
public readonly state = inject(SharedStateService);
public readonly paginationService = inject(PaginationService);
public readonly resolverStateService = inject(ResolverStateService);
public readonly navigationState = inject(NavigationStateService);
readonly loadingState = computed(() =>
this.resolverStateService.isResolvingInside('/persons'),
this.navigationState.isResolvingInside('/persons'),
);
persons: CustomAuthor[] = [];
total = 0;
@@ -600,6 +603,13 @@ export class PersonListComponent {
return `${start}-${end} von ${this.total} Personen`;
}
/** Announced to screen readers whenever a new result set is rendered. */
get resultAnnouncement(): string {
if (this.loading) return '';
if (!this.total) return 'Keine Personen gefunden';
return this.resultRange();
}
// Bookmarks
toggleBookmark(person: CustomAuthor): void {
this.bookmarkService
@@ -34,7 +34,7 @@
<div class="toggle-group">
<mat-button-toggle-group
class="mat-button-toggle-group"
aria-label="Select view"
aria-label="Ansicht wählen"
(change)="onToggleChange($event)"
[value]="displayedTable()"
style="width: 100%">
@@ -9,7 +9,7 @@ import {
import { ActivatedRoute } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { ResolverStateService } from '../../shared/services/resolver-state.service';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
import { NewsArticle, NewsPage } from '../../resolvers/person-news.resolver';
import {
CardSearchComponent,
@@ -27,7 +27,7 @@ import { SelectorOption } from '../../shared/ui/query-param-selector/query-param
export class PersonNewsComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly resolverStateService = inject(ResolverStateService);
private readonly navigationState = inject(NavigationStateService);
readonly sortingDirectionOptions: SelectorOption[] = [
{ value: 'desc', display_name: 'Neueste zuerst' },
@@ -40,7 +40,7 @@ export class PersonNewsComponent implements OnInit {
private currentSize = 10;
get loading(): boolean {
return this.resolverStateService.isResolving();
return this.navigationState.isResolving();
}
readonly page = computed<Page>(() => ({
@@ -33,10 +33,11 @@
(expandedChange)="onSubfieldLegendExpandedChange($event)">
</app-topic-legend>
<div class="view-toggle" aria-label="Ansicht wechseln">
<div class="view-toggle" role="group" aria-label="Ansicht wechseln">
<button
type="button"
[class.active]="timelineViewMode === 'years'"
[attr.aria-pressed]="timelineViewMode === 'years'"
(click)="setTimelineViewMode('years')">
Jahre
</button>
@@ -44,6 +45,7 @@
<button
type="button"
[class.active]="timelineViewMode === 'compact'"
[attr.aria-pressed]="timelineViewMode === 'compact'"
(click)="setTimelineViewMode('compact')">
Kompakt
</button>
@@ -51,6 +53,7 @@
<button
type="button"
[class.active]="timelineViewMode === 'wordcloud'"
[attr.aria-pressed]="timelineViewMode === 'wordcloud'"
(click)="setTimelineViewMode('wordcloud')">
Wordcloud
</button>
@@ -1,30 +0,0 @@
@if (loading) {
<div class="word-cloud-state">Forschungsthemen werden geladen ...</div>
} @else if (loadFailed) {
<div class="word-cloud-state">
Forschungsthemen konnten nicht geladen werden.
</div>
} @else if (words.length) {
<div class="word-cloud-chart">
@for (word of words; track word.name) {
<button
type="button"
class="word-cloud-word"
[class.word-cloud-word-active]="isWordActiveByLegend(word)"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[disabled]="!word.topicId"
[attr.aria-label]="wordAriaLabel(word)"
[appComponentTooltip]="AppTopicTooltipComponent"
[tooltipInputs]="tooltipInputsFor(word)"
[tooltipDisabled]="!word.rawTopicId"
[tooltipMaxWidth]="'500px'"
(click)="selectWord(word)">
{{ word.name }}
</button>
}
</div>
} @else {
<p class="word-cloud-state">Keine Forschungsthemen gefunden.</p>
}
@@ -1,59 +0,0 @@
:host {
display: block;
min-height: 420px;
}
.word-cloud-chart {
width: 100%;
min-height: 420px;
display: flex;
flex-wrap: wrap;
align-content: center;
align-items: baseline;
justify-content: center;
gap: 0.35em 1em;
padding: 1.5rem 1rem;
box-sizing: border-box;
}
.word-cloud-word {
appearance: none;
border: none;
background: none;
padding: 0.1em 0.3em;
margin: 0;
border-radius: 6px;
font-family: 'Open Sans', Arial, sans-serif;
line-height: 1.1;
cursor: pointer;
transition:
transform 0.15s ease,
background-color 0.15s ease,
box-shadow 0.15s ease;
&:hover:not(:disabled),
&:focus-visible {
transform: scale(1.08);
outline: none;
}
&:disabled {
cursor: default;
}
}
.word-cloud-word-active {
background: color-mix(in srgb, currentColor 14%, transparent);
box-shadow: inset 0 0 0 1.5px currentColor;
}
.word-cloud-state {
margin: 0;
min-height: 420px;
display: flex;
align-items: center;
justify-content: center;
color: var(--sg-text-muted);
font-size: 14px;
text-align: center;
}
@@ -1,305 +0,0 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ComponentTooltipDirective } from '../../../../directives/component-tooltip.directive';
import { AppTopicTooltipComponent } from '../../../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import { topicHierarchyColor } from '../../../../resolvers/utils/topic-colors';
import {
getTopicLegendFieldId,
getTopicLegendSubfieldId,
TopicLegendTopic,
} from '../../../../resolvers/utils/topic-legend';
import type {
TopicTimelineElement,
TopicTimelineTopic,
} from '../research-timeline/research-timeline.component';
import {
formatYearRange,
normalizeSelectedYears,
} from '../../../../resolvers/utils/year-range';
import { workQueryParamKeys } from '../../../../resolvers/work-page.resolver';
interface WordTooltipInputs {
topicId: string;
secondaryActionLabel: string | null;
secondaryActionLink: unknown[] | null;
secondaryActionQueryParams: Record<string, string | number | number[]>;
}
export interface WordCloudWord {
name: string;
topicId: string;
rawTopicId: string;
fieldLegendId: string;
subfieldLegendId: string;
color: string;
fontSize: number;
fontWeight: number;
}
export interface ResearchWordcloud {
words: WordCloudWord[];
legendTopics: TopicLegendTopic[];
}
const displayedWordLimit = 30;
const minimumFontSize = 12;
const maximumFontSize = 32;
interface AggregatedTopic {
name: string;
count: number;
legendTopic: TopicLegendTopic;
}
export function buildResearchWordcloud(
elements: readonly TopicTimelineElement[],
startYear: number | undefined,
endYear: number | undefined,
): ResearchWordcloud {
const yearsInRange = elements.filter((element) =>
isWithinYearRange(element.year, startYear, endYear),
);
const aggregated = aggregateTopics(yearsInRange);
if (aggregated.size === 0) {
return { words: [], legendTopics: [] };
}
const displayed = Array.from(aggregated.values())
.sort(
(left, right) =>
right.count - left.count || left.name.localeCompare(right.name),
)
.slice(0, displayedWordLimit);
const intensity = buildIntensityScale(displayed);
const words = displayed.map((topic): WordCloudWord => {
const legendTopic = topic.legendTopic;
const scale = intensity(topic.count);
return {
name: topic.name,
topicId: legendTopic.id ?? '',
rawTopicId: stripOpenAlexId(legendTopic.id),
fieldLegendId: getTopicLegendFieldId(legendTopic),
subfieldLegendId: getTopicLegendSubfieldId(legendTopic),
color: topicHierarchyColor(legendTopic),
fontSize: Math.round(
minimumFontSize + scale * (maximumFontSize - minimumFontSize),
),
fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400,
};
});
return {
words: centreWords(words),
legendTopics: displayed.map((topic) => topic.legendTopic),
};
}
function aggregateTopics(
elements: readonly TopicTimelineElement[],
): Map<string, AggregatedTopic> {
const aggregated = new Map<string, AggregatedTopic>();
for (const element of elements) {
for (const topic of element.primary_topics ?? []) {
if (!topic.name) {
continue;
}
const key = topic.id ?? topic.name;
const existing = aggregated.get(key);
if (existing) {
existing.count += topic.count;
continue;
}
aggregated.set(key, {
name: topic.name,
count: topic.count,
legendTopic: toLegendTopic(topic),
});
}
}
return aggregated;
}
function buildIntensityScale(
topics: readonly AggregatedTopic[],
): (count: number) => number {
const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0)));
const minimumWeight = Math.min(...weights);
const maximumWeight = Math.max(...weights);
if (maximumWeight === minimumWeight) {
return () => 0.5;
}
return (count) =>
(Math.sqrt(Math.max(count, 0)) - minimumWeight) /
(maximumWeight - minimumWeight);
}
function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic {
return {
id: topic.id,
name: topic.name,
field_id: topic.field_id,
field_name: topic.field_name,
field_description: topic.field_description,
domain_id: topic.domain_id,
domain_name: topic.domain_name,
domain_description: topic.domain_description,
subfield_id: topic.subfield_id,
subfield_name: topic.subfield_name,
subfield_description: topic.subfield_description,
};
}
function isWithinYearRange(
year: number | undefined,
startYear: number | undefined,
endYear: number | undefined,
): boolean {
if (startYear !== undefined && (year === undefined || year < startYear)) {
return false;
}
if (endYear !== undefined && (year === undefined || year > endYear)) {
return false;
}
return true;
}
function centreWords(words: WordCloudWord[]): WordCloudWord[] {
const centred: WordCloudWord[] = [];
words.forEach((word, index) => {
if (index % 2 === 0) {
centred.push(word);
return;
}
centred.unshift(word);
});
return centred;
}
function stripOpenAlexId(id: string | null | undefined): string {
return (id ?? '').replace('https://openalex.org/', '');
}
@Component({
selector: 'app-research-wordcloud',
standalone: true,
imports: [ComponentTooltipDirective],
templateUrl: './research-wordcloud.component.html',
styleUrl: './research-wordcloud.component.scss',
})
export class ResearchWordcloudComponent {
readonly AppTopicTooltipComponent = AppTopicTooltipComponent;
@Input() set words(value: WordCloudWord[]) {
this._words = value;
this.rebuildTooltipInputs();
}
get words(): WordCloudWord[] {
return this._words;
}
@Input() set personPublicationsLink(value: unknown[] | null) {
this._personPublicationsLink = value;
this.rebuildTooltipInputs();
}
@Input() set personName(value: string) {
this._personName = value;
this.rebuildTooltipInputs();
}
@Input() set selectedYears(value: number[]) {
this._selectedYears = normalizeSelectedYears(value);
this.rebuildTooltipInputs();
}
@Input() loading = false;
@Input() loadFailed = false;
@Input() activeFieldIds: ReadonlySet<string> = new Set();
@Input() activeSubfieldIds: ReadonlySet<string> = new Set();
@Output() wordSelect = new EventEmitter<WordCloudWord>();
private _words: WordCloudWord[] = [];
private _personPublicationsLink: unknown[] | null = null;
private _personName = '';
private _selectedYears: number[] = [];
private tooltipInputsByTopic = new Map<string, WordTooltipInputs>();
selectWord(word: WordCloudWord): void {
if (!word.topicId) {
return;
}
this.wordSelect.emit(word);
}
isWordActiveByLegend(word: WordCloudWord): boolean {
return (
this.activeFieldIds.has(word.fieldLegendId) ||
(word.subfieldLegendId.length > 0 &&
this.activeSubfieldIds.has(word.subfieldLegendId))
);
}
tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null {
return this.tooltipInputsByTopic.get(word.topicId) ?? null;
}
wordAriaLabel(word: WordCloudWord): string {
return `${this.publicationsLabel()} zum Thema ${word.name}${this.yearRangeSuffix()}`;
}
private publicationsLabel(): string {
return this._personName
? `Publikationen von ${this._personName}`
: 'Publikationen dieser Person';
}
private yearRangeSuffix(): string {
return this._selectedYears.length > 0
? ` ${formatYearRange(this._selectedYears)}`
: '';
}
private rebuildTooltipInputs(): void {
const label = `${this.publicationsLabel()}${this.yearRangeSuffix()}`;
const link = this._personPublicationsLink;
this.tooltipInputsByTopic = new Map(
this._words
.filter((word) => word.topicId)
.map((word) => [
word.topicId,
{
topicId: word.rawTopicId,
secondaryActionLabel: link ? label : null,
secondaryActionLink: link,
secondaryActionQueryParams: {
[workQueryParamKeys.page]: 0,
...(this._selectedYears.length > 0
? { [workQueryParamKeys.years]: this._selectedYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
},
},
]),
);
}
}
@@ -22,16 +22,22 @@
(yearSelect)="onTimelineYearSelect($event)"
(loadEarlierYears)="onTimelineLoadEarlierYears()"
(legendSelectionChange)="onLegendSelectionChange($event)">
<app-research-wordcloud
<app-keyword-wordcloud
timeline-wordcloud-content
variant="bare"
[title]="null"
[words]="wordCloudWords"
[loading]="loadingWordCloud"
[loadFailed]="wordCloudLoadFailed"
[activeFieldIds]="activeLegendFieldIds"
[activeSubfieldIds]="activeLegendSubfieldIds"
[selectedYears]="wordCloudYears"
[personName]="personName"
[personPublicationsLink]="personPublicationsLink"
(wordSelect)="onWordClick($event)" />
loadingMessage="Forschungsthemen werden geladen ..."
loadFailedMessage="Forschungsthemen konnten nicht geladen werden."
emptyTitle="Keine Forschungsthemen gefunden."
emptyMessage=""
[interactive]="true"
chartAriaLabel="Wordcloud der Forschungsthemen"
[isWordActive]="isWordActiveByLegend"
[wordAriaLabel]="wordCloudAriaLabel"
[wordTooltip]="wordCloudTooltip"
(wordClick)="onWordClick($event)" />
</app-research-timeline>
</section>
@@ -14,20 +14,33 @@ import {
} from './components/research-timeline/research-timeline.component';
import {
buildResearchWordcloud,
ResearchWordcloudComponent,
WordCloudWord,
} from './components/research-wordcloud/research-wordcloud.component';
} from './research-wordcloud.utils';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import {
TopicLegendSelectionState,
TopicLegendTopic,
} from '../../resolvers/utils/topic-legend';
import { PersonDataResolved } from '../../resolvers/person.resolver';
import { formatYearRange } from '../../resolvers/utils/year-range';
import { AppTopicTooltipComponent } from '../../shared/ui/app-topic-tooltip/app-topic-tooltip.component';
import {
KeywordWordcloudComponent,
WordCloudTooltipConfig,
WordCloudWordData,
} from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component';
type WordTooltipInputs = {
topicId: string;
secondaryActionLabel: string | null;
secondaryActionLink: unknown[] | null;
secondaryActionQueryParams: Record<string, string | number | number[]>;
};
@Component({
selector: 'app-person-overview',
standalone: true,
imports: [ResearchTimelineComponent, ResearchWordcloudComponent],
imports: [ResearchTimelineComponent, KeywordWordcloudComponent],
templateUrl: './person-overview.component.html',
styleUrl: './person-overview.component.scss',
})
@@ -73,6 +86,27 @@ export class PersonOverviewComponent implements OnInit {
personName = '';
personPublicationsLink: unknown[] | null = null;
readonly wordCloudTooltip: WordCloudTooltipConfig = {
component: AppTopicTooltipComponent,
inputs: (word) => this.tooltipInputsFor(word as WordCloudWord),
disabled: (word) => !(word as WordCloudWord).rawTopicId,
maxWidth: '500px',
};
readonly isWordActiveByLegend = (word: WordCloudWordData): boolean => {
const topicWord = word as WordCloudWord;
return (
this.activeLegendFieldIds.has(topicWord.fieldLegendId) ||
(topicWord.subfieldLegendId.length > 0 &&
this.activeLegendSubfieldIds.has(topicWord.subfieldLegendId))
);
};
readonly wordCloudAriaLabel = (word: WordCloudWordData): string => {
const topicWord = word as WordCloudWord;
return `${this.publicationsLabel()} zum Thema ${topicWord.name}${this.yearRangeSuffix()}`;
};
ngOnInit(): void {
combineLatest(this.route.pathFromRoot.map((route) => route.paramMap))
.pipe(
@@ -222,8 +256,9 @@ export class PersonOverviewComponent implements OnInit {
this.loadCompleteTopicTimeline(this.currentAuthorId);
}
onWordClick(word: WordCloudWord): void {
if (!word.topicId) return;
onWordClick(word: WordCloudWordData): void {
const topicWord = word as WordCloudWord;
if (!topicWord.topicId) return;
void this.router.navigate(['../publications'], {
relativeTo: this.route,
queryParams: {
@@ -231,7 +266,7 @@ export class PersonOverviewComponent implements OnInit {
...(this.wordCloudYears.length > 0
? { [workQueryParamKeys.years]: this.wordCloudYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
[workQueryParamKeys.topicId]: topicWord.topicId,
},
});
}
@@ -241,6 +276,39 @@ export class PersonOverviewComponent implements OnInit {
this.activeLegendSubfieldIds = selection.subfieldIds;
}
private tooltipInputsFor(word: WordCloudWord): WordTooltipInputs | null {
if (!word.topicId) return null;
const link = this.personPublicationsLink;
return {
topicId: word.rawTopicId,
secondaryActionLabel: link
? `${this.publicationsLabel()}${this.yearRangeSuffix()}`
: null,
secondaryActionLink: link,
secondaryActionQueryParams: {
[workQueryParamKeys.page]: 0,
...(this.wordCloudYears.length > 0
? { [workQueryParamKeys.years]: this.wordCloudYears }
: {}),
[workQueryParamKeys.topicId]: word.topicId,
},
};
}
private publicationsLabel(): string {
return this.personName
? `Publikationen von ${this.personName}`
: 'Publikationen dieser Person';
}
private yearRangeSuffix(): string {
return this.wordCloudYears.length > 0
? ` ${formatYearRange(this.wordCloudYears)}`
: '';
}
private findAuthorId(paramMaps: readonly ParamMap[]): string {
return (
paramMaps
@@ -0,0 +1,166 @@
import { topicHierarchyColor } from '../../resolvers/utils/topic-colors';
import {
getTopicLegendFieldId,
getTopicLegendSubfieldId,
TopicLegendTopic,
} from '../../resolvers/utils/topic-legend';
import type { WordCloudWordData } from '../../shared/ui/keyword-wordcloud/keyword-wordcloud.component';
import type {
TopicTimelineElement,
TopicTimelineTopic,
} from './components/research-timeline/research-timeline.component';
export interface WordCloudWord extends WordCloudWordData {
topicId: string;
rawTopicId: string;
fieldLegendId: string;
subfieldLegendId: string;
color: string;
fontSize: number;
fontWeight: number;
}
export interface ResearchWordcloud {
words: WordCloudWord[];
legendTopics: TopicLegendTopic[];
}
const displayedWordLimit = 30;
const minimumFontSize = 12;
const maximumFontSize = 32;
interface AggregatedTopic {
name: string;
count: number;
legendTopic: TopicLegendTopic;
}
export function buildResearchWordcloud(
elements: readonly TopicTimelineElement[],
startYear: number | undefined,
endYear: number | undefined,
): ResearchWordcloud {
const yearsInRange = elements.filter((element) =>
isWithinYearRange(element.year, startYear, endYear),
);
const aggregated = aggregateTopics(yearsInRange);
if (aggregated.size === 0) {
return { words: [], legendTopics: [] };
}
const displayed = Array.from(aggregated.values())
.sort(
(left, right) =>
right.count - left.count || left.name.localeCompare(right.name),
)
.slice(0, displayedWordLimit);
const intensity = buildIntensityScale(displayed);
const words = displayed.map((topic): WordCloudWord => {
const legendTopic = topic.legendTopic;
const scale = intensity(topic.count);
return {
name: topic.name,
topicId: legendTopic.id ?? '',
rawTopicId: stripOpenAlexId(legendTopic.id),
fieldLegendId: getTopicLegendFieldId(legendTopic),
subfieldLegendId: getTopicLegendSubfieldId(legendTopic),
color: topicHierarchyColor(legendTopic),
fontSize: Math.round(
minimumFontSize + scale * (maximumFontSize - minimumFontSize),
),
fontWeight: scale > 0.66 ? 800 : scale > 0.33 ? 600 : 400,
};
});
return {
words,
legendTopics: displayed.map((topic) => topic.legendTopic),
};
}
function aggregateTopics(
elements: readonly TopicTimelineElement[],
): Map<string, AggregatedTopic> {
const aggregated = new Map<string, AggregatedTopic>();
for (const element of elements) {
for (const topic of element.primary_topics ?? []) {
if (!topic.name) {
continue;
}
const key = topic.id ?? topic.name;
const existing = aggregated.get(key);
if (existing) {
existing.count += topic.count;
continue;
}
aggregated.set(key, {
name: topic.name,
count: topic.count,
legendTopic: toLegendTopic(topic),
});
}
}
return aggregated;
}
function buildIntensityScale(
topics: readonly AggregatedTopic[],
): (count: number) => number {
const weights = topics.map((topic) => Math.sqrt(Math.max(topic.count, 0)));
const minimumWeight = Math.min(...weights);
const maximumWeight = Math.max(...weights);
if (maximumWeight === minimumWeight) {
return () => 0.5;
}
return (count) =>
(Math.sqrt(Math.max(count, 0)) - minimumWeight) /
(maximumWeight - minimumWeight);
}
function toLegendTopic(topic: TopicTimelineTopic): TopicLegendTopic {
return {
id: topic.id,
name: topic.name,
field_id: topic.field_id,
field_name: topic.field_name,
field_description: topic.field_description,
domain_id: topic.domain_id,
domain_name: topic.domain_name,
domain_description: topic.domain_description,
subfield_id: topic.subfield_id,
subfield_name: topic.subfield_name,
subfield_description: topic.subfield_description,
};
}
function isWithinYearRange(
year: number | undefined,
startYear: number | undefined,
endYear: number | undefined,
): boolean {
if (startYear !== undefined && (year === undefined || year < startYear)) {
return false;
}
if (endYear !== undefined && (year === undefined || year > endYear)) {
return false;
}
return true;
}
function stripOpenAlexId(id: string | null | undefined): string {
return (id ?? '').replace('https://openalex.org/', '');
}
@@ -1,183 +1,231 @@
<app-page-container>
@if (!isPersonLoading()) {
<section class="person-hero">
<div class="profile-card">
<div class="profile-avatar">{{ initials() }}</div>
<div class="profile-main">
<div class="name-line">
<span>Person</span>
<h1>{{ displayName() }}</h1>
<button
type="button"
class="profile-bookmark-button"
[class.bookmarked]="bookmarkService.isBookmarked(person()?.id)"
[attr.aria-label]="
bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen'
: 'Person bookmarken'
"
[matTooltip]="
bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen'
: 'Person bookmarken'
"
(click)="toggleBookmark()">
<mat-icon>{{
bookmarkService.isBookmarked(person()?.id)
? BOOKMARK_ICON
: BOOKMARK_BORDER_ICON
}}</mat-icon>
</button>
</div>
@if (resolvedInstitution(); as inst) {
<div class="institution-line">
<app-institution-chip
[institution]="inst"
size="normal"
[showIcon]="true"
[isClickable]="false" />
@if (secondaryInstitutions().length > 0) {
<button
type="button"
class="more-institutions-btn"
[appComponentTooltip]="PersonInstitutionTooltipListComponent"
[tooltipInputs]="{ institutions: secondaryInstitutions() }"
[attr.aria-label]="
secondaryInstitutions().length + ' weitere Institutionen'
">
<mat-icon class="more-info-icon">{{ MORE_INFO_ICON }}</mat-icon>
<span class="count-text"
>+{{ secondaryInstitutions().length }}</span
>
</button>
}
@if (!isPersonLoading()) {
<section class="person-hero">
<div class="profile-card">
<div class="profile-avatar">{{ initials() }}</div>
<div class="profile-main">
<div class="name-line">
<span>Person</span>
<h1>{{ displayName() }}</h1>
<button
type="button"
class="profile-bookmark-button"
[class.bookmarked]="bookmarkService.isBookmarked(person()?.id)"
[attr.aria-label]="
bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen'
: 'Person bookmarken'
"
[matTooltip]="
bookmarkService.isBookmarked(person()?.id)
? 'Bookmark entfernen'
: 'Person bookmarken'
"
(click)="toggleBookmark()">
<mat-icon>{{
bookmarkService.isBookmarked(person()?.id)
? BOOKMARK_ICON
: BOOKMARK_BORDER_ICON
}}</mat-icon>
</button>
</div>
}
@if (
worksCount() !== null || citedByCount() !== null || h_index() !== null
) {
<span class="stats-line">
@if (worksCount() !== null) {
<span class="stat-item">
<mat-icon class="stat-icon">{{ PUBLICATION_ICON }}</mat-icon>
{{ worksCount() | number }} Publikationen
</span>
}
@if (worksCount() !== null && citedByCount() !== null) {
·
}
@if (citedByCount() !== null) {
<span class="stat-item">
<mat-icon class="stat-icon">{{ CITATION_ICON }}</mat-icon>
{{ citedByCount() | number }} Zitationen
</span>
}
@if (
(worksCount() !== null || citedByCount() !== null) &&
h_index() !== null
) {
·
}
@if (h_index() !== null) {
<span
class="stat-item has-tooltip"
[matTooltip]="
'Der h-Index beträgt ' +
h_index() +
': ' +
h_index() +
' Publikationen wurden jeweils mindestens ' +
h_index() +
'-mal zitiert.'
"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon class="stat-icon">{{ TRENDING_UP_ICON }}</mat-icon>
h-Index {{ h_index() }}
</span>
}
</span>
}
@if (displayCareerStage() || orcid()) {
<div class="meta-line">
<app-career-stage-chip
[careerStage]="displayCareerStage()"
[activeYears]="person()?.career_metrics?.active_years" />
@if (orcid(); as orcidId) {
<a
class="orcid-chip"
[href]="orcidUrl()"
target="_blank"
rel="noopener"
matTooltip="ORCID-Profil öffnen"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon>{{ VERIFIED_ICON }}</mat-icon>
{{ orcidId }}
</a>
}
</div>
}
</div>
</div>
<aside class="sidebar">
<div class="bio-card">
@if (isBioLoading()) {
<app-loading
text="Biografie wird geladen..."
[icon]="DESCRIPTION_ICON"
[size]="150"
[diameter]="150"></app-loading>
} @else if (personBio() != null) {
<div class="bio-header">
<h3>Biografie</h3>
<span
class="ai-badge"
matTooltip="Diese Biografie wurde automatisch mit KI erstellt und kann Fehler enthalten."
matTooltipPosition="above"
[matTooltipShowDelay]="250">
<mat-icon>{{ AI_GENERATED_ICON }}</mat-icon>
KI-generiert
@if (
resolvedInstitution() ||
(canOpenVerifiedOrganizationHierarchy() &&
verifiedOrganizations().length > 0)
) {
<div class="institution-line">
@if (resolvedInstitution(); as inst) {
<app-institution-chip
[institution]="inst"
size="normal"
[showIcon]="true"
[isClickable]="false" />
@if (secondaryInstitutions().length > 0) {
<button
type="button"
class="more-institutions-btn"
[appComponentTooltip]="
PersonInstitutionTooltipListComponent
"
[tooltipInputs]="{ institutions: secondaryInstitutions() }"
[attr.aria-label]="
secondaryInstitutions().length + ' weitere Institutionen'
">
<mat-icon class="more-info-icon">{{
MORE_INFO_ICON
}}</mat-icon>
<span class="count-text"
>+{{ secondaryInstitutions().length }}</span
>
</button>
}
}
@if (canOpenVerifiedOrganizationHierarchy()) {
@for (org of verifiedOrganizations(); track $index) {
@if (canOpenOrganizationHierarchy(org)) {
<button
type="button"
class="verified-org-chip"
[matTooltip]="
'Verifizierte Organisation: ' +
org.org_name +
' – Hierarchie öffnen'
"
matTooltipPosition="right"
[matTooltipShowDelay]="250"
[attr.aria-label]="
'Verifizierte Organisation: ' +
org.org_name +
'. Hierarchie öffnen.'
"
(click)="openOrganizationHierarchy(org)">
<mat-icon>{{ VERIFIED_ICON }}</mat-icon>
<span>{{ org.org_name }}</span>
</button>
} @else {
<span
class="verified-org-chip static"
[matTooltip]="
'Verifizierte Organisation: ' + org.org_name
"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon>{{ VERIFIED_ICON }}</mat-icon>
<span>{{ org.org_name }}</span>
</span>
}
}
}
</div>
}
@if (
worksCount() !== null ||
citedByCount() !== null ||
h_index() !== null
) {
<span class="stats-line">
@if (worksCount() !== null) {
<span class="stat-item">
<mat-icon class="stat-icon">{{ PUBLICATION_ICON }}</mat-icon>
{{ worksCount() | number }} Publikationen
</span>
}
@if (worksCount() !== null && citedByCount() !== null) {
·
}
@if (citedByCount() !== null) {
<span class="stat-item">
<mat-icon class="stat-icon">{{ CITATION_ICON }}</mat-icon>
{{ citedByCount() | number }} Zitationen
</span>
}
@if (
(worksCount() !== null || citedByCount() !== null) &&
h_index() !== null
) {
·
}
@if (h_index() !== null) {
<span
class="stat-item has-tooltip"
[matTooltip]="
'Der h-Index beträgt ' +
h_index() +
': ' +
h_index() +
' Publikationen wurden jeweils mindestens ' +
h_index() +
'-mal zitiert.'
"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon class="stat-icon">{{ TRENDING_UP_ICON }}</mat-icon>
h-Index {{ h_index() }}
</span>
}
</span>
</div>
<p>{{ personBio() }}</p>
}
@if (displayCareerStage() || orcid()) {
<div class="meta-line">
<app-career-stage-chip
[careerStage]="displayCareerStage()"
[activeYears]="person()?.career_metrics?.active_years" />
@if (orcid(); as orcidId) {
<a
class="orcid-chip"
[href]="orcidUrl()"
target="_blank"
rel="noopener"
matTooltip="ORCID-Profil öffnen"
matTooltipPosition="right"
[matTooltipShowDelay]="250">
<mat-icon>{{ VERIFIED_ICON }}</mat-icon>
{{ orcidId }}
</a>
}
</div>
}
</div>
</div>
<aside class="sidebar">
<div class="bio-card">
@if (isBioLoading()) {
<app-loading
text="Biografie wird geladen..."
[icon]="DESCRIPTION_ICON"
[size]="150"
[diameter]="150"></app-loading>
} @else if (personBio() != null) {
<div class="bio-header">
<h3>Biografie</h3>
<span
class="ai-badge"
matTooltip="Diese Biografie wurde automatisch mit KI erstellt und kann Fehler enthalten."
matTooltipPosition="above"
[matTooltipShowDelay]="250">
<mat-icon>{{ AI_GENERATED_ICON }}</mat-icon>
KI-generiert
</span>
</div>
<p>{{ personBio() }}</p>
}
</div>
</aside>
<app-person-interesting
[topics]="primaryTopicCounts()"
[loading]="isTopicsLoading()"
[personName]="personName()"
[personPublicationsLink]="personPublicationsLink()"
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
</section>
@if (this.links()) {
<app-link-tab-nav-bar
#navBar
[links]="links()"
[tabPanel]="tabPanel"></app-link-tab-nav-bar>
}
} @else {
<app-loading
text="Person wird geladen..."
[icon]="PERSON_ICON"
[size]="150"
[diameter]="150"></app-loading>
}
<mat-tab-nav-panel #tabPanel class="person-panel">
@let activeLink = this.activeLink();
@if (activeLink) {
<div class="description-container">
@if (activeLink.label) {
<h5>{{ activeLink.label }}</h5>
}
@if (activeLink.description) {
<span class="description">{{ activeLink.description }}</span>
}
</div>
</aside>
<app-person-interesting
[topics]="primaryTopicCounts()"
[loading]="isTopicsLoading()"
[personName]="personName()"
[personPublicationsLink]="personPublicationsLink()"
(tagClick)="onInterestingTagClick($event)"></app-person-interesting>
</section>
@if (this.links()) {
<app-link-tab-nav-bar
#navBar
[links]="links()"
[tabPanel]="tabPanel"></app-link-tab-nav-bar>
}
} @else {
<app-loading
text="Person wird geladen..."
[icon]="PERSON_ICON"
[size]="150"
[diameter]="150"></app-loading>
}
<mat-tab-nav-panel #tabPanel class="person-panel">
@let activeLink = this.activeLink();
@if (activeLink) {
<div class="description-container">
@if (activeLink.label) {
<h5>{{ activeLink.label }}</h5>
}
@if (activeLink.description) {
<span class="description">{{ activeLink.description }}</span>
}
}
<div class="content">
<router-outlet></router-outlet>
</div>
}
<div class="content">
<router-outlet></router-outlet>
</div>
</mat-tab-nav-panel>
</mat-tab-nav-panel>
</app-page-container>
@@ -146,6 +146,55 @@
font-size: 13px;
}
.verified-org-chip {
display: inline-flex;
align-items: center;
gap: 6px;
min-height: 24px;
max-width: 100%;
padding: 2px 10px;
border: 1px solid var(--sg-border);
border-radius: 999px;
background: var(--sg-surface-muted);
color: var(--sg-text);
font-size: 13px;
font-weight: 600;
line-height: 1.2;
text-decoration: none;
transition:
border-color 0.15s,
background 0.15s;
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
mat-icon {
flex: 0 0 auto;
width: 16px;
height: 16px;
font-size: 16px;
color: var(--sg-success);
}
&[type='button'] {
cursor: pointer;
}
&[type='button']:hover,
&[type='button']:focus-visible {
border-color: var(--sg-success);
background: var(--sg-primary-soft);
outline: none;
}
&.static {
cursor: default;
}
}
.stats-line {
display: flex;
align-items: center;
@@ -39,12 +39,17 @@ import { CareerStageChipComponent } from '../../shared/ui/career-stage-chip/care
import { AppInstitutionChipComponent } from '../../shared/ui/app-institution-chip/app-institution-chip.component';
import { ComponentTooltipDirective } from '../../directives/component-tooltip.directive';
import { PersonInstitutionTooltipListComponent } from '../../shared/ui/person-institution-tooltip-list/person-institution-tooltip-list.component';
import { DehydratedInstitution, WorksService } from '../../api';
import {
DehydratedInstitution,
VerifiedOrganization,
WorksService,
} from '../../api';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PersonBioResolved } from '../../resolvers/person-bio.resolver';
import { PersonDataResolved } from '../../resolvers/person.resolver';
import { BookmarkService } from '../../shared/services/bookmark.service';
import { AuthorAffiliationService } from '../../shared/services/author-affiliation.service';
import { CredentialService } from '../../shared/services/credential.service';
import { collaborationGraphQueryParamKeys } from '../../resolvers/collaboration-graph.resolver';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import {
@@ -73,6 +78,14 @@ import {
} from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
/** Accepts raw and full-URL OpenAlex IDs, e.g. `I123` or `.../I123`. */
const normalizeInstitutionId = (value: string | null | undefined): string =>
(value ?? '')
.trim()
.replace(/^https:\/\/openalex\.org\//i, '')
.replace(/\/+$/, '')
.toUpperCase();
@Component({
selector: 'app-person',
imports: [
@@ -116,6 +129,7 @@ export class PersonComponent {
private readonly destroyRef = inject(DestroyRef);
readonly bookmarkService = inject(BookmarkService);
private readonly authorAffiliationService = inject(AuthorAffiliationService);
private readonly credentialService = inject(CredentialService);
canFetchGdprRelevantData = input.required<boolean>();
@@ -206,6 +220,33 @@ export class PersonComponent {
.subscribe();
}
canOpenOrganizationHierarchy(organization: VerifiedOrganization): boolean {
return (
this.canOpenVerifiedOrganizationHierarchy() &&
!!organization.org_uri &&
(organization.org_hierarchy_path?.length ?? 0) > 0
);
}
openOrganizationHierarchy(organization: VerifiedOrganization): void {
if (!this.canOpenOrganizationHierarchy(organization)) return;
void this.router.navigate(['/hierarchy'], {
queryParams: {
orgFocus: organization.org_uri,
orgFocusPath: JSON.stringify(organization.org_hierarchy_path ?? []),
hierarchyExpanded: true,
organizationExpanded: false,
orgUrl: null,
orgName: null,
orgExpanded: null,
orgSelectionCategory: null,
orgSelectionIndex: null,
classifiedCategory: null,
classifiedPage: null,
},
});
}
readonly personBio = toSignal(
combineLatest([this.activatedRoute.data, toObservable(this.person)]).pipe(
switchMap(([data, person]) => {
@@ -249,6 +290,35 @@ export class PersonComponent {
readonly secondaryInstitutions = computed<DehydratedInstitution[]>(() =>
this.authorAffiliationService.resolveSecondaryInstitutions(this.person()),
);
readonly verifiedOrganizationData = toSignal(
this.activatedRoute.data.pipe(
switchMap((data) => {
const resolved = data['personData'] as PersonDataResolved | undefined;
return resolved?.verifiedOrganizations$ ?? of(null);
}),
),
{ initialValue: null },
);
readonly verifiedOrganizations = computed(
() => this.verifiedOrganizationData()?.organizations ?? [],
);
/**
* Verified organizations come from one institution's OrgMiner data. Only
* users of that institution have a hierarchy where the nodes can be found.
*/
readonly canOpenVerifiedOrganizationHierarchy = computed(() => {
const userInstitutionId = normalizeInstitutionId(
this.credentialService.effectiveInstitutionId(),
);
const dataInstitutionId = normalizeInstitutionId(
this.verifiedOrganizationData()?.institution_id,
);
return (
!!userInstitutionId &&
!!dataInstitutionId &&
userInstitutionId === dataInstitutionId
);
});
readonly worksCount = computed(() => this.person()?.works_count ?? null);
readonly citedByCount = computed(() => this.person()?.cited_by_count ?? null);
readonly h_index = computed(
@@ -172,7 +172,4 @@ export class BundDetailsComponent implements OnInit {
return 'var(--sg-text-muted)';
}
}
goBack(): void {
window.history.back();
}
}
@@ -279,8 +279,4 @@ export class DfgDetailsComponent implements OnInit {
queryParams: { search: institutionName },
});
}
goBack(): void {
window.history.back();
}
}
@@ -4,6 +4,7 @@
subtitle="Durchsuche geförderte Projekte aus DFG-, EU- und Bundesdatenquellen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardTmp]="cardTmp"
[additionalFiltersTmp]="additionalFiltersTmp"
[cardMinWidth]="380"
@@ -1,4 +1,4 @@
import { Component, computed, input, signal } from '@angular/core';
import { Component, computed, inject, input, signal } from '@angular/core';
import { FundingProjectPage, ProjectType } from '../../api';
import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card';
@@ -16,6 +16,7 @@ import { FilterObserver } from '../../shared/ui/selected-filters/selected-filter
import { FilterCardComponent } from '../../shared/ui/filter-card/filter-card.component';
import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({
selector: 'app-projects',
@@ -36,6 +37,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class ProjectsComponent {
fundingProjectPage = input.required<FundingProjectPage>();
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/projects'),
);
page = computed<Page>(() => ({
page: this.fundingProjectPage().page || 0,
size: this.fundingProjectPage().size || 10,
@@ -1,14 +1,5 @@
<app-page-container>
<div class="detail-page">
<button
type="button"
class="back-link"
(click)="navigateBack()"
[attr.aria-label]="returnAriaLabel">
<mat-icon>{{ ARROW_BACK_ICON }}</mat-icon>
{{ returnLabel }}
</button>
@if (loading) {
<app-loading
text="Publikation wird geladen..."
@@ -8,27 +8,6 @@
min-width: 0;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 7px;
margin-bottom: 22px;
padding: 0;
border: 0;
background: transparent;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-decoration: none;
cursor: pointer;
}
.back-link mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
}
.hero {
display: grid;
grid-template-columns: minmax(0, 1fr) 420px;
@@ -24,8 +24,8 @@ import { LanguageCodePipe } from '../../shared/pipes/language-code.pipe';
import { WorkPrimaryCategoryPipe } from '../../shared/pipes/work-primary-category.pipe';
import { ResearchProfileComponent } from './research-profile/research-profile.component';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { BackNavigationService } from '../../shared/services/back-navigation.service';
import {
ARROW_BACK_ICON,
CHEVRON_LEFT_ICON,
CHEVRON_RIGHT_ICON,
CITATION_ICON,
@@ -82,7 +82,6 @@ interface InstitutionDetail {
styleUrl: './publication-detail.component.scss',
})
export class PublicationDetailComponent implements OnInit {
readonly ARROW_BACK_ICON = ARROW_BACK_ICON;
readonly PUBLICATION_ICON = PUBLICATION_ICON;
readonly SEARCH_OFF_ICON = SEARCH_OFF_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
@@ -109,6 +108,7 @@ export class PublicationDetailComponent implements OnInit {
private readonly httpClient = inject(HttpClient);
private readonly location = inject(Location);
private readonly router = inject(Router);
private readonly backNavigation = inject(BackNavigationService);
private readonly worksService = inject(WorksService);
workClassification = input.required<WorkClassification | null>();
@@ -130,20 +130,22 @@ export class PublicationDetailComponent implements OnInit {
readonly institutionsPageSize = 5;
returnUrl: string | null = null;
returnLabel = 'Alle Publikationen';
returnAriaLabel = 'Zurück zu den Publikationen';
ngOnInit(): void {
this.loading = true;
const navigationState = this.location.getState() as {
returnUrl?: string;
returnLabel?: string;
} | null;
if (navigationState?.returnUrl) {
this.returnUrl = navigationState.returnUrl;
this.returnLabel = navigationState.returnLabel ?? 'Zurück';
this.returnAriaLabel = `Zurück zu ${this.returnLabel}`;
// The topbar back button should return to the page the user came from,
// not to an unrelated history entry.
const unregister = this.backNavigation.registerLocalBack(() =>
this.navigateBack(),
);
this.destroyRef.onDestroy(unregister);
}
this.route.data.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
@@ -4,6 +4,7 @@
subtitle="Durchsuche wissenschaftliche Publikationen nach Titel, Autor:innen, Themen oder Institutionen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardMinWidth]="500"
[cardTmp]="cardTmp"
[additionalFiltersTmp]="additionalFiltersTmp"
@@ -19,6 +19,7 @@ import { PublicationFilterComponent } from '../../shared/ui/publication-filters/
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
import { workQueryParamKeys } from '../../resolvers/work-page.resolver';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({
selector: 'app-publications',
@@ -34,6 +35,11 @@ import { PageContainerComponent } from '../../shared/ui/page-container/page-cont
export class PublicationsComponent {
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/publications'),
);
workPage = input.required<WorkPageV2>();
selectedAuthorsPage = input.required<AuthorPage>();
@@ -4,6 +4,7 @@
subtitle="Entdecke Forschungsfelder nach Namen, Publikationen und Zitierungen.">
<app-card-search
[page]="page()"
[loading]="loading()"
[cardMinWidth]="550"
[cardTmp]="cardTmp"
[observers]="observers"
@@ -1,4 +1,4 @@
import { Component, computed, input } from '@angular/core';
import { Component, computed, inject, input } from '@angular/core';
import {
CardSearchComponent,
Page,
@@ -10,20 +10,22 @@ import { topicQueryParamKeys } from '../../resolvers/topic-page.resolver';
import { SelectorOption } from '../../shared/ui/query-param-selector/query-param-selector.component';
import { SEARCH_ICON } from '../../shared/ui/icons';
import { PageContainerComponent } from '../../shared/ui/page-container/page-container.component';
import { NavigationStateService } from '../../shared/services/navigation-state.service';
@Component({
selector: 'app-topics',
imports: [
CardSearchComponent,
AppTopicCardComponent,
PageContainerComponent,
],
imports: [CardSearchComponent, AppTopicCardComponent, PageContainerComponent],
templateUrl: './topics.component.html',
styleUrl: './topics.component.scss',
})
export class TopicsComponent {
topicPage = input.required<TopicPageV2>();
private readonly navigationState = inject(NavigationStateService);
readonly loading = computed(() =>
this.navigationState.isResolvingInside('/topics'),
);
observers: FilterObserver[] = [
{
id: 'query',

Some files were not shown because too many files have changed in this diff Show More