Merge branch 'researchers-to-projects' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/dfg-details

This commit is contained in:
2026-06-18 10:37:00 +02:00
51 changed files with 1960 additions and 450 deletions
Vendored
+3
View File
@@ -28,6 +28,9 @@ pipeline {
}
stage('Save Docker image') {
when {
branch 'main'
}
steps {
sh 'docker save ${IMAGE_PREFIX}-app:${IMAGE_VERSION} | gzip > app-image.tar.gz'
}
@@ -35,15 +35,6 @@ headers = {
"Content-Type": "application/json"
}
def float_array_to_base64(vector):
"""
Convert a float vector into a Base64 string representing 32-bit big-endian float bytes.
Elasticsearch expects big-endian floats for binary/Base64 dense_vector encoding.
"""
arr = np.asarray(vector, dtype=np.float32)
big_endian_bytes = arr.astype('>f4').tobytes()
return base64.b64encode(big_endian_bytes).decode('utf-8')
def split_into_sentences(text):
if not text:
return []
@@ -52,77 +43,6 @@ def split_into_sentences(text):
# Filter out empty or extremely short sentences
return [s for s in sentences if len(s.strip()) > 3]
def check_and_update_mapping():
print("Checking 'topicvectors' index...")
with httpx.Client(timeout=30.0) as client:
exists_resp = client.head(f"{ELASTIC_URL}topicvectors", headers=headers)
if exists_resp.status_code == 404:
print("Index 'topicvectors' does not exist. Creating index with mapping...")
create_payload = {
"mappings": {
"properties": {
"id": {"type": "keyword"},
"display_name": {
"type": "text",
"fields": {
"keyword": {"type": "keyword", "ignore_above": 256}
}
},
"display_name_vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
},
"description": {"type": "text"},
"description_vectors": {
"type": "nested",
"properties": {
"vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
}
}
},
"keywords": {
"type": "text",
"fields": {
"keyword": {"type": "keyword"}
}
},
"cited_by_count": {"type": "long"},
"works_count": {"type": "long"},
"updated_date": {"type": "date"},
"created_date": {"type": "date"}
}
}
}
resp = client.put(
f"{ELASTIC_URL}topicvectors",
json=create_payload,
headers=headers
)
if resp.status_code == 200:
print("Successfully created 'topicvectors' index.")
else:
print(f"Failed to create index: {resp.status_code} - {resp.text}")
resp.raise_for_status()
else:
print("Index 'topicvectors' already exists.")
def fetch_all_topics():
print("Fetching topics from 'openalex-topics'...")
topics = []
@@ -204,8 +124,6 @@ def bulk_index_topics(topics, display_name_vectors, nested_description_vectors):
print(f"Indexed batch {i} to {i + len(batch_topics)}")
def main():
check_and_update_mapping()
topics = fetch_all_topics()
if not topics:
print("No topics found. Exiting.")
+60 -96
View File
@@ -1,150 +1,114 @@
{
"query": "Robotics",
"max_score": 22.734766,
"query": "localization",
"max_score": 23.237041,
"results": [
{
"topic_name": "Soft Robotics and Applications",
"score": 22.734766
},
{
"topic_name": "Robotics and Automated Systems",
"score": 21.997686
},
{
"topic_name": "Educational Robotics and Engineering",
"score": 21.919401
},
{
"topic_name": "Prosthetics and Rehabilitation Robotics",
"score": 21.846806
},
{
"topic_name": "Micro and Nano Robotics",
"score": 21.820261
},
{
"topic_name": "Reinforcement Learning in Robotics",
"score": 21.757397
"topic_name": "Indoor and Outdoor Localization Technologies",
"score": 23.237041
},
{
"topic_name": "Robotics and Sensor-Based Localization",
"score": 19.993645
"score": 21.511477
},
{
"topic_name": "Social Robot Interaction and HRI",
"score": 13.187252
"topic_name": "Spectral Theory in Mathematical Physics",
"score": 14.039959
},
{
"topic_name": "Robotic Locomotion and Control",
"score": 12.283064
"topic_name": "Socioeconomic Development in MENA",
"score": 11.518878
},
{
"topic_name": "Power Line Inspection Robots",
"score": 11.873396
"topic_name": "Electrical Fault Detection and Protection",
"score": 10.770052
},
{
"topic_name": "Mechatronics Education and Applications",
"score": 11.171629
"topic_name": "Machine Learning in Bioinformatics",
"score": 10.322677
},
{
"topic_name": "Educational Technology and Optimization",
"score": 10.924184
"topic_name": "Software System Performance and Reliability",
"score": 10.112644
},
{
"topic_name": "Mechanical and Thermal Properties Analysis",
"score": 10.924184
"topic_name": "Quantum many-body systems",
"score": 10.112644
},
{
"topic_name": "Psychiatry, Mental Health, Neuroscience",
"score": 10.687462
"topic_name": "Random lasers and scattering media",
"score": 10.112644
},
{
"topic_name": "Advanced Materials and Mechanics",
"score": 10.460782
"topic_name": "Insect Pheromone Research and Control",
"score": 9.910988
},
{
"topic_name": "Wetland Management and Conservation",
"score": 10.460782
"topic_name": "Tactile and Sensory Interactions",
"score": 9.910988
},
{
"topic_name": "Artificial Intelligence Applications",
"score": 10.243518
"topic_name": "Handwritten Text Recognition Techniques",
"score": 9.910988
},
{
"topic_name": "Digitalization, Law, and Regulation",
"score": 10.243518
"topic_name": "Integrated Circuits and Semiconductor Failure Analysis",
"score": 9.910988
},
{
"topic_name": "Engineering and Technology Innovations",
"score": 10.243518
"topic_name": "Medical Imaging and Analysis",
"score": 9.7172165
},
{
"topic_name": "Advanced Algorithms and Applications",
"score": 10.035095
"topic_name": "Microwave Imaging and Scattering Analysis",
"score": 9.7172165
},
{
"topic_name": "Teaching and Learning Programming",
"score": 10.035095
"topic_name": "Neurology and Historical Studies",
"score": 9.7172165
},
{
"topic_name": "Distributed Control Multi-Agent Systems",
"score": 10.035095
"topic_name": "High-Velocity Impact and Material Behavior",
"score": 9.7172165
},
{
"topic_name": "Advanced Scientific and Engineering Studies",
"score": 9.834986
"topic_name": "Software Engineering Research",
"score": 9.530875
},
{
"topic_name": "Space Satellite Systems and Control",
"score": 9.6427
"topic_name": "Software Testing and Debugging Techniques",
"score": 9.530875
},
{
"topic_name": "Smart Agriculture and AI",
"score": 9.279837
"topic_name": "Digital Media Forensic Detection",
"score": 9.530875
},
{
"topic_name": "Infrared Thermography in Medicine",
"score": 9.351548
},
{
"topic_name": "Explainable Artificial Intelligence (XAI)",
"score": 9.351548
},
{
"topic_name": "Underwater Vehicles and Communication Systems",
"score": 9.279837
"score": 9.351548
},
{
"topic_name": "Modular Robots and Swarm Intelligence",
"score": 7.7584143
"topic_name": "Diffusion and Search Dynamics",
"score": 8.8518915
},
{
"topic_name": "Diverse Perspectives in Modern Studies",
"topic_name": "Direction-of-Arrival Estimation Techniques",
"score": 5.968384
},
{
"topic_name": "Retinal Imaging and Analysis",
"score": 5.6107
},
{
"topic_name": "Teleoperation and Haptic Systems",
"score": 5.2510495
},
{
"topic_name": "Optimization and Search Problems",
"score": 5.1682277
},
{
"topic_name": "Adaptive Dynamic Programming Control",
"score": 4.8615155
},
{
"topic_name": "Robotic Mechanisms and Dynamics",
"score": 2.6450925
},
{
"topic_name": "Control and Dynamics of Mobile Robots",
"score": 2.5917463
},
{
"topic_name": "Robot Manipulation and Learning",
"score": 2.5859585
},
{
"topic_name": "Robotic Process Automation Applications",
"score": 1.7370787
},
{
"topic_name": "Robotic Path Planning Algorithms",
"score": 1.6302633
"topic_name": "Radar Systems and Signal Processing",
"score": 4.721418
}
]
}
}
+1 -4
View File
@@ -6,7 +6,4 @@ ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FM
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
LLM_MODEL=gemma4-e4b
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
LLM_MODEL=gemma4-e4b
@@ -1,9 +1,12 @@
import logging
from typing import List, Set
from typing import Any, Dict, Literal, Optional
from inse.models.openalex.institution import Institution
from inse.exceptions import NotFoundException
from inse.integrations import elasticsearch
from inse.institutions.model import InstitutionPage
logger = logging.getLogger(__name__)
@@ -12,12 +15,12 @@ logger = logging.getLogger(__name__)
class InstitutionsSearchClient:
def __init__(self):
"""
Initializes the client. Credentials and URLs are handled by the
Initializes the client. Credentials and URLs are handled by the
centralized elasticsearch integration.
"""
pass
async def get_institution_by_id(self, raw_institution_id: str) -> Institution:
def get_institution_by_id(self, raw_institution_id: str) -> Institution:
"""
Retrieves a single institution by its OpenAlex ID from the local Elasticsearch cluster.
"""
@@ -26,27 +29,111 @@ class InstitutionsSearchClient:
"id": f"https://openalex.org/{raw_institution_id.upper()}",
}
}
res = elasticsearch.search(
index="openalex-institutions",
query=query,
size=1
)
res = elasticsearch.search(index="openalex-institutions", query=query, size=1)
hits = res.get("hits", {}).get("hits", [])
if not hits:
raise NotFoundException(f"Institution with ID '{raw_institution_id}' not found.")
raise NotFoundException(
f"Institution with ID '{raw_institution_id}' not found."
)
institution = self._convert_hit_to_institution(hits[0])
if not institution:
raise NotFoundException(
f"Institution with ID '{raw_institution_id}' could not be parsed."
)
return institution
def get_institutions_by_name(
self,
name: str,
page: int = 0,
size: int = 10,
sort_by: Literal[
"relevance", "name", "works_count", "citations_count"
] = "relevance",
sorting_direction: Literal["asc", "desc"] = "asc",
) -> InstitutionPage:
sort_config: list = []
if sort_by == "relevance":
sort_config.append(
{
"_score": {
"order": sorting_direction if sorting_direction else "desc"
}
}
)
elif sort_by == "works_count":
sort_config.append({"works_count": {"order": sorting_direction}})
elif sort_by == "citations_count":
sort_config.append({"cited_by_count": {"order": sorting_direction}})
else:
sort_config.append({"display_name.keyword": {"order": sorting_direction}})
query: Dict[str, Any] = {"match_all": {}}
if len(name) > 0:
query = {
"match_phrase_prefix": {
"display_name": {
"query": name,
"max_expansions": 50,
}
}
}
elif sort_by == "relevance":
sort_config = [{"display_name.keyword": {"order": sorting_direction}}]
authors = await self.get_authors_by_institution_id(raw_institution_id)
logger.debug(
"Retrieved authors for institution_id=%s: %s", raw_institution_id, authors
"Searching institutions with name='%s', page=%d, size=%d, sorting_direction='%s', query: %s",
name,
page,
size,
sorting_direction,
query,
)
try:
response = elasticsearch.search(
index="openalex-institutions",
offset=page * size,
size=size,
sort=sort_config,
query=query,
)
except Exception as e:
logger.exception("Error while searching for institutions: %s", e)
raise
return self.response_to_institution_page(response, page, size)
def response_to_institution_page(
self, response: Dict[str, Any], page: int, size: int
) -> InstitutionPage:
hits = response.get("hits", {}).get("hits", [])
institutions = []
for hit in hits:
institution = self._convert_hit_to_institution(hit)
if institution:
institutions.append(institution)
total = response.get("hits", {}).get("total", {}).get("value", 0)
logger.debug(
"Parsed institution page: page=%d, size=%d, total=%d", page, size, total
)
return InstitutionPage(
elements=institutions,
page=page,
size=size,
total=total,
)
return Institution.from_dict(hits[0]["_source"])
async def get_authors_by_institution_id(self, raw_institution_id: str) -> List[str]:
"""
Fetches authors associated with an institution.
Fetches authors associated with an institution.
Note: This query is specifically looking for current affiliations (2026).
"""
query = {
@@ -75,14 +162,19 @@ class InstitutionsSearchClient:
raw_institution_id,
query,
)
res = elasticsearch.search(index="openalex-authors", query=query)
hits = res.get("hits", {}).get("hits", [])
# Extracting display_name directly from the author document source
authors = {hit["_source"].get("display_name") for hit in hits if hit["_source"].get("display_name")}
authors = {
hit["_source"].get("display_name")
for hit in hits
if hit["_source"].get("display_name")
}
return list(authors)
async def search_institutions(
def search_institutions(
self,
query_text: str,
country_code: str | None = None,
@@ -153,14 +245,22 @@ class InstitutionsSearchClient:
sort=[
{"works_count": {"order": "desc"}},
],
source=["id", "display_name", "country_code", "type", "works_count", "cited_by_count", "geo"],
source=[
"id",
"display_name",
"country_code",
"type",
"works_count",
"cited_by_count",
"geo",
],
)
hits = res.get("hits", {}).get("hits", [])
return [Institution.from_dict(hit["_source"]) for hit in hits]
async def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]:
def get_institution_aliases_by_id(self, raw_institution_id: str) -> List[str]:
"""Get a list of institution aliases for a given institution ID, including both display name alternatives and predefined aliases.
Args:
@@ -169,7 +269,7 @@ class InstitutionsSearchClient:
Returns:
List[str]: A list of aliases for the given institution ID.
"""
institution = await self.get_institution_by_id(raw_institution_id)
institution = self.get_institution_by_id(raw_institution_id)
aliases = list(
self.augment_aliases(set(institution.display_name_alternatives or []))
| self.get_predefined_institution_aliases(raw_institution_id)
@@ -246,3 +346,46 @@ class InstitutionsSearchClient:
)
aliases.append(alias.replace("-", " "))
return aliases
def _convert_hit_to_institution(self, hit: Dict[str, Any]) -> Optional[Institution]:
"""Convert an Elasticsearch hit to an Institution object, applying necessary data cleaning and validation.
Args:
hit (Dict[str, Any]): The Elasticsearch hit to convert.
Returns:
Optional[Institution]: The converted Institution object or None if conversion fails.
"""
source = hit.get("_source")
if not source:
return None
ALLOWED_TYPES = {
"education",
"healthcare",
"company",
"archive",
"nonprofit",
"government",
"facility",
"other",
}
cleaned_source = {}
for key, value in source.items():
if isinstance(value, str) and "T" in value:
cleaned_source[key] = value.split("T")[0]
elif key == "type" and value not in ALLOWED_TYPES:
cleaned_source[key] = "other"
else:
cleaned_source[key] = value
try:
return Institution.model_validate(cleaned_source)
except Exception as e:
logger.exception(
"Failed to validate institution hit ID %s: %s", hit.get("_id"), e
)
return None
+3 -3
View File
@@ -41,7 +41,7 @@ _VALID_INSTITUTION_TYPES = {
async def get_institution_by_id(
raw_institution_id: str, client: InstitutionsSearchClient
) -> Institution:
return await client.get_institution_by_id(raw_institution_id)
return client.get_institution_by_id(raw_institution_id)
async def list_institutions(
@@ -117,10 +117,10 @@ async def autocomplete_institutions(
client: InstitutionsSearchClient,
) -> AutocompleteResponse:
"""
Returns institution options for autocomplete inputs using the local
Returns institution options for autocomplete inputs using the local
Elasticsearch cluster via the provided client.
"""
institutions = await client.search_institutions(
institutions = client.search_institutions(
query_text=query,
country_code=country_code,
institution_type=institution_type,
@@ -0,0 +1,17 @@
from typing import List
from pydantic import BaseModel, Field
from inse.models.openalex.institution import Institution
class InstitutionPage(BaseModel):
elements: List[Institution] = Field(
default_factory=list, description="List of institutions in the current page."
)
page: int = Field(default=0, description="Current page number. (0-indexed)")
size: int = Field(default=10, description="Number of institutions per page.")
total: int = Field(
default=0,
description="Total number of institutions matching the search criteria.",
)
@@ -5,15 +5,15 @@ REST API for OpenAlex institutions.
"""
from functools import lru_cache
from typing import Annotated
from typing import Annotated, Literal
from fastapi import APIRouter, Depends, status, Query
from inse.models.openalex.autocomplete_response import AutocompleteResponse
from inse.models.openalex.institutions_list_response import InstitutionsListResponse
from inse.tags import Tags
from inse.config import get_settings
from inse.models.openalex.institution import Institution
from inse.institutions.model import InstitutionPage
from . import logic
from inse.institutions.institutions_search_client import InstitutionsSearchClient
@@ -25,6 +25,84 @@ router = APIRouter(prefix="/api/inse-service/institutions", tags=[Tags.INSTITUTI
def get_institutions_search_client() -> InstitutionsSearchClient:
return InstitutionsSearchClient()
@router.get(
"/search",
summary="Searches for institutions by name.",
description="Searches for institutions by name with pagination.",
operation_id="searchInstitutionsByName",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": InstitutionPage,
},
},
response_model_exclude_none=True,
)
async def search_institutions_by_name(
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
name: Annotated[
str,
Query(
description="Institution name to search for, for example 'University of Duisburg Essen'.",
),
] = "",
page: Annotated[
int,
Query(description="Page number (0-indexed).", ge=0),
] = 0,
size: Annotated[
int,
Query(description="Number of institutions per page.", ge=1, le=100),
] = 10,
sort_by: Annotated[
Literal["relevance", "name", "works_count", "citations_count"],
Query(
description="Field to sort by, either 'relevance', 'name', 'works_count', or 'citations_count'.",
regex="^(relevance|name|works_count|citations_count)$",
),
] = "name",
sorting_direction: Annotated[
Literal["asc", "desc"],
Query(
description="Sorting direction, either 'asc' or 'desc'.",
regex="^(asc|desc)$",
),
] = "asc",
) -> InstitutionPage:
return client.get_institutions_by_name(
name=name,
page=page,
size=size,
sort_by=sort_by,
sorting_direction=sorting_direction,
)
@router.get(
"/{id}",
summary="Returns a single institution by ID.",
description="Returns a single institution by its OpenAlex ID.",
operation_id="getInstitutionById",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": Institution,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
)
async def get_institution(
id: str,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
) -> Institution:
return await logic.get_institution_by_id(raw_institution_id=id, client=client)
@router.get(
"/autocomplete",
operation_id="autocompleteInstitutions",
@@ -52,7 +130,9 @@ async def autocomplete_institutions(
int,
Query(description="Maximum number of autocomplete options.", ge=1, le=25),
] = 10,
client: Annotated[InstitutionsSearchClient, Depends(get_institutions_search_client)] = None,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
] = None,
):
return await logic.autocomplete_institutions(
query=query,
@@ -125,25 +205,3 @@ async def list_institutions(
sample=sample,
select=select,
)
@router.get(
"/{id}",
summary="Returns a single institution by ID.",
description="Returns a single institution by its OpenAlex ID.",
operation_id="getInstitutionById",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": Institution,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
)
async def get_institution(
id: str,
client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
) -> Institution:
return await logic.get_institution_by_id(raw_institution_id=id, client=client)
@@ -1,38 +1,87 @@
from typing import Any, Optional
import logging
from typing import Any, Dict, List, Optional, Tuple
import httpx
from .. import config
logger = logging.getLogger(__name__)
def _cluster_credentials(cluster: str) -> tuple[str, str]:
def _cluster_credentials(cluster: str) -> Tuple[str, str]:
"""Retrieves the Elasticsearch URL and API key for the specified cluster from the configuration.
Args:
cluster (str): The cluster for which to retrieve credentials. Allowed values are "nes" and "inse".
Raises:
ValueError: If the cluster is unknown or the credentials are not set in the configuration.
Returns:
Tuple[str, str]: The Elasticsearch URL and API key for the specified cluster.
"""
if cluster == "nes":
if (
not config.settings.elasticsearch_url
or not config.settings.elasticsearch_api_key
):
raise ValueError(
"Elasticsearch URL and API key must be set in the configuration for cluster 'nes'"
)
return config.settings.elasticsearch_url, config.settings.elasticsearch_api_key
elif cluster == "inse":
return config.settings.elasticsearch_inse_url, config.settings.elasticsearch_inse_api_key
if (
not config.settings.elasticsearch_inse_url
or not config.settings.elasticsearch_inse_api_key
):
raise ValueError(
"Elasticsearch INSE URL and API key must be set in the configuration for cluster 'inse'"
)
return (
config.settings.elasticsearch_inse_url,
config.settings.elasticsearch_inse_api_key,
)
else:
raise ValueError(f"Unbekannter Cluster: {cluster!r} (erlaubt: 'nes', 'inse')")
raise ValueError(f"Unknown cluster: {cluster!r} (allowed: 'nes', 'inse')")
def search(
index: str,
query_field: str = None,
query_value: str = None,
query: dict = None,
source = None,
size: int = None,
offset:int = None,
sort: list = None,
body: dict = None,
track_total_hits = False,
query_field: Optional[str] = None,
query_value: Optional[str] = None,
query: Optional[Dict] = None,
source: Optional[List] = None,
size: Optional[int] = None,
offset: Optional[int] = None,
sort: Optional[List] = None,
body: Optional[Dict] = None,
track_total_hits=False,
cluster: str = "nes",
) -> dict[str, Any]:
) -> Dict[str, Any]:
"""Searches the specified Elasticsearch index using either a simple query string or a full query body.
Args:
index (str): The name of the Elasticsearch index to search.
query_field (Optional[str], optional): The field to search in. Defaults to None.
query_value (Optional[str], optional): The value to search for. Defaults to None.
query (Optional[Dict], optional): The full query body. Defaults to None.
source (Optional[List], optional): The fields to include in the response. Defaults to None.
size (Optional[int], optional): The maximum number of results to return. Defaults to None.
offset (Optional[int], optional): The number of results to skip. Defaults to None.
sort (Optional[List], optional): The fields to sort by. Defaults to None.
body (Optional[Dict], optional): The full query body. Defaults to None.
track_total_hits (bool, optional): Whether to track the total number of hits. Defaults to False.
cluster (str, optional): The Elasticsearch cluster to search. Defaults to "nes".
Returns:
Dict[str, Any]: The search results.
"""
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {
"Authorization": f"ApiKey {api_key}",
"Content-Type": "application/json"
}
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
payload: Dict[str, Any]
if body is not None:
payload = body
@@ -51,18 +100,16 @@ def search(
else:
payload = {
"query": {
"query_string": {
"default_field": query_field,
"query": query_value
}
"query_string": {"default_field": query_field, "query": query_value}
}
}
with httpx.Client(timeout=httpx.Timeout(30.0)) as client:
logger.debug(
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} with payload: {payload}"
)
response = client.post(
f"{elasticsearch_url}/{index}/_search",
json=payload,
headers=headers
f"{elasticsearch_url}/{index}/_search", json=payload, headers=headers
)
response.raise_for_status()
return response.json()
@@ -71,16 +118,13 @@ def search(
def get(
index: str,
doc_id: str,
source: list = None,
source: Optional[list] = None,
cluster: str = "nes",
) -> dict[str, Any]:
elasticsearch_url, api_key = _cluster_credentials(cluster)
headers = {
"Authorization": f"ApiKey {api_key}",
"Content-Type": "application/json"
}
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
params = {}
if source is not None:
@@ -88,9 +132,7 @@ def get(
with httpx.Client() as client:
response = client.get(
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
params=params,
headers=headers
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
)
response.raise_for_status()
return response.json()
+2 -2
View File
@@ -11,7 +11,7 @@ from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from inse.collaboration_network.router import router as collaboration_network_router
from inse.institutions.service import router as institutions_service_router
from inse.institutions.router import router as institutions_router
from inse.topics.service import router as topics_service_router
from inse.works.service import router as works_service_router
from inse.persons.service import router as persons_service_router
@@ -39,7 +39,7 @@ app = FastAPI(
servers=settings.servers,
)
app.include_router(collaboration_network_router)
app.include_router(institutions_service_router)
app.include_router(institutions_router)
app.include_router(topics_service_router)
app.include_router(works_service_router)
app.include_router(persons_service_router)
+133 -6
View File
@@ -7,7 +7,9 @@ Business logic for persons / authors.
import json
import logging
import time
from datetime import datetime
from typing import Optional, Callable, Any, List
from elasticsearch import ApiError, NotFoundError
import hashlib
import httpx
from fastapi import HTTPException
@@ -24,8 +26,8 @@ from inse.persons.model import (
CustomAuthor,
CustomAuthorsListResponse,
PersonSearchRequest,
CareerMetrics,
)
logger = logging.getLogger(__name__)
INDEX_NAME = "openalex-authors"
@@ -186,6 +188,120 @@ def _fetch_works_and_topics(author_id: str) -> tuple[list, list]:
return works, topics
def _get_publication_years_for_author(author_id: str) -> list[int]:
author_url = f"https://openalex.org/{author_id.strip()}"
body = {
"size": 0,
"query": {
"nested": {
"path": "authorships",
"query": {
"bool": {
"filter": [
{"term": {"authorships.author.id": author_url}},
],
},
},
},
},
"aggs": {
"publication_years": {
"terms": {
"field": "publication_year",
"size": 1000,
},
},
},
}
response = elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=body,
)
buckets = (
response.get("aggregations", {})
.get("publication_years", {})
.get("buckets", [])
)
publication_years: list[int] = []
for bucket in buckets:
year = bucket.get("key")
count = bucket.get("doc_count", 0)
if isinstance(year, int):
publication_years.extend([year] * count)
return publication_years
def _classify_career_stage(active_years: int) -> str:
if active_years <= 0:
return "unknown"
if active_years <= 4:
return "Early Researcher"
if active_years <= 10:
return "Emerging Researcher"
if active_years <= 20:
return "Established Researcher"
return "Senior Researcher"
def _compute_career_metrics(publication_years: list[int]) -> CareerMetrics:
current_year = datetime.now().year
if not publication_years:
return CareerMetrics()
sorted_years = sorted(publication_years)
unique_years = sorted(set(publication_years))
first_year = sorted_years[0]
last_year = sorted_years[-1]
publication_count = len(sorted_years)
active_years = len(unique_years)
career_stage = _classify_career_stage(active_years)
career_age = last_year - first_year
career_span = last_year - first_year + 1
publications_per_active_year = (
publication_count / active_years if active_years > 0 else None
)
publications_per_career_year = (
publication_count / career_span if career_span > 0 else None
)
years_since_last_publication = current_year - last_year
has_suspicious_publication_years = first_year < 1970 or career_span > 60
return CareerMetrics(
first_publication_year=first_year,
last_publication_year=last_year,
career_age=career_age,
career_span=career_span,
career_stage=career_stage,
active_years=active_years,
publication_count=publication_count,
publications_per_active_year=publications_per_active_year,
publications_per_career_year=publications_per_career_year,
years_since_last_publication=years_since_last_publication,
has_suspicious_publication_years=has_suspicious_publication_years,
)
def get_career_metrics_for_author(author_id: str) -> CareerMetrics:
publication_years = _get_publication_years_for_author(author_id)
return _compute_career_metrics(publication_years)
def _build_papers(works: list) -> list:
papers = []
@@ -254,23 +370,34 @@ def generate_person_bio(author_id: str, include: Optional[set[str]] = None) -> s
def get_person_by_id(
author_id: str, include: Optional[str] = None
) -> AuthorsListResponse:
) -> CustomAuthorsListResponse:
body = {
"_source": include.split(",") if include else True,
}
try:
hit = elasticsearch.get(index="openalex-authors", body=body, doc_id=author_id)
hit = elasticsearch.get(
index="openalex-authors",
body=body,
doc_id=author_id,
)
except NotFoundError:
raise HTTPException(
status_code=404, detail=f"Person with id {author_id} not found"
)
except ApiError as e:
raise HTTPException(status_code=500, detail=f"Elasticsearch error: {str(e)}")
persons = [util.get_persons_data(hit)]
return AuthorsListResponse(results=persons)
author = util.get_persons_data(hit)
career_metrics = get_career_metrics_for_author(author_id)
custom_author = CustomAuthor(
**author.model_dump(),
career_metrics=career_metrics,
)
return CustomAuthorsListResponse(results=[custom_author])
def search_persons_by_name(
+42 -3
View File
@@ -13,20 +13,59 @@ from inse.models.openalex.authors_list_response import AuthorsListResponse
from inse.models.openalex.group_by_result import GroupByResult
class CareerMetrics(BaseModel):
first_publication_year: Optional[int] = Field(
default=None, description="First publication year of the author."
)
last_publication_year: Optional[int] = Field(
default=None, description="Last publication year of the author."
)
career_age: Optional[int] = Field(
default=None, description="Difference between last and first publication year."
)
career_span: Optional[int] = Field(
default=None, description="Inclusive span from first to last publication year."
)
career_stage: Optional[str] = Field(
default=None,
description="Threshold-based career stage derived from active publication years.",
)
active_years: int = Field(
default=0, description="Number of distinct years with at least one publication."
)
publication_count: int = Field(
default=0, description="Number of publications used for career metrics."
)
publications_per_active_year: Optional[float] = Field(
default=None, description="Average publications per active publication year."
)
publications_per_career_year: Optional[float] = Field(
default=None, description="Average publications per year over the full career span."
)
years_since_last_publication: Optional[int] = Field(
default=None, description="Years since the last publication."
)
has_suspicious_publication_years: bool = Field(
default=False, description="True if publication years look suspicious."
)
class CustomAuthor(Author):
relevance_rating: Optional[str] = Field(
default=None, description="The relevance suitability rating."
)
career_metrics: Optional[CareerMetrics] = Field(
default=None, description="Publication-history-based career metrics."
)
class CustomAuthorsListResponse(AuthorsListResponse):
placeholder: Optional[CustomAuthor] = Field(
default=None, description="A placeholder field for generation."
)
# meta: Optional[Meta] = None
# results: Optional[List[CustomAuthor]] = None
# group_by: Optional[List[GroupByResult]] = None
results: Optional[List[CustomAuthor]] = None
meta: Optional[Meta] = None
group_by: Optional[List[GroupByResult]] = None
class PersonBio(BaseModel):
+2 -2
View File
@@ -85,7 +85,7 @@ def generate_person_bio(
@router.get(
"/person/{id}",
operation_id="getPersonByID",
response_model=AuthorsListResponse,
response_model=model.CustomAuthorsListResponse,
summary="Searches for person by ID.",
tags=["Persons"],
)
@@ -102,7 +102,7 @@ def get_person_by_id(
),
example="topics_full,topic_share",
),
],
] = None,
):
return logic.get_person_by_id(author_id=id, include=include)
+15 -1
View File
@@ -1,4 +1,4 @@
from typing import List, Optional
from typing import List, Literal, Optional
from pydantic import BaseModel, Field
@@ -73,3 +73,17 @@ class DfgProjectPage(Page):
elements: List[DfgProjectSummary] = Field(
default_factory=list, description="The DFG projects on this page."
)
class InstitutionFunderSummary(BaseModel):
type: Literal["bund", "eu", "dfg"] = Field(
description="The type of funding data (e.g., 'bund', 'eu', 'dfg')."
)
funding_per_year: dict = Field(
default_factory=dict,
description="A dictionary mapping years to total funding amounts for that year.",
)
annual_average_over_period: float = Field(
default=0.0,
description="The average annual funding over the continuous period covered by the data.",
)
@@ -124,7 +124,7 @@ class BundProjectsSearchClient(ProjectsSearchClient):
raise ValueError("Elasticsearch INSE API key is missing in settings.")
super().__init__(
base_url=settings.elasticsearch_inse_url,
index="projects_bund",
index="projects_bund_v1",
api_key=settings.elasticsearch_inse_api_key,
)
@@ -236,24 +236,6 @@ class BundProjectsSearchClient(ProjectsSearchClient):
response = await self.make_search_request(query)
return self.response_to_bund_project_page(response, page, size)
async def get_bund_projects_by_institution_name(
self,
institution_names: List[str],
page: int,
size: int,
sort_by: str = "topic",
sort_direction: str = "asc",
) -> BundProjectPage:
query = self.bund_projects_query(
page=page,
size=size,
institution_names=institution_names,
sort_by=sort_by,
sort_direction=sort_direction,
)
response = await self.make_search_request(query)
return self.response_to_bund_project_page(response, page, size)
class EuProjectsSearchClient(ProjectsSearchClient):
def __init__(self):
+39 -2
View File
@@ -4,7 +4,12 @@ from typing import Annotated, Optional
from fastapi import APIRouter, Depends, Query, status
from inse.projects.model import BundProjectPage, DfgProjectPage, EuProjectPage
from inse.projects.model import (
BundProjectPage,
DfgProjectPage,
EuProjectPage,
InstitutionFunderSummary,
)
from inse.tags import Tags
from inse.projects import service as projects_service
from inse.projects.projects_search_client import (
@@ -15,7 +20,7 @@ from inse.projects.projects_search_client import (
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
from inse.institutions.service import get_institutions_search_client
from inse.institutions.router import get_institutions_search_client
logger = logging.getLogger(__name__)
@@ -83,6 +88,38 @@ async def get_bund_projects(
)
@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.",
operation_id="getBundFundingOverTime",
responses={
status.HTTP_200_OK: {
"description": "Successful Response",
"model": InstitutionFunderSummary,
},
status.HTTP_404_NOT_FOUND: {"description": "Institution not found"},
},
response_model_by_alias=False,
)
async def get_bund_funding_over_time(
bund_search_client: Annotated[
BundProjectsSearchClient, Depends(get_bund_search_client)
],
institutions_search_client: Annotated[
InstitutionsSearchClient, Depends(get_institutions_search_client)
],
institution_id: Annotated[
str, Query(description="The institution ID to filter by.")
],
) -> InstitutionFunderSummary:
return await projects_service.get_institution_bund_funding_over_time(
bund_search_client=bund_search_client,
institutions_search_client=institutions_search_client,
institution_id=institution_id,
)
@router.get(
"/institution/eu/search",
summary="Get EU projects.",
+85 -30
View File
@@ -1,12 +1,18 @@
import datetime
import logging
from typing import List, Optional
from typing import Dict, List, Optional
from inse.projects.projects_search_client import (
BundProjectsSearchClient,
DfgProjectsSearchClient,
EuProjectsSearchClient,
)
from inse.projects.model import BundProjectPage, DfgProjectPage, EuProjectPage
from inse.projects.model import (
BundProjectPage,
DfgProjectPage,
EuProjectPage,
InstitutionFunderSummary,
)
from inse.institutions.institutions_search_client import (
InstitutionsSearchClient,
)
@@ -29,8 +35,8 @@ async def get_bund_projects_by_institution_id(
logger.info(
f"Fetching bund projects for institution_id={institution_id}, page={page}, size={size}"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_id(institution_id)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
institution_id
)
logger.debug(
f"Found institution aliases for institution_id={institution_id}: {institution_aliases}"
@@ -60,8 +66,8 @@ async def get_eu_projects_by_institution_id(
logger.info(
f"Fetching EU projects for institution_id={institution_id}, page={page}, size={size}"
)
institution_aliases = (
await institutions_search_client.get_institution_aliases_by_id(institution_id)
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
institution_id
)
logger.debug(
f"Found institution aliases for institution_id={institution_id}: {institution_aliases}"
@@ -78,30 +84,6 @@ async def get_eu_projects_by_institution_id(
return response
async def get_bund_projects_by_institution_name(
bund_search_client: BundProjectsSearchClient,
page: int,
size: int,
institution_names: List[str] = [],
sort_by: str = "topic",
sort_direction: str = "asc",
) -> BundProjectPage:
logger.info(
f"Fetching bund projects for institution_names={institution_names}, page={page}, size={size}"
)
response = await bund_search_client.search_bund_projects(
page=page,
size=size,
institution_names=institution_names,
sort_by=sort_by,
sort_direction=sort_direction,
)
logger.debug(f"get_bund_projects_by_institution_name response: {response}")
return response
async def get_dfg_projects_by_author_id(
dfg_search_client: DfgProjectsSearchClient,
author_id: str,
@@ -131,3 +113,76 @@ async def get_dfg_projects_by_author_id(
sort_direction=sort_direction,
)
return response
async def get_institution_bund_funding_over_time(
bund_search_client: BundProjectsSearchClient,
institutions_search_client: InstitutionsSearchClient,
institution_id: str,
) -> InstitutionFunderSummary:
logger.info(f"Fetching funding over time for institution_id={institution_id}")
institution_aliases = institutions_search_client.get_institution_aliases_by_id(
institution_id
)
logger.debug(
f"Found institution aliases for institution_id={institution_id}: {institution_aliases}"
)
response = await bund_search_client.search_bund_projects(
page=0,
size=10000,
institution_names=institution_aliases,
)
funding_per_year: Dict[int, float] = {}
for project in response.elements:
funding_start = project.funding_start
funding_end = project.funding_end
funding_amount = project.grant_amount
if not funding_start or not funding_end or not funding_amount:
continue
delta = (funding_end - funding_start).days + 1
if delta <= 0:
continue
amount_per_day = funding_amount / delta
start_year = funding_start.year
end_year = funding_end.year
for year in range(start_year, end_year + 1):
if year == start_year:
year_start = funding_start
else:
year_start = datetime.date(year, 1, 1)
if year == end_year:
year_end = funding_end
else:
year_end = datetime.date(year, 12, 31)
days_in_year = (year_end - year_start).days + 1
proportional_share = days_in_year * amount_per_day
funding_per_year[year] = (
funding_per_year.get(year, 0.0) + proportional_share
)
sorted_funding_per_year: Dict[int, float] = {}
if funding_per_year:
min_year = min(funding_per_year.keys())
max_year = max(funding_per_year.keys())
for year in range(min_year, max_year + 1):
sorted_funding_per_year[year] = funding_per_year.get(year, 0.0)
total_sum = sum(sorted_funding_per_year.values())
annual_average_over_period = total_sum / len(sorted_funding_per_year)
else:
annual_average_over_period = 0.0
return InstitutionFunderSummary(
type="bund",
funding_per_year=sorted_funding_per_year,
annual_average_over_period=annual_average_over_period,
)
+178 -16
View File
@@ -337,6 +337,11 @@ Content-Type: application/json
# }
# }
###
GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_mapping
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
###
GET https://inse.nes.uni-due.de/elastic/projects_dfg_all/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
@@ -451,37 +456,157 @@ Content-Type: application/json
###
GET https://inse.nes.uni-due.de/elastic/projects_bund/_mapping
GET https://inse.nes.uni-due.de/elastic/projects_bund_v1/_mapping
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
###
GET https://inse.nes.uni-due.de/elastic/projects_bund/_search
GET https://inse.nes.uni-due.de/elastic/projects_bund_v1/_search
Authorization: ApiKey bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
Content-Type: application/json
{
"size": 10,
"from": 1000,
"size": 0,
"query": {
"match": {
"Zuwendungsempf\u00e4nger": {
"query": "Universit\u00e4t Duisburg-Essen",
"operator": "and"
}
"bool": {
"must": [
{
"bool": {
"should": [
{
"match": {
"Zuwendungsempfänger": {
"query": "university of duisburg-eßen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "university of duisburg-essen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universitaet duisburg-essen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universitaet duisburg essen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universität duisburg-essen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universitat duisburg-eßen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universitat duisburg essen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "university of duisburg essen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universitat duisburg-essen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universität duisburg-eßen",
"operator": "and"
}
}
},
{
"match": {
"Zuwendungsempfänger": {
"query": "universität duisburg essen",
"operator": "and"
}
}
}
],
"minimum_should_match": 1
}
}
]
}
},
"sort": [
{
"Thema.keyword": {
"order": "asc"
"aggs": {
"distributed_annual_amounts": {
"scripted_metric": {
"init_script": "state.years_map = [:]",
"map_script": "if (doc['funding_start'].size() == 0 || doc['funding_end'].size() == 0 || doc['Fördersumme'].size() == 0) { return; } def start = doc['funding_start'].value.toLocalDate(); def end = doc['funding_end'].value.toLocalDate(); def totalAmount = doc['Fördersumme'].value; def startYear = start.getYear(); def endYear = end.getYear(); if (startYear == endYear) { state.years_map[startYear] = state.years_map.getOrDefault(startYear, 0.0) + totalAmount; } else { long totalDays = ChronoUnit.DAYS.between(start, end) + 1; if (totalDays <= 0) return; double amountPerDay = totalAmount / (double)totalDays; for (int y = startYear; y <= endYear; y++) { def yearStart = (y == startYear) ? start : LocalDate.of(y, 1, 1); def yearEnd = (y == endYear) ? end : LocalDate.of(y, 12, 31); long daysInYear = ChronoUnit.DAYS.between(yearStart, yearEnd) + 1; double proportionalShare = daysInYear * amountPerDay; state.years_map[y] = state.years_map.getOrDefault(y, 0.0) + proportionalShare; } }",
"combine_script": "return state.years_map",
"reduce_script": "def final_map = [:]; for (state in states) { for (entry in state.entrySet()) { final_map[entry.getKey()] = final_map.getOrDefault(entry.getKey(), 0.0) + entry.getValue(); } } if (final_map.isEmpty()) { return ['funding_per_year': final_map, 'annual_average_over_period': 0.0]; } double totalSum = 0.0; for (val in final_map.values()) { totalSum += val; } double avg = totalSum / final_map.size(); return ['funding_per_year': final_map, 'annual_average_over_period': avg];"
}
}
]
}
}
###
# {
# "size": 10,
# "from": 1000,
# "query": {
# "match": {
# "Zuwendungsempf\u00e4nger": {
# "query": "Universit\u00e4t Duisburg-Essen",
# "operator": "and"
# }
# }
# },
# "sort": [
# {
# "Thema.keyword": {
# "order": "asc"
# }
# }
# ]
# }
#{'size': 10, 'from': 0, 'query': {'match': {'Zuwendungsempfänger': {'query': 'Universität Duisburg-Essen', 'operator': 'and'}}}, 'sort': [{'Thema': {'order': 'asc'}}]}
# {
@@ -688,6 +813,29 @@ GET https://project.nes.uni-due.de/elastic/openalex-authors/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
{
"query": {
"bool": {
"must": [
{
"prefix": {
"display_name.keyword": "Marcus Roth"
}
},
{
"nested": {
"path": "last_known_institutions",
"query": {
"match": {
"last_known_institutions.display_name": "University of Duisburg-Essen"
}
}
}
}
]
}
}
}
###
@@ -783,6 +931,20 @@ GET https://project.nes.uni-due.de/elastic/openalex-authors/_mapping
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
###
GET https://project.nes.uni-due.de/elastic/openalex-institutions/_search
Authorization: ApiKey am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ==
Content-Type: application/json
{
"query": {},
"size": 10,
"from": 0,
"sort": [{ "works_count": { "order": "desc" } }]
}
###
GET https://project.nes.uni-due.de/elastic/openalex-awards/_search
@@ -1,4 +1,5 @@
.gitignore
.openapi-generator-ignore
README.md
api.base.service.ts
api.module.ts
@@ -38,6 +39,7 @@ model/award.ts
model/bodyCreateUser.ts
model/bundProject.ts
model/bundProjectPage.ts
model/careerMetrics.ts
model/categoryNested.ts
model/collaborationNetwork.ts
model/collaborationNetworkEdge.ts
@@ -63,10 +65,12 @@ model/groupByResult.ts
model/hTTPValidationError.ts
model/identityGrant.ts
model/institution.ts
model/institutionFunderSummary.ts
model/institutionGeo.ts
model/institutionIds.ts
model/institutionInformation.ts
model/institutionNetworkNode.ts
model/institutionPage.ts
model/institutionsListResponse.ts
model/item.ts
model/itemCreate.ts
@@ -23,6 +23,8 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { Institution } from '../model/institution';
// @ts-ignore
import { InstitutionPage } from '../model/institutionPage';
// @ts-ignore
import { InstitutionsListResponse } from '../model/institutionsListResponse';
// @ts-ignore
import { RankingResponse } from '../model/rankingResponse';
@@ -312,4 +314,74 @@ export class InstitutionsService extends BaseService {
);
}
/**
* Searches for institutions by name.
* Searches for institutions by name with pagination.
* @endpoint get /api/inse-service/institutions/search
* @param name Institution name to search for, for example \&#39;University of Duisburg Essen\&#39;.
* @param page Page number (0-indexed).
* @param size Number of institutions per page.
* @param sortBy Field to sort by, either \&#39;relevance\&#39;, \&#39;name\&#39;, \&#39;works_count\&#39;, or \&#39;citations_count\&#39;.
* @param sortingDirection Sorting direction, either \&#39;asc\&#39; or \&#39;desc\&#39;.
* @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 searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionPage>;
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionPage>>;
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionPage>>;
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', 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>name, 'name');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>size, 'size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortingDirection, 'sorting_direction');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
}
+10 -16
View File
@@ -112,16 +112,13 @@ export class PersonsService extends BaseService {
* @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 getPersonByID(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public getPersonByID(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public getPersonByID(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public getPersonByID(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getPersonByID(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public getPersonByID(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public getPersonByID(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public getPersonByID(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getPersonByID.');
}
if (include === null || include === undefined) {
throw new Error('Required parameter include was null or undefined when calling getPersonByID.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -154,7 +151,7 @@ export class PersonsService extends BaseService {
let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
return this.httpClient.request<CustomAuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
@@ -176,16 +173,13 @@ export class PersonsService extends BaseService {
* @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 getPersonByID_1(id: string, include: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorsListResponse>;
public getPersonByID_1(id: string, include: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorsListResponse>>;
public getPersonByID_1(id: string, include: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorsListResponse>>;
public getPersonByID_1(id: string, include: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
public getPersonByID_1(id: string, include?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CustomAuthorsListResponse>;
public getPersonByID_1(id: string, include?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CustomAuthorsListResponse>>;
public getPersonByID_1(id: string, include?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CustomAuthorsListResponse>>;
public getPersonByID_1(id: string, include?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getPersonByID_1.');
}
if (include === null || include === undefined) {
throw new Error('Required parameter include was null or undefined when calling getPersonByID_1.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
@@ -218,7 +212,7 @@ export class PersonsService extends BaseService {
let localVarPath = `/api/inse-service/person/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorsListResponse>('get', `${basePath}${localVarPath}`,
return this.httpClient.request<CustomAuthorsListResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
@@ -24,6 +24,8 @@ import { DfgProjectPage } from '../model/dfgProjectPage';
import { EuProjectPage } from '../model/euProjectPage';
// @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore
import { InstitutionFunderSummary } from '../model/institutionFunderSummary';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -41,6 +43,67 @@ export class ProjectsService extends BaseService {
super(basePath, configuration);
}
/**
* Get funding over time for bund projects.
* Returns the funding over time for bund projects associated with the specified institution.
* @endpoint get /api/projects/institution/bund/funding-over-time
* @param institutionId The institution ID to filter by.
* @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 getBundFundingOverTime(institutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionFunderSummary>;
public getBundFundingOverTime(institutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionFunderSummary>>;
public getBundFundingOverTime(institutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionFunderSummary>>;
public getBundFundingOverTime(institutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (institutionId === null || institutionId === undefined) {
throw new Error('Required parameter institutionId was null or undefined when calling getBundFundingOverTime.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>institutionId, 'institution_id');
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/projects/institution/bund/funding-over-time`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionFunderSummary>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Get bund projects.
* Returns a page of bund projects based on the provided pagination parameters and optional institution filter.
+34
View File
@@ -0,0 +1,34 @@
/**
* 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 CareerMetrics {
first_publication_year?: number | null;
last_publication_year?: number | null;
career_age?: number | null;
career_span?: number | null;
career_stage?: string | null;
/**
* Number of distinct years with at least one publication.
*/
active_years?: number;
/**
* Number of publications used for career metrics.
*/
publication_count?: number;
publications_per_active_year?: number | null;
publications_per_career_year?: number | null;
years_since_last_publication?: number | null;
/**
* True if publication years look suspicious.
*/
has_suspicious_publication_years?: boolean;
}
@@ -10,9 +10,9 @@
export const CollaborationNetworkNodeType = {
author: 'author',
institution: 'institution',
work: 'work'
Author: 'author',
Institution: 'institution',
Work: 'work'
} as const;
export type CollaborationNetworkNodeType = typeof CollaborationNetworkNodeType[keyof typeof CollaborationNetworkNodeType];
+2
View File
@@ -9,6 +9,7 @@
*/
import { AuthorAffiliationsInner } from './authorAffiliationsInner';
import { AuthorParsedLongestName } from './authorParsedLongestName';
import { CareerMetrics } from './careerMetrics';
import { DehydratedInstitution } from './dehydratedInstitution';
import { AuthorCountsByYearInner } from './authorCountsByYearInner';
import { AuthorIds } from './authorIds';
@@ -35,5 +36,6 @@ export interface CustomAuthor {
created_date?: string | null;
updated_date?: string | null;
relevance_rating?: string | null;
career_metrics?: CareerMetrics | null;
}
@@ -9,13 +9,12 @@
*/
import { Meta } from './meta';
import { CustomAuthor } from './customAuthor';
import { Author } from './author';
import { GroupByResult } from './groupByResult';
export interface CustomAuthorsListResponse {
meta?: Meta | null;
results?: Array<Author> | null;
results?: Array<CustomAuthor> | null;
group_by?: Array<GroupByResult> | null;
placeholder?: CustomAuthor | null;
}
@@ -0,0 +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.
*/
export interface InstitutionFunderSummary {
/**
* The type of funding data (e.g., \'bund\', \'eu\', \'dfg\').
*/
type: InstitutionFunderSummary.TypeEnum;
/**
* A dictionary mapping years to total funding amounts for that year.
*/
funding_per_year?: object;
/**
* The average annual funding over the continuous period covered by the data.
*/
annual_average_over_period?: number;
}
export namespace InstitutionFunderSummary {
export const TypeEnum = {
Bund: 'bund',
Eu: 'eu',
Dfg: 'dfg'
} as const;
export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum];
}
@@ -0,0 +1,31 @@
/**
* 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 { Institution } from './institution';
export interface InstitutionPage {
/**
* List of institutions in the current page.
*/
elements?: Array<Institution>;
/**
* Current page number. (0-indexed)
*/
page?: number;
/**
* Number of institutions per page.
*/
size?: number;
/**
* Total number of institutions matching the search criteria.
*/
total?: number;
}
+3
View File
@@ -19,6 +19,7 @@ export * from './award';
export * from './bodyCreateUser';
export * from './bundProject';
export * from './bundProjectPage';
export * from './careerMetrics';
export * from './categoryNested';
export * from './collaborationNetwork';
export * from './collaborationNetworkEdge';
@@ -44,10 +45,12 @@ export * from './groupByResult';
export * from './hTTPValidationError';
export * from './identityGrant';
export * from './institution';
export * from './institutionFunderSummary';
export * from './institutionGeo';
export * from './institutionIds';
export * from './institutionInformation';
export * from './institutionNetworkNode';
export * from './institutionPage';
export * from './institutionsListResponse';
export * from './item';
export * from './itemCreate';
+3
View File
@@ -40,6 +40,7 @@ export const appConfig: ApplicationConfig = {
const router = inject(Router);
const errorService = inject(ErrorService);
if (
router.url.includes('/error') ||
router.currentNavigation()?.extractedUrl.toString().includes('/error')
@@ -51,6 +52,8 @@ export const appConfig: ApplicationConfig = {
return;
}
console.error('Fehler beim Navigieren:', navigationError);
const error = navigationError.error;
let errorMessage: string = 'Unbekannter Fehler';
if (error instanceof HttpErrorResponse) {
+30 -8
View File
@@ -8,6 +8,9 @@ import { institutionResolver } from './resolvers/institution.resolver';
import { bundProjectsResolver } from './resolvers/bund-projects.resolver';
import { euProjectsResolver } from './resolvers/eu-projects.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
import { institutionsResolver } from './resolvers/institutions.resolver';
import { bundProjectsFundingResolver } from './resolvers/bund-projects-funding.resolver';
export const routes: Routes = [
{
path: '',
@@ -170,6 +173,24 @@ export const routes: Routes = [
},
],
},
{
path: 'institutions',
canActivate: [userGuard],
loadComponent: () =>
import('./modules/institutions/institutions.component').then(
(mod) => mod.InstitutionsComponent,
),
resolve: {
institutionPage: institutionsResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['search', 'page', 'size', 'sort_by', 'sorting_order'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
},
{
path: 'institution/:institutionId',
canActivate: [userGuard],
@@ -193,6 +214,13 @@ export const routes: Routes = [
(mod) => mod.InstitutionOverviewComponent,
),
},
{
path: 'publications',
loadComponent: () =>
import('./modules/institution-publications/institution-publications.component').then(
(mod) => mod.InstitutionPublicationsComponent,
),
},
{
path: 'projects',
loadComponent: () => {
@@ -203,6 +231,7 @@ export const routes: Routes = [
resolve: {
bundProjectPage: bundProjectsResolver,
euProjectPage: euProjectsResolver,
bundProjectsFunding: bundProjectsFundingResolver,
},
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction', 'search'];
@@ -212,14 +241,7 @@ export const routes: Routes = [
);
},
},
],
runGuardsAndResolvers: (from, to) => {
const keys = ['page', 'size', 'sort_by', 'sort_direction'];
return keys.some(
(key) => from.queryParamMap.get(key) !== to.queryParamMap.get(key),
);
},
]
},
{
path: 'error',
@@ -0,0 +1 @@
<div echarts [options]="options"></div>
@@ -0,0 +1,153 @@
import { Component, effect, input } from '@angular/core';
import * as echarts from 'echarts/core';
import { EChartsOption } from 'echarts';
import { GridComponent, LegendComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { NgxEchartsDirective } from 'ngx-echarts';
import { InstitutionFunderSummary } from '../../api';
echarts.use([GridComponent, CanvasRenderer, LegendComponent]);
type FunderData = {
funderName: string;
fundingMap: Record<number, number>;
};
@Component({
selector: 'app-institution-projects-funding-graph',
imports: [NgxEchartsDirective],
templateUrl: './institution-projects-funding-graph.component.html',
styleUrl: './institution-projects-funding-graph.component.scss',
})
export class InstitutionProjectsFundingGraphComponent {
options!: EChartsOption;
fundings = input.required<InstitutionFunderSummary[]>();
constructor() {
effect(() => {
const fundings = this.fundings();
this.generateChartOptions(fundings);
});
}
generateChartOptions(fundings: InstitutionFunderSummary[]): void {
const floorToTwoDecimals = (value: number): string => {
const floored = Math.floor(value * 100) / 100;
return floored.toLocaleString(undefined, {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
};
const yearsSet = new Set<string>();
fundings.forEach((series) => {
if (series.funding_per_year) {
Object.keys(series.funding_per_year).forEach((year) =>
yearsSet.add(year),
);
}
});
const xAxisYears = Array.from(yearsSet).sort(
(a, b) => Number(a) - Number(b),
);
const currentYearStr = new Date().getFullYear().toString();
const chartSeries = fundings.map((series, index) => {
const fundingMap = (series.funding_per_year || {}) as Record<
string,
number
>;
const dataPoints = xAxisYears.map((year) => fundingMap[year] ?? 0);
const baseSeries: any = {
name: series.type.toUpperCase(),
type: 'line',
stack: 'TotalInstitutionalFunding',
areaStyle: {},
emphasis: { focus: 'series' },
data: dataPoints,
};
if (index === 0) {
baseSeries.markLine = {
symbol: ['none', 'none'],
silent: true,
label: {
show: true,
position: 'end',
formatter: 'Aktuelles Jahr',
backgroundColor: '#333',
color: '#fff',
padding: [4, 6],
borderRadius: 4,
},
lineStyle: {
color: '#ff4d4f',
type: 'dashed',
width: 2,
},
data: [
{
xAxis: currentYearStr,
},
],
};
}
return baseSeries;
});
this.options = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
label: { backgroundColor: '#6a7985' },
},
valueFormatter: (value) => {
const numericValue = Array.isArray(value) ? 0 : Number(value ?? 0);
return floorToTwoDecimals(numericValue);
},
},
legend: {
data: fundings.map((series) => series.type.toUpperCase()),
top: '10%',
},
grid: {
left: '4%',
right: '4%',
bottom: '5%',
containLabel: true,
},
xAxis: [
{
type: 'category',
boundaryGap: false,
data: xAxisYears,
},
],
yAxis: [
{
type: 'value',
axisLabel: {
formatter: (value: number) =>
value.toLocaleString(undefined, {
style: 'currency',
currency: 'EUR',
maximumFractionDigits: 0,
}),
},
},
],
series: chartSeries,
};
}
}
@@ -1,48 +1,89 @@
<div class="content">
<h3>Projekte</h3>
<mat-card appearance="outlined">
<mat-card-content>
<mat-form-field style="width: 100%">
<mat-label>Suche nach Themen</mat-label>
<input
matInput
type="search"
[debounceTime]="300"
[(debouncedValue)]="urlSearchTerm"
(debouncedValueChange)="handleSearchTermChange($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearchTerm()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<mat-tab-group
[selectedIndex]="tabIndex()"
(selectedTabChange)="selectedTabChange($event)">
<mat-tab label="EU">
<app-data-table
[data]="euProjectData"
[columns]="euProjectColumns"
[activeSortKey]="urlSortKey()"
[sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab>
<mat-tab label="Bund">
<app-data-table
[data]="bundProjectData"
[columns]="bundProjectColumns"
[activeSortKey]="urlSortKey()"
[sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab>
</mat-tab-group>
<mat-paginator
[length]="this.pageTotal()"
[pageSize]="this.pageSize()"
[pageIndex]="this.pageIndex()"
(page)="handlePageChange($event)" />
</mat-card-content>
</mat-card>
<div class="funding-area">
<mat-card appearance="outlined">
<mat-card-content>
<mat-form-field style="width: 100%">
<mat-label>Suche nach Themen</mat-label>
<input
matInput
type="search"
[debounceTime]="300"
[(debouncedValue)]="urlSearchTerm"
(debouncedValueChange)="handleSearchTermChange($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearchTerm()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<mat-tab-group
[selectedIndex]="tabIndex()"
(selectedTabChange)="selectedTabChange($event)">
<mat-tab label="EU">
<app-data-table
[data]="euProjectData"
[columns]="euProjectColumns"
[activeSortKey]="urlSortKey()"
[sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab>
<mat-tab label="Bund">
<app-data-table
[data]="bundProjectData"
[columns]="bundProjectColumns"
[activeSortKey]="urlSortKey()"
[sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab>
</mat-tab-group>
<mat-paginator
[length]="this.pageTotal()"
[pageSize]="this.pageSize()"
[pageIndex]="this.pageIndex()"
(page)="handlePageChange($event)" />
</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()]" />
</mat-card-content>
</mat-card>
<div class="funding-info-cards">
<app-person-network-info-card
[description]="'Gesamte Förderung durch Bund'"
[value]="
(bundTotalFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-person-network-info-card
[description]="'Durchschnittliche jährliche Förderung durch Bund'"
[value]="
(bundAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
<app-person-network-info-card
[description]="'Gesamte Förderung durch die Europäische Union'"
[value]="
(123456789 | currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ??
undefined
" />
<app-person-network-info-card
[description]="
'Durchschnittliche jährliche Förderung durch die Europäische Union'
"
[value]="
(12345 | currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
" />
</div>
</div>
</div>
</div>
<ng-template #fundingStartTmp let-row>
@@ -6,3 +6,26 @@ mat-card,
mat-paginator {
background-color: var(--sg-background);
}
.funding-area {
display: flex;
flex-direction: column;
gap: 1rem;
}
.funding-info-section {
display: flex;
flex-direction: column;
gap: 1rem;
}
.funding-info-cards {
display: flex;
flex-direction: row;
gap: 1rem;
app-person-network-info-card {
width: 100%;
height: 100%;
}
}
@@ -14,6 +14,7 @@ import {
BundProjectPage,
EuProject,
EuProjectPage,
InstitutionFunderSummary,
} from '../../api';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
@@ -31,6 +32,8 @@ import { Sort, SortDirection } from '@angular/material/sort';
import { DebounceDirective } from '../../directives/debounce.directive';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component';
import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component';
type BundProjectRow = {
topic: string;
@@ -62,6 +65,8 @@ type EuProjectRow = {
DebounceDirective,
MatIconModule,
MatButtonModule,
InstitutionProjectsFundingGraphComponent,
PersonNetworkInfoCardComponent,
],
templateUrl: './institution-projects.component.html',
styleUrl: './institution-projects.component.scss',
@@ -79,6 +84,20 @@ export class InstitutionProjectsComponent implements OnInit {
bundProjectColumns: GenericColumn<BundProjectRow>[] = [];
bundProjectData: BundProjectRow[] = [];
bundProjectsFunding = input.required<InstitutionFunderSummary>();
bundTotalFunding = computed(() => {
const funding = this.bundProjectsFunding();
return Object.values(
funding.funding_per_year as Record<string, number>,
).reduce((sum, yearFunding) => sum + yearFunding, 0);
});
bundAverageAnnualFunding = computed(() => {
const funding = this.bundProjectsFunding();
return funding.annual_average_over_period ?? 0;
});
urlSortKey = signal<string>('');
urlSortDirection = signal<SortDirection>('');
urlSearchTerm = signal<string>('');
@@ -118,11 +137,15 @@ export class InstitutionProjectsComponent implements OnInit {
const searchTerm = this.urlSearchTerm();
if (searchTerm) {
this.router.navigate([], {
queryParams: { search: searchTerm },
queryParams: { search: searchTerm, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
});
effect(() => {
console.log('Funding over time data:', this.bundProjectsFunding());
});
}
readonly queryParams = toSignal(this.activatedRoute.queryParamMap, {
@@ -286,14 +309,14 @@ export class InstitutionProjectsComponent implements OnInit {
handleSearchTermChange(newTerm: string): void {
this.router.navigate([], {
queryParams: { search: newTerm },
queryParams: { search: newTerm, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
clearSearchTerm(): void {
this.router.navigate([], {
queryParams: { search: null },
queryParams: { search: null, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
@@ -0,0 +1 @@
<p>institution-publications works!</p>
@@ -0,0 +1,11 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-institution-publications',
imports: [],
templateUrl: './institution-publications.component.html',
styleUrl: './institution-publications.component.scss',
})
export class InstitutionPublicationsComponent {
}
@@ -26,13 +26,14 @@ export class InstitutionComponent implements OnInit {
links = [
{ label: 'Übersicht', path: 'overview', disabled: false },
{ label: 'Publikationen', path: 'publications', disabled: false },
{
label: 'Projekte',
path: 'projects',
disabled: false,
queryParams: {
project_tab: 'bund',
page: 1,
page: 0,
size: 10,
search: '',
sort_by: 'topic',
@@ -0,0 +1,116 @@
<div class="content">
<h1>Passende Institutionen finden</h1>
<mat-divider />
<div class="search-and-sorting">
<mat-form-field style="width: 100%">
<mat-label>Suche nach Namen</mat-label>
<input
matInput
type="search"
[debounceTime]="300"
[(debouncedValue)]="urlSearchTerm"
(debouncedValueChange)="handleSearchTermChange($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearchTerm()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<div class="sorting">
<select (change)="handleSortFieldChange($event)" [value]="urlSortBy()">
<option value="relevance">Relevanz</option>
<option value="name">Name</option>
<option value="works_count">Anzahl Publikationen</option>
<option value="citations_count">Anzahl Zitationen</option>
</select>
<select
(change)="handleSortOrderChange($event)"
[value]="urlSortingOrder()">
<option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option>
</select>
</div>
</div>
<mat-divider />
@let institutionPageValue = institutionPage();
@if (
institutionPageValue.elements && institutionPageValue.elements.length > 0
) {
<div class="cards">
@for (institution of institutionPageValue.elements; track $index) {
@let institutionId = extractInstitutionId(institution);
<mat-card
class="card"
appearance="outlined"
[routerLink]="
institution.id
? ['/institution', institution.id.split('/').pop() ?? '']
: null
">
<mat-card-header>
<mat-card-title>{{ getDisplayName(institution) }}</mat-card-title>
<mat-card-subtitle
>{{ institution.geo?.city }},
{{ institution.geo?.country }}</mat-card-subtitle
>
</mat-card-header>
<mat-card-content class="card-content">
<mat-divider />
<div class="card-metadata">
<span>Publikationen: {{ institution.works_count }}</span>
<span>Zitationen: {{ institution.cited_by_count }}</span>
</div>
<mat-divider />
</mat-card-content>
<mat-card-footer>
<mat-card-actions>
<a
mat-button
[routerLink]="['/institution', institutionId, 'overview']"
(click)="$event.stopPropagation()">
<mat-icon>info</mat-icon>
Übersicht
</a>
<a
mat-button
[routerLink]="['/institution', institutionId, 'publications']"
(click)="$event.stopPropagation()">
<mat-icon>article</mat-icon>
Publikationen
</a>
<a
mat-button
[routerLink]="['/institution', institutionId, 'projects']"
(click)="$event.stopPropagation()">
<mat-icon>work</mat-icon>
Projekte
</a>
</mat-card-actions>
</mat-card-footer>
</mat-card>
}
</div>
} @else {
<div class="no-results">
<p>Keine passenden Institutionen gefunden.</p>
</div>
}
<mat-divider />
<mat-paginator
[length]="institutionPageValue.total"
[pageSize]="institutionPageValue.size"
[pageSizeOptions]="[10, 20, 50]"
[pageIndex]="institutionPageValue.page"
(page)="handlePageChange($event)">
</mat-paginator>
</div>
@@ -0,0 +1,99 @@
.content {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
.sorting {
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
.sorting select {
padding: 0.75rem;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
font-size: 1rem;
}
.sorting select:hover {
cursor: pointer;
}
.cards {
display: grid;
gap: 1.5rem;
grid-template-columns: repeat(4, 1fr);
padding: 0 1rem;
}
@media (max-width: 900px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 600px) {
.cards {
grid-template-columns: 1fr;
}
}
mat-paginator {
background-color: var(--sg-background);
}
.card {
padding: 0.5rem;
background-color: var(--sg-background);
transition: transform 0.3s ease;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.card:hover {
cursor: pointer;
transform: scale(1.05);
}
.card-content {
display: flex;
flex-direction: column;
justify-content: flex-end;
gap: 0.5rem;
flex: 1;
}
.card-metadata {
display: flex;
flex-direction: column;
gap: 0.2rem;
font-size: 0.9rem;
color: var(--sg-text-secondary);
}
mat-card-actions {
padding-top: 0.5rem;
display: flex;
gap: 0.5rem;
}
mat-card-actions a {
width: 100%;
text-decoration: none;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
}
.no-results {
text-align: center;
padding: 2rem;
color: var(--sg-text-secondary);
}
.search-and-sorting {
padding: 0 1rem;
}
@@ -0,0 +1,108 @@
import { Component, effect, input, signal } from '@angular/core';
import { Institution, InstitutionPage } from '../../api';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatInputModule } from '@angular/material/input';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon';
import { DebounceDirective } from '../../directives/debounce.directive';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatDividerModule } from '@angular/material/divider';
@Component({
selector: 'app-institutions',
imports: [
MatButtonModule,
MatCardModule,
MatInputModule,
MatIconModule,
DebounceDirective,
MatPaginator,
MatDividerModule,
RouterModule,
],
templateUrl: './institutions.component.html',
styleUrl: './institutions.component.scss',
})
export class InstitutionsComponent {
institutionPage = input.required<InstitutionPage>();
urlSearchTerm = signal<string>('');
urlSortBy = signal<string>('relevance');
urlSortingOrder = signal<string>('desc');
constructor(
private readonly activatedRoute: ActivatedRoute,
private readonly router: Router,
) {
this.activatedRoute.queryParams
.pipe(takeUntilDestroyed())
.subscribe((params) => {
this.urlSearchTerm.set(params['search'] || '');
this.urlSortBy.set(params['sort_by'] || 'relevance');
this.urlSortingOrder.set(params['sorting_order'] || 'desc');
});
effect(() => {
const searchTerm = this.urlSearchTerm();
this.router.navigate([], {
queryParams: { search: searchTerm },
queryParamsHandling: 'merge',
});
});
}
handleSearchTermChange(newTerm: string): void {
this.router.navigate([], {
queryParams: { search: newTerm },
queryParamsHandling: 'merge',
});
}
clearSearchTerm(): void {
this.router.navigate([], {
queryParams: { search: null },
queryParamsHandling: 'merge',
});
}
handlePageChange(event: PageEvent): void {
this.router.navigate([], {
queryParams: { page: event.pageIndex, size: event.pageSize },
queryParamsHandling: 'merge',
});
}
extractInstitutionId(institution: Institution): string {
return institution.id?.split('/').pop() ?? '';
}
handleSortFieldChange(event: Event): void {
const selectElement = event.target as HTMLSelectElement;
const sortField = selectElement.value;
this.router.navigate([], {
queryParams: { sort_by: sortField },
queryParamsHandling: 'merge',
});
}
handleSortOrderChange(event: Event): void {
const selectElement = event.target as HTMLSelectElement;
const sortOrder = selectElement.value;
this.router.navigate([], {
queryParams: { sorting_order: sortOrder },
queryParamsHandling: 'merge',
});
}
getDisplayName(institution: Institution): string {
const primary = institution.display_name?.trim();
if (primary && primary.length > 0) return primary;
const alt = institution.display_name_alternatives?.[0]?.trim();
if (alt && alt.length > 0) return alt;
return 'Unbekannte Institution';
}
}
@@ -5,15 +5,7 @@
{{ getInitials(person.display_name) }}
</div>
<div class="header-main">
<div class="rating-and-bookmark">
@if (person.relevance_rating) {
<span
[skText]="loading"
class="suitability-badge"
[ngClass]="getRatingClass(person.relevance_rating)">
{{ person.relevance_rating }}
</span>
}
<div class="bookmark">
<button
class="bookmark-btn"
(click)="
@@ -26,16 +18,20 @@
}}</mat-icon>
</button>
</div>
<h2 [skText]="loading" class="person-name">{{ person.display_name }}</h2>
<h2
[skText]="loading"
class="person-name"
[title]="person.display_name ?? ''">
{{ person.display_name ?? '' }}
</h2>
<p [skText]="loading" class="person-id">
{{ getDistinguishingId(person) }}
{{ getDistinguishingId(person) ?? '' }}
</p>
<p [skText]="loading" class="stats">
Publikationen: {{ person.works_count }} · Zitationen:
{{ person.cited_by_count }}
{{ getStatsString() }}
</p>
<p [skText]="loading" class="stats">
h_index: {{person.summary_stats?.h_index }}
<p [skText]="loading" class="stats">
{{ getHIndexString() }}
</p>
</div>
</a>
@@ -60,9 +56,12 @@
"
>apartment</mat-icon
>
<span [skText]="loading" style="vertical-align: middle">{{
inst.display_name ?? '' | truncate: 30
}}</span>
<span
[skText]="loading"
class="institution-name"
style="vertical-align: middle"
>{{ inst.display_name ?? '' }}</span
>
@if (inst.country_code && !loading) {
<img
alt=""
@@ -71,6 +70,7 @@
height="10"
style="margin-left: 6px; vertical-align: middle" />
<span
class="country-code"
style="font-size: 9px; margin-left: 2px; vertical-align: middle"
>{{ inst.country_code.toUpperCase() }}</span
>
@@ -108,6 +108,11 @@
font-size: 16px;
font-weight: 600;
color: var(--sg-text);
min-height: 24px;
line-height: 24px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.institution {
display: flex;
@@ -133,6 +138,26 @@
display: inline-flex;
align-items: center;
transition: all 0.2s ease;
max-width: 100%;
box-sizing: border-box;
.institution-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
min-width: 0;
flex: 1;
}
.flag-img {
flex-shrink: 0;
}
.country-code {
display: inline-block;
flex-shrink: 0;
white-space: nowrap;
}
&:hover {
background: var(--sg-primary);
@@ -143,13 +168,15 @@
.flag-img {
border: 1px solid;
vertical-align: -10px;
vertical-align: middle;
}
.person-id {
margin: 2px 0 0;
font-size: 10px;
color: var(--sg-text-soft);
min-height: 15px;
line-height: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
@@ -159,6 +186,11 @@
margin: 4px 0 0;
font-size: 10px;
color: var(--sg-text-muted);
min-height: 15px;
line-height: 15px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.card-body {
@@ -186,6 +218,11 @@
border-radius: 4px;
cursor: pointer;
transition: all 0.2s ease;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
box-sizing: border-box;
&:hover {
background: var(--sg-primary-soft);
@@ -3,18 +3,11 @@ import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api';
import { TruncatePipe } from '../../shared/pipes/truncate.pipe';
import { SkTextDirective } from '../../custom-directives/sk-text.directive';
@Component({
selector: 'app-person-card',
standalone: true,
imports: [
CommonModule,
RouterLink,
MatIconModule,
TruncatePipe,
SkTextDirective,
],
imports: [CommonModule, RouterLink, MatIconModule, SkTextDirective],
templateUrl: './person-card.component.html',
styleUrl: './person-card.component.scss',
})
@@ -62,8 +55,11 @@ export class PersonCardComponent {
if (topic.field?.display_name) parts.push(topic.field.display_name);
if (topic.subfield?.display_name) parts.push(topic.subfield.display_name);
if (parts.length === 0) return topic.display_name || '';
return parts.join(' - ');
const path = parts.join(' - ');
if (topic.display_name) {
return path ? `${topic.display_name}\n(${path})` : topic.display_name;
}
return path;
}
getDistinguishingId(person: CustomAuthor): string {
@@ -74,6 +70,30 @@ export class PersonCardComponent {
return '';
}
getStatsString(): string {
const works = this.person.works_count;
const citations = this.person.cited_by_count;
const hasWorks = works !== undefined && works !== null;
const hasCitations = citations !== undefined && citations !== null;
if (hasWorks && hasCitations) {
return `Publikationen: ${works} · Zitationen: ${citations}`;
} else if (hasWorks) {
return `Publikationen: ${works}`;
} else if (hasCitations) {
return `Zitationen: ${citations}`;
}
return '';
}
getHIndexString(): string {
const hIndex = this.person.summary_stats?.h_index;
if (hIndex !== undefined && hIndex !== null) {
return `h_index: ${hIndex}`;
}
return '';
}
toggleBookmark(): void {
this.bookmarkToggle.emit(this.person);
}
@@ -0,0 +1,13 @@
import { ResolveFn } from '@angular/router';
import { InstitutionFunderSummary, ProjectsService } from '../api';
import { inject } from '@angular/core';
export const bundProjectsFundingResolver: ResolveFn<
InstitutionFunderSummary
> = (route, state) => {
let institutionId = route.paramMap.get('institutionId');
if (!institutionId) {
institutionId = route.parent?.paramMap.get('institutionId') ?? null;
}
return inject(ProjectsService).getBundFundingOverTime(institutionId || '');
};
@@ -0,0 +1,29 @@
import { inject } from '@angular/core';
import { ResolveFn } from '@angular/router';
import { InstitutionPage, InstitutionsService } from '../api';
export const institutionsResolver: ResolveFn<InstitutionPage> = (
route,
state,
) => {
const queryParamMap = route.queryParamMap;
const query = queryParamMap.get('search') ?? '';
const page = Number(queryParamMap.get('page') ?? '0');
const pageSize = Number(queryParamMap.get('size') ?? '10');
const sortBy = (queryParamMap.get('sort_by') ?? 'works_count') as
| 'relevance'
| 'name'
| 'works_count'
| 'citations_count';
const sortOrder = (queryParamMap.get('sorting_order') ?? 'desc') as
| 'asc'
| 'desc';
return inject(InstitutionsService).searchInstitutionsByName(
query,
page,
pageSize,
sortBy,
sortOrder,
);
};
@@ -80,6 +80,7 @@ mat-toolbar.main {
width: var(--sg-sidebar-width);
background: var(--sg-surface);
border-right: 1px solid var(--sg-border);
border-radius: 0;
box-shadow: none;
}
@@ -37,6 +37,19 @@ export class AppMenuComponent {
queryParams: { institutionName: this.credentialService.organizationName.value },
disabled: false,
},
{
label: 'Institutionen',
icon: 'apartment',
route: '/institutions',
disabled: false,
queryParams: {
search: '',
page: 0,
size: 10,
sort_by: 'works_count',
sorting_order: 'desc',
},
},
];
constructor(