refactor(dashboard): split dashboard logic into dedicated services
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/head This commit looks good
- add separate services for top authors, project statuses and topic treemaps - extract shared project ID and statistics logic - move common period and institution helpers into common module - add individual top-author API routes - load top-author analyses independently in the frontend - remove unused dashboard code and helper functions - reduce the main dashboard service to general statistics and topic visualizations
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
import hashlib
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.projects import service as projects_service
|
||||
|
||||
from .model import BundProjectTopics, DfgProjectKeyword, DfgProjectTopic
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bund_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> BundProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.search_bund_projects_with_filters(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
executing_agency=None,
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
project_ids.update(
|
||||
project.funding_code
|
||||
for project in projects.elements
|
||||
if project.funding_code
|
||||
)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
if project_ids:
|
||||
mapping_project_ids = sorted(
|
||||
hashlib.sha256(project_id.encode("utf-8")).hexdigest()
|
||||
for project_id in project_ids
|
||||
)
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.PROJECTS_BUND_TOPICS),
|
||||
query={"terms": {"project_id": mapping_project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return BundProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -0,0 +1,92 @@
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
|
||||
DashboardPeriod = tuple[int | None, int | None]
|
||||
|
||||
|
||||
def dashboard_period(
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardPeriod:
|
||||
if from_year is not None and to_year is not None and from_year > to_year:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="from_year must be less than or equal to to_year.",
|
||||
)
|
||||
return from_year, to_year
|
||||
|
||||
|
||||
def project_overlap_filter(
|
||||
start_field: str,
|
||||
end_field: str,
|
||||
period: DashboardPeriod,
|
||||
*,
|
||||
missing_end_is_ongoing: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
from_year, to_year = period
|
||||
filters: list[dict[str, Any]] = []
|
||||
if to_year is not None:
|
||||
filters.append({"range": {start_field: {"lte": to_year}}})
|
||||
if from_year is not None:
|
||||
end_filter: dict[str, Any] = {"range": {end_field: {"gte": from_year}}}
|
||||
if missing_end_is_ongoing:
|
||||
end_filter = {
|
||||
"bool": {
|
||||
"should": [
|
||||
end_filter,
|
||||
{"bool": {"must_not": {"exists": {"field": end_field}}}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
filters.append(end_filter)
|
||||
return {"bool": {"filter": filters}} if filters else None
|
||||
|
||||
|
||||
def project_boundary_year_filter(
|
||||
start_field: str,
|
||||
end_field: str,
|
||||
period: DashboardPeriod,
|
||||
date_format: Literal["iso", "de", "year"],
|
||||
) -> dict[str, Any] | None:
|
||||
from_year, to_year = period
|
||||
filters: list[dict[str, Any]] = []
|
||||
if to_year is not None:
|
||||
if date_format == "year":
|
||||
filters.append({"range": {start_field: {"lte": to_year}}})
|
||||
else:
|
||||
last_day = (
|
||||
f"{to_year}-12-31" if date_format == "iso" else f"31.12.{to_year}"
|
||||
)
|
||||
filters.append({"range": {start_field: {"lte": last_day}}})
|
||||
if from_year is not None:
|
||||
if date_format == "year":
|
||||
filters.append({"range": {end_field: {"gte": from_year}}})
|
||||
else:
|
||||
first_day = (
|
||||
f"{from_year}-01-01" if date_format == "iso" else f"01.01.{from_year}"
|
||||
)
|
||||
filters.append({"range": {end_field: {"gte": first_day}}})
|
||||
return {"bool": {"filter": filters}} if filters else None
|
||||
|
||||
|
||||
def normalize_institution_id(value: str) -> str:
|
||||
return (
|
||||
value
|
||||
if value.startswith("https://openalex.org/")
|
||||
else f"https://openalex.org/{value}"
|
||||
)
|
||||
|
||||
|
||||
def raw_institution_id(value: str) -> str:
|
||||
return normalize_institution_id(value).removeprefix("https://openalex.org/")
|
||||
|
||||
|
||||
def institution_works_query(institution_id: str) -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"term": {"authorships.institutions.id": institution_id}},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .model import DfgProjectKeyword, DfgProjectTopic, DfgProjectTopics
|
||||
from .common import normalize_institution_id as _normalize_institution_id
|
||||
from .project_ids_service import _get_dfg_project_ids_from_projects_service
|
||||
|
||||
|
||||
async def get_dashboard_dfg_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
if project_ids:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.PROJECTS_DFG_OPENALEX_TOPICS),
|
||||
query={"terms": {"project_id": project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return DfgProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -0,0 +1,109 @@
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .model import DfgProjectKeyword, DfgProjectTopic, EuProjectTopics
|
||||
from .common import normalize_institution_id as _normalize_institution_id
|
||||
from .project_ids_service import _get_eu_project_ids_from_projects_service
|
||||
|
||||
|
||||
async def get_dashboard_eu_topics(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> EuProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_eu_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
if project_ids:
|
||||
mapping_indices = (
|
||||
ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING,
|
||||
ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS,
|
||||
)
|
||||
for mapping_index in mapping_indices:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(mapping_index),
|
||||
query={"terms": {"project_id": project_ids}},
|
||||
source=["project_id", "keyword", "topic_matches"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
source = hit.get("_source", {})
|
||||
project_id = str(source.get("project_id") or "")
|
||||
if not project_id:
|
||||
continue
|
||||
keyword = str(source.get("keyword") or "").strip()
|
||||
matched_project_ids.add(project_id)
|
||||
for match in source.get("topic_matches", []):
|
||||
topic_id = str(match.get("topic_id") or "")
|
||||
if not topic_id:
|
||||
continue
|
||||
topic = topics.setdefault(
|
||||
topic_id,
|
||||
{
|
||||
"id": topic_id,
|
||||
"name": str(match.get("topic_display_name") or topic_id),
|
||||
"subfield": match.get("subfield"),
|
||||
"field": match.get("field"),
|
||||
"domain": match.get("domain"),
|
||||
"project_ids": set(),
|
||||
"keywords": {},
|
||||
},
|
||||
)
|
||||
topic["project_ids"].add(project_id)
|
||||
if keyword:
|
||||
topic["keywords"].setdefault(keyword, set()).add(project_id)
|
||||
|
||||
field_project_ids: dict[str, set[str]] = defaultdict(set)
|
||||
subfield_project_ids: dict[tuple[str, str], set[str]] = defaultdict(set)
|
||||
for topic in topics.values():
|
||||
field_name = str(topic["field"] or "")
|
||||
subfield_name = str(topic["subfield"] or "")
|
||||
field_project_ids[field_name].update(topic["project_ids"])
|
||||
subfield_project_ids[(field_name, subfield_name)].update(topic["project_ids"])
|
||||
|
||||
topic_list = [
|
||||
DfgProjectTopic(
|
||||
id=topic["id"],
|
||||
name=topic["name"],
|
||||
subfield=topic["subfield"],
|
||||
field=topic["field"],
|
||||
domain=topic["domain"],
|
||||
project_count=len(topic["project_ids"]),
|
||||
field_project_count=len(field_project_ids[str(topic["field"] or "")]),
|
||||
subfield_project_count=len(
|
||||
subfield_project_ids[
|
||||
(str(topic["field"] or ""), str(topic["subfield"] or ""))
|
||||
]
|
||||
),
|
||||
keywords=sorted(
|
||||
[
|
||||
DfgProjectKeyword(
|
||||
name=keyword,
|
||||
project_count=len(keyword_project_ids),
|
||||
)
|
||||
for keyword, keyword_project_ids in topic["keywords"].items()
|
||||
],
|
||||
key=lambda entry: (-entry.project_count, entry.name),
|
||||
),
|
||||
)
|
||||
for topic in topics.values()
|
||||
]
|
||||
topic_list.sort(key=lambda topic: (-topic.project_count, topic.name, topic.id))
|
||||
return EuProjectTopics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
project_count=len(project_ids),
|
||||
matched_project_count=len(matched_project_ids),
|
||||
topics=topic_list,
|
||||
)
|
||||
@@ -98,6 +98,11 @@ class TopAuthorStatistics(BaseModel):
|
||||
news: list[TopAuthor]
|
||||
|
||||
|
||||
class TopAuthorAnalysis(BaseModel):
|
||||
institution_id: str
|
||||
authors: list[TopAuthor]
|
||||
|
||||
|
||||
class TopicHeatmapValue(BaseModel):
|
||||
year: int
|
||||
count: int
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.model import EuCordisProjectType
|
||||
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Returns every matching DFG project ID through the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.get_dfg_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=(
|
||||
[str(year) for year in range(1900, period[1] + 1)]
|
||||
if period[1] is not None
|
||||
else None
|
||||
),
|
||||
funding_end_years=(
|
||||
[str(year) for year in range(period[0], 2101)]
|
||||
if period[0] is not None
|
||||
else None
|
||||
),
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
|
||||
|
||||
async def _get_eu_project_ids_from_projects_service(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
"""Loads all organization EU project IDs from the canonical project service."""
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
page_size = 1000
|
||||
page_number = 0
|
||||
project_ids: set[str] = set()
|
||||
|
||||
while True:
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(institution_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=page_number,
|
||||
size=page_size,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
project_ids.update(project.id for project in projects.elements if project.id)
|
||||
if len(project_ids) >= projects.total or not projects.elements:
|
||||
break
|
||||
page_number += 1
|
||||
|
||||
return sorted(project_ids)
|
||||
@@ -0,0 +1,122 @@
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.model import EuCordisProjectType
|
||||
|
||||
from .common import (
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
from .model import DashboardStatisticValue
|
||||
|
||||
|
||||
async def get_dashboard_eu_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.search_eu_cordis_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_ids=None,
|
||||
organization_ids=None,
|
||||
organization_names=None,
|
||||
project_types=list(EuCordisProjectType),
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
framework_programmes=None,
|
||||
funding_schemes=None,
|
||||
statuses=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.search_bund_projects_with_filters(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
executing_agency=None,
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
title=None,
|
||||
keywords=None,
|
||||
funding_arts=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
countries=None,
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.get_dfg_projects(
|
||||
institutions_search_client=InstitutionsSearchClient(),
|
||||
raw_oa_institution_id=_raw_institution_id(normalized_id),
|
||||
author_id=None,
|
||||
author_filter_ids=None,
|
||||
institution_ids=None,
|
||||
keywords=None,
|
||||
topic_ids=None,
|
||||
filter_topic_ids=None,
|
||||
title=None,
|
||||
funding_start_years=None,
|
||||
funding_end_years=None,
|
||||
active_from_year=period[0],
|
||||
active_to_year=period[1],
|
||||
page=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
skip_enrichment=True,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=projects.total,
|
||||
)
|
||||
@@ -0,0 +1,513 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
|
||||
from .common import (
|
||||
DashboardPeriod,
|
||||
dashboard_period as _dashboard_period,
|
||||
normalize_institution_id as _normalize_institution_id,
|
||||
project_boundary_year_filter as _project_boundary_year_filter,
|
||||
project_overlap_filter as _project_overlap_filter,
|
||||
raw_institution_id as _raw_institution_id,
|
||||
)
|
||||
from .institute_helper import get_openalex_institution
|
||||
from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DfgProjectStatusStatistics,
|
||||
EuProjectStatusStatistics,
|
||||
)
|
||||
from .project_statistics_service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
)
|
||||
|
||||
|
||||
def _status_count(aggregations: dict[str, Any], status_name: str) -> int:
|
||||
return int(aggregations.get(status_name, {}).get("projects", {}).get("value", 0))
|
||||
|
||||
|
||||
def reconcile_status_counts(
|
||||
total: int, ongoing: int, upcoming: int, completed: int
|
||||
) -> tuple[int, int, int]:
|
||||
"""Make status buckets add up to the authoritative project-service total."""
|
||||
counts = [max(0, ongoing), max(0, upcoming), max(0, completed)]
|
||||
difference = total - sum(counts)
|
||||
if difference >= 0:
|
||||
counts[0] += difference
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
excess = -difference
|
||||
for index in (0, 1, 2):
|
||||
reduction = min(counts[index], excess)
|
||||
counts[index] -= reduction
|
||||
excess -= reduction
|
||||
if excess == 0:
|
||||
break
|
||||
return counts[0], counts[1], counts[2]
|
||||
|
||||
|
||||
def _status_filter_aggregations(
|
||||
start_field: str, end_field: str, today: str
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {start_field: {"lte": today}}},
|
||||
{"range": {end_field: {"gte": today}}},
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"upcoming": {"filter": {"range": {start_field: {"gt": today}}}},
|
||||
"completed": {"filter": {"range": {end_field: {"lt": today}}}},
|
||||
}
|
||||
|
||||
|
||||
async def get_dashboard_eu_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> EuProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
if not project_ids:
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
today = datetime.now().date().isoformat()
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters: list[dict[str, Any]] = [{"terms": {"id": sorted(project_ids)}}]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"startDate", "endDate", period, "iso"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
"aggs": {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"range": {"startDate": {"lte": today}}},
|
||||
{"range": {"endDate": {"gte": today}}},
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
"upcoming": {
|
||||
"filter": {"range": {"startDate": {"gt": today}}},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
"completed": {
|
||||
"filter": {"range": {"endDate": {"lt": today}}},
|
||||
"aggs": {"projects": {"cardinality": {"field": "id"}}},
|
||||
},
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
_status_count(aggregations, "ongoing"),
|
||||
_status_count(aggregations, "upcoming"),
|
||||
_status_count(aggregations, "completed"),
|
||||
)
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> BmbfProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
filters = [_alias_match_query("Zuwendungsempfänger", aliases)]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"funding_start", "funding_end", period, "de"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
"aggs": _status_filter_aggregations(
|
||||
"funding_start", "funding_end", datetime.now().strftime("%d.%m.%Y")
|
||||
),
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
total = (
|
||||
await get_dashboard_bmbf_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
)
|
||||
return BmbfProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def get_dashboard_dfg_project_statuses(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectStatusStatistics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(normalized_id)
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id, organization_name, from_year=from_year, to_year=to_year
|
||||
)
|
||||
).value
|
||||
if not project_ids:
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
|
||||
filters: list[dict[str, Any]] = [
|
||||
{
|
||||
"terms": {
|
||||
"projects.project_id": [int(project_id) for project_id in project_ids]
|
||||
}
|
||||
}
|
||||
]
|
||||
if period_filter := _project_boundary_year_filter(
|
||||
"projects.funding_start", "projects.funding_end", period, "year"
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"aggs": {
|
||||
"projects_nested": {
|
||||
"nested": {"path": "projects"},
|
||||
"aggs": {
|
||||
"selected_projects": {
|
||||
"filter": filters[0]
|
||||
if len(filters) == 1
|
||||
else {"bool": {"filter": filters}},
|
||||
"aggs": {
|
||||
"ongoing": {
|
||||
"filter": {
|
||||
"match_phrase": {
|
||||
"projects.status_de": "laufend"
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projects.project_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"completed": {
|
||||
"filter": {
|
||||
"match_phrase": {
|
||||
"projects.status_de": "abgeschlossen"
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projects.project_id"
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = (
|
||||
response.get("aggregations", {})
|
||||
.get("projects_nested", {})
|
||||
.get("selected_projects", {})
|
||||
)
|
||||
ongoing, upcoming, completed = reconcile_status_counts(
|
||||
total,
|
||||
_status_count(aggregations, "ongoing"),
|
||||
0,
|
||||
_status_count(aggregations, "completed"),
|
||||
)
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
async def _get_dfg_project_ids_for_institution(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[str]:
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
institution = await get_openalex_institution(institution_id)
|
||||
institution_names = _openalex_institution_names(institution)
|
||||
|
||||
institutes_response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _dfg_institute_name_query(institution_names),
|
||||
"aggs": {
|
||||
"institute_ids": {"terms": {"field": "institute_id", "size": 1000}}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
institute_ids = [
|
||||
bucket["key"]
|
||||
for bucket in (
|
||||
institutes_response.get("aggregations", {})
|
||||
.get("institute_ids", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
if not institute_ids:
|
||||
return []
|
||||
|
||||
projects_response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_INSTITUTES_V2,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {"terms": {"institute_id": institute_ids}},
|
||||
"aggs": {
|
||||
"projects_nested": {
|
||||
"nested": {"path": "projects"},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"filter": {
|
||||
"terms": {"projects.institute_ref_id": institute_ids}
|
||||
},
|
||||
"aggs": {
|
||||
"values": {
|
||||
"terms": {
|
||||
"field": "projects.project_id",
|
||||
"size": 10000,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
project_ids = [
|
||||
str(bucket["key"])
|
||||
for bucket in (
|
||||
projects_response.get("aggregations", {})
|
||||
.get("projects_nested", {})
|
||||
.get("project_ids", {})
|
||||
.get("values", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
return await _filter_dfg_project_ids_by_period(project_ids, period)
|
||||
|
||||
|
||||
async def _eu_project_ids_for_aliases(aliases: list[str]) -> set[str]:
|
||||
project_ids: set[str] = set()
|
||||
async for hit in elasticsearch.scan(
|
||||
index=str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD),
|
||||
query=_eu_organization_query(aliases),
|
||||
source=["projectID"],
|
||||
page_size=1000,
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
project_id = hit.get("_source", {}).get("projectID")
|
||||
if project_id is not None:
|
||||
project_ids.add(str(project_id))
|
||||
return project_ids
|
||||
|
||||
|
||||
async def _filter_dfg_project_ids_by_period(
|
||||
project_ids: list[str],
|
||||
period: DashboardPeriod,
|
||||
) -> list[str]:
|
||||
period_filter = _project_overlap_filter(
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
period,
|
||||
missing_end_is_ongoing=True,
|
||||
)
|
||||
if not project_ids or not period_filter:
|
||||
return project_ids
|
||||
|
||||
numeric_project_ids = [
|
||||
int(project_id) for project_id in project_ids if str(project_id).isdigit()
|
||||
]
|
||||
if not numeric_project_ids:
|
||||
return []
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.DFG_PROJECTS,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"terms": {"id": numeric_project_ids}},
|
||||
period_filter,
|
||||
]
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"terms": {
|
||||
"field": "id",
|
||||
"size": len(numeric_project_ids),
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
return [
|
||||
str(bucket["key"])
|
||||
for bucket in (
|
||||
response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
|
||||
)
|
||||
if bucket.get("key") is not None
|
||||
]
|
||||
|
||||
|
||||
async def _institution_aliases(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
) -> list[str]:
|
||||
aliases = (
|
||||
await InstitutionsSearchClient().get_institution_aliases_by_oa_institution_id(
|
||||
_raw_institution_id(institution_id)
|
||||
)
|
||||
)
|
||||
return sorted(
|
||||
{
|
||||
alias.strip()
|
||||
for alias in [organization_name, *aliases]
|
||||
if alias and alias.strip()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _eu_organization_query(aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"terms": {
|
||||
"name.keyword": [alias.upper() for alias in aliases],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _alias_match_query(field: str, aliases: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match": {
|
||||
field: {
|
||||
"query": alias,
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
}
|
||||
for alias in aliases
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _openalex_institution_names(institution: Any) -> list[str]:
|
||||
return sorted(
|
||||
{
|
||||
name.strip()
|
||||
for name in [
|
||||
institution.display_name,
|
||||
*(institution.display_name_alternatives or []),
|
||||
*(institution.display_name_acronyms or []),
|
||||
]
|
||||
if name and name.strip()
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _dfg_institute_name_query(institution_names: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_de.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_en.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
@@ -18,28 +18,40 @@ from .model import (
|
||||
EuProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
TopAuthorStatistics,
|
||||
TopAuthorAnalysis,
|
||||
TopicHeatmap,
|
||||
TopicWordCloud,
|
||||
)
|
||||
from .service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_bund_topics,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_topics,
|
||||
get_dashboard_eu_project_statuses,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_patents,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
get_topic_word_cloud,
|
||||
)
|
||||
from .project_statistics_service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
)
|
||||
from .bund_topics_service import get_dashboard_bund_topics
|
||||
from .dfg_topics_service import get_dashboard_dfg_topics
|
||||
from .eu_topics_service import get_dashboard_eu_topics
|
||||
from .project_status_service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_eu_project_statuses,
|
||||
)
|
||||
from .top_authors_service import (
|
||||
get_top_authors,
|
||||
get_top_eu_project_authors,
|
||||
get_top_news_authors,
|
||||
get_top_patent_authors,
|
||||
get_top_project_authors,
|
||||
get_top_work_authors,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/dashboard", tags=[Tags.DASHBOARD])
|
||||
|
||||
@@ -325,6 +337,94 @@ async def dashboard_top_authors(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/works",
|
||||
operation_id="getDashboardTopWorkAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_work_authors(
|
||||
works_period: Literal["all_time", "last_5_years"] = Query(
|
||||
default="all_time", pattern="^(all_time|last_5_years)$"
|
||||
),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_work_authors(
|
||||
organization.openalex_institution_id, works_period, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/projects",
|
||||
operation_id="getDashboardTopProjectAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_project_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_project_authors(
|
||||
organization.openalex_institution_id, organization.name, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/eu-projects",
|
||||
operation_id="getDashboardTopEuProjectAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_eu_project_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_eu_project_authors(
|
||||
organization.openalex_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/patents",
|
||||
operation_id="getDashboardTopPatentAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_patent_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_patent_authors(
|
||||
organization.openalex_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/top-authors/news",
|
||||
operation_id="getDashboardTopNewsAuthors",
|
||||
response_model=TopAuthorAnalysis,
|
||||
)
|
||||
async def dashboard_top_news_authors(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorAnalysis:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_top_news_authors(
|
||||
organization.openalex_institution_id, from_year, to_year
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topic-heatmap",
|
||||
operation_id="getDashboardTopicHeatmap",
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,5 @@
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
@@ -10,25 +9,33 @@ from sqlmodel import Session, SQLModel, create_engine
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
_get_dfg_project_ids_from_projects_service,
|
||||
_openalex_work_authors_by_eu_projects,
|
||||
_project_boundary_year_filter,
|
||||
_reconcile_project_status_counts,
|
||||
_top_news_authors,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_bund_topics,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_eu_topics,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_publications,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
get_topic_word_cloud,
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.dashboard.common import (
|
||||
project_boundary_year_filter as _project_boundary_year_filter,
|
||||
)
|
||||
from inse.dashboard.bund_topics_service import get_dashboard_bund_topics
|
||||
from inse.dashboard.eu_topics_service import get_dashboard_eu_topics
|
||||
from inse.dashboard.project_status_service import reconcile_status_counts
|
||||
from inse.dashboard.project_ids_service import (
|
||||
_get_dfg_project_ids_from_projects_service,
|
||||
)
|
||||
from inse.dashboard.project_statistics_service import (
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
)
|
||||
from inse.dashboard.top_authors_service import (
|
||||
_openalex_work_authors_by_eu_projects,
|
||||
_top_news_authors,
|
||||
get_top_authors,
|
||||
)
|
||||
from inse.model import ESIndex
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.persons.model import CustomAuthorsListResponse
|
||||
@@ -52,8 +59,8 @@ def anyio_backend():
|
||||
|
||||
|
||||
def test_project_status_counts_match_authoritative_total():
|
||||
assert _reconcile_project_status_counts(12, 4, 1, 5) == (6, 1, 5)
|
||||
assert _reconcile_project_status_counts(7, 4, 2, 3) == (2, 2, 3)
|
||||
assert reconcile_status_counts(12, 4, 1, 5) == (6, 1, 5)
|
||||
assert reconcile_status_counts(7, 4, 2, 3) == (2, 2, 3)
|
||||
|
||||
|
||||
def test_project_status_period_uses_interval_overlap():
|
||||
@@ -86,25 +93,25 @@ def test_project_status_period_uses_interval_overlap():
|
||||
async def test_top_news_authors_applies_dashboard_period():
|
||||
response = {
|
||||
"aggregations": {
|
||||
"authors": {
|
||||
"buckets": [{"key": "Ada Example", "doc_count": 3}]
|
||||
}
|
||||
"authors": {"buckets": [{"key": "Ada Example", "doc_count": 3}]}
|
||||
}
|
||||
}
|
||||
|
||||
async def scan(**kwargs):
|
||||
assert kwargs["index"] == str(ESIndex.AKTUELLES)
|
||||
assert kwargs["query"] == {
|
||||
"range": {"date_year": {"gte": 2020, "lte": 2023}}
|
||||
}
|
||||
assert kwargs["query"] == {"range": {"date_year": {"gte": 2020, "lte": 2023}}}
|
||||
yield {"_id": "N1"}
|
||||
yield {"_id": "N2"}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
with (
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as mocked_search,
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.scan",
|
||||
new=scan,
|
||||
),
|
||||
):
|
||||
result = await _top_news_authors(
|
||||
[{"id": "https://openalex.org/A1", "name": "Ada Example"}],
|
||||
@@ -141,7 +148,7 @@ async def test_dfg_topic_project_ids_use_paginated_projects_service():
|
||||
]
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects",
|
||||
"inse.projects.service.get_dfg_projects",
|
||||
new=AsyncMock(side_effect=pages),
|
||||
) as mocked_get_projects:
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
@@ -213,10 +220,13 @@ async def test_eu_topics_scan_all_programme_indices_and_deduplicate_projects():
|
||||
}
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service._get_eu_project_ids_from_projects_service",
|
||||
new=AsyncMock(return_value=["P1", "P2", "P3"]),
|
||||
), patch("inse.dashboard.service.elasticsearch.scan", new=scan):
|
||||
with (
|
||||
patch(
|
||||
"inse.dashboard.eu_topics_service._get_eu_project_ids_from_projects_service",
|
||||
new=AsyncMock(return_value=["P1", "P2", "P3"]),
|
||||
),
|
||||
patch("inse.integrations.elasticsearch.scan", new=scan),
|
||||
):
|
||||
result = await get_dashboard_eu_topics(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
@@ -282,12 +292,15 @@ async def test_bund_topics_use_mapping_index_and_unique_hierarchy_counts():
|
||||
}
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_projects, patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
with (
|
||||
patch(
|
||||
"inse.projects.service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_projects,
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.scan",
|
||||
new=scan,
|
||||
),
|
||||
):
|
||||
result = await get_dashboard_bund_topics(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -328,9 +341,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
if index == ESIndex.DFG_INSTITUTES_V2:
|
||||
if "institute_ids" in kwargs["body"].get("aggs", {}):
|
||||
return {
|
||||
"aggregations": {
|
||||
"institute_ids": {"buckets": [{"key": 10210}]}
|
||||
}
|
||||
"aggregations": {"institute_ids": {"buckets": [{"key": 10210}]}}
|
||||
}
|
||||
return {
|
||||
"aggregations": {
|
||||
@@ -350,48 +361,59 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
|
||||
return {"hits": {"total": {"value": 3}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University", "Example Uni"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_openalex_institution",
|
||||
new=AsyncMock(
|
||||
return_value=Institution(
|
||||
id=ORG_INSTITUTION_ID,
|
||||
display_name="Example University",
|
||||
display_name_alternatives=["Example Universität"],
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects",
|
||||
new=AsyncMock(
|
||||
return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
|
||||
patch(
|
||||
"inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University", "Example Uni"]),
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(
|
||||
return_value=EuCordisProjectSearchPage(
|
||||
elements=[], total=10, page=0, size=1
|
||||
)
|
||||
patch(
|
||||
"inse.dashboard.project_status_service.get_openalex_institution",
|
||||
new=AsyncMock(
|
||||
return_value=Institution(
|
||||
id=ORG_INSTITUTION_ID,
|
||||
display_name="Example University",
|
||||
display_name_alternatives=["Example Universität"],
|
||||
)
|
||||
),
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(
|
||||
return_value=BundProjectPage(elements=[], total=5, page=0, size=1)
|
||||
patch(
|
||||
"inse.projects.service.get_dfg_projects",
|
||||
new=AsyncMock(
|
||||
return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
|
||||
),
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.persons_service.search_persons_list",
|
||||
new=AsyncMock(
|
||||
return_value=CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=35, page=1, per_page=1)
|
||||
)
|
||||
patch(
|
||||
"inse.projects.service.search_eu_cordis_projects",
|
||||
new=AsyncMock(
|
||||
return_value=EuCordisProjectSearchPage(
|
||||
elements=[], total=10, page=0, size=1
|
||||
)
|
||||
),
|
||||
),
|
||||
patch(
|
||||
"inse.projects.service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(
|
||||
return_value=BundProjectPage(elements=[], total=5, page=0, size=1)
|
||||
),
|
||||
),
|
||||
patch(
|
||||
"inse.dashboard.service.persons_service.search_persons_list",
|
||||
new=AsyncMock(
|
||||
return_value=CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=35, page=1, per_page=1)
|
||||
)
|
||||
),
|
||||
),
|
||||
patch(
|
||||
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||
new=AsyncMock(
|
||||
return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)
|
||||
),
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||
new=AsyncMock(return_value=Institution(id=ORG_INSTITUTION_ID, works_count=120)),
|
||||
):
|
||||
result = await get_dashboard_statistics(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -409,17 +431,21 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
"bmbf_projects": 5,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_publications_uses_exact_es_count_for_period():
|
||||
with patch(
|
||||
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||
new=AsyncMock(
|
||||
return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250)
|
||||
),
|
||||
) as mocked_get_institution, patch(
|
||||
"inse.dashboard.service.elasticsearch.count",
|
||||
new=AsyncMock(return_value=22),
|
||||
) as mocked_count:
|
||||
with (
|
||||
patch(
|
||||
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
|
||||
new=AsyncMock(
|
||||
return_value=Institution(id=ORG_INSTITUTION_ID, works_count=250)
|
||||
),
|
||||
) as mocked_get_institution,
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.count",
|
||||
new=AsyncMock(return_value=22),
|
||||
) as mocked_count,
|
||||
):
|
||||
all_time = await get_dashboard_publications(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
@@ -478,7 +504,7 @@ async def test_dashboard_dfg_projects_uses_projects_service_total():
|
||||
project_page = DfgProjectPage(elements=[], total=42, page=0, size=1)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects",
|
||||
"inse.projects.service.get_dfg_projects",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_dfg_projects(
|
||||
@@ -506,7 +532,7 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total():
|
||||
project_page = BundProjectPage(elements=[], total=29, page=0, size=1)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_bund_projects_with_filters",
|
||||
"inse.projects.service.search_bund_projects_with_filters",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_bmbf_projects(
|
||||
@@ -530,12 +556,10 @@ async def test_dashboard_bmbf_projects_uses_projects_service_total():
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_eu_projects_uses_projects_service_total():
|
||||
project_page = EuCordisProjectSearchPage(
|
||||
elements=[], total=37, page=0, size=1
|
||||
)
|
||||
project_page = EuCordisProjectSearchPage(elements=[], total=37, page=0, size=1)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
"inse.projects.service.search_eu_cordis_projects",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_eu_projects(
|
||||
@@ -588,11 +612,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
if kwargs["index"] == "aktuell_postproc":
|
||||
return {
|
||||
"aggregations": {
|
||||
"authors": {
|
||||
"buckets": [
|
||||
{"key": "Ada Example", "doc_count": 6}
|
||||
]
|
||||
}
|
||||
"authors": {"buckets": [{"key": "Ada Example", "doc_count": 6}]}
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
|
||||
@@ -618,9 +638,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
if kwargs["index"] == ESIndex.DFG_PROJECTS:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [{"key": "Grace Example", "doc_count": 3}]
|
||||
}
|
||||
"people": {"buckets": [{"key": "Grace Example", "doc_count": 3}]}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -712,9 +730,15 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
if kwargs.get("raw_oa_institution_id"):
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||
EuCordisProjectSummary(id="P3", project_type=EuCordisProjectType.HEU),
|
||||
EuCordisProjectSummary(
|
||||
id="P1", project_type=EuCordisProjectType.FP7
|
||||
),
|
||||
EuCordisProjectSummary(
|
||||
id="P2", project_type=EuCordisProjectType.H2020
|
||||
),
|
||||
EuCordisProjectSummary(
|
||||
id="P3", project_type=EuCordisProjectType.HEU
|
||||
),
|
||||
],
|
||||
total=3,
|
||||
page=0,
|
||||
@@ -727,24 +751,30 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
size=1,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(
|
||||
return_value=[
|
||||
{"id": "A1", "name": "Ada Example", "count": 4},
|
||||
]
|
||||
with (
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search,
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.scan",
|
||||
new=scan,
|
||||
),
|
||||
patch(
|
||||
"inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
),
|
||||
patch(
|
||||
"inse.projects.service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
),
|
||||
patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(
|
||||
return_value=[
|
||||
{"id": "A1", "name": "Ada Example", "count": 4},
|
||||
]
|
||||
),
|
||||
),
|
||||
):
|
||||
result = await get_top_authors(
|
||||
@@ -775,8 +805,7 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
project_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"]
|
||||
in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
|
||||
if call.kwargs["index"] in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
|
||||
]
|
||||
assert project_calls == []
|
||||
|
||||
@@ -926,9 +955,7 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
|
||||
assert kwargs["body"]["query"] == {
|
||||
"terms": {"projectID": ["P1", "P2"]}
|
||||
}
|
||||
assert kwargs["body"]["query"] == {"terms": {"projectID": ["P1", "P2"]}}
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
@@ -1056,8 +1083,12 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
if kwargs.get("raw_oa_institution_id"):
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||
EuCordisProjectSummary(
|
||||
id="P1", project_type=EuCordisProjectType.FP7
|
||||
),
|
||||
EuCordisProjectSummary(
|
||||
id="P2", project_type=EuCordisProjectType.H2020
|
||||
),
|
||||
],
|
||||
total=2,
|
||||
page=0,
|
||||
@@ -1070,18 +1101,23 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
size=1,
|
||||
)
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
with (
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
),
|
||||
patch(
|
||||
"inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
),
|
||||
patch(
|
||||
"inse.projects.service.search_eu_cordis_projects",
|
||||
new=AsyncMock(side_effect=eu_projects),
|
||||
),
|
||||
patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
),
|
||||
):
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -1133,27 +1169,23 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
|
||||
},
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
],
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
),
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.scan",
|
||||
new=scan,
|
||||
),
|
||||
patch(
|
||||
"inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
),
|
||||
patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -1235,21 +1267,23 @@ async def test_top_authors_can_rank_works_by_last_five_years():
|
||||
},
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.elasticsearch.scan",
|
||||
new=scan,
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
with (
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
),
|
||||
patch(
|
||||
"inse.integrations.elasticsearch.scan",
|
||||
new=scan,
|
||||
),
|
||||
patch(
|
||||
"inse.institutions.institutions_search_client.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
),
|
||||
patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
),
|
||||
):
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -1369,7 +1403,7 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search:
|
||||
result = await get_topic_heatmap(
|
||||
@@ -1423,17 +1457,14 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
|
||||
== "topics.subfield.id"
|
||||
)
|
||||
assert (
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"][
|
||||
"aggs"
|
||||
]["topics"]["terms"]["field"]
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"]["aggs"][
|
||||
"topics"
|
||||
]["terms"]["field"]
|
||||
== "topics.id"
|
||||
)
|
||||
subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
|
||||
assert "aggs" not in subfield_aggs["subfields"]["aggs"]["works"]
|
||||
assert (
|
||||
"aggs"
|
||||
not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"]
|
||||
)
|
||||
assert "aggs" not in subfield_aggs["subfields"]["aggs"]["topics"]["aggs"]["works"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -1449,7 +1480,7 @@ async def test_topic_heatmap_defaults_to_all_time():
|
||||
return {"hits": {"hits": []}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search:
|
||||
result = await get_topic_heatmap(
|
||||
@@ -1485,7 +1516,7 @@ async def test_topic_word_cloud_maps_related_topics_and_excludes_selected_topic(
|
||||
}
|
||||
}
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
"inse.integrations.elasticsearch.search",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as mocked_search:
|
||||
result = await get_topic_word_cloud(
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Observable, catchError, forkJoin, map, of } from 'rxjs';
|
||||
|
||||
import { Configuration } from '../../api';
|
||||
import { TopicTreemapData } from '../../shared/ui/topic-treemap/topic-treemap.models';
|
||||
@@ -95,6 +95,11 @@ export interface TopAuthorStatistics {
|
||||
news: TopAuthor[];
|
||||
}
|
||||
|
||||
export interface TopAuthorAnalysis {
|
||||
institution_id: string;
|
||||
authors: TopAuthor[];
|
||||
}
|
||||
|
||||
export interface TopicWordCloudWord {
|
||||
id: string;
|
||||
name: string;
|
||||
@@ -228,9 +233,38 @@ export class DashboardStatisticsService {
|
||||
getTopAuthors(
|
||||
period: DashboardPeriodBounds = {},
|
||||
): Observable<TopAuthorStatistics> {
|
||||
return this.httpClient.get<TopAuthorStatistics>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors`,
|
||||
{ params: this.periodParams(period) },
|
||||
const analysis = (source: string) =>
|
||||
this.httpClient
|
||||
.get<TopAuthorAnalysis>(
|
||||
`${this.apiConfiguration?.basePath ?? ''}/api/dashboard/top-authors/${source}`,
|
||||
{ params: this.periodParams(period) },
|
||||
)
|
||||
.pipe(catchError(() => of(null)));
|
||||
|
||||
return forkJoin({
|
||||
works: analysis('works'),
|
||||
projects: analysis('projects'),
|
||||
euProjects: analysis('eu-projects'),
|
||||
patents: analysis('patents'),
|
||||
news: analysis('news'),
|
||||
}).pipe(
|
||||
map((responses) => {
|
||||
const successfulResponse = Object.values(responses).find(
|
||||
(response) => response !== null,
|
||||
);
|
||||
if (!successfulResponse) {
|
||||
throw new Error('All top-author analyses failed.');
|
||||
}
|
||||
|
||||
return {
|
||||
institution_id: successfulResponse.institution_id,
|
||||
works: responses.works?.authors ?? [],
|
||||
projects: responses.projects?.authors ?? [],
|
||||
eu_projects: responses.euProjects?.authors ?? [],
|
||||
patents: responses.patents?.authors ?? [],
|
||||
news: responses.news?.authors ?? [],
|
||||
};
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user