import { Component, OnInit, computed, inject, signal } from '@angular/core'; import { DecimalPipe, NgTemplateOutlet } from '@angular/common'; import { ActivatedRoute, RouterLink } from '@angular/router'; import { MatIconModule } from '@angular/material/icon'; import { EChartsOption } from 'echarts'; import { NgxEchartsDirective } from 'ngx-echarts'; import { AuthorOrientationProfile, AuthorOrientationProfilesRequest, AuthorStaticStats, AuthorTopicProfile, AuthorTopicStats, PublicationType, RankingService, SelectedAuthorsRequest, Topic, TopicsService, } from '../../api'; import { AuthorResearchProfileComponent, ResearchProfileAuthor, } from './author-research-profile/author-research-profile.component'; import { TopicTreemapComponent, TopicTreemapData, } from '../../shared/ui/topic-treemap/topic-treemap.component'; import { ChipComponent } from '../../shared/ui/chip/chip.component'; import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component'; import { ChartThemeService } from '../../shared/services/chart-theme.service'; import { topicHierarchyColor } from '../../resolvers/utils/topic-colors'; import { DATE_RANGE_ICON, OPEN_IN_NEW_ICON, STAR_ICON, } from '../../shared/ui/icons'; import { AUTHOR_COLORS, OTHER_COLOR, SUBFIELD_COLORS, } from './compare-authors-colors'; const SUBFIELD_LIMIT = 5; interface AuthorSummary { authorId: string; name: string; color: string; // section 1 // topic stats totalWorks: number | null; corresponding: number | null; avgPercentile: number | null; top10: number | null; top1: number | null; fwciAboveOne: number | null; avgFwci: number | null; // citations over the topic works citationsTotal: number | null; avgCitations: number | null; maxCitations: number | null; hIndex: number | null; // industry collaboration (works with a company co-author institution) industryWorks: number | null; industryShare: number | null; // active years within the topic firstYear: number | null; lastYear: number | null; // author-position split (first / middle / last) firstAuthor: number | null; middleAuthor: number | null; lastAuthor: number | null; // section 2: author-level stats (keyword-independent) companies: number | null; news: number | null; patents: number | null; } interface MetricCell { raw: number | null; best: boolean; } interface GroupSegment { label: string; colorClass: string; decimals: boolean; plain: boolean; } interface GroupCell { values: (number | null)[]; } interface MetricRow { label: string; hint: string; decimals: boolean; kind: 'scalar' | 'group'; cells: MetricCell[]; segments: GroupSegment[]; groupCells: GroupCell[]; nameMatched: boolean; } interface RowDef { label: string; hint: string; select: (a: AuthorSummary) => number | null; decimals?: boolean; nameMatched?: boolean; } interface SegmentDef { label: string; colorClass: string; select: (a: AuthorSummary) => number | null; decimals?: boolean; plain?: boolean; } @Component({ selector: 'app-compare-authors', standalone: true, imports: [ DecimalPipe, NgTemplateOutlet, RouterLink, MatIconModule, NgxEchartsDirective, AuthorResearchProfileComponent, TopicTreemapComponent, ChipComponent, TopicChipComponent, ], templateUrl: './compare-authors.component.html', styleUrl: './compare-authors.component.scss', }) export class CompareAuthorsComponent implements OnInit { readonly DATE_RANGE_ICON = DATE_RANGE_ICON; readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON; readonly STAR_ICON = STAR_ICON; private readonly route = inject(ActivatedRoute); private readonly rankingService = inject(RankingService); private readonly topicsService = inject(TopicsService); private readonly chartTheme = inject(ChartThemeService); readonly keywords = signal([]); readonly operator = signal<'and' | 'or'>('or'); readonly operatorLabel = computed(() => this.operator() === 'and' ? 'UND' : 'ODER', ); // resolved OpenAlex topic (field/domain) per keyword for colour matching private readonly keywordTopics = signal>({}); keywordColor(keyword: string): string { const topic = this.keywordTopics()[this.normalizeKeyword(keyword)]; return topicHierarchyColor( topic ? { id: topic.id, name: topic.display_name, field_id: topic.field?.id, field_name: topic.field?.display_name, domain_id: topic.domain?.id, domain_name: topic.domain?.display_name, } : { name: keyword }, ); } private normalizeKeyword(keyword: string): string { return keyword.trim().toLowerCase(); } readonly timespan = signal<{ from: number; to: number } | null>(null); // full OpenAlex ids in the requested order — the source of truth for colour + order readonly authorIds = signal([]); // section 1: combined topic stats, one entry per author readonly topic = signal([]); // section 2: keyword-independent author-level stats readonly staticStats = signal([]); // section 3: topic profile over ALL works of each author readonly profile = signal([]); readonly orientationProfiles = signal([]); readonly profileLoading = signal(false); readonly orientationProfilesLoading = signal(false); readonly loading = signal(false); // maps both sections onto one row per author, in the requested order readonly summary = computed(() => { const topicById = new Map(this.topic().map((a) => [a.author_id, a])); const staticById = new Map(this.staticStats().map((a) => [a.author_id, a])); const authorPalette = this.chartTheme.colors().authorColors; return this.authorIds().map((id, index) => { const t = topicById.get(id); const m = staticById.get(id); const name = t?.display_name ?? m?.display_name ?? id.split('/').pop() ?? id; const authorSummary: AuthorSummary = { authorId: id, name, color: authorPalette[index % authorPalette.length], totalWorks: t ? t.works_total : null, corresponding: t ? t.corresponding_count : null, avgPercentile: t ? t.avg_percentile : null, top10: t ? t.top10_count : null, top1: t ? t.top1_count : null, fwciAboveOne: t?.fwci_above_one_count ?? null, avgFwci: t?.avg_fwci ?? null, citationsTotal: t?.citations_total ?? null, avgCitations: t?.avg_citations ?? null, maxCitations: t?.max_citations ?? null, hIndex: t?.h_index ?? null, industryWorks: t?.industry_works_count ?? null, industryShare: t && t.works_total > 0 ? (t.industry_works_count ?? 0) / t.works_total : null, firstYear: t?.first_year ?? null, lastYear: t?.last_year ?? null, firstAuthor: t?.first_author_count ?? null, middleAuthor: t?.middle_author_count ?? null, lastAuthor: t?.last_author_count ?? null, companies: m?.companies_count ?? null, news: m?.news_count ?? null, patents: m?.patents_count ?? null, }; return authorSummary; }); }); readonly hasData = computed(() => this.summary().length > 0); // section 1 table: stats over the topic-filtered works readonly topicRows = computed(() => [ ...this.buildRows([ { label: 'Werke gesamt', hint: 'Publikationen zum Thema im Zeitraum', select: (a) => a.totalWorks, }, { label: 'Corresponding-Author-Werke', hint: 'Werke, in denen die Person korrespondierende:r Autor:in ist', select: (a) => a.corresponding, }, ]), this.buildGroupRow( 'Zitationen', 'Zitationen der Themen-Werke: gesamt | Ø pro Werk', [ { label: 'gesamt', colorClass: 'cit-total', select: (a) => a.citationsTotal, }, { label: 'Ø', colorClass: 'cit-avg', decimals: true, select: (a) => a.avgCitations, }, ], ), ...this.buildRows([ { label: 'Ø Impact-Perzentil', hint: 'Feld-normalisiertes Zitations-Perzentil (0–1)', select: (a) => a.avgPercentile, decimals: true, }, { label: 'h-Index', hint: 'h-Index über die Werke zum Thema', select: (a) => a.hIndex, }, { label: 'Meistzitiertes Werk', hint: 'Zitationen des meistzitierten Werks zum Thema', select: (a) => a.maxCitations, }, { label: 'Top-10%-Werke', hint: 'Werke unter den 10% meistzitierten', select: (a) => a.top10, }, { label: 'Top-1%-Werke', hint: 'Werke unter den 1% meistzitierten', select: (a) => a.top1, }, ]), this.buildGroupRow( 'FWCI', 'Field-Weighted Citation Impact: Werke über Feld-Durchschnitt | Ø über alle', [ { label: '> 1', colorClass: 'fwci-count', select: (a) => a.fwciAboveOne, }, { label: 'Ø', colorClass: 'fwci-avg', decimals: true, select: (a) => a.avgFwci, }, ], ), this.buildGroupRow( 'Autor-Position', 'Werke nach Position (Erst | Mittel | Letzt)', [ { label: 'Erst', colorClass: 'pos-first', select: (a) => a.firstAuthor, }, { label: 'Mittel', colorClass: 'pos-middle', select: (a) => a.middleAuthor, }, { label: 'Letzt', colorClass: 'pos-last', select: (a) => a.lastAuthor }, ], ), this.buildGroupRow( 'Industrie-Kollaboration', 'Werke mit Co-Autor:in aus einem Unternehmen: Anzahl | Anteil', [ { label: 'Anzahl', colorClass: 'ind-count', select: (a) => a.industryWorks, }, { label: 'Anteil', colorClass: 'ind-share', decimals: true, select: (a) => a.industryShare, }, ], ), this.buildGroupRow( 'Aktiv im Thema', 'Erstes und letztes Publikationsjahr zum Thema', [ { label: 'von', colorClass: 'year-from', plain: true, select: (a) => a.firstYear, }, { label: 'bis', colorClass: 'year-to', plain: true, select: (a) => a.lastYear, }, ], ), ]); // section 2 table: author-level stats, independent of the keywords readonly staticRows = computed(() => this.buildRows([ { label: 'Unternehmensgründungen', hint: 'Handelsregister-Verbindungen über den Namen', select: (a) => a.companies, nameMatched: true, }, { label: 'News-Artikel', hint: 'Nachrichtenartikel, die die Person namentlich nennen', select: (a) => a.news, nameMatched: true, }, { label: 'Patente', hint: 'Der Person zugeordnete Patente', nameMatched: true, select: (a) => a.patents, }, ]), ); // section 3: profiles in the requested author order (drives all charts) readonly orderedProfiles = computed(() => { const byId = new Map(this.profile().map((p) => [p.author_id, p])); return this.authorIds() .map((id) => byId.get(id)) .filter((p): p is AuthorTopicProfile => p !== undefined); }); readonly researchProfileAuthors = computed(() => { return this.summary().map((author) => ({ authorId: author.authorId, name: author.name, color: author.color, })); }); // treemap (section 3): one author's full topic hierarchy, switchable via tabs readonly selectedTreemapAuthor = signal(0); // drill-down state of the treemap for the selected author readonly treemapNodeId = signal(undefined); readonly treemapProfile = computed(() => { const profiles = this.orderedProfiles(); if (profiles.length === 0) return null; const index = Math.min(this.selectedTreemapAuthor(), profiles.length - 1); return profiles[index]; }); // maps the selected author's field_tree onto the shared treemap data model readonly treemapData = computed(() => { const profile = this.treemapProfile(); if (!profile) return undefined; return { institution_id: profile.author_id, organization_name: profile.display_name, years: [], fields: (profile.field_tree ?? []).map((field) => ({ id: field.id, name: field.name, total: field.count, values: [], subfields: (field.subfields ?? []).map((subfield) => ({ id: subfield.id, name: subfield.name, total: subfield.count, values: [], topics: (subfield.topics ?? []).map((topic) => ({ id: topic.id, name: topic.name, total: topic.count, values: [], })), })), })), }; }); selectTreemapAuthor(index: number): void { this.selectedTreemapAuthor.set(index); // reset the drill-down when switching author this.treemapNodeId.set(undefined); } authorColor(authorId: string): string { return ( this.summary().find((a) => a.authorId === authorId)?.color ?? OTHER_COLOR ); } authorProfileId(authorId: string): string { const parts = authorId.split('/'); return parts[parts.length - 1]; } // colours the author names on the chart axes like the legend chips private authorAxisLabel(profiles: AuthorTopicProfile[]) { const rich: Record = {}; profiles.forEach((_, i) => { rich[`a${i}`] = { color: AUTHOR_COLORS[i % AUTHOR_COLORS.length], fontWeight: 600, }; }); return { formatter: (value: string) => { const index = profiles.findIndex((p) => p.display_name === value); return index >= 0 ? `{a${index}|${value}}` : value; }, rich, // rich-text labels are measured slightly too narrow — leave some slack margin: 12, }; } // chart 1: how each author's complete body of work distributes over subfields readonly subfieldChart = computed(() => { const profiles = this.orderedProfiles(); if (profiles.length === 0) return {}; // union of the biggest subfields across all authors, one colour each const totals = new Map(); for (const p of profiles) { for (const s of p.subfields || []) { totals.set(s.name, (totals.get(s.name) ?? 0) + s.count); } } const topSubfields = [...totals.entries()] .sort((a, b) => b[1] - a[1]) .slice(0, SUBFIELD_LIMIT) .map(([name]) => name); const shownCounts = profiles.map((p) => topSubfields.map( (name) => p.subfields?.find((s) => s.name === name)?.count ?? 0, ), ); const series: any[] = topSubfields.map((name, si) => ({ name, type: 'bar', stack: 'profil', barWidth: 22, emphasis: { focus: 'series' }, itemStyle: { color: SUBFIELD_COLORS[si % SUBFIELD_COLORS.length] }, data: profiles.map((p, ai) => { const count = shownCounts[ai][si]; return { value: p.works_total > 0 ? Math.round((count / p.works_total) * 1000) / 10 : 0, count, }; }), })); // everything outside the shown subfields (incl. works without primary topic) series.push({ name: 'Sonstige', type: 'bar', stack: 'profil', barWidth: 22, emphasis: { focus: 'series' }, itemStyle: { color: OTHER_COLOR }, data: profiles.map((p, ai) => { const rest = p.works_total - shownCounts[ai].reduce((sum, c) => sum + c, 0); return { value: p.works_total > 0 ? Math.round((rest / p.works_total) * 1000) / 10 : 0, count: rest, }; }), }); return { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: (params: any) => { const lines = params .filter((p: any) => p.data.count > 0) .map( (p: any) => `${p.marker} ${p.seriesName}: ${p.data.value} % (${p.data.count} Werke)`, ); return `${params[0]?.name ?? ''}
${lines.join('
')}`; }, }, legend: { type: 'scroll', top: 0, textStyle: { color: this.chartTheme.colors().text }, }, grid: { left: 16, right: 24, top: 56, bottom: 8, containLabel: true }, xAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value} %' }, }, yAxis: { type: 'category', inverse: true, data: profiles.map((p) => p.display_name), axisLabel: this.authorAxisLabel(profiles), }, series, } as EChartsOption; }); // chart 2: topic focus — how much of the complete body of work is on the searched topic readonly focusChart = computed(() => { const profiles = this.orderedProfiles(); if (profiles.length === 0) return {}; const pct = (part: number, whole: number) => whole > 0 ? Math.round((part / whole) * 1000) / 10 : 0; return { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: (params: any) => { const lines = params.map( (p: any) => `${p.marker} ${p.seriesName}: ${p.data.value} % (${p.data.part} von ${p.data.whole} Werken)`, ); return `${params[0]?.name ?? ''}
${lines.join('
')}`; }, }, legend: { top: 0, textStyle: { color: this.chartTheme.colors().text } }, grid: { left: 16, right: 40, top: 32, bottom: 8, containLabel: true }, xAxis: { type: 'value', max: 100, axisLabel: { formatter: '{value} %' }, }, yAxis: { type: 'category', inverse: true, data: profiles.map((p) => p.display_name), axisLabel: this.authorAxisLabel(profiles), }, series: [ { name: 'Anteil am Gesamtwerk', type: 'bar', itemStyle: { color: '#2563eb' }, label: { show: true, position: 'right', formatter: '{c} %' }, data: profiles.map((p) => ({ value: pct(p.matched_works, p.works_total), part: p.matched_works, whole: p.works_total, })), }, { name: 'davon Primärthema', type: 'bar', itemStyle: { color: '#7c3aed' }, label: { show: true, position: 'right', formatter: '{c} %' }, data: profiles.map((p) => ({ value: pct(p.primary_topic_matches, p.matched_works), part: p.primary_topic_matches, whole: p.matched_works, })), }, ], } as EChartsOption; }); // chart 3: topic breadth — how many distinct (sub)fields the author publishes in readonly breadthChart = computed(() => { const profiles = this.orderedProfiles(); if (profiles.length === 0) return {}; return { tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, legend: { top: 0, textStyle: { color: this.chartTheme.colors().text } }, grid: { left: 16, right: 40, top: 32, bottom: 8, containLabel: true }, xAxis: { type: 'value' }, yAxis: { type: 'category', inverse: true, data: profiles.map((p) => p.display_name), axisLabel: this.authorAxisLabel(profiles), }, series: [ { name: 'Themen', type: 'bar', itemStyle: { color: this.chartTheme.colors().blueHighlight }, label: { show: true, position: 'right' }, data: profiles.map((p) => p.distinct_topics), }, { name: 'Subfields', type: 'bar', itemStyle: { color: this.chartTheme.colors().warning }, label: { show: true, position: 'right' }, data: profiles.map((p) => p.distinct_subfields), }, { name: 'Fields', type: 'bar', itemStyle: { color: this.chartTheme.colors().success }, label: { show: true, position: 'right' }, data: profiles.map((p) => p.distinct_fields), }, ], } as EChartsOption; }); // turns row definitions into table rows, marking the best value per row private buildRows(defs: RowDef[]): MetricRow[] { const authors = this.summary(); return defs.map((def) => { const values = authors.map(def.select); const present = values.filter((v): v is number => v !== null); const max = present.length ? Math.max(...present) : null; return { label: def.label, hint: def.hint, decimals: def.decimals ?? false, kind: 'scalar' as const, cells: values.map((raw) => ({ raw, best: raw !== null && max !== null && raw === max && max > 0, })), segments: [], groupCells: [], nameMatched: def.nameMatched ?? false, }; }); } private buildGroupRow( label: string, hint: string, segs: SegmentDef[], ): MetricRow { return { label, hint, decimals: false, kind: 'group' as const, cells: [], segments: segs.map((s) => ({ label: s.label, colorClass: s.colorClass, decimals: s.decimals ?? false, plain: s.plain ?? false, })), groupCells: this.summary().map((a) => ({ values: segs.map((s) => s.select(a)), })), nameMatched: false, }; } hasNameMatchedRow(rows: MetricRow[]): boolean { return rows.some((row) => row.nameMatched); } ngOnInit(): void { // everything is read from the URL so a shared link lands on the same view const rawAuthors = this.route.snapshot.queryParamMap.get('authors') ?? ''; const rawKeywords = this.route.snapshot.queryParamMap.get('keywords') ?? ''; const rawOperator = this.route.snapshot.queryParamMap.get('operator'); const rawTopics = this.route.snapshot.queryParamMap.get('topics') ?? ''; const fuzzy = this.route.snapshot.queryParamMap.get('fuzzy') === 'true'; const rawPubType = this.route.snapshot.queryParamMap.get('pubType'); const rawTFrom = this.route.snapshot.queryParamMap.get('tFrom'); const rawTTo = this.route.snapshot.queryParamMap.get('tTo'); const authorIds = this.parseList(rawAuthors); const keywords = this.parseList(rawKeywords); this.keywords.set(keywords); this.resolveKeywordColors(keywords); if (authorIds.length === 0 || keywords.length === 0) { return; } const operator = rawOperator === 'and' ? 'and' : 'or'; this.operator.set(operator); const publication_types = rawPubType ? this.parseList(rawPubType) .map((s) => this.getPublicationType(s)) .filter((v): v is PublicationType => !!v) : undefined; const timespan = rawTFrom && rawTTo ? { from: +rawTFrom, to: +rawTTo } : undefined; this.timespan.set(timespan ?? null); // ids in the url are bare (A5036...); the endpoint expects full OpenAlex urls const fullIds = authorIds.map((id) => `https://openalex.org/${id}`); this.authorIds.set(fullIds); // same two match modes as the persons list: topic ids when fuzzy, raw keywords otherwise const topicIds = this.parseList(rawTopics); const request: SelectedAuthorsRequest = { author_ids: fullIds, keywords: fuzzy && topicIds.length > 0 ? topicIds : keywords, operator: operator, fuzzy: fuzzy && topicIds.length > 0, publication_types: publication_types, timespan: timespan, }; const orientationRequest: AuthorOrientationProfilesRequest = { author_ids: fullIds, publication_types: publication_types, timespan: timespan, }; // section 1: topic-filtered works stats this.loading.set(true); this.rankingService.topicStatsApiRankTopicStatsPost(request).subscribe({ next: (results) => { this.topic.set(results); this.loading.set(false); }, error: (error) => { console.error(error); this.topic.set([]); this.loading.set(false); }, }); // section 3: topic profile over ALL works (same filter, own endpoint) this.profileLoading.set(true); this.rankingService.topicProfileApiRankTopicProfilePost(request).subscribe({ next: (results) => { this.profile.set(results); this.profileLoading.set(false); }, error: (error) => { console.error(error); this.profile.set([]); this.profileLoading.set(false); }, }); // section 2: keyword-independent author-level stats this.rankingService .staticStatsApiRankStaticStatsPost({ author_ids: fullIds }) .subscribe({ next: (results) => { this.staticStats.set(results); }, error: (error) => { console.error(error); this.staticStats.set([]); }, }); if (fullIds.length >= 2) { this.orientationProfilesLoading.set(true); this.rankingService .orientationProfilesApiRankOrientationProfilesPost(orientationRequest) .subscribe({ next: (results) => { this.orientationProfiles.set(results); this.orientationProfilesLoading.set(false); }, error: (error) => { console.error(error); this.orientationProfiles.set([]); this.orientationProfilesLoading.set(false); }, }); } } private resolveKeywordColors(keywords: string[]): void { if (keywords.length === 0) return; this.topicsService.vectorSearchTopicsBatch({ keywords }).subscribe({ next: ({ results }) => { const topics: Record = {}; for (const result of results) { if (result.topic) { topics[this.normalizeKeyword(result.keyword)] = result.topic; } } this.keywordTopics.set(topics); }, error: (error) => { console.error('Error resolving keyword topics:', error); }, }); } private parseList(raw: string): string[] { return raw .split(',') .map((value) => value.trim()) .filter(Boolean); } getPublicationType(str: string): PublicationType | null { const normalized = str.trim().toLowerCase(); for (const [key, value] of Object.entries(PublicationType)) { if (value.toLowerCase() === normalized) { return value as PublicationType; } } return null; } }