Added default institution from token. Added button links depending on current tab. Changed top 10 to top 20 and added custom projects top 20 query for projects

This commit is contained in:
Kazgatari
2026-07-19 19:15:26 +02:00
parent ebb986b225
commit 616b83e546
8 changed files with 292 additions and 23 deletions
@@ -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,161 @@ 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:
res_alias = await elasticsearch.search(
index="institutions_alias",
query={"term": {"id.keyword": entity_id if entity_id.startswith("http") else f"https://openalex.org/{entity_id}"}},
size=1,
cluster="nes"
)
hits_alias = res_alias.get("hits", {}).get("hits", [])
if hits_alias:
aliases = hits_alias[0]["_source"].get("aliases", [short_id])
except Exception:
pass
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": []}
# 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}"
@@ -862,7 +1022,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 +1056,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 +1065,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": []}
@@ -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' },
@@ -746,13 +761,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 +828,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 +1113,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
@@ -1089,10 +1139,7 @@ export class UniTrendParentComponent implements OnInit {
// Add comparison institution
addInstitution(id: string, name: string) {
const current = this.comparisonInstitutions();
if (
!current.some((i: CompareItem) => i.id === id) &&
id !== this.primaryInstitution()
) {
if (!current.some((i: CompareItem) => i.id === id)) {
this.comparisonInstitutions.set([...current, { id, name }]);
}
this.searchQuery.set('');
@@ -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 `/person/${cleanId}/projects?page=0&size=10&sort_by=title&sort_direction=asc&search=`;
}
if (tab === 'patents') {
return `/person/${cleanId}/patents`;
}
return `/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 `/institution/${cleanId}/projects?project_tab=bund&page=0&size=10&search=&sort_by=title&sort_direction=asc`;
}
if (tab === 'patents') {
return `/institution/${cleanId}/patents?filter=all&sortBy=date&matchType=all&page=1`;
}
return `/institution/${cleanId}/publications`;
}
onSelectPie(id: string, name: string): void {
this.selectPie.emit({ id, name, type: 'institution' });
}