Compare commits

...
Author SHA1 Message Date
farajollahi d48435b948 fix bug
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-06 18:12:38 +02:00
spsaefan c054cf99fe Fix all time slider
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-04 23:19:50 +02:00
spsaefan 98a742f024 Match dashboard publications with publications page
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-08-04 22:59:36 +02:00
3 changed files with 281 additions and 84 deletions
+89 -49
View File
@@ -30,6 +30,7 @@ from inse.projects.model import (
ProjectsFilteringProperties,
ProjectType,
)
from inse.works.v2 import service as works_v2_service
from .institute_helper import get_openalex_institution
from .model import (
@@ -241,28 +242,34 @@ async def get_dashboard_publications(
) -> DashboardStatisticValue:
normalized_id = _normalize_institution_id(institution_id)
period = _dashboard_period(from_year, to_year)
institution = await institutions_v2_service.get_institution_by_id_or_raise(
raw_oa_institution_id=_raw_institution_id(normalized_id),
source=["id", "works_count", "counts_by_year"],
must = [
works_v2_service._institutions_nested_query([normalized_id]),
]
if publication_years := _dashboard_publication_years(period):
must.append({"terms": {"publication_year": publication_years}})
response = await elasticsearch.search(
index=ESIndex.OPENALEX_WORKS_WILDCARD,
body={
"size": 0,
"track_total_hits": True,
"query": {"bool": {"must": must}},
},
cluster=ESCluster.NES,
)
if period == (None, None):
value = int(institution.works_count or 0)
else:
value = sum(
int(entry.works_count or 0)
for entry in institution.counts_by_year or []
if (
(period[0] is None or int(entry.year or 0) >= period[0])
and (period[1] is None or int(entry.year or 0) <= period[1])
)
)
return DashboardStatisticValue(
institution_id=normalized_id,
organization_name=organization_name,
value=value,
value=_total(response),
)
def _dashboard_publication_years(period: DashboardPeriod) -> list[int] | None:
from_year, to_year = period
if from_year is None and to_year is None:
return None
return list(range(from_year or 1900, (to_year or 2100) + 1))
async def get_dashboard_persons(
institution_id: str,
organization_name: str,
@@ -1183,7 +1190,10 @@ async def get_top_authors(
to_year = datetime.now().year
period = _dashboard_period(from_year, to_year)
authors = await _safe_institution_authors(normalized_id)
works = _top_work_authors(authors, period)
works = await _safe_top_authors(
"works",
_top_work_authors(normalized_id, period, authors),
)
projects = await _safe_top_authors(
"projects",
_top_project_authors(
@@ -1595,51 +1605,81 @@ def _short_author_id(value: str) -> str:
return value.replace("https://openalex.org/", "").strip().upper()
def _top_work_authors(
authors: list[dict[str, Any]],
async def _top_work_authors(
institution_id: str,
period: DashboardPeriod,
institution_authors: list[dict[str, Any]],
) -> list[TopAuthor]:
if period != (None, None):
ranked_authors = sorted(
(
{
**author,
"selected_works_count": _works_count_in_period(author, period),
}
for author in authors
),
key=lambda author: author["selected_works_count"],
reverse=True,
)
else:
ranked_authors = [
{**author, "selected_works_count": author["works_count"]}
for author in authors
]
institution_author_ids = {
_short_author_id(str(author["id"]))
for author in institution_authors
if author.get("id")
}
if not institution_author_ids:
return []
must = [works_v2_service._institutions_nested_query([institution_id])]
if publication_years := _dashboard_publication_years(period):
must.append({"terms": {"publication_year": publication_years}})
author_counts: dict[str, int] = defaultdict(int)
author_names: dict[str, str] = {}
async for hit in elasticsearch.scan(
index=str(ESIndex.OPENALEX_WORKS_WILDCARD),
query={"bool": {"must": must}},
source=[
"id",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
],
page_size=1000,
cluster=ESCluster.NES,
):
hit_author_ids: set[str] = set()
for authorship in hit.get("_source", {}).get("authorships", []):
if not any(
_normalize_institution_id(institution.get("id")) == institution_id
for institution in authorship.get("institutions") or []
if institution.get("id")
):
continue
author = authorship.get("author") or {}
author_id = author.get("id")
if not author_id:
continue
author_id = str(author_id)
if _short_author_id(author_id) not in institution_author_ids:
continue
hit_author_ids.add(author_id)
if author.get("display_name"):
author_names.setdefault(author_id, str(author["display_name"]))
for author_id in hit_author_ids:
author_counts[author_id] += 1
ranked_authors = sorted(
(
{
"id": author_id,
"name": author_names.get(author_id, author_id),
"count": count,
}
for author_id, count in author_counts.items()
),
key=lambda author: author["count"],
reverse=True,
)
return [
TopAuthor(
id=_short_author_id(author["id"]),
name=author["name"],
count=author["selected_works_count"],
count=author["count"],
)
for author in ranked_authors[:TOP_AUTHOR_LIMIT]
if author["selected_works_count"] > 0
if author["count"] > 0
]
def _works_count_in_period(author: dict[str, Any], period: DashboardPeriod) -> int:
from_year, to_year = period
return sum(
int(item.get("works_count", 0) or 0)
for item in author.get("counts_by_year", [])
if (
(from_year is None or int(item.get("year", 0) or 0) >= from_year)
and (to_year is None or int(item.get("year", 0) or 0) <= to_year)
)
)
async def _safe_institution_authors(institution_id: str) -> list[dict[str, Any]]:
try:
return await _institution_authors(institution_id)
+177 -25
View File
@@ -24,7 +24,6 @@ from inse.dashboard.service import (
get_topic_word_cloud,
)
from inse.model import ESCluster, ESIndex
from inse.models.openalex.author_counts_by_year_inner import AuthorCountsByYearInner
from inse.models.openalex.institution import Institution
from inse.models.openalex.meta import Meta
from inse.persons.model import CustomAuthorsListResponse
@@ -188,21 +187,16 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
}
@pytest.mark.anyio
async def test_dashboard_publications_uses_institutions_v2_counts():
institution = Institution(
id=ORG_INSTITUTION_ID,
works_count=250,
counts_by_year=[
AuthorCountsByYearInner(year=2021, works_count=10),
AuthorCountsByYearInner(year=2022, works_count=12),
AuthorCountsByYearInner(year=2023, works_count=14),
],
)
async def test_dashboard_publications_counts_matching_openalex_works():
with patch(
"inse.dashboard.service.institutions_v2_service.get_institution_by_id_or_raise",
new=AsyncMock(return_value=institution),
) as mocked_get_institution:
"inse.dashboard.service.elasticsearch.search",
new=AsyncMock(
side_effect=[
{"hits": {"total": {"value": 250}}},
{"hits": {"total": {"value": 22}}},
]
),
) as mocked_search:
all_time = await get_dashboard_publications(
ORG_INSTITUTION_ID,
"Example Org",
@@ -216,10 +210,33 @@ async def test_dashboard_publications_uses_institutions_v2_counts():
assert all_time.value == 250
assert selected_period.value == 22
assert mocked_get_institution.await_args_list[0].kwargs == {
"raw_oa_institution_id": "I123",
"source": ["id", "works_count", "counts_by_year"],
}
all_time_body = mocked_search.await_args_list[0].kwargs["body"]
selected_period_body = mocked_search.await_args_list[1].kwargs["body"]
assert mocked_search.await_args_list[0].kwargs["index"] == (
ESIndex.OPENALEX_WORKS_WILDCARD
)
assert all_time_body["track_total_hits"] is True
assert all_time_body["query"]["bool"]["must"] == [
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [ORG_INSTITUTION_ID]
}
},
}
},
}
}
]
assert selected_period_body["query"]["bool"]["must"] == [
all_time_body["query"]["bool"]["must"][0],
{"terms": {"publication_year": [2021, 2022]}},
]
@pytest.mark.anyio
@@ -438,6 +455,48 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
return {"aggregations": {"people": {"buckets": []}}}
scan_calls = []
async def scan(**kwargs):
scan_calls.append(kwargs)
yield {
"_id": "W1",
"_source": {
"id": "https://openalex.org/W1",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
},
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": "https://openalex.org/I999"}],
},
],
},
}
yield {
"_id": "W2",
"_source": {
"id": "https://openalex.org/W2",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
},
}
async def eu_projects(**kwargs):
if kwargs.get("raw_oa_institution_id"):
return EuCordisProjectSearchPage(
@@ -461,6 +520,9 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
"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(
@@ -482,8 +544,9 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert result.works[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
"count": 42,
"count": 2,
}
assert len(result.works) == 1
assert result.patents[0].model_dump() == {
"id": "A1",
"name": "Ada Example",
@@ -523,18 +586,44 @@ async def test_top_authors_maps_works_patents_news_and_eu_projects():
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
assert "aggs" not in eu_body
works_calls = [
assert len(scan_calls) == 1
assert scan_calls[0]["index"] == str(ESIndex.OPENALEX_WORKS_WILDCARD)
assert scan_calls[0]["query"]["bool"]["must"] == [
{
"nested": {
"path": "authorships",
"query": {
"nested": {
"path": "authorships.institutions",
"query": {
"terms": {
"authorships.institutions.id": [ORG_INSTITUTION_ID]
}
},
}
},
}
}
]
assert scan_calls[0]["source"] == [
"id",
"authorships.author.id",
"authorships.author.display_name",
"authorships.institutions.id",
]
eu_work_calls = [
call
for call in mocked_search.await_args_list
if call.kwargs["index"] == "openalex-works"
]
assert len(works_calls) == 1
works_body = works_calls[0].kwargs["body"]
assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
assert len(eu_work_calls) == 1
eu_works_body = eu_work_calls[0].kwargs["body"]
assert eu_works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
"https://doi.org/10.1234/p1",
"https://doi.org/10.1234/p2",
]
assert works_body["_source"] == [
assert eu_works_body["_source"] == [
"doi",
"authorships.author.id",
"authorships.author.display_name",
@@ -813,9 +902,29 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
raise RuntimeError("projects unavailable")
async def scan(**kwargs):
yield {
"_id": "W1",
"_source": {
"id": "https://openalex.org/W1",
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
],
},
}
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"]),
@@ -879,9 +988,47 @@ async def test_top_authors_can_rank_works_by_last_five_years():
}
return {"aggregations": {"people": {"buckets": []}}}
scan_calls = []
async def scan(**kwargs):
scan_calls.append(kwargs)
for index in range(16):
yield {
"_id": f"W-grace-{index}",
"_source": {
"authorships": [
{
"author": {
"id": "https://openalex.org/A2",
"display_name": "Grace Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
]
},
}
for index in range(2):
yield {
"_id": f"W-ada-{index}",
"_source": {
"authorships": [
{
"author": {
"id": "https://openalex.org/A1",
"display_name": "Ada Example",
},
"institutions": [{"id": ORG_INSTITUTION_ID}],
}
]
},
}
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"]),
@@ -909,6 +1056,11 @@ async def test_top_authors_can_rank_works_by_last_five_years():
"count": 2,
}
assert len(scan_calls) == 1
assert scan_calls[0]["query"]["bool"]["must"][1] == {
"terms": {"publication_year": list(range(current_year - 4, current_year + 1))}
}
@pytest.mark.anyio
async def test_topic_heatmap_maps_field_year_counts_and_shares():
@@ -108,7 +108,7 @@ export class DashboardComponent implements OnInit {
readonly topicTreemapMinYear = 1900;
readonly topicTreemapMaxYear = new Date().getFullYear();
dashboardPeriodMode: DashboardPeriodMode = 'all_time';
dashboardFromYear = this.topicTreemapMaxYear - 4;
dashboardFromYear = this.topicTreemapMinYear;
dashboardToYear = this.topicTreemapMaxYear;
selectedTopicTreemapNode?: string;
selectedDfgTopicTreemapNode?: string;
@@ -406,14 +406,16 @@ export class DashboardComponent implements OnInit {
this.dashboardPeriodMode = mode;
}
this.applyPresetPeriod();
this.dashboardFromYear = this.parseDashboardYear(
params.get('fromYear'),
this.dashboardFromYear,
);
this.dashboardToYear = this.parseDashboardYear(
params.get('toYear'),
this.dashboardToYear,
);
if (this.dashboardPeriodMode !== 'all_time') {
this.dashboardFromYear = this.parseDashboardYear(
params.get('fromYear'),
this.dashboardFromYear,
);
this.dashboardToYear = this.parseDashboardYear(
params.get('toYear'),
this.dashboardToYear,
);
}
if (this.dashboardFromYear > this.dashboardToYear) {
this.dashboardFromYear = this.dashboardToYear;
}
@@ -422,7 +424,10 @@ export class DashboardComponent implements OnInit {
private applyPresetPeriod(): void {
const currentYear = this.topicTreemapMaxYear;
if (this.dashboardPeriodMode === 'last_10_years') {
if (this.dashboardPeriodMode === 'all_time') {
this.dashboardFromYear = this.topicTreemapMinYear;
this.dashboardToYear = currentYear;
} else if (this.dashboardPeriodMode === 'last_10_years') {
this.dashboardFromYear = currentYear - 9;
this.dashboardToYear = currentYear;
} else if (this.dashboardPeriodMode === 'last_5_years') {