add static author-level stats (Gründungen/News/Patente)

This commit is contained in:
Steven Tischer
2026-07-19 17:20:57 +02:00
parent 8d4fb333a2
commit ea131c9780
9 changed files with 454 additions and 107 deletions
+65
View File
@@ -1,6 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import logging
from time import time
from typing import Any, List, Optional
@@ -14,6 +15,7 @@ from inse.persons.query_builder import build_author_filter_clauses
from inse.company_connections.logic import get_company_counts_by_names
from .. import config
from .model import (
AuthorStaticStats,
AuthorTopicStats,
CareerStage,
CompanyStatusFilter,
@@ -246,6 +248,69 @@ async def topic_stats_for_authors(
return results
async def _get_display_names_by_ids(author_ids: List[str]) -> dict:
if not author_ids:
return {}
body = {
"size": len(author_ids),
"_source": ["id", "display_name"],
"query": {"terms": {"id": author_ids}},
}
response: dict[str, Any] = await elasticsearch.search(
index="openalex-authors",
body=body,
cluster=ESCluster.NES,
)
names = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
author_id = source.get("id")
if author_id:
names[author_id] = source.get("display_name", "")
return names
async def static_stats_for_authors(
author_ids: List[str],
company_status: CompanyStatusFilter = CompanyStatusFilter.ALL,
) -> List[AuthorStaticStats]:
"""Section 2: per author, keyword-independent stats (companies, news, patents).
Companies and news are matched by exact display name, patents by author id.
"""
if not author_ids:
return []
names_by_id = await _get_display_names_by_ids(author_ids)
names = [name for name in names_by_id.values() if name]
company_counts, news_counts, patent_counts = await asyncio.gather(
get_company_counts_by_names(names, company_status=company_status),
_get_news_counts_by_names(names),
_get_patent_counts_by_author_ids(author_ids),
)
results = []
for author_id in author_ids:
name = names_by_id.get(author_id, "")
results.append(
AuthorStaticStats(
author_id=author_id,
display_name=name,
companies_count=company_counts.get(name, 0),
news_count=news_counts.get(name, 0),
patents_count=patent_counts.get(author_id, 0),
)
)
return results
def _publication_type_filter(publication_types: List[PublicationType]) -> dict:
"""Keeps only works whose type is one of the given publication types."""
type_values = []
+28
View File
@@ -167,6 +167,18 @@ class SelectedAuthorsRequest(BaseModel):
return value
class AuthorMetricsRequest(BaseModel):
author_ids: List[str] = Field(
min_length=1,
description="OpenAlex IDs of the authors.",
)
company_status: CompanyStatusFilter = Field(
default=CompanyStatusFilter.ALL,
description="Which companies to count for the company-foundations metric: "
"'all', only 'active' (non-deleted), or only 'deleted'.",
)
class AuthorTopicStats(BaseModel):
"""Section 1: combined stats over an author's works that match the topic filter."""
@@ -189,6 +201,22 @@ class AuthorTopicStats(BaseModel):
)
class AuthorStaticStats(BaseModel):
"""Section 2: author-level stats independent of any keyword/topic/time filter."""
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
companies_count: int = Field(
description="Number of Handelsregister company connections matched by the author's name.",
)
news_count: int = Field(
description="Number of news articles that mention the author by exact name.",
)
patents_count: int = Field(
description="Number of patents matched to the author (from the org_patents index).",
)
class RankedAuthor(BaseModel):
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
+15
View File
@@ -6,6 +6,8 @@ from fastapi import APIRouter
from inse.tags import Tags
from . import logic
from .model import (
AuthorMetricsRequest,
AuthorStaticStats,
AuthorTopicStats,
KeywordToAuthorRequest,
RankedAuthor,
@@ -61,3 +63,16 @@ async def topic_stats(request: SelectedAuthorsRequest):
request.publication_types,
request.timespan,
)
# Compare authors table 2 (author-level stats, keyword/time-independent)
@router.post("/static-stats", response_model=List[AuthorStaticStats])
async def static_stats(request: AuthorMetricsRequest):
logger.info(
"static-stats author_ids=%s company_status=%s",
request.author_ids,
request.company_status,
)
return await logic.static_stats_for_authors(
request.author_ids,
request.company_status,
)
+117
View File
@@ -30,6 +30,10 @@ import { RankedAuthor } from '../model/rankedAuthor';
import { RankSelectedAuthorRequest } from '../model/rankSelectedAuthorRequest';
// @ts-ignore
import { AuthorTopicStats } from '../model/authorTopicStats';
// @ts-ignore
import { AuthorStaticStats } from '../model/authorStaticStats';
// @ts-ignore
import { AuthorMetricsRequest } from '../model/authorMetricsRequest';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -280,4 +284,117 @@ export class RankingService extends BaseService {
},
);
}
/**
* Section 2: keyword-independent author-level stats (companies, news, patents).
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public staticStats(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorStaticStats>>;
public staticStats(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStats(
authorMetricsRequest: AuthorMetricsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStats(
authorMetricsRequest: AuthorMetricsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error(
'Required parameter authorMetricsRequest was null or undefined when calling staticStats.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
@@ -0,0 +1,20 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface AuthorMetricsRequest {
/**
* OpenAlex IDs of the authors.
*/
author_ids: Array<string>;
/**
* Which companies to count for the company-foundations metric: \'all\', only \'active\' (non-deleted), or only \'deleted\'.
*/
company_status?: string;
}
@@ -0,0 +1,32 @@
/**
* Innovation Search Engine API
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
export interface AuthorStaticStats {
/**
* The OpenAlex ID of the author.
*/
author_id: string;
/**
* The name of the author.
*/
display_name: string;
/**
* Number of Handelsregister company connections matched by the author\'s name.
*/
companies_count: number;
/**
* Number of news articles that mention the author by exact name.
*/
news_count: number;
/**
* Number of patents matched to the author (from the org_patents index).
*/
patents_count: number;
}
+2
View File
@@ -221,3 +221,5 @@ export * from './rankedAuthor';
export * from './keywordToAuthorRequest';
export * from './rankSelectedAuthorRequest';
export * from './authorTopicStats';
export * from './authorStaticStats';
export * from './authorMetricsRequest';
@@ -36,54 +36,68 @@
} @else if (!hasData()) {
<p class="compare-hint">Keine Daten für die ausgewählten Autoren.</p>
} @else {
<!-- section 1: topic stats side by side -->
<!-- section 1: stats over the topic-filtered works -->
<section class="card">
<h2 class="card-title">Kennzahlen zu den Keywords</h2>
<p class="card-sub">
Bester Wert je Zeile ist hervorgehoben. „–“ bedeutet, dass der Wert für
diese:n Autor:in nicht vorliegt.
</p>
<ng-container
[ngTemplateOutlet]="statsTable"
[ngTemplateOutletContext]="{ rows: topicRows() }" />
</section>
<div class="table-scroll">
<table class="compare-table">
<thead>
<tr>
<th class="metric-col">Kennzahl</th>
@for (author of summary(); track author.authorId) {
<th class="author-col">
<span class="th-name">
<span
class="legend-swatch"
[style.background]="author.color"></span>
{{ author.name }}
</span>
</th>
}
</tr>
</thead>
<tbody>
@for (row of metricRows(); track row.label) {
<tr>
<th scope="row" class="metric-col">
<span class="metric-label">{{ row.label }}</span>
<span class="metric-hint">{{ row.hint }}</span>
</th>
@for (cell of row.cells; track $index) {
<td class="value-cell" [class.best]="cell.best">
@if (cell.raw === null) {
<span class="value-empty">–</span>
} @else if (row.decimals) {
{{ cell.raw | number: '1.2-2' }}
} @else {
{{ cell.raw | number }}
}
</td>
}
</tr>
}
</tbody>
</table>
</div>
<!-- section 2: author-level stats, independent of the keywords and time -->
<section class="card">
<h2 class="card-title">Kennzahlen zur Person</h2>
<p class="card-sub">Unabhängig von den Keywords und Zeitraum.</p>
<ng-container
[ngTemplateOutlet]="statsTable"
[ngTemplateOutletContext]="{ rows: staticRows() }" />
</section>
}
</div>
<ng-template #statsTable let-rows="rows">
<div class="table-scroll">
<table class="compare-table">
<thead>
<tr>
<th class="metric-col">Kennzahl</th>
@for (author of summary(); track author.authorId) {
<th class="author-col">
<span class="th-name">
<span
class="legend-swatch"
[style.background]="author.color"></span>
{{ author.name }}
</span>
</th>
}
</tr>
</thead>
<tbody>
@for (row of rows; track row.label) {
<tr>
<th scope="row" class="metric-col">
<span class="metric-label">{{ row.label }}</span>
<span class="metric-hint">{{ row.hint }}</span>
</th>
@for (cell of row.cells; track $index) {
<td class="value-cell" [class.best]="cell.best">
@if (cell.raw === null) {
<span class="value-empty">–</span>
} @else if (row.decimals) {
{{ cell.raw | number: '1.2-2' }}
} @else {
{{ cell.raw | number }}
}
</td>
}
</tr>
}
</tbody>
</table>
</div>
</ng-template>
@@ -1,9 +1,9 @@
import { Component, OnInit, computed, inject, signal } from '@angular/core';
import { DecimalPipe } from '@angular/common';
import { DecimalPipe, NgTemplateOutlet } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { MatIconModule } from '@angular/material/icon';
import { AuthorTopicStats, RankingService } from '../../api';
import { AuthorStaticStats, AuthorTopicStats, RankingService } from '../../api';
const AUTHOR_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd'];
@@ -11,11 +11,16 @@ interface AuthorSummary {
authorId: string;
name: string;
color: string;
totalWorks: number;
// section 1: topic stats
totalWorks: number | null;
corresponding: number | null;
avgPercentile: number | null;
top10: number | null;
top1: number | null;
// section 2: author-level stats (keyword-independent)
companies: number | null;
news: number | null;
patents: number | null;
}
interface MetricCell {
@@ -30,10 +35,17 @@ interface MetricRow {
cells: MetricCell[];
}
interface RowDef {
label: string;
hint: string;
select: (a: AuthorSummary) => number | null;
decimals?: boolean;
}
@Component({
selector: 'app-compare-authors',
standalone: true,
imports: [DecimalPipe, MatIconModule],
imports: [DecimalPipe, NgTemplateOutlet, MatIconModule],
templateUrl: './compare-authors.component.html',
styleUrl: './compare-authors.component.scss',
})
@@ -48,80 +60,110 @@ export class CompareAuthorsComponent implements OnInit {
// section 1: combined topic stats, one entry per author
readonly topic = signal<AuthorTopicStats[]>([]);
// section 2: keyword-independent author-level stats
readonly staticStats = signal<AuthorStaticStats[]>([]);
readonly loading = signal(false);
// maps the topic stats onto one row per author, in the requested order
// maps both sections onto one row per author, in the requested order
readonly summary = computed<AuthorSummary[]>(() => {
const stats = new Map(this.topic().map((a) => [a.author_id, a]));
const topicById = new Map(this.topic().map((a) => [a.author_id, a]));
const staticById = new Map(this.staticStats().map((a) => [a.author_id, a]));
return this.authorIds().map((id, index) => {
const s = stats.get(id);
const name = s?.display_name ?? id.split('/').pop() ?? id;
const t = topicById.get(id);
const m = staticById.get(id);
const name =
t?.display_name ?? m?.display_name ?? id.split('/').pop() ?? id;
return {
authorId: id,
name,
color: AUTHOR_COLORS[index % AUTHOR_COLORS.length],
totalWorks: s ? s.works_total : 0,
corresponding: s ? s.corresponding_count : null,
avgPercentile: s ? s.avg_percentile : null,
top10: s ? s.top10_count : null,
top1: s ? s.top1_count : null,
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,
companies: m ? m.companies_count : null,
news: m ? m.news_count : null,
patents: m ? m.patents_count : null,
};
});
});
readonly hasData = computed(() => this.summary().length > 0);
// the comparison table: every scalar value the backend returns, best per row marked
readonly metricRows = computed<MetricRow[]>(() => {
const authors = this.summary();
// section 1 table: stats over the topic-filtered works
readonly topicRows = computed<MetricRow[]>(() =>
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,
},
{
label: 'Ø Impact-Perzentil',
hint: 'Feld-normalisiertes Zitations-Perzentil (0–1)',
select: (a) => a.avgPercentile,
decimals: true,
},
{
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,
},
]),
);
const row = (
label: string,
hint: string,
select: (a: AuthorSummary) => number | null,
decimals = false,
): MetricRow => {
const values = authors.map(select);
// section 2 table: author-level stats, independent of the keywords
readonly staticRows = computed<MetricRow[]>(() =>
this.buildRows([
{
label: 'Unternehmensgründungen',
hint: 'Handelsregister-Verbindungen über den Namen',
select: (a) => a.companies,
},
{
label: 'News-Artikel',
hint: 'Nachrichtenartikel, die die Person namentlich nennen',
select: (a) => a.news,
},
{
label: 'Patente',
hint: 'Der Person zugeordnete Patente',
select: (a) => a.patents,
},
]),
);
// 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,
hint,
decimals,
label: def.label,
hint: def.hint,
decimals: def.decimals ?? false,
cells: values.map((raw) => ({
raw,
best: raw !== null && max !== null && raw === max && max > 0,
})),
};
};
return [
row(
'Werke gesamt',
'Publikationen zum Thema im Zeitraum',
(a) => a.totalWorks,
),
row(
'Corresponding-Author-Werke',
'Werke, in denen die Person korrespondierende:r Autor:in ist',
(a) => a.corresponding,
),
row(
'Ø Impact-Perzentil',
'Feld-normalisiertes Zitations-Perzentil (0–1)',
(a) => a.avgPercentile,
true,
),
row(
'Top-10%-Werke',
'Werke unter den 10% meistzitierten',
(a) => a.top10,
),
row('Top-1%-Werke', 'Werke unter den 1% meistzitierten', (a) => a.top1),
];
});
});
}
ngOnInit(): void {
// everything is read from the URL so a shared link lands on the same view
@@ -152,24 +194,36 @@ export class CompareAuthorsComponent implements OnInit {
const fullIds = authorIds.map((id) => `https://openalex.org/${id}`);
this.authorIds.set(fullIds);
const requestPayload = {
author_ids: fullIds,
keywords: keywords,
operator: operator,
publication_types: publication_types,
timespan: timespan,
};
// section 1: topic-filtered works stats
this.loading.set(true);
this.rankingService.topicStats(requestPayload).subscribe({
this.rankingService
.topicStats({
author_ids: fullIds,
keywords: keywords,
operator: operator,
publication_types: publication_types,
timespan: timespan,
})
.subscribe({
next: (results) => {
this.topic.set(results);
this.loading.set(false);
},
error: (error) => {
console.error(error);
this.topic.set([]);
this.loading.set(false);
},
});
// section 2: keyword-independent author-level stats
this.rankingService.staticStats({ author_ids: fullIds }).subscribe({
next: (results) => {
this.topic.set(results);
this.loading.set(false);
this.staticStats.set(results);
},
error: (error) => {
console.error(error);
this.topic.set([]);
this.loading.set(false);
this.staticStats.set([]);
},
});
}