From 67eee2913e9db667a6ac115ff86b951e8652a332 Mon Sep 17 00:00:00 2001 From: Kazgatari <56477241+Kazgatari@users.noreply.github.com> Date: Fri, 17 Jul 2026 13:41:07 +0200 Subject: [PATCH] adapted trend to get dfg and better search for Keywords --- .../university_ranking/trend_strategies.py | 517 +++++++++++++----- .../uni-trend-parent.component.ts | 2 +- 2 files changed, 376 insertions(+), 143 deletions(-) diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 5ecdd25d..1698df9f 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -717,6 +717,17 @@ class PatentsTrendStrategy(TrendStrategy): return TrendResponse(series=series_list, years=years_range, location_mappings={}) +DFG_INSTITUTION_FIELDS = [ + "Antragstellende Institution", + "Mitantragstellende Institution", + "Beteiligte Einrichtung", + "Beteiligte Hochschule", + "Beteiligte Institution", + "IGK-Partnerinstitution", + "Partnerorganisation", + "Unternehmen", +] + class ProjectsTrendStrategy(TrendStrategy): async def get_trend( self, @@ -748,20 +759,21 @@ class ProjectsTrendStrategy(TrendStrategy): clean_regions = [r.strip() for r in query_regions] ids_to_resolve = list(set(query_institutions)) - # 1. Resolve institution names & variants, country names, and regions + # 1. Resolve institution names & aliases, country names, and regions async def fetch_institutions(): names = {primary_inst_id: primary_inst_name} codes = {} - variants_map = {} + aliases_map = {} if not ids_to_resolve: - return names, codes, variants_map + return names, codes, aliases_map try: - from inse.patents.institutions.name_matching import institution_search_variants + from inse.institutions.institutions_search_client import InstitutionsSearchClient + client = InstitutionsSearchClient() res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_INSTITUTIONS), + index=ESIndex.OPENALEX_INSTITUTIONS.value, query={"terms": {"id": ids_to_resolve}}, size=len(ids_to_resolve), - source=["id", "display_name", "display_name_alternatives", "acronyms", "country_code"], + source=["id", "display_name", "country_code"], cluster="nes" ) for hit in res.get("hits", {}).get("hits", []): @@ -769,16 +781,20 @@ class ProjectsTrendStrategy(TrendStrategy): inst_id = source["id"] names[inst_id] = source.get("display_name", inst_id) codes[inst_id] = source.get("country_code", "") - - variants = set() - for name in [source.get("display_name")] + source.get("display_name_alternatives", []) + source.get("acronyms", []): - if name: - for var in institution_search_variants(name): - variants.add(var) - variants_map[inst_id] = list(variants) + + 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)] + + 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 except Exception as e: logger.warning("Failed to resolve institution details from ES: %s", e) - return names, codes, variants_map + return names, codes, aliases_map async def fetch_countries(): names = {} @@ -786,7 +802,7 @@ class ProjectsTrendStrategy(TrendStrategy): return names try: res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_COUNTRIES), + index=ESIndex.OPENALEX_COUNTRIES.value, query={"terms": {"country_code": clean_countries}}, size=len(clean_countries), source=["country_code", "display_name"], @@ -806,7 +822,7 @@ class ProjectsTrendStrategy(TrendStrategy): return names, ccodes try: res = await elasticsearch.search( - index=str(ESIndex.OPENALEX_CONTINENTS), + index=ESIndex.OPENALEX_CONTINENTS.value, query={ "bool": { "should": [ @@ -829,7 +845,7 @@ class ProjectsTrendStrategy(TrendStrategy): return names, ccodes ( - (resolved_names, resolved_country_codes, resolved_variants), + (resolved_names, resolved_country_codes, resolved_aliases), resolved_country_names, (resolved_continent_names, continent_country_codes) ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents()) @@ -852,33 +868,19 @@ class ProjectsTrendStrategy(TrendStrategy): from inse.patents.search_client import PatentSearchClient patent_client = PatentSearchClient() - # 2. Fetch matched project IDs for each topic + # 2. Fetch matched project IDs for each topic (if fuzzy is True) topic_project_ids = {} indices_mapping = { - "projects_cordiseu_heurope_openalex_topics": ("cordis_eu_horizon_europe_organizations", "cordis_eu_horizon_europe_projects"), - "projects_cordiseu_h2020_openalex_topics": ("cordis_eu_horizon_2020_organizations", "cordis_eu_horizon_2020_projects"), - "projects_cordiseu_fp7_openalex_topics": ("cordis_eu_fp7_organizations", "cordis_eu_fp7_projects"), - "projects_bund_openalex_topics": ("projects_bund_v1", None) + "projects_cordiseu_heurope_openalex_topics": (ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS), + "projects_cordiseu_h2020_openalex_topics": (ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS), + "projects_cordiseu_fp7_openalex_topics": (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS), + "projects_bund_openalex_topics": (ESIndex.PROJECTS_BUND_V1, None), + "projects_dfg_openalex_topics": (ESIndex.PROJECTS_DFG_ALL, None) } - for idx, t in enumerate(topics): - topic_project_ids[t] = {ind: [] for ind in indices_mapping} - - if not fuzzy and keywords and idx < len(keywords): - kw_val = keywords[idx] - map_query = { - "query": { - "bool": { - "should": [ - {"match": {"keyword": kw_val}}, - {"term": {"topic_matches.topic_display_name.keyword": kw_val}} - ], - "minimum_should_match": 1 - } - }, - "size": 10000 - } - else: + if fuzzy: + for idx, t in enumerate(topics): + topic_project_ids[t] = {ind: [] for ind in indices_mapping} map_query = { "query": { "term": { @@ -888,19 +890,19 @@ class ProjectsTrendStrategy(TrendStrategy): "size": 10000 } - map_tasks = [] - ind_list = list(indices_mapping.keys()) - for ind in ind_list: - map_tasks.append(patent_client._search(index=ind, payload=map_query)) + map_tasks = [] + ind_list = list(indices_mapping.keys()) + for ind in ind_list: + map_tasks.append(patent_client._search(index=ind, payload=map_query)) - map_responses = await asyncio.gather(*map_tasks, return_exceptions=True) - for m_idx, res_map in enumerate(map_responses): - if isinstance(res_map, Exception): - logger.warning("Failed to query mapping index %s: %s", ind_list[m_idx], res_map) - continue - hits = res_map.get("hits", {}).get("hits", []) - p_ids = [h["_source"]["project_id"] for h in hits if h.get("_source", {}).get("project_id")] - topic_project_ids[t][ind_list[m_idx]] = p_ids + map_responses = await asyncio.gather(*map_tasks, return_exceptions=True) + for m_idx, res_map in enumerate(map_responses): + if isinstance(res_map, Exception): + logger.warning("Failed to query mapping index %s: %s", ind_list[m_idx], res_map) + continue + hits = res_map.get("hits", {}).get("hits", []) + p_ids = [h["_source"]["project_id"] for h in hits if h.get("_source", {}).get("project_id")] + topic_project_ids[t][ind_list[m_idx]] = p_ids # 3. For each entity & topic, filter actual indices and aggregate accumulated_data = { @@ -908,119 +910,350 @@ class ProjectsTrendStrategy(TrendStrategy): for key in filters_map } - async def query_project_trends(entity_key, entity_type, entity_val, topic): + async def query_project_trends(entity_key, entity_type, entity_val, topic, keyword): + # Fetch entity_project_ids for EU cordis indices (HEU, H2020, FP7) + async def get_eu_entity_project_ids(org_index): + filter_clauses = [] + if entity_type == "institution": + aliases = resolved_aliases.get(entity_val, []) + filter_clauses.append({ + "terms": { + "name.keyword": [alias.upper() for alias in aliases] + } + }) + elif entity_type == "country": + filter_clauses.append({"term": {"country": entity_val}}) + elif entity_type == "region": + filter_clauses.append({"terms": {"country": entity_val}}) + + try: + res = await patent_client._search( + index=org_index.value, + payload={ + "query": { + "bool": { + "filter": filter_clauses + } + }, + "size": 0, + "aggs": { + "project_ids": { + "terms": { + "field": "projectID", + "size": 65536 + } + } + } + } + ) + buckets = res.get("aggregations", {}).get("project_ids", {}).get("buckets", []) + return [b["key"] for b in buckets] + except Exception as e: + logger.warning("Failed to query CORDIS orgs index %s: %s", org_index.value, e) + return [] + + eu_indices = [ + (ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, "projects_cordiseu_heurope_openalex_topics"), + (ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, "projects_cordiseu_h2020_openalex_topics"), + (ESIndex.CORDIS_EU_FP7_ORGANIZATIONS, ESIndex.CORDIS_EU_FP7_PROJECTS, "projects_cordiseu_fp7_openalex_topics") + ] + + eu_org_tasks = [get_eu_entity_project_ids(org_idx) for org_idx, _, _ in eu_indices] + eu_org_ids_list = await asyncio.gather(*eu_org_tasks) + actual_tasks = [] - for index, (org_index, proj_index) in indices_mapping.items(): - p_ids = topic_project_ids[topic].get(index, []) - if not p_ids: - continue + # 1. BUND + include_bund = True + if entity_type == "country" and entity_val != "DE": + include_bund = False + elif entity_type == "region" and "DE" not in entity_val: + include_bund = False - if proj_index: # Cordis EU - must_clauses = [{"terms": {"projectID": p_ids}}] - if entity_type == "institution": - vars = resolved_variants.get(entity_val, [entity_val]) - must_clauses.append({"terms": {"name.keyword": [n.upper() for n in vars]}}) - elif entity_type == "country": - must_clauses.append({"term": {"country": entity_val}}) - elif entity_type == "region": - must_clauses.append({"terms": {"country": entity_val}}) - - org_payload = { - "query": {"bool": {"must": must_clauses}}, - "size": 10000, - "_source": ["projectID"] + if include_bund: + bund_filters = [] + if entity_type == "institution": + aliases = resolved_aliases.get(entity_val, []) + bund_filters.append({ + "bool": { + "should": [ + { + "match": { + "Zuwendungsempfänger": { + "query": alias, + "operator": "and" + } + } + } + for alias in aliases + ], + "minimum_should_match": 1 + } + }) + + if fuzzy: + p_ids = topic_project_ids[topic].get("projects_bund_openalex_topics", []) + if p_ids: + bund_filters.append({"ids": {"values": p_ids}}) + bund_query = {"query": {"bool": {"filter": bund_filters}}} + else: + bund_query = None + else: + bund_query = { + "query": { + "bool": { + "filter": [ + { + "bool": { + "should": [ + {"match": {"Thema": keyword}}, + {"match": {"Klartext Leistungsplansystematik": keyword}}, + {"match": {"Förderprofil": keyword}}, + {"match": {"Leistungsplansystematik_fullname": keyword}} + ], + "minimum_should_match": 1 + } + } + ] + bund_filters + } + } } - async def process_cordis(oi=org_index, pi=proj_index, payload=org_payload): - try: - res_org = await patent_client._search(index=oi, payload=payload) - matching_ids = list(set(h["_source"]["projectID"] for h in res_org.get("hits", {}).get("hits", []) if h.get("_source", {}).get("projectID"))) - if not matching_ids: - return [] - - proj_payload = { - "query": {"terms": {"id": matching_ids}}, - "size": 10000, - "_source": ["id", "startDate"] + if bund_query: + bund_payload = { + **bund_query, + "size": 0, + "aggs": { + "projects_by_year": { + "date_histogram": { + "field": "funding_start", + "calendar_interval": "year", + "format": "yyyy" + } } - res_proj = await patent_client._search(index=pi, payload=proj_payload) - dates = [] - for h in res_proj.get("hits", {}).get("hits", []): - start_date = h["_source"].get("startDate") - if start_date: - dates.append(start_date) - return dates + } + } + async def process_bund(): + try: + res = await patent_client._search(index=ESIndex.PROJECTS_BUND_V1.value, payload=bund_payload) + return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", []) except Exception as e: - logger.warning("Failed in process_cordis for %s/%s: %s", oi, pi, e) - return [] - - actual_tasks.append(process_cordis()) - - else: # Bund - must_clauses = [{"ids": {"values": p_ids}}] - include_bund = True - if entity_type == "institution": - vars = resolved_variants.get(entity_val, [entity_val]) - must_clauses.append({ + logger.warning("Failed to query BUND projects: %s", e) + return "date", [] + actual_tasks.append(process_bund()) + + # 2. DFG + include_dfg = True + if entity_type == "country" and entity_val != "DE": + include_dfg = False + elif entity_type == "region" and "DE" not in entity_val: + include_dfg = False + + if include_dfg: + dfg_filters = [] + if entity_type == "institution": + aliases = resolved_aliases.get(entity_val, []) + dfg_entity_shoulds = [] + for field in DFG_INSTITUTION_FIELDS: + dfg_entity_shoulds.append({ "bool": { - "should": [{"match_phrase": {"Zuwendungsempfänger": name}} for name in vars], + "should": [ + { + "match": { + field: { + "query": alias, + "operator": "and" + } + } + } + for alias in aliases + ], "minimum_should_match": 1 } }) - elif entity_type == "country": - if entity_val != "DE": - include_bund = False - elif entity_type == "region": - if "DE" not in entity_val: - include_bund = False - - if include_bund: - bund_payload = { - "query": {"bool": {"must": must_clauses}}, - "size": 10000, - "_source": ["Förderbeginn"] + dfg_entity_shoulds.append({ + "nested": { + "path": "persons", + "query": { + "bool": { + "should": [ + { + "match": { + "persons.affiliation_de": { + "query": alias, + "operator": "and" + } + } + } + for alias in aliases + ] + [ + { + "match": { + "persons.affiliation_en": { + "query": alias, + "operator": "and" + } + } + } + for alias in aliases + ], + "minimum_should_match": 1 + } + } } - async def process_bund(oi=org_index, payload=bund_payload): - try: - res_bund = await patent_client._search(index=oi, payload=payload) - dates = [] - for h in res_bund.get("hits", {}).get("hits", []): - start_date = h["_source"].get("Förderbeginn") - if start_date: - dates.append(start_date) - return dates - except Exception as e: - logger.warning("Failed to query BUND projects: %s", e) - return [] - actual_tasks.append(process_bund()) + }) + dfg_filters.append({ + "bool": { + "should": dfg_entity_shoulds, + "minimum_should_match": 1 + } + }) + + if fuzzy: + p_ids = topic_project_ids[topic].get("projects_dfg_openalex_topics", []) + if p_ids: + dfg_filters.append({"ids": {"values": p_ids}}) + dfg_query = {"query": {"bool": {"filter": dfg_filters}}} + else: + dfg_query = None + else: + dfg_query = { + "query": { + "bool": { + "filter": [ + { + "bool": { + "should": [ + {"match": {"title_de": keyword}}, + {"match": {"title_en": keyword}}, + {"match": {"description": keyword}}, + {"match": {"subject_area_de": keyword}}, + {"match": {"subject_area_en": keyword}}, + {"match": {"abstract_de": keyword}}, + {"match": {"abstract_en": keyword}}, + {"match": {"final_report_abstract_de": keyword}}, + {"match": {"final_report_abstract_en": keyword}} + ], + "minimum_should_match": 1 + } + } + ] + dfg_filters + } + } + } + + if dfg_query: + dfg_payload = { + **dfg_query, + "size": 0, + "aggs": { + "projects_by_year": { + "terms": { + "field": "funding_start", + "size": 100 + } + } + } + } + async def process_dfg(): + try: + res = await patent_client._search(index=ESIndex.PROJECTS_DFG_ALL.value, payload=dfg_payload) + return "terms", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", []) + except Exception as e: + logger.warning("Failed to query DFG projects: %s", e) + return "terms", [] + actual_tasks.append(process_dfg()) + + # 3. EU Cordis + for eu_idx, (org_index, proj_index, mapping_key) in enumerate(eu_indices): + entity_project_ids = eu_org_ids_list[eu_idx] + if not entity_project_ids: + continue + + if fuzzy: + p_ids = topic_project_ids[topic].get(mapping_key, []) + common_ids = list(set(p_ids) & set(entity_project_ids)) + if common_ids: + proj_query = {"query": {"bool": {"filter": [{"terms": {"id": common_ids}}]}}} + else: + proj_query = None + else: + proj_query = { + "query": { + "bool": { + "filter": [ + {"terms": {"id": entity_project_ids}}, + { + "bool": { + "should": [ + {"match": {"title": keyword}}, + {"match": {"objective": keyword}} + ], + "minimum_should_match": 1 + } + } + ] + } + } + } + + if proj_query: + proj_payload = { + **proj_query, + "size": 0, + "aggs": { + "projects_by_year": { + "date_histogram": { + "field": "startDate", + "calendar_interval": "year", + "format": "yyyy" + } + } + } + } + async def process_cordis(p_idx=proj_index, payload=proj_payload): + try: + res = await patent_client._search(index=p_idx.value, payload=payload) + return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", []) + except Exception as e: + logger.warning("Failed to query CORDIS projects index %s: %s", p_idx.value, e) + return "date", [] + actual_tasks.append(process_cordis()) if not actual_tasks: return - all_dates_lists = await asyncio.gather(*actual_tasks) + results = await asyncio.gather(*actual_tasks) year_counts = {} - for dates in all_dates_lists: - for d in dates: - try: - if "-" in str(d): - yr = int(str(d).split("-")[0]) - elif "." in str(d): - yr = int(str(d).split(".")[-1]) - else: - yr = int(str(d)[:4]) - if start_year <= yr <= end_year: - year_counts[yr] = year_counts.get(yr, 0) + 1 - except Exception: - continue + for agg_type, buckets in results: + for b in buckets: + if agg_type == "date": + yr_str = b.get("key_as_string") + if yr_str: + try: + yr = int(yr_str) + 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: + try: + yr = int(yr) + if start_year <= yr <= end_year: + year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0) + except ValueError: + pass for yr, count in year_counts.items(): accumulated_data[entity_key][topic][yr] = (count, 1) tasks = [] for entity_key, (entity_type, entity_val) in filters_map.items(): - for topic in topics: - tasks.append(query_project_trends(entity_key, entity_type, entity_val, topic)) + for idx, topic in enumerate(topics): + keyword = keywords[idx] if (keywords and idx < len(keywords)) else topic + tasks.append(query_project_trends(entity_key, entity_type, entity_val, topic, keyword)) await asyncio.gather(*tasks) diff --git a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts index fd983643..cccc4a72 100644 --- a/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts +++ b/webapp/src/app/modules/university-ranking/uni-trend-parent/uni-trend-parent.component.ts @@ -82,7 +82,7 @@ export const TREND_CONFIGS: Record = { }, projects: { showInstitutionSelector: true, - showLocationSelector: false, + showLocationSelector: true, showAuthorSelector: false, yAxisLabel: 'Projektförderung (Anz)', chartTitle: 'Drittmittelförderung-Trends',