added cosmetic disable for topic chips and disabled in trend, when no information available. Changed Patent logic to UDE vs World

This commit is contained in:
Kazgatari
2026-07-21 00:25:48 +02:00
parent a5664e01fe
commit b9d0d4cbf3
4 changed files with 233 additions and 89 deletions
@@ -571,6 +571,27 @@ class AuthorsTrendStrategy(TrendStrategy):
return TrendResponse(series=series_list, years=years_range)
USPTO_PATENT_FIELDS = [
"title",
"abstract",
"description_paragraph",
"claims",
"claims_text",
"openalex_topics.topic_display_name",
"openalex_topics.topic_id",
]
EPO_PATENT_FIELDS = [
"title_de",
"title_en",
"abstract",
"description_paragraph",
"claims_en",
"claims_de",
"openalex_topics.topic_display_name",
"openalex_topics.topic_id",
]
class PatentsTrendStrategy(TrendStrategy):
async def get_trend(
self,
@@ -588,48 +609,29 @@ class PatentsTrendStrategy(TrendStrategy):
primary_inst_id = DEFAULT_INSTITUTION_ID
primary_inst_name = DEFAULT_INSTITUTION_NAME
world_inst_id = "WORLD"
world_inst_name = "Rest der Welt"
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)
series_entities = [
(primary_inst_id, primary_inst_name),
(world_inst_id, world_inst_name),
]
# 1. Resolve institution names from openalex-institutions index
resolved_names = {primary_inst_id: primary_inst_name}
try:
res = await elasticsearch.search(
index=str(ESIndex.OPENALEX_INSTITUTIONS),
query={"terms": {"id": query_institutions}},
size=len(query_institutions),
source=["id", "display_name"],
cluster="nes"
)
for hit in res.get("hits", {}).get("hits", []):
source = hit["_source"]
resolved_names[source["id"]] = source.get("display_name", source["id"])
except Exception as e:
logger.warning("Failed to resolve institution details from ES: %s", e)
# 2. Fetch patents using the existing API endpoint / logic
# 1. Fetch UDE patents using get_org_patents_by_institution_id
from inse.patents.org.logic import get_org_patents_by_institution_id
async def fetch_patents(inst_id: str):
try:
res = await get_org_patents_by_institution_id(
institution_id=inst_id,
match_type="all",
page=0,
size=10000
)
return inst_id, res.patents, res.institution_name
except Exception as e:
logger.error("Failed to fetch org-patents for institution %s: %s", inst_id, e)
return inst_id, [], None
ude_patents = []
try:
res = await get_org_patents_by_institution_id(
institution_id=primary_inst_id,
match_type="all",
page=0,
size=10000,
)
ude_patents = res.patents
except Exception as e:
logger.error("Failed to fetch org-patents for UDE: %s", e)
fetched = await asyncio.gather(*(fetch_patents(inst_id) for inst_id in query_institutions))
# Helper matching functions (case-insensitive substring topic and keyword matching)
def matches_topic(patent, topic: str) -> bool:
if not patent.openalex_topics:
return False
@@ -643,10 +645,10 @@ class PatentsTrendStrategy(TrendStrategy):
return True
return False
def matches_patent(patent, topic: str, keyword: Optional[str], fuzzy: bool) -> bool:
def matches_patent(patent, topic: str, keyword: Optional[str], is_fuzzy: bool) -> bool:
if matches_topic(patent, topic):
return True
if not fuzzy and keyword:
if not is_fuzzy and keyword:
kw_lower = keyword.lower()
if patent.title and kw_lower in patent.title.lower():
return True
@@ -658,35 +660,116 @@ class PatentsTrendStrategy(TrendStrategy):
return True
return False
# 3. For each institution & topic, filter patents and group by year
accumulated_data = {
f"inst_{inst_id}": {t: {yr: (0, 1) for yr in years_range} for t in topics}
for inst_id in query_institutions
f"inst_{primary_inst_id}": {
t: {yr: (0, 1) for yr in years_range} for t in topics
},
f"inst_{world_inst_id}": {
t: {yr: (0, 1) for yr in years_range} for t in topics
},
}
for inst_id, patents, name in fetched:
if name:
resolved_names[inst_id] = name
for idx, t in enumerate(topics):
keyword = keywords[idx] if keywords and idx < len(keywords) else None
for p in patents:
if matches_patent(p, t, keyword, fuzzy):
# Filter UDE patents per topic
for idx, t in enumerate(topics):
kw = keywords[idx] if keywords and idx < len(keywords) else None
for p in ude_patents:
if matches_patent(p, t, kw, fuzzy):
try:
yr_val = int(p.publication_year) if p.publication_year else None
if yr_val in years_range:
c_count, _ = accumulated_data[f"inst_{primary_inst_id}"][t][yr_val]
accumulated_data[f"inst_{primary_inst_id}"][t][yr_val] = (c_count + 1, 1)
except Exception:
pass
# 2. Fetch Global / Rest der Welt patent counts via ES aggregations across EPO and USPTO
for idx, t in enumerate(topics):
search_term = (
t if fuzzy else (keywords[idx] if keywords and idx < len(keywords) else t)
)
if not search_term:
continue
uspto_query = {
"size": 0,
"query": {
"multi_match": {
"query": search_term,
"fields": USPTO_PATENT_FIELDS,
"type": "best_fields",
"operator": "or",
}
},
"aggs": {
"by_year": {
"terms": {"field": "publication_year", "size": 50}
}
},
}
epo_query = {
"size": 0,
"query": {
"multi_match": {
"query": search_term,
"fields": EPO_PATENT_FIELDS,
"type": "best_fields",
"operator": "or",
}
},
"aggs": {
"by_year": {
"terms": {"field": "date_publication_year", "size": 50}
}
},
}
try:
uspto_res, epo_res = await asyncio.gather(
elasticsearch.search(
index="uspto_patents_3.0",
body=uspto_query,
cluster=ESCluster.INSE,
),
elasticsearch.search(
index="epo_index_1.0",
body=epo_query,
cluster=ESCluster.INSE,
),
return_exceptions=True,
)
if not isinstance(uspto_res, Exception):
buckets = uspto_res.get("aggregations", {}).get("by_year", {}).get("buckets", [])
for b in buckets:
try:
yr_val = int(p.publication_year) if p.publication_year else None
yr_val = int(b.get("key"))
if yr_val in years_range:
count, _ = accumulated_data[f"inst_{inst_id}"][t][yr_val]
accumulated_data[f"inst_{inst_id}"][t][yr_val] = (count + 1, 1)
cnt, _ = accumulated_data[f"inst_{world_inst_id}"][t][yr_val]
accumulated_data[f"inst_{world_inst_id}"][t][yr_val] = (cnt + int(b.get("doc_count", 0)), 1)
except Exception:
pass
if not isinstance(epo_res, Exception):
buckets = epo_res.get("aggregations", {}).get("by_year", {}).get("buckets", [])
for b in buckets:
try:
yr_val = int(b.get("key"))
if yr_val in years_range:
cnt, _ = accumulated_data[f"inst_{world_inst_id}"][t][yr_val]
accumulated_data[f"inst_{world_inst_id}"][t][yr_val] = (cnt + int(b.get("doc_count", 0)), 1)
except Exception:
pass
except Exception as exc:
logger.error("Failed to query global patent trends: %s", exc)
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
series_list = []
for inst_id in query_institutions:
for inst_id, entity_name in series_entities:
entity_key = f"inst_{inst_id}"
topic_dict = accumulated_data[entity_key]
entity_name = resolved_names.get(inst_id, inst_id).split("/")[-1]
topic_data_map = {}
for topic, year_dict in topic_dict.items():
@@ -697,24 +780,30 @@ class PatentsTrendStrategy(TrendStrategy):
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
))
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=inst_id,
entity_name=entity_name,
entity_type="institution",
country_code=None,
topic_data=topic_data_map
))
series_list.append(
TrendSeries(
entity_id=inst_id,
entity_name=entity_name,
entity_type="institution",
country_code=None,
topic_data=topic_data_map,
)
)
return TrendResponse(series=series_list, years=years_range, location_mappings={})
return TrendResponse(
series=series_list, years=years_range, location_mappings={}
)
DFG_INSTITUTION_FIELDS = [
@@ -132,6 +132,7 @@
[label]="topic"
[active]="activeChartTopic() === topic"
[color]="getTopicColor(topic)"
[disabled]="isTopicEmpty(topic)"
(chipClick)="updateActiveChartTopic(topic)">
</app-topic-chip>
}
@@ -76,7 +76,7 @@ export const TREND_CONFIGS: Record<string, TrendStrategyConfig> = {
chartTitle: 'Autorentrends',
},
patents: {
showInstitutionSelector: true,
showInstitutionSelector: false,
showLocationSelector: false,
showAuthorSelector: false,
yAxisLabel: 'Patentanmeldungen',
@@ -231,12 +231,23 @@ export class UniTrendParentComponent implements OnInit {
getTopicColor(topic: string): string {
const mapped = this.getMappedTopic(topic);
const entries = this.state?.selectedKeywordEntries() ?? [];
const ext = this.state?.extractedKeywords() ?? [];
const man = this.state?.manualKeywords() ?? [];
const all = [...ext, ...man];
const all = [...entries, ...ext, ...man];
const targetLower = topic.toLowerCase().trim();
const mappedLower = mapped.toLowerCase().trim();
const match = all.find(
(e) => e.topic_mapping?.topic?.display_name === mapped,
(e) =>
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
mappedLower ||
e.topic_mapping?.topic?.display_name?.toLowerCase().trim() ===
targetLower ||
e.llm_keyword?.keyword?.toLowerCase().trim() === targetLower,
);
if (match && match.topic_mapping?.topic) {
return topicHierarchyColor({
name: match.topic_mapping.topic.display_name,
@@ -340,7 +351,7 @@ export class UniTrendParentComponent implements OnInit {
if (!raw) return null;
const type = this.selectedSearchType();
if (type === 'news' || type === 'all') {
if (type === 'news' || type === 'all' || type === 'patents') {
return {
...raw,
series: raw.series.map((s) => ({
@@ -444,12 +455,23 @@ export class UniTrendParentComponent implements OnInit {
const searchType = this.selectedSearchType();
if (topics.length > 0) {
// Find existing selections that are still in topics, or default to all
const validSelections = currentSelections.filter((t: string) =>
topics.includes(t),
);
if (validSelections.length > 0) {
this.selectedTrendTopics.set(validSelections);
const altTopics = fuzzy ? kws : (this.state?.topicsList() ?? kws);
const mappedSelections: string[] = [];
currentSelections.forEach((item) => {
if (topics.includes(item)) {
mappedSelections.push(item);
} else {
const idx = altTopics.indexOf(item);
if (idx !== -1 && idx < topics.length && topics[idx]) {
mappedSelections.push(topics[idx]);
}
}
});
const finalSelections = Array.from(new Set(mappedSelections));
if (finalSelections.length > 0) {
this.selectedTrendTopics.set(finalSelections);
} else {
this.selectedTrendTopics.set(topics);
}
@@ -883,8 +905,8 @@ export class UniTrendParentComponent implements OnInit {
.searchPersonsList(
undefined, // query
'University of Duisburg-Essen', // primary institution
undefined, // sortBy
undefined, // sortOrder
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
1, // page
3, // pageSize
@@ -972,8 +994,8 @@ export class UniTrendParentComponent implements OnInit {
.searchPersonsList(
undefined, // query
'University of Duisburg-Essen', // UDE
undefined, // sortBy
undefined, // sortOrder
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
1, // page
6, // pageSize
@@ -990,8 +1012,8 @@ export class UniTrendParentComponent implements OnInit {
.searchPersonsList(
undefined,
undefined, // global!
undefined,
undefined,
'cited_by_count',
'desc',
[topic],
1,
6,
@@ -1231,8 +1253,8 @@ export class UniTrendParentComponent implements OnInit {
.searchPersonsList(
undefined, // query
name, // institutionName
undefined, // sortBy
undefined, // sortOrder
'cited_by_count', // sortBy
'desc', // sortOrder
[topic], // topic
1, // page
3, // pageSize
@@ -1289,8 +1311,37 @@ export class UniTrendParentComponent implements OnInit {
this.updateUrlParams();
}
isTopicEmpty(topic: string): boolean {
const data = this.trendResponse();
if (!data || !data.series || data.series.length === 0) {
return false;
}
const mapped = this.getMappedTopic(topic);
const startYr = this.startYear();
const endYr = this.endYear();
let totalRaw = 0;
data.series.forEach((s) => {
if (s.visible !== false && s.topic_data) {
const items = s.topic_data[topic] || s.topic_data[mapped];
if (items) {
items.forEach((y) => {
if (y.year >= startYr && y.year <= endYr) {
totalRaw += y.raw || 0;
}
});
}
}
});
return totalRaw === 0;
}
// Topic tab toggle (data reuses instantly)
updateActiveChartTopic(topic: string) {
if (this.isTopicEmpty(topic)) {
return;
}
this.activeChartTopic.set(topic);
this.updateUrlParams();
}
@@ -18,7 +18,10 @@
cursor: pointer;
&:disabled {
cursor: default;
cursor: not-allowed;
opacity: 0.45;
filter: grayscale(0.85);
pointer-events: none;
}
}