feature/Keyword_search_rework #229

Merged
kuzko merged 5 commits from feature/Keyword_search_rework into dev 2026-07-20 01:10:03 +02:00
14 changed files with 3622 additions and 10150 deletions
File diff suppressed because it is too large Load Diff
@@ -745,6 +745,11 @@ async def get_trend_data(
return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings)
# Default fallback institution: University of Duisburg-Essen
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
DEFAULT_TOP_TOPICS_SIZE = 20
async def get_top_topics_for_entity(
entity_id: str,
entity_type: str,
@@ -773,12 +778,12 @@ async def get_top_topics_for_entity(
pass
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
top_10 = sorted_topics[:10]
items = [{"name": name, "count": count} for name, count in top_10]
top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE]
items = [{"name": name, "count": count} for name, count in top_slice]
sum_top_10 = sum(count for name, count in top_10)
sum_top = sum(count for name, count in top_slice)
total_topics = sum(topic_counts.values())
other_count = max(0, total_topics - sum_top_10)
other_count = max(0, total_topics - sum_top)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
@@ -787,6 +792,349 @@ async def get_top_topics_for_entity(
logger.error("Failed to query top patent topics for institution: %s", e)
return {"items": []}
if search_type == "projects":
try:
from inse.patents.search_client import PatentSearchClient
patent_client = PatentSearchClient()
short_id = entity_id.split("/")[-1]
aliases = [short_id, entity_id]
if entity_type == "institution":
try:
from inse.institutions.institutions_search_client import InstitutionsSearchClient
client = InstitutionsSearchClient()
resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(entity_id)
if resolved_aliases:
aliases = resolved_aliases
except Exception as e:
logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e)
include_german = True
if entity_type == "country" and entity_id.strip().upper() != "DE":
include_german = False
elif entity_type == "region" and "DE" not in entity_id.strip().upper():
include_german = False
project_ids_by_index = {}
# 1. BUND
if include_german:
bund_filters = []
if entity_type == "institution":
bund_filters.append({
"bool": {
"should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
"minimum_should_match": 1
}
})
try:
bund_res = await patent_client._search(
index=ESIndex.PROJECTS_BUND_V1.value,
payload={
"query": {"bool": {"filter": bund_filters}},
"size": 10000,
"_source": ["_id"]
}
)
p_ids = [h["_id"] for h in bund_res.get("hits", {}).get("hits", []) if "_id" in h]
if p_ids:
project_ids_by_index[ESIndex.PROJECTS_BUND_TOPICS.value] = p_ids
except Exception as e:
logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e)
# 2. DFG
if include_german:
try:
dfg_pids = []
if entity_type == "institution":
should_clauses = [{"match": {"root_name_en": {"query": alias, "operator": "and"}}} for alias in aliases]
dfg_inst_res = await patent_client._search(
index=ESIndex.DFG_INSTITUTES.value,
payload={"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}}, "size": 1000}
)
for hit in dfg_inst_res.get("hits", {}).get("hits", []):
for p in hit.get("_source", {}).get("projects", []):
if p.get("project_id"):
dfg_pids.append(str(p["project_id"]))
if dfg_pids or entity_type != "institution":
dfg_filters = []
if dfg_pids:
dfg_filters.append({"ids": {"values": dfg_pids}})
dfg_res = await patent_client._search(
index=ESIndex.DFG_PROJECTS.value,
payload={"query": {"bool": {"filter": dfg_filters}}, "size": 10000, "_source": ["id"]}
)
p_ids = [str(h["_source"]["id"]) for h in dfg_res.get("hits", {}).get("hits", []) if h.get("_source", {}).get("id")]
if p_ids:
project_ids_by_index[ESIndex.PROJECTS_DFG_TOPICS.value] = p_ids
except Exception as e:
logger.warning("Failed to fetch DFG project IDs in get_top_topics_for_entity: %s", e)
# 3. EU CORDIS
eu_indices = [
(ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value),
(ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value),
(ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value)
]
for org_idx, proj_idx, topic_idx in eu_indices:
try:
filter_clauses = []
if entity_type == "institution":
filter_clauses.append({"terms": {"name.keyword": [alias.upper() for alias in aliases]}})
elif entity_type == "country":
filter_clauses.append({"term": {"country": entity_id.strip().upper()}})
eu_org_res = await patent_client._search(
index=org_idx.value,
payload={
"query": {"bool": {"filter": filter_clauses}},
"size": 0,
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}}
}
)
eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
if eu_pids:
project_ids_by_index[topic_idx] = eu_pids
except Exception as e:
logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e)
topic_counts = {}
for topic_idx, p_ids in project_ids_by_index.items():
if not p_ids:
continue
for i in range(0, len(p_ids), 1000):
chunk = p_ids[i:i+1000]
payload = {
"query": {"terms": {"project_id": chunk}},
"size": 0,
"aggs": {
"topic_matches": {
"nested": {"path": "topic_matches"},
"aggs": {
"topics": {
"terms": {"field": "topic_matches.topic_display_name", "size": 100}
}
}
}
}
}
try:
res = await patent_client._search(index=topic_idx, payload=payload)
buckets = res.get("aggregations", {}).get("topic_matches", {}).get("topics", {}).get("buckets", [])
for b in buckets:
t_name = b["key"]
cnt = b["doc_count"]
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
except Exception as e:
logger.warning("Failed to aggregate topics from %s: %s", topic_idx, e)
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE]
items = [{"name": name, "count": count} for name, count in top_slice]
sum_top = sum(count for name, count in top_slice)
total_topics = sum(topic_counts.values())
other_count = max(0, total_topics - sum_top)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
return {"items": items}
except Exception as e:
logger.error("Failed to query top project topics for entity: %s", e)
return {"items": []}
# Default fallback institution: University of Duisburg-Essen
DEFAULT_INSTITUTION_ID = "https://openalex.org/I62318514"
DEFAULT_INSTITUTION_NAME = "University of Duisburg-Essen"
DEFAULT_TOP_TOPICS_SIZE = 20
async def get_top_topics_for_entity(
entity_id: str,
entity_type: str,
start_year: int,
end_year: int,
search_type: str
) -> Dict[str, Any]:
if search_type == "patents" and entity_type == "institution":
from inse.patents.org.logic import get_org_patents_by_institution_id
try:
res = await get_org_patents_by_institution_id(
institution_id=entity_id,
match_type="all",
page=0,
size=10000
)
topic_counts = {}
for p in res.patents:
try:
yr = int(p.publication_year) if p.publication_year else None
if yr and start_year <= yr <= end_year:
for ot in p.openalex_topics:
if ot.topic_display_name:
topic_counts[ot.topic_display_name] = topic_counts.get(ot.topic_display_name, 0) + 1
except Exception:
pass
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE]
items = [{"name": name, "count": count} for name, count in top_slice]
sum_top = sum(count for name, count in top_slice)
total_topics = sum(topic_counts.values())
other_count = max(0, total_topics - sum_top)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
return {"items": items}
except Exception as e:
logger.error("Failed to query top patent topics for institution: %s", e)
return {"items": []}
if search_type == "projects":
try:
from inse.patents.search_client import PatentSearchClient
patent_client = PatentSearchClient()
short_id = entity_id.split("/")[-1]
aliases = [short_id, entity_id]
if entity_type == "institution":
try:
from inse.institutions.institutions_search_client import InstitutionsSearchClient
client = InstitutionsSearchClient()
resolved_aliases = await client.get_institution_aliases_by_oa_institution_id(short_id)
if resolved_aliases:
aliases = list(resolved_aliases)
except Exception as e:
logger.warning("Failed to resolve institution aliases in get_top_topics_for_entity: %s", e)
include_german = True
if entity_type == "country" and entity_id.strip().upper() != "DE":
include_german = False
elif entity_type == "region" and "DE" not in entity_id.strip().upper():
include_german = False
project_ids_by_index = {}
# 1. BUND
if include_german:
bund_filters = []
if entity_type == "institution":
bund_filters.append({
"bool": {
"should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
"minimum_should_match": 1
}
})
try:
bund_res = await patent_client._search(
index=ESIndex.PROJECTS_BUND_V1.value,
payload={
"query": {"bool": {"filter": bund_filters}},
"size": 10000,
"_source": ["_id"]
}
)
p_ids = [h["_id"] for h in bund_res.get("hits", {}).get("hits", []) if "_id" in h]
if p_ids:
project_ids_by_index[ESIndex.PROJECTS_BUND_TOPICS.value] = p_ids
except Exception as e:
logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e)
# 2. DFG
if include_german:
try:
dfg_pids = []
if entity_type == "institution":
should_clauses = [{"match": {"root_name_en": {"query": alias, "operator": "and"}}} for alias in aliases]
dfg_inst_res = await patent_client._search(
index=ESIndex.DFG_INSTITUTES.value,
payload={"query": {"bool": {"should": should_clauses, "minimum_should_match": 1}}, "size": 1000}
)
for hit in dfg_inst_res.get("hits", {}).get("hits", []):
for p in hit.get("_source", {}).get("projects", []):
if p.get("project_id"):
dfg_pids.append(str(p["project_id"]))
if dfg_pids or entity_type != "institution":
dfg_filters = []
if dfg_pids:
dfg_filters.append({"ids": {"values": dfg_pids}})
dfg_res = await patent_client._search(
index=ESIndex.DFG_PROJECTS.value,
payload={"query": {"bool": {"filter": dfg_filters}}, "size": 10000, "_source": ["id"]}
)
p_ids = [str(h["_source"]["id"]) for h in dfg_res.get("hits", {}).get("hits", []) if h.get("_source", {}).get("id")]
if p_ids:
project_ids_by_index[ESIndex.PROJECTS_DFG_TOPICS.value] = p_ids
except Exception as e:
logger.warning("Failed to fetch DFG project IDs in get_top_topics_for_entity: %s", e)
# 3. EU CORDIS
eu_indices = [
(ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value),
(ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value),
(ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value)
]
for org_idx, proj_idx, topic_idx in eu_indices:
try:
filter_clauses = []
if entity_type == "institution":
filter_clauses.append({"terms": {"name.keyword": [alias.upper() for alias in aliases]}})
elif entity_type == "country":
filter_clauses.append({"term": {"country": entity_id.strip().upper()}})
eu_org_res = await patent_client._search(
index=org_idx.value,
payload={
"query": {"bool": {"filter": filter_clauses}},
"size": 0,
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}}
}
)
eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
if eu_pids:
project_ids_by_index[topic_idx] = eu_pids
except Exception as e:
logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e)
topic_counts = {}
for topic_idx, p_ids in project_ids_by_index.items():
if not p_ids:
continue
for i in range(0, len(p_ids), 500):
chunk = p_ids[i:i+500]
payload = {
"query": {"terms": {"project_id": chunk}},
"size": 10000,
"_source": ["topic_matches"]
}
try:
res = await patent_client._search(index=topic_idx, payload=payload)
hits = res.get("hits", {}).get("hits", [])
for hit in hits:
matches = hit.get("_source", {}).get("topic_matches", [])
for m in matches:
t_name = m.get("topic_display_name")
if t_name:
topic_counts[t_name] = topic_counts.get(t_name, 0) + 1
except Exception as e:
logger.warning("Failed to aggregate topics from %s: %s", topic_idx, e)
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE]
items = [{"name": name, "count": count} for name, count in top_slice]
sum_top = sum(count for name, count in top_slice)
total_topics = sum(topic_counts.values())
other_count = max(0, total_topics - sum_top)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
return {"items": items}
except Exception as e:
logger.error("Failed to query top project topics for entity: %s", e)
return {"items": []}
# Default fallback: openalex-works* query for publications/authors
# 1. Normalize ID and prepare filter clause
if entity_type == "institution":
entity_url = entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id}"
@@ -812,7 +1160,6 @@ async def get_top_topics_for_entity(
}
}
elif entity_type == "region":
from inse.model import ESIndex
ccs = []
try:
res = await elasticsearch.search(
@@ -862,7 +1209,7 @@ async def get_top_topics_for_entity(
"top_topics": {
"terms": {
"field": "primary_topic.id",
"size": 10
"size": DEFAULT_TOP_TOPICS_SIZE
},
"aggs": {
"top_topic_hits": {
@@ -896,8 +1243,8 @@ async def get_top_topics_for_entity(
# Calculate "Other"
total_hits = res.get("hits", {}).get("total", {}).get("value", 0)
sum_top_10 = sum(b["count"] for b in items)
other_count = max(0, total_hits - sum_top_10)
sum_top_slice = sum(b["count"] for b in items)
other_count = max(0, total_hits - sum_top_slice)
if other_count > 0:
items.append({"name": "Andere Themen", "count": other_count})
@@ -905,4 +1252,3 @@ async def get_top_topics_for_entity(
except Exception as e:
logger.error("Failed to query top topics for entity in ES: %s", e)
return {"items": []}
@@ -746,22 +746,37 @@ class ProjectsTrendStrategy(TrendStrategy):
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)
def clean_inst_id(id_str: str) -> str:
return id_str.split("/")[-1] if id_str and "/" in id_str else id_str
primary_inst_short = clean_inst_id(DEFAULT_INSTITUTION_ID)
primary_inst_full = f"https://openalex.org/{primary_inst_short}"
raw_insts = institutions or []
query_insts_short = [clean_inst_id(i) for i in raw_insts if i]
if primary_inst_short not in query_insts_short:
query_insts_short.insert(0, primary_inst_short)
# Preserve order while deduplicating
seen_insts = set()
dedup_inst_shorts = []
for s_id in query_insts_short:
if s_id not in seen_insts:
seen_insts.add(s_id)
dedup_inst_shorts.append(s_id)
query_institutions = dedup_inst_shorts
ids_to_resolve = [f"https://openalex.org/{i}" for i in query_institutions]
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))
# 1. Resolve institution names & aliases, country names, and regions
async def fetch_institutions():
names = {primary_inst_id: primary_inst_name}
names = {primary_inst_full: DEFAULT_INSTITUTION_NAME, primary_inst_short: DEFAULT_INSTITUTION_NAME}
codes = {}
aliases_map = {}
if not ids_to_resolve:
@@ -778,20 +793,27 @@ class ProjectsTrendStrategy(TrendStrategy):
)
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
inst_id = source["id"]
names[inst_id] = source.get("display_name", inst_id)
codes[inst_id] = source.get("country_code", "")
async def get_aliases(inst_id):
try:
return inst_id, await client.get_institution_aliases_by_oa_institution_id(inst_id)
except Exception as e:
logger.warning("Failed to get aliases for %s: %s", inst_id, e)
return inst_id, [names.get(inst_id, inst_id)]
full_id = source["id"]
short_id = clean_inst_id(full_id)
d_name = source.get("display_name", full_id)
c_code = source.get("country_code", "")
names[full_id] = d_name
names[short_id] = d_name
codes[full_id] = c_code
codes[short_id] = c_code
alias_results = await asyncio.gather(*(get_aliases(inst_id) for inst_id in ids_to_resolve))
for inst_id, aliases in alias_results:
aliases_map[inst_id] = aliases
async def get_aliases(inst_short_id):
try:
resolved = await client.get_institution_aliases_by_oa_institution_id(inst_short_id)
return inst_short_id, resolved or [names.get(inst_short_id, inst_short_id)]
except Exception as e:
logger.warning("Failed to get aliases for %s: %s", inst_short_id, e)
return inst_short_id, [names.get(inst_short_id, inst_short_id)]
alias_results = await asyncio.gather(*(get_aliases(i) for i in query_institutions))
for inst_short_id, aliases in alias_results:
aliases_map[inst_short_id] = aliases
aliases_map[f"https://openalex.org/{inst_short_id}"] = aliases
except Exception as e:
logger.warning("Failed to resolve institution details from ES: %s", e)
return names, codes, aliases_map
@@ -1136,7 +1158,28 @@ class ProjectsTrendStrategy(TrendStrategy):
{"match": {"abstract_de": keyword}},
{"match": {"abstract_en": keyword}},
{"match": {"final_report_abstract_de": keyword}},
{"match": {"final_report_abstract_en": keyword}}
{"match": {"final_report_abstract_en": keyword}},
{
"nested": {
"path": "publications",
"query": {"match": {"publications.title": keyword}}
}
},
{
"nested": {
"path": "subject_classification",
"query": {
"bool": {
"should": [
{"match": {"subject_classification.fach": keyword}},
{"match": {"subject_classification.fachkollegium": keyword}},
{"match": {"subject_classification.wissenschaftsbereich": keyword}}
],
"minimum_should_match": 1
}
}
}
}
],
"minimum_should_match": 1
}
@@ -1228,19 +1271,19 @@ class ProjectsTrendStrategy(TrendStrategy):
for agg_type, buckets in results:
for b in buckets:
if agg_type == "date":
yr_str = b.get("key_as_string")
yr_str = b.get("key_as_string") or str(b.get("key", ""))
if yr_str:
try:
yr = int(yr_str)
yr = int(yr_str[:4])
if start_year <= yr <= end_year:
year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
except ValueError:
pass
else: # terms
yr = b.get("key")
if yr is not None:
yr_val = b.get("key")
if yr_val is not None:
try:
yr = int(yr)
yr = int(str(yr_val)[:4])
if start_year <= yr <= end_year:
year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
except ValueError:
@@ -1263,8 +1306,8 @@ class ProjectsTrendStrategy(TrendStrategy):
for entity_key, topic_dict in accumulated_data.items():
entity_type, entity_val = filters_map[entity_key]
if entity_type == "institution":
entity_id = entity_val
entity_name = resolved_names.get(entity_id, entity_id).split("/")[-1]
entity_id = entity_val if entity_val.startswith("http") else f"https://openalex.org/{entity_val}"
entity_name = resolved_names.get(entity_val, entity_val).split("/")[-1]
elif entity_type == "country":
entity_id = entity_val
entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}")
@@ -1432,61 +1475,46 @@ class AllTrendStrategy(TrendStrategy):
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
target_inst = institutions[0] if institutions and len(institutions) > 0 else DEFAULT_INSTITUTION_ID
short_id = target_inst.split("/")[-1].upper()
is_ude = (short_id == "I62318514")
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, fuzzy, institutions=[DEFAULT_INSTITUTION_ID])
pat_task = pat_strat.get_trend(topics, keywords, fuzzy)
proj_task = proj_strat.get_trend(topics, keywords, fuzzy)
news_task = news_strat.get_trend(topics, keywords, fuzzy)
tasks = [
pub_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]),
pat_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst]),
proj_strat.get_trend(topics, keywords, fuzzy, institutions=[target_inst])
]
pub_res, pat_res, proj_res, news_res = await asyncio.gather(pub_task, pat_task, proj_task, news_task)
if is_ude:
news_strat = NewsTrendStrategy()
tasks.append(news_strat.get_trend(topics, keywords, fuzzy))
results = await asyncio.gather(*tasks)
pub_res = results[0]
pat_res = results[1]
proj_res = results[2]
news_res = results[3] if is_ude else None
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)
pub_series = pub_res.series[0] if pub_res.series else 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
@@ -1498,9 +1526,29 @@ class AllTrendStrategy(TrendStrategy):
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")
add_composite(pub_series, "publications", "Akademische Publikationen")
add_composite(pat_series, "patents", "Patentanmeldungen")
add_composite(proj_series, "projects", "Drittmittelförderung")
if is_ude and news_res:
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
)
add_composite(news_series, "news", "UDE Campus Aktuell Beiträge")
return TrendResponse(series=composite_series, years=years_range)
@@ -1,17 +1,15 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface DfgInstitutionSummary {
id: number;
name_de?: string | null;
name_en?: string | null;
export interface DfgInstitutionSummary {
id: number;
name_de?: string | null;
name_en?: string | null;
}
+9 -11
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -9,14 +9,12 @@
*/
import { DfgInstitutionSummary } from './dfgInstitutionSummary';
export interface DfgPersonSummary {
person_id: number;
project_ref_id: number;
full_name?: string | null;
role_label_en?: string | null;
role_label_de?: string | null;
root_institution?: DfgInstitutionSummary | null;
institution?: DfgInstitutionSummary | null;
export interface DfgPersonSummary {
person_id: number;
project_ref_id: number;
full_name?: string | null;
role_label_en?: string | null;
role_label_de?: string | null;
root_institution?: DfgInstitutionSummary | null;
institution?: DfgInstitutionSummary | null;
}
+27 -29
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -10,32 +10,30 @@
import { DfgInstitutionSummary } from './dfgInstitutionSummary';
import { DfgPersonSummary } from './dfgPersonSummary';
export interface DfgProjectSummary {
/**
* The unique identifier of the DFG project.
*/
id: string;
link?: string | null;
title?: string | null;
professional_classification?: string | null;
funding_start?: string | null;
funding_end?: string | null;
/**
* Root institutions associated with the project (e.g. universities or umbrella organizations).
*/
root_institutions?: Array<DfgInstitutionSummary>;
/**
* Institutions associated with the project.
*/
institutions?: Array<DfgInstitutionSummary>;
/**
* The names of the persons involved in the DFG project.
*/
names?: Array<string>;
/**
* The persons involved in the DFG project.
*/
persons?: Array<DfgPersonSummary>;
export interface DfgProjectSummary {
/**
* The unique identifier of the DFG project.
*/
id: string;
link?: string | null;
title?: string | null;
professional_classification?: string | null;
funding_start?: string | null;
funding_end?: string | null;
/**
* Root institutions associated with the project (e.g. universities or umbrella organizations).
*/
root_institutions?: Array<DfgInstitutionSummary>;
/**
* Institutions associated with the project.
*/
institutions?: Array<DfgInstitutionSummary>;
/**
* The names of the persons involved in the DFG project.
*/
names?: Array<string>;
/**
* The persons involved in the DFG project.
*/
persons?: Array<DfgPersonSummary>;
}
@@ -5,7 +5,5 @@
<span class="pie-loader-text">Lade Daten...</span>
</div>
}
@for (key of [entityId() || titleText() || 'overall']; track key) {
<div echarts [options]="chartOptions()" class="pie-chart-container"></div>
}
<div echarts [options]="chartOptions()" class="pie-chart-container"></div>
</div>
@@ -23,6 +23,12 @@
</button>
<button
[class.active]="selectedSearchType() === 'news'"
[disabled]="!isUde()"
[title]="
!isUde()
? 'News-Trends sind nur für die Universität Duisburg-Essen verfügbar'
: ''
"
(click)="setSearchType('news')">
<mat-icon>campaign</mat-icon> News
</button>
@@ -159,7 +165,10 @@
<app-uni-pie-chart
[titleText]="
'Top 10 Themen (Gesamt): ' + selectedPieEntity()!.name
'Top ' +
topTopicsSize() +
' Themen (Gesamt): ' +
selectedPieEntity()!.name
"
[pieData]="topTopicsData()"
[loading]="isTopTopicsLoading() || isTrendLoading()"
@@ -174,6 +183,7 @@
<!-- Unified Institution Search, Compare, & Recommendations -->
@if (activeConfig().showInstitutionSelector) {
<app-institution-selector
[activeTab]="selectedSearchType()"
[comparisonInstitutions]="comparisonInstitutions()"
[primaryInstitution]="primaryInstitution()"
[primaryInstitutionName]="primaryInstitutionName()"
@@ -196,6 +206,7 @@
<!-- Reusable Author Selection UI (Main Panel below chart) -->
@if (activeConfig().showAuthorSelector) {
<app-author-selector
[activeTab]="selectedSearchType()"
[comparisonAuthors]="comparisonAuthors()"
[topSuggestions]="recommendedAuthors()"
[isSuggestionsLoading]="isSuggestionsLoading()"
@@ -212,10 +212,14 @@
height: 16px;
}
&:hover:not(.active) {
&:hover:not(.active):not([disabled]) {
color: #0f172a;
background: #f1f5f9;
}
&[disabled] {
opacity: 0.4;
cursor: not-allowed;
}
&.active {
background: white;
color: #3b82f6;
@@ -34,7 +34,9 @@ import {
UniversityRankingsService,
InstitutionsService,
PersonsService,
OrganizationService,
} from '../../../api';
import { CredentialService } from '../../../shared/services/credential.service';
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import { YearRangeSliderComponent } from '../../../shared/ui/year-range-slider/year-range-slider.component';
@@ -131,6 +133,12 @@ export class UniTrendParentComponent implements OnInit {
private readonly apiService = inject(UniversityRankingsService);
private readonly institutionsApiService = inject(InstitutionsService);
private readonly personsApiService = inject(PersonsService);
private readonly organizationService = inject(OrganizationService, {
optional: true,
});
private readonly credentialService = inject(CredentialService, {
optional: true,
});
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
@@ -139,6 +147,8 @@ export class UniTrendParentComponent implements OnInit {
optional: true,
});
readonly topTopicsSize = signal<number>(20);
// Input containing extracted/selected keywords from parent
readonly keywordsInput = input<string[]>([], { alias: 'keywords' });
@@ -156,10 +166,15 @@ export class UniTrendParentComponent implements OnInit {
'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all'
>('publications');
readonly selectedTrendTopics = signal<string[]>([]);
readonly primaryInstitution = signal<string | null>(null);
readonly primaryInstitution = signal<string | null>('I62318514');
readonly primaryInstitutionName = signal<string>(
'Universität Duisburg-Essen',
);
readonly isUde = computed(() => {
const p = this.primaryInstitution() || 'I62318514';
return p.includes('I62318514') || p === 'I62318514';
});
readonly comparisonInstitutions = signal<CompareItem[]>([]);
readonly comparisonCountries = signal<CompareItem[]>([
{ id: 'DE', name: 'Deutschland' },
@@ -352,16 +367,25 @@ export class UniTrendParentComponent implements OnInit {
}
// Default: publications, patents, projects
// Resilient ID normalization helper
const cleanId = (id: string | null | undefined): string => {
if (!id) return '';
const lower = id.toLowerCase().trim();
return lower.includes('/') ? lower.split('/').pop()! : lower;
};
const currentInstIds = new Set(
this.comparisonInstitutions().map((i: CompareItem) => i.id.toLowerCase()),
this.comparisonInstitutions().map((i: CompareItem) => cleanId(i.id)),
);
const currentCountryIds = new Set(
this.comparisonCountries().map((c: CompareItem) => c.id.toLowerCase()),
this.comparisonCountries().map((c: CompareItem) => cleanId(c.id)),
);
const currentRegionIds = new Set(
this.comparisonRegions().map((r: CompareItem) => r.id.toLowerCase()),
this.comparisonRegions().map((r: CompareItem) => cleanId(r.id)),
);
const primaryInstCleanId = cleanId(
this.primaryInstitution() || 'I62318514',
);
const defaultInstId = 'https://openalex.org/I62318514'.toLowerCase();
const primaryInstSeries: TrendSeries[] = [];
const compInstSeries: TrendSeries[] = [];
@@ -369,19 +393,19 @@ export class UniTrendParentComponent implements OnInit {
const regionSeries: TrendSeries[] = [];
raw.series.forEach((s: TrendSeries) => {
const id = s.entity_id.toLowerCase();
const cId = cleanId(s.entity_id);
if (s.entity_type === 'institution') {
if (id === defaultInstId) {
if (cId === primaryInstCleanId) {
primaryInstSeries.push(s);
} else if (currentInstIds.has(id)) {
} else if (currentInstIds.has(cId)) {
compInstSeries.push(s);
}
} else if (s.entity_type === 'country') {
if (currentCountryIds.has(id)) {
if (currentCountryIds.has(cId)) {
countrySeries.push(s);
}
} else if (s.entity_type === 'region') {
if (currentRegionIds.has(id)) {
if (currentRegionIds.has(cId)) {
regionSeries.push(s);
}
}
@@ -539,18 +563,23 @@ export class UniTrendParentComponent implements OnInit {
// Handle initialization and synchronization of URL state
this.route.queryParams.subscribe((params) => {
let hasInstsFromUrl = false;
if (params['search_type']) {
this.selectedSearchType.set(params['search_type'] as any);
}
// Parse institutions serialized as id|name
if (params['institutions']) {
hasInstsFromUrl = true;
const insts = Array.isArray(params['institutions'])
? params['institutions']
: [params['institutions']];
const parsed = insts.map((i: string) => {
const parts = i.split('|');
return { id: parts[0], name: parts[1] || parts[0] };
const cleanId = parts[0].includes('/')
? parts[0].split('/').pop() || parts[0]
: parts[0];
return { id: cleanId, name: parts[1] || parts[0] };
});
const currentIds = this.comparisonInstitutions()
@@ -564,10 +593,11 @@ export class UniTrendParentComponent implements OnInit {
if (currentIds !== parsedIds) {
this.comparisonInstitutions.set(parsed);
}
} else {
if (this.comparisonInstitutions().length > 0) {
this.comparisonInstitutions.set([]);
}
}
// If URL didn't specify institutions and list is currently empty, initialize defaults
if (!hasInstsFromUrl && this.comparisonInstitutions().length === 0) {
this.initializeDefaultInstitutions();
}
// Parse countries
@@ -746,13 +776,44 @@ export class UniTrendParentComponent implements OnInit {
}
ngOnInit() {
if (this.credentialService) {
const profile = this.credentialService.accountProfile();
if (profile?.organization_name) {
this.primaryInstitutionName.set(profile.organization_name);
}
const orgId = this.credentialService.effectiveOrganizationId();
if (orgId && this.organizationService) {
this.organizationService.getOrganisations().subscribe({
next: (res) => {
const matchingOrg = res.items?.find((o) => o.id === orgId);
const openAlexId =
matchingOrg?.other_inst_id ||
(matchingOrg as any)?.openalex_institution_id;
if (matchingOrg && openAlexId) {
this.primaryInstitution.set(openAlexId);
if (matchingOrg.name) {
this.primaryInstitutionName.set(matchingOrg.name);
}
}
},
error: () => {},
});
}
}
this.initializeDefaultInstitutions();
}
// Dynamically load top institutions to initialize comparisons using the top-institutions service
initializeDefaultInstitutions() {
const primaryId = this.primaryInstitution() || 'I62318514';
const primaryName =
this.primaryInstitutionName() || 'Universität Duisburg-Essen';
const kws = this.keywords();
if (kws.length === 0) return;
if (kws.length === 0) {
this.comparisonInstitutions.set([{ id: primaryId, name: primaryName }]);
return;
}
// Use mapped topic names if softSearch is false
const topics = this.state?.topicsList() ?? kws;
@@ -782,6 +843,7 @@ export class UniTrendParentComponent implements OnInit {
overallInsts: Array<TopInstitutionItem>;
}) => {
const uniqueInsts = new Map<string, string>();
uniqueInsts.set(primaryId, primaryName);
deInsts.forEach((inst: TopInstitutionItem) => {
if (inst.id)
@@ -1066,6 +1128,9 @@ export class UniTrendParentComponent implements OnInit {
setSearchType(
type: 'publications' | 'authors' | 'patents' | 'projects' | 'news' | 'all',
) {
if (type === 'news' && !this.isUde()) {
return;
}
this.selectedSearchType.set(type);
// Auto-initialize default lists if empty for the target type
@@ -1088,12 +1153,17 @@ export class UniTrendParentComponent implements OnInit {
// Add comparison institution
addInstitution(id: string, name: string) {
const cleanId = id.includes('/') ? id.split('/').pop() || id : id;
const current = this.comparisonInstitutions();
if (
!current.some((i: CompareItem) => i.id === id) &&
id !== this.primaryInstitution()
) {
this.comparisonInstitutions.set([...current, { id, name }]);
const exists = current.some((i: CompareItem) => {
const itemClean = i.id.includes('/')
? i.id.split('/').pop() || i.id
: i.id;
return itemClean.toLowerCase() === cleanId.toLowerCase();
});
if (!exists) {
this.comparisonInstitutions.set([...current, { id: cleanId, name }]);
this.updateUrlParams();
}
this.searchQuery.set('');
this.searchResults.set([]);
@@ -1104,6 +1174,7 @@ export class UniTrendParentComponent implements OnInit {
this.comparisonInstitutions.set(
current.filter((i: CompareItem) => i.id !== id),
);
this.updateUrlParams();
}
// Add country or region
@@ -1128,6 +1199,7 @@ export class UniTrendParentComponent implements OnInit {
this.locationQuery.set('');
this.locationSearchResults.set([]);
this.loadTrendSuggestions();
this.updateUrlParams();
}
removeLocation(id: string, type: 'country' | 'continent') {
@@ -1143,6 +1215,7 @@ export class UniTrendParentComponent implements OnInit {
);
}
this.loadTrendSuggestions();
this.updateUrlParams();
}
// Add Top 3 Authors for a selected institution from institutions autocomplete
@@ -1183,6 +1256,7 @@ export class UniTrendParentComponent implements OnInit {
});
this.comparisonAuthors.set(updated);
this.isSuggestionsLoading.set(false);
this.updateUrlParams();
},
error: (err) => {
console.error('Failed to load top authors for institution:', err);
@@ -1199,12 +1273,14 @@ export class UniTrendParentComponent implements OnInit {
const current = this.comparisonAuthors();
if (!current.some((a) => a.id === shortId)) {
this.comparisonAuthors.set([...current, { id: shortId, name }]);
this.updateUrlParams();
}
}
removeAuthor(id: string) {
const current = this.comparisonAuthors();
this.comparisonAuthors.set(current.filter((a: CompareItem) => a.id !== id));
this.updateUrlParams();
}
// Scaling mode toggle (data reuses instantly)
@@ -56,6 +56,15 @@
{{ auth.name }}
</span>
<div class="item-actions">
<a
[href]="getRedirectUrl(auth.id)"
target="_blank"
class="action-btn redirect-btn"
[style.color]="getEntityColor()(auth.id)"
(click)="$event.stopPropagation()"
title="Zur Detailansicht des Autors wechseln">
<mat-icon>open_in_new</mat-icon>
</a>
<button
type="button"
class="action-btn visibility-btn"
@@ -15,6 +15,7 @@ export interface CompareItem {
styleUrl: './author-selector.component.scss',
})
export class AuthorSelectorComponent {
readonly activeTab = input<string>('publications');
readonly comparisonAuthors = input<CompareItem[]>([]);
readonly topSuggestions = input<any[]>([]);
readonly isSuggestionsLoading = input<boolean>(false);
@@ -31,6 +32,18 @@ export class AuthorSelectorComponent {
readonly toggleVisibility = output<string>();
readonly selectPie = output<{ id: string; name: string; type: 'author' }>();
getRedirectUrl(id: string): string {
const cleanId = id.includes('/') ? id.split('/').pop() || id : id;
const tab = this.activeTab();
if (tab === 'projects') {
return `/inse-webapp/person/${cleanId}/projects?page=0&size=10&sort_by=title&sort_direction=asc&search=`;
}
if (tab === 'patents') {
return `/inse-webapp/person/${cleanId}/patents`;
}
return `/inse-webapp/person/${cleanId}/publications`;
}
onSelectPie(id: string, name: string): void {
this.selectPie.emit({ id, name, type: 'author' });
}
@@ -7,13 +7,8 @@
<div
class="primary-inst-badge clickable-pie-target"
[class.active-pie]="selectedPieEntityId() === primaryInstitution()"
(click)="
onSelectPie(
primaryInstitution() || '',
primaryInstitutionName() || ''
)
"
[title]="'Klicken, um die Themenverteilung im Kreisdiagramm anzuzeigen'">
(click)="onSelectPrimaryBadge()"
[title]="'Klicken, um die Einrichtung zur Vergleichsliste hinzuzufügen'">
<span class="label">Zugewiesen:</span>
<strong class="name">
<mat-icon class="pie-icon-indicator">{{
@@ -77,6 +72,15 @@
{{ inst.name }}
</span>
<div class="item-actions">
<a
[href]="getRedirectUrl(inst.id)"
target="_blank"
class="action-btn redirect-btn"
[style.color]="getEntityColor()(inst.id)"
(click)="$event.stopPropagation()"
title="Zur Detailansicht der Einrichtung wechseln">
<mat-icon>open_in_new</mat-icon>
</a>
<button
type="button"
class="action-btn visibility-btn"
@@ -15,6 +15,7 @@ export interface CompareItem {
styleUrl: './institution-selector.component.scss',
})
export class InstitutionSelectorComponent {
readonly activeTab = input<string>('publications');
readonly comparisonInstitutions = input<CompareItem[]>([]);
readonly primaryInstitution = input<string | null>(null);
readonly primaryInstitutionName = input<string | null>(null);
@@ -37,6 +38,27 @@ export class InstitutionSelectorComponent {
type: 'institution';
}>();
onSelectPrimaryBadge(): void {
const id = this.primaryInstitution();
const name = this.primaryInstitutionName();
if (id && name) {
this.addInstitution.emit({ id, name });
this.onSelectPie(id, name);
}
}
getRedirectUrl(id: string): string {
const cleanId = id.includes('/') ? id.split('/').pop() || id : id;
const tab = this.activeTab();
if (tab === 'projects') {
return `/inse-webapp/institution/${cleanId}/projects?project_tab=bund&page=0&size=10&search=&sort_by=title&sort_direction=asc`;
}
if (tab === 'patents') {
return `/inse-webapp/institution/${cleanId}/patents?filter=all&sortBy=date&matchType=all&page=1`;
}
return `/inse-webapp/institution/${cleanId}/publications`;
}
onSelectPie(id: string, name: string): void {
this.selectPie.emit({ id, name, type: 'institution' });
}
@@ -70,8 +92,20 @@ export class InstitutionSelectorComponent {
isAlreadyAdded(id: string | undefined): boolean {
if (!id) return false;
const isPrimary = this.primaryInstitution() === id;
const isComp = this.comparisonInstitutions().some((i) => i.id === id);
const cleanTarget = id.includes('/') ? id.split('/').pop() || id : id;
const primaryId = this.primaryInstitution();
const cleanPrimary = primaryId
? primaryId.includes('/')
? primaryId.split('/').pop() || primaryId
: primaryId
: null;
const isPrimary = cleanPrimary?.toLowerCase() === cleanTarget.toLowerCase();
const isComp = this.comparisonInstitutions().some((i) => {
const cleanItem = i.id.includes('/')
? i.id.split('/').pop() || i.id
: i.id;
return cleanItem.toLowerCase() === cleanTarget.toLowerCase();
});
return isPrimary || isComp;
}
}