Compare commits

...
Author SHA1 Message Date
Kazgatari 641f40ff45 fixed merge conflict
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-01 21:49:00 +02:00
Kazgatari 6f0d17a991 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/trend_visual 2026-08-01 21:48:12 +02:00
Kazgatari 2d1155d46b Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/trend_visual 2026-08-01 21:43:25 +02:00
khalti a1cf6e06af Merge pull request 'fix(person-funding): icon-only publication link + return to Förderungen' (#257) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #257
2026-08-01 21:35:49 +02:00
khalti 2e4a861e9c fix(person-funding): icon-only publication link + return to Förderungen
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-08-01 21:29:05 +02:00
Kazgatari 70e4ad71a6 adapted network graph to dark mode & added padding to trend pie chart
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-01 21:23:52 +02:00
Kazgatari dc27b49f63 changed style value for input fields. Avoids propblem of standard html color when no input is provided (e.g. Input field placeholder vanishes after clicking out, when clicking back inside, the color is static black) 2026-08-01 21:08:00 +02:00
khalti b8707c7619 Merge pull request 'refactor(person-funding, person-patents, institution-patents): match publication-table styling and pagination' (#256) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #256
2026-08-01 20:48:02 +02:00
Kazgatari b251abb79f adapted topic chip v2 (why do we have 2?) to be more intense in color and change the text in dark mode 2026-08-01 20:44:15 +02:00
khalti 14be6c1a6c refactor(person-funding, person-patents, institution-patents): match publication-table styling and pagination
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-01 20:40:02 +02:00
Kazgatari 7addfe2a71 added overide for angular material tooltip (did not work natively with dark mode) 2026-08-01 20:35:58 +02:00
Kazgatari 2474700473 refactored from legacy host binding to use modern @component (host: ) implementation 2026-08-01 20:35:21 +02:00
Kazgatari 0150f81a24 !!! Implemented big style changes to overall style.css for scroll bars and navigation tabs!!! + minor style changes for the author compare components to adapt in darkmode. 2026-08-01 20:14:29 +02:00
Kazgatari 8a801d0bb5 implement dynamic color changes for e-chart (test) 2026-08-01 19:31:47 +02:00
Kazgatari 496d2c88f0 more hardcoded changes 2026-08-01 19:31:23 +02:00
Kazgatari 9d8b287c13 reverted some color values because EChart breaks 2026-08-01 19:09:08 +02:00
Kazgatari 94e0cad2d0 revert soft colors 2026-08-01 18:20:47 +02:00
Kazgatari 8be123bf3a changed hardcoded values to theme 2026-08-01 18:00:21 +02:00
Kazgatari 570da1b47c changed more static hex colors to dynamic themed ones 2026-08-01 15:42:23 +02:00
Kazgatari 02dd286d55 replaced other hard coded values with theme 2026-08-01 15:28:50 +02:00
Kazgatari 58199760de smaller theme adaptions like shadows 2026-08-01 15:22:20 +02:00
Kazgatari 17b59213d3 changed static color to use dynamic theme 2026-08-01 15:12:59 +02:00
Kazgatari 06e2785914 changed static color to use dynamic theme 2026-08-01 15:12:48 +02:00
Kazgatari 0aea390e5e changed static color to use dynamic theme 2026-08-01 15:12:18 +02:00
Kazgatari c33a900c66 changed static color to use dynamic theme 2026-08-01 15:11:56 +02:00
Kazgatari f36e9a7d54 changed static color to use dynamic theme 2026-08-01 15:11:36 +02:00
Kazgatari 7259e3a0c0 changed static color to use dynamic theme 2026-08-01 15:11:04 +02:00
Kazgatari b0581ad452 changed static color to use dynamic theme 2026-08-01 15:10:41 +02:00
Kazgatari 813953f1f5 changed static colors to use new theme 2026-08-01 15:09:55 +02:00
Kazgatari 288b21d407 added proper color theme and services to inject based on system, dark, light mode 2026-08-01 15:08:30 +02:00
kuzko 01453f73dc Merge pull request 'refactor/trend_visual' (#255) from refactor/trend_visual into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #255
2026-08-01 13:05:15 +02:00
Kazgatari 410f1ade01 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into refactor/trend_visual
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-08-01 12:53:55 +02:00
Kazgatari 621a9dd2a1 fix: moved huggingface offline mode settings to base image, to prevent first call to fetch updates from huggingface
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-01 12:30:18 +02:00
genja 18b9b8bf67 Merge pull request 'feature/keywords-analysis: updated project tables, added authors to eu projects page, updated project funding retrieval' (#254) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #254
2026-08-01 02:17:46 +02:00
genja 3f1ea0a418 updated project funding resolvers to apply filters
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-08-01 01:58:19 +02:00
genja 211f7b82dc optimized funding data retrieval + added filters 2026-08-01 01:57:42 +02:00
genja 6675976feb Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-08-01 01:09:32 +02:00
Kazgatari 034d3ee453 style changes and removed last logs
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-31 16:56:32 +02:00
Kazgatari faa866f4e1 added exception handling 2026-07-31 16:04:14 +02:00
Kazgatari 9c3e36930c changed caching to Parameter Keyed caching. Rest is handled by resolver and e-tags
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-31 14:24:20 +02:00
Kazgatari d4daecd921 fix fuzzy / keyword names on chips 2026-07-31 14:08:24 +02:00
Kazgatari 9f10e9e7af fixed resolver issues, where fuzzy search would not display anything 2026-07-31 13:55:02 +02:00
Kazgatari fa9def349c fuzzy search does not work 2026-07-31 13:22:29 +02:00
tischer 4073214131 Merge pull request 'enforce_llm_response_schema' (#253) from enforce_llm_response_schema into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #253
2026-07-30 21:26:07 +02:00
Steven Tischer 03fac2a656 add LLM response schema to keyword extraction
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-30 21:15:37 +02:00
Steven Tischer a204584ddd implement LLM response schema validation for author bio generation 2026-07-30 21:04:09 +02:00
genja 25de01c7be regenerated models and services
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-30 01:30:44 +02:00
genja 176235689f removed unused imports 2026-07-30 01:30:30 +02:00
genja f27ee8b295 updated resolvers for projects fetching for institutions 2026-07-30 01:30:14 +02:00
genja 32616fe6aa old chips replaced for oa_topics and oa_authors 2026-07-30 01:24:30 +02:00
genja 9a5cb9e9b0 added oa_authors to eu cordis details page 2026-07-30 01:23:31 +02:00
genja d11869c70b inserted generic project tables to institute component 2026-07-30 01:22:56 +02:00
genja abb8c9dbb5 fxied bug with too many author results 2026-07-30 01:21:53 +02:00
genja b8442213f8 splitted logic for ROOT and underlying institute results into 2 separated entities 2026-07-30 01:21:40 +02:00
genja 0d19abb293 added corresponding oa_authors to each EU publication response 2026-07-30 01:19:57 +02:00
khalti 6ea3e79087 Merge pull request 'refactor(person-funding): reuse shared publication-detail page for 'Mehr Infos' instead of duplicated inline panel' (#252) from ts-136-patent-to-researchers-v2 into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #252
2026-07-28 15:39:48 +02:00
khalti ba72b146a2 fix: resolve merge conflict with dev in person-funding.component.ts
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 15:35:09 +02:00
farajollahi 0f360c86b2 Merge pull request 'eu-top-authors' (#251) from eu-top-authors into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #251
2026-07-28 12:21:22 +02:00
farajollahi ecf7a6f905 Merge branch 'dev' into eu-top-authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-28 12:09:16 +02:00
farajollahi 7b912196e9 Merge pull request 'implement keyword select and dfg status diagramm' (#250) from dfg-status-dashboard into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #250
2026-07-28 11:06:24 +02:00
farajollahi 6e4742206f Merge branch 'dev' into dfg-status-dashboard
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 10:45:41 +02:00
farajollahi a28ecc9d02 implement keyword select and dfg status diagramm
LocationBasedServices/smartguide/pipeline/head Build started...
LocationBasedServices/smartguide/pipeline/pr-dev This commit looks good
2026-07-28 10:43:42 +02:00
genja 53397f844e Merge pull request 'feature/keywords-analysis' (#249) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #249
2026-07-28 10:09:56 +02:00
genja 818398ccda Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 10:08:48 +02:00
spsaefan a6c7068ca6 Merge branch 'global-time-filter' into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
# Please enter a commit message to explain why this merge is necessary,
:wq
2026-07-28 09:31:03 +02:00
genja 4785bb4d40 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 09:19:31 +02:00
genja 1a9f9496fd date formatting for BUND details page fixed 2026-07-28 09:18:56 +02:00
genja 78f35daa58 fixed pagination options for project tables 2026-07-28 09:17:51 +02:00
Kazgatari b2e70c2bb3 fix: institution visisbility button & refactor ID type (full OpenAlex link vs ID) into parent component
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 09:11:40 +02:00
genja 3d8ceeb5b6 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-28 00:40:19 +02:00
genja 0b8540d70b regenerated services and models 2026-07-28 00:35:34 +02:00
genja e9ccfe6796 added BUND institutions resolver, BUND projects desolver adjusted for the new logic 2026-07-28 00:35:20 +02:00
genja e20f2732b3 minor UI fixes 2026-07-28 00:34:35 +02:00
genja 4da4ea1bff moved BUND projects out from person component to keywords search 2026-07-28 00:32:21 +02:00
genja 93ba39f9b0 fixed filters for BUND projects 2026-07-28 00:31:51 +02:00
genja 0642a3704d added new func for retrievingbund project by topic_ids 2026-07-28 00:31:30 +02:00
genja 57e1bafa8b added BUND institutions endpoint with autocomplete 2026-07-28 00:30:20 +02:00
genja 3d5eb524aa added Institutions filter and funding-type filter for BUND 2026-07-28 00:24:52 +02:00
genja c15afed0aa added funding type selector for BUND projects 2026-07-28 00:18:24 +02:00
genja b133ce80c9 added BUND institutions selector 2026-07-28 00:17:36 +02:00
Roman ae8332dc3d (dashboard) fix pytest
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-27 23:10:01 +02:00
Roman 026a35dd90 (work-classifications): show orientation scores for limited publication samples
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-27 21:58:55 +02:00
Roman 5fdc1cdce3 refactor(dashboard): use shared active institution membership query for person count
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-27 21:40:35 +02:00
Roman 02bb8b8fb8 (work-classifications): add research profiles to author comparison (ranking) 2026-07-27 21:23:53 +02:00
khalti 27f289f4a0 refactor(person-funding): reuse shared publication-detail page for 'Mehr Infos' instead of duplicated inline panel
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
2026-07-27 21:22:49 +02:00
Kazgatari 4fe78c2b88 made pie chart bigger and seperated header to properly resize
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-27 09:22:16 +02:00
genja 2e8dd00aa6 Merge pull request 'feature/keywords-analysis' (#247) from feature/keywords-analysis into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #247
2026-07-26 22:49:24 +02:00
genja 127eed5c49 regenerated services
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
2026-07-26 22:41:38 +02:00
genja 7a84fc2b12 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis 2026-07-26 22:39:48 +02:00
genja 96e0925054 dfg tests adjusted 2026-07-26 22:36:36 +02:00
genja 730ee7f89a applied the new OpenAlex topics component for EU detail page 2026-07-26 21:55:48 +02:00
genja e62d1ca458 new ui component for displaying OpenAlex topics on project pages 2026-07-26 21:55:02 +02:00
genja 6bca5643ee added openalex topics and authors to EU details project page 2026-07-26 21:54:25 +02:00
genja db20b23ff3 reworked the dfg detail page for the new DFG data 2026-07-26 21:53:21 +02:00
genja 66f34668a9 added openalex topics to dfg detail page 2026-07-26 21:52:53 +02:00
genja ceadc26741 added openalex topics to bund detail page 2026-07-26 21:51:23 +02:00
genja 3a74dc9b7b created new DfgProjectsDetails model from the new DFG data models 2026-07-26 18:38:32 +02:00
genja 4a47d752cb removed unused components from uni-trend-parent component 2026-07-26 18:31:43 +02:00
genja 46aee46ea3 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-26 10:59:40 +02:00
genja 3a78519655 Merge branch 'dev' of nes.uni-due.de:lbs/smartguide into feature/keywords-analysis
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 16:36:54 +02:00
genja c6de85d4a0 cache time increased up to 10 minutes 2026-07-24 16:35:26 +02:00
farajollahi 0dd2023224 Restrict EU top authors to user institution
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-21 09:41:27 +02:00
farajollahi d4880b417b Align dashboard EU authors with person details 2026-07-21 09:33:18 +02:00
farajollahi a7ced052dd Verify EU author counts by unique project 2026-07-21 09:20:07 +02:00
farajollahi 9ac618ebec Revert "Align EU project author counts with person details"
This reverts commit 167913aa85.
2026-07-21 01:05:55 +02:00
farajollahi de6339586f Remove DFG top authors from dashboard 2026-07-21 00:59:34 +02:00
farajollahi 97c9e2eec3 Merge branch 'dev' into eu-top-authors
# Conflicts:
#	service/src/main/inse/dashboard/service.py
#	service/src/main/inse/dashboard/test_service.py
#	webapp/src/app/api/model/topAuthorStatistics.ts
2026-07-21 00:51:45 +02:00
farajollahi 167913aa85 Align EU project author counts with person details 2026-07-21 00:48:28 +02:00
farajollahi 18c9785325 change index
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-20 23:59:08 +02:00
farajollahi f4e0888ce2 fix organsaition id
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-20 22:50:31 +02:00
spsaefan d3266ee50e Use EU project index for top authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-20 20:37:40 +02:00
spsaefan 410bcdec4b Use OpenAlex IDs for EU authors
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-17 13:32:59 +02:00
253 changed files with 13721 additions and 7613 deletions
+10 -1
View File
@@ -6,5 +6,14 @@ RUN mkdir /test && \
pip install --root-user-action=ignore --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu && \
pip install --root-user-action=ignore --no-cache-dir "sentence-transformers~=5.5.1"
ARG MODEL_NAME=intfloat/multilingual-e5-base
ENV MODEL_NAME=${MODEL_NAME}
ENV SENTENCE_TRANSFORMERS_HOME=/models
RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('intfloat/multilingual-e5-base')"
ENV HF_HOME=/models
RUN python -c "import os, sentence_transformers; sentence_transformers.SentenceTransformer(os.environ['MODEL_NAME'])"
ENV HF_HUB_OFFLINE=1
ENV TRANSFORMERS_OFFLINE=1
ENV HF_DATASETS_OFFLINE=1
+22 -3
View File
@@ -6,9 +6,28 @@ so it is available for local runs or testing.
Usage (run once from project root):
python service/sentence_transformer/download_model.py
"""
import os
import sys
from pathlib import Path
# Ensure service/src/main is in sys.path
current_dir = Path(__file__).parent.resolve()
src_main_dir = current_dir.parent / "src" / "main"
if str(src_main_dir) not in sys.path:
sys.path.insert(0, str(src_main_dir))
from inse.config import settings
from sentence_transformers import SentenceTransformer
MODEL_NAME = "intfloat/multilingual-e5-base"
print(f"Downloading '{MODEL_NAME}' to default cache directory...")
MODEL_NAME = settings.sentence_transformers_model_name
print(f"Downloading '{MODEL_NAME}' to cache directory...")
model = SentenceTransformer(MODEL_NAME)
print("Done.")
print(f"Verifying offline model loading for '{MODEL_NAME}'...")
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"
os.environ["HF_DATASETS_OFFLINE"] = "1"
offline_model = SentenceTransformer(MODEL_NAME, local_files_only=True)
print("Done. Model downloaded and verified for 100% offline usage.")
+2 -1
View File
@@ -169,8 +169,9 @@ def main():
print("No topics found. Exiting.")
return
from inse.util import get_model
print(f"Initializing SentenceTransformer model '{MODEL_NAME}'...")
model = SentenceTransformer(MODEL_NAME)
model = get_model()
# 1. Gather all texts to embed
keywords_by_topic = []
+1 -1
View File
@@ -142,7 +142,7 @@ async def get_authors_by_ids(author_ids: list[str]) -> AuthorPage:
return await search_authors(
page=0,
size=len(author_ids),
size=len(author_ids) if len(author_ids) <10000 else 10000,
query={"terms": {"id": author_ids}},
source=[
"id",
+8
View File
@@ -34,6 +34,14 @@ class BmbfProjectStatusStatistics(BaseModel):
completed: int
class DfgProjectStatusStatistics(BaseModel):
institution_id: str
organization_name: str
ongoing: int
upcoming: int
completed: int
class DfgProjectTopic(BaseModel):
id: str
name: str
+22
View File
@@ -12,6 +12,7 @@ from .model import (
BmbfProjectStatusStatistics,
DashboardStatisticValue,
DashboardStatistics,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthorStatistics,
@@ -22,6 +23,7 @@ from .service import (
get_dashboard_bmbf_project_statuses,
get_dashboard_bmbf_projects,
get_dashboard_dfg_projects,
get_dashboard_dfg_project_statuses,
get_dashboard_dfg_topics,
get_dashboard_eu_projects,
get_dashboard_eu_project_statuses,
@@ -210,6 +212,26 @@ async def dashboard_dfg_projects(
)
@router.get(
"/projects/dfg/status",
operation_id="getDashboardDfgProjectStatuses",
response_model=DfgProjectStatusStatistics,
)
async def dashboard_dfg_project_statuses(
from_year: int | None = Query(default=None, ge=1900, le=2100),
to_year: int | None = Query(default=None, ge=1900, le=2100),
session: Session = Depends(get_session),
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DfgProjectStatusStatistics:
organization = get_dashboard_organization(session, access_token)
return await get_dashboard_dfg_project_statuses(
organization.openalex_institution_id,
organization.name,
from_year=from_year,
to_year=to_year,
)
@router.get(
"/projects/dfg/topics",
operation_id="getDashboardDfgProjectTopics",
+296 -101
View File
@@ -1,6 +1,8 @@
import asyncio
import logging
import re
from types import SimpleNamespace
from collections import defaultdict
from datetime import datetime
from typing import Any, Literal
@@ -9,6 +11,9 @@ from sqlmodel import Session
from inse import config
from inse.auth.model import AccessToken, Organization
from inse.authors.institution_membership_query import (
build_active_institution_membership_query,
)
from inse.integrations import elasticsearch
from inse.institutions.institutions_search_client import InstitutionsSearchClient
from inse.model import ESCluster, ESIndex
@@ -22,6 +27,7 @@ from .model import (
DashboardStatisticValue,
DashboardStatistics,
DfgProjectTopic,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthor,
@@ -34,6 +40,14 @@ from .model import (
TopicWordCloud,
TopicWordCloudWord,
)
from inse.projects.eu_cordis_projects_client import (
get_eu_project_ids_by_organization_filters,
)
from inse.projects.model import (
EuCordisProjectType,
ProjectType,
ProjectsFilteringProperties,
)
TOP_AUTHOR_LIMIT = 10
TOPIC_HEATMAP_LIMIT = 25
@@ -45,6 +59,30 @@ DashboardPeriod = tuple[int | None, int | None]
logger = logging.getLogger(__name__)
async def get_eu_organization_project_contributions(
organization_names: list[str],
projects_filtering_properties: ProjectsFilteringProperties,
) -> SimpleNamespace:
project_ids_by_type = await get_eu_project_ids_by_organization_filters(
project_types=list(EuCordisProjectType),
organization_names=organization_names,
)
project_ids = {
str(project_id)
for ids in project_ids_by_type.values()
for project_id in ids
}
return SimpleNamespace(
elements=[
SimpleNamespace(project_id=project_id)
for project_id in sorted(project_ids)
],
total=len(project_ids),
page=projects_filtering_properties.page,
size=projects_filtering_properties.size,
)
ACADEMIC_TITLE_RE = re.compile(
r"^(?:(?:professor(?:in)?|prof|dr)(?:\.-[a-z]+)?\.?|rer\.|nat\.|med\.|ing\.)\s+",
re.IGNORECASE,
@@ -221,74 +259,9 @@ async def get_dashboard_persons(
organization_name: str,
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
target_year = datetime.now().year - 1
recent_affiliation_query = {
"nested": {
"path": "affiliations",
"query": {
"bool": {
"filter": [
{
"match_phrase": {
"affiliations.institution.id": normalized_id
}
},
{"range": {"affiliations.years": {"gte": target_year}}},
]
}
},
}
}
matching_last_known_institution_query = {
"nested": {
"path": "last_known_institutions",
"query": {
"match_phrase": {
"last_known_institutions.id": normalized_id
}
},
}
}
missing_last_known_institutions_query = {
"bool": {
"must_not": [
{
"nested": {
"path": "last_known_institutions",
"query": {"exists": {"field": "last_known_institutions.id"}},
}
}
]
}
}
search_query = {
"bool": {
"should": [
{
"bool": {
"filter": [
matching_last_known_institution_query,
recent_affiliation_query,
]
}
},
{
"bool": {
"filter": [
missing_last_known_institutions_query,
recent_affiliation_query,
]
}
},
],
"minimum_should_match": 1,
}
}
response = await elasticsearch.search(
index=ESIndex.OPENALEX_AUTHORS,
query=search_query,
query=build_active_institution_membership_query(normalized_id),
size=0,
track_total_hits=True,
cluster=ESCluster.NES,
@@ -557,6 +530,108 @@ async def get_dashboard_dfg_projects(
)
async def get_dashboard_dfg_project_statuses(
institution_id: str,
organization_name: str,
from_year: int | None = None,
to_year: int | None = None,
) -> DfgProjectStatusStatistics:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
project_ids = await _get_dfg_project_ids_for_institution(
normalized_id,
)
if not project_ids:
return DfgProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=0,
upcoming=0,
completed=0,
)
selected_project_filters: list[dict[str, Any]] = [
{
"terms": {
"projects.project_id": [
int(project_id) for project_id in project_ids
]
}
}
]
if period_filter := _project_overlap_filter(
"projects.funding_start",
"projects.funding_end",
period,
missing_end_is_ongoing=True,
):
selected_project_filters.append(period_filter)
response = await elasticsearch.search(
index=ESIndex.DFG_INSTITUTES_V2,
body={
"size": 0,
"aggs": {
"projects_nested": {
"nested": {"path": "projects"},
"aggs": {
"selected_projects": {
"filter": (
selected_project_filters[0]
if len(selected_project_filters) == 1
else {"bool": {"filter": selected_project_filters}}
),
"aggs": {
"ongoing": {
"filter": {
"match_phrase": {
"projects.status_de": "laufend"
}
},
"aggs": {
"projects": {
"cardinality": {
"field": "projects.project_id"
}
}
},
},
"completed": {
"filter": {
"match_phrase": {
"projects.status_de": "abgeschlossen"
}
},
"aggs": {
"projects": {
"cardinality": {
"field": "projects.project_id"
}
}
},
},
},
}
},
}
},
},
cluster=ESCluster.INSE,
)
aggregations = (
response.get("aggregations", {})
.get("projects_nested", {})
.get("selected_projects", {})
)
return DfgProjectStatusStatistics(
institution_id=normalized_id,
organization_name=organization_name,
ongoing=_project_status_count(aggregations, "ongoing"),
upcoming=0,
completed=_project_status_count(aggregations, "completed"),
)
async def get_dashboard_dfg_topics(
institution_id: str,
organization_name: str,
@@ -899,6 +974,7 @@ async def get_top_authors(
from_year = datetime.now().year - 4
to_year = datetime.now().year
period = _dashboard_period(from_year, to_year)
aliases = await _institution_aliases(normalized_id, organization_name)
authors = await _safe_institution_authors(normalized_id)
works = _top_work_authors(authors, period)
projects = await _safe_top_authors(
@@ -912,8 +988,9 @@ async def get_top_authors(
)
eu_projects = await _safe_top_authors(
"eu_projects",
_top_eu_project_publication_authors(),
_top_eu_project_publication_authors(normalized_id, aliases, authors),
)
patents = await _safe_top_authors(
"patents",
_top_patent_authors(
@@ -922,10 +999,12 @@ async def get_top_authors(
to_year=period[1],
),
)
news = await _safe_top_authors(
"news",
_top_news_authors(authors),
)
return TopAuthorStatistics(
institution_id=normalized_id,
works=works,
@@ -1880,52 +1959,168 @@ async def _top_patent_authors(
]
async def _top_eu_project_publication_authors() -> list[TopAuthor]:
response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_FP7_PUBLICATIONS,
async def _top_eu_project_publication_authors(
institution_id: str,
organization_names: list[str],
institution_authors: list[dict[str, Any]],
) -> list[TopAuthor]:
institution_author_ids = {
author_id
for author in institution_authors
if (author_id := _normalize_author_id(author.get("id")))
}
if not institution_author_ids:
return []
project_page = await get_eu_organization_project_contributions(
organization_names=organization_names,
projects_filtering_properties=ProjectsFilteringProperties(
project_type=ProjectType.EU,
page=0,
size=10000,
),
)
project_ids = [project.project_id for project in project_page.elements]
if not project_ids:
return []
publication_response = await elasticsearch.search(
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
body={
"size": 0,
"aggs": {
"authors": {
"terms": {
"script": {
"lang": "painless",
"source": _cordis_publication_authors_script(),
},
"size": TOP_AUTHOR_LIMIT,
"order": {"_count": "desc"},
}
"size": 10000,
"_source": ["projectID", "qaProcessedDoi"],
"query": {
"terms": {
"projectID": project_ids,
}
},
},
cluster=ESCluster.INSE,
)
doi_project_ids = _cordis_publication_doi_project_ids(
publication_response,
set(project_ids),
)
if not doi_project_ids:
return []
works_response = await elasticsearch.search(
index="openalex-works",
body={
"size": 10000,
"_source": [
"doi",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
],
"query": {
"bool": {
"filter": [
{"terms": {"doi": sorted(doi_project_ids)}},
_institution_works_query(institution_id),
]
}
},
},
cluster=ESCluster.NES,
)
return _openalex_work_authors_by_eu_projects(
works_response,
doi_project_ids,
institution_id,
institution_author_ids,
)
def _cordis_publication_doi_project_ids(
response: dict[str, Any],
allowed_project_ids: set[str],
) -> dict[str, set[str]]:
doi_project_ids: dict[str, set[str]] = defaultdict(set)
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
project_id = str(source.get("projectID") or "").strip()
if not project_id or project_id not in allowed_project_ids:
continue
doi = _normalize_doi(source.get("qaProcessedDoi"))
if doi:
doi_project_ids[doi].add(project_id)
return dict(doi_project_ids)
def _normalize_doi(value: Any) -> str | None:
if not isinstance(value, str) or not value.strip():
return None
doi = value.strip().lower()
if doi.startswith("https://doi.org/"):
return doi
if doi.startswith("http://doi.org/"):
return "https://" + doi.removeprefix("http://")
if doi.startswith("doi.org/"):
return f"https://{doi}"
return f"https://doi.org/{doi}"
def _openalex_work_authors_by_eu_projects(
response: dict[str, Any],
doi_project_ids: dict[str, set[str]],
institution_id: str,
institution_author_ids: set[str],
) -> list[TopAuthor]:
# Count unique CORDIS projects per author, not publications. Multiple works
# (and therefore multiple DOIs) can belong to the same project ID.
author_project_ids: dict[str, set[str]] = defaultdict(set)
author_names: dict[str, str] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
project_ids = doi_project_ids.get(_normalize_doi(source.get("doi")) or "")
if not project_ids:
continue
for authorship in source.get("authorships") or []:
if not any(
institution.get("id") == institution_id
for institution in authorship.get("institutions") or []
):
continue
author = authorship.get("author") or {}
author_id = _normalize_author_id(author.get("id"))
author_name = str(author.get("display_name") or "").strip()
if (
not author_id
or author_id not in institution_author_ids
or not author_name
):
continue
author_project_ids[author_id].update(project_ids)
author_names.setdefault(author_id, author_name)
ranked_authors = sorted(
author_project_ids.items(),
key=lambda item: (-len(item[1]), author_names.get(item[0], ""), item[0]),
)
return [
TopAuthor(
name=str(bucket["key"]),
count=int(bucket.get("doc_count", 0)),
id=_short_author_id(author_id),
name=author_names[author_id],
count=len(project_ids),
)
for bucket in (
response.get("aggregations", {}).get("authors", {}).get("buckets", [])
)
if str(bucket.get("key", "")).strip()
for author_id, project_ids in ranked_authors[:TOP_AUTHOR_LIMIT]
]
def _cordis_publication_authors_script() -> str:
return (
"def names = new HashSet(); "
"def source = params['_source']; "
"def value = source.containsKey('authors') ? source['authors'] "
" : (source.containsKey('Authors') ? source['Authors'] : null); "
"if (value instanceof String && value.length() > 0) { "
" for (name in value.splitOnToken(';')) { "
" def trimmed = name.trim(); "
" if (trimmed.length() > 0) { names.add(trimmed); } "
" } "
"} "
"return new ArrayList(names);"
)
def _normalize_author_id(value: Any) -> str | None:
if not isinstance(value, str) or not value.strip():
return None
short_id = value.replace("https://openalex.org/", "").strip().upper()
return f"https://openalex.org/{short_id}"
async def _top_news_authors(authors: list[dict[str, Any]]) -> list[TopAuthor]:
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -52,6 +52,7 @@ from inse.patents.service import (
)
from inse.persons.service import router as persons_service_router
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
from inse.projects.bund_institutions.router import router as bund_institutions_router
from inse.projects.dfg_persons.router import router as dfg_persons_router
from inse.projects.eu_organizations.router import router as eu_organizations_router
from inse.projects.router import router as projects_router
@@ -103,6 +104,7 @@ app = FastAPI(
app.include_router(institution_patents_router)
app.include_router(org_patents_router)
app.include_router(institutions_router)
app.include_router(bund_institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
@@ -137,7 +139,7 @@ app.include_router(background_jobs_router)
app.include_router(eu_organizations_router)
app.add_middleware(
ETagCacheMiddleware,
ttl=120, # 2 minutes expiration time
ttl=600, # 10 minutes expiration time
)
app.add_middleware(
CORSMiddleware,
@@ -16,10 +16,11 @@ NO_STORE_PATH_PREFIXES = (
"/api/background-jobs",
"/api/bookmarks",
"/api/organizations",
"/api/dashboard",
"/api/rank/rank-author",
"/api/works/v2/classification/",
)
"/api/dashboard",
"/api/rank/rank-author",
"/api/rank/orientation-profiles",
"/api/works/v2/classification/",
)
NO_STORE_PATH_FRAGMENTS = (
"/company-connections",
@@ -8,8 +8,8 @@
"""
from datetime import date, datetime
from typing import Optional, List, Set, Any
from typing import Optional, List, Set, Any, Dict
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from pydantic import BaseModel, ConfigDict, Field, field_validator
@@ -189,6 +189,10 @@ class BundProjectDetails(BaseModel):
default_factory=list,
description="All institutions associated with the Bund project",
)
oa_topics: Optional[List[Topic]] = Field(
default_factory=list,
description="OpenAlex topics associated with the Bund project",
)
# --- Validators for type coercion ---
@@ -301,7 +305,17 @@ class BundProjectDetails(BaseModel):
if source.get("PT_fullname"):
institutions.add(source["PT_fullname"].strip())
topics_raw = source.get("oa_topics") or []
if not isinstance(source, dict):
return cls.model_validate(source)
oa_topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
return cls(
id=hit["_id"],
funding_reference=source.get("Förderkennzeichen"),
@@ -334,4 +348,24 @@ class BundProjectDetails(BaseModel):
unix_timestamp=source.get("unix_timestamp"),
associated_persons=sorted(persons),
institutions=sorted(institutions),
oa_topics=oa_topics
)
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
@@ -1,293 +1,435 @@
# coding: utf-8
"""
DFG Project Clean Model
DFG Project Clean Model (v2)
Summary model that consolidates all scattered person and institution fields
from the raw projects_dfg_all index into clean, unified lists.
Enriched, consolidated model built on top of the structured
projects_dfg_v2 API models (DFGProject / DFGPerson / DFGInstitute),
rather than the old flat projects_dfg_all Elasticsearch index.
"""
from typing import Optional, List, Set
from typing import List, Optional
from pydantic import BaseModel, ConfigDict, Field
from inse.models.projects_dfg_v2.project.dfg_project import DFGProject
from inse.models.projects_dfg_v2.project.dfg_project_persons_inner import (
DFGProjectPersonsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_institutions_inner import (
DFGProjectInstitutionsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import (
DFGProjectSubprojectsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_publications_inner import (
DFGProjectPublicationsInner,
)
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import (
DFGProjectFachgebieteInner,
)
from inse.topics.model import Topic
class DfgProjectPersonRole(BaseModel):
"""A person associated with the project, together with their role."""
model_config = ConfigDict(populate_by_name=True)
person_id: Optional[int] = Field(default=None, description="DFG person ID")
full_name: Optional[str] = Field(default=None, description="Full name of the person")
orcid_id: Optional[str] = Field(
default=None,
description=(
"ORCID iD, if known. Not present on the project's embedded person "
"record (DFGProjectPersonsInner) -- only populated if the caller "
"cross-references the full DFGPerson record via person_id and "
"calls DfgProjectDetails.enrich_orcids afterwards."
),
)
role_key: Optional[str] = Field(
default=None, description="Machine-readable role key (e.g. 'antragsteller')"
)
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
affiliation_de: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (German)"
)
affiliation_en: Optional[str] = Field(
default=None, description="Person's affiliation at time of project (English)"
)
is_deceased: Optional[bool] = Field(default=None, description="Whether the person is deceased")
is_head: Optional[bool] = Field(
default=None, description="Whether this person is highlighted as the project head"
)
@classmethod
def from_inner(cls, p: DFGProjectPersonsInner) -> "DfgProjectPersonRole":
return cls(
person_id=p.person_id,
full_name=p.full_name,
role_key=p.role_key,
role_label_de=p.role_label_de,
role_label_en=p.role_label_en,
affiliation_de=p.affiliation_de,
affiliation_en=p.affiliation_en,
is_deceased=p.is_deceased,
is_head=p.is_head_display,
)
class DfgProjectInstitutionRole(BaseModel):
"""An institution associated with the project, together with its role."""
model_config = ConfigDict(populate_by_name=True)
institute_id: Optional[int] = Field(default=None, description="DFG institute ID")
name_de: Optional[str] = Field(default=None, description="Institution name (German)")
name_en: Optional[str] = Field(default=None, description="Institution name (English)")
role_key: Optional[str] = Field(default=None, description="Machine-readable role key")
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
is_dissolved: Optional[bool] = Field(
default=None, description="Whether the institution has since been dissolved"
)
is_head: Optional[bool] = Field(
default=None, description="Whether this institution is highlighted as the lead institution"
)
@classmethod
def from_inner(cls, i: DFGProjectInstitutionsInner) -> "DfgProjectInstitutionRole":
return cls(
institute_id=i.institute_id,
name_de=i.institute_name_de,
name_en=i.institute_name_en,
role_key=i.role_key,
role_label_de=i.role_label_de,
role_label_en=i.role_label_en,
is_dissolved=i.is_dissolved,
is_head=i.is_head_display,
)
class DfgProjectSubprojectSummary(BaseModel):
"""A lightweight reference to a sub-project of this project."""
model_config = ConfigDict(populate_by_name=True)
subproject_id: Optional[int] = None
title_de: Optional[str] = None
title_en: Optional[str] = None
short_title: Optional[str] = None
role_label_de: Optional[str] = Field(
default=None, description="Role of the sub-project lead within the sub-project"
)
person_full_name: Optional[str] = Field(
default=None, description="Sub-project lead, derived from first/last name fields"
)
status_de: Optional[str] = None
funding_start: Optional[int] = None
funding_end: Optional[int] = None
@classmethod
def from_inner(cls, s: DFGProjectSubprojectsInner) -> "DfgProjectSubprojectSummary":
person_full_name = None
if s.person_first_names or s.person_last_name:
person_full_name = " ".join(
part for part in [s.person_first_names, s.person_last_name] if part
).strip() or None
return cls(
subproject_id=s.subproject_id,
title_de=s.title_de,
title_en=s.title_en,
short_title=s.short_title,
role_label_de=s.role_label_de,
person_full_name=person_full_name,
status_de=s.status_de,
funding_start=s.funding_start,
funding_end=s.funding_end,
)
class DfgProjectPublicationSummary(BaseModel):
"""A lightweight reference to a publication resulting from the project."""
model_config = ConfigDict(populate_by_name=True)
publication_id: Optional[int] = None
title: Optional[str] = None
authors_editors: Optional[str] = None
doi: Optional[str] = None
publication_year: Optional[int] = None
@classmethod
def from_inner(cls, p: DFGProjectPublicationsInner) -> "DfgProjectPublicationSummary":
return cls(
publication_id=p.publication_id,
title=p.title,
authors_editors=p.authors_editors,
doi=p.doi,
publication_year=p.publication_year,
)
class DfgProjectSubjectArea(BaseModel):
"""A single subject-area classification entry (DFG 'Fachsystematik')."""
model_config = ConfigDict(populate_by_name=True)
fach: Optional[str] = None
fachgebiet: Optional[str] = None
fachkollegium: Optional[str] = None
wissenschaftsbereich: Optional[str] = None
@classmethod
def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea":
return cls(
fach=f.fach,
fachgebiet=f.fachgebiet,
fachkollegium=f.fachkollegium,
wissenschaftsbereich=f.wissenschaftsbereich,
)
class DfgProjectDetails(BaseModel):
"""
Clean summary model for a DFG project, consolidating all person roles
and institution references into unified lists.
Clean, enriched summary model for a DFG project.
"""
model_config = ConfigDict(
populate_by_name=True,
validate_assignment=True,
model_config = ConfigDict(populate_by_name=True, validate_assignment=True)
id: Optional[int] = Field(default=None, description="The DFG project ID")
link: Optional[str] = Field(default=None, description="Canonical DFG link to the project")
page_url: Optional[str] = Field(default=None, description="DFG GEPRIS page URL")
external_link: Optional[str] = Field(
default=None, description="External project website/link, if provided"
)
id: str = Field(description="The ID of the DFG project")
link: Optional[str] = Field(default=None, description="The link to the DFG project")
title: Optional[str] = Field(
default=None, description="The title of the DFG project"
title_de: Optional[str] = Field(default=None, description="Project title (German)")
title_en: Optional[str] = Field(default=None, description="Project title (English)")
description_de: Optional[str] = Field(default=None, description="Project abstract (German)")
description_en: Optional[str] = Field(default=None, description="Project abstract (English)")
final_report_abstract_de: Optional[str] = Field(
default=None, description="Final report abstract (German), if the project has concluded"
)
description: Optional[str] = Field(
default=None, description="The description of the DFG project"
final_report_abstract_en: Optional[str] = Field(
default=None, description="Final report abstract (English), if the project has concluded"
)
project_identifier: Optional[str] = Field(
default=None,
description="The project identifier of the DFG project",
)
project_identifier_de: Optional[str] = Field(default=None, description="DFG project identifier (German)")
project_identifier_en: Optional[str] = Field(default=None, description="DFG project identifier (English)")
funding_start_date: Optional[str] = Field(
default=None, description="The funding start date of the DFG project"
)
funding_end_date: Optional[str] = Field(
default=None, description="The funding end date of the DFG project"
)
funding_start: Optional[int] = Field(default=None, description="Funding start year")
funding_end: Optional[int] = Field(default=None, description="Funding end year")
funding_period_de: Optional[str] = Field(default=None, description="Human-readable funding period (German)")
funding_period_en: Optional[str] = Field(default=None, description="Human-readable funding period (English)")
funding_type_de: Optional[str] = Field(default=None, description="Funding type / programme (German)")
funding_type_en: Optional[str] = Field(default=None, description="Funding type / programme (English)")
funding_type_key: Optional[str] = Field(default=None, description="Machine-readable funding type key")
dfg_procedure: Optional[str] = Field(
default=None, description="The DFG procedure"
)
subject_area: Optional[str] = Field(
default=None,
description="The subject area classification",
)
funding_type: Optional[str] = Field(
default=None, description="The type of funding"
)
international_reference: Optional[str] = Field(
default=None,
description="International reference",
default=None, description="DFG procedure / template type (e.g. Sachbeihilfe, SFB, GRK)"
)
website: Optional[str] = Field(
default=None, description="The project website"
is_transfer_project: Optional[bool] = Field(
default=None, description="Whether this is a transfer project"
)
# Unified person list: all person names from any role
website_html_de: Optional[str] = Field(
default=None, description="Raw project website HTML content (German), as served by DFG"
)
website_html_en: Optional[str] = Field(
default=None, description="Raw project website HTML content (English), as served by DFG"
)
equipment_group: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) group, for equipment-funding projects",
)
equipment_name: Optional[str] = Field(
default=None,
description="Large-equipment (Großgerät) name, for equipment-funding projects",
)
subject_area_de: Optional[str] = Field(default=None, description="Subject area, summary text (German)")
subject_area_en: Optional[str] = Field(default=None, description="Subject area, summary text (English)")
subject_classifications: List[DfgProjectSubjectArea] = Field(
default_factory=list,
description="Detailed DFG subject-area classification entries (Fachsystematik)",
)
international_relation_de: Optional[str] = Field(
default=None, description="International reference/cooperation (German)"
)
international_relation_en: Optional[str] = Field(
default=None, description="International reference/cooperation (English)"
)
# Structured, role-aware person and institution lists
persons: List[DfgProjectPersonRole] = Field(
default_factory=list,
description="All persons associated with the project, each with their role",
)
institutions: List[DfgProjectInstitutionRole] = Field(
default_factory=list,
description="All institutions associated with the project, each with their role",
)
# Convenience flat views, derived from the structured lists above
associated_persons: List[str] = Field(
default_factory=list,
description="All persons associated with the DFG project (any role)",
description="Flat, de-duplicated list of all person full names (convenience view)",
)
# Unified institution list: all institutions involved
institutions: List[str] = Field(
associated_institutions: List[str] = Field(
default_factory=list,
description="All institutions associated with the DFG project",
description="Flat, de-duplicated list of all institution names (convenience view)",
)
# Sub-project reference
subproject_of: Optional[str] = Field(
default=None,
description="Parent project this is a sub-project of",
# Parent / sub-project structure
parent_project_id: Optional[int] = Field(default=None, description="Parent project ID, if this is a sub-project")
parent_title_de: Optional[str] = Field(default=None, description="Parent project title (German)")
parent_title_en: Optional[str] = Field(default=None, description="Parent project title (English)")
subprojects: List[DfgProjectSubprojectSummary] = Field(
default_factory=list, description="Sub-projects of this project, if any"
)
publications: List[DfgProjectPublicationSummary] = Field(
default_factory=list, description="Publications resulting from the project"
)
topics: Optional[List[Topic]] = Field(
default_factory=list, description="OpenAlex topics associated with the project ID"
)
@classmethod
def from_dfg_project(cls, project: DFGProject) -> "DfgProjectDetails":
"""
Build a DfgProjectDetails from a fully-typed DFGProject instance
(e.g. as returned by the projects_dfg_v2 API client).
"""
persons = [DfgProjectPersonRole.from_inner(p) for p in (project.persons or [])]
institutions = [
DfgProjectInstitutionRole.from_inner(i) for i in (project.institutions or [])
]
subprojects = [
DfgProjectSubprojectSummary.from_inner(s) for s in (project.subprojects or [])
]
publications = [
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
]
subject_classifications = [
DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or [])
]
# De-duplicated flat views, order-preserving
seen_persons = set()
associated_persons = []
for p in persons:
if p.full_name and p.full_name not in seen_persons:
seen_persons.add(p.full_name)
associated_persons.append(p.full_name)
seen_institutions = set()
associated_institutions = []
for i in institutions:
name = i.name_de or i.name_en
if name and name not in seen_institutions:
seen_institutions.add(name)
associated_institutions.append(name)
return cls(
id=project.id or project.project_id,
link=project.link,
page_url=project.page_url,
external_link=project.external_link,
title_de=project.title_de,
title_en=project.title_en,
description_de=project.abstract_de,
description_en=project.abstract_en,
final_report_abstract_de=project.final_report_abstract_de,
final_report_abstract_en=project.final_report_abstract_en,
project_identifier_de=project.project_identifier_de,
project_identifier_en=project.project_identifier_en,
funding_start=project.funding_start,
funding_end=project.funding_end,
funding_period_de=project.funding_period_de,
funding_period_en=project.funding_period_en,
funding_type_de=project.funding_type_de,
funding_type_en=project.funding_type_en,
funding_type_key=project.funding_type_key,
dfg_procedure=project.template_type,
is_transfer_project=project.is_transfer_project,
website_html_de=project.website_html_de,
website_html_en=project.website_html_en,
equipment_group=project.equipment_group,
equipment_name=project.equipment_name,
subject_area_de=project.subject_area_de,
subject_area_en=project.subject_area_en,
subject_classifications=subject_classifications,
international_relation_de=project.international_relation_de,
international_relation_en=project.international_relation_en,
persons=persons,
institutions=institutions,
associated_persons=associated_persons,
associated_institutions=associated_institutions,
parent_project_id=project.parent_project_id,
parent_title_de=project.parent_title_de,
parent_title_en=project.parent_title_en,
subprojects=subprojects,
publications=publications,
topics=project.topics,
)
@classmethod
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
"""Convenience constructor from a raw dict (e.g. a JSON API response body)."""
obj = cls._sanitize_raw_project_dict(obj)
return cls.from_dfg_project(DFGProject.from_dict(obj))
@staticmethod
def _sanitize_raw_project_dict(obj: dict) -> dict:
"""
Work around known mismatches between the generated DFGProject model
and the actual shape of API/index data, before handing off to
DFGProject.from_dict (which would otherwise raise a ValidationError
and abort the whole parse).
"""
if isinstance(obj.get("subject_classifications"), list):
obj = dict(obj)
obj.pop("subject_classifications", None)
return obj
@classmethod
def from_elastic_hit(cls, hit: dict) -> "DfgProjectDetails":
"""
Create a DfgProject from an Elasticsearch hit, consolidating all
person and institution fields into unified lists.
Compatibility constructor for callers still reading from an
Elasticsearch hit (e.g. `{"_id": ..., "_source": {...}}`), matching
the old model's from_elastic_hit signature.
"""
source = dict(hit.get("_source", {}))
source = hit.get("_source", {})
if source.get("id") is None and source.get("project_id") is None:
raw_id = hit.get("_id")
if raw_id is not None:
try:
source["id"] = int(raw_id)
except (TypeError, ValueError):
# Non-numeric _id (e.g. a composite/legacy key) - leave
# id unset rather than fail the whole parse.
pass
associated_persons: Set[str] = set()
institutions: Set[str] = set()
return cls.from_dict(source)
# --- Collect all persons and institutions from nested persons array ---
persons_list = source.get("persons", [])
if isinstance(persons_list, list):
for p in persons_list:
if isinstance(p, dict):
full_name = p.get("full_name")
if full_name:
associated_persons.add(full_name.strip())
aff_de = p.get("affiliation_de")
if aff_de:
institutions.add(aff_de.strip())
aff_en = p.get("affiliation_en")
if aff_en:
institutions.add(aff_en.strip())
# --- Collect all persons from every person-related field ---
# Applicant fields
_add_persons(source, associated_persons, "Antragsteller") # semicolon-separated
_add_person(source, associated_persons, "Antragstellerin")
_add_persons(
source, associated_persons, "Antragstellerinnen"
) # semicolon-separated
_add_persons(
source, associated_persons, "Antragstellerinnen / Antragsteller"
) # semicolon-separated
# Co-applicant fields
_add_persons(source, associated_persons, "Mitantragsteller")
_add_person(source, associated_persons, "Mitantragstellerin")
_add_persons(source, associated_persons, "Mitantragstellerinnen")
_add_persons(
source, associated_persons, "Mitantragstellerinnen / Mitantragsteller"
)
# Former applicant fields
_add_persons(source, associated_persons, "Ehemalige Antragsteller")
_add_person(source, associated_persons, "Ehemalige Antragstellerin")
_add_persons(source, associated_persons, "Ehemalige Antragstellerinnen")
_add_persons(
source,
associated_persons,
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
)
_add_person(source, associated_persons, "Ehemaliger Antragsteller")
# Speaker / coordinator fields
_add_person(source, associated_persons, "Sprecher")
_add_person(source, associated_persons, "Sprecherin")
_add_persons(source, associated_persons, "Sprecherinnen")
_add_persons(source, associated_persons, "Sprecherinnen / Sprecher")
_add_person(source, associated_persons, "Co-Sprecher")
_add_persons(source, associated_persons, "Co-Sprecherinnen / Co-Sprecher")
# IGK partner speaker fields
_add_person(source, associated_persons, "Sprecher (IGK-Partner)")
_add_person(source, associated_persons, "Sprecherin (IGK-Partner)")
_add_persons(
source,
associated_persons,
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
)
# Leader fields
_add_person(source, associated_persons, "Leiter")
_add_person(source, associated_persons, "Leiterin")
_add_persons(source, associated_persons, "Leiterinnen")
_add_persons(source, associated_persons, "Leiterinnen / Leiter")
# Sub-project leader fields
_add_persons(source, associated_persons, "Teilprojektleiter")
_add_person(source, associated_persons, "Teilprojektleiterin")
_add_persons(source, associated_persons, "Teilprojektleiterinnen")
_add_persons(
source, associated_persons, "Teilprojektleiterinnen / Teilprojektleiter"
)
# Participating scientist fields
_add_persons(source, associated_persons, "beteiligte Wissenschaftler")
_add_person(source, associated_persons, "beteiligte Wissenschaftlerin")
_add_persons(source, associated_persons, "beteiligte Wissenschaftlerinnen")
_add_persons(
source,
associated_persons,
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
)
_add_person(source, associated_persons, "beteiligter Wissenschaftler")
# Participating person fields
_add_person(source, associated_persons, "Beteiligte Person")
_add_persons(source, associated_persons, "Beteiligte Personen")
# Host fields (for guest researchers)
_add_person(source, associated_persons, "Gastgeber")
_add_person(source, associated_persons, "Gastgeberin")
_add_persons(source, associated_persons, "Gastgeberinnen")
_add_persons(source, associated_persons, "Gastgeberinnen / Gastgeber")
# Cooperation partner fields
_add_person(source, associated_persons, "Kooperationspartner")
_add_person(source, associated_persons, "Kooperationspartnerin")
_add_persons(source, associated_persons, "Kooperationspartnerinnen")
_add_persons(
source, associated_persons, "Kooperationspartnerinnen / Kooperationspartner"
)
# Co-responsible fields
_add_person(source, associated_persons, "Mitverantwortlich")
_add_person(source, associated_persons, "Mitverantwortlich(e)")
_add_persons(source, associated_persons, "Mitverantwortliche")
# Application partner
_add_person(source, associated_persons, "Anwendungspartner")
# Foreign co-applicant fields
_add_persons(source, associated_persons, "ausländische Mitantragsteller")
_add_person(source, associated_persons, "ausländischer Mitantragsteller")
# Person creator (from nested fields)
if "person_creater_name" in source and source["person_creater_name"]:
associated_persons.add(source["person_creater_name"].strip())
# Deputy (stellvertr) - nested object
stellvertr = source.get("stellvertr")
if stellvertr and isinstance(stellvertr, dict):
for field in ["stellvertreter", "stellvertreterin"]:
if field in stellvertr and stellvertr[field]:
associated_persons.add(stellvertr[field].strip())
# --- Collect all institutions ---
_add_institution(source, institutions, "Antragstellende Institution")
_add_institution(source, institutions, "Mitantragstellende Institution")
_add_institution(source, institutions, "Beteiligte Einrichtung")
_add_institution(source, institutions, "Beteiligte Hochschule")
_add_institution(source, institutions, "Beteiligte Institution")
_add_institution(source, institutions, "IGK-Partnerinstitution")
_add_institution(source, institutions, "Partnerorganisation")
_add_institution(source, institutions, "Unternehmen")
# Foreign institution (nested object)
auslaend = source.get("ausländ")
if auslaend and isinstance(auslaend, dict):
for field in [
"auslaendischeInstitution",
"auslaendischeInstitution2",
"auslaendischesUnternehmen",
"auslaendischesUnternehmen2",
]:
if field in auslaend and auslaend[field]:
institutions.add(auslaend[field].strip())
return cls(
id=hit["_id"],
link=source.get("link") or source.get("page_url"),
title=source.get("title") or source.get("title_de") or source.get("title_en"),
description=source.get("description") or source.get("abstract_de") or source.get("abstract_en"),
project_identifier=source.get("Projektkennung") or source.get("project_identifier_de") or source.get("project_identifier_en"),
funding_start_date=str(source.get("funding_start")) if source.get("funding_start") is not None else None,
funding_end_date=str(source.get("funding_end")) if source.get("funding_end") is not None else None,
dfg_procedure=source.get("DFG-Verfahren") or source.get("template_type"),
subject_area=source.get("Fachliche Zuordnung") or source.get("subject_area_de") or source.get("subject_area_en"),
funding_type=source.get("Förderung") or source.get("funding_type_sort"),
international_reference=source.get("Internationaler Bezug") or source.get("international_relation_de") or source.get("international_relation_en"),
website=source.get("Webseite"),
associated_persons=sorted(associated_persons), # sorted for consistency
institutions=sorted(institutions),
subproject_of=source.get("Teilprojekt zu") or source.get("parent_project_id"),
)
# --- Helper functions for parsing source fields ---
def _add_person(source: dict, persons: Set[str], field: str) -> None:
"""Add a single person value from a field."""
if field in source and source[field]:
value = source[field].strip()
if value:
persons.add(value)
def _add_persons(source: dict, persons: Set[str], field: str) -> None:
"""Add persons from a semicolon-separated field."""
if field in source and source[field]:
for person in source[field].split(";"):
cleaned = person.strip()
if cleaned:
persons.add(cleaned)
def _add_institution(source: dict, institutions: Set[str], field: str) -> None:
"""Add a single institution value from a field."""
if field in source and source[field]:
value = source[field].strip()
if value:
institutions.add(value)
def enrich_orcids(self, persons_by_id: dict) -> None:
"""
Fill in orcid_id on each entry in `self.persons`, given a mapping of
person_id -> DFGPersonPerson (or DFGPerson) for the persons involved
in this project
"""
for person in self.persons:
record = persons_by_id.get(person.person_id)
if record is not None:
person.orcid_id = getattr(record, "orcid_id", None)
@@ -29,6 +29,7 @@ from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import DF
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
class DFGProject(BaseModel):
"""
@@ -52,7 +53,7 @@ class DFGProject(BaseModel):
funding_type_key: Optional[StrictStr] = None
funding_type_sort: Optional[StrictStr] = None
id: Optional[StrictInt] = None
institution_roles_order: Optional[StrictStr] = None
institution_roles_order: Optional[list[StrictStr]] = None
institutions: Optional[List[DFGProjectInstitutionsInner]] = None
international_relation_de: Optional[StrictStr] = None
international_relation_en: Optional[StrictStr] = None
@@ -62,7 +63,7 @@ class DFGProject(BaseModel):
parent_project_id: Optional[StrictInt] = None
parent_title_de: Optional[StrictStr] = None
parent_title_en: Optional[StrictStr] = None
person_roles_order: Optional[StrictStr] = None
person_roles_order: Optional[list[StrictStr]] = None
persons: Optional[List[DFGProjectPersonsInner]] = None
project: Optional[DFGProjectProject] = None
project_id: Optional[StrictInt] = None
@@ -72,13 +73,14 @@ class DFGProject(BaseModel):
subject_area_de: Optional[StrictStr] = None
subject_area_en: Optional[StrictStr] = None
subject_classifications: Optional[DFGProjectFachgebieteInner] = None
subproject_order: Optional[StrictStr] = None
subproject_order: Optional[list[StrictStr]] = None
subprojects: Optional[List[DFGProjectSubprojectsInner]] = None
template_type: Optional[StrictStr] = None
title_de: Optional[StrictStr] = None
title_en: Optional[StrictStr] = None
website_html_de: Optional[StrictStr] = None
website_html_en: Optional[StrictStr] = None
topics: Optional[List[Topic]] = None
__properties: ClassVar[List[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
model_config = ConfigDict(
@@ -168,9 +170,18 @@ class DFGProject(BaseModel):
"""Create an instance of DFGProject from a dict"""
if obj is None:
return None
topics_raw = obj.get("topics") or []
if not isinstance(obj, dict):
return cls.model_validate(obj)
topics = None
if isinstance(topics_raw, list) and topics_raw:
sorted_topics_raw = sorted(
(t for t in topics_raw if isinstance(t, dict)),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
_obj = cls.model_validate({
"abstract_de": obj.get("abstract_de"),
@@ -217,8 +228,29 @@ class DFGProject(BaseModel):
"title_de": obj.get("title_de"),
"title_en": obj.get("title_en"),
"website_html_de": obj.get("website_html_de"),
"website_html_en": obj.get("website_html_en")
"website_html_en": obj.get("website_html_en"),
"topics": topics,
})
return _obj
@staticmethod
def _topic_from_match(match: Dict[str, Any]) -> Topic:
"""Builds a Topic model from a flattened topic_match dict.
"""
domain_name = match.get("domain")
field_name = match.get("field")
subfield_name = match.get("subfield")
domain = TopicDomain(display_name=domain_name) if domain_name else None
field = TopicField(display_name=field_name) if field_name else None
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
return Topic(
id=match.get("topic_id"),
display_name=match.get("topic_display_name"),
domain=domain,
field=field,
subfield=subfield,
)
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class Fp7ProjectDetails(BaseModel):
"""
@@ -70,6 +71,9 @@ class Fp7ProjectDetails(BaseModel):
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
ipr_count: Optional[int] = Field(default=None, alias="iprCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
@@ -79,7 +83,7 @@ class Fp7ProjectDetails(BaseModel):
"title", "topics", "totalCost",
"organizations", "publications", "iprs", "reportSummaries",
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"organizationCount", "publicationCount", "iprCount"
"organizationCount", "publicationCount", "iprCount","oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -163,6 +167,10 @@ class Fp7ProjectDetails(BaseModel):
"organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
"publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
"iprCount": len(obj.get("iprs", [])) if obj.get("iprs") else 0,
# # OpenAlex related fields
# "oaTopics": [Topic.from_dict(topic) for topic in obj.get("oaTopics", [])] if obj.get("oaTopics") else None,
# "oaAuthors": AuthorPage.from_dict(obj.get("oaAuthors")) if obj.get("oaAuthors") else None,
})
return _obj
@@ -178,6 +186,8 @@ class Fp7ProjectDetails(BaseModel):
web_links: Optional[List[Fp7WebLink]] = None,
eurosci_voc: Optional[List[Fp7EurosciVoc]] = None,
legal_basis_list: Optional[List[Fp7LegalBasis]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -211,4 +221,6 @@ class Fp7ProjectDetails(BaseModel):
organizationCount=len(organizations) if organizations else 0,
publicationCount=len(publications) if publications else 0,
iprCount=len(iprs) if iprs else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -23,12 +23,14 @@ from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
from inse.authors.v2.model import Author
class Fp7Publication(BaseModel):
"""
Fp7Publication
""" # noqa: E501
authors: Optional[StrictStr] = None
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
collection: Optional[StrictStr] = None
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
doi: Optional[StrictStr] = None
@@ -46,7 +48,7 @@ class Fp7Publication(BaseModel):
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
title: Optional[StrictStr] = None
volume: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"]
model_config = ConfigDict(
validate_by_name=True,
@@ -26,7 +26,8 @@ from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLi
from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class H2020ProjectDetails(BaseModel):
"""
@@ -73,7 +74,10 @@ class H2020ProjectDetails(BaseModel):
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
erc_pi_count: Optional[int] = Field(default=None, alias="ercPiCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
@@ -84,6 +88,7 @@ class H2020ProjectDetails(BaseModel):
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"ercPrincipalInvestigators",
"organizationCount", "publicationCount", "deliverableCount", "ercPiCount"
,"oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -185,6 +190,8 @@ class H2020ProjectDetails(BaseModel):
eurosci_voc: Optional[List[H2020EurosciVoc]] = None,
legal_basis_list: Optional[List[H2020LegalBasis]] = None,
erc_principal_investigators: Optional[List[H2020ErcPI]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -221,4 +228,6 @@ class H2020ProjectDetails(BaseModel):
publicationCount=len(publications) if publications else 0,
deliverableCount=len(deliverables) if deliverables else 0,
ercPiCount=len(erc_principal_investigators) if erc_principal_investigators else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -23,12 +23,13 @@ from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
from inse.authors.v2.model import Author
class H2020Publication(BaseModel):
"""
H2020Publication
""" # noqa: E501
authors: Optional[StrictStr] = None
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
collection: Optional[StrictStr] = None
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
doi: Optional[StrictStr] = None
@@ -46,7 +47,8 @@ class H2020Publication(BaseModel):
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
title: Optional[StrictStr] = None
volume: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"]
model_config = ConfigDict(
validate_by_name=True,
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.authors.v2.model import AuthorPage
from inse.models.openalex.topic import Topic
class HEUProjectDetails(BaseModel):
"""
@@ -70,7 +71,9 @@ class HEUProjectDetails(BaseModel):
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
# OpenAlex related fields
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
__properties: ClassVar[List[str]] = [
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
@@ -79,7 +82,7 @@ class HEUProjectDetails(BaseModel):
"title", "topics", "totalCost",
"organizations", "publications", "deliverables", "reportSummaries",
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
"organizationCount", "publicationCount", "deliverableCount"
"organizationCount", "publicationCount", "deliverableCount","oaTopics", "oaAuthors"
]
model_config = ConfigDict(
@@ -178,6 +181,8 @@ class HEUProjectDetails(BaseModel):
web_links: Optional[List[HEUWebLink]] = None,
eurosci_voc: Optional[List[HEUEurosciVoc]] = None,
legal_basis_list: Optional[List[HEULegalBasis]] = None,
oa_topics: Optional[List[Topic]] = None,
oa_authors: Optional[AuthorPage] = None,
) -> Self:
"""
Factory method to create a detailed project from a base project and its relations.
@@ -211,4 +216,6 @@ class HEUProjectDetails(BaseModel):
organizationCount=len(organizations) if organizations else 0,
publicationCount=len(publications) if publications else 0,
deliverableCount=len(deliverables) if deliverables else 0,
oa_authors=oa_authors,
oa_topics=oa_topics or [],
)
@@ -23,12 +23,14 @@ from typing import Any, ClassVar, Dict, List, Optional
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python
from inse.authors.v2.model import Author
class HEUPublication(BaseModel):
"""
HEUPublication
""" # noqa: E501
authors: Optional[StrictStr] = None
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
collection: Optional[StrictStr] = None
content_update_date: Optional[datetime] = Field(default=None, alias="contentUpdateDate")
doi: Optional[StrictStr] = None
@@ -46,7 +48,8 @@ class HEUPublication(BaseModel):
repository_url: Optional[StrictStr] = Field(default=None, alias="repositoryUrl")
title: Optional[StrictStr] = None
volume: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume"]
oa_authors: Optional[List[Author]] = Field(default=None, alias="oaAuthors", description="OpenAlex authors matched to this publication's DOI")
__properties: ClassVar[List[str]] = ["authors", "collection", "contentUpdateDate", "doi", "id", "isPublishedAs", "journalNumber", "journalTitle", "projectAcronym", "projectID", "publishedPages", "publishedYear", "publisher", "qaProcessedDoi", "rcn", "repositoryUrl", "title", "volume", "oaAuthors"]
model_config = ConfigDict(
validate_by_name=True,
+15 -20
View File
@@ -4,16 +4,16 @@
Business logic for the "aktuell" news index on the INSE cluster.
"""
import json
import logging
import re
from pydantic import ValidationError
from inse.exceptions import ElasticsearchException
from ..integrations import elasticsearch, llm
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
from ..topics.logic import vector_search_topics_batch
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
from .model import (MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsKeywords, NewsPage)
logger = logging.getLogger(__name__)
@@ -294,12 +294,19 @@ async def _get_article_keywords(
if not text:
return [], postproc_id
raw = await llm.call(
response = await llm.call(
system_prompt=KEYWORD_SYSTEM_PROMPT,
user_prompt=f"Artikel:\n{text}",
json_schema=NewsKeywords.model_json_schema(),
schema_name="keywords",
temperature=0.3,
)
keywords = _parse_keywords(raw)
try:
keywords = _normalize_keywords(NewsKeywords.model_validate_json(response).keywords)
except ValidationError:
logger.warning(f"Keyword extraction for news {news_id} returned no valid JSON: {response}")
keywords = []
if keywords:
postproc_id = await _store_keywords(news_id, postproc_id, keywords)
@@ -359,24 +366,12 @@ async def get_article_topics_from_index(news_id: str) -> list:
return matched
def _parse_keywords(raw: str) -> list:
raw = (raw or "").strip()
try:
parsed = json.loads(raw)
if isinstance(parsed, list):
candidates = parsed
elif isinstance(parsed, dict):
candidates = parsed.get("keywords", [])
else:
candidates = []
except (json.JSONDecodeError, TypeError):
candidates = re.split(r"[,\n]", raw)
def _normalize_keywords(candidates: list) -> list:
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
seen = set()
keywords = []
for item in candidates:
term = str(item).strip().strip('"').strip()
term = item.strip().strip('"').strip()
if term and term.lower() not in seen:
seen.add(term.lower())
keywords.append(term)
+5 -1
View File
@@ -3,7 +3,11 @@
from typing import List, Optional
from pydantic import BaseModel
from pydantic import BaseModel, Field
class NewsKeywords(BaseModel):
keywords: List[str] = Field(description="The extracted keywords from the article.")
class NewsArticle(BaseModel):
+14 -4
View File
@@ -11,6 +11,8 @@ import time
from datetime import datetime
from typing import List, Optional
from pydantic import ValidationError
from inse.exceptions import (
BadRequestException,
ElasticsearchException,
@@ -26,6 +28,7 @@ from inse.persons.model import (
CareerMetrics,
CustomAuthor,
CustomAuthorsListResponse,
PersonBio
)
from inse.persons.query_builder import build_authors_search_rescored
from inse.works.logic import enrich_topic_descriptions
@@ -473,21 +476,28 @@ async def generate_person_bio(
Beschreibe in zwei Sätzen das Hauptforschungsfeld des Autors. Formuliere dabei allgemeinverständlich, sodass auch Personen ohne Fachwissen einen Einblick in die Forschung gewinnen. Nenne keine konkreten Publikationen oder Einzelwerke, sondern konzentriere dich auf die übergeordneten Forschungsinteressen und Themen. Verzichte auf bloße Aufzählungen und verbinde die Informationen zu einem flüssigen Text.
Beschreibe anschließend in ein bis zwei Sätzen die wirtschaftliche Relevanz der Forschung anhand von Anwendungen, Technologien oder Branchen, die davon profitieren könnten.
Verwende insgesamt maximal 100 bis 120 Wörter. Formuliere die Antwort so, dass sie ohne weitere Anpassungen direkt als Kurzbiografie verwendet werden kann. Verwende keine Superlative oder übertriebene Formulierungen, sondern bleibe sachlich und informativ. Gebe den Text als One-Liner zurück, ohne Zeilenumbrüche oder Aufzählungen. Verwende keine Gedankenstriche (– oder —) zur Gliederung von Sätzen. Formuliere stattdessen mit Kommas, Klammern oder zwei getrennten Sätzen.
Gib ausschließlich ein JSON-Objekt zurück, das den Text im Feld "bio" enthält.
"""
user_prompt = f"Daten zur Person:\n{person_json}"
bio = await llm.call(
response = await llm.call(
system_prompt=system_prompt,
user_prompt=user_prompt,
json_schema=PersonBio.model_json_schema(),
schema_name="bio",
temperature=0.8,
top_p=0.95,
)
try:
bio = PersonBio.model_validate_json(response).bio
except ValidationError:
logger.warning(f"Bio generation for author {author_id} returned no valid JSON: {response}")
bio = "Etwas ist schiefgelaufen."
elapsed_time = time.time() - start_time
logger.info(
f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds"
)
logger.info(f"Bio generation for author {author_id} took {elapsed_time:.2f} seconds")
return bio
@@ -0,0 +1,42 @@
from typing import Optional
from inse.model import Page
from pydantic import BaseModel
class BundInstitutionSummary(BaseModel):
"""A single institution entry derived from a BUND project record.
Note: this index has no dedicated institution entity — each entry is
reconstructed from the agency/recipient fields on a single project hit,
so the same institution may appear multiple times (once per project).
"""
department: Optional[str] = None
department_fullname: Optional[str] = None
name: Optional[str] = None
recepient: Optional[str] = None
municipality: Optional[str] = None
place: Optional[str] = None
state: Optional[str] = None
country: Optional[str] = None
@classmethod
def from_source(cls, source: dict) -> "BundInstitutionSummary":
"""Build a BundInstitutionSummary from a raw Elasticsearch _source dict."""
return cls(
department=source.get("Ressort"),
department_fullname=source.get("Ressort_fullname"),
name=source.get("Ausführende Stelle"),
recepient=source.get("Zuwendungsempfänger"),
municipality=source.get("Stadt/Gemeinde"),
place=source.get("Ort"),
state=source.get("Bundesland"),
country=source.get("Staat"),
)
class BundInstitutionSummaryPage(Page[BundInstitutionSummary]):
"""A paginated response containing a list of institutions."""
pass
@@ -0,0 +1,47 @@
import logging
from typing import Annotated
from fastapi import APIRouter, Query
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
from inse.tags import Tags
from inse.projects.bund_institutions.service import autocomplete_institutions_for_selector, get_institutions_by_names
logger = logging.getLogger(__name__)
INSTITUTIONS_BUND_PREFIX = "/api/bund/institutions"
router = APIRouter(prefix=INSTITUTIONS_BUND_PREFIX, tags=[Tags.BUND_INSTITUTIONS])
@router.get(
"/names",
operation_id="getBundInstitutionsByName",
summary="Returns a list of institutions based on their names.",
)
async def get_bund_institutions(
institution_names: Annotated[
list[str],
Query(description="A list of institution names to retrieve."),
] = [],
) -> BundInstitutionSummaryPage:
return await get_institutions_by_names(institution_names=institution_names or [])
@router.get(
"/autocomplete/selector",
operation_id="getBundInstitutionAutocompleteForSelector",
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
)
async def get_bund_institution_autocomplete(
query: Annotated[
str,
Query(
description="A search term to filter institutions by (partial matches allowed)."
),
] = "",
) -> BundInstitutionSummaryPage:
return await autocomplete_institutions_for_selector(query=query)
@@ -0,0 +1,169 @@
import logging
from typing import Dict, List, Optional
from inse.integrations import elasticsearch
from inse.model import ESIndex, ESCluster
from inse.projects.bund_institutions.model import BundInstitutionSummary
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
logger = logging.getLogger(__name__)
# Fields on the BUND project index that describe the institution/agency involved,
# used consistently across all lookup functions below.
_INSTITUTION_SOURCE_FIELDS = [
"Ressort",
"Ressort_fullname",
"Ausführende Stelle",
"Zuwendungsempfänger",
"Stadt/Gemeinde",
"Ort",
"Bundesland",
"Staat",
]
async def search_institutions(
page: int = 0,
size: int = 10,
query: Optional[Dict] = None,
source: Optional[List[str]] = None,
sort: Optional[List[Dict]] = None,
body: Optional[Dict] = None,
) -> BundInstitutionSummaryPage:
"""Searches for institutions in the BUND Projects Elasticsearch index based on the provided parameters.
Note: PROJECTS_BUND_V1 indexes projects, not institutions directly, so each
matching project hit is reshaped into a BundInstitutionSummary. The same
institution may therefore appear multiple times if it's tied to multiple projects.
Args:
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
query (Optional[Dict], optional): The search query to filter institutions by. Defaults to None.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
sort (Optional[List[Dict]], optional): A list of sorting criteria. Defaults to None.
body (Optional[Dict], optional): The request body for the Elasticsearch search query. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the search criteria.
"""
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
cluster=ESCluster.INSE,
query=query,
source=source or _INSTITUTION_SOURCE_FIELDS,
size=size,
offset=size * page,
sort=sort,
body=body,
)
hits_block = response.get("hits", {})
hits = hits_block.get("hits", [])
institutions: List[BundInstitutionSummary] = [
BundInstitutionSummary.from_source(hit.get("_source", {})) for hit in hits
]
return BundInstitutionSummaryPage(
elements=institutions,
total=hits_block.get("total", {}).get("value", len(institutions)),
page=page,
size=size,
)
async def get_institutions_by_names(institution_names: List[str]) -> BundInstitutionSummaryPage:
"""Retrieves institutions based on a list of institution (Ausführende Stelle) names.
Args:
institution_names (List[str]): A list of institution names to retrieve.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the provided names.
"""
logger.debug(f"Fetching institutions for names: {institution_names}")
if not institution_names:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=0,
size=len(institution_names),
query={
"terms": {
"Ausführende Stelle.keyword": institution_names,
}
},
source=_INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions(
query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term, matching against both the
executing agency (Ausführende Stelle) and recipient (Zuwendungsempfänger) fields.
Args:
query (str): The search term to autocomplete institutions with.
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
logger.debug(f"Autocomplete institutions for query: {query}")
if not query:
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
return await search_institutions(
page=page,
size=size,
query={
"bool": {
"should": [
{
"match_phrase_prefix": {
"Ausführende Stelle": {
"query": query,
"max_expansions": 50,
"boost": 2,
}
}
},
{
"match_phrase_prefix": {
"Zuwendungsempfänger": {
"query": query,
"max_expansions": 50,
}
}
},
],
"minimum_should_match": 1,
}
},
source=source or _INSTITUTION_SOURCE_FIELDS,
)
async def autocomplete_institutions_for_selector(
query: str, page: int = 0, size: int = 10
) -> BundInstitutionSummaryPage:
"""Autocompletes institutions based on a search term for use in a selector component.
Args:
query (str): The search term to filter institutions by (partial matches allowed).
page (int, optional): The page number to retrieve. Defaults to 0.
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
Returns:
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
"""
return await autocomplete_institutions(
query=query,
page=page,
size=size,
source=_INSTITUTION_SOURCE_FIELDS,
)
@@ -5,7 +5,7 @@ from collections import defaultdict
from inse.config import get_settings
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.authors.v2.model import AuthorPage
from inse.authors.v2.model import AuthorPage,Author
from inse.authors.v2.service import get_authors_by_ids
# Import base models
from inse.models.cordis_eu_project import CordisEuProject
@@ -46,7 +46,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLin
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
from inse.projects.model import EuCordisProjectType, EuCordisProjectSummary
from inse.projects.model import (
EuCordisProjectType,
EuCordisProjectSearchPage,
@@ -56,7 +56,7 @@ from inse.projects.model import (
EuCordisEurosciVocSummary,
)
from inse.projects.logic import get_eu_project_ids_by_openalex_topic_ids, get_openalex_topics_for_eu_projects
from inse.models.openalex.topic import Topic
settings = get_settings()
logger = logging.getLogger(__name__)
@@ -96,24 +96,13 @@ _HEU_ENTITY_CONFIGS = [
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc},
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
]
async def get_enriched_cordis_project_by_id(
project_id: str,
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
"""
Fetches and enriches a single Cordis EU project by its ID across all programme types.
Args:
project_id: The project ID to fetch.
Returns:
The enriched detailed project model, or None if not found.
"""
if not project_id:
return None
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
@@ -130,32 +119,143 @@ async def get_enriched_cordis_project_by_id(
index = hit.get("_index", "")
source = hit.get("_source", {})
program_type = _determine_program_type_from_index(index)
project_type = EuCordisProjectType.from_index_name(index)
enrichers = {
"fp7": _enrich_fp7_project,
"h2020": _enrich_h2020_project,
"heu": _enrich_heu_project,
EuCordisProjectType.FP7: _enrich_fp7_project,
EuCordisProjectType.H2020: _enrich_h2020_project,
EuCordisProjectType.HEU: _enrich_heu_project,
}
enricher = enrichers.get(program_type)
enricher = enrichers.get(project_type)
if enricher is None:
logger.warning(f"Unknown programme type for index: {index}")
return CordisEuProject.model_validate(source)
return await enricher(project_id, source)
return await enricher(project_id, source, project_type)
# helpers
def _determine_program_type_from_index(index: str) -> str:
"""Determines the programme type from the Elasticsearch index name."""
index_lower = index.lower()
if "fp7" in index_lower:
return "fp7"
if "horizon_2020" in index_lower:
return "h2020"
if "heu" in index_lower or "horizon_europe" in index_lower:
return "heu"
return "unknown"
async def _fetch_openalex_author_data_for_project_ids(
project_ids: List[str],
) -> Tuple[Dict[str, AuthorPage], Dict[str, Dict[str, List[Author]]]]:
"""
Single batched fetch that returns, per project_id:
- an AuthorPage of all OpenAlex authors across all of the project's publications
- a map of raw DOI -> List[Author] for attaching authors to individual publications
"""
if not project_ids:
return {}, {}
query = {"bool": {"filter": [{"terms": {"projectID": project_ids}}]}}
response = await elasticsearch.search(
query=query,
index=ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD,
cluster=ESCluster.INSE,
source=["projectID", "doi", "qaProcessedDoi"],
size=10000,
)
dois_by_project: Dict[str, Set[str]] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
pid = source.get("projectID")
if not pid:
continue
dois_by_project.setdefault(pid, set())
doi = source.get("doi")
qa_processed_doi = source.get("qaProcessedDoi")
if doi:
dois_by_project[pid].add(doi)
elif qa_processed_doi:
dois_by_project[pid].add(qa_processed_doi)
all_dois = list({doi for dois in dois_by_project.values() for doi in dois})
# single ES call for the whole batch, keyed by raw DOI
author_ids_by_doi = await get_openalex_author_ids_by_dois(dois=all_dois)
all_author_ids = list({aid for ids in author_ids_by_doi.values() for aid in ids})
# single ES call to fetch all Author objects across every project
author_page = await get_authors_by_ids(author_ids=all_author_ids)
authors_by_id = {author.id: author for author in author_page.elements}
author_page_by_project: Dict[str, AuthorPage] = {}
doi_author_map_by_project: Dict[str, Dict[str, List[Author]]] = {}
for pid in project_ids:
dois = dois_by_project.get(pid, set())
doi_authors: Dict[str, List[Author]] = {}
project_author_ids: Set[str] = set()
for doi in dois:
ids_for_doi = author_ids_by_doi.get(doi, [])
doi_authors[doi] = [authors_by_id[aid] for aid in ids_for_doi if aid in authors_by_id]
project_author_ids.update(ids_for_doi)
doi_author_map_by_project[pid] = doi_authors
authors_for_project = [authors_by_id[aid] for aid in project_author_ids if aid in authors_by_id]
author_page_by_project[pid] = AuthorPage(
elements=authors_for_project,
total=len(authors_for_project),
page=0,
size=len(authors_for_project),
)
return author_page_by_project, doi_author_map_by_project
async def get_openalex_authors_for_cordis_project_ids(
project_ids: List[str],
) -> Dict[str, AuthorPage]:
"""Returns a mapping of project_id -> AuthorPage for a batch of projects."""
author_page_by_project, _ = await _fetch_openalex_author_data_for_project_ids(project_ids)
return author_page_by_project
async def _fetch_authors_and_topics_for_project(
project_id: str,
project_type: EuCordisProjectType,
) -> Tuple[Optional[AuthorPage], List[Topic], Dict[str, List[Author]]]:
"""Fetches OpenAlex authors (project-level + per-DOI map) and mapped topics for a single project."""
(author_page_by_project, doi_author_map_by_project), topics_lookup = await asyncio.gather(
_fetch_openalex_author_data_for_project_ids([project_id]),
get_openalex_topics_for_eu_projects({project_type: [project_id]}),
)
author_page = author_page_by_project.get(project_id)
doi_author_map = doi_author_map_by_project.get(project_id, {})
raw_topic_matches = sorted(
topics_lookup.get((project_type, project_id), []),
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
topics = [
EuCordisProjectSummary.topic_from_match(match)
for match in raw_topic_matches
if isinstance(match, dict)
]
return author_page, topics, doi_author_map
def _attach_authors_to_publications(
publications: List[Any],
doi_author_map: Dict[str, List[Author]],
) -> List[Any]:
"""Sets oa_authors on each publication by matching its doi/qaProcessedDoi against doi_author_map."""
for pub in publications:
doi = getattr(pub, "doi", None)
qa_processed_doi = getattr(pub, "qa_processed_doi", None)
authors = doi_author_map.get(doi) if doi else None
if not authors and qa_processed_doi:
authors = doi_author_map.get(qa_processed_doi)
pub.oa_authors = authors or []
return publications
async def _fetch_related_entities_parallel(
@@ -244,10 +344,10 @@ async def _fetch_related_entities(
return grouped
async def _enrich_fp7_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[Fp7ProjectDetails]:
"""Enriches a single FP7 project with all related data."""
try:
@@ -256,42 +356,68 @@ async def _enrich_fp7_project(
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
related, (authors, topics, doi_author_map) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
related["publications"] = _attach_authors_to_publications(
related.get("publications", []), doi_author_map
)
return Fp7ProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_h2020_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[H2020ProjectDetails]:
"""Enriches a single H2020 project with all related data."""
try:
project = H2020Project.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
related, (authors, topics, doi_author_map) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
related["publications"] = _attach_authors_to_publications(
related.get("publications", []), doi_author_map
)
return H2020ProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
async def _enrich_heu_project(
project_id: str,
project_source: Dict[str, Any],
project_type: EuCordisProjectType,
) -> Optional[HEUProjectDetails]:
"""Enriches a single Horizon Europe project with all related data."""
try:
project = HEUProject.model_validate(project_source)
except Exception as e:
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
return None
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
related, (authors, topics, doi_author_map) = await asyncio.gather(
_fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS),
_fetch_authors_and_topics_for_project(project_id, project_type),
)
return HEUProjectDetails.from_project_with_relations(project=project, **related)
related["publications"] = _attach_authors_to_publications(
related.get("publications", []), doi_author_map
)
return HEUProjectDetails.from_project_with_relations(
project=project, oa_authors=authors, oa_topics=topics, **related
)
@@ -432,7 +558,6 @@ async def get_eu_project_ids_by_organization_filters(
for org_name in organization_names:
if name and org_name.lower() in name.lower():
project_org_matches[project_id].add(f"name:{org_name.lower()}")
print(f"Project organization matches for {project_type}: {project_org_matches}")
required_orgs = set()
# Add ID requirements
@@ -454,7 +579,6 @@ async def get_eu_project_ids_by_organization_filters(
continue
result[project_type].append(project_id)
print(f"Final project IDs by type: {result}")
return result
async def get_eu_organizations_for_projects(
@@ -580,9 +704,13 @@ async def get_eu_euroscivoc_for_projects(
return lookup
async def search_eu_cordis_projects(
page: int,
size: int,
class _NoMatchingEuProjects(Exception):
"""Internal sentinel: some filter resolved to zero matching project IDs,
so the overall query can short-circuit to an empty result without
hitting Elasticsearch again."""
async def _build_eu_cordis_search_query(
project_types: Optional[List[EuCordisProjectType]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
@@ -597,16 +725,16 @@ async def search_eu_cordis_projects(
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
) -> EuCordisProjectSearchPage:
) -> Tuple[Dict[str, Any], List[EuCordisProjectType], List[Any]]:
"""
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
Mirrors DFG behavior:
- fuzzy=True + topic_ids => OpenAlex topic mapping lookup
- filter_topic_ids are always applied independently
- selected organizations/topics must ALL match
Builds the (query, project_types, indices) tuple shared by every EU CORDIS
project search/aggregation. Centralizing this means the filters applied to
the results table and to any derived aggregation (e.g. funding-over-time)
can never drift apart.
Raises _NoMatchingEuProjects if any filter resolves to zero project IDs,
so callers can short-circuit to an empty result without a wasted query.
"""
if not project_types:
project_types = [
@@ -622,7 +750,7 @@ async def search_eu_cordis_projects(
# === Author filter resolved in service layer ===
if author_project_ids is not None:
if not author_project_ids:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append({"terms": {"id": author_project_ids}})
@@ -635,7 +763,7 @@ async def search_eu_cordis_projects(
topic_filter = _eu_project_type_index_filter(topic_project_ids_by_type)
if not topic_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(topic_filter)
@@ -690,7 +818,7 @@ async def search_eu_cordis_projects(
topic_filter = _eu_project_type_index_filter(filter_topic_project_ids_by_type)
if not topic_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(topic_filter)
@@ -704,7 +832,7 @@ async def search_eu_cordis_projects(
org_filter = _eu_project_type_index_filter(org_project_ids_by_type)
if not org_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(org_filter)
@@ -767,12 +895,64 @@ async def search_eu_cordis_projects(
country_filter = _eu_project_type_index_filter(country_project_ids_by_type)
if not country_filter:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
raise _NoMatchingEuProjects()
must_clauses.append(country_filter)
query = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
return query, project_types, indices
async def search_eu_cordis_projects(
page: int,
size: int,
project_types: Optional[List[EuCordisProjectType]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
author_project_ids: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
title: Optional[str] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
) -> EuCordisProjectSearchPage:
"""
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
Mirrors DFG behavior:
- fuzzy=True + topic_ids => OpenAlex topic mapping lookup
- filter_topic_ids are always applied independently
- selected organizations/topics must ALL match
"""
try:
query, project_types, indices = await _build_eu_cordis_search_query(
project_types=project_types,
organization_ids=organization_ids,
organization_names=organization_names,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
except _NoMatchingEuProjects:
return EuCordisProjectSearchPage(elements=[], total=0, page=page, size=size)
sort_direction = sort_direction.lower()
if sort_direction not in ["asc", "desc"]:
sort_direction = "asc"
@@ -862,7 +1042,108 @@ async def search_eu_cordis_projects(
page=page,
size=size,
)
async def get_eu_cordis_projects_funding_data(
project_types: Optional[List[EuCordisProjectType]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
author_project_ids: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
title: Optional[str] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
fuzzy: bool = False,
) -> List[Dict[str, Any]]:
"""
Fetches ONLY the fields needed for a funding-over-time aggregation
(id, startDate, endDate, ecMaxContribution) for every EU CORDIS project
matching the given filters.
This intentionally skips the author/organization/CORDIS-topic/EuroSciVoc/
OpenAlex-topic enrichment that `search_eu_cordis_projects` performs per
project, since none of that is needed to compute funding totals. That
enrichment is what makes the funding-over-time endpoint slow for
institutions with many projects - this function avoids it entirely.
"""
try:
query, _, indices = await _build_eu_cordis_search_query(
project_types=project_types,
organization_ids=organization_ids,
organization_names=organization_names,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
except _NoMatchingEuProjects:
return []
results: List[Dict[str, Any]] = []
page_size = 5000
search_after: Optional[List[Any]] = None
while True:
body: Dict[str, Any] = {
"size": page_size,
"track_total_hits": False,
"_source": ["id", "startDate", "endDate", "ecMaxContribution"],
"query": query,
# "id" is unique per project and used elsewhere as a term-filter
# field, so it's mapped as keyword - safe + deterministic sort
# key for search_after pagination across an arbitrarily large
# result set.
"sort": [{"id": {"order": "asc", "unmapped_type": "keyword"}}],
}
if search_after is not None:
body["search_after"] = search_after
response = await elasticsearch.search(
index=indices,
cluster=ESCluster.INSE,
body=body,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit.get("_source", {})
results.append(
{
"id": source.get("id"),
"start_date": source.get("startDate"),
"end_date": source.get("endDate"),
"ec_max_contribution": source.get("ecMaxContribution"),
}
)
if len(hits) < page_size:
break
search_after = hits[-1].get("sort")
if not search_after:
break
return results
def _to_openalex_doi_url(raw_doi: str) -> str:
"""CORDIS stores bare DOIs (e.g. '10.1093/toxsci/kfs018');
OpenAlex works index stores full URLs ('https://doi.org/10.1093/toxsci/kfs018')."""
+168 -51
View File
@@ -46,7 +46,45 @@ async def get_dfg_institution_names_by_ids(institution_ids: List[int]) -> Option
except Exception as e:
logger.exception(f"Error fetching institution names for ids {institution_ids}: {str(e)}")
return []
async def get_institution_ids_by_institution_aliases(institution_aliases: list[str]) -> list[int]:
if not institution_aliases:
return []
response = await elasticsearch.search(
index=ESIndex.DFG_INSTITUTES,
cluster=ESCluster.INSE,
body={
"size": 10000,
"_source": ["institute_id"],
"query": {
"bool": {
"should": [
clause
for name in institution_aliases
for clause in (
# {"match": {"root_name_de": {"query": name, "operator": "and"}}},
# {"match": {"root_name_en": {"query": name, "operator": "and"}}},
# {"match": {"institute_name_de": {"query": name, "operator": "and"}}},
# {"match": {"institute_name_en": {"query": name, "operator": "and"}}},
{"match_phrase": {"root_name_de":name}},
{"match_phrase": {"root_name_en":name}},
{"match_phrase": {"institute_name_de":name}},
{"match_phrase": {"institute_name_en": name}},
)
],
"minimum_should_match": 1,
}
}
},
)
return list(
{
hit["_source"]["institute_id"]
for hit in response.get("hits", {}).get("hits", [])
if hit.get("_source", {}).get("institute_id") is not None
}
)
async def get_person_ids_by_institution_ids(
institution_ids: list[int],
) -> list[int]:
@@ -59,10 +97,13 @@ async def get_person_ids_by_institution_ids(
body={
"size": 10000,
"_source": ["person_id"],
"query": {
"terms": {
"institute_id": institution_ids
}
"query": { "bool":{
"should": [
{"terms": {"institute_id": institution_ids}},
{"terms": {"root_id": institution_ids}},
],
"minimum_should_match": 1,
}
}
},
)
@@ -74,6 +115,72 @@ async def get_person_ids_by_institution_ids(
if hit.get("_source", {}).get("person_id") is not None
}
)
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
if not topic_ids:
return []
required_topics = set(topic_ids)
project_topics: dict[str, Set[str]] = defaultdict(set)
page_size = 1000
from_ = 0
while True:
body = {
"size": page_size,
"from": from_,
"_source": ["project_id", "topic_matches"],
"query": {
"terms": {
"topic_matches.topic_id.keyword": topic_ids
}
},
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
cluster=ESCluster.INSE,
body=body,
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
for hit in hits:
source = hit["_source"]
project_id = source.get("project_id")
if not project_id:
continue
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
for match in topic_matches:
topic_id = match.get("topic_id")
if topic_id in required_topics:
project_topics[project_id].add(topic_id)
if len(hits) < page_size:
break
from_ += page_size
return [
project_id
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""Fetches project IDs whose topic_matches contain EVERY given topic ID,
even if the topics are distributed across multiple documents for the same project.
@@ -137,63 +244,73 @@ async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
for project_id, found_topics in project_topics.items()
if required_topics.issubset(found_topics)
]
async def get_openalex_topics_for_dfg_projects(
project_ids: List[str],
) -> Dict[int, List[Dict[str, Any]]]:
"""Fetches OpenAlex topic matches for the given DFG project IDs.
Args:
project_ids (List[str]): The DFG project IDs to fetch topics for.
Returns:
Dict[int, List[Dict[str, Any]]]: Mapping of project_id -> list of topic match dicts,
each containing topic_id, topic_display_name, domain, field, subfield, rank.
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of BUND project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
topic_lookup: Dict[int, List[Dict[str, Any]]] = {}
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
page_size = 1000
from_ = 0
# print(f"Fetching topics for {len(project_ids)} DFG projects in batches of {page_size}...{project_ids}")
while True:
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_TOPICS,
cluster=ESCluster.INSE,
body={
"size": page_size,
"from": from_,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
},
)
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
hits = response.get("hits", {}).get("hits", [])
if not hits:
break
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[pid] = src.get("topic_matches", [])
return lookup
async def get_openalex_topics_for_dfg_projects(
project_ids: List[str],
) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of DFG project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
for hit in hits:
source = hit["_source"]
project_id = int(source.get("project_id"))
if project_id is None:
continue
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
topic_matches = source.get("topic_matches") or []
if isinstance(topic_matches, dict):
topic_matches = [topic_matches]
response = await elasticsearch.search(
index=ESIndex.PROJECTS_DFG_TOPICS,
body=body,
cluster=ESCluster.INSE
)
topic_lookup.setdefault(project_id, []).extend(topic_matches)
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[str(pid)] = src.get("topic_matches", [])
if len(hits) < page_size:
break
from_ += page_size
#logger.info(f"Fetched topics for {len(topic_lookup)} DFG projects.")
return topic_lookup
return lookup
async def get_person_institutes(
person_ids: list[int],
+29 -8
View File
@@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDet
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
from inse.authors.v2.model import AuthorPage
from inse.projects.bund_institutions.model import BundInstitutionSummary
from typing import Union
class ProjectType(StrEnum):
@@ -75,6 +76,11 @@ class BundProjectSummary(BundProject):
description="The OpenAlex topics of the project",
examples=[["Artificial Intelligence", "Machine Learning"]],
)
institution: Optional[BundInstitutionSummary] = Field(
default=None,
description="The executing agency / recipient institution for this project, "
"derived from the project's own agency fields.",
)
@classmethod
def from_hit(cls, hit: dict) -> "BundProjectSummary":
@@ -91,7 +97,6 @@ class BundProjectSummary(BundProject):
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
)
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
print(f"oa_topics: {oa_topics}")
return cls(
funding_code=source.get("Förderkennzeichen"),
department=source.get("Ressort"),
@@ -110,8 +115,8 @@ class BundProjectSummary(BundProject):
topic=source.get("Thema"),
performance_plan_system=source.get("Leistungsplansystematik"),
performance_plan_system_text=source.get("Klartext Leistungsplansystematik"),
funding_start=source.get("Förderbeginn"),
funding_end=source.get("Förderende"),
funding_start=source.get("funding_start"),
funding_end=source.get("funding_end"),
grant_amount=source.get("Fördersumme"),
funding_profile=source.get("Förderprofil"),
joint_project=source.get("Verbundprojekt"),
@@ -122,6 +127,7 @@ class BundProjectSummary(BundProject):
new=source.get("neu"),
duration=source.get("Laufzeit"),
oa_topics=oa_topics,
institution=BundInstitutionSummary.from_source(source),
)
@staticmethod
@@ -258,19 +264,33 @@ class DfgProjectSummary(BaseModel):
institution = None
if person.get("institute_id") is not None:
institution = DfgInstitutionSummary(
institute = DfgInstitutionSummary(
id=person["institute_id"],
institute_name_de=person.get("institute_name_de"),
institute_name_en=person.get("institute_name_en"),
address_country_de=person.get("address_country_de"),
address_country_en=person.get("address_country_en"),
root_id=person["root_id"],
root_name_de=person.get("root_name_de"),
root_name_en=person.get("root_name_en"),
root_id=None,
root_name_de=None,
root_name_en=None,
)
institutions[person["institute_id"]] = institution
institutions[f"institute:{person['institute_id']}"] = institute
if person.get("root_id") is not None:
root_institution = DfgInstitutionSummary(
id=person["root_id"],
institute_name_de=person.get("root_name_de"),
institute_name_en=person.get("root_name_en"),
address_country_de=person.get("address_country_de"),
address_country_en=person.get("address_country_en"),
root_id=None,
root_name_de=None,
root_name_en=None,
)
institutions[f"root:{person['root_id']}"] = root_institution
if person.get("person_id") is not None:
project_persons.append(
DfgPersonSummary(
@@ -284,6 +304,7 @@ class DfgProjectSummary(BaseModel):
)
)
topics_raw = source.get("topics") or []
print(f"Raw topics for DFG project {hit.get('_id', '')}: {topics_raw}")
topics = None
if isinstance(topics_raw, list) and topics_raw:
# Sort by rank if present, so the most relevant topic comes first
@@ -1,6 +1,6 @@
import json
import logging
from typing import Any, Dict, List, Optional, Set, Tuple
from typing import Any, Dict, List, Optional, Set
import urllib
from inse.config import get_settings
@@ -21,7 +21,7 @@ from inse.models.dfg_project_details import DfgProjectDetails
from inse.models.bund_project_details import BundProjectDetails
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids,get_bund_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects, get_institution_ids_by_institution_aliases
settings = get_settings()
@@ -29,66 +29,6 @@ logger = logging.getLogger(__name__)
logger.setLevel(settings.logging_level)
DFG_PERSON_FIELDS: List[str] = [
"Antragsteller",
"Antragstellerin",
"Antragstellerinnen",
"Antragstellerinnen / Antragsteller",
"Beteiligte Person",
"Beteiligte Personen",
"Co-Sprecher",
"Co-Sprecherinnen / Co-Sprecher",
"Ehemalige Antragsteller",
"Ehemalige Antragstellerin",
"Ehemalige Antragstellerinnen",
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
"Ehemaliger Antragsteller",
"Gastgeber",
"Gastgeberin",
"Gastgeberinnen",
"Gastgeberinnen / Gastgeber",
"Kooperationspartner",
"Kooperationspartnerin",
"Kooperationspartnerinnen",
"Kooperationspartnerinnen / Kooperationspartner",
"Leiter",
"Leiterin",
"Leiterinnen",
"Leiterinnen / Leiter",
"Mitantragsteller",
"Mitantragstellerin",
"Mitantragstellerinnen",
"Mitantragstellerinnen / Mitantragsteller",
"Mitverantwortlich",
"Mitverantwortlich(e)",
"Mitverantwortliche",
"Sprecher",
"Sprecher (IGK-Partner)",
"Sprecherin",
"Sprecherin (IGK-Partner)",
"Sprecherinnen",
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
"Sprecherinnen / Sprecher",
"Teilprojektleiter",
"Teilprojektleiterin",
"Teilprojektleiterinnen",
"Teilprojektleiterinnen / Teilprojektleiter",
"ausländ. Mitantragstellerin",
"ausländ. Mitantragstellerinnen",
"ausländ. Mitantragstellerinnen / ausländische Mitantragsteller",
"ausländische Mitantragsteller",
"ausländischer Mitantragsteller",
"beteiligte Wissenschaftler",
"beteiligte Wissenschaftlerin",
"beteiligte Wissenschaftlerinnen",
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
"beteiligter Wissenschaftler",
"person_creater_name",
"stellvertr. Sprecher",
"stellvertr. Sprecherin",
"stellvertr. Sprecherinnen / stellvertr. Sprecher",
]
# BUND
@@ -204,10 +144,13 @@ async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails
query=query,
size=1,
)
hits = response.get("hits", {}).get("hits", [])
if hits:
hit = hits[0]
elastic_id = hit["_id"]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=[elastic_id])
hit["_source"]["oa_topics"] = topic_lookup.get(elastic_id, [])
details = BundProjectDetails.from_elastic_hit(hit=hit)
return details
return None
@@ -380,7 +323,6 @@ async def get_dfg_project_ids_by_names(names: List[str]) -> List[str]:
for project in hit.get("_source", {}).get("projects", [])
if "project_id" in project
}
print(f"Retrieved project IDs for names {len(project_ids)}: {project_ids}")
return list(project_ids)
async def get_dfg_project_ids_by_dois(dois: List[str]) -> List[str]:
@@ -405,8 +347,9 @@ async def get_dfg_project_ids_by_dois(dois: List[str]) -> List[str]:
async def search_dfg_projects(
page: int,
size: int,
institution_aliases: Optional[List[str]] = None,
project_ids: Optional[List[int]] = None,
institution_ids: Optional[List[int]] = None,
institution_ids: Optional[List[int]] = [],
names: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
@@ -466,7 +409,7 @@ async def search_dfg_projects(
"query": {},
}
must_clauses: List[Dict[str, Any]] = []
must_clauses: List[Dict[str, Any]] = []
if project_ids:
must_clauses.append({"terms": {"id": project_ids}})
# === Primary search clause: mutually exclusive fuzzy(topic_ids) vs keyword phrase search ===
@@ -567,6 +510,24 @@ async def search_dfg_projects(
if name_must_clauses:
must_clauses.append({"bool": {"must": name_must_clauses}})
if institution_aliases:
matching_institution_ids = await get_institution_ids_by_institution_aliases(
institution_aliases=institution_aliases
)
if not matching_institution_ids:
return DfgProjectPage(elements=[], total=0, page=page, size=size)
matching_person_ids = await get_person_ids_by_institution_ids(
institution_ids=matching_institution_ids
)
must_clauses.append(
{
"nested": {
"path": "persons",
"query": {"terms": {"persons.person_id": matching_person_ids}},
}
}
)
if institution_ids:
matching_person_ids = await get_person_ids_by_institution_ids(
institution_ids=institution_ids
@@ -607,7 +568,7 @@ async def search_dfg_projects(
sort_config = {"id": {"order": sort_direction}}
body["sort"] = [sort_config]
# print(f"Executing DFG project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
response = await elasticsearch.search(
index=ESIndex.DFG_PROJECTS,
@@ -631,9 +592,7 @@ async def search_dfg_projects(
for hit in hits:
source = hit["_source"]
project_id = source["id"]
source["topics"] = topic_lookup.get(project_id, [])
source["topics"] = topic_lookup.get(str(project_id), [])
persons = source.get("persons", [])
for person in persons:
person_id = person.get("person_id")
@@ -679,6 +638,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
Returns:
Optional[DfgProjectDetails]: The project details or None if not found.
"""
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id])
query = {"ids": {"values": [project_id]}}
response = await elasticsearch.search(
@@ -690,79 +650,43 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
if hits:
hit = hits[0]
hit["_source"]["topics"] = topic_lookup.get(project_id, [])
details = DfgProjectDetails.from_elastic_hit(hit=hit)
return details
return None
#BUND
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
"""
Query the `projects_bund_openalex_topics` index to find BUND project IDs
that match any of the given OpenAlex topic IDs.
"""
body: Dict[str, Any] = {
"size": 0,
"query": {
"terms": {
"topic_matches.topic_id": topic_ids
}
},
"aggs": {
"project_ids": {
"terms": {
"field": "project_id.keyword",
"size": 10000
def _bund_year_filters(field: str, years: List[str]) -> Dict[str, Any]:
should = []
for year in years:
year = str(year).strip()
if not year:
continue
should.append(
{
"range": {
field: {
"gte": f"01.01.{year}",
"lte": f"31.12.{year}",
}
}
}
)
return {
"bool": {
"should": should,
"minimum_should_match": 1,
}
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
print(f"Received response for topic_ids {topic_ids}: {json.dumps(response, indent=2)}")
buckets = response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
return [bucket["key"] for bucket in buckets]
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
"""
Retrieve OpenAlex topic details for a list of BUND project IDs.
Returns a dict mapping `project_id` -> list of topic_match objects.
"""
if not project_ids:
return {}
body: Dict[str, Any] = {
"size": 10000,
"query": {
"terms": {
"project_id.keyword": project_ids
}
},
"_source": ["project_id", "topic_matches"]
}
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_TOPICS,
body=body,
cluster=ESCluster.INSE
)
lookup: Dict[str, List[Dict]] = {}
for hit in response.get("hits", {}).get("hits", []):
src = hit["_source"]
pid = src.get("project_id")
if pid:
lookup[pid] = src.get("topic_matches", [])
return lookup
async def search_bund_projects_with_filters(
executing_agency: Optional[List[str]] = None,
institution_ids: Optional[List[int]] = None,
oa_institution_aliases: Optional[List[str]] = None,
raw_oa_institution_id: Optional[str] = None,
funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings
title: Optional[str] = None,
keywords: Optional[List[str]] = None,
@@ -776,12 +700,18 @@ async def search_bund_projects_with_filters(
sort_by: str = "title",
sort_direction: str = "asc",
fuzzy: bool = False,
skip_topic_enrichment: bool = False,
) -> BundProjectPage:
"""
Main search function for BUND projects, analogous to the DFG search.
"""
from_ = page * size
skip_topic_enrichment: when True, skips the extra OpenAlex-topics lookup
used to populate `oa_topics` on each result. Callers that only need core
project fields (e.g. funding-over-time aggregation) should set this to
avoid the unnecessary ES round trip.
"""
from_ = page * size
#institution_ids = ["I62318514"]
# Fields we need to build BundProject objects (validation aliases match these exact names)
source_fields = [
"Förderkennzeichen",
@@ -812,7 +742,6 @@ async def search_bund_projects_with_filters(
"datum",
"neu",
"Laufzeit",
# Also include funding_start/end for sorting and filtering (they may also be needed)
"funding_start",
"funding_end",
]
@@ -825,13 +754,28 @@ async def search_bund_projects_with_filters(
}
must_clauses: List[Dict[str, Any]] = []
if oa_institution_aliases:
must_clauses.append(
{
"bool": {
"should": [
clause
for name in oa_institution_aliases
for clause in (
{"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}},
{"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}},
)
],
"minimum_should_match": 1,
}
}
)
# === Primary search clause: fuzzy(topic_ids) vs keyword phrase search ===
if fuzzy and topic_ids:
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids)
if not matching_project_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_project_ids}})
must_clauses.append({"terms": {"_id": matching_project_ids}})
elif keywords:
keyword_clauses = []
@@ -841,7 +785,7 @@ async def search_bund_projects_with_filters(
keyword_clauses.append({
"multi_match": {
"query": kw,
"fields": ["Verbundprojekt"], # searching title/acronym field
"fields": ["Verbundprojekt","Thema"], # searching title/acronym field
"type": "phrase_prefix",
"max_expansions": 100,
}
@@ -854,21 +798,38 @@ async def search_bund_projects_with_filters(
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
if not matching_filter_ids:
return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_filter_ids}})
must_clauses.append({"terms": {"_id": matching_filter_ids}})
if title:
must_clauses.append({
"multi_match": {
"query": title,
"fields": ["Verbundprojekt"],
"fields": ["Verbundprojekt","Thema"], # searching title field
"type": "phrase_prefix",
"max_expansions": 100,
}
})
# print(f"Executing BUND project search with institution_ids: {institution_ids}, executing_agency: {executing_agency}, funding_arts: {funding_arts}, countries: {countries}, funding_start_years: {funding_start_years}, funding_end_years: {funding_end_years}")
if executing_agency:
must_clauses.append({"terms": {"Ausführende Stelle.keyword": executing_agency}})
# institution_names = await institutions_search_client.get_institution_aliases_by_oa_institution_id(executing_agency[0].split("/")[-1])
# institution_page = await institutions_search_client.get_institutions_by_alias(alias=institution_names[0])
# print(f"Retrieved institution names for IDs {executing_agency}: {institution_names}")
# print(f"Retrieved institution page for names {institution_names}: {institution_page}")
# if not institution_names:
# return BundProjectPage(elements=[], total=0, page=page, size=size)
must_clauses.append({
"bool": {
"should": [
clause
for name in executing_agency
for clause in (
{"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}},
{"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}},
)
],
"minimum_should_match": 1,
}
})
if funding_arts:
must_clauses.append({"terms": {"Förderart.keyword": funding_arts}})
@@ -876,13 +837,12 @@ async def search_bund_projects_with_filters(
must_clauses.append({"terms": {"Staat.keyword": countries}})
if funding_start_years:
must_clauses.append({"terms": {"funding_start": funding_start_years}})
must_clauses.append(_bund_year_filters("funding_start", funding_start_years))
if funding_end_years:
must_clauses.append({"terms": {"funding_end": funding_end_years}})
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
# === Sorting ===
sort_by = sort_by.strip().lower()
sort_direction = sort_direction.strip().lower()
@@ -900,7 +860,7 @@ async def search_bund_projects_with_filters(
sort_config = {"Förderkennzeichen.keyword": {"order": sort_direction}}
body["sort"] = [sort_config]
# print(f"Executing BUND project search with body: {json.dumps(body, indent=2)}")
# === Execute Search ===
response = await elasticsearch.search(
index=ESIndex.PROJECTS_BUND_V1,
@@ -911,12 +871,13 @@ async def search_bund_projects_with_filters(
hits = response.get("hits", {}).get("hits", [])
# Enrich with OpenAlex topics
project_ids = [hit["_id"] for hit in hits]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids)
print(f"Enriched BUND projects with topics: {json.dumps(topic_lookup, indent=2)}")
for hit in hits:
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
# Enrich with OpenAlex topics (skipped for callers that don't need them,
# e.g. funding-over-time aggregation, to avoid an unnecessary ES call)
if not skip_topic_enrichment:
project_ids = [hit["_id"] for hit in hits]
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids)
for hit in hits:
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
return _complete_response_to_bund_project_page(response, page, size)
@@ -1084,4 +1045,4 @@ def _hit_to_funding_project(hit: Dict[str, Any]) -> FundingProject:
else:
raise ValueError(
"The provided hit does not belong to a recognized project index."
)
)
+162 -12
View File
@@ -100,7 +100,9 @@ async def get_single_dfg_project(
response_model_by_alias=False,
)
async def search_bund_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
executing_agency: Annotated[
Optional[List[str]],
Query(description="Executing Agencies (Ausführende Stellen) to filter by."),
@@ -137,9 +139,9 @@ async def search_bund_projects(
Optional[List[str]],
Query(description="Organization countries."),
] = None,
institution_ids: Annotated[
Optional[List[str]],
Query(description="Institution IDs to filter by."),
raw_oa_institution_id: Annotated[
Optional[str],
Query(description="The ID of the institution to filter by."),
] = None,
page: Annotated[int, Query(description="The page number.", ge=0)] = 0,
size: Annotated[int, Query(description="The page size.", ge=1)] = 20,
@@ -154,6 +156,7 @@ async def search_bund_projects(
] = False,
) -> BundProjectPage:
return await projects_service.search_bund_projects_with_filters(
institutions_search_client=institutions_search_client,
executing_agency=executing_agency,
funding_arts=funding_arts,
title=title,
@@ -163,7 +166,7 @@ async def search_bund_projects(
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
institution_ids=institution_ids,
raw_oa_institution_id=raw_oa_institution_id,
page=page,
size=size,
sort_by=sort_by,
@@ -432,7 +435,11 @@ async def get_single_eu_cordis_project(
@router.get(
"/institution/bund/funding-over-time",
summary="Get funding over time for bund projects.",
description="Returns the funding over time for bund projects associated with the specified institution.",
description=(
"Returns the funding over time for BUND projects. Accepts the same "
"filters as /bund/search, so the funding total can be made to match "
"whatever the results table is currently filtered to."
),
operation_id="getInstitutionBundProjectsFundingOverTime",
responses={
status.HTTP_200_OK: {
@@ -448,19 +455,73 @@ async def get_institution_bund_projects_funding_over_time(
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
str, Query(description="The institution ID to filter by.")
],
Optional[str], Query(description="The institution ID to filter by.")
] = None,
executing_agency: Annotated[
Optional[List[str]],
Query(description="Executing Agencies (Ausführende Stellen) to filter by."),
] = None,
funding_arts: Annotated[
Optional[List[str]],
Query(description="Project types to include: fp7, h2020, heu."),
] = None,
title: Annotated[
Optional[str],
Query(description="Project title/acronym search."),
] = None,
keywords: Annotated[
Optional[List[str]],
Query(description="Raw keywords to search in title/objective/keywords/topics."),
] = None,
topic_ids: Annotated[
Optional[List[str]],
Query(description="OpenAlex topic IDs used for fuzzy topic resolution."),
] = None,
filter_topic_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex topic IDs used as mandatory filters."),
] = None,
funding_start_years: Annotated[
Optional[List[str]],
Query(description="Funding start years."),
] = None,
funding_end_years: Annotated[
Optional[List[str]],
Query(description="Funding end years."),
] = None,
countries: Annotated[
Optional[List[str]],
Query(description="Organization countries."),
] = None,
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> InstitutionFunderSummary:
return await projects_service.get_institution_bund_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
executing_agency=executing_agency,
funding_arts=funding_arts,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
fuzzy=fuzzy,
)
@router.get(
"/institution/eu/funding-over-time",
summary="Get funding over time for EU projects.",
description="Returns the funding over time for EU projects associated with the specified institution.",
description=(
"Returns the funding over time for EU CORDIS projects. Accepts the "
"same filters as /eu/search, so the funding total can be made to "
"match whatever the results table is currently filtered to."
),
operation_id="getInstitutionCordisEuProjectsFundingOverTime",
responses={
status.HTTP_200_OK: {
@@ -476,12 +537,93 @@ async def get_institution_cordis_eu_projects_funding_over_time(
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
str, Query(description="The institution ID to filter by.")
],
Optional[str],
Query(description="OpenAlex institution ID to filter by."),
] = None,
author_id: Annotated[
Optional[str],
Query(description="OpenAlex author ID to filter by."),
] = None,
author_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex author IDs to filter by. All selected authors must match."),
] = None,
organization_ids: Annotated[
Optional[List[str]],
Query(description="CORDIS organisation IDs. All selected organizations must match."),
] = None,
organization_names: Annotated[
Optional[List[str]],
Query(description="CORDIS organization names. All selected organizations must match."),
] = None,
project_types: Annotated[
Optional[List[EuCordisProjectType]],
Query(description="Project types to include: fp7, h2020, heu."),
] = None,
title: Annotated[
Optional[str],
Query(description="Project title/acronym search."),
] = None,
keywords: Annotated[
Optional[List[str]],
Query(description="Raw keywords to search in title/objective/keywords/topics."),
] = None,
topic_ids: Annotated[
Optional[List[str]],
Query(description="OpenAlex topic IDs used for fuzzy topic resolution."),
] = None,
filter_topic_ids: Annotated[
Optional[List[str]],
Query(description="Additional OpenAlex topic IDs used as mandatory filters."),
] = None,
funding_start_years: Annotated[
Optional[List[str]],
Query(description="Funding start years."),
] = None,
funding_end_years: Annotated[
Optional[List[str]],
Query(description="Funding end years."),
] = None,
countries: Annotated[
Optional[List[str]],
Query(description="Organization countries."),
] = None,
framework_programmes: Annotated[
Optional[List[str]],
Query(description="Framework programme filters."),
] = None,
funding_schemes: Annotated[
Optional[List[str]],
Query(description="Funding scheme filters."),
] = None,
statuses: Annotated[
Optional[List[str]],
Query(description="Project status filters."),
] = None,
fuzzy: Annotated[
bool,
Query(description="Use OpenAlex topic-id resolution if true, otherwise raw keyword search."),
] = False,
) -> InstitutionFunderSummary:
return await projects_service.get_institution_cordis_eu_projects_funding_over_time(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
author_id=author_id,
author_ids=author_ids,
organization_ids=organization_ids,
organization_names=organization_names,
project_types=project_types,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
@@ -500,6 +642,12 @@ async def get_institution_cordis_eu_projects_funding_over_time(
response_model_by_alias=False,
)
async def get_dfg_projects(
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
raw_oa_institution_id: Annotated[
Optional[str], Query(description="The openalex institution ID to filter by.")
] = None,
author_id: Annotated[Optional[str], Query(description="The openalex author ID to filter by.")] = None,
author_filter_ids: Annotated[Optional[List[int]], Query(description="The dfg author IDs to filter by.")] = None,
institution_ids: Annotated[
@@ -557,6 +705,8 @@ async def get_dfg_projects(
fuzzy,
)
return await projects_service.get_dfg_projects_by_author_id(
institutions_search_client=institutions_search_client,
raw_oa_institution_id=raw_oa_institution_id,
author_id=author_id,
author_filter_ids=author_filter_ids,
institution_ids=institution_ids,
@@ -612,4 +762,4 @@ async def search_projects(
title=title,
sort_by=sort_by,
sort_direction=sort_direction,
)
)
+183 -50
View File
@@ -29,6 +29,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HE
from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDetails
from inse.projects.eu_cordis_projects_client import (
get_enriched_cordis_project_by_id,
get_eu_cordis_projects_funding_data,
search_eu_cordis_projects as _search_eu_cordis_projects_es,
)
from typing import Union
@@ -148,6 +149,8 @@ async def _get_dfg_project_ids_for_openalex_authors(
return list(set.intersection(*project_sets))
async def get_dfg_projects_by_author_id(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: Optional[str],
author_id: Optional[str],
author_filter_ids: Optional[List[int]],
institution_ids: Optional[List[int]],
@@ -206,16 +209,24 @@ async def get_dfg_projects_by_author_id(
"No author names found for author_filter_ids=%s",
author_filter_ids,
)
if institution_ids:
logger.debug(
"No institutions found for institution_ids=%s",
institution_ids,
institution_aliases = []
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
if not institution_aliases:
return DfgProjectPage(
elements=[],
page=page,
size=size,
total=0,
)
return await projects_search_client.search_dfg_projects(
page=page,
size=size,
institution_aliases=institution_aliases,
project_ids=author_project_ids,
names=filter_names or [],
institution_ids=institution_ids,
@@ -232,60 +243,164 @@ async def get_dfg_projects_by_author_id(
async def get_institution_cordis_eu_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
raw_oa_institution_id: Optional[str] = None,
project_types: Optional[List[EuCordisProjectType]] = None,
author_id: Optional[str] = None,
author_ids: Optional[List[str]] = None,
organization_ids: Optional[List[str]] = None,
organization_names: Optional[List[str]] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
title: Optional[str] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
framework_programmes: Optional[List[str]] = None,
funding_schemes: Optional[List[str]] = None,
statuses: Optional[List[str]] = None,
fuzzy: bool = False,
) -> InstitutionFunderSummary:
page = await search_eu_cordis_projects(
page=0,
size=10000,
raw_oa_institution_id=raw_oa_institution_id,
institutions_search_client=institutions_search_client,
"""
Computes funding-over-time for EU CORDIS projects, applying the exact same
filters as `search_eu_cordis_projects` (the table search). Uses a
lightweight, fully-paginated fetch of just id/dates/amount - no author,
organization or topic enrichment - so this stays fast even when a filter
combination matches many thousands of projects.
"""
resolved_organization_names: List[str] = list(organization_names or [])
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
resolved_organization_names.extend(institution_aliases)
all_author_ids: List[str] = []
if author_id:
all_author_ids.append(author_id)
all_author_ids.extend(author_ids or [])
author_project_ids = await _get_eu_project_ids_for_openalex_authors(
author_ids=all_author_ids
)
funding_data = await get_eu_cordis_projects_funding_data(
project_types=project_types,
organization_ids=organization_ids,
organization_names=resolved_organization_names or None,
author_project_ids=author_project_ids,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
title=title,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
framework_programmes=framework_programmes,
funding_schemes=funding_schemes,
statuses=statuses,
fuzzy=fuzzy,
)
return _calculate_funding_over_time(
project_type=ProjectType.EU,
projects=page.elements,
funding_start_attr="start_date",
funding_end_attr="end_date",
funding_amount_attr="ec_max_contribution",
funding_entries=[
(entry.get("start_date"), entry.get("end_date"), entry.get("ec_max_contribution"))
for entry in funding_data
],
)
async def get_institution_bund_projects_funding_over_time(
institutions_search_client: InstitutionsSearchClient,
raw_oa_institution_id: str,
raw_oa_institution_id: Optional[str] = None,
executing_agency: Optional[List[str]] = None,
funding_arts: Optional[List[str]] = None,
title: Optional[str] = None,
keywords: Optional[List[str]] = None,
topic_ids: Optional[List[str]] = None,
filter_topic_ids: Optional[List[str]] = None,
funding_start_years: Optional[List[str]] = None,
funding_end_years: Optional[List[str]] = None,
countries: Optional[List[str]] = None,
fuzzy: bool = False,
) -> InstitutionFunderSummary:
"""
Computes funding-over-time for BUND projects, applying the exact same
filters as `search_bund_projects_with_filters` (the table search).
Skips the OpenAlex-topic enrichment step (irrelevant to a funding sum)
and pages through ALL matches rather than a single capped size=10000
request, so totals stay correct and fast for large result sets.
"""
logger.info(
f"Fetching funding over time for institution_id={raw_oa_institution_id}"
f"Fetching funding over time for institution_id={raw_oa_institution_id}, "
f"executing_agency={executing_agency}, funding_arts={funding_arts}, "
f"title={title}, keywords={keywords}, topic_ids={topic_ids}, "
f"filter_topic_ids={filter_topic_ids}, funding_start_years={funding_start_years}, "
f"funding_end_years={funding_end_years}, countries={countries}, fuzzy={fuzzy}"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
institution_aliases = []
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
)
logger.debug(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
response = await projects_search_client.search_bund_projects(
filter_properties=ProjectsFilteringProperties(
project_type=ProjectType.BUND,
page=0,
size=10000,
),
institution_names=institution_aliases,
)
if not institution_aliases:
return _calculate_funding_over_time(
project_type=ProjectType.BUND,
funding_entries=[],
)
page_size = 5000
page = 0
funding_entries: List[Any] = []
while True:
response = await projects_search_client.search_bund_projects_with_filters(
oa_institution_aliases=institution_aliases,
raw_oa_institution_id=raw_oa_institution_id,
executing_agency=executing_agency,
funding_arts=funding_arts,
title=title,
keywords=keywords,
topic_ids=topic_ids,
filter_topic_ids=filter_topic_ids,
funding_start_years=funding_start_years,
funding_end_years=funding_end_years,
countries=countries,
page=page,
size=page_size,
fuzzy=fuzzy,
skip_topic_enrichment=True,
)
funding_entries.extend(
(element.funding_start, element.funding_end, element.grant_amount)
for element in response.elements
)
if len(response.elements) < page_size:
break
page += 1
return _calculate_funding_over_time(
project_type=ProjectType.BUND,
projects=response.elements,
funding_start_attr="funding_start",
funding_end_attr="funding_end",
funding_amount_attr="grant_amount",
funding_entries=funding_entries,
)
#Bund
async def search_bund_projects_with_filters(
institutions_search_client: InstitutionsSearchClient,
executing_agency: Optional[str],
institution_ids: Optional[List[str]],
raw_oa_institution_id: Optional[str],
title: Optional[str],
keywords: Optional[List[str]],
funding_arts: Optional[List[str]],
@@ -300,9 +415,24 @@ async def search_bund_projects_with_filters(
sort_direction: str = "asc",
fuzzy: bool = False,
) -> BundProjectPage:
institution_aliases = []
if raw_oa_institution_id:
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_oa_institution_id(
raw_oa_institution_id
)
)
if not institution_aliases:
return BundProjectPage(
elements=[],
page=page,
size=size,
total=0,
)
return await projects_search_client.search_bund_projects_with_filters(
oa_institution_aliases=institution_aliases,
raw_oa_institution_id=raw_oa_institution_id,
executing_agency=executing_agency,
institution_ids=[],
funding_arts=funding_arts,
title=title,
keywords=keywords,
@@ -320,20 +450,24 @@ async def search_bund_projects_with_filters(
def _calculate_funding_over_time(
project_type: ProjectType,
projects: List[Any],
funding_start_attr: str,
funding_end_attr: str,
funding_amount_attr: str,
funding_entries: List[Any],
) -> InstitutionFunderSummary:
"""
funding_entries: list of (funding_start, funding_end, funding_amount)
tuples. Each date value may be a date/datetime, an ISO date string, or
None; amount may be numeric or None.
"""
funding_per_year: Dict[int, float] = {}
for project in projects:
funding_start = getattr(project, funding_start_attr)
funding_end = getattr(project, funding_end_attr)
funding_amount = getattr(project, funding_amount_attr)
for funding_start, funding_end, funding_amount in funding_entries:
if not funding_start or not funding_end or not funding_amount:
continue
if isinstance(funding_start, str):
funding_start = datetime.date.fromisoformat(funding_start[:10])
if isinstance(funding_end, str):
funding_end = datetime.date.fromisoformat(funding_end[:10])
if hasattr(funding_start, "date"):
funding_start = funding_start.date()
if hasattr(funding_end, "date"):
@@ -511,7 +645,7 @@ async def search_eu_cordis_projects(
f"Found institution aliases for institution_id={raw_oa_institution_id}: {institution_aliases}"
)
resolved_organization_names.extend(institution_aliases)
print("Resolved organization names:", resolved_organization_names)
all_author_ids: List[str] = []
if author_id:
@@ -520,7 +654,6 @@ async def search_eu_cordis_projects(
author_project_ids = await _get_eu_project_ids_for_openalex_authors(
author_ids=all_author_ids
)
return await _search_eu_cordis_projects_es(
page=page,
size=size,
@@ -7,7 +7,7 @@ async def test_search_dfg_projects():
res = await projects_search_client.search_dfg_projects(
page=0,
size=5,
names=["Wolfgang Ahrens"],
names=["Bovensiepen"],
)
assert res is not None
assert res.total > 0
@@ -15,23 +15,19 @@ async def test_search_dfg_projects():
for element in res.elements:
assert element.id is not None
assert any(
all(part.lower() in name.lower() for part in "Wolfgang Ahrens".split())
all(part.lower() in name.lower() for part in "Bovensiepen".split())
for name in element.names
)
@pytest.mark.anyio
async def test_get_dfg_project_by_id():
# Get by ID of the project we found or a known one
known_id = "164008977"
known_id = 164008977
project = await projects_search_client.get_dfg_project_by_id(known_id)
assert project is not None
assert project.id == known_id
assert project.title is not None
assert project.title_de is not None
assert any(
all(part.lower() in person.lower() for part in "Wolfgang Ahrens".split())
for person in project.associated_persons
)
assert any(
"Leibniz" in inst
for inst in project.institutions
all(part.lower() in person.full_name.lower() for part in "Wolfgang Ahrens".split())
for person in project.persons
)
@@ -0,0 +1,241 @@
from decimal import Decimal, ROUND_HALF_UP
from typing import Any
from inse.authors.v2.service import authors_currently_belong_to_institution
from inse.integrations import elasticsearch
from inse.model import ESIndex
from inse.works.v2.model import WorkPrimaryCategory
from .model import PublicationType, Timespan
from .orientation_profile_model import (
AuthorOrientationProfile,
AuthorOrientationProfileStatus,
)
_SCORE_FIELD = "classification.applied_orientation_score"
_PRIMARY_CATEGORY_VALUES = {
category.value for category in WorkPrimaryCategory
}
def _author_filter(author_ids: list[str]) -> dict[str, Any]:
return {
"nested": {
"path": "authors",
"query": {"terms": {"authors.id": author_ids}},
}
}
def _orientation_profile_query(
author_ids: list[str],
publication_types: list[PublicationType],
timespan: Timespan | None,
) -> dict[str, Any]:
filters: list[dict[str, Any]] = [_author_filter(author_ids)]
if publication_types:
filters.append(
{
"terms": {
"publication_type": [
publication_type.value
for publication_type in publication_types
]
}
}
)
if timespan:
filters.append(
{
"range": {
"publication_year": {
"gte": timespan.from_year,
"lte": timespan.to_year,
}
}
}
)
return {
"size": 0,
"query": {"bool": {"filter": filters}},
"aggs": {
"authors": {
"nested": {"path": "authors"},
"aggs": {
"selected": {
"filter": {"terms": {"authors.id": author_ids}},
"aggs": {
"by_author": {
"terms": {
"field": "authors.id",
"size": len(author_ids),
"execution_hint": "map",
},
"aggs": {
"works": {
"reverse_nested": {},
"aggs": {
"classified": {
"filter": {
"exists": {
"field": (
"classification."
"primary_category"
)
}
},
"aggs": {
"by_primary_category": {
"terms": {
"field": (
"classification."
"primary_category"
),
"size": len(
WorkPrimaryCategory
),
}
}
},
},
"scored": {
"filter": {
"exists": {
"field": _SCORE_FIELD
}
},
"aggs": {
"average_score": {
"avg": {
"field": _SCORE_FIELD
}
}
},
},
},
}
},
}
},
}
},
}
},
}
def _rounded_score(value: float) -> int:
return int(Decimal(str(value)).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
def _profile_from_bucket(
author_id: str,
bucket: dict[str, Any] | None,
) -> AuthorOrientationProfile:
works = (bucket or {}).get("works", {})
classified_count = works.get("classified", {}).get("doc_count", 0)
category_buckets = (
works.get("classified", {})
.get("by_primary_category", {})
.get("buckets", [])
)
category_counts = {
WorkPrimaryCategory(category_bucket["key"]): category_bucket["doc_count"]
for category_bucket in category_buckets
if category_bucket.get("key") in _PRIMARY_CATEGORY_VALUES
}
scored = works.get("scored", {})
scored_count = scored.get("doc_count", 0)
average_score = scored.get("average_score", {}).get("value")
if classified_count == 0:
status = AuthorOrientationProfileStatus.NO_CLASSIFIED_PUBLICATIONS
elif scored_count == 0 or average_score is None:
status = AuthorOrientationProfileStatus.NO_ORIENTATION_SCORE
else:
score = _rounded_score(average_score)
return AuthorOrientationProfile(
author_id=author_id,
status=AuthorOrientationProfileStatus.AVAILABLE,
orientation_score=score,
primary_category_counts=category_counts,
classified_work_count=classified_count,
scored_work_count=scored_count,
)
return AuthorOrientationProfile(
author_id=author_id,
status=status,
primary_category_counts=category_counts,
classified_work_count=classified_count,
scored_work_count=scored_count,
)
async def orientation_profiles_for_authors(
author_ids: list[str],
institution_id: str | None,
publication_types: list[PublicationType],
timespan: Timespan | None,
) -> list[AuthorOrientationProfile]:
"""Return protected orientation profiles in the requested author order.
Institution membership is checked for all authors in one query. Only
matching active members are included in the work-classification
aggregation, so restricted classification data is never retrieved.
"""
if not institution_id:
allowed_author_ids: set[str] = set()
else:
allowed_author_ids = await authors_currently_belong_to_institution(
author_ids,
institution_id,
)
restricted_profiles = {
author_id: AuthorOrientationProfile(
author_id=author_id,
status=AuthorOrientationProfileStatus.RESTRICTED,
)
for author_id in author_ids
if author_id not in allowed_author_ids
}
allowed_in_request_order = [
author_id for author_id in author_ids if author_id in allowed_author_ids
]
profiles_by_id: dict[str, AuthorOrientationProfile] = restricted_profiles
if allowed_in_request_order:
response = await elasticsearch.search(
index=ESIndex.WORK_CLASSIFICATIONS,
body=_orientation_profile_query(
allowed_in_request_order,
publication_types,
timespan,
),
)
buckets = (
response.get("aggregations", {})
.get("authors", {})
.get("selected", {})
.get("by_author", {})
.get("buckets", [])
)
buckets_by_author = {
bucket.get("key"): bucket
for bucket in buckets
if isinstance(bucket.get("key"), str)
}
for author_id in allowed_in_request_order:
profiles_by_id[author_id] = _profile_from_bucket(
author_id,
buckets_by_author.get(author_id),
)
return [profiles_by_id[author_id] for author_id in author_ids]
@@ -0,0 +1,78 @@
from enum import StrEnum
from pydantic import BaseModel, Field, field_validator
from inse.works.v2.model import WorkPrimaryCategory
from .model import PublicationType, Timespan
class AuthorOrientationProfileStatus(StrEnum):
AVAILABLE = "available"
INSUFFICIENT_SCORED_PUBLICATIONS = "insufficient_scored_publications"
NO_CLASSIFIED_PUBLICATIONS = "no_classified_publications"
NO_ORIENTATION_SCORE = "no_orientation_score"
RESTRICTED = "restricted"
class AuthorOrientationProfilesRequest(BaseModel):
"""Filters used to compare the research orientation of selected authors."""
author_ids: list[str] = Field(
min_length=1,
max_length=4,
description="One to four unique OpenAlex author IDs.",
)
publication_types: list[PublicationType] = Field(
default_factory=list,
description="Optional publication-type filter. Empty means all types.",
)
timespan: Timespan | None = Field(
default=None,
description="Optional inclusive publication-year filter.",
)
@field_validator("author_ids")
@classmethod
def normalize_author_ids(cls, values: list[str]) -> list[str]:
normalized: list[str] = []
for value in values:
author_id = value.strip()
if not author_id:
raise ValueError("author IDs must not be empty")
if not author_id.startswith("https://openalex.org/"):
author_id = f"https://openalex.org/{author_id}"
if author_id in normalized:
raise ValueError("author IDs must be unique")
normalized.append(author_id)
return normalized
class AuthorOrientationProfile(BaseModel):
"""Aggregated research-orientation result for one selected author."""
author_id: str = Field(description="The full OpenAlex author ID.")
status: AuthorOrientationProfileStatus
orientation_score: int | None = Field(
default=None,
ge=0,
le=100,
description="Rounded mean score, available when at least one work has a score.",
)
primary_category_counts: dict[WorkPrimaryCategory, int] | None = Field(
default=None,
description=(
"Matching work counts grouped by primary category; hidden when "
"access is restricted."
),
)
classified_work_count: int | None = Field(
default=None,
ge=0,
description="Matching classified works; hidden when access is restricted.",
)
scored_work_count: int | None = Field(
default=None,
ge=0,
description="Matching works with an orientation score; hidden when restricted.",
)
+25
View File
@@ -7,6 +7,11 @@ from inse.auth.model import AccessTokenMetadata
from inse.auth.service import CurrentUserAccessTokenPayloadDep
from inse.tags import Tags
from . import logic
from .orientation_profile_logic import orientation_profiles_for_authors
from .orientation_profile_model import (
AuthorOrientationProfile,
AuthorOrientationProfilesRequest,
)
from .model import (
AuthorMetricsRequest,
AuthorStaticStats,
@@ -117,3 +122,23 @@ async def static_stats(request: AuthorMetricsRequest):
request.author_ids,
request.company_status,
)
@router.post(
"/orientation-profiles",
response_model=List[AuthorOrientationProfile],
)
async def orientation_profiles(
request: AuthorOrientationProfilesRequest,
access_token_metadata: Annotated[
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
],
):
"""Compare orientation scores for active members of the account institution."""
return await orientation_profiles_for_authors(
author_ids=request.author_ids,
institution_id=access_token_metadata.effective_institution_id,
publication_types=request.publication_types,
timespan=request.timespan,
)
+2
View File
@@ -24,3 +24,5 @@ class Tags(StrEnum):
DFG_INSTITUTIONS = "DFG Institutions"
DFG_PERSONS = "DFG Persons"
BACKGROUND_JOBS = "Background Jobs"
BUND_INSTITUTIONS = "BUND Institutions"
+21 -1
View File
@@ -74,7 +74,27 @@ async def search_topics(
query = None
if search_term:
query = {"match_phrase_prefix": {"display_name": search_term}}
search_terms = [
term.strip() for term in search_term.split(",") if term.strip()
]
if len(search_terms) == 1:
query = {
"match_phrase_prefix": {"display_name": search_terms[0]}
}
elif search_terms:
query = {
"bool": {
"should": [
{
"match_phrase_prefix": {
"display_name": search_term
}
}
for search_term in search_terms
],
"minimum_should_match": 1,
}
}
return await _search_topics(
page=page,
@@ -0,0 +1,41 @@
from unittest.mock import AsyncMock, patch
import pytest
from inse.topics.v2.service import search_topics
@pytest.fixture
def anyio_backend():
return "asyncio"
@pytest.mark.anyio
async def test_search_topics_treats_comma_separated_terms_as_alternatives():
with patch(
"inse.topics.v2.service.elasticsearch.search",
new=AsyncMock(
return_value={
"hits": {"hits": [], "total": {"value": 0}}
}
),
) as search:
await search_topics("Artificial Intelligence, Machine Learning")
assert search.await_args.kwargs["query"] == {
"bool": {
"should": [
{
"match_phrase_prefix": {
"display_name": "Artificial Intelligence"
}
},
{
"match_phrase_prefix": {
"display_name": "Machine Learning"
}
},
],
"minimum_should_match": 1,
}
}
@@ -3,6 +3,7 @@ from typing import List, Optional
from fastapi import APIRouter, Query, Depends
from inse.tags import Tags
from inse.exceptions import BadRequestException
from . import logic, trend_logic
from .model import (
RankingResponse,
@@ -43,7 +44,7 @@ def get_trend_strategy(search_type: TrendSearchType = Query(TrendSearchType.PUBL
return NewsTrendStrategy()
elif search_type == TrendSearchType.ALL:
return AllTrendStrategy()
raise ValueError(f"Unknown search type: {search_type}")
raise BadRequestException(f"Unknown search type: {search_type}")
@router.get(
"",
@@ -74,6 +75,8 @@ async def get_trend(
authors: Optional[List[str]] = Query(None, description="List of OpenAlex Author IDs"),
strategy: TrendStrategy = Depends(get_trend_strategy)
):
if not topics or len(topics) == 0:
raise BadRequestException("Topics list cannot be empty")
return await strategy.get_trend(
topics=topics,
keywords=keywords,
@@ -128,12 +128,23 @@ async def get_top_institutions_by_region(
meta_top = await TrendMetadataResolver.resolve_all(topics=[topic])
topic_id = meta_top.get("resolved_topic_ids", {}).get(topic)
topic_display_name = meta_top.get("resolved_topic_names", {}).get(topic, topic)
topic_filter = (
{"term": {"topics.id.keyword": topic_id}}
if topic_id
else {"match_phrase": {"topics.display_name": topic}}
)
if not topic_id and (topic.startswith("https://openalex.org/") or (topic.startswith("T") and topic[1:].isdigit())):
topic_id = topic if topic.startswith("https://openalex.org/") else f"https://openalex.org/{topic}"
if topic_id:
topic_filter = {
"bool": {
"should": [
{"term": {"topics.id.keyword": topic_id}},
{"term": {"topics.id": topic_id}},
],
"minimum_should_match": 1,
}
}
else:
topic_filter = {"match_phrase": {"topics.display_name": topic_display_name}}
must_clauses: List[Dict[str, Any]] = [
{"term": {"type": "education"}},
@@ -12,15 +12,18 @@ DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
def clean_inst_id(id_str: str) -> str:
"""Extracts short OpenAlex ID from full URL or returns as-is."""
"""Extracts short OpenAlex ID from full URL or returns as-is, ensuring uppercase prefix."""
if not id_str:
return ""
s = id_str.strip()
return s.split("/")[-1] if "/" in s else s
raw_id = s.split("/")[-1] if "/" in s else s
if len(raw_id) > 1 and raw_id[0].isalpha():
return raw_id[0].upper() + raw_id[1:]
return raw_id.upper()
def to_full_inst_url(id_str: str) -> str:
"""Ensures institution ID is formatted as a full OpenAlex URL."""
"""Ensures institution ID is formatted as a full OpenAlex URL with proper capitalization."""
cleaned = clean_inst_id(id_str)
return f"https://openalex.org/{cleaned}" if cleaned else id_str
@@ -85,8 +88,9 @@ class TrendMetadataResolver:
alias_results = await asyncio.gather(*(get_alias(i) for i in inst_full_ids))
for short_id, alias_list in alias_results:
aliases_map[short_id] = alias_list
aliases_map[f"https://openalex.org/{short_id}"] = alias_list
s_upper = clean_inst_id(short_id)
aliases_map[s_upper] = alias_list
aliases_map[f"https://openalex.org/{s_upper}"] = alias_list
except Exception as e:
logger.warning("Failed to resolve institutions from ES: %s", e)
@@ -142,31 +146,65 @@ class TrendMetadataResolver:
async def fetch_topics():
topic_ids: Dict[str, str] = {}
topic_display_names: Dict[str, str] = {}
if not topic_names:
return topic_ids
return topic_ids, topic_display_names
should_clauses = []
for t in topic_names:
if not t:
continue
clean_id = clean_inst_id(t)
canonical_id = f"https://openalex.org/{clean_id}" if clean_id.startswith("T") else t
if t.startswith("https://openalex.org/") or (clean_id.startswith("T") and clean_id[1:].isdigit()):
should_clauses.extend([
{"term": {"id": canonical_id}},
{"term": {"id.keyword": canonical_id}},
{"term": {"id": clean_id}},
{"term": {"id.keyword": clean_id}},
])
else:
should_clauses.append({"match_phrase": {"display_name": t}})
try:
res = await elasticsearch.search(
index=ESIndex.OPENALEX_TOPICS.value,
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}},
size=len(topic_names) * 2,
query={"bool": {"should": should_clauses, "minimum_should_match": 1}},
size=max(10, len(topic_names) * 3),
source=["id", "display_name"],
cluster="nes",
)
for hit in res.get("hits", {}).get("hits", []):
src = hit["_source"]
full_id = src.get("id", "")
short_id = clean_inst_id(full_id)
canonical_id = f"https://openalex.org/{short_id}" if short_id.startswith("T") else full_id
d_name = src.get("display_name", "")
for t in topic_names:
if t.lower() in d_name.lower():
topic_ids[t] = src["id"]
t_clean = clean_inst_id(t)
t_canonical = f"https://openalex.org/{t_clean}" if t_clean.startswith("T") else t
if (
t == full_id
or t == short_id
or t == canonical_id
or t_canonical == canonical_id
or t_clean == short_id
or t.lower() in d_name.lower()
or d_name.lower() in t.lower()
):
topic_ids[t] = canonical_id
topic_display_names[t] = d_name
topic_display_names[canonical_id] = d_name
topic_display_names[short_id] = d_name
topic_display_names[full_id] = d_name
except Exception as e:
logger.warning("Failed to resolve topic IDs from ES: %s", e)
return topic_ids
return topic_ids, topic_display_names
(
(inst_names, inst_country_codes, inst_aliases),
country_names,
(continent_names, continent_country_codes),
resolved_topic_ids,
(resolved_topic_ids, resolved_topic_names),
) = await asyncio.gather(
fetch_institutions(),
fetch_countries(),
@@ -182,6 +220,7 @@ class TrendMetadataResolver:
"continent_names": continent_names,
"continent_country_codes": continent_country_codes,
"resolved_topic_ids": resolved_topic_ids,
"resolved_topic_names": resolved_topic_names,
}
@@ -196,6 +235,12 @@ class TrendQueryBuilder:
fuzzy: bool = True,
) -> Dict[str, Any]:
"""Builds a topic or keyword matching clause."""
target_id = resolved_topic_id
if not target_id and topic_display_name:
c_id = clean_inst_id(topic_display_name)
if c_id.startswith("T") and c_id[1:].isdigit():
target_id = f"https://openalex.org/{c_id}"
if not fuzzy and keyword:
return {
"bool": {
@@ -208,12 +253,15 @@ class TrendQueryBuilder:
"minimum_should_match": 1,
}
}
elif resolved_topic_id:
elif target_id:
c_id = clean_inst_id(target_id)
canonical_id = f"https://openalex.org/{c_id}" if c_id.startswith("T") else target_id
target_ids = list(dict.fromkeys([canonical_id, target_id, c_id]))
return {
"bool": {
"should": [
{"nested": {"path": "topics", "query": {"term": {"topics.id": resolved_topic_id}}}},
{"term": {"primary_topic.id": resolved_topic_id}},
{"nested": {"path": "topics", "query": {"terms": {"topics.id": target_ids}}}},
{"terms": {"primary_topic.id": target_ids}},
],
"minimum_should_match": 1,
}
@@ -316,7 +316,7 @@ class AuthorsTrendStrategy(TrendStrategy):
if not query_authors:
return TrendResponse(series=[], years=years_range)
query_authors_clean = [clean_inst_id(a).upper() for a in query_authors if a]
query_authors_clean = [clean_inst_id(a) for a in query_authors if a]
# Resolve author display names
resolved_names: Dict[str, str] = {}
@@ -329,7 +329,7 @@ class AuthorsTrendStrategy(TrendStrategy):
cluster=ESCluster.NES,
)
for hit in res.get("hits", {}).get("hits", []):
short_id = hit["_id"]
short_id = clean_inst_id(hit["_id"])
full_id = f"https://openalex.org/{short_id}"
display_name = hit["_source"].get("display_name", short_id)
resolved_names[short_id] = display_name
@@ -340,14 +340,12 @@ class AuthorsTrendStrategy(TrendStrategy):
meta = await TrendMetadataResolver.resolve_all(topics=topics)
resolved_topic_ids = meta["resolved_topic_ids"]
query_authors_full = [
a if a.startswith("https://openalex.org/") else f"https://openalex.org/{clean_inst_id(a).upper()}"
for a in query_authors
]
query_authors_full = [to_full_inst_url(a) for a in query_authors if a]
filters_map: Dict[str, Dict[str, Any]] = {}
for auth_id, auth_url in zip(query_authors, query_authors_full):
filters_map[f"author_{auth_id}"] = {
clean_id = clean_inst_id(auth_id)
filters_map[f"author_{clean_id}"] = {
"nested": {
"path": "authorships",
"query": {"term": {"authorships.author.id": auth_url}},
@@ -508,16 +506,17 @@ class PatentsTrendStrategy(TrendStrategy):
def matches_patent(patent, topic: str, keyword: Optional[str], is_fuzzy: bool) -> bool:
if matches_topic(patent, topic):
return True
if not is_fuzzy and keyword:
t_lower = topic.lower()
if patent.title and t_lower in patent.title.lower():
return True
if patent.abstract and t_lower in patent.abstract.lower():
return True
if keyword:
kw_lower = keyword.lower()
if patent.title and kw_lower in patent.title.lower():
return True
if patent.abstract and kw_lower in patent.abstract.lower():
return True
if patent.openalex_topics:
for ot in patent.openalex_topics:
if ot.topic_display_name and kw_lower in ot.topic_display_name.lower():
return True
return False
accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]] = {
+72 -60
View File
@@ -1,60 +1,72 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains utility functions
for the service implementation.
"""
from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise NotFoundException("Not found.")
else:
return value
def get_persons_data(hit:dict):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
return author
from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model
_model: SentenceTransformer | None = None
def get_model():
global _model
if _model is None:
import os
# If SENTENCE_TRANSFORMERS_HOME is not set, check if container-baked /models folder is available
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
if os.path.exists("/models"):
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
os.environ["HF_HUB_OFFLINE"] = "1"
else:
# If it is set to /models, enforce offline mode as it is baked into the image
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
os.environ["HF_HUB_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name
_model = SentenceTransformer(model_name)
return _model
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This module contains utility functions
for the service implementation.
"""
from typing import Optional
from typing import TypeVar
from inse.models.openalex import Author
from . import model
from inse.exceptions import NotFoundException
T = TypeVar('T')
def raise_not_found_if_none(value: Optional[T]) -> T:
''' Returns the value, if it is set, or raises a 404, if the value is None.'''
if value == None:
raise NotFoundException("Not found.")
else:
return value
def get_persons_data(hit:dict):
source = hit.get("_source", {})
source_copy = dict(source)
source_copy["id"] = hit.get("_id", "") or source_copy.get("id")
# Resilient sanitization of IDs to protect against model regeneration type conflicts (#Generated)
ids = source_copy.get("ids")
if isinstance(ids, dict):
ids_copy = {}
orcid_val = ids.get("orcid")
if orcid_val:
ids_copy["orcid"] = str(orcid_val)
source_copy["ids"] = ids_copy
author = Author.from_dict(source_copy)
return author
from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model
_model: SentenceTransformer | None = None
def get_model():
global _model
if _model is None:
import os
# Determine offline mode
is_offline = os.environ.get("HF_HUB_OFFLINE") == "1"
if "SENTENCE_TRANSFORMERS_HOME" not in os.environ:
if os.path.exists("/models"):
os.environ["SENTENCE_TRANSFORMERS_HOME"] = "/models"
os.environ["HF_HOME"] = "/models"
is_offline = True
elif os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
is_offline = True
if is_offline:
os.environ["HF_HUB_OFFLINE"] = "1"
os.environ["TRANSFORMERS_OFFLINE"] = "1"
os.environ["HF_DATASETS_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name
try:
if is_offline:
_model = SentenceTransformer(model_name, local_files_only=True)
else:
_model = SentenceTransformer(model_name)
except Exception:
# Fallback if local_files_only fails in unexpected local dev environments
_model = SentenceTransformer(model_name)
return _model
+4 -10
View File
@@ -25,10 +25,7 @@
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"styles": ["src/styles.scss"],
"scripts": []
},
"configurations": {
@@ -41,8 +38,8 @@
},
{
"type": "anyComponentStyle",
"maximumWarning": "5kb",
"maximumError": "10kb"
"maximumWarning": "10kb",
"maximumError": "20kb"
}
],
"outputHashing": "all"
@@ -83,10 +80,7 @@
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"styles": ["src/styles.scss"],
"scripts": []
}
}
@@ -6,6 +6,7 @@ api.module.ts
api/api.ts
api/auth.service.ts
api/authorsV2.service.ts
api/bUNDInstitutions.service.ts
api/backgroundJobs.service.ts
api/bookmarks.service.ts
api/companyConnections.service.ts
@@ -43,6 +44,9 @@ model/authorCountsByYearInner.ts
model/authorIds.ts
model/authorMetricsRequest.ts
model/authorNode.ts
model/authorOrientationProfile.ts
model/authorOrientationProfileStatus.ts
model/authorOrientationProfilesRequest.ts
model/authorPage.ts
model/authorParsedLongestName.ts
model/authorPositionCount.ts
@@ -66,6 +70,8 @@ model/bodyLogin.ts
model/bodyRequestOtk.ts
model/bodyRequestPasswordReset.ts
model/bodyResetPassword.ts
model/bundInstitutionSummary.ts
model/bundInstitutionSummaryPage.ts
model/bundProjectDetails.ts
model/bundProjectPage.ts
model/bundProjectSummary.ts
@@ -96,7 +102,13 @@ model/dfgInstitutionSummaryPage.ts
model/dfgPersonSummary.ts
model/dfgPersonSummaryPage.ts
model/dfgProjectDetails.ts
model/dfgProjectInstitutionRole.ts
model/dfgProjectPage.ts
model/dfgProjectPersonRole.ts
model/dfgProjectPublicationSummary.ts
model/dfgProjectStatusStatistics.ts
model/dfgProjectSubjectArea.ts
model/dfgProjectSubprojectSummary.ts
model/dfgProjectSummary.ts
model/dfgProjectTopic.ts
model/dfgProjectTopics.ts
+29 -1
View File
@@ -2,6 +2,8 @@ export * from './auth.service';
import { AuthService } from './auth.service';
export * from './authorsV2.service';
import { AuthorsV2Service } from './authorsV2.service';
export * from './bUNDInstitutions.service';
import { BUNDInstitutionsService } from './bUNDInstitutions.service';
export * from './backgroundJobs.service';
import { BackgroundJobsService } from './backgroundJobs.service';
export * from './bookmarks.service';
@@ -46,4 +48,30 @@ export * from './works.service';
import { WorksService } from './works.service';
export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, AuthorsV2Service, BackgroundJobsService, BookmarksService, CompanyConnectionsService, DFGInstitutionsService, DFGPersonsService, DashboardService, FundingService, INSEServiceService, InstitutionsService, InstitutionsV2Service, KeywordsService, NewsService, OrganizationService, PatentsService, PersonsService, ProjectsService, RankingService, TopicsService, TopicsV2Service, UniversityRankingsService, WorksService, WorksV2Service];
export const APIS = [
AuthService,
AuthorsV2Service,
BUNDInstitutionsService,
BackgroundJobsService,
BookmarksService,
CompanyConnectionsService,
DFGInstitutionsService,
DFGPersonsService,
DashboardService,
FundingService,
INSEServiceService,
InstitutionsService,
InstitutionsV2Service,
KeywordsService,
NewsService,
OrganizationService,
PatentsService,
PersonsService,
ProjectsService,
RankingService,
TopicsService,
TopicsV2Service,
UniversityRankingsService,
WorksService,
WorksV2Service,
];
@@ -0,0 +1,258 @@
/**
* 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.
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { BundInstitutionSummaryPage } from '../model/bundInstitutionSummaryPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root',
})
export class BUNDInstitutionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/**
* Returns a list of institutions based on a search term for autocomplete functionality.
* @endpoint get /api/bund/institutions/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @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 getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionAutocompleteForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
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/bund/institutions/autocomplete/selector`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns a list of institutions based on their names.
* @endpoint get /api/bund/institutions/names
* @param institutionNames A list of institution names to retrieve.
* @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 getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<BundInstitutionSummaryPage>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
public getBundInstitutionsByName(
institutionNames?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (institutionNames) {
institutionNames.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'institution_names',
);
});
}
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/bund/institutions/names`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<BundInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
File diff suppressed because it is too large Load Diff
+620 -265
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,16 +9,26 @@
*/
/* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams,
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
import { Inject, Injectable, Optional } from '@angular/core';
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore
import { AuthorMetricsRequest } from '../model/authorMetricsRequest';
// @ts-ignore
import { AuthorOrientationProfile } from '../model/authorOrientationProfile';
// @ts-ignore
import { AuthorOrientationProfilesRequest } from '../model/authorOrientationProfilesRequest';
// @ts-ignore
import { AuthorStaticStats } from '../model/authorStaticStats';
// @ts-ignore
import { AuthorTopicProfile } from '../model/authorTopicProfile';
@@ -34,283 +44,628 @@ import { RankedAuthor } from '../model/rankedAuthor';
import { SelectedAuthorsRequest } from '../model/selectedAuthorsRequest';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class RankingService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
super(basePath, configuration);
/**
* Orientation Profiles
* Compare orientation scores for active members of the account institution.
* @endpoint post /api/rank/orientation-profiles
* @param authorOrientationProfilesRequest
* @param secureFgpAcc
* @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 orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorOrientationProfile>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorOrientationProfile>>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorOrientationProfile>>>;
public orientationProfilesApiRankOrientationProfilesPost(
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
authorOrientationProfilesRequest === null ||
authorOrientationProfilesRequest === undefined
) {
throw new Error(
'Required parameter authorOrientationProfilesRequest was null or undefined when calling orientationProfilesApiRankOrientationProfilesPost.',
);
}
/**
* Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @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 rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (keywordToAuthorRequest === null || keywordToAuthorRequest === undefined) {
throw new Error('Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.');
}
let localVarHeaders = this.defaultHeaders;
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
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;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
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/rank/rank-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<RankedAuthor>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordToAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
/**
* Static Stats
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @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 staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorStaticStats>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error('Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.');
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
let localVarHeaders = this.defaultHeaders;
const localVarTransferCache: boolean = options?.transferCache ?? true;
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;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
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/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
/**
* Topic Profile
* @endpoint post /api/rank/topic-profile
* @param selectedAuthorsRequest
* @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 topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicProfile>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) {
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.');
}
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;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
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/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
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';
}
}
/**
* Topic Stats
* @endpoint post /api/rank/topic-stats
* @param selectedAuthorsRequest
* @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 topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicStats>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) {
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.');
}
let localVarPath = `/api/rank/orientation-profiles`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorOrientationProfile>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorOrientationProfilesRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
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;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
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/rank/topic-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicStats>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
/**
* Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @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 rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
keywordToAuthorRequest === null ||
keywordToAuthorRequest === undefined
) {
throw new Error(
'Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.',
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
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;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
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/rank/rank-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<RankedAuthor>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordToAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Static Stats
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @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 staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorStaticStats>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error(
'Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.',
);
}
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;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
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/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Profile
* @endpoint post /api/rank/topic-profile
* @param selectedAuthorsRequest
* @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 topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicProfile>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.',
);
}
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;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
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/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Stats
* @endpoint post /api/rank/topic-stats
* @param selectedAuthorsRequest
* @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 topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicStats>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.',
);
}
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;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
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/rank/topic-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
@@ -0,0 +1,27 @@
/**
* 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 { AuthorOrientationProfileStatus } from './authorOrientationProfileStatus';
import { WorkPrimaryCategory } from './workPrimaryCategory';
/**
* Aggregated research-orientation result for one selected author.
*/
export interface AuthorOrientationProfile {
/**
* The full OpenAlex author ID.
*/
author_id: string;
status: AuthorOrientationProfileStatus;
orientation_score?: number | null;
primary_category_counts?: Partial<Record<WorkPrimaryCategory, number>> | null;
classified_work_count?: number | null;
scored_work_count?: number | null;
}
export namespace AuthorOrientationProfile {}
@@ -0,0 +1,19 @@
/**
* 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 const AuthorOrientationProfileStatus = {
available: 'available',
insufficient_scored_publications: 'insufficient_scored_publications',
no_classified_publications: 'no_classified_publications',
no_orientation_score: 'no_orientation_score',
restricted: 'restricted',
} as const;
export type AuthorOrientationProfileStatus =
(typeof AuthorOrientationProfileStatus)[keyof typeof AuthorOrientationProfileStatus];
@@ -0,0 +1,26 @@
/**
* 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 { Timespan } from './timespan';
import { PublicationType } from './publicationType';
/**
* Filters used to compare the research orientation of selected authors.
*/
export interface AuthorOrientationProfilesRequest {
/**
* One to four unique OpenAlex author IDs.
*/
author_ids: Array<string>;
/**
* Optional publication-type filter. Empty means all types.
*/
publication_types?: Array<PublicationType>;
timespan?: Timespan | 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.
*/
/**
* A single institution entry derived from a BUND project record. Note: this index has no dedicated institution entity — each entry is reconstructed from the agency/recipient fields on a single project hit, so the same institution may appear multiple times (once per project).
*/
export interface BundInstitutionSummary {
department?: string | null;
department_fullname?: string | null;
name?: string | null;
recepient?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
}
@@ -0,0 +1,32 @@
/**
* 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 { BundInstitutionSummary } from './bundInstitutionSummary';
/**
* A paginated response containing a list of institutions.
*/
export interface BundInstitutionSummaryPage {
/**
* The elements of the page.
*/
elements?: Array<BundInstitutionSummary>;
/**
* The page number. (0-based)
*/
page?: number;
/**
* The page size in elements.
*/
size?: number;
/**
* The total number of elements.
*/
total?: number;
}
+44 -44
View File
@@ -1,57 +1,57 @@
/**
* 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 { Topic } from './topic';
/**
* Clean summary model for a Bund (federal) project, consolidating all fields into semantic English names with proper native types.
*/
export interface BundProjectDetails {
/**
* The ID of the Bund project
*/
id: string;
funding_reference?: string | null;
title?: string | null;
description?: string | null;
joint_project?: string | null;
funding_type?: string | null;
funding_profile?: string | null;
funding_amount?: number | null;
funding_start_date?: string | null;
funding_end_date?: string | null;
duration?: string | null;
performance_plan_code?: string | null;
performance_plan_fullname?: string | null;
executing_agency?: string | null;
funding_recipient?: string | null;
project_agency?: string | null;
project_agency_fullname?: string | null;
department?: string | null;
department_fullname?: string | null;
division?: string | null;
location?: string | null;
municipality?: string | null;
state?: string | null;
country?: string | null;
municipality_code?: string | null;
publication_date?: string | null;
is_new?: boolean | null;
record_date?: string | null;
unix_timestamp?: number | null;
/**
* All persons associated with the Bund project (from nested Arb object)
*/
associated_persons?: Array<string>;
/**
* All institutions associated with the Bund project
*/
institutions?: Array<string>;
export interface BundProjectDetails {
/**
* The ID of the Bund project
*/
id: string;
funding_reference?: string | null;
title?: string | null;
description?: string | null;
joint_project?: string | null;
funding_type?: string | null;
funding_profile?: string | null;
funding_amount?: number | null;
funding_start_date?: string | null;
funding_end_date?: string | null;
duration?: string | null;
performance_plan_code?: string | null;
performance_plan_fullname?: string | null;
executing_agency?: string | null;
funding_recipient?: string | null;
project_agency?: string | null;
project_agency_fullname?: string | null;
department?: string | null;
department_fullname?: string | null;
division?: string | null;
location?: string | null;
municipality?: string | null;
state?: string | null;
country?: string | null;
municipality_code?: string | null;
publication_date?: string | null;
is_new?: boolean | null;
record_date?: string | null;
unix_timestamp?: number | null;
/**
* All persons associated with the Bund project (from nested Arb object)
*/
associated_persons?: Array<string>;
/**
* All institutions associated with the Bund project
*/
institutions?: Array<string>;
oa_topics?: Array<Topic> | null;
}
+33 -33
View File
@@ -1,44 +1,44 @@
/**
* 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 { Topic } from './topic';
import { BundInstitutionSummary } from './bundInstitutionSummary';
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
'new'?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
export interface BundProjectSummary {
funding_code?: string | null;
department?: string | null;
department_fullname?: string | null;
referat?: string | null;
project_sponsor?: string | null;
project_sponsor_fullname?: string | null;
work_unit?: string | null;
recipient?: string | null;
municipal_code?: string | null;
municipality?: string | null;
place?: string | null;
state?: string | null;
country?: string | null;
implementing_agency?: string | null;
topic?: string | null;
performance_plan_system?: string | null;
performance_plan_system_text?: string | null;
funding_start?: string | null;
funding_end?: string | null;
grant_amount?: number | null;
funding_profile?: string | null;
joint_project?: string | null;
funding_type?: string | null;
publication_date?: string | null;
unix_timestamp?: number | null;
date?: string | null;
new?: boolean | null;
duration?: string | null;
oa_topics?: Array<Topic> | null;
institution?: BundInstitutionSummary | null;
}
+70 -29
View File
@@ -1,41 +1,82 @@
/**
* 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 { DfgProjectPersonRole } from './dfgProjectPersonRole';
import { DfgProjectSubprojectSummary } from './dfgProjectSubprojectSummary';
import { DfgProjectInstitutionRole } from './dfgProjectInstitutionRole';
import { DfgProjectSubjectArea } from './dfgProjectSubjectArea';
import { Topic } from './topic';
import { DfgProjectPublicationSummary } from './dfgProjectPublicationSummary';
/**
* Clean summary model for a DFG project, consolidating all person roles and institution references into unified lists.
* Clean, enriched summary model for a DFG project.
*/
export interface DfgProjectDetails {
/**
* The ID of the DFG project
*/
id: string;
link?: string | null;
title?: string | null;
description?: string | null;
project_identifier?: string | null;
funding_start_date?: string | null;
funding_end_date?: string | null;
dfg_procedure?: string | null;
subject_area?: string | null;
funding_type?: string | null;
international_reference?: string | null;
website?: string | null;
/**
* All persons associated with the DFG project (any role)
*/
associated_persons?: Array<string>;
/**
* All institutions associated with the DFG project
*/
institutions?: Array<string>;
subproject_of?: string | null;
export interface DfgProjectDetails {
id?: number | null;
link?: string | null;
page_url?: string | null;
external_link?: string | null;
title_de?: string | null;
title_en?: string | null;
description_de?: string | null;
description_en?: string | null;
final_report_abstract_de?: string | null;
final_report_abstract_en?: string | null;
project_identifier_de?: string | null;
project_identifier_en?: string | null;
funding_start?: number | null;
funding_end?: number | null;
funding_period_de?: string | null;
funding_period_en?: string | null;
funding_type_de?: string | null;
funding_type_en?: string | null;
funding_type_key?: string | null;
dfg_procedure?: string | null;
is_transfer_project?: boolean | null;
website_html_de?: string | null;
website_html_en?: string | null;
equipment_group?: string | null;
equipment_name?: string | null;
subject_area_de?: string | null;
subject_area_en?: string | null;
/**
* Detailed DFG subject-area classification entries (Fachsystematik)
*/
subject_classifications?: Array<DfgProjectSubjectArea>;
international_relation_de?: string | null;
international_relation_en?: string | null;
/**
* All persons associated with the project, each with their role
*/
persons?: Array<DfgProjectPersonRole>;
/**
* All institutions associated with the project, each with their role
*/
institutions?: Array<DfgProjectInstitutionRole>;
/**
* Flat, de-duplicated list of all person full names (convenience view)
*/
associated_persons?: Array<string>;
/**
* Flat, de-duplicated list of all institution names (convenience view)
*/
associated_institutions?: Array<string>;
parent_project_id?: number | null;
parent_title_de?: string | null;
parent_title_en?: string | null;
/**
* Sub-projects of this project, if any
*/
subprojects?: Array<DfgProjectSubprojectSummary>;
/**
* Publications resulting from the project
*/
publications?: Array<DfgProjectPublicationSummary>;
topics?: Array<Topic> | null;
}
@@ -0,0 +1,25 @@
/**
* 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.
*/
/**
* An institution associated with the project, together with its role.
*/
export interface DfgProjectInstitutionRole {
institute_id?: number | null;
name_de?: string | null;
name_en?: string | null;
role_key?: string | null;
role_label_de?: string | null;
role_label_en?: string | null;
is_dissolved?: boolean | null;
is_head?: boolean | null;
}
@@ -0,0 +1,27 @@
/**
* 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.
*/
/**
* A person associated with the project, together with their role.
*/
export interface DfgProjectPersonRole {
person_id?: number | null;
full_name?: string | null;
orcid_id?: string | null;
role_key?: string | null;
role_label_de?: string | null;
role_label_en?: string | null;
affiliation_de?: string | null;
affiliation_en?: string | null;
is_deceased?: boolean | null;
is_head?: boolean | null;
}
@@ -0,0 +1,22 @@
/**
* 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.
*/
/**
* A lightweight reference to a publication resulting from the project.
*/
export interface DfgProjectPublicationSummary {
publication_id?: number | null;
title?: string | null;
authors_editors?: string | null;
doi?: string | null;
publication_year?: number | null;
}
@@ -0,0 +1,17 @@
/**
* 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 DfgProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
@@ -0,0 +1,21 @@
/**
* 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.
*/
/**
* A single subject-area classification entry (DFG \'Fachsystematik\').
*/
export interface DfgProjectSubjectArea {
fach?: string | null;
fachgebiet?: string | null;
fachkollegium?: string | null;
wissenschaftsbereich?: string | null;
}
@@ -0,0 +1,26 @@
/**
* 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.
*/
/**
* A lightweight reference to a sub-project of this project.
*/
export interface DfgProjectSubprojectSummary {
subproject_id?: number | null;
title_de?: string | null;
title_en?: string | null;
short_title?: string | null;
role_label_de?: string | null;
person_full_name?: string | null;
status_de?: string | null;
funding_start?: number | null;
funding_end?: number | null;
}
+45 -43
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -13,6 +13,7 @@ import { HEUOrganization } from './hEUOrganization';
import { HEUPublication } from './hEUPublication';
import { Fp7WebLink } from './fp7WebLink';
import { HEUWebLink } from './hEUWebLink';
import { AuthorPage } from './authorPage';
import { HEUDeliverable } from './hEUDeliverable';
import { Fp7ProjectIPR } from './fp7ProjectIPR';
import { HEUEurosciVoc } from './hEUEurosciVoc';
@@ -21,51 +22,52 @@ import { HEULegalBasis } from './hEULegalBasis';
import { HEUTopic } from './hEUTopic';
import { Fp7ReportSummary } from './fp7ReportSummary';
import { HEUReportSummary } from './hEUReportSummary';
import { Topic } from './topic';
import { HEUProjectDetails } from './hEUProjectDetails';
/**
* The project data
*/
export interface EuProjectData {
acronym?: string;
contentUpdateDate?: string;
ecMaxContribution?: number;
ecSignatureDate?: string;
endDate?: string;
frameworkProgramme?: string;
fundingScheme?: string;
grantDoi?: string;
humanValidated?: boolean;
id?: string;
keywords?: string;
legalBasis?: string;
masterCall?: string;
nature?: string;
objective?: string;
rcn?: string;
startDate?: string;
status?: string;
subCall?: string;
title?: string;
topics?: string;
totalCost?: number;
organizations?: Array<HEUOrganization>;
publications?: Array<HEUPublication>;
iprs?: Array<Fp7ProjectIPR>;
report_summaries?: Array<Fp7ReportSummary>;
topicsList?: Array<HEUTopic>;
web_links?: Array<Fp7WebLink>;
eurosciVoc?: Array<HEUEurosciVoc>;
legalBasisList?: Array<HEULegalBasis>;
organizationCount?: number;
publicationCount?: number;
iprCount?: number;
deliverables?: Array<HEUDeliverable>;
reportSummaries?: Array<HEUReportSummary>;
webLinks?: Array<HEUWebLink>;
ercPrincipalInvestigators?: Array<H2020ErcPI>;
deliverableCount?: number;
ercPiCount?: number;
export interface EuProjectData {
acronym?: string;
contentUpdateDate?: string;
ecMaxContribution?: number;
ecSignatureDate?: string;
endDate?: string;
frameworkProgramme?: string;
fundingScheme?: string;
grantDoi?: string;
humanValidated?: boolean;
id?: string;
keywords?: string;
legalBasis?: string;
masterCall?: string;
nature?: string;
objective?: string;
rcn?: string;
startDate?: string;
status?: string;
subCall?: string;
title?: string;
topics?: string;
totalCost?: number;
organizations?: Array<HEUOrganization>;
publications?: Array<HEUPublication>;
iprs?: Array<Fp7ProjectIPR>;
report_summaries?: Array<Fp7ReportSummary>;
topicsList?: Array<HEUTopic>;
web_links?: Array<Fp7WebLink>;
eurosciVoc?: Array<HEUEurosciVoc>;
legalBasisList?: Array<HEULegalBasis>;
organizationCount?: number;
publicationCount?: number;
iprCount?: number;
oaTopics?: Array<Topic>;
oaAuthors?: AuthorPage;
deliverables?: Array<HEUDeliverable>;
reportSummaries?: Array<HEUReportSummary>;
webLinks?: Array<HEUWebLink>;
ercPrincipalInvestigators?: Array<H2020ErcPI>;
deliverableCount?: number;
ercPiCount?: number;
}
+39 -37
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -12,47 +12,49 @@ import { Fp7WebLink } from './fp7WebLink';
import { Fp7Publication } from './fp7Publication';
import { Fp7ReportSummary } from './fp7ReportSummary';
import { Fp7Topic } from './fp7Topic';
import { AuthorPage } from './authorPage';
import { Fp7ProjectIPR } from './fp7ProjectIPR';
import { Topic } from './topic';
import { Fp7Organization } from './fp7Organization';
import { Fp7LegalBasis } from './fp7LegalBasis';
/**
* Comprehensive FP7 Project model combining all related entities. This model extends the base Fp7Project with all associated data.
*/
export interface Fp7ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<Fp7Organization> | null;
publications?: Array<Fp7Publication> | null;
iprs?: Array<Fp7ProjectIPR> | null;
report_summaries?: Array<Fp7ReportSummary> | null;
topicsList?: Array<Fp7Topic> | null;
web_links?: Array<Fp7WebLink> | null;
eurosciVoc?: Array<Fp7EurosciVoc> | null;
legalBasisList?: Array<Fp7LegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
iprCount?: number | null;
export interface Fp7ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<Fp7Organization> | null;
publications?: Array<Fp7Publication> | null;
iprs?: Array<Fp7ProjectIPR> | null;
report_summaries?: Array<Fp7ReportSummary> | null;
topicsList?: Array<Fp7Topic> | null;
web_links?: Array<Fp7WebLink> | null;
eurosciVoc?: Array<Fp7EurosciVoc> | null;
legalBasisList?: Array<Fp7LegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
iprCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+22 -22
View File
@@ -1,35 +1,35 @@
/**
* 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 { Author } from './author';
/**
* Fp7Publication
*/
export interface Fp7Publication {
authors?: string | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
export interface Fp7Publication {
authors?: string | null;
oaAuthors?: Array<Author> | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
}
+41 -39
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -11,51 +11,53 @@ import { H2020LegalBasis } from './h2020LegalBasis';
import { H2020ErcPI } from './h2020ErcPI';
import { H2020Deliverable } from './h2020Deliverable';
import { H2020WebLink } from './h2020WebLink';
import { AuthorPage } from './authorPage';
import { H2020Publication } from './h2020Publication';
import { H2020ReportSummary } from './h2020ReportSummary';
import { H2020Topic } from './h2020Topic';
import { H2020EurosciVoc } from './h2020EurosciVoc';
import { Topic } from './topic';
import { H2020Organization } from './h2020Organization';
/**
* Comprehensive Horizon 2020 Project model combining all related entities. This model extends the base H2020Project with all associated data.
*/
export interface H2020ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<H2020Organization> | null;
publications?: Array<H2020Publication> | null;
deliverables?: Array<H2020Deliverable> | null;
reportSummaries?: Array<H2020ReportSummary> | null;
topicsList?: Array<H2020Topic> | null;
webLinks?: Array<H2020WebLink> | null;
eurosciVoc?: Array<H2020EurosciVoc> | null;
legalBasisList?: Array<H2020LegalBasis> | null;
ercPrincipalInvestigators?: Array<H2020ErcPI> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
ercPiCount?: number | null;
export interface H2020ProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<H2020Organization> | null;
publications?: Array<H2020Publication> | null;
deliverables?: Array<H2020Deliverable> | null;
reportSummaries?: Array<H2020ReportSummary> | null;
topicsList?: Array<H2020Topic> | null;
webLinks?: Array<H2020WebLink> | null;
eurosciVoc?: Array<H2020EurosciVoc> | null;
legalBasisList?: Array<H2020LegalBasis> | null;
ercPrincipalInvestigators?: Array<H2020ErcPI> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
ercPiCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+22 -22
View File
@@ -1,35 +1,35 @@
/**
* 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 { Author } from './author';
/**
* H2020Publication
*/
export interface H2020Publication {
authors?: string | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
export interface H2020Publication {
authors?: string | null;
oaAuthors?: Array<Author> | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
}
+39 -37
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -12,47 +12,49 @@ import { HEUOrganization } from './hEUOrganization';
import { HEUTopic } from './hEUTopic';
import { HEUPublication } from './hEUPublication';
import { HEUWebLink } from './hEUWebLink';
import { AuthorPage } from './authorPage';
import { HEUReportSummary } from './hEUReportSummary';
import { HEUDeliverable } from './hEUDeliverable';
import { Topic } from './topic';
import { HEUEurosciVoc } from './hEUEurosciVoc';
/**
* Comprehensive Horizon Europe Project model combining all related entities. This model extends the base HEUProject with all associated data.
*/
export interface HEUProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<HEUOrganization> | null;
publications?: Array<HEUPublication> | null;
deliverables?: Array<HEUDeliverable> | null;
reportSummaries?: Array<HEUReportSummary> | null;
topicsList?: Array<HEUTopic> | null;
webLinks?: Array<HEUWebLink> | null;
eurosciVoc?: Array<HEUEurosciVoc> | null;
legalBasisList?: Array<HEULegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
export interface HEUProjectDetails {
acronym?: string | null;
contentUpdateDate?: string | null;
ecMaxContribution?: number | null;
ecSignatureDate?: string | null;
endDate?: string | null;
frameworkProgramme?: string | null;
fundingScheme?: string | null;
grantDoi?: string | null;
humanValidated?: boolean | null;
id?: string | null;
keywords?: string | null;
legalBasis?: string | null;
masterCall?: string | null;
nature?: string | null;
objective?: string | null;
rcn?: string | null;
startDate?: string | null;
status?: string | null;
subCall?: string | null;
title?: string | null;
topics?: string | null;
totalCost?: number | null;
organizations?: Array<HEUOrganization> | null;
publications?: Array<HEUPublication> | null;
deliverables?: Array<HEUDeliverable> | null;
reportSummaries?: Array<HEUReportSummary> | null;
topicsList?: Array<HEUTopic> | null;
webLinks?: Array<HEUWebLink> | null;
eurosciVoc?: Array<HEUEurosciVoc> | null;
legalBasisList?: Array<HEULegalBasis> | null;
organizationCount?: number | null;
publicationCount?: number | null;
deliverableCount?: number | null;
oaTopics?: Array<Topic> | null;
oaAuthors?: AuthorPage | null;
}
+22 -22
View File
@@ -1,35 +1,35 @@
/**
* 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 { Author } from './author';
/**
* HEUPublication
*/
export interface HEUPublication {
authors?: string | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
export interface HEUPublication {
authors?: string | null;
oaAuthors?: Array<Author> | null;
collection?: string | null;
contentUpdateDate?: string | null;
doi?: string | null;
id?: string | null;
isPublishedAs?: string | null;
journalNumber?: string | null;
journalTitle?: string | null;
projectAcronym?: string | null;
projectID?: string | null;
publishedPages?: string | null;
publishedYear?: number | null;
publisher?: string | null;
qaProcessedDoi?: string | null;
rcn?: string | null;
repositoryUrl?: string | null;
title?: string | null;
volume?: string | null;
}
+11
View File
@@ -9,6 +9,9 @@ export * from './authorCountsByYearInner';
export * from './authorIds';
export * from './authorMetricsRequest';
export * from './authorNode';
export * from './authorOrientationProfile';
export * from './authorOrientationProfileStatus';
export * from './authorOrientationProfilesRequest';
export * from './authorPage';
export * from './authorParsedLongestName';
export * from './authorPositionCount';
@@ -32,6 +35,8 @@ export * from './bodyLogin';
export * from './bodyRequestOtk';
export * from './bodyRequestPasswordReset';
export * from './bodyResetPassword';
export * from './bundInstitutionSummary';
export * from './bundInstitutionSummaryPage';
export * from './bundProjectDetails';
export * from './bundProjectPage';
export * from './bundProjectSummary';
@@ -62,7 +67,13 @@ export * from './dfgInstitutionSummaryPage';
export * from './dfgPersonSummary';
export * from './dfgPersonSummaryPage';
export * from './dfgProjectDetails';
export * from './dfgProjectInstitutionRole';
export * from './dfgProjectPage';
export * from './dfgProjectPersonRole';
export * from './dfgProjectPublicationSummary';
export * from './dfgProjectStatusStatistics';
export * from './dfgProjectSubjectArea';
export * from './dfgProjectSubprojectSummary';
export * from './dfgProjectSummary';
export * from './dfgProjectTopic';
export * from './dfgProjectTopics';
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
+89 -26
View File
@@ -39,6 +39,7 @@ import {
} from './resolvers/work-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
import { SearchResultsStateService } from './modules/keywords-search/search-results/search-results-state.service';
import { roleGuard } from './shared/guards/role.guard';
import { UserRole } from './api';
@@ -241,6 +242,20 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedBundInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
@@ -270,6 +285,7 @@ export const routes: Routes = [
'search_type',
'topic',
'topics',
'trend_topics',
'keyword',
'keywords',
'institutions',
@@ -279,7 +295,9 @@ export const routes: Routes = [
'fuzzy',
];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
(key) =>
from.queryParamMap.getAll(key).join(',') !==
to.queryParamMap.getAll(key).join(','),
);
},
},
@@ -526,20 +544,6 @@ export const routes: Routes = [
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.PERSON,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.KEYWORDS_SEARCH,
},
},
],
},
{
@@ -689,17 +693,71 @@ export const routes: Routes = [
(mod) => mod.InstitutionProjectsComponent,
),
resolve: {
bundProjectPage: bundProjectPageResolver,
bundProjectsFunding: bundProjectsFundingResolver,
cordisEuProjectPage: euCordisProjectsResolver,
cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
runGuardsAndResolvers: 'always',
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'dfg',
},
{
path: 'dfg',
component: DfgProjectsComponent,
resolve: {
dfgProjectPage: dfgProjectsResolver,
selectedDfgInstitutionsPage: selectedDfgInstitutionsResolver,
selectedDfgAuthorsPage: selectedDfgAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION,
},
},
{
path: 'eu',
component: EuProjectsComponent,
resolve: {
euCordisProjectPage: euCordisProjectsResolver,
selectedEuInstitutionsPage: selectedEuInstitutionsResolver,
selectedEuAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION,
},
},
{
path: 'bund',
component: BundProjectsComponent,
resolve: {
bundProjectPage: bundProjectsResolver,
selectedBundInstitutionsPage: selectedBundInstitutionsResolver,
selectedBundAuthorsPage: selectedAuthorsResolver,
selectedTopicsPage: selectedTopicsResolver,
},
runGuardsAndResolvers: 'always',
data: {
resolvingFor: RESOLVING_PROJECT_PAGE_FOR.INSTITUTION,
},
},
],
// resolve: {
// bundProjectPage: bundProjectPageResolver,
// bundProjectsFunding: bundProjectsFundingResolver,
// cordisEuProjectPage: euCordisProjectsResolver,
// cordisEuProjectsFunding: cordisEuProjectsFundingResolver,
// },
// runGuardsAndResolvers: (from, to) => {
// const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
// return keys.some(
// (key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
// );
// },
},
{
path: 'patents',
@@ -757,9 +815,14 @@ export const routes: Routes = [
topicPage: topicPageResolver,
},
runGuardsAndResolvers: (from, to) => {
return Object.values(topicQueryParamKeys).some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
return Object.values(topicQueryParamKeys).some((key) => {
const fromValues = from.queryParamMap.getAll(key);
const toValues = to.queryParamMap.getAll(key);
return (
fromValues.length !== toValues.length ||
fromValues.some((value, index) => value !== toValues[index])
);
});
},
},
{
@@ -23,10 +23,11 @@ h1,
h2,
p {
margin: 0;
color: var(--sg-text);
}
.page-header p {
color: #64748b;
color: var(--sg-text-muted);
margin-top: 6px;
}
@@ -46,19 +47,19 @@ p {
}
.table-panel {
border: 1px solid #d7dde6;
border: 1px solid var(--sg-border);
border-radius: 8px;
background: #fff;
background: var(--sg-card-bg);
}
.table-header {
justify-content: space-between;
padding: 16px;
border-bottom: 1px solid #e5e7eb;
border-bottom: 1px solid var(--sg-border);
}
.table-header span {
color: #64748b;
color: var(--sg-text-muted);
}
.table-wrap {
@@ -74,29 +75,29 @@ th,
td {
padding: 12px 16px;
text-align: left;
border-bottom: 1px solid #edf1f7;
border-bottom: 1px solid var(--sg-border);
white-space: nowrap;
}
th {
color: #475569;
color: var(--sg-text);
font-weight: 700;
background: #f8fafc;
background: var(--sg-surface-muted);
}
tr.deleted {
color: #94a3b8;
color: var(--sg-text-soft);
}
tr.deactivated:not(.deleted) {
color: #64748b;
background: #f8fafc;
color: var(--sg-text-muted);
background: var(--sg-surface-soft);
}
.link-button {
border: 0;
background: transparent;
color: #1d4ed8;
color: var(--sg-blue-highlight);
padding: 0;
font: inherit;
cursor: pointer;
@@ -109,25 +110,25 @@ tr.deactivated:not(.deleted) {
min-height: 24px;
border-radius: 999px;
padding: 2px 10px;
background: #eef2ff;
color: #3730a3;
background: var(--sg-primary-soft);
color: var(--sg-blue-highlight);
font-size: 12px;
font-weight: 700;
}
.status {
background: #dcfce7;
color: #166534;
background: var(--sg-success-soft);
color: var(--sg-success);
}
.status--deleted {
background: #fee2e2;
color: #991b1b;
background: var(--sg-error-soft);
color: var(--sg-error);
}
.status--deactivated {
background: #fef3c7;
color: #92400e;
background: var(--sg-warning-soft);
color: var(--sg-warning);
}
.row-actions {
@@ -135,7 +136,7 @@ tr.deactivated:not(.deleted) {
}
.empty {
color: #64748b;
color: var(--sg-text-muted);
text-align: center;
}
@@ -6,10 +6,14 @@
background:
radial-gradient(
circle at top left,
rgba(61, 124, 255, 0.12),
color-mix(in srgb, var(--sg-primary) 15%, transparent),
transparent 34%
),
linear-gradient(160deg, #f7f9ff 0%, #ffffff 64%);
linear-gradient(
160deg,
var(--sg-surface-muted) 0%,
var(--sg-background) 64%
);
}
.login-panel {
@@ -80,7 +84,7 @@ p {
.step--active span {
background: var(--sg-primary);
border-color: var(--sg-primary);
color: #ffffff;
color: var(--sg-background);
}
.step-line {
@@ -158,7 +162,7 @@ p {
}
.expiry--expired {
color: #ba1a1a;
color: var(--sg-error);
}
@media (max-width: 560px) {
@@ -16,15 +16,16 @@
h1 {
margin: 2px 0 6px;
font-size: 2rem;
color: var(--sg-text);
}
p {
margin: 0;
color: #667085;
color: var(--sg-text-muted);
}
.eyebrow {
color: #3f51b5;
color: var(--sg-primary);
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.12em;
@@ -38,21 +39,22 @@
align-items: center;
gap: 0 10px;
padding: 14px 18px;
border: 1px solid #e4e7ec;
border: 1px solid var(--sg-border);
border-radius: 14px;
background: white;
background: var(--sg-surface);
mat-icon {
grid-row: 1 / 3;
color: #3f51b5;
color: var(--sg-primary);
}
strong {
font-size: 1.25rem;
color: var(--sg-text);
}
span {
color: #667085;
color: var(--sg-text-muted);
font-size: 0.75rem;
}
}
@@ -71,19 +73,19 @@
align-items: center;
justify-content: center;
text-align: center;
color: #667085;
color: var(--sg-text-muted);
}
.empty-state mat-icon {
width: 54px;
height: 54px;
font-size: 54px;
color: #98a2b3;
color: var(--sg-text-soft);
}
.empty-state h2 {
margin: 16px 0 6px;
color: #1d2939;
color: var(--sg-text);
}
@media (max-width: 700px) {
@@ -1,8 +1,9 @@
import { Component, computed, input, output } from '@angular/core';
import { Component, computed, inject, input, output } from '@angular/core';
import { CollaborationGraph } from '../../api';
import { EChartsCoreOption } from 'echarts';
import { MatIconModule } from '@angular/material/icon';
import { NgxEchartsDirective } from 'ngx-echarts';
import { ChartThemeService } from '../../shared/services/chart-theme.service';
import * as echarts from 'echarts/core';
import {
@@ -36,9 +37,10 @@ export interface NodeClickEvent {
})
export class CollaborationGraphComponent {
collaborationGraph = input.required<CollaborationGraph>();
handleNodeClick = output<NodeClickEvent>();
private readonly chartTheme = inject(ChartThemeService);
readonly isEmptyGraph = computed(() => {
const graph = this.collaborationGraph();
return (
@@ -67,10 +69,13 @@ export class CollaborationGraphComponent {
options = computed<EChartsCoreOption>(() => {
const graph = this.collaborationGraph();
const colors = this.chartTheme.colors();
if (!graph) {
return {};
}
const textColor = colors.text;
const frequencies = this.occurenceFrequencies();
const minFrequency = Math.min(...Object.values(frequencies));
const maxFrequency = Math.max(...Object.values(frequencies));
@@ -129,10 +134,10 @@ export class CollaborationGraphComponent {
}));
const categories = [
{ name: 'author' },
{ name: 'collaborator' },
{ name: 'institution' },
{ name: 'work' },
{ name: 'author', itemStyle: { color: colors.blueHighlight } },
{ name: 'collaborator', itemStyle: { color: colors.success } },
{ name: 'institution', itemStyle: { color: colors.warning } },
{ name: 'work', itemStyle: { color: colors.primary } },
];
return {
@@ -142,6 +147,9 @@ export class CollaborationGraphComponent {
orient: 'horizontal',
formatter: (name: string) => this.categoryLabels[name] || name,
itemGap: 20,
textStyle: { color: textColor },
inactiveColor: colors.mutedTextColor,
inactiveBorderColor: colors.tooltipBorder,
},
series: {
type: 'graph',
@@ -152,19 +160,42 @@ export class CollaborationGraphComponent {
links: links,
categories: categories,
roam: true,
roamTrigger: 'global', // + 2 hours because of incomplete documentation https://github.com/apache/echarts/issues/17214
roamTrigger: 'global',
zoom: 0.1,
force: {
repulsion: 10000,
friction: 0.9,
gravity: 0.2,
},
label: {
show: true,
position: 'right',
color: textColor,
fontSize: 12,
},
emphasis: {
focus: 'adjacency',
label: {
show: true,
color: textColor,
fontWeight: 'bold',
},
lineStyle: {
width: 5,
},
},
blur: {
itemStyle: {
opacity: 0.15,
},
label: {
show: false,
opacity: 0.15,
},
lineStyle: {
opacity: 0.1,
},
},
},
};
});
@@ -0,0 +1,185 @@
import { Component, computed, inject, input } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { WorkPrimaryCategory } from '../../../api';
import { ChartThemeService } from '../../../shared/services/chart-theme.service';
import { SUBFIELD_COLORS } from '../compare-authors-colors';
export interface AuthorCategoryLegendItem {
category: WorkPrimaryCategory;
label: string;
color: string;
}
const categoryLegendItem = (
category: WorkPrimaryCategory,
label: string,
color: string,
): AuthorCategoryLegendItem => ({
category,
label,
color,
});
export const AUTHOR_CATEGORY_LEGEND: readonly AuthorCategoryLegendItem[] = [
categoryLegendItem(
WorkPrimaryCategory.BasicResearch,
'Grundlagenforschung',
SUBFIELD_COLORS[0],
),
categoryLegendItem(
WorkPrimaryCategory.AppliedResearch,
'Anwendungsbasierte Forschung',
SUBFIELD_COLORS[1],
),
categoryLegendItem(
WorkPrimaryCategory.ExperimentalDevelopment,
'Experimentelle Entwicklung',
SUBFIELD_COLORS[2],
),
categoryLegendItem(
WorkPrimaryCategory.NonResearch,
'Nicht-forschende Tätigkeit',
SUBFIELD_COLORS[3],
),
categoryLegendItem(
WorkPrimaryCategory.NotClassified,
'Nicht klassifiziert',
SUBFIELD_COLORS[4],
),
];
@Component({
selector: 'app-author-category-pie',
standalone: true,
imports: [NgxEchartsDirective],
template: '<div echarts class="category-chart" [options]="options()"></div>',
styles: `
:host {
display: block;
width: 100%;
max-width: 240px;
}
.category-chart {
width: 100%;
height: 220px;
}
`,
})
export class AuthorCategoryPieComponent {
counts = input<Partial<Record<WorkPrimaryCategory, number>> | null>(null);
private readonly chartTheme = inject(ChartThemeService);
readonly total = computed(() =>
Object.values(this.counts() ?? {}).reduce(
(sum, count) => sum + Math.max(0, count),
0,
),
);
readonly options = computed<EChartsOption>(() => {
const counts = this.counts() ?? {};
const total = this.total();
const colors = this.chartTheme.colors();
const textColor = colors.text;
const mutedColor = colors.mutedTextColor;
const tooltipBg = colors.cardBg;
const tooltipBorder = colors.splitLine;
const palette = colors.subfieldColors;
const categoryLegend: readonly AuthorCategoryLegendItem[] = [
categoryLegendItem(
WorkPrimaryCategory.BasicResearch,
'Grundlagenforschung',
palette[0],
),
categoryLegendItem(
WorkPrimaryCategory.AppliedResearch,
'Anwendungsbasierte Forschung',
palette[1],
),
categoryLegendItem(
WorkPrimaryCategory.ExperimentalDevelopment,
'Experimentelle Entwicklung',
palette[2],
),
categoryLegendItem(
WorkPrimaryCategory.NonResearch,
'Nicht-forschende Tätigkeit',
palette[3],
),
categoryLegendItem(
WorkPrimaryCategory.NotClassified,
'Nicht klassifiziert',
palette[4],
),
];
return {
animation: false,
tooltip: {
trigger: 'item',
formatter: '{b}: {c} Publikationen ({d} %)',
backgroundColor: tooltipBg,
borderColor: tooltipBorder,
textStyle: { color: textColor },
},
graphic: {
type: 'text',
left: 'center',
top: 'middle',
silent: true,
style: {
text: `{value|${total}}\n{label|klassifiziert}`,
textAlign: 'center',
textVerticalAlign: 'middle',
rich: {
value: {
fill: textColor,
fontSize: 22,
fontWeight: 700,
lineHeight: 23,
},
label: {
fill: mutedColor,
fontSize: 11,
fontWeight: 600,
lineHeight: 12,
},
},
},
},
series: [
{
type: 'pie',
radius: ['40%', '70%'],
center: ['50%', '50%'],
avoidLabelOverlap: true,
silent: false,
selectedMode: false,
padAngle: 1,
itemStyle: {
borderRadius: 2,
},
label: {
show: false,
},
labelLine: { show: false },
emphasis: {
scale: true,
scaleSize: 6,
},
data: categoryLegend
.map((item) => ({
name: item.label,
value: Math.max(0, counts[item.category] ?? 0),
itemStyle: { color: item.color },
}))
.filter((item) => item.value > 0),
},
],
};
});
}
@@ -0,0 +1,106 @@
@if (visible()) {
<mat-card appearance="outlined" class="research-profile-card">
<mat-card-header class="profile-header">
<mat-icon class="profile-icon">science</mat-icon>
<div class="profile-heading">
<mat-card-title>Forschungsprofil</mat-card-title>
<mat-card-subtitle>
Vergleich der Forschungsorientierung
</mat-card-subtitle>
</div>
</mat-card-header>
<mat-card-content>
<section aria-labelledby="category-distribution-title">
<h3 id="category-distribution-title" class="section-title">
Verteilung der Forschungskategorien
</h3>
<div class="author-grid">
@for (view of views(); track view.author.authorId) {
<mat-card appearance="outlined" class="author-card">
<mat-card-header class="author-header">
<div class="author-heading">
<span
class="author-color"
[style.background]="view.author.color"></span>
<mat-card-title>{{ view.author.name }}</mat-card-title>
</div>
</mat-card-header>
<mat-card-content class="distribution-content">
@if (hasCategoryData(view.profile)) {
<app-author-category-pie
[counts]="view.profile.primary_category_counts ?? null" />
} @else {
<p class="status-label distribution-status">
{{ categoryStatusLabel(view.profile) }}
</p>
}
</mat-card-content>
</mat-card>
}
</div>
<mat-chip-set class="category-legend" aria-label="Forschungskategorien">
@for (item of categoryLegend; track item.category) {
<mat-chip class="legend-chip" [style.--legend-color]="item.color">
<span class="legend-color" [style.background]="item.color"></span>
{{ item.label }}
</mat-chip>
}
</mat-chip-set>
</section>
<mat-divider class="section-divider"></mat-divider>
<section aria-labelledby="average-score-title">
<h3 id="average-score-title" class="section-title">
Durchschnittlicher Orientierungsscore
</h3>
<div class="author-grid">
@for (view of views(); track view.author.authorId) {
<mat-card appearance="outlined" class="author-card">
<mat-card-header class="author-header">
<div class="author-heading">
<span
class="author-color"
[style.background]="view.author.color"></span>
<mat-card-title>{{ view.author.name }}</mat-card-title>
</div>
</mat-card-header>
<mat-card-content class="score-content">
<app-orientation-gauge
[score]="view.profile.orientation_score ?? null" />
@if (hasLowScoreSample(view.profile)) {
<mat-card
appearance="outlined"
class="warning-note"
[style.--warning-border]="lowSampleTokens.border"
[style.--warning-background]="lowSampleTokens.background"
[style.--warning-text]="lowSampleTokens.color">
<span>Geringe Datengrundlage</span>
<mat-icon
class="info-icon"
[matTooltip]="lowScoreSampleTooltip(view.profile)"
matTooltipPosition="above"
aria-label="Erläuterung zur Datengrundlage">
info_outline
</mat-icon>
</mat-card>
} @else if (!isAvailable(view.profile)) {
<p class="status-label">
{{ statusLabel(view.profile.status) }}
</p>
}
</mat-card-content>
</mat-card>
}
</div>
</section>
</mat-card-content>
</mat-card>
}
@@ -0,0 +1,207 @@
:host {
display: block;
}
.research-profile-card {
border-color: var(--sg-border);
border-radius: 16px;
box-shadow: var(--sg-shadow-sm);
}
.profile-header {
align-items: center;
padding: 20px 22px 16px;
}
.profile-icon {
flex: 0 0 30px;
width: 30px;
height: 30px;
margin: 0 12px 0 0;
color: var(--sg-text-muted);
font-size: 30px;
line-height: 30px;
}
.profile-heading {
display: flex;
flex-direction: column;
gap: 1px;
min-width: 0;
}
mat-card-title {
color: var(--sg-text);
font-size: 16px;
font-weight: 700;
line-height: 1.25;
}
mat-card-subtitle {
margin: 0;
color: var(--sg-text-muted);
font-size: 13px;
line-height: 1.3;
}
.research-profile-card > mat-card-content {
padding: 10px 22px 22px;
}
section {
min-width: 0;
}
.section-title {
margin: 8px 0 12px;
color: var(--sg-text);
font-size: 15px;
font-weight: 700;
line-height: 1.3;
}
.author-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(230px, 1fr));
gap: 14px;
}
.author-card {
min-width: 0;
border-color: var(--sg-border);
background: var(--sg-surface);
}
.author-header {
align-items: center;
min-height: 52px;
padding: 14px 16px 4px;
}
.author-heading {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.author-heading mat-card-title {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.author-color {
flex: 0 0 auto;
width: 12px;
height: 12px;
border-radius: 3px;
}
.distribution-content,
.score-content {
display: flex;
flex-direction: column;
align-items: center;
padding: 0 16px 16px;
}
.distribution-content {
justify-content: center;
min-height: 232px;
}
.score-content {
min-height: 220px;
}
.score-content app-orientation-gauge {
margin-top: -4px;
}
.category-legend {
display: flex;
justify-content: center;
margin-top: 14px;
}
.legend-chip {
--mdc-chip-elevated-container-color: var(--sg-surface-soft);
--mdc-chip-label-text-color: var(--sg-text);
--mdc-chip-outline-color: var(--sg-border);
border: 1px solid var(--sg-border);
color: var(--sg-text);
}
.legend-color {
display: inline-block;
width: 9px;
height: 9px;
margin-right: 6px;
border-radius: 50%;
}
.section-divider {
margin: 22px 0 18px;
}
.status-label {
display: flex;
align-items: center;
justify-content: center;
min-height: 34px;
margin: 20px 0 0;
color: var(--sg-text-muted);
font-size: 13px;
font-weight: 600;
text-align: center;
}
.warning-note {
display: flex;
flex-direction: row;
align-items: center;
gap: 10px;
min-height: 42px;
margin-top: 12px;
padding: 9px 12px;
border-color: var(--warning-border);
border-radius: 12px;
background: var(--warning-background);
color: var(--warning-text);
box-shadow: none;
font-size: 13px;
line-height: 1.4;
}
.warning-note .info-icon {
flex: 0 0 auto;
width: 16px;
height: 16px;
color: inherit;
font-size: 16px;
line-height: 16px;
opacity: 0.7;
cursor: default;
&:hover {
opacity: 1;
}
}
.distribution-status {
margin: 0;
}
@media (max-width: 720px) {
.research-profile-card > mat-card-header,
.research-profile-card > mat-card-content {
padding-right: 16px;
padding-left: 16px;
}
.author-grid {
grid-template-columns: 1fr;
}
}
@@ -0,0 +1,134 @@
import { Component, computed, input } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatChipsModule } from '@angular/material/chips';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import {
AuthorOrientationProfile,
AuthorOrientationProfileStatus,
} from '../../../api';
import { OrientationGaugeComponent } from '../../../shared/ui/orientation-gauge/orientation-gauge.component';
import { topicChipColorTokens } from '../../../shared/ui/topic-chip/topic-chip.component';
import {
AUTHOR_CATEGORY_LEGEND,
AuthorCategoryPieComponent,
} from './author-category-pie.component';
export interface ResearchProfileAuthor {
authorId: string;
name: string;
color: string;
}
interface AuthorOrientationView {
author: ResearchProfileAuthor;
profile: AuthorOrientationProfile;
}
const LOW_SAMPLE_MAX_WORKS = 4;
const LOW_SAMPLE_TOKENS = topicChipColorTokens('orange');
@Component({
selector: 'app-author-research-profile',
standalone: true,
imports: [
MatCardModule,
MatChipsModule,
MatDividerModule,
MatIconModule,
MatTooltipModule,
AuthorCategoryPieComponent,
OrientationGaugeComponent,
],
templateUrl: './author-research-profile.component.html',
styleUrl: './author-research-profile.component.scss',
})
export class AuthorResearchProfileComponent {
authors = input.required<ResearchProfileAuthor[]>();
profiles = input.required<AuthorOrientationProfile[]>();
loading = input(false);
readonly categoryLegend = AUTHOR_CATEGORY_LEGEND;
readonly lowSampleTokens = LOW_SAMPLE_TOKENS;
readonly views = computed<AuthorOrientationView[]>(() => {
const profilesById = new Map(
this.profiles().map((profile) => [profile.author_id, profile]),
);
return this.authors()
.map((author) => {
const profile = profilesById.get(author.authorId);
return profile ? { author, profile } : null;
})
.filter((view): view is AuthorOrientationView => view !== null);
});
readonly visible = computed(() => {
const profiles = this.profiles();
const profilesWithoutClassifiedWorks = profiles.filter(
(profile) => (profile.classified_work_count ?? 0) === 0,
).length;
return (
!this.loading() &&
profiles.length >= 2 &&
profilesWithoutClassifiedWorks < 3
);
});
statusLabel(status: AuthorOrientationProfileStatus): string {
switch (status) {
case AuthorOrientationProfileStatus.insufficient_scored_publications:
return 'Zu wenige Publikationen für einen Orientierungsscore';
case AuthorOrientationProfileStatus.no_classified_publications:
return 'Keine klassifizierten Publikationen';
case AuthorOrientationProfileStatus.no_orientation_score:
return 'Kein Orientierungsscore verfügbar';
case AuthorOrientationProfileStatus.restricted:
return 'Orientierungsscore nicht verfügbar';
default:
return '';
}
}
isAvailable(profile: AuthorOrientationProfile): boolean {
return profile.status === AuthorOrientationProfileStatus.available;
}
hasLowScoreSample(profile: AuthorOrientationProfile): boolean {
const scoredWorkCount = profile.scored_work_count ?? 0;
return (
profile.orientation_score != null &&
scoredWorkCount > 0 &&
scoredWorkCount <= LOW_SAMPLE_MAX_WORKS
);
}
lowScoreSampleTooltip(profile: AuthorOrientationProfile): string {
const scoredWorkCount = profile.scored_work_count ?? 0;
const publicationLabel =
scoredWorkCount === 1
? 'einer Publikation'
: `${scoredWorkCount} Publikationen`;
return `Der Orientierungsscore basiert auf nur ${publicationLabel} und ist daher nur eingeschränkt aussagekräftig.`;
}
hasCategoryData(profile: AuthorOrientationProfile): boolean {
return Object.values(profile.primary_category_counts ?? {}).some(
(count) => count > 0,
);
}
categoryStatusLabel(profile: AuthorOrientationProfile): string {
if (profile.status === AuthorOrientationProfileStatus.restricted) {
return 'Forschungsprofil nicht verfügbar';
}
if (
profile.status ===
AuthorOrientationProfileStatus.no_classified_publications
) {
return 'Keine klassifizierten Publikationen';
}
return 'Keine Kategoriedaten verfügbar';
}
}
@@ -0,0 +1,14 @@
export const AUTHOR_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd'];
export const SUBFIELD_COLORS = [
'#2563eb',
'#16a34a',
'#d97706',
'#7c3aed',
'#0891b2',
'#db2777',
'#65a30d',
'#b45309',
];
export const OTHER_COLOR = '#9ca3af';
@@ -97,6 +97,11 @@
<p class="compare-hint">Keine Daten für das Themenprofil.</p>
}
</section>
<app-author-research-profile
[authors]="researchProfileAuthors()"
[profiles]="orientationProfiles()"
[loading]="orientationProfilesLoading()" />
}
</div>
@@ -18,7 +18,7 @@
margin: 0;
font-size: 24px;
font-weight: 700;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
}
}
@@ -34,16 +34,16 @@
gap: 6px;
padding: 4px 12px;
border-radius: 999px;
background: var(--sg-surface-muted, #f7f9ff);
border: 1px solid var(--sg-border, #dde5f2);
color: var(--sg-text-muted, #64708f);
background: var(--sg-surface-muted);
border: 1px solid var(--sg-border);
color: var(--sg-text-muted);
font-size: 13px;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
color: var(--sg-text-soft, #8a95b3);
color: var(--sg-text-soft);
}
}
@@ -62,7 +62,7 @@
gap: 8px;
font-size: 14px;
font-weight: 600;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
}
.legend-swatch {
@@ -74,10 +74,10 @@
/* ---- cards ---- */
.card {
background: #fff;
border: 1px solid #d7e4ff;
background: var(--sg-card-bg);
border: 1px solid var(--sg-border);
border-radius: 16px;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.04);
box-shadow: var(--sg-shadow-sm);
padding: 20px 22px;
}
@@ -85,19 +85,19 @@
margin: 0;
font-size: 16px;
font-weight: 700;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
}
.card-sub {
margin: 4px 0 0;
font-size: 13px;
color: var(--sg-text-muted, #64708f);
color: var(--sg-text-muted);
}
.compare-hint {
padding: 24px;
text-align: center;
color: var(--sg-text-muted, #64708f);
color: var(--sg-text-muted);
}
/* ---- comparison table ---- */
@@ -114,7 +114,7 @@
thead th {
text-align: left;
padding: 0 16px 10px;
border-bottom: 2px solid var(--sg-border, #dde5f2);
border-bottom: 2px solid var(--sg-border);
vertical-align: bottom;
}
@@ -127,12 +127,12 @@
align-items: center;
gap: 8px;
font-weight: 700;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
}
tbody tr + tr th,
tbody tr + tr td {
border-top: 1px solid var(--sg-border, #dde5f2);
border-top: 1px solid var(--sg-border);
}
tbody th,
@@ -148,7 +148,7 @@
.metric-label {
display: block;
font-weight: 600;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
}
.metric-hint {
@@ -156,24 +156,24 @@
margin-top: 2px;
font-size: 12px;
font-weight: 400;
color: var(--sg-text-soft, #8a95b3);
color: var(--sg-text-soft);
}
.value-cell {
text-align: right;
font-variant-numeric: tabular-nums;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
white-space: nowrap;
&.best {
font-weight: 700;
color: var(--sg-primary, #0b1020);
background: var(--sg-surface-soft, #f3f6fd);
color: var(--sg-primary);
background: var(--sg-surface-soft);
}
}
.value-empty {
color: var(--sg-text-soft, #8a95b3);
color: var(--sg-text-soft);
}
/* author-position row: first / middle / last shown together, colour-coded */
@@ -186,49 +186,49 @@
font-variant-numeric: tabular-nums;
&.pos-first {
color: #16a34a;
color: var(--sg-success);
}
&.pos-middle {
color: #d97706;
color: var(--sg-warning);
}
&.pos-last {
color: #2563eb;
color: var(--sg-primary);
}
&.rel-count {
color: #7c3aed;
color: var(--sg-blue-highlight);
}
&.rel-avg {
color: #0891b2;
color: var(--sg-blue-highlight);
}
&.cit-total {
color: #b91c1c;
color: var(--sg-error);
}
&.cit-avg {
color: #ea580c;
color: var(--sg-warning);
}
&.fwci-count {
color: #4d7c0f;
color: var(--sg-success);
}
&.fwci-avg {
color: #0d9488;
color: var(--sg-success);
}
&.year-from {
color: #6d28d9;
color: var(--sg-primary);
}
&.year-to {
color: #be185d;
color: var(--sg-primary);
}
&.ind-count {
color: #92400e;
color: var(--sg-warning);
}
&.ind-share {
color: #1d4ed8;
color: var(--sg-blue-highlight);
}
}
.pos-sep {
margin: 0 4px;
color: var(--sg-text-soft, #b6bed6);
color: var(--sg-text-soft);
font-weight: 400;
}
@@ -244,13 +244,13 @@
margin: 18px 0 0;
font-size: 14px;
font-weight: 700;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
}
.chart-hint {
margin: 2px 0 8px;
font-size: 12px;
color: var(--sg-text-muted, #64708f);
color: var(--sg-text-muted);
}
.profile-chart {
@@ -6,6 +6,8 @@ import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import {
AuthorOrientationProfile,
AuthorOrientationProfilesRequest,
AuthorStaticStats,
AuthorTopicProfile,
AuthorTopicStats,
@@ -13,19 +15,17 @@ import {
RankingService,
SelectedAuthorsRequest,
} from '../../api';
import {
AuthorResearchProfileComponent,
ResearchProfileAuthor,
} from './author-research-profile/author-research-profile.component';
import { ChartThemeService } from '../../shared/services/chart-theme.service';
import {
AUTHOR_COLORS,
OTHER_COLOR,
SUBFIELD_COLORS,
} from './compare-authors-colors';
const AUTHOR_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd'];
const SUBFIELD_COLORS = [
'#2563eb',
'#16a34a',
'#d97706',
'#7c3aed',
'#0891b2',
'#db2777',
'#65a30d',
'#b45309',
];
const OTHER_COLOR = '#9ca3af';
const SUBFIELD_LIMIT = 5;
interface AuthorSummary {
@@ -74,7 +74,6 @@ interface GroupSegment {
label: string;
colorClass: string;
decimals: boolean;
// render the value as-is, without the number pipe (e.g. years)
plain: boolean;
}
@@ -110,13 +109,20 @@ interface SegmentDef {
@Component({
selector: 'app-compare-authors',
standalone: true,
imports: [DecimalPipe, NgTemplateOutlet, MatIconModule, NgxEchartsDirective],
imports: [
DecimalPipe,
NgTemplateOutlet,
MatIconModule,
NgxEchartsDirective,
AuthorResearchProfileComponent,
],
templateUrl: './compare-authors.component.html',
styleUrl: './compare-authors.component.scss',
})
export class CompareAuthorsComponent implements OnInit {
private readonly route = inject(ActivatedRoute);
private readonly rankingService = inject(RankingService);
private readonly chartTheme = inject(ChartThemeService);
readonly keywords = signal<string[]>([]);
readonly timespan = signal<{ from: number; to: number } | null>(null);
@@ -129,13 +135,16 @@ export class CompareAuthorsComponent implements OnInit {
readonly staticStats = signal<AuthorStaticStats[]>([]);
// section 3: topic profile over ALL works of each author
readonly profile = signal<AuthorTopicProfile[]>([]);
readonly orientationProfiles = signal<AuthorOrientationProfile[]>([]);
readonly profileLoading = signal(false);
readonly orientationProfilesLoading = signal(false);
readonly loading = signal(false);
// maps both sections onto one row per author, in the requested order
readonly summary = computed<AuthorSummary[]>(() => {
const topicById = new Map(this.topic().map((a) => [a.author_id, a]));
const staticById = new Map(this.staticStats().map((a) => [a.author_id, a]));
const authorPalette = this.chartTheme.colors().authorColors;
return this.authorIds().map((id, index) => {
const t = topicById.get(id);
@@ -146,7 +155,7 @@ export class CompareAuthorsComponent implements OnInit {
const authorSummary: AuthorSummary = {
authorId: id,
name,
color: AUTHOR_COLORS[index % AUTHOR_COLORS.length],
color: authorPalette[index % authorPalette.length],
totalWorks: t ? t.works_total : null,
corresponding: t ? t.corresponding_count : null,
avgPercentile: t ? t.avg_percentile : null,
@@ -357,6 +366,14 @@ export class CompareAuthorsComponent implements OnInit {
.filter((p): p is AuthorTopicProfile => p !== undefined);
});
readonly researchProfileAuthors = computed<ResearchProfileAuthor[]>(() => {
return this.summary().map((author) => ({
authorId: author.authorId,
name: author.name,
color: author.color,
}));
});
// colours the author names on the chart axes like the legend chips
private authorAxisLabel(profiles: AuthorTopicProfile[]) {
const rich: Record<string, { color: string; fontWeight: number }> = {};
@@ -454,7 +471,11 @@ export class CompareAuthorsComponent implements OnInit {
return `<b>${params[0]?.name ?? ''}</b><br/>${lines.join('<br/>')}`;
},
},
legend: { type: 'scroll', top: 0 },
legend: {
type: 'scroll',
top: 0,
textStyle: { color: this.chartTheme.colors().text },
},
grid: { left: 16, right: 24, top: 56, bottom: 8, containLabel: true },
xAxis: {
type: 'value',
@@ -491,7 +512,7 @@ export class CompareAuthorsComponent implements OnInit {
return `<b>${params[0]?.name ?? ''}</b><br/>${lines.join('<br/>')}`;
},
},
legend: { top: 0 },
legend: { top: 0, textStyle: { color: this.chartTheme.colors().text } },
grid: { left: 16, right: 40, top: 32, bottom: 8, containLabel: true },
xAxis: {
type: 'value',
@@ -538,7 +559,7 @@ export class CompareAuthorsComponent implements OnInit {
return {
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: { top: 0 },
legend: { top: 0, textStyle: { color: this.chartTheme.colors().text } },
grid: { left: 16, right: 40, top: 32, bottom: 8, containLabel: true },
xAxis: { type: 'value' },
yAxis: {
@@ -551,21 +572,21 @@ export class CompareAuthorsComponent implements OnInit {
{
name: 'Themen',
type: 'bar',
itemStyle: { color: '#0891b2' },
itemStyle: { color: this.chartTheme.colors().blueHighlight },
label: { show: true, position: 'right' },
data: profiles.map((p) => p.distinct_topics),
},
{
name: 'Subfields',
type: 'bar',
itemStyle: { color: '#d97706' },
itemStyle: { color: this.chartTheme.colors().warning },
label: { show: true, position: 'right' },
data: profiles.map((p) => p.distinct_subfields),
},
{
name: 'Fields',
type: 'bar',
itemStyle: { color: '#16a34a' },
itemStyle: { color: this.chartTheme.colors().success },
label: { show: true, position: 'right' },
data: profiles.map((p) => p.distinct_fields),
},
@@ -657,6 +678,11 @@ export class CompareAuthorsComponent implements OnInit {
publication_types: publication_types,
timespan: timespan,
};
const orientationRequest: AuthorOrientationProfilesRequest = {
author_ids: fullIds,
publication_types: publication_types,
timespan: timespan,
};
// section 1: topic-filtered works stats
this.loading.set(true);
@@ -698,6 +724,23 @@ export class CompareAuthorsComponent implements OnInit {
this.staticStats.set([]);
},
});
if (fullIds.length >= 2) {
this.orientationProfilesLoading.set(true);
this.rankingService
.orientationProfilesApiRankOrientationProfilesPost(orientationRequest)
.subscribe({
next: (results) => {
this.orientationProfiles.set(results);
this.orientationProfilesLoading.set(false);
},
error: (error) => {
console.error(error);
this.orientationProfiles.set([]);
this.orientationProfilesLoading.set(false);
},
});
}
}
private parseList(raw: string): string[] {
@@ -44,6 +44,14 @@ export interface BmbfProjectStatusStatistics {
completed: number;
}
export interface DfgProjectStatusStatistics {
institution_id: string;
organization_name: string;
ongoing: number;
upcoming: number;
completed: number;
}
export interface DfgProjectTopic {
id: string;
name: string;
@@ -149,6 +157,15 @@ export class DashboardStatisticsService {
);
}
getDfgProjectStatuses(
period: DashboardPeriodBounds = {},
): Observable<DfgProjectStatusStatistics> {
return this.httpClient.get<DfgProjectStatusStatistics>(
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/projects/dfg/status`,
{ params: this.periodParams(period) },
);
}
getBmbfProjectCount(
period: DashboardPeriodBounds = {},
): Observable<DashboardStatisticValue> {
@@ -165,20 +165,22 @@
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading ||
euProjectStatusesError ||
bmbfProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses)
dfgProjectStatusesError ||
(euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses)
) {
<section class="topic-heatmap-section">
<header class="topic-heatmap-header">
<div>
<h2>Projektstatus nach Fördergeber</h2>
<p>
Laufende, kommende und abgeschlossene EU- und Bund-Projekte Ihrer
Organisation.
Laufende, kommende und abgeschlossene EU-, Bund- und DFG-Projekte
Ihrer Organisation.
</p>
</div>
@if (euProjectStatuses && bmbfProjectStatuses) {
@if (euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses) {
<div class="project-status-summary">
<span>
EU:
@@ -196,11 +198,23 @@
bmbfProjectStatuses.completed | number
}}
</span>
<span>
DFG:
{{
dfgProjectStatuses.ongoing +
dfgProjectStatuses.upcoming +
dfgProjectStatuses.completed | number
}}
</span>
</div>
}
</header>
@if (euProjectStatusesLoading || bmbfProjectStatusesLoading) {
@if (
euProjectStatusesLoading ||
bmbfProjectStatusesLoading ||
dfgProjectStatusesLoading
) {
<div class="project-status-loading" role="status" aria-live="polite">
<app-loading
text="Projektstatus wird geladen …"
@@ -208,14 +222,22 @@
size="64"
diameter="64"></app-loading>
</div>
} @else if (euProjectStatusesError || bmbfProjectStatusesError) {
} @else if (
euProjectStatusesError ||
bmbfProjectStatusesError ||
dfgProjectStatusesError
) {
<p class="statistics-error">
Der Status der EU- und Bund-Projekte konnte nicht geladen werden.
Der Status der EU-, Bund- und DFG-Projekte konnte nicht geladen
werden.
</p>
} @else if (euProjectStatuses && bmbfProjectStatuses) {
} @else if (
euProjectStatuses && bmbfProjectStatuses && dfgProjectStatuses
) {
<app-eu-project-status-chart
[statuses]="euProjectStatuses"
[bmbfStatuses]="bmbfProjectStatuses"></app-eu-project-status-chart>
[bmbfStatuses]="bmbfProjectStatuses"
[dfgStatuses]="dfgProjectStatuses"></app-eu-project-status-chart>
}
</section>
}
@@ -1,8 +1,6 @@
// src/app/modules/university-ranking/dashboard.component.scss
.dashboard-wrapper {
padding: 2rem;
font-family: 'Inter', sans-serif;
color: #333;
color: var(--sg-text);
.dashboard-period-filter {
display: flex;
@@ -16,22 +14,22 @@
display: inline-flex;
overflow: hidden;
flex: 0 0 auto;
border: 1px solid #cbd5e1;
border: 1px solid var(--sg-border);
border-radius: 6px;
background: #fff;
background: var(--sg-surface);
button {
padding: 0.55rem 0.8rem;
border: 0;
border-right: 1px solid #cbd5e1;
border-right: 1px solid var(--sg-border);
background: transparent;
color: #334155;
color: var(--sg-text);
cursor: pointer;
font: inherit;
&.active {
background: #1d4ed8;
color: #fff;
background: var(--sg-blue-highlight);
color: var(--sg-card-bg);
}
}
@@ -57,10 +55,10 @@
gap: 1rem;
min-height: 120px;
padding: 1.25rem;
border: 1px solid #e2e8f0;
border: 1px solid var(--sg-border);
border-radius: 12px;
background: #fff;
box-shadow: 0 4px 14px rgb(15 23 42 / 6%);
background: var(--sg-card-bg);
box-shadow: var(--sg-shadow-sm);
color: inherit;
text-decoration: none;
transition:
@@ -69,13 +67,13 @@
transform 160ms ease;
&:hover {
border-color: #93c5fd;
box-shadow: 0 8px 24px rgb(15 23 42 / 12%);
border-color: var(--sg-card-hover-border);
box-shadow: var(--sg-shadow-md);
transform: translateY(-2px);
}
&:focus-visible {
outline: 3px solid #93c5fd;
outline: 3px solid var(--sg-card-hover-border);
outline-offset: 3px;
}
@@ -86,13 +84,13 @@
span,
small {
display: block;
color: #64748b;
color: var(--sg-text-muted);
}
strong {
display: block;
margin: 0.2rem 0;
color: #0f172a;
color: var(--sg-text);
font-size: clamp(1.7rem, 3vw, 2.3rem);
line-height: 1.1;
}
@@ -105,38 +103,38 @@
height: 52px;
place-items: center;
border-radius: 12px;
background: #dbeafe;
color: #1d4ed8;
background: var(--sg-primary-soft);
color: var(--sg-blue-highlight);
&--persons {
background: #dcfce7;
color: #15803d;
background: var(--sg-success-soft);
color: var(--sg-success);
}
&--patents {
background: #fee2e2;
color: #b91c1c;
background: var(--sg-error-soft);
color: var(--sg-error);
}
&--eu-projects {
background: #e0f2fe;
color: #0369a1;
background: var(--sg-primary-soft);
color: var(--sg-blue-highlight);
}
&--bund-projects {
background: #fef3c7;
color: #b45309;
background: var(--sg-warning-soft);
color: var(--sg-warning);
}
&--dfg-projects {
background: #f3e8ff;
color: #7e22ce;
background: var(--sg-warning-soft);
color: var(--sg-warning);
}
}
.statistics-error {
margin: -1rem 0 2rem;
color: #b91c1c;
color: var(--sg-error);
}
.top-authors-section {
@@ -146,9 +144,9 @@
.topic-heatmap-section {
margin-bottom: 2.5rem;
padding: 1.25rem;
border: 1px solid #e2e8f0;
border: 1px solid var(--sg-border);
border-radius: 12px;
background: #fff;
background: var(--sg-card-bg);
}
.topic-heatmap-header {
@@ -165,7 +163,7 @@
p {
margin-top: 0.35rem;
color: #64748b;
color: var(--sg-text-muted);
}
@media (max-width: 820px) {
@@ -194,8 +192,8 @@
span {
padding: 0.35rem 0.65rem;
border-radius: 999px;
background: #f1f5f9;
color: #475569;
background: var(--sg-surface-muted);
color: var(--sg-text-muted);
font-size: 0.9rem;
font-weight: 600;
}
@@ -203,7 +201,7 @@
.dfg-topic-summary {
flex: 0 0 auto;
color: #475569;
color: var(--sg-text-muted);
font-weight: 600;
}
@@ -221,7 +219,7 @@
p {
margin-top: 0.35rem;
color: #64748b;
color: var(--sg-text-muted);
}
@media (max-width: 720px) {
@@ -246,16 +244,16 @@
.top-authors-chart {
padding: 1.25rem;
border: 1px solid #e2e8f0;
border: 1px solid var(--sg-border);
border-radius: 12px;
background: #fff;
background: var(--sg-card-bg);
h3 {
display: flex;
align-items: center;
gap: 0.5rem;
margin: 0 0 1rem;
color: #0f172a;
color: var(--sg-text);
}
}
@@ -268,7 +266,7 @@
.author-rank {
flex: 0 0 1.4rem;
color: #64748b;
color: var(--sg-text-muted);
font-size: 0.8rem;
text-align: center;
}
@@ -287,7 +285,7 @@
.author-name {
overflow: hidden;
color: #1d4ed8;
color: var(--sg-blue-highlight);
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
@@ -306,7 +304,7 @@
&:focus-visible {
border-radius: 2px;
outline: 2px solid #93c5fd;
outline: 2px solid var(--sg-card-hover-border);
outline-offset: 2px;
}
}
@@ -315,20 +313,20 @@
overflow: hidden;
height: 7px;
border-radius: 999px;
background: #e2e8f0;
background: var(--sg-border);
}
.author-bar-fill {
display: block;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #2563eb, #60a5fa);
background: var(--sg-blue-highlight);
transition: width 220ms ease;
}
.empty-chart {
margin: 2rem 0;
color: #64748b;
color: var(--sg-text-muted);
text-align: center;
}
}
@@ -23,6 +23,7 @@ import {
DashboardStatisticValue,
DashboardStatistics,
DashboardStatisticsService,
DfgProjectStatusStatistics,
DfgProjectTopics,
EuProjectStatusStatistics,
TopAuthor,
@@ -101,6 +102,9 @@ export class DashboardComponent implements OnInit {
bmbfProjectStatuses?: BmbfProjectStatusStatistics;
bmbfProjectStatusesLoading = false;
bmbfProjectStatusesError = false;
dfgProjectStatuses?: DfgProjectStatusStatistics;
dfgProjectStatusesLoading = false;
dfgProjectStatusesError = false;
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
@@ -125,6 +129,7 @@ export class DashboardComponent implements OnInit {
this.loadDfgProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
}
private loadStatistics(): void {
@@ -281,12 +286,17 @@ export class DashboardComponent implements OnInit {
}
onTopicTreemapTopicSelect(topic: TopicTreemapTopicSelect): void {
const period = this.selectedPeriodBounds();
this.dialog.open<TopicWordCloudDialogComponent, TopicWordCloudDialogData>(
TopicWordCloudDialogComponent,
{
width: '85vw',
maxWidth: '92vw',
data: topic,
data: {
...topic,
fromYear: period.fromYear,
toYear: period.toYear,
},
},
);
}
@@ -368,6 +378,7 @@ export class DashboardComponent implements OnInit {
this.loadDfgProjectTopics();
this.loadEuProjectStatuses();
this.loadBmbfProjectStatuses();
this.loadDfgProjectStatuses();
}
private loadStatistic(
@@ -479,6 +490,22 @@ export class DashboardComponent implements OnInit {
});
}
private loadDfgProjectStatuses(): void {
this.dfgProjectStatusesLoading = true;
this.dfgProjectStatusesError = false;
this.statisticsService
.getDfgProjectStatuses(this.selectedPeriodBounds())
.pipe(finalize(() => (this.dfgProjectStatusesLoading = false)))
.subscribe({
next: (statuses) => {
this.dfgProjectStatuses = statuses;
},
error: () => {
this.dfgProjectStatusesError = true;
},
});
}
private loadTopicTreemap(): void {
if (this.dashboardFromYear > this.dashboardToYear) {
this.topicTreemapLoading = false;
@@ -8,5 +8,5 @@
min-height: 260px;
margin: 0;
place-items: center;
color: #64748b;
color: var(--sg-text-muted);
}
@@ -1,6 +1,7 @@
import { Component, Input, OnChanges } from '@angular/core';
import { Component, Input, OnChanges, effect, inject } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { ChartThemeService } from '../../../shared/services/chart-theme.service';
import { DfgProjectTopic } from '../dashboard-statistics.service';
@@ -13,9 +14,22 @@ import { DfgProjectTopic } from '../dashboard-statistics.service';
export class DfgTopicDonutComponent implements OnChanges {
@Input() topics: DfgProjectTopic[] = [];
private chartTheme = inject(ChartThemeService);
options: EChartsOption = {};
constructor() {
effect(() => {
this.buildOptions();
});
}
ngOnChanges(): void {
this.buildOptions();
}
private buildOptions(): void {
const theme = this.chartTheme.colors();
this.options = {
color: [
'#7255d9',
@@ -29,9 +43,13 @@ export class DfgTopicDonutComponent implements OnChanges {
'#db2777',
'#9333ea',
],
backgroundColor: theme.backgroundColor,
tooltip: {
trigger: 'item',
confine: true,
backgroundColor: theme.tooltipBg,
borderColor: theme.tooltipBorder,
textStyle: { color: theme.tooltipTextColor },
formatter: (params: any) =>
`<strong>${this.escapeHtml(String(params.name ?? ''))}</strong><br>${Number(params.value ?? 0).toLocaleString('de-DE')} DFG-Projekte`,
},
@@ -41,7 +59,7 @@ export class DfgTopicDonutComponent implements OnChanges {
top: 'middle',
right: 12,
width: '38%',
textStyle: { color: '#334155' },
textStyle: { color: theme.textColor },
formatter: (name: string) => this.truncate(name, 42),
},
graphic: [
@@ -52,7 +70,7 @@ export class DfgTopicDonutComponent implements OnChanges {
style: {
text: `${this.topics.length}\nTopics`,
align: 'center',
fill: '#0f172a',
fill: theme.textColor,
fontSize: 18,
fontWeight: 700,
lineHeight: 25,
@@ -68,7 +86,7 @@ export class DfgTopicDonutComponent implements OnChanges {
avoidLabelOverlap: true,
minAngle: 3,
itemStyle: {
borderColor: '#ffffff',
borderColor: theme.cardBg,
borderWidth: 3,
borderRadius: 5,
},
@@ -1,9 +1,11 @@
import { Component, Input, OnChanges } from '@angular/core';
import { Component, Input, OnChanges, effect, inject } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { ChartThemeService } from '../../../shared/services/chart-theme.service';
import {
BmbfProjectStatusStatistics,
DfgProjectStatusStatistics,
EuProjectStatusStatistics,
} from '../dashboard-statistics.service';
@@ -16,19 +18,42 @@ import {
export class EuProjectStatusChartComponent implements OnChanges {
@Input({ required: true }) statuses!: EuProjectStatusStatistics;
@Input({ required: true }) bmbfStatuses!: BmbfProjectStatusStatistics;
@Input({ required: true }) dfgStatuses!: DfgProjectStatusStatistics;
private chartTheme = inject(ChartThemeService);
options: EChartsOption = {};
constructor() {
effect(() => {
// Re-build options when theme colors signal changes
this.buildOptions();
});
}
ngOnChanges(): void {
this.buildOptions();
}
private buildOptions(): void {
const theme = this.chartTheme.colors();
const values = [
{
name: 'Laufend',
data: [this.statuses?.ongoing ?? 0, this.bmbfStatuses?.ongoing ?? 0],
data: [
this.statuses?.ongoing ?? 0,
this.bmbfStatuses?.ongoing ?? 0,
this.dfgStatuses?.ongoing ?? 0,
],
color: '#2563eb',
},
{
name: 'Kommend',
data: [this.statuses?.upcoming ?? 0, this.bmbfStatuses?.upcoming ?? 0],
data: [
this.statuses?.upcoming ?? 0,
this.bmbfStatuses?.upcoming ?? 0,
this.dfgStatuses?.upcoming ?? 0,
],
color: '#f59e0b',
},
{
@@ -36,18 +61,23 @@ export class EuProjectStatusChartComponent implements OnChanges {
data: [
this.statuses?.completed ?? 0,
this.bmbfStatuses?.completed ?? 0,
this.dfgStatuses?.completed ?? 0,
],
color: '#64748b',
color: theme.mutedTextColor,
},
];
this.options = {
color: values.map((item) => item.color),
animationDuration: 500,
backgroundColor: theme.backgroundColor,
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
confine: true,
backgroundColor: theme.tooltipBg,
borderColor: theme.tooltipBorder,
textStyle: { color: theme.tooltipTextColor },
valueFormatter: (value) =>
`${Number(value ?? 0).toLocaleString('de-DE')} Projekte`,
},
@@ -55,7 +85,7 @@ export class EuProjectStatusChartComponent implements OnChanges {
top: 0,
left: 'center',
data: values.map((item) => item.name),
textStyle: { color: '#334155' },
textStyle: { color: theme.textColor },
},
grid: { top: 56, right: 24, bottom: 30, left: 24, containLabel: true },
xAxis: {
@@ -64,15 +94,16 @@ export class EuProjectStatusChartComponent implements OnChanges {
name: 'Anzahl Projekte',
nameLocation: 'middle',
nameGap: 28,
axisLabel: { color: '#64748b' },
splitLine: { lineStyle: { color: '#e2e8f0' } },
axisLabel: { color: theme.mutedTextColor },
nameTextStyle: { color: theme.mutedTextColor },
splitLine: { lineStyle: { color: theme.gridLineColor } },
},
yAxis: {
type: 'category',
data: ['EU-Projekte', 'Bund-Projekte'],
data: ['EU-Projekte', 'Bund-Projekte', 'DFG-Projekte'],
axisTick: { show: false },
axisLine: { show: false },
axisLabel: { color: '#334155', fontWeight: 600 },
axisLabel: { color: theme.textColor, fontWeight: 600 },
},
series: values.map((item, index) => ({
name: item.name,
@@ -85,7 +116,7 @@ export class EuProjectStatusChartComponent implements OnChanges {
position: 'inside',
formatter: (params) =>
Number(params.value ?? 0) > 0 ? String(params.value) : '',
color: '#ffffff',
color: theme.labelColor,
fontWeight: 700,
},
itemStyle: {
@@ -91,16 +91,100 @@
<span>Die Keywords konnten nicht geladen werden.</span>
</div>
} @else if (words.length) {
<div class="keyword-toolbar" aria-label="Ausgewählte Keywords">
<div class="keyword-toolbar-label">
<mat-icon aria-hidden="true">tune</mat-icon>
<span>
<strong>Keyword-Auswahl</strong>
<small
>Klicken Sie auf Begriffe in der Wordcloud, um sie
auszuwählen.</small
>
</span>
</div>
<div class="keyword-selection" aria-live="polite">
@for (word of selectedWords(); track word.id) {
<button
type="button"
class="keyword-chip"
[attr.aria-label]="word.name + ' aus Auswahl entfernen'"
(click)="toggleWord(word)">
{{ word.name }}
<mat-icon aria-hidden="true">close</mat-icon>
</button>
} @empty {
<span class="keyword-selection-empty">Noch nichts ausgewählt</span>
}
</div>
<div class="keyword-toolbar-actions">
@if (selectedWordIds.size) {
<button
mat-button
type="button"
class="keyword-clear"
(click)="clearSelection()">
Auswahl löschen
</button>
}
<a
mat-stroked-button
class="keyword-search keyword-search--secondary"
routerLink="/keywords"
[queryParams]="{
manual: selectedWordsQuery(),
selected: selectedWordsQuery(),
}"
[class.keyword-search--disabled]="!selectedWordIds.size"
[attr.aria-disabled]="!selectedWordIds.size"
[attr.tabindex]="selectedWordIds.size ? 0 : -1"
(click)="
!selectedWordIds.size
? $event.preventDefault()
: closeForSearchNavigation()
">
<mat-icon aria-hidden="true">manage_search</mat-icon>
Suche in Keywords
</a>
<a
mat-flat-button
class="keyword-search"
routerLink="/topics"
[queryParams]="{
query: selectedWordNames(),
page: 0,
sortBy: 'works_count',
sortDirection: 'desc',
}"
[class.keyword-search--disabled]="!selectedWordIds.size"
[attr.aria-disabled]="!selectedWordIds.size"
[attr.tabindex]="selectedWordIds.size ? 0 : -1"
(click)="
!selectedWordIds.size
? $event.preventDefault()
: closeForSearchNavigation()
">
<mat-icon aria-hidden="true">search</mat-icon>
Suche in Themen
</a>
</div>
</div>
<div class="word-cloud-chart" aria-label="Wordcloud verwandter Themen">
@for (word of words; track word.id) {
<span
<button
type="button"
class="word-cloud-word"
[class.word-cloud-word--selected]="isWordSelected(word)"
[attr.aria-pressed]="isWordSelected(word)"
[style.color]="word.color"
[style.fontSize.px]="word.fontSize"
[style.fontWeight]="word.fontWeight"
[title]="word.name + ': ' + word.count + ' Publikationen'">
[title]="word.name + ': ' + word.count + ' Publikationen'"
(click)="toggleWord(word)">
{{ word.name }}
</span>
</button>
}
</div>
} @else {
@@ -4,12 +4,12 @@
justify-content: space-between;
gap: 24px;
padding: 24px 28px 20px;
border-bottom: 1px solid var(--sg-border, #dde5f2);
background: linear-gradient(135deg, #ffffff 52%, #f6f0ff 100%);
border-bottom: 1px solid var(--sg-border);
background: var(--sg-card-bg);
h2 {
margin: 1px 0 3px;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
font-family: 'Montserrat', sans-serif;
font-size: 1.375rem;
font-weight: 700;
@@ -18,7 +18,7 @@
p {
margin: 0;
color: var(--sg-text-muted, #64708f);
color: var(--sg-text-muted);
font-size: 0.8125rem;
font-weight: 400;
}
@@ -31,7 +31,7 @@
.dialog-eyebrow {
display: block;
color: #7255d9;
color: var(--sg-primary);
font-size: 0.6875rem;
font-weight: 700;
letter-spacing: 0.08em;
@@ -41,18 +41,18 @@
.dialog-close {
flex: 0 0 auto;
color: var(--sg-text-muted, #64708f);
color: var(--sg-text-muted);
&:hover {
background: #f1f3f7;
color: var(--sg-text, #101a3d);
background: var(--sg-surface-soft);
color: var(--sg-text);
}
}
mat-dialog-content {
min-height: 410px;
padding: 20px 28px 28px !important;
background: #ffffff;
background: var(--sg-card-bg);
}
.topic-context-card {
@@ -62,9 +62,9 @@ mat-dialog-content {
gap: 12px;
margin-bottom: 18px;
padding: 12px;
border: 1px solid var(--sg-border, #dde5f2);
border: 1px solid var(--sg-border);
border-radius: 12px;
background: var(--sg-surface-muted, #f7f9ff);
background: var(--sg-surface-muted);
}
.topic-context-item {
@@ -91,21 +91,21 @@ mat-dialog-content {
}
.topic-context-icon--field {
border: 1px solid #bdd4ff;
background: #f0f6ff;
color: #0b63ce;
border: 1px solid var(--sg-blue-highlight);
background: var(--sg-primary-soft);
color: var(--sg-blue-highlight);
}
.topic-context-icon--subfield {
border: 1px solid #bdebcf;
background: #effaf3;
color: #24834f;
border: 1px solid var(--sg-success);
background: var(--sg-success-soft);
color: var(--sg-success);
}
.topic-context-icon--topic {
border: 1px solid #d8cafe;
background: #f6f0ff;
color: #7255d9;
border: 1px solid var(--sg-primary);
background: var(--sg-primary-soft);
color: var(--sg-primary);
}
.topic-context-copy {
@@ -116,7 +116,7 @@ mat-dialog-content {
strong {
overflow: hidden;
color: #334155;
color: var(--sg-text);
font-size: 0.8125rem;
font-weight: 600;
line-height: 1.35;
@@ -126,11 +126,11 @@ mat-dialog-content {
}
.topic-context-item--topic strong {
color: #7255d9;
color: var(--sg-primary);
}
.topic-context-label {
color: var(--sg-text-soft, #8a95b3);
color: var(--sg-text-soft);
font-size: 0.625rem;
font-weight: 700;
letter-spacing: 0.07em;
@@ -141,15 +141,15 @@ mat-dialog-content {
.topic-context-arrow {
width: 18px;
height: 18px;
color: #a8b2c8;
color: var(--sg-text-soft);
font-size: 18px;
}
.word-cloud-panel {
overflow: hidden;
border: 1px solid var(--sg-border, #dde5f2);
border: 1px solid var(--sg-border);
border-radius: 16px;
background: #ffffff;
background: var(--sg-card-bg);
box-shadow: var(--sg-shadow-sm);
}
@@ -159,11 +159,11 @@ mat-dialog-content {
justify-content: space-between;
gap: 16px;
padding: 14px 18px;
border-bottom: 1px solid #e8edf5;
border-bottom: 1px solid var(--sg-border);
h3 {
margin: 0 0 2px;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
font-family: 'Montserrat', sans-serif;
font-size: 0.9375rem;
font-weight: 700;
@@ -171,7 +171,7 @@ mat-dialog-content {
p {
margin: 0;
color: var(--sg-text-muted, #64708f);
color: var(--sg-text-muted);
font-size: 0.75rem;
}
}
@@ -179,14 +179,121 @@ mat-dialog-content {
.word-count {
flex: 0 0 auto;
padding: 5px 9px;
border: 1px solid #d8cafe;
border: 1px solid var(--sg-primary);
border-radius: 999px;
background: #f6f0ff;
color: #7255d9;
background: var(--sg-primary-soft);
color: var(--sg-primary);
font-size: 0.6875rem;
font-weight: 700;
}
.keyword-toolbar {
display: grid;
grid-template-columns: auto minmax(160px, 1fr) auto;
align-items: center;
gap: 14px;
padding: 10px 14px;
border-bottom: 1px solid var(--sg-border);
background: var(--sg-surface-muted);
}
.keyword-toolbar-label {
display: flex;
align-items: center;
gap: 8px;
color: var(--sg-text);
> mat-icon {
width: 19px;
height: 19px;
color: var(--sg-primary);
font-size: 19px;
}
> span {
display: flex;
flex-direction: column;
gap: 1px;
}
strong {
font-size: 0.75rem;
}
small {
color: var(--sg-text-muted);
font-size: 0.6875rem;
}
}
.keyword-selection {
display: flex;
min-width: 0;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.keyword-chip {
display: inline-flex;
min-height: 28px;
align-items: center;
gap: 4px;
padding: 4px 7px 4px 9px;
border: 1px solid var(--sg-primary);
border-radius: 999px;
background: var(--sg-primary-soft);
color: var(--sg-primary);
cursor: pointer;
font: inherit;
font-size: 0.6875rem;
font-weight: 600;
mat-icon {
width: 14px;
height: 14px;
font-size: 14px;
}
&:hover {
border-color: var(--sg-primary);
background: var(--sg-surface-soft);
}
}
.keyword-selection-empty {
color: var(--sg-text-soft);
font-size: 0.75rem;
font-style: italic;
}
.keyword-clear {
white-space: nowrap;
}
.keyword-toolbar-actions {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 4px;
white-space: nowrap;
}
.keyword-search {
mat-icon {
margin-right: 5px;
}
}
.keyword-search--secondary {
background: var(--sg-card-bg);
}
.keyword-search--disabled {
pointer-events: none;
opacity: 0.45;
}
.word-cloud-chart {
display: flex;
min-height: 280px;
@@ -196,24 +303,17 @@ mat-dialog-content {
justify-content: center;
gap: 14px 20px;
padding: 30px 34px;
background:
radial-gradient(
circle at 15% 20%,
rgba(114, 85, 217, 0.06),
transparent 28%
),
radial-gradient(
circle at 85% 75%,
rgba(11, 99, 206, 0.05),
transparent 30%
),
#ffffff;
background: var(--sg-card-bg);
}
.word-cloud-word {
appearance: none;
padding: 3px 5px;
border: 1px solid transparent;
border-radius: 6px;
cursor: help;
background: transparent;
cursor: pointer;
font-family: inherit;
line-height: 1.1;
text-align: center;
transition:
@@ -221,9 +321,21 @@ mat-dialog-content {
background-color 150ms ease;
&:hover {
background: rgba(241, 243, 247, 0.9);
background: var(--sg-surface-soft);
transform: translateY(-2px);
}
&:focus-visible {
outline: 3px solid var(--sg-primary);
outline-offset: 2px;
}
}
.word-cloud-word--selected {
border-color: currentColor;
background: var(--sg-card-bg);
box-shadow: var(--sg-shadow-md);
transform: translateY(-2px);
}
.word-cloud-state {
@@ -234,12 +346,12 @@ mat-dialog-content {
flex-direction: column;
gap: 6px;
padding: 24px;
color: var(--sg-text-muted, #64708f);
color: var(--sg-text-muted);
text-align: center;
strong {
margin-top: 4px;
color: var(--sg-text, #101a3d);
color: var(--sg-text);
font-size: 0.9375rem;
}
@@ -254,24 +366,24 @@ mat-dialog-content {
height: 46px;
place-items: center;
border-radius: 50%;
background: #f1f3f7;
color: #64708f;
background: var(--sg-surface-soft);
color: var(--sg-text-muted);
}
.state-icon--loading {
background: #f6f0ff;
color: #7255d9;
background: var(--sg-primary-soft);
color: var(--sg-primary);
animation: state-pulse 1.4s ease-in-out infinite;
}
.word-cloud-state--error .state-icon {
background: #fff1f5;
color: #d12f61;
background: var(--sg-error-soft);
color: var(--sg-error);
}
@keyframes state-pulse {
50% {
box-shadow: 0 0 0 8px rgba(114, 85, 217, 0.08);
box-shadow: 0 0 0 8px var(--sg-primary-soft);
transform: scale(1.04);
}
}
@@ -303,6 +415,20 @@ mat-dialog-content {
gap: 10px 14px;
padding: 24px 18px;
}
.keyword-toolbar {
grid-template-columns: 1fr auto;
}
.keyword-toolbar-actions {
grid-column: 2;
grid-row: 1;
}
.keyword-selection {
grid-column: 1 / -1;
grid-row: 2;
}
}
@media (prefers-reduced-motion: reduce) {
@@ -1,9 +1,14 @@
import { CommonModule } from '@angular/common';
import { Component, DestroyRef, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import {
MAT_DIALOG_DATA,
MatDialogModule,
MatDialogRef,
} from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { RouterLink } from '@angular/router';
import {
DashboardStatisticsService,
@@ -28,30 +33,40 @@ interface DisplayWord extends TopicWordCloudWord {
@Component({
selector: 'app-topic-wordcloud-dialog',
standalone: true,
imports: [CommonModule, MatButtonModule, MatDialogModule, MatIconModule],
imports: [
CommonModule,
MatButtonModule,
MatDialogModule,
MatIconModule,
RouterLink,
],
templateUrl: './topic-wordcloud-dialog.component.html',
styleUrl: './topic-wordcloud-dialog.component.scss',
})
export class TopicWordCloudDialogComponent {
readonly data = inject<TopicWordCloudDialogData>(MAT_DIALOG_DATA);
private readonly dialogRef = inject(
MatDialogRef<TopicWordCloudDialogComponent>,
);
private readonly statisticsService = inject(DashboardStatisticsService);
private readonly destroyRef = inject(DestroyRef);
words: DisplayWord[] = [];
selectedWordIds = new Set<string>();
loading = true;
loadFailed = false;
private readonly colors = [
'#2563eb',
'#059669',
'#d97706',
'#dc2626',
'#7c3aed',
'#0284c7',
'#ea580c',
'#4f46e5',
'#0f766e',
'#be123c',
'var(--sg-blue-highlight)',
'var(--sg-success)',
'var(--sg-warning)',
'var(--sg-error)',
'var(--sg-primary)',
'var(--sg-blue-highlight)',
'var(--sg-warning)',
'var(--sg-primary-strong)',
'var(--sg-success)',
'var(--sg-error)',
];
constructor() {
@@ -74,6 +89,42 @@ export class TopicWordCloudDialogComponent {
});
}
toggleWord(word: DisplayWord): void {
const selected = new Set(this.selectedWordIds);
if (selected.has(word.id)) {
selected.delete(word.id);
} else {
selected.add(word.id);
}
this.selectedWordIds = selected;
}
isWordSelected(word: DisplayWord): boolean {
return this.selectedWordIds.has(word.id);
}
selectedWords(): DisplayWord[] {
return this.words.filter((word) => this.selectedWordIds.has(word.id));
}
selectedWordsQuery(): string {
return this.selectedWordNames().join(', ');
}
selectedWordNames(): string[] {
return this.selectedWords().map((word) => word.name);
}
clearSelection(): void {
this.selectedWordIds = new Set<string>();
}
closeForSearchNavigation(): void {
if (this.selectedWordIds.size) {
this.dialogRef.close();
}
}
private buildWords(words: TopicWordCloudWord[]): DisplayWord[] {
if (!words.length) return [];
const values = words.map((word) => word.count);
@@ -1,6 +1,6 @@
.error-container {
min-height: 90vh;
background-color: none !important;
background-color: transparent !important;
display: flex;
align-items: center;
justify-content: center;
@@ -11,9 +11,7 @@
.error-card {
max-width: 450px;
width: 100%;
box-shadow:
0 4px 6px -1px rgb(0 0 0 / 0.05),
0 2px 4px -2px rgb(0 0 0 / 0.05) !important;
box-shadow: var(--sg-shadow-sm) !important;
}
.error-content {
@@ -33,7 +31,7 @@
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.05em;
color: #94a3b8;
color: var(--sg-text-muted);
text-transform: uppercase;
}
@@ -41,7 +39,7 @@
margin: 0.5rem 0 1rem 0;
font-size: 1.75rem;
font-weight: 700;
color: #1e293b;
color: var(--sg-text);
letter-spacing: -0.025em;
line-height: 1.2;
}
@@ -49,7 +47,7 @@
.error-message {
margin: 0 0 2rem 0;
font-size: 1rem;
color: #475569;
color: var(--sg-text-muted);
line-height: 1.6;
}
@@ -68,17 +66,18 @@
.diagnostics-title {
font-size: 0.75rem !important;
font-weight: 600;
color: #94a3b8;
color: var(--sg-text-muted);
letter-spacing: 0.05em;
}
.diagnostics-code {
margin-top: 0.5rem;
padding: 1rem;
background-color: #0f172a;
background-color: var(--sg-surface-muted);
border: 1px solid var(--sg-border);
border-radius: 8px;
font-size: 0.75rem;
color: #34d399;
color: var(--sg-success);
overflow-x: auto;
font-family: monospace;
text-align: left;
@@ -127,21 +127,12 @@
</tbody>
</table>
@if (hasPagination()) {
<div class="pagination">
<button
[disabled]="selectedPage === 1"
(click)="setPage(selectedPage - 1)">
Zurück
</button>
<span>Seite {{ selectedPage }} von {{ getPageCount() }}</span>
<button
[disabled]="selectedPage === getPageCount()"
(click)="setPage(selectedPage + 1)">
Weiter
</button>
</div>
}
<app-query-param-paginator
[total]="totalPatents"
queryParamPageKey="page"
queryParamSizeKey="size"
[pageSizeOptions]="[10, 20, 50]"
(handlePageChange)="onPatentPageChange($event)" />
</div>
@if (selectedPatent) {
@@ -224,7 +215,7 @@
<span class="patent-detail-action__label"
>Patentdetails anzeigen</span
>
<span class="material-icons" aria-hidden="true">chevron_right</span>
<mat-icon aria-hidden="true">chevron_right</mat-icon>
</button>
<p class="patent-detail-hint">
Abstract, Erfinder, Anmelder und IPC/CPC-Klassifikation
@@ -1,19 +1,19 @@
.message {
padding: 16px;
color: #666;
color: var(--sg-text-muted);
&.message-hint {
padding-top: 0;
font-size: 13px;
color: #888;
color: var(--sg-text-muted);
code {
display: inline-block;
margin-top: 6px;
padding: 4px 8px;
border-radius: 6px;
background: #f5f5f5;
color: #333;
background: var(--sg-surface-soft);
color: var(--sg-text);
font-size: 12px;
}
}
@@ -26,6 +26,11 @@
gap: 16px;
}
app-query-param-paginator {
display: block;
margin-top: 14px;
}
.patents-toolbar-field {
width: fit-content;
min-width: 180px;
@@ -55,36 +60,53 @@
table {
width: 100%;
border-collapse: collapse;
border-collapse: separate;
border-spacing: 0;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
overflow: hidden;
th {
text-align: left;
padding: 10px 12px;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #333;
padding: 12px 16px;
background: var(--sg-surface-muted);
border-bottom: 1px solid var(--sg-border);
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.02em;
color: var(--sg-text-muted);
}
tr {
cursor: pointer;
color: var(--sg-text);
transition: background-color 0.15s ease;
&:hover {
background: #f5f5f5;
&:hover td {
background: var(--sg-surface-soft);
}
&.selected {
background: #f0f0f0;
&.selected td {
background: var(--sg-primary-soft);
}
&:last-child td {
border-bottom: 0;
}
}
td {
padding: 10px 12px;
border-bottom: 1px solid #f0f0f0;
padding: 12px 16px;
border-bottom: 1px solid var(--sg-border);
color: var(--sg-text);
font-size: 13px;
transition: background-color 0.15s ease;
}
.patent-title {
color: #333;
font-weight: 500;
color: var(--sg-text);
font-weight: 600;
max-width: 280px;
white-space: nowrap;
overflow: hidden;
@@ -96,7 +118,7 @@
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: #555;
color: var(--sg-text-muted);
font-size: 13px;
}
@@ -118,26 +140,26 @@
font-weight: 700;
&--institution {
background: #f5f3ff;
color: #6d28d9;
border: 1px solid #ddd6fe;
background: var(--sg-primary-soft);
color: var(--sg-primary);
border: 1px solid var(--sg-border);
}
&--name {
background: #fff7ed;
color: #c2410c;
border: 1px solid #fed7aa;
background: var(--sg-warning-soft);
color: var(--sg-warning);
border: 1px solid var(--sg-border);
}
&--both {
background: #ecfdf5;
color: #047857;
border: 1px solid #a7f3d0;
background: var(--sg-success-soft);
color: var(--sg-success);
border: 1px solid var(--sg-border);
}
}
.author-link {
color: #2563eb;
color: var(--sg-blue-highlight);
text-decoration: none;
font-size: 0.82rem;
@@ -155,30 +177,31 @@
font-weight: 700;
&--epo {
background: #effaf3;
color: #24834f;
border: 1px solid #bdebcf;
background: var(--sg-success-soft);
color: var(--sg-success);
border: 1px solid var(--sg-border);
}
&--uspto {
background: #f0f6ff;
color: #0b63ce;
border: 1px solid #bdd4ff;
background: var(--sg-primary-soft);
color: var(--sg-blue-highlight);
border: 1px solid var(--sg-border);
}
}
.patent-detail {
width: 440px;
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 20px;
background: #fafafa;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
padding: 24px;
background: var(--sg-surface);
box-shadow: var(--sg-shadow-sm);
&.empty {
display: flex;
align-items: center;
justify-content: center;
color: #999;
color: var(--sg-text-muted);
min-height: 200px;
}
@@ -189,14 +212,14 @@
.overview-title {
font-size: 15px;
font-weight: 600;
color: #333;
font-weight: 700;
color: var(--sg-text);
margin: 0;
}
.overview-subtitle {
font-size: 13px;
color: #888;
color: var(--sg-text-muted);
margin: 0;
}
@@ -208,9 +231,9 @@
}
.overview-stat {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
padding: 12px 8px;
text-align: center;
@@ -218,48 +241,48 @@
display: block;
font-size: 22px;
font-weight: 700;
color: #333;
color: var(--sg-text);
}
.overview-label {
display: block;
font-size: 12px;
color: #888;
color: var(--sg-text-muted);
margin-top: 4px;
}
&--total {
.overview-value,
.overview-label {
color: #0b63ce;
color: var(--sg-blue-highlight);
}
}
&--institution {
.overview-value,
.overview-label {
color: #6d28d9;
color: var(--sg-primary);
}
}
&--name {
.overview-value,
.overview-label {
color: #c2410c;
color: var(--sg-warning);
}
}
&--both {
.overview-value,
.overview-label {
color: #047857;
color: var(--sg-success);
}
}
}
.overview-hint {
font-size: 12px;
color: #aaa;
color: var(--sg-text-muted);
margin: 0;
}
}
@@ -267,7 +290,8 @@
h3 {
margin: 0 0 16px 0;
font-size: 16px;
color: #333;
font-weight: 700;
color: var(--sg-text);
line-height: 1.4;
}
}
@@ -278,16 +302,16 @@
gap: 10px;
.stat {
background: white;
border: 1px solid #e0e0e0;
border-radius: 8px;
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
padding: 10px;
text-align: center;
.stat-label {
display: block;
font-size: 11px;
color: #666;
color: var(--sg-text-muted);
margin-bottom: 4px;
text-transform: uppercase;
letter-spacing: 0.03em;
@@ -297,7 +321,7 @@
display: block;
font-size: 15px;
font-weight: bold;
color: #333;
color: var(--sg-text);
}
}
}
@@ -306,7 +330,7 @@
margin: 14px 0 0;
font-size: 13px;
line-height: 1.55;
color: #555;
color: var(--sg-text-muted);
}
.patent-detail-action {
@@ -317,10 +341,10 @@
width: 100%;
margin-top: 16px;
padding: 12px 14px;
border: 1px solid #bdd4ff;
border: 1px solid var(--sg-border);
border-radius: 10px;
background: linear-gradient(180deg, #f8fbff 0%, #eef4ff 100%);
color: #0b63ce;
background: var(--sg-surface-soft);
color: var(--sg-blue-highlight);
font-size: 14px;
font-weight: 600;
cursor: pointer;
@@ -330,9 +354,9 @@
box-shadow 0.15s;
&:hover {
border-color: #0b63ce;
background: #f0f6ff;
box-shadow: 0 2px 8px rgba(11, 99, 206, 0.12);
border-color: var(--sg-blue-highlight);
background: var(--sg-primary-soft);
box-shadow: var(--sg-shadow-sm);
}
.material-icons {
@@ -344,34 +368,34 @@
margin: 8px 0 0;
font-size: 12px;
line-height: 1.4;
color: #888;
color: var(--sg-text-muted);
text-align: center;
}
.patent-full-detail {
flex: 1;
border: 1px solid #e0e0e0;
border-radius: 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
padding: 20px;
background: #fafafa;
background: var(--sg-surface-muted);
h3 {
margin: 0 0 4px 0;
font-size: 16px;
color: #333;
color: var(--sg-text);
line-height: 1.4;
}
h4 {
margin: 16px 0 8px 0;
font-size: 14px;
color: #555;
color: var(--sg-text-muted);
font-weight: 600;
}
p {
font-size: 13px;
color: #444;
color: var(--sg-text);
line-height: 1.6;
margin: 0;
}
@@ -381,20 +405,15 @@
display: inline-flex;
align-items: center;
gap: 0.4rem;
width: auto;
margin-bottom: 1rem;
padding: 0.5rem 0.85rem;
border: 1px solid #d6e3f8;
border: 1px solid var(--sg-border);
border-radius: 999px;
background: #f8fbff;
color: #2563eb;
background: var(--sg-surface-soft);
color: var(--sg-blue-highlight);
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition:
background-color 0.15s ease,
@@ -403,14 +422,14 @@
box-shadow 0.15s ease;
&:hover {
background: #eef5ff;
border-color: #bcd3f7;
color: #1d4ed8;
box-shadow: 0 1px 4px rgba(37, 99, 235, 0.12);
background: var(--sg-primary-soft);
border-color: var(--sg-blue-highlight);
color: var(--sg-blue-highlight);
box-shadow: var(--sg-shadow-sm);
}
&:focus-visible {
outline: 2px solid #93c5fd;
outline: 2px solid var(--sg-blue-highlight);
outline-offset: 2px;
}
}
@@ -418,7 +437,7 @@
.detail-section {
margin-top: 12px;
padding-top: 12px;
border-top: 1px solid #eee;
border-top: 1px solid var(--sg-border);
}
.patent-meta {
@@ -428,10 +447,10 @@
&__list {
margin: 0;
border: 1px solid #e2e8f4;
border: 1px solid var(--sg-border);
border-radius: 12px;
background: linear-gradient(180deg, #fff 0%, #f8faff 100%);
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.04);
background: var(--sg-surface);
box-shadow: var(--sg-shadow-sm);
overflow: hidden;
}
@@ -441,7 +460,7 @@
gap: 12px 16px;
align-items: center;
padding: 11px 16px;
border-top: 1px solid #eef2f8;
border-top: 1px solid var(--sg-border);
&:first-child {
border-top: 0;
@@ -451,7 +470,7 @@
margin: 0;
font-size: 12px;
font-weight: 500;
color: #64748b;
color: var(--sg-text-muted);
line-height: 1.35;
}
@@ -459,7 +478,7 @@
margin: 0;
font-size: 14px;
font-weight: 600;
color: #1e293b;
color: var(--sg-text);
line-height: 1.35;
word-break: break-word;
}
@@ -483,32 +502,32 @@
.tag {
padding: 4px 10px;
border-radius: 999px;
background: #f0f6ff;
border: 1px solid #dbeafe;
color: #1e40af;
background: var(--sg-primary-soft);
border: 1px solid var(--sg-border);
color: var(--sg-blue-highlight);
font-size: 0.8rem;
line-height: 1.3;
}
.classification-section {
&--ipc .classification-card {
background: #f0f6ff;
border-color: #bfdbfe;
background: var(--sg-primary-soft);
border-color: var(--sg-border);
}
&--ipc .classification-badge--system {
background: #dbeafe;
color: #1d4ed8;
background: var(--sg-surface-muted);
color: var(--sg-blue-highlight);
}
&--cpc .classification-card {
background: #f0fdf4;
border-color: #bbf7d0;
background: var(--sg-success-soft);
border-color: var(--sg-success);
}
&--cpc .classification-badge--system {
background: #dcfce7;
color: #15803d;
background: var(--sg-success-soft);
color: var(--sg-success);
}
}
@@ -521,7 +540,7 @@
.classification-card {
padding: 12px 14px;
border-radius: 10px;
border: 1px solid #dbeafe;
border: 1px solid var(--sg-border);
}
.classification-card__header {
@@ -547,7 +566,7 @@
.classification-code {
font-size: 0.9rem;
font-weight: 700;
color: #0f172a;
color: var(--sg-text);
}
.classification-badge {
@@ -562,15 +581,15 @@
}
.classification-badge--level {
background: #e2e8f0;
color: #475569;
background: var(--sg-surface-soft);
color: var(--sg-text-muted);
}
.classification-summary {
margin: 10px 0 0;
font-size: 0.84rem;
line-height: 1.5;
color: #334155;
color: var(--sg-text-muted);
}
.classification-toggle {
@@ -578,7 +597,7 @@
padding: 0;
border: 0;
background: none;
color: #2563eb;
color: var(--sg-blue-highlight);
font-size: 0.78rem;
cursor: pointer;
@@ -590,7 +609,7 @@
.classification-hierarchy {
margin: 10px 0 0;
padding-top: 10px;
border-top: 1px solid rgba(15, 23, 42, 0.08);
border-top: 1px solid var(--sg-border);
}
.classification-hierarchy__row {
@@ -603,7 +622,7 @@
margin: 0;
font-size: 0.72rem;
font-weight: 700;
color: #64748b;
color: var(--sg-text-muted);
text-transform: uppercase;
letter-spacing: 0.03em;
}
@@ -612,7 +631,7 @@
margin: 0;
font-size: 0.8rem;
line-height: 1.45;
color: #334155;
color: var(--sg-text);
}
}
@@ -625,9 +644,10 @@
button {
padding: 4px 10px;
border: 1px solid #d0d0d0;
border: 1px solid var(--sg-border);
border-radius: 6px;
background: white;
background: var(--sg-surface);
color: var(--sg-text);
cursor: pointer;
font-size: 12px;
@@ -639,6 +659,6 @@
span {
font-size: 12px;
color: #666;
color: var(--sg-text-muted);
}
}
@@ -11,6 +11,8 @@ import {
getPublicationStageLabel,
} from '../patent-detail/patent-detail.utils';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { PageEvent } from '@angular/material/paginator';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
type SortMode = 'date' | 'title';
type SourceFilter = 'all' | 'EPO' | 'USPTO';
@@ -25,6 +27,7 @@ type OrgPatentMatchTypeFilter = 'all' | 'institution' | 'name' | 'both';
MatFormFieldModule,
MatSelectModule,
MatIconModule,
QueryParamPaginatorComponent,
],
templateUrl: './institution-patents.component.html',
styleUrl: './institution-patents.component.scss',
@@ -47,8 +50,8 @@ export class InstitutionPatentsComponent implements OnInit {
activeMatchType: OrgPatentMatchTypeFilter = 'all';
sortMode: SortMode = 'date';
selectedPage = 1;
readonly pageSize = 20;
pageIndex = 0;
pageSize = 20;
totalPatents = 0;
ngOnInit(): void {
@@ -59,6 +62,12 @@ export class InstitutionPatentsComponent implements OnInit {
const sortFromUrl = this.route.snapshot.queryParamMap.get('sortBy');
const matchTypeFromUrl =
this.route.snapshot.queryParamMap.get('matchType');
this.pageIndex = this.parsePageIndexParam(
this.route.snapshot.queryParamMap.get('page'),
);
this.pageSize = this.parsePageSizeParam(
this.route.snapshot.queryParamMap.get('size'),
);
if (this.isValidFilter(filterFromUrl)) {
this.activeFilter = filterFromUrl;
@@ -79,7 +88,7 @@ export class InstitutionPatentsComponent implements OnInit {
setFilter(filter: SourceFilter): void {
this.activeFilter = filter;
this.selectedPage = 1;
this.pageIndex = 0;
this.selectedPatent = null;
this.reloadPatents();
}
@@ -87,7 +96,7 @@ export class InstitutionPatentsComponent implements OnInit {
setMatchType(matchType: OrgPatentMatchTypeFilter): void {
if (this.activeMatchType === matchType) return;
this.activeMatchType = matchType;
this.selectedPage = 1;
this.pageIndex = 0;
this.selectedPatent = null;
this.reloadPatents();
}
@@ -108,8 +117,9 @@ export class InstitutionPatentsComponent implements OnInit {
this.router.navigate(['/patent', this.selectedPatent.patent_id]);
}
setPage(page: number): void {
this.selectedPage = Math.min(Math.max(page, 1), this.getPageCount());
onPatentPageChange(event: PageEvent): void {
this.pageIndex = event.pageIndex;
this.pageSize = event.pageSize;
this.selectedPatent = null;
this.reloadPatents();
}
@@ -118,14 +128,6 @@ export class InstitutionPatentsComponent implements OnInit {
return this.filteredPatents;
}
getPageCount(): number {
return Math.max(1, Math.ceil(this.totalPatents / this.pageSize));
}
hasPagination(): boolean {
return this.totalPatents > this.pageSize;
}
private reloadPatents(): void {
const institutionId =
this.institutionId ??
@@ -145,7 +147,7 @@ export class InstitutionPatentsComponent implements OnInit {
institutionId,
this.activeMatchType !== 'all' ? this.activeMatchType : undefined,
this.selectedPage - 1,
this.pageIndex,
this.pageSize,
this.activeFilter !== 'all' ? this.activeFilter : undefined,
)
@@ -183,13 +185,24 @@ export class InstitutionPatentsComponent implements OnInit {
filter: this.activeFilter,
sortBy: this.sortMode,
matchType: this.activeMatchType,
page: this.selectedPage,
page: this.pageIndex,
size: this.pageSize,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
private parsePageIndexParam(value: string | null): number {
const parsed = Number(value);
return Number.isInteger(parsed) && parsed >= 0 ? parsed : 0;
}
private parsePageSizeParam(value: string | null): number {
const parsed = Number(value);
return Number.isInteger(parsed) && parsed > 0 ? parsed : 20;
}
private isValidFilter(value: string | null): value is SourceFilter {
return value === 'all' || value === 'EPO' || value === 'USPTO';
}
@@ -2,94 +2,87 @@
<h3>Projekte</h3>
<div class="funding-area">
<mat-card appearance="outlined">
<mat-card-content>
<app-query-param-input
label="Suche nach Themen"
queryParamKey="search" />
<div class="person-projects">
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
matTabLink
[routerLink]="[route.path]"
queryParamsHandling="merge"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
{{ route.label }}
</a>
}
</nav>
<mat-tab-group
[selectedIndex]="tabIndex()"
(selectedTabChange)="selectedTabChange($event)">
<mat-tab label="EU">
<app-data-table
[data]="euProjectData"
[columns]="euProjectColumns"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
</mat-tab>
<mat-tab label="Bund">
<app-data-table
[data]="bundProjectData"
[columns]="bundProjectColumns"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
</mat-tab>
</mat-tab-group>
<app-query-param-paginator
[total]="pageTotal()"
[pageSizeOptions]="[10, 20, 50]" />
</mat-card-content>
</mat-card>
<div class="funding-info-section">
<mat-card appearance="outlined">
<mat-card-header>
<mat-card-title>Förderung über Zeit</mat-card-title>
</mat-card-header>
<mat-card-content>
<app-institution-projects-funding-graph
[fundings]="[bundProjectsFunding(), cordisEuProjectsFunding()]" />
</mat-card-content>
</mat-card>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
<div class="funding-info-section">
<mat-card appearance="outlined">
<mat-card-header>
<mat-card-title>Förderung über Zeit</mat-card-title>
</mat-card-header>
<mat-card-content>
<app-institution-projects-funding-graph
[fundings]="[bundProjectsFunding(), cordisEuProjectsFunding()]" />
</mat-card-content>
</mat-card>
<div class="funding-info-cards">
<app-info-card
[description]="'Gesamte Förderung durch Bund'"
[value]="
(bundTotalFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Durchschnittliche jährliche Förderung durch Bund'"
[value]="
(bundAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Gesamte Förderung durch die Europäische Union'"
[value]="
(euTotalFunding() | currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ??
undefined
" />
<app-info-card
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
[value]="
(euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<div class="funding-info-cards">
<app-info-card
[description]="'Gesamte Förderung durch Bund'"
[value]="
(bundTotalFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Durchschnittliche jährliche Förderung durch Bund'"
[value]="
(bundAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Gesamte Förderung durch die Europäische Union'"
[value]="
(euTotalFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-info-card
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'"
[value]="
(euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
</div>
</div>
</div>
</div>
<ng-template #fundingStartTmp let-row>
{{ row.funding_start | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingEndTmp let-row>
{{ row.funding_end | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingAmountTmp let-row>
{{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #euProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
<mat-icon>open_in_new</mat-icon>
</a></ng-template
>
<ng-template #bundProjectActionsTmp let-row>
<a
mat-icon-button
color="primary"
[routerLink]="['/projects/bund', row.id]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
</div>
<ng-template #fundingStartTmp let-row>
{{ row.funding_start | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingEndTmp let-row>
{{ row.funding_end | date: 'dd.MM.yyyy' }}
</ng-template>
<ng-template #fundingAmountTmp let-row>
{{ row.funding_amount | currency: 'EUR' : 'symbol' : '1.0-0' : 'de' }}
</ng-template>
<ng-template #euProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/eu', row.id]">
<mat-icon>open_in_new</mat-icon>
</a></ng-template
>
<ng-template #bundProjectActionsTmp let-row>
<a mat-icon-button color="primary" [routerLink]="['/projects/bund', row.id]">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>

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