This commit is contained in:
@@ -11,13 +11,12 @@ from sqlmodel import Session
|
||||
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_institution_membership_query,
|
||||
)
|
||||
from inse.institutions.institutions_search_client import InstitutionsSearchClient
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.patents.org.elastic_search_client import OrgPatentsSearchClient
|
||||
from inse.persons import service as persons_service
|
||||
from inse.projects import service as projects_service
|
||||
from inse.projects.dfg_institutions.service import (
|
||||
autocomplete_institutions_for_selector,
|
||||
)
|
||||
@@ -270,20 +269,25 @@ async def get_dashboard_persons(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="from_year and to_year must either both be provided or both omitted.",
|
||||
)
|
||||
membership_query = build_institution_membership_query(
|
||||
persons = await persons_service.search_persons_list(
|
||||
query=None,
|
||||
institution_id=normalized_id,
|
||||
year_mode="between" if period[0] is not None else "all",
|
||||
year=period[0],
|
||||
year_to=period[1],
|
||||
sort_by=None,
|
||||
sort_order=None,
|
||||
topic=None,
|
||||
page=1,
|
||||
page_size=1,
|
||||
include="",
|
||||
year_filter_enabled=period[0] is not None,
|
||||
filter_mode="between" if period[0] is not None else None,
|
||||
filter_year=period[0],
|
||||
filter_year_to=period[1],
|
||||
)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.OPENALEX_AUTHORS,
|
||||
query=membership_query,
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.NES,
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=int(persons.meta.count or 0) if persons.meta else 0,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_patents(
|
||||
@@ -315,45 +319,43 @@ async def get_dashboard_eu_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
period_filter = _project_overlap_filter(
|
||||
"startDate",
|
||||
"endDate",
|
||||
_date_period(period, "iso"),
|
||||
)
|
||||
if period_filter:
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
value = await _count_eu_projects_in_period(project_ids, period_filter)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=value,
|
||||
)
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD,
|
||||
body={
|
||||
"size": 0,
|
||||
"query": _eu_organization_query(aliases),
|
||||
"aggs": {
|
||||
"projects": {
|
||||
"cardinality": {
|
||||
"field": "projectID",
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
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=(
|
||||
[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
|
||||
),
|
||||
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=int(
|
||||
response.get("aggregations", {})
|
||||
.get("projects", {})
|
||||
.get("value", 0)
|
||||
),
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
@@ -368,10 +370,18 @@ async def get_dashboard_eu_project_statuses(
|
||||
project_ids = await _eu_project_ids_for_aliases(aliases)
|
||||
|
||||
if not project_ids:
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
@@ -426,12 +436,26 @@ async def get_dashboard_eu_project_statuses(
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
aggregations = response.get("aggregations", {})
|
||||
total = (
|
||||
await get_dashboard_eu_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
_project_status_count(aggregations, "ongoing"),
|
||||
_project_status_count(aggregations, "upcoming"),
|
||||
_project_status_count(aggregations, "completed"),
|
||||
)
|
||||
return EuProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
||||
upcoming=_project_status_count(aggregations, "upcoming"),
|
||||
completed=_project_status_count(aggregations, "completed"),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -441,6 +465,32 @@ def _project_status_count(aggregations: dict[str, Any], status_name: str) -> int
|
||||
)
|
||||
|
||||
|
||||
def _reconcile_project_status_counts(
|
||||
total: int,
|
||||
ongoing: int,
|
||||
upcoming: int,
|
||||
completed: int,
|
||||
) -> tuple[int, int, int]:
|
||||
"""Makes 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]
|
||||
|
||||
# Defensive fallback for stale/duplicated status documents: reduce buckets
|
||||
# without ever returning negative values, preferring the inferred ongoing
|
||||
# bucket before changing explicit upcoming/completed classifications.
|
||||
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]
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_projects(
|
||||
institution_id: str,
|
||||
organization_name: str,
|
||||
@@ -448,23 +498,38 @@ async def get_dashboard_bmbf_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
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_overlap_filter(
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
_date_period(period, "de"),
|
||||
):
|
||||
filters.append(period_filter)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
query=filters[0] if len(filters) == 1 else {"bool": {"filter": filters}},
|
||||
size=0,
|
||||
track_total_hits=True,
|
||||
cluster=ESCluster.INSE,
|
||||
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=(
|
||||
[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
|
||||
),
|
||||
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,
|
||||
)
|
||||
return _dashboard_statistic_value(normalized_id, organization_name, response)
|
||||
|
||||
|
||||
async def get_dashboard_bmbf_project_statuses(
|
||||
@@ -498,12 +563,26 @@ async def get_dashboard_bmbf_project_statuses(
|
||||
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_project_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=int(aggregations.get("ongoing", {}).get("doc_count", 0)),
|
||||
upcoming=int(aggregations.get("upcoming", {}).get("doc_count", 0)),
|
||||
completed=int(aggregations.get("completed", {}).get("doc_count", 0)),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -535,15 +614,37 @@ async def get_dashboard_dfg_projects(
|
||||
to_year: int | None = None,
|
||||
) -> DashboardStatisticValue:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
projects = await projects_service.get_dfg_projects_by_author_id(
|
||||
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=(
|
||||
[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=0,
|
||||
size=1,
|
||||
sort_by="id",
|
||||
sort_direction="asc",
|
||||
fuzzy=False,
|
||||
)
|
||||
return DashboardStatisticValue(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
value=len(project_ids),
|
||||
value=projects.total,
|
||||
)
|
||||
|
||||
|
||||
@@ -559,10 +660,18 @@ async def get_dashboard_dfg_project_statuses(
|
||||
normalized_id,
|
||||
)
|
||||
if not project_ids:
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=0,
|
||||
ongoing=total,
|
||||
upcoming=0,
|
||||
completed=0,
|
||||
)
|
||||
@@ -640,12 +749,26 @@ async def get_dashboard_dfg_project_statuses(
|
||||
.get("projects_nested", {})
|
||||
.get("selected_projects", {})
|
||||
)
|
||||
total = (
|
||||
await get_dashboard_dfg_projects(
|
||||
normalized_id,
|
||||
organization_name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
).value
|
||||
ongoing, upcoming, completed = _reconcile_project_status_counts(
|
||||
total,
|
||||
_project_status_count(aggregations, "ongoing"),
|
||||
0,
|
||||
_project_status_count(aggregations, "completed"),
|
||||
)
|
||||
return DfgProjectStatusStatistics(
|
||||
institution_id=normalized_id,
|
||||
organization_name=organization_name,
|
||||
ongoing=_project_status_count(aggregations, "ongoing"),
|
||||
upcoming=0,
|
||||
completed=_project_status_count(aggregations, "completed"),
|
||||
ongoing=ongoing,
|
||||
upcoming=upcoming,
|
||||
completed=completed,
|
||||
)
|
||||
|
||||
|
||||
@@ -656,17 +779,11 @@ async def get_dashboard_dfg_topics(
|
||||
to_year: int | None = None,
|
||||
) -> DfgProjectTopics:
|
||||
normalized_id = _normalize_institution_id(institution_id)
|
||||
project_ids = await _get_dfg_project_ids_for_institution(
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
normalized_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
print(
|
||||
"Dashboard DFG project topics "
|
||||
f"for institution {normalized_id}: "
|
||||
f"{len(project_ids)} project IDs={project_ids}",
|
||||
flush=True,
|
||||
)
|
||||
topics: dict[str, dict[str, Any]] = {}
|
||||
matched_project_ids: set[str] = set()
|
||||
|
||||
@@ -735,6 +852,53 @@ async def get_dashboard_dfg_topics(
|
||||
)
|
||||
|
||||
|
||||
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_by_author_id(
|
||||
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_dfg_project_ids_for_institution(
|
||||
institution_id: str,
|
||||
from_year: int | None = None,
|
||||
@@ -1011,7 +1175,6 @@ async def get_top_authors(
|
||||
from_year = datetime.now().year - 4
|
||||
to_year = datetime.now().year
|
||||
period = _dashboard_period(from_year, to_year)
|
||||
aliases = await _institution_aliases(normalized_id, organization_name)
|
||||
authors = await _safe_institution_authors(normalized_id)
|
||||
works = _top_work_authors(authors, period)
|
||||
projects = await _safe_top_authors(
|
||||
@@ -1025,7 +1188,12 @@ async def get_top_authors(
|
||||
)
|
||||
eu_projects = await _safe_top_authors(
|
||||
"eu_projects",
|
||||
_top_eu_project_publication_authors(normalized_id, aliases, authors),
|
||||
_top_eu_project_publication_authors(
|
||||
normalized_id,
|
||||
authors,
|
||||
from_year=period[0],
|
||||
to_year=period[1],
|
||||
),
|
||||
)
|
||||
|
||||
patents = await _safe_top_authors(
|
||||
@@ -1998,8 +2166,9 @@ async def _top_patent_authors(
|
||||
|
||||
async def _top_eu_project_publication_authors(
|
||||
institution_id: str,
|
||||
organization_names: list[str],
|
||||
institution_authors: list[dict[str, Any]],
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[TopAuthor]:
|
||||
institution_author_ids = {
|
||||
author_id
|
||||
@@ -2009,17 +2178,12 @@ async def _top_eu_project_publication_authors(
|
||||
if not institution_author_ids:
|
||||
return []
|
||||
|
||||
project_page = await get_eu_organization_project_contributions(
|
||||
organization_names=organization_names,
|
||||
projects_filtering_properties=ProjectsFilteringProperties(
|
||||
project_type=ProjectType.EU,
|
||||
page=0,
|
||||
size=10000,
|
||||
),
|
||||
project_ids = await _get_eu_project_ids_from_projects_service(
|
||||
institution_id,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
project_ids = [project.project_id for project in project_page.elements]
|
||||
|
||||
if not project_ids:
|
||||
return []
|
||||
|
||||
@@ -2028,11 +2192,7 @@ async def _top_eu_project_publication_authors(
|
||||
body={
|
||||
"size": 10000,
|
||||
"_source": ["projectID", "qaProcessedDoi"],
|
||||
"query": {
|
||||
"terms": {
|
||||
"projectID": project_ids,
|
||||
}
|
||||
},
|
||||
"query": {"terms": {"projectID": project_ids}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
@@ -2074,6 +2234,59 @@ async def _top_eu_project_publication_authors(
|
||||
)
|
||||
|
||||
|
||||
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=(
|
||||
[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
|
||||
),
|
||||
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)
|
||||
|
||||
|
||||
def _cordis_publication_doi_project_ids(
|
||||
response: dict[str, Any],
|
||||
allowed_project_ids: set[str],
|
||||
|
||||
@@ -10,7 +10,13 @@ from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
_openalex_work_authors_by_eu_projects,
|
||||
_get_dfg_project_ids_from_projects_service,
|
||||
_reconcile_project_status_counts,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_persons,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
@@ -18,6 +24,16 @@ from inse.dashboard.service import (
|
||||
)
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.models.openalex.meta import Meta
|
||||
from inse.persons.model import CustomAuthorsListResponse
|
||||
from inse.projects.model import (
|
||||
BundProjectPage,
|
||||
DfgProjectPage,
|
||||
DfgProjectSummary,
|
||||
EuCordisProjectSearchPage,
|
||||
EuCordisProjectSummary,
|
||||
EuCordisProjectType,
|
||||
)
|
||||
|
||||
ORG_INSTITUTION_ID = "https://openalex.org/I123"
|
||||
|
||||
@@ -27,6 +43,47 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dfg_topic_project_ids_use_paginated_projects_service():
|
||||
pages = [
|
||||
DfgProjectPage(
|
||||
elements=[DfgProjectSummary(id="101"), DfgProjectSummary(id="102")],
|
||||
total=3,
|
||||
page=0,
|
||||
size=1000,
|
||||
),
|
||||
DfgProjectPage(
|
||||
elements=[DfgProjectSummary(id="103")],
|
||||
total=3,
|
||||
page=1,
|
||||
size=1000,
|
||||
),
|
||||
]
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(side_effect=pages),
|
||||
) as mocked_get_projects:
|
||||
project_ids = await _get_dfg_project_ids_from_projects_service(
|
||||
ORG_INSTITUTION_ID,
|
||||
from_year=2020,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
assert project_ids == ["101", "102", "103"]
|
||||
assert mocked_get_projects.await_count == 2
|
||||
first_call = mocked_get_projects.await_args_list[0]
|
||||
assert first_call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert first_call.kwargs["skip_enrichment"] is True
|
||||
assert first_call.kwargs["funding_start_years"][-1] == "2022"
|
||||
assert first_call.kwargs["funding_end_years"][0] == "2020"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
async def search(**kwargs):
|
||||
@@ -84,6 +141,30 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
display_name_alternatives=["Example Universität"],
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.projects_service.get_dfg_projects_by_author_id",
|
||||
new=AsyncMock(
|
||||
return_value=DfgProjectPage(elements=[], total=3, page=0, size=1)
|
||||
),
|
||||
), 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.service.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)
|
||||
)
|
||||
),
|
||||
):
|
||||
result = await get_dashboard_statistics(
|
||||
ORG_INSTITUTION_ID,
|
||||
@@ -110,55 +191,109 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
|
||||
person_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_persons_uses_persons_service_for_organization():
|
||||
response = CustomAuthorsListResponse(
|
||||
results=[], meta=Meta(count=64, page=1, per_page=1)
|
||||
)
|
||||
person_query = person_call.kwargs["query"]
|
||||
affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
|
||||
|
||||
assert affiliation["nested"]["path"] == "affiliations"
|
||||
assert affiliation["nested"]["query"]["bool"]["filter"][0] == {
|
||||
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
|
||||
}
|
||||
eu_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
|
||||
with patch(
|
||||
"inse.dashboard.service.persons_service.search_persons_list",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as mocked_search_persons:
|
||||
result = await get_dashboard_persons(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2020,
|
||||
to_year=2023,
|
||||
)
|
||||
|
||||
assert result.value == 64
|
||||
call = mocked_search_persons.await_args
|
||||
assert call.kwargs["institution_id"] == ORG_INSTITUTION_ID
|
||||
assert call.kwargs["filter_mode"] == "between"
|
||||
assert call.kwargs["filter_year"] == 2020
|
||||
assert call.kwargs["filter_year_to"] == 2023
|
||||
assert call.kwargs["page"] == 1
|
||||
assert call.kwargs["page_size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
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_by_author_id",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_dfg_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2020,
|
||||
to_year=2022,
|
||||
)
|
||||
|
||||
assert result.value == 42
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2022"
|
||||
assert call.kwargs["funding_end_years"][0] == "2020"
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
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",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_bmbf_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2018,
|
||||
to_year=2020,
|
||||
)
|
||||
|
||||
assert result.value == 29
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2020"
|
||||
assert call.kwargs["funding_end_years"][0] == "2018"
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_eu_projects_uses_projects_service_total():
|
||||
project_page = EuCordisProjectSearchPage(
|
||||
elements=[], total=37, page=0, size=1
|
||||
)
|
||||
assert eu_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert eu_call.kwargs["body"]["query"] == {
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
"EXAMPLE ORG",
|
||||
"EXAMPLE UNI",
|
||||
"EXAMPLE UNIVERSITY",
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
bund_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
|
||||
)
|
||||
assert bund_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
with patch(
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(return_value=project_page),
|
||||
) as mocked_get_projects:
|
||||
result = await get_dashboard_eu_projects(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
from_year=2019,
|
||||
to_year=2021,
|
||||
)
|
||||
|
||||
dfg_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
|
||||
]
|
||||
assert len(dfg_calls) == 2
|
||||
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls)
|
||||
assert result.value == 37
|
||||
mocked_get_projects.assert_awaited_once()
|
||||
call = mocked_get_projects.await_args
|
||||
assert call.kwargs["raw_oa_institution_id"] == "I123"
|
||||
assert call.kwargs["funding_start_years"][-1] == "2021"
|
||||
assert call.kwargs["funding_end_years"][0] == "2019"
|
||||
assert call.kwargs["project_types"] == list(EuCordisProjectType)
|
||||
assert call.kwargs["page"] == 0
|
||||
assert call.kwargs["size"] == 1
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -279,14 +414,17 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
"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",
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
return_value=EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
SimpleNamespace(project_id="P3"),
|
||||
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,
|
||||
size=1000,
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
@@ -580,13 +718,16 @@ async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_i
|
||||
"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",
|
||||
"inse.dashboard.service.projects_service.search_eu_cordis_projects",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
return_value=EuCordisProjectSearchPage(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
EuCordisProjectSummary(id="P1", project_type=EuCordisProjectType.FP7),
|
||||
EuCordisProjectSummary(id="P2", project_type=EuCordisProjectType.H2020),
|
||||
],
|
||||
total=2,
|
||||
page=0,
|
||||
size=1000,
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
|
||||
@@ -944,6 +944,7 @@ async def search_eu_cordis_projects(
|
||||
sort_by: str = "title",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> EuCordisProjectSearchPage:
|
||||
"""
|
||||
Generic EU CORDIS project search across FP7, H2020 and Horizon Europe.
|
||||
@@ -1015,6 +1016,14 @@ async def search_eu_cordis_projects(
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
total = response.get("hits", {}).get("total", {}).get("value", 0)
|
||||
|
||||
if skip_enrichment:
|
||||
return EuCordisProjectSearchPage(
|
||||
elements=[EuCordisProjectSummary.from_hit(hit) for hit in hits],
|
||||
total=total,
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
|
||||
project_ids_by_type: dict[EuCordisProjectType, list[str]] = defaultdict(list)
|
||||
|
||||
for hit in hits:
|
||||
@@ -1333,4 +1342,4 @@ async def get_openalex_authors_for_projects_ids(
|
||||
result[(project_type, pid)] = author_pages_by_project_id.get(
|
||||
pid, AuthorPage(elements=[], total=0, page=0, size=0)
|
||||
)
|
||||
return result
|
||||
return result
|
||||
|
||||
@@ -366,6 +366,7 @@ async def search_dfg_projects(
|
||||
sort_by: str = "id",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> DfgProjectPage:
|
||||
"""Searches for DFG projects based on the provided filtering and sorting criteria.
|
||||
|
||||
@@ -584,6 +585,9 @@ async def search_dfg_projects(
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
|
||||
if skip_enrichment:
|
||||
return _complete_response_to_dfg_project_page(response, page, size)
|
||||
|
||||
project_ids = [hit["_source"]["id"] for hit in hits]
|
||||
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=project_ids)
|
||||
|
||||
@@ -1167,4 +1171,4 @@ def _hit_to_funding_project(hit: dict[str, Any]) -> FundingProject:
|
||||
else:
|
||||
raise ValueError(
|
||||
"The provided hit does not belong to a recognized project index."
|
||||
)
|
||||
)
|
||||
|
||||
@@ -174,6 +174,7 @@ async def get_dfg_projects_by_author_id(
|
||||
sort_by: str = "topic",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> DfgProjectPage:
|
||||
logger.debug(
|
||||
"Fetching DFG projects for author_id=%s, author_filter_ids=%s, "
|
||||
@@ -248,6 +249,7 @@ async def get_dfg_projects_by_author_id(
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
skip_enrichment=skip_enrichment,
|
||||
)
|
||||
|
||||
async def get_institution_cordis_eu_projects_funding_over_time(
|
||||
@@ -623,6 +625,7 @@ async def search_eu_cordis_projects(
|
||||
sort_by: str = "title",
|
||||
sort_direction: str = "asc",
|
||||
fuzzy: bool = False,
|
||||
skip_enrichment: bool = False,
|
||||
) -> EuCordisProjectSearchPage:
|
||||
"""Single entry point for EU CORDIS project search.
|
||||
|
||||
@@ -683,4 +686,5 @@ async def search_eu_cordis_projects(
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
fuzzy=fuzzy,
|
||||
)
|
||||
skip_enrichment=skip_enrichment,
|
||||
)
|
||||
|
||||
@@ -3,11 +3,10 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from math import floor
|
||||
from time import time
|
||||
from typing import Any
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_active_institution_membership_query,
|
||||
)
|
||||
@@ -746,15 +745,29 @@ def _bucket_to_ranked_author(author_bucket: dict) -> RankedAuthor:
|
||||
)
|
||||
|
||||
|
||||
def _min_max_normalize(values: pd.Series) -> pd.Series:
|
||||
def _quantile(values: list[float], quantile: float) -> float:
|
||||
"""Returns a linearly interpolated quantile (the former pandas default)."""
|
||||
ordered = sorted(values)
|
||||
if not ordered:
|
||||
return 0.0
|
||||
position = (len(ordered) - 1) * quantile
|
||||
lower_index = floor(position)
|
||||
upper_index = min(lower_index + 1, len(ordered) - 1)
|
||||
fraction = position - lower_index
|
||||
return ordered[lower_index] + (
|
||||
ordered[upper_index] - ordered[lower_index]
|
||||
) * fraction
|
||||
|
||||
|
||||
def _min_max_normalize(values: list[float]) -> list[float]:
|
||||
"""Scales a numeric column to the range [0, 1] via min-max normalization."""
|
||||
minimum = values.min()
|
||||
maximum = values.max()
|
||||
minimum = min(values)
|
||||
maximum = max(values)
|
||||
# if all values are the same, return a series of 1.0 to avoid division by zero.
|
||||
if maximum == minimum:
|
||||
return pd.Series([1.0] * len(values))
|
||||
return [1.0] * len(values)
|
||||
|
||||
return (values - minimum) / (maximum - minimum)
|
||||
return [(value - minimum) / (maximum - minimum) for value in values]
|
||||
|
||||
|
||||
def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
||||
@@ -775,38 +788,29 @@ def _apply_scores(authors: list[RankedAuthor], weights: RankingWeights) -> None:
|
||||
news_counts.append(author.news_count)
|
||||
patents_counts.append(author.patents_count)
|
||||
|
||||
frame = pd.DataFrame({
|
||||
"works": works_counts,
|
||||
"citations": citations_counts,
|
||||
"companies": companies_counts,
|
||||
"news": news_counts,
|
||||
"patents": patents_counts,
|
||||
})
|
||||
|
||||
quantile_value = 0.95
|
||||
|
||||
frame["works"] = frame["works"].clip(upper=frame["works"].quantile(quantile_value))
|
||||
frame["citations"] = frame["citations"].clip(upper=frame["citations"].quantile(quantile_value))
|
||||
frame["companies"] = frame["companies"].clip(upper=frame["companies"].quantile(quantile_value))
|
||||
frame["news"] = frame["news"].clip(upper=frame["news"].quantile(quantile_value))
|
||||
frame["patents"] = frame["patents"].clip(upper=frame["patents"].quantile(quantile_value))
|
||||
|
||||
works_normalized = _min_max_normalize(frame["works"])
|
||||
citations_normalized = _min_max_normalize(frame["citations"])
|
||||
companies_normalized = _min_max_normalize(frame["companies"])
|
||||
news_normalized = _min_max_normalize(frame["news"])
|
||||
patents_normalized = _min_max_normalize(frame["patents"])
|
||||
|
||||
scores = (
|
||||
works_normalized * weights.works
|
||||
+ citations_normalized * weights.citation
|
||||
+ companies_normalized * weights.companies
|
||||
+ news_normalized * weights.news
|
||||
+ patents_normalized * weights.patents
|
||||
)
|
||||
metrics = [
|
||||
works_counts,
|
||||
citations_counts,
|
||||
companies_counts,
|
||||
news_counts,
|
||||
patents_counts,
|
||||
]
|
||||
normalized_metrics = [
|
||||
_min_max_normalize(
|
||||
[min(value, _quantile(values, quantile_value)) for value in values]
|
||||
)
|
||||
for values in metrics
|
||||
]
|
||||
|
||||
for index, author in enumerate(authors):
|
||||
author.score = float(scores.iloc[index])
|
||||
author.score = float(
|
||||
normalized_metrics[0][index] * weights.works
|
||||
+ normalized_metrics[1][index] * weights.citation
|
||||
+ normalized_metrics[2][index] * weights.companies
|
||||
+ normalized_metrics[3][index] * weights.news
|
||||
+ normalized_metrics[4][index] * weights.patents
|
||||
)
|
||||
|
||||
|
||||
def _author_score(author: RankedAuthor) -> float:
|
||||
|
||||
Reference in New Issue
Block a user