diff --git a/service/src/main/inse/university_ranking/trend_strategies.py b/service/src/main/inse/university_ranking/trend_strategies.py index 904f76d8..205879bb 100644 --- a/service/src/main/inse/university_ranking/trend_strategies.py +++ b/service/src/main/inse/university_ranking/trend_strategies.py @@ -583,48 +583,307 @@ class PatentsTrendStrategy(TrendStrategy): 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_id = DEFAULT_INSTITUTION_ID primary_inst_name = DEFAULT_INSTITUTION_NAME - entities = [primary_inst_name] + + query_institutions = [] if institutions: - entities.extend(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)) + + # 1. Resolve institution names & variants, country names, and regions + async def fetch_institutions(): + names = {primary_inst_id: primary_inst_name} + codes = {} + variants_map = {} + if not ids_to_resolve: + return names, codes, variants_map + try: + from inse.patents.institutions.name_matching import institution_search_variants + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query={"terms": {"id": ids_to_resolve}}, + size=len(ids_to_resolve), + source=["id", "display_name", "display_name_alternatives", "acronyms", "country_code"], + cluster="nes" + ) + 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", "") + + 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) + except Exception as e: + logger.warning("Failed to resolve institution details from ES: %s", e) + return names, codes, variants_map + + 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 + + ( + (resolved_names, resolved_country_codes, resolved_variants), + resolved_country_names, + (resolved_continent_names, continent_country_codes) + ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents()) + + location_mappings = continent_country_codes.copy() + + # Build list of entities + filters_map = {} + for inst_id in query_institutions: + filters_map[f"inst_{inst_id}"] = ("institution", inst_id) + for cc in clean_countries: + filters_map[f"country_{cc}"] = ("country", cc) + for r_code, member_ccs in continent_country_codes.items(): + if member_ccs: + filters_map[f"region_{r_code}"] = ("region", member_ccs) + + if not filters_map: + return TrendResponse(series=[], years=years_range, location_mappings=location_mappings) + + # 2. Query IPC symbols for each topic + from inse.patents.search_client import PatentSearchClient + patent_client = PatentSearchClient() + + topic_symbols = {} + for idx, t in enumerate(topics): + if not fuzzy and keywords and idx < len(keywords): + kw_val = keywords[idx] + query = { + "query": { + "bool": { + "should": [ + {"match": {"ipc_label": kw_val}}, + {"nested": {"path": "topic_matches", "query": {"match": {"topic_matches.topic_display_name": kw_val}}}}, + {"nested": {"path": "topic_matches", "query": {"match": {"topic_matches.subfield": kw_val}}}}, + {"nested": {"path": "keyword_matches", "query": {"match": {"keyword_matches.keyword": kw_val}}}}, + {"nested": {"path": "keyword_matches", "query": {"match": {"keyword_matches.topic_display_name": kw_val}}}} + ], + "minimum_should_match": 1 + } + }, + "size": 10000 + } + else: + query = { + "query": { + "nested": { + "path": "topic_matches", + "query": { + "term": { + "topic_matches.topic_display_name": t + } + } + } + }, + "size": 10000 + } + try: + res = await patent_client._search(index="patents_openalex_keywords", payload=query) + hits = res.get("hits", {}).get("hits", []) + symbols = [hit["_source"]["ipc_symbol"] for hit in hits if hit.get("_source", {}).get("ipc_symbol")] + topic_symbols[t] = list(set(symbols)) + except Exception as e: + logger.error("Failed to query patents_openalex_keywords for topic %s: %s", t, e) + topic_symbols[t] = [] + + # 3. For each entity & topic, build queries and fetch timeseries data + accumulated_data = { + key: {t: {yr: (0, 1) for yr in years_range} for t in topics} + for key in filters_map + } + + async def query_patents_trends(entity_key, entity_type, entity_val, topic, symbols): + if not symbols: + return + + epo_ipc_filter = {"bool": {"should": [{"match_phrase_prefix": {"ipc": sym}} for sym in symbols], "minimum_should_match": 1}} + uspto_ipcr_filter = {"bool": {"should": [{"match_phrase_prefix": {"ipcr": sym}} for sym in symbols], "minimum_should_match": 1}} + + epo_must = [epo_ipc_filter] + uspto_must = [uspto_ipcr_filter] + + if entity_type == "institution": + vars = resolved_variants.get(entity_val, [entity_val]) + epo_must.append(patent_client._match_organization_names("applicants_name", vars)) + uspto_must.append(patent_client._match_organization_names("assignees_orgs", vars)) + elif entity_type == "country": + epo_must.append({"match": {"applicants_adr": entity_val}}) + uspto_must.append({"match": {"assignees_addresses": entity_val}}) + elif entity_type == "region": + epo_must.append({"bool": {"should": [{"match": {"applicants_adr": cc}} for cc in entity_val], "minimum_should_match": 1}}) + uspto_must.append({"bool": {"should": [{"match": {"assignees_addresses": cc}} for cc in entity_val], "minimum_should_match": 1}}) + + epo_query = { + "query": {"bool": {"must": epo_must}}, + "size": 0, + "aggs": { + "by_year": { + "terms": { + "field": "date_publication_year", + "size": 100 + } + } + } + } + uspto_query = { + "query": {"bool": {"must": uspto_must}}, + "size": 0, + "aggs": { + "by_year": { + "terms": { + "field": "publication_year", + "size": 100 + } + } + } + } + + try: + res_epo, res_us = await asyncio.gather( + patent_client.search_epo(epo_query), + patent_client.search_uspto(uspto_query) + ) + + buckets_epo = res_epo.get("aggregations", {}).get("by_year", {}).get("buckets", []) + buckets_us = res_us.get("aggregations", {}).get("by_year", {}).get("buckets", []) + + year_counts = {} + for b in buckets_epo: + try: + yr = int(b["key"]) + year_counts[yr] = year_counts.get(yr, 0) + int(b["doc_count"]) + except Exception: + pass + for b in buckets_us: + try: + yr = int(b["key"]) + year_counts[yr] = year_counts.get(yr, 0) + int(b["doc_count"]) + except Exception: + pass + + for yr, count in year_counts.items(): + if yr in years_range: + accumulated_data[entity_key][topic][yr] = (count, 1) + + except Exception as e: + logger.error("Failed to query patent trends for %s / %s: %s", entity_key, topic, e) + + tasks = [] + for entity_key, (entity_type, entity_val) in filters_map.items(): + for topic in topics: + symbols = topic_symbols.get(topic, []) + tasks.append(query_patents_trends(entity_key, entity_type, entity_val, topic, symbols)) + + await asyncio.gather(*tasks) + + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) series_list = [] - for entity in entities: + 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] + elif entity_type == "country": + entity_id = entity_val + entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") + elif entity_type == "region": + entity_id = entity_key[len("region_"):] + entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") + topic_data_map = {} - for topic in topics: + for topic, year_dict in topic_dict.items(): 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 + 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=int(counts[idx]), - normalized=float(counts[idx] / 15.0), - cumulative=float(cum_counts[idx] / max_cum), + 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, - entity_name=entity.split("/")[-1], - entity_type="institution", + 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) + return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) + -### index? Or query against existing scattered indicies? class ProjectsTrendStrategy(TrendStrategy): async def get_trend( self, @@ -636,45 +895,344 @@ class ProjectsTrendStrategy(TrendStrategy): 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_id = DEFAULT_INSTITUTION_ID primary_inst_name = DEFAULT_INSTITUTION_NAME - entities = [primary_inst_name] + + query_institutions = [] if institutions: - entities.extend(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)) + + # 1. Resolve institution names & variants, country names, and regions + async def fetch_institutions(): + names = {primary_inst_id: primary_inst_name} + codes = {} + variants_map = {} + if not ids_to_resolve: + return names, codes, variants_map + try: + from inse.patents.institutions.name_matching import institution_search_variants + res = await elasticsearch.search( + index=str(ESIndex.OPENALEX_INSTITUTIONS), + query={"terms": {"id": ids_to_resolve}}, + size=len(ids_to_resolve), + source=["id", "display_name", "display_name_alternatives", "acronyms", "country_code"], + cluster="nes" + ) + 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", "") + + 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) + except Exception as e: + logger.warning("Failed to resolve institution details from ES: %s", e) + return names, codes, variants_map + + 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 + + ( + (resolved_names, resolved_country_codes, resolved_variants), + resolved_country_names, + (resolved_continent_names, continent_country_codes) + ) = await asyncio.gather(fetch_institutions(), fetch_countries(), fetch_continents()) + + location_mappings = continent_country_codes.copy() + + # Build list of entities + filters_map = {} + for inst_id in query_institutions: + filters_map[f"inst_{inst_id}"] = ("institution", inst_id) + for cc in clean_countries: + filters_map[f"country_{cc}"] = ("country", cc) + for r_code, member_ccs in continent_country_codes.items(): + if member_ccs: + filters_map[f"region_{r_code}"] = ("region", member_ccs) + + if not filters_map: + return TrendResponse(series=[], years=years_range, location_mappings=location_mappings) + + from inse.patents.search_client import PatentSearchClient + patent_client = PatentSearchClient() + + # 2. Fetch matched project IDs for each topic + 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) + } + + 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: + map_query = { + "query": { + "term": { + "topic_matches.topic_display_name.keyword": t + } + }, + "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_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 = { + key: {t: {yr: (0, 1) for yr in years_range} for t in topics} + for key in filters_map + } + + async def query_project_trends(entity_key, entity_type, entity_val, topic): + 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 + + 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"] + } + + 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"] + } + 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 + 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({ + "bool": { + "should": [{"match_phrase": {"Zuwendungsempfänger": name}} for name in vars], + "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"] + } + 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()) + + if not actual_tasks: + return + + all_dates_lists = 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 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)) + + await asyncio.gather(*tasks) + + normalized_lookup = self._normalize_series(years_range, accumulated_data, topics) series_list = [] - for entity in entities: + 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] + elif entity_type == "country": + entity_id = entity_val + entity_name = resolved_country_names.get(entity_id, f"Country {entity_id}") + elif entity_type == "region": + entity_id = entity_key[len("region_"):] + entity_name = resolved_continent_names.get(entity_id, f"Continent {entity_id}") + topic_data_map = {} - for topic in topics: + for topic, year_dict in topic_dict.items(): 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 + 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=int(counts[idx]), - normalized=float(counts[idx] / 10.0), - cumulative=float(cum_counts[idx] / max_cum), + 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, - entity_name=entity.split("/")[-1], - entity_type="institution", + 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) + return TrendResponse(series=series_list, years=years_range, location_mappings=location_mappings) ### requires proper index (currently only workaround) class NewsTrendStrategy(TrendStrategy):