Strategy pattern in backend (mock for patent and projects for now)
This commit is contained in:
@@ -4,6 +4,15 @@ from inse.models.openalex.topic import Topic
|
||||
|
||||
DashboardMetric = Literal['publications', 'citations']
|
||||
|
||||
from enum import Enum
|
||||
class TrendSearchType(str, Enum):
|
||||
PUBLICATIONS = "publications"
|
||||
AUTHORS = "authors"
|
||||
PATENTS = "patents"
|
||||
PROJECTS = "projects"
|
||||
NEWS = "news"
|
||||
ALL = "all"
|
||||
|
||||
class YearlyData(BaseModel):
|
||||
year: int
|
||||
publications: int
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi import APIRouter, Query, Depends
|
||||
|
||||
from inse.tags import Tags
|
||||
from . import logic, trend_logic
|
||||
@@ -9,8 +9,10 @@ from .model import (
|
||||
DashboardMetric,
|
||||
TrendResponse,
|
||||
TopInstitutionItem,
|
||||
AutocompleteLocationItem
|
||||
AutocompleteLocationItem,
|
||||
TrendSearchType
|
||||
)
|
||||
from .trend_strategies import TrendStrategy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -19,6 +21,29 @@ router = APIRouter(
|
||||
tags=[Tags.UNIVERSITY_RANKINGS]
|
||||
)
|
||||
|
||||
def get_trend_strategy(search_type: TrendSearchType = Query(TrendSearchType.PUBLICATIONS)) -> TrendStrategy:
|
||||
from .trend_strategies import (
|
||||
PublicationsTrendStrategy,
|
||||
AuthorsTrendStrategy,
|
||||
PatentsTrendStrategy,
|
||||
ProjectsTrendStrategy,
|
||||
NewsTrendStrategy,
|
||||
AllTrendStrategy,
|
||||
)
|
||||
if search_type == TrendSearchType.PUBLICATIONS:
|
||||
return PublicationsTrendStrategy()
|
||||
elif search_type == TrendSearchType.AUTHORS:
|
||||
return AuthorsTrendStrategy()
|
||||
elif search_type == TrendSearchType.PATENTS:
|
||||
return PatentsTrendStrategy()
|
||||
elif search_type == TrendSearchType.PROJECTS:
|
||||
return ProjectsTrendStrategy()
|
||||
elif search_type == TrendSearchType.NEWS:
|
||||
return NewsTrendStrategy()
|
||||
elif search_type == TrendSearchType.ALL:
|
||||
return AllTrendStrategy()
|
||||
raise ValueError(f"Unknown search type: {search_type}")
|
||||
|
||||
@router.get(
|
||||
"",
|
||||
response_model=RankingResponse,
|
||||
@@ -36,19 +61,26 @@ async def get_rankings(
|
||||
@router.get(
|
||||
"/trend",
|
||||
response_model=TrendResponse,
|
||||
summary="Returns timeseries publication data for compared institutions, countries and regions."
|
||||
summary="Returns timeseries publication data for compared institutions, countries, and regions."
|
||||
)
|
||||
async def get_trend(
|
||||
topics: List[str] = Query(..., description="List of topics to analyze"),
|
||||
keywords: Optional[List[str]] = Query(None, description="List of raw keywords corresponding to topics"),
|
||||
soft_search: bool = Query(True, description="True if using mapped topics, False if using raw keywords"),
|
||||
institutions: Optional[List[str]] = Query(None, description="List of OpenAlex Institution IDs"),
|
||||
countries: Optional[List[str]] = Query(None, description="List of country codes"),
|
||||
regions: Optional[List[str]] = Query(None, description="List of region identifiers")
|
||||
regions: Optional[List[str]] = Query(None, description="List of region identifiers"),
|
||||
authors: Optional[List[str]] = Query(None, description="List of OpenAlex Author IDs"),
|
||||
strategy: TrendStrategy = Depends(get_trend_strategy)
|
||||
):
|
||||
return await trend_logic.get_trend_data(
|
||||
return await strategy.get_trend(
|
||||
topics=topics,
|
||||
keywords=keywords,
|
||||
soft_search=soft_search,
|
||||
institutions=institutions,
|
||||
countries=countries,
|
||||
regions=regions
|
||||
regions=regions,
|
||||
authors=authors
|
||||
)
|
||||
|
||||
@router.get(
|
||||
|
||||
@@ -0,0 +1,894 @@
|
||||
import abc
|
||||
import asyncio
|
||||
import logging
|
||||
import datetime
|
||||
from typing import List, Dict, Any, Optional
|
||||
import numpy as np
|
||||
from sklearn.preprocessing import MinMaxScaler
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex, ESCluster
|
||||
from .model import (
|
||||
TrendResponse,
|
||||
TrendSeries,
|
||||
TopicYearlyData
|
||||
)
|
||||
from .trend_logic import (
|
||||
DEFAULT_INSTITUTION_ID,
|
||||
DEFAULT_INSTITUTION_NAME
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class TrendStrategy(abc.ABC):
|
||||
@abc.abstractmethod
|
||||
async def get_trend(
|
||||
self,
|
||||
topics: List[str],
|
||||
keywords: Optional[List[str]] = None,
|
||||
soft_search: bool = True,
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None,
|
||||
authors: Optional[List[str]] = None,
|
||||
) -> TrendResponse:
|
||||
pass
|
||||
|
||||
def _normalize_series(
|
||||
self,
|
||||
years_range: List[int],
|
||||
accumulated_data: Dict[str, Dict[str, Dict[int, tuple]]],
|
||||
topics: List[str]
|
||||
) -> Dict[tuple, Dict[str, List[float]]]:
|
||||
series_keys = []
|
||||
raw_lists = []
|
||||
cumsum_lists = []
|
||||
|
||||
for entity_key, topic_dict in accumulated_data.items():
|
||||
for topic, year_dict in topic_dict.items():
|
||||
raw_counts = []
|
||||
for yr in years_range:
|
||||
count, _ = year_dict[yr]
|
||||
raw_counts.append(count)
|
||||
|
||||
cumulative_counts = list(np.cumsum(raw_counts))
|
||||
series_keys.append((entity_key, topic))
|
||||
raw_lists.append(raw_counts)
|
||||
cumsum_lists.append(cumulative_counts)
|
||||
|
||||
normalized_lookup = {}
|
||||
if raw_lists:
|
||||
raw_matrix = np.array(raw_lists, dtype=float).T
|
||||
cumsum_matrix = np.array(cumsum_lists, dtype=float).T
|
||||
|
||||
scaler_raw = MinMaxScaler()
|
||||
normalized_matrix = scaler_raw.fit_transform(raw_matrix)
|
||||
|
||||
scaler_cumsum = MinMaxScaler()
|
||||
normalized_cumsum_matrix = scaler_cumsum.fit_transform(cumsum_matrix)
|
||||
|
||||
normalized_lists = normalized_matrix.T.tolist()
|
||||
normalized_cumsum_lists = normalized_cumsum_matrix.T.tolist()
|
||||
|
||||
for idx, (entity_key, topic) in enumerate(series_keys):
|
||||
normalized_lookup[(entity_key, topic)] = {
|
||||
"normalized": normalized_lists[idx],
|
||||
"cumulative": normalized_cumsum_lists[idx]
|
||||
}
|
||||
return normalized_lookup
|
||||
|
||||
|
||||
class PublicationsTrendStrategy(TrendStrategy):
|
||||
async def get_trend(
|
||||
self,
|
||||
topics: List[str],
|
||||
keywords: Optional[List[str]] = None,
|
||||
soft_search: bool = True,
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None,
|
||||
authors: Optional[List[str]] = None,
|
||||
) -> TrendResponse:
|
||||
start_year = 2000
|
||||
end_year = datetime.datetime.now().year - 1
|
||||
years_range = list(range(start_year, end_year + 1))
|
||||
|
||||
primary_inst_id = DEFAULT_INSTITUTION_ID
|
||||
primary_inst_name = DEFAULT_INSTITUTION_NAME
|
||||
|
||||
query_institutions = []
|
||||
if institutions:
|
||||
query_institutions = [i.strip() for i in institutions]
|
||||
if primary_inst_id not in query_institutions:
|
||||
query_institutions.insert(0, primary_inst_id)
|
||||
|
||||
query_countries = countries or []
|
||||
query_regions = regions or []
|
||||
|
||||
clean_countries = [c.strip().upper() for c in query_countries]
|
||||
clean_regions = [r.strip() for r in query_regions]
|
||||
ids_to_resolve = list(set(query_institutions))
|
||||
|
||||
# Resolution lookups
|
||||
async def fetch_institutions():
|
||||
names = {primary_inst_id: primary_inst_name}
|
||||
codes = {}
|
||||
if not ids_to_resolve:
|
||||
return names, codes
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_INSTITUTIONS),
|
||||
query={"terms": {"id": ids_to_resolve}},
|
||||
size=len(ids_to_resolve),
|
||||
source=["id", "display_name", "country_code"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
names[source["id"]] = source.get("display_name", source["id"])
|
||||
codes[source["id"]] = source.get("country_code", "")
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve institution details from ES: %s", e)
|
||||
return names, codes
|
||||
|
||||
async def fetch_countries():
|
||||
names = {}
|
||||
if not clean_countries:
|
||||
return names
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_COUNTRIES),
|
||||
query={"terms": {"country_code": clean_countries}},
|
||||
size=len(clean_countries),
|
||||
source=["country_code", "display_name"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
names[source["country_code"]] = source["display_name"]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve country names from ES: %s", e)
|
||||
return names
|
||||
|
||||
async def fetch_continents():
|
||||
names = {}
|
||||
ccodes = {}
|
||||
if not clean_regions:
|
||||
return names, ccodes
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=str(ESIndex.OPENALEX_CONTINENTS),
|
||||
query={
|
||||
"bool": {
|
||||
"should": [
|
||||
{"terms": {"wikidata_id.keyword": clean_regions}},
|
||||
{"terms": {"id": [f"https://openalex.org/continents/{r}" for r in clean_regions]}}
|
||||
]
|
||||
}
|
||||
},
|
||||
size=len(clean_regions),
|
||||
source=["id", "display_name", "wikidata_id", "countries"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
c_code = source.get("wikidata_id") or source["id"].split("/")[-1]
|
||||
names[c_code] = source["display_name"]
|
||||
ccodes[c_code] = [c["id"].split("/")[-1].upper() for c in source.get("countries", [])]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve continent names from ES: %s", e)
|
||||
return names, ccodes
|
||||
|
||||
async def fetch_topics():
|
||||
t_ids = {}
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}},
|
||||
size=len(topics) * 2,
|
||||
source=["id", "display_name"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
for t in topics:
|
||||
if t.lower() in source["display_name"].lower():
|
||||
t_ids[t] = source["id"]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve topic IDs from ES: %s", e)
|
||||
return t_ids
|
||||
|
||||
(
|
||||
(resolved_names, resolved_country_codes),
|
||||
resolved_country_names,
|
||||
(resolved_continent_names, continent_country_codes),
|
||||
resolved_topic_ids
|
||||
) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents(), fetch_topics())
|
||||
|
||||
location_mappings = continent_country_codes.copy()
|
||||
|
||||
filters_map = {}
|
||||
for inst_id in query_institutions:
|
||||
filters_map[f"inst_{inst_id}"] = {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"term": {"authorships.institutions.id": inst_id}}
|
||||
}
|
||||
}
|
||||
for cc in clean_countries:
|
||||
filters_map[f"country_{cc}"] = {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"term": {"authorships.institutions.country_code": cc}}
|
||||
}
|
||||
}
|
||||
for r_code, member_ccs in continent_country_codes.items():
|
||||
if member_ccs:
|
||||
filters_map[f"region_{r_code}"] = {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"terms": {"authorships.institutions.country_code": member_ccs}}
|
||||
}
|
||||
}
|
||||
|
||||
if not filters_map:
|
||||
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
|
||||
|
||||
accumulated_data = {
|
||||
key: {t: {yr: (0, 1) for yr in years_range} for t in topics}
|
||||
for key in filters_map
|
||||
}
|
||||
|
||||
topic_clauses = []
|
||||
topic_filters = {}
|
||||
for idx, t in enumerate(topics):
|
||||
if not soft_search and keywords and idx < len(keywords):
|
||||
clause = {
|
||||
"nested": {
|
||||
"path": "keywords",
|
||||
"query": {"match_phrase": {"keywords.display_name": keywords[idx]}}
|
||||
}
|
||||
}
|
||||
else:
|
||||
tid = resolved_topic_ids.get(t)
|
||||
if tid:
|
||||
clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}},
|
||||
{"term": {"primary_topic.id": tid}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
else:
|
||||
clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}},
|
||||
{"match_phrase": {"primary_topic.display_name": t}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
topic_clauses.append(clause)
|
||||
topic_filters[t] = clause
|
||||
|
||||
entity_should_clauses = []
|
||||
if query_institutions:
|
||||
entity_should_clauses.append({
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"terms": {"authorships.institutions.id": query_institutions}}
|
||||
}
|
||||
})
|
||||
if clean_countries:
|
||||
entity_should_clauses.append({
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"terms": {"authorships.institutions.country_code": clean_countries}}
|
||||
}
|
||||
})
|
||||
all_continent_countries = []
|
||||
for member_ccs in continent_country_codes.values():
|
||||
all_continent_countries.extend(member_ccs)
|
||||
if all_continent_countries:
|
||||
entity_should_clauses.append({
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {"terms": {"authorships.institutions.country_code": list(set(all_continent_countries))}}
|
||||
}
|
||||
})
|
||||
|
||||
filter_clauses = [
|
||||
{"range": {"publication_year": {"gte": start_year, "lte": end_year}}},
|
||||
{"bool": {"should": topic_clauses, "minimum_should_match": 1}}
|
||||
]
|
||||
if entity_should_clauses:
|
||||
filter_clauses.append({"bool": {"should": entity_should_clauses, "minimum_should_match": 1}})
|
||||
|
||||
query = {"bool": {"filter": filter_clauses}}
|
||||
aggregations = {
|
||||
"topics_agg": {
|
||||
"filters": {"filters": topic_filters},
|
||||
"aggs": {
|
||||
"entities_agg": {
|
||||
"filters": {"filters": filters_map},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {"field": "publication_year", "size": len(years_range) * 2}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=f"{str(ESIndex.OPENALEX_WORKS)}*",
|
||||
body={"query": query, "aggs": aggregations},
|
||||
size=0,
|
||||
cluster="nes"
|
||||
)
|
||||
topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {})
|
||||
for t_name, t_bucket in topics_buckets.items():
|
||||
entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {})
|
||||
for entity_key, e_bucket in entities_buckets.items():
|
||||
year_buckets = e_bucket.get("by_year", {}).get("buckets", [])
|
||||
for yr_bucket in year_buckets:
|
||||
yr = int(yr_bucket.get("key"))
|
||||
count = int(yr_bucket.get("doc_count", 0))
|
||||
if yr in years_range:
|
||||
accumulated_data[entity_key][t_name][yr] = (count, 1)
|
||||
except Exception as e:
|
||||
logger.error("Error executing Elasticsearch publication trend: %s", e)
|
||||
|
||||
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
||||
|
||||
series_list = []
|
||||
for entity_key, topic_dict in accumulated_data.items():
|
||||
if entity_key.startswith("inst_"):
|
||||
entity_id = entity_key[len("inst_"):]
|
||||
entity_name = resolved_names.get(entity_id, entity_id)
|
||||
entity_type = "institution"
|
||||
elif entity_key.startswith("country_"):
|
||||
entity_id = entity_key[len("country_"):]
|
||||
entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}")
|
||||
entity_type = "country"
|
||||
elif entity_key.startswith("region_"):
|
||||
entity_id = entity_key[len("region_"):]
|
||||
entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}")
|
||||
entity_type = "region"
|
||||
else:
|
||||
continue
|
||||
|
||||
topic_data_map = {}
|
||||
for topic, year_dict in topic_dict.items():
|
||||
yearly_data_items = []
|
||||
lookup = normalized_lookup.get((entity_key, topic), {})
|
||||
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||
|
||||
for idx, yr in enumerate(years_range):
|
||||
count, _ = year_dict[yr]
|
||||
yearly_data_items.append(TopicYearlyData(
|
||||
year=yr,
|
||||
raw=count,
|
||||
normalized=norm_vals[idx],
|
||||
cumulative=cum_vals[idx],
|
||||
institutions_count=1
|
||||
))
|
||||
topic_data_map[topic] = yearly_data_items
|
||||
|
||||
series_list.append(TrendSeries(
|
||||
entity_id=entity_id,
|
||||
entity_name=entity_name,
|
||||
entity_type=entity_type,
|
||||
country_code=resolved_country_codes.get(entity_id) if entity_type == "institution" else None,
|
||||
topic_data=topic_data_map
|
||||
))
|
||||
|
||||
return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings)
|
||||
|
||||
|
||||
class AuthorsTrendStrategy(TrendStrategy):
|
||||
async def get_trend(
|
||||
self,
|
||||
topics: List[str],
|
||||
keywords: Optional[List[str]] = None,
|
||||
soft_search: bool = True,
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None,
|
||||
authors: Optional[List[str]] = None,
|
||||
) -> TrendResponse:
|
||||
start_year = 2000
|
||||
end_year = datetime.datetime.now().year - 1
|
||||
years_range = list(range(start_year, end_year + 1))
|
||||
|
||||
query_authors = authors or []
|
||||
if not query_authors:
|
||||
return TrendResponse(series=[], years=years_range)
|
||||
|
||||
# Resolve author names from openalex-authors index using document ids
|
||||
resolved_names = {}
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-authors",
|
||||
body={"query": {"ids": {"values": query_authors}}},
|
||||
size=len(query_authors),
|
||||
source=["display_name"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
resolved_names[hit["_id"]] = hit["_source"].get("display_name", hit["_id"])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve author details from ES: %s", e)
|
||||
|
||||
# Fetch topic IDs
|
||||
resolved_topic_ids = {}
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topics]}},
|
||||
size=len(topics) * 2,
|
||||
source=["id", "display_name"],
|
||||
cluster="nes"
|
||||
)
|
||||
for hit in res.get("hits", {}).get("hits", []):
|
||||
source = hit["_source"]
|
||||
for t in topics:
|
||||
if t.lower() in source["display_name"].lower():
|
||||
resolved_topic_ids[t] = source["id"]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to resolve topic IDs from ES: %s", e)
|
||||
|
||||
query_authors_full = [
|
||||
a if a.startswith("https://openalex.org/") else f"https://openalex.org/{a.upper()}"
|
||||
for a in query_authors
|
||||
]
|
||||
|
||||
filters_map = {}
|
||||
for auth_id in query_authors:
|
||||
auth_url = auth_id if auth_id.startswith("https://openalex.org/") else f"https://openalex.org/{auth_id.upper()}"
|
||||
filters_map[f"author_{auth_id}"] = {
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"term": {"authorships.author.id": auth_url}}
|
||||
}
|
||||
}
|
||||
|
||||
accumulated_data = {
|
||||
key: {t: {yr: (0, 1) for yr in years_range} for t in topics}
|
||||
for key in filters_map
|
||||
}
|
||||
|
||||
topic_clauses = []
|
||||
topic_filters = {}
|
||||
for idx, t in enumerate(topics):
|
||||
if not soft_search and keywords and idx < len(keywords):
|
||||
clause = {
|
||||
"nested": {
|
||||
"path": "keywords",
|
||||
"query": {"match_phrase": {"keywords.display_name": keywords[idx]}}
|
||||
}
|
||||
}
|
||||
else:
|
||||
tid = resolved_topic_ids.get(t)
|
||||
if tid:
|
||||
clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"term": {"topics.id": tid}}}},
|
||||
{"term": {"primary_topic.id": tid}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
else:
|
||||
clause = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"nested": {"path": "topics", "query": {"match_phrase": {"topics.display_name": t}}}},
|
||||
{"match_phrase": {"primary_topic.display_name": t}}
|
||||
],
|
||||
"minimum_should_match": 1
|
||||
}
|
||||
}
|
||||
topic_clauses.append(clause)
|
||||
topic_filters[t] = clause
|
||||
|
||||
entity_should_clauses = [{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"terms": {"authorships.author.id": query_authors_full}}
|
||||
}
|
||||
}]
|
||||
|
||||
filter_clauses = [
|
||||
{"range": {"publication_year": {"gte": start_year, "lte": end_year}}},
|
||||
{"bool": {"should": topic_clauses, "minimum_should_match": 1}},
|
||||
{"bool": {"should": entity_should_clauses, "minimum_should_match": 1}}
|
||||
]
|
||||
|
||||
query = {"bool": {"filter": filter_clauses}}
|
||||
aggregations = {
|
||||
"topics_agg": {
|
||||
"filters": {"filters": topic_filters},
|
||||
"aggs": {
|
||||
"entities_agg": {
|
||||
"filters": {"filters": filters_map},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {"field": "publication_year", "size": len(years_range) * 2}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=f"{str(ESIndex.OPENALEX_WORKS)}*",
|
||||
body={"query": query, "aggs": aggregations},
|
||||
size=0,
|
||||
cluster="nes"
|
||||
)
|
||||
topics_buckets = res.get("aggregations", {}).get("topics_agg", {}).get("buckets", {})
|
||||
for t_name, t_bucket in topics_buckets.items():
|
||||
entities_buckets = t_bucket.get("entities_agg", {}).get("buckets", {})
|
||||
for entity_key, e_bucket in entities_buckets.items():
|
||||
year_buckets = e_bucket.get("by_year", {}).get("buckets", [])
|
||||
for yr_bucket in year_buckets:
|
||||
yr = int(yr_bucket.get("key"))
|
||||
count = int(yr_bucket.get("doc_count", 0))
|
||||
if yr in years_range:
|
||||
accumulated_data[entity_key][t_name][yr] = (count, 1)
|
||||
except Exception as e:
|
||||
logger.error("Error executing Elasticsearch author trend: %s", e)
|
||||
|
||||
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
||||
|
||||
series_list = []
|
||||
for entity_key, topic_dict in accumulated_data.items():
|
||||
entity_id = entity_key[len("author_"):]
|
||||
entity_name = resolved_names.get(entity_id, entity_id)
|
||||
|
||||
topic_data_map = {}
|
||||
for topic, year_dict in topic_dict.items():
|
||||
yearly_data_items = []
|
||||
lookup = normalized_lookup.get((entity_key, topic), {})
|
||||
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||
|
||||
for idx, yr in enumerate(years_range):
|
||||
count, _ = year_dict[yr]
|
||||
yearly_data_items.append(TopicYearlyData(
|
||||
year=yr,
|
||||
raw=count,
|
||||
normalized=norm_vals[idx],
|
||||
cumulative=cum_vals[idx],
|
||||
institutions_count=1
|
||||
))
|
||||
topic_data_map[topic] = yearly_data_items
|
||||
|
||||
series_list.append(TrendSeries(
|
||||
entity_id=entity_id,
|
||||
entity_name=entity_name,
|
||||
entity_type="institution",
|
||||
topic_data=topic_data_map
|
||||
))
|
||||
|
||||
return TrendResponse(series=series_list, years=years_range)
|
||||
|
||||
|
||||
class PatentsTrendStrategy(TrendStrategy):
|
||||
async def get_trend(
|
||||
self,
|
||||
topics: List[str],
|
||||
keywords: Optional[List[str]] = None,
|
||||
soft_search: bool = True,
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None,
|
||||
authors: Optional[List[str]] = None,
|
||||
) -> TrendResponse:
|
||||
# Stub for new patent-topic matching index. Returns a simulated matching curve.
|
||||
start_year = 2000
|
||||
end_year = datetime.datetime.now().year - 1
|
||||
years_range = list(range(start_year, end_year + 1))
|
||||
|
||||
primary_inst_name = DEFAULT_INSTITUTION_NAME
|
||||
entities = [primary_inst_name]
|
||||
if institutions:
|
||||
entities.extend(institutions)
|
||||
|
||||
series_list = []
|
||||
for entity in entities:
|
||||
topic_data_map = {}
|
||||
for topic in topics:
|
||||
yearly_data_items = []
|
||||
# Simple simulated growth with noise
|
||||
seed = hash(entity + topic) % 100
|
||||
np.random.seed(seed)
|
||||
counts = np.sort(np.random.randint(0, 15, size=len(years_range)))
|
||||
cum_counts = list(np.cumsum(counts))
|
||||
max_cum = cum_counts[-1] if cum_counts[-1] > 0 else 1
|
||||
|
||||
for idx, yr in enumerate(years_range):
|
||||
yearly_data_items.append(TopicYearlyData(
|
||||
year=yr,
|
||||
raw=int(counts[idx]),
|
||||
normalized=float(counts[idx] / 15.0),
|
||||
cumulative=float(cum_counts[idx] / max_cum),
|
||||
institutions_count=1
|
||||
))
|
||||
topic_data_map[topic] = yearly_data_items
|
||||
|
||||
series_list.append(TrendSeries(
|
||||
entity_id=entity,
|
||||
entity_name=entity.split("/")[-1],
|
||||
entity_type="institution",
|
||||
topic_data=topic_data_map
|
||||
))
|
||||
|
||||
return TrendResponse(series=series_list, years=years_range)
|
||||
|
||||
|
||||
class ProjectsTrendStrategy(TrendStrategy):
|
||||
async def get_trend(
|
||||
self,
|
||||
topics: List[str],
|
||||
keywords: Optional[List[str]] = None,
|
||||
soft_search: bool = True,
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None,
|
||||
authors: Optional[List[str]] = None,
|
||||
) -> TrendResponse:
|
||||
# Stub for third-party funding counts. Returns a simulated funding curve.
|
||||
start_year = 2000
|
||||
end_year = datetime.datetime.now().year - 1
|
||||
years_range = list(range(start_year, end_year + 1))
|
||||
|
||||
primary_inst_name = DEFAULT_INSTITUTION_NAME
|
||||
entities = [primary_inst_name]
|
||||
if institutions:
|
||||
entities.extend(institutions)
|
||||
|
||||
series_list = []
|
||||
for entity in entities:
|
||||
topic_data_map = {}
|
||||
for topic in topics:
|
||||
yearly_data_items = []
|
||||
seed = hash(entity + topic + "proj") % 100
|
||||
np.random.seed(seed)
|
||||
counts = np.sort(np.random.randint(0, 10, size=len(years_range)))
|
||||
cum_counts = list(np.cumsum(counts))
|
||||
max_cum = cum_counts[-1] if cum_counts[-1] > 0 else 1
|
||||
|
||||
for idx, yr in enumerate(years_range):
|
||||
yearly_data_items.append(TopicYearlyData(
|
||||
year=yr,
|
||||
raw=int(counts[idx]),
|
||||
normalized=float(counts[idx] / 10.0),
|
||||
cumulative=float(cum_counts[idx] / max_cum),
|
||||
institutions_count=1
|
||||
))
|
||||
topic_data_map[topic] = yearly_data_items
|
||||
|
||||
series_list.append(TrendSeries(
|
||||
entity_id=entity,
|
||||
entity_name=entity.split("/")[-1],
|
||||
entity_type="institution",
|
||||
topic_data=topic_data_map
|
||||
))
|
||||
|
||||
return TrendResponse(series=series_list, years=years_range)
|
||||
|
||||
|
||||
class NewsTrendStrategy(TrendStrategy):
|
||||
async def get_trend(
|
||||
self,
|
||||
topics: List[str],
|
||||
keywords: Optional[List[str]] = None,
|
||||
soft_search: bool = True,
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None,
|
||||
authors: Optional[List[str]] = None,
|
||||
) -> TrendResponse:
|
||||
start_year = 2000
|
||||
end_year = datetime.datetime.now().year - 1
|
||||
years_range = list(range(start_year, end_year + 1))
|
||||
|
||||
search_terms = keywords if keywords else topics
|
||||
|
||||
# Each series will map all topic keys to its data.
|
||||
accumulated_data = {
|
||||
f"news_topic_{t}": {top: {yr: (0, 1) for yr in years_range} for top in topics}
|
||||
for t in topics
|
||||
}
|
||||
|
||||
# Query UDE news postprocessed index to get matching news IDs
|
||||
async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]:
|
||||
term = search_terms[idx] if idx < len(search_terms) else t_name
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
query={"match": {"keywords": term}},
|
||||
size=10000,
|
||||
source=["news_id"],
|
||||
cluster="inse"
|
||||
)
|
||||
return [
|
||||
hit["_source"]["news_id"]
|
||||
for hit in res.get("hits", {}).get("hits", [])
|
||||
if hit.get("_source", {}).get("news_id")
|
||||
]
|
||||
except Exception as e:
|
||||
logger.warning("Failed to search UDE news postproc keywords: %s", e)
|
||||
return []
|
||||
|
||||
# Find all matching news IDs concurrently
|
||||
matching_ids_list = await asyncio.gather(*[
|
||||
fetch_news_ids_for_term(idx, t) for idx, t in enumerate(topics)
|
||||
])
|
||||
|
||||
async def count_by_year(t_name: str, news_ids: List[str]):
|
||||
if not news_ids:
|
||||
return
|
||||
try:
|
||||
# Query aktuell index using matching news IDs and aggregate by date_year
|
||||
res = await elasticsearch.search(
|
||||
index="aktuell",
|
||||
body={
|
||||
"query": {"bool": {"filter": [
|
||||
{"ids": {"values": news_ids}},
|
||||
{"range": {"date_year": {"gte": start_year, "lte": end_year}}}
|
||||
]}},
|
||||
"aggs": {
|
||||
"by_year": {
|
||||
"terms": {"field": "date_year", "size": len(years_range) * 2}
|
||||
}
|
||||
}
|
||||
},
|
||||
size=0,
|
||||
cluster="inse"
|
||||
)
|
||||
buckets = res.get("aggregations", {}).get("by_year", {}).get("buckets", [])
|
||||
for b in buckets:
|
||||
yr = int(b.get("key"))
|
||||
count = int(b.get("doc_count", 0))
|
||||
if yr in years_range:
|
||||
entity_key = f"news_topic_{t_name}"
|
||||
# Set this count for all topic keys in this topic's series
|
||||
for top in topics:
|
||||
accumulated_data[entity_key][top] = dict(accumulated_data[entity_key][top])
|
||||
accumulated_data[entity_key][top][yr] = (count, 1)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to aggregate news years from ES: %s", e)
|
||||
|
||||
# Aggregate news publication years concurrently
|
||||
await asyncio.gather(*[
|
||||
count_by_year(t, ids) for t, ids in zip(topics, matching_ids_list)
|
||||
])
|
||||
|
||||
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
||||
|
||||
series_list = []
|
||||
for t_name in topics:
|
||||
entity_key = f"news_topic_{t_name}"
|
||||
topic_data_map = {}
|
||||
for topic in topics:
|
||||
yearly_data_items = []
|
||||
lookup = normalized_lookup.get((entity_key, topic), {})
|
||||
norm_vals = lookup.get("normalized", [0.0] * len(years_range))
|
||||
cum_vals = lookup.get("cumulative", [0.0] * len(years_range))
|
||||
|
||||
for idx, yr in enumerate(years_range):
|
||||
count, _ = accumulated_data[entity_key][topic][yr]
|
||||
yearly_data_items.append(TopicYearlyData(
|
||||
year=yr,
|
||||
raw=count,
|
||||
normalized=norm_vals[idx],
|
||||
cumulative=cum_vals[idx],
|
||||
institutions_count=1
|
||||
))
|
||||
topic_data_map[topic] = yearly_data_items
|
||||
|
||||
series_list.append(TrendSeries(
|
||||
entity_id=entity_key,
|
||||
entity_name=t_name,
|
||||
entity_type="institution",
|
||||
topic_data=topic_data_map
|
||||
))
|
||||
|
||||
return TrendResponse(series=series_list, years=years_range)
|
||||
|
||||
|
||||
class AllTrendStrategy(TrendStrategy):
|
||||
async def get_trend(
|
||||
self,
|
||||
topics: List[str],
|
||||
keywords: Optional[List[str]] = None,
|
||||
soft_search: bool = True,
|
||||
institutions: Optional[List[str]] = None,
|
||||
countries: Optional[List[str]] = None,
|
||||
regions: Optional[List[str]] = None,
|
||||
authors: Optional[List[str]] = None,
|
||||
) -> TrendResponse:
|
||||
# Runs Publications, Patents, Projects, and News strategies concurrently
|
||||
# overlays their curves to display a Topic Lifecycle dashboard for UDE
|
||||
pub_strat = PublicationsTrendStrategy()
|
||||
pat_strat = PatentsTrendStrategy()
|
||||
proj_strat = ProjectsTrendStrategy()
|
||||
news_strat = NewsTrendStrategy()
|
||||
|
||||
# Query UDE publications data only
|
||||
pub_task = pub_strat.get_trend(topics, keywords, soft_search, institutions=[DEFAULT_INSTITUTION_ID])
|
||||
pat_task = pat_strat.get_trend(topics, keywords, soft_search)
|
||||
proj_task = proj_strat.get_trend(topics, keywords, soft_search)
|
||||
news_task = news_strat.get_trend(topics, keywords, soft_search)
|
||||
|
||||
pub_res, pat_res, proj_res, news_res = await asyncio.gather(pub_task, pat_task, proj_task, news_task)
|
||||
|
||||
start_year = 2000
|
||||
end_year = datetime.datetime.now().year - 1
|
||||
years_range = list(range(start_year, end_year + 1))
|
||||
|
||||
# Extract UDE publications series
|
||||
pub_series = next((s for s in pub_res.series if s.entity_id == DEFAULT_INSTITUTION_ID), None)
|
||||
pat_series = pat_res.series[0] if pat_res.series else None
|
||||
proj_series = proj_res.series[0] if proj_res.series else None
|
||||
|
||||
# Reconstruct a single news series containing the correct data for each topic
|
||||
merged_news_topic_data = {}
|
||||
for topic in topics:
|
||||
term_key = f"news_topic_{topic}"
|
||||
matching_series = next((s for s in news_res.series if s.entity_id == term_key), None)
|
||||
if matching_series and topic in matching_series.topic_data:
|
||||
merged_news_topic_data[topic] = matching_series.topic_data[topic]
|
||||
else:
|
||||
merged_news_topic_data[topic] = [
|
||||
TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1)
|
||||
for yr in years_range
|
||||
]
|
||||
|
||||
news_series = TrendSeries(
|
||||
entity_id="news",
|
||||
entity_name="UDE Campus Aktuell Beiträge",
|
||||
entity_type="institution",
|
||||
topic_data=merged_news_topic_data
|
||||
)
|
||||
|
||||
# Build composite TrendSeries
|
||||
composite_series = []
|
||||
|
||||
# Helper to construct TrendSeries
|
||||
def add_composite(series_obj: Optional[TrendSeries], c_id: str, c_name: str):
|
||||
topic_data_map = {}
|
||||
for topic in topics:
|
||||
if series_obj and topic in series_obj.topic_data:
|
||||
topic_data_map[topic] = series_obj.topic_data[topic]
|
||||
else:
|
||||
# Fallback empty list
|
||||
topic_data_map[topic] = [
|
||||
TopicYearlyData(year=yr, raw=0, normalized=0.0, cumulative=0.0, institutions_count=1)
|
||||
for yr in years_range
|
||||
]
|
||||
composite_series.append(TrendSeries(
|
||||
entity_id=c_id,
|
||||
entity_name=c_name,
|
||||
entity_type="institution",
|
||||
topic_data=topic_data_map
|
||||
))
|
||||
|
||||
add_composite(pub_series, "publications", "Akademische Publikationen (UDE)")
|
||||
add_composite(pat_series, "patents", "Patentanmeldungen (UDE)")
|
||||
add_composite(proj_series, "projects", "Drittmittelförderung (UDE)")
|
||||
add_composite(news_series, "news", "UDE Campus Aktuell Beiträge")
|
||||
|
||||
return TrendResponse(series=composite_series, years=years_range)
|
||||
@@ -435,6 +435,10 @@ export class UniversityRankingsService extends BaseService {
|
||||
institutions?: Array<string>,
|
||||
countries?: Array<string>,
|
||||
regions?: Array<string>,
|
||||
keywords?: Array<string>,
|
||||
softSearch?: boolean,
|
||||
searchType?: string,
|
||||
authors?: Array<string>,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
@@ -448,6 +452,10 @@ export class UniversityRankingsService extends BaseService {
|
||||
institutions?: Array<string>,
|
||||
countries?: Array<string>,
|
||||
regions?: Array<string>,
|
||||
keywords?: Array<string>,
|
||||
softSearch?: boolean,
|
||||
searchType?: string,
|
||||
authors?: Array<string>,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
@@ -461,6 +469,10 @@ export class UniversityRankingsService extends BaseService {
|
||||
institutions?: Array<string>,
|
||||
countries?: Array<string>,
|
||||
regions?: Array<string>,
|
||||
keywords?: Array<string>,
|
||||
softSearch?: boolean,
|
||||
searchType?: string,
|
||||
authors?: Array<string>,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
@@ -474,6 +486,10 @@ export class UniversityRankingsService extends BaseService {
|
||||
institutions?: Array<string>,
|
||||
countries?: Array<string>,
|
||||
regions?: Array<string>,
|
||||
keywords?: Array<string>,
|
||||
softSearch?: boolean,
|
||||
searchType?: string,
|
||||
authors?: Array<string>,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
@@ -525,6 +541,38 @@ export class UniversityRankingsService extends BaseService {
|
||||
);
|
||||
});
|
||||
}
|
||||
if (keywords) {
|
||||
keywords.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'keywords',
|
||||
);
|
||||
});
|
||||
}
|
||||
if (softSearch !== undefined && softSearch !== null) {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>softSearch,
|
||||
'soft_search',
|
||||
);
|
||||
}
|
||||
if (searchType) {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>searchType,
|
||||
'search_type',
|
||||
);
|
||||
}
|
||||
if (authors) {
|
||||
authors.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'authors',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
|
||||
@@ -38,6 +38,18 @@ export class SearchResultsStateService {
|
||||
() => this._payload()?.manualKeywords ?? [],
|
||||
);
|
||||
|
||||
// Compute parallel keywords and topic names for trend dashboard strategies
|
||||
readonly keywordsList = computed(() => this.keywords());
|
||||
readonly topicsList = computed(() => {
|
||||
const ext = this.extractedKeywords();
|
||||
const man = this.manualKeywords();
|
||||
const all = [...ext, ...man];
|
||||
return this.keywords().map((kw) => {
|
||||
const match = all.find((e) => e.llm_keyword?.keyword === kw);
|
||||
return match?.topic_mapping?.topic?.display_name ?? kw;
|
||||
});
|
||||
});
|
||||
|
||||
setPayload(payload: SearchResultsPayload): void {
|
||||
this._payload.set(payload);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user