add corresponding authors feature with query and visualization

This commit is contained in:
Steven Tischer
2026-07-13 08:17:25 +02:00
parent 7775400a3f
commit 8f65cd78ba
9 changed files with 694 additions and 1 deletions
+209
View File
@@ -12,6 +12,8 @@ from inse.model import ESCluster
from inse.persons.logic import _classify_career_stage
from .. import config
from .model import (
AuthorCorrespondingCount,
AuthorImpactStats,
AuthorYearlyWorks,
CareerStage,
KeywordOperator,
@@ -222,6 +224,213 @@ async def yearly_works_for_authors(
return results
def _corresponding_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
) -> dict:
"""Builds a query that counts, per selected author, the topic works where they are the corresponding author."""
return {
"size": 0,
"query": {
"bool": {
"filter": [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
],
},
},
"aggs": {
"authors": {
"nested": {"path": "authorships"},
"aggs": {
"corresponding": {
# keep only authorships of the selected authors where they
# are the corresponding author
"filter": {
"bool": {
"filter": [
{"terms": {"authorships.author.id": author_ids}},
{"term": {"authorships.is_corresponding": True}},
],
},
},
"aggs": {
"by_author": {
"terms": {
"field": "authorships.author.id",
"size": len(author_ids),
"execution_hint": "map",
},
"aggs": {
"author_name": {
"terms": {
"field": "authorships.author.display_name.keyword",
"size": 1,
"execution_hint": "map",
},
},
},
},
},
},
},
},
},
}
async def corresponding_works_for_authors(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
) -> List[AuthorCorrespondingCount]:
"""For each selected author, counts the topic works where they are the corresponding author."""
if not author_ids:
return []
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_corresponding_query(author_ids, keywords, operator),
cluster=ESCluster.NES,
)
author_buckets = (
response.get("aggregations", {})
.get("authors", {})
.get("corresponding", {})
.get("by_author", {})
.get("buckets", [])
)
results = []
for author_bucket in author_buckets:
results.append(
AuthorCorrespondingCount(
author_id=author_bucket.get("key", ""),
display_name=_display_name_from_bucket(author_bucket),
value=author_bucket.get("doc_count", 0),
)
)
return results
def _impact_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
) -> dict:
"""Builds a query with per-author citation-impact stats over their topic works.
The percentile fields live on the work (citation_normalized_percentile), so we
step back to the work level with reverse_nested before averaging / counting.
"""
return {
"size": 0,
"query": {
"bool": {
"filter": [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
],
},
},
"aggs": {
"authors": {
"nested": {"path": "authorships"},
"aggs": {
"selected": {
"filter": {"terms": {"authorships.author.id": author_ids}},
"aggs": {
"by_author": {
"terms": {
"field": "authorships.author.id",
"size": len(author_ids),
"execution_hint": "map",
},
"aggs": {
"author_name": {
"terms": {
"field": "authorships.author.display_name.keyword",
"size": 1,
"execution_hint": "map",
},
},
"to_work": {
"reverse_nested": {},
"aggs": {
"avg_percentile": {
"avg": {
"field": "citation_normalized_percentile.value",
},
},
"top1": {
"filter": {
"term": {
"citation_normalized_percentile.is_in_top_1_percent": True,
},
},
},
"top10": {
"filter": {
"term": {
"citation_normalized_percentile.is_in_top_10_percent": True,
},
},
},
},
},
},
},
},
},
},
},
},
}
async def impact_stats_for_authors(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
) -> List[AuthorImpactStats]:
"""For each selected author, returns citation-impact stats over their topic works."""
if not author_ids:
return []
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_impact_query(author_ids, keywords, operator),
cluster=ESCluster.NES,
)
author_buckets = (
response.get("aggregations", {})
.get("authors", {})
.get("selected", {})
.get("by_author", {})
.get("buckets", [])
)
results = []
for author_bucket in author_buckets:
to_work = author_bucket.get("to_work", {})
avg_value = to_work.get("avg_percentile", {}).get("value")
results.append(
AuthorImpactStats(
author_id=author_bucket.get("key", ""),
display_name=_display_name_from_bucket(author_bucket),
avg_percentile=float(avg_value) if avg_value is not None else 0.0,
top1_count=to_work.get("top1", {}).get("doc_count", 0),
top10_count=to_work.get("top10", {}).get("doc_count", 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 = []
+22
View File
@@ -143,6 +143,28 @@ class AuthorYearlyWorks(BaseModel):
)
class AuthorCorrespondingCount(BaseModel):
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
value: int = Field(
description="Number of the author's works on the topic where they are the corresponding author.",
)
class AuthorImpactStats(BaseModel):
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
avg_percentile: float = Field(
description="Average field-normalized citation percentile (0-1) over the author's topic works.",
)
top1_count: int = Field(
description="Number of the author's topic works in the top 1% most-cited.",
)
top10_count: int = Field(
description="Number of the author's topic works in the top 10% most-cited.",
)
class RankedAuthor(BaseModel):
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
+32
View File
@@ -6,6 +6,8 @@ from fastapi import APIRouter
from inse.tags import Tags
from . import logic
from .model import (
AuthorCorrespondingCount,
AuthorImpactStats,
AuthorYearlyWorks,
KeywordToAuthorRequest,
RankedAuthor,
@@ -56,3 +58,33 @@ async def rank_selected_author(request: SelectedAuthorsRequest):
request.keywords,
request.operator,
)
@router.post("/corresponding-authors", response_model=List[AuthorCorrespondingCount])
async def corresponding_authors(request: SelectedAuthorsRequest):
logger.info(
"corresponding-authors author_ids=%s keywords=%s operator=%s",
request.author_ids,
request.keywords,
request.operator,
)
return await logic.corresponding_works_for_authors(
request.author_ids,
request.keywords,
request.operator,
)
@router.post("/impact-stats", response_model=List[AuthorImpactStats])
async def impact_stats(request: SelectedAuthorsRequest):
logger.info(
"impact-stats author_ids=%s keywords=%s operator=%s",
request.author_ids,
request.keywords,
request.operator,
)
return await logic.impact_stats_for_authors(
request.author_ids,
request.keywords,
request.operator,
)
+236
View File
@@ -30,6 +30,10 @@ import { RankedAuthor } from '../model/rankedAuthor';
import { RankSelectedAuthorRequest } from '../model/rankSelectedAuthorRequest';
// @ts-ignore
import { AuthorYearlyWorks } from '../model/authorYearlyWorks';
// @ts-ignore
import { AuthorCorrespondingCount } from '../model/authorCorrespondingCount';
// @ts-ignore
import { AuthorImpactStats } from '../model/authorImpactStats';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -281,4 +285,236 @@ export class RankingService extends BaseService {
},
);
}
/**
* Per selected author: number of topic works where they are the corresponding author.
* @endpoint post /api/rank/corresponding-authors
* @param rankSelectedAuthorRequest
* @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 correspondingAuthors(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorCorrespondingCount>>;
public correspondingAuthors(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorCorrespondingCount>>>;
public correspondingAuthors(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorCorrespondingCount>>>;
public correspondingAuthors(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
rankSelectedAuthorRequest === null ||
rankSelectedAuthorRequest === undefined
) {
throw new Error(
'Required parameter rankSelectedAuthorRequest was null or undefined when calling correspondingAuthors.',
);
}
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/corresponding-authors`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorCorrespondingCount>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: rankSelectedAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Per selected author: citation-impact stats (avg percentile, top 1% / top 10% counts) over their topic works.
* @endpoint post /api/rank/impact-stats
* @param rankSelectedAuthorRequest
* @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 impactStats(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorImpactStats>>;
public impactStats(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorImpactStats>>>;
public impactStats(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorImpactStats>>>;
public impactStats(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
rankSelectedAuthorRequest === null ||
rankSelectedAuthorRequest === undefined
) {
throw new Error(
'Required parameter rankSelectedAuthorRequest was null or undefined when calling impactStats.',
);
}
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/impact-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorImpactStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: rankSelectedAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
}
@@ -0,0 +1,24 @@
/**
* 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 AuthorCorrespondingCount {
/**
* The OpenAlex ID of the author.
*/
author_id: string;
/**
* The name of the author.
*/
display_name: string;
/**
* Number of the author\'s works on the topic where they are the corresponding author.
*/
value: number;
}
+2
View File
@@ -199,3 +199,5 @@ export * from './rankedAuthor';
export * from './keywordToAuthorRequest';
export * from './rankSelectedAuthorRequest';
export * from './authorYearlyWorks';
export * from './authorCorrespondingCount';
export * from './authorImpactStats';
@@ -20,4 +20,52 @@
</mat-card-content>
</mat-card>
}
@if (corresponding().length > 0) {
<mat-card>
<mat-card-content>
<h2 class="chart-title">Corresponding-Author-Werke</h2>
<div
echarts
[options]="barChartOption()"
[autoResize]="true"
class="chart-container"></div>
</mat-card-content>
</mat-card>
}
@if (impact().length > 0) {
<mat-card>
<mat-card-content>
<h2 class="chart-title">Ø Impact-Perzentil (0–1)</h2>
<div
echarts
[options]="avgPercentileOption()"
[autoResize]="true"
class="chart-container"></div>
</mat-card-content>
</mat-card>
<mat-card>
<mat-card-content>
<h2 class="chart-title">Top-10%-Works</h2>
<div
echarts
[options]="top10Option()"
[autoResize]="true"
class="chart-container"></div>
</mat-card-content>
</mat-card>
<mat-card>
<mat-card-content>
<h2 class="chart-title">Top-1%-Works</h2>
<div
echarts
[options]="top1Option()"
[autoResize]="true"
class="chart-container"></div>
</mat-card-content>
</mat-card>
}
</div>
@@ -16,3 +16,13 @@
height: 500px;
width: 100%;
}
.chart-title {
margin: 0 0 0.5rem;
font-size: 1rem;
font-weight: 500;
}
mat-card {
margin-bottom: 1rem;
}
@@ -4,7 +4,12 @@ import { MatCardModule } from '@angular/material/card';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective } from 'ngx-echarts';
import { AuthorYearlyWorks, RankingService } from '../../api';
import {
AuthorCorrespondingCount,
AuthorImpactStats,
AuthorYearlyWorks,
RankingService,
} from '../../api';
const LINE_COLORS = ['#1565c0', '#e6550d', '#2ca02c', '#9467bd'];
@@ -21,6 +26,8 @@ export class CompareAuthorsComponent implements OnInit {
readonly keywords = signal<string[]>([]);
readonly data = signal<AuthorYearlyWorks[]>([]);
readonly corresponding = signal<AuthorCorrespondingCount[]>([]);
readonly impact = signal<AuthorImpactStats[]>([]);
readonly loading = signal(false);
readonly chartOption = computed<EChartsOption>(() => {
@@ -67,6 +74,85 @@ export class CompareAuthorsComponent implements OnInit {
};
});
// bar chart: works where the author is the corresponding author, per selected author
readonly barChartOption = computed<EChartsOption>(() => {
const authors = this.corresponding();
if (authors.length === 0) {
return {};
}
const bars = authors.map((author, index) => ({
value: author.value,
itemStyle: { color: LINE_COLORS[index % LINE_COLORS.length] },
}));
return {
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: {
type: 'category',
data: authors.map((author) => author.display_name),
axisLabel: { interval: 0, rotate: 30 },
},
yAxis: { type: 'value', name: 'Corresponding Works' },
series: [
{ type: 'bar', data: bars },
] as unknown as EChartsOption['series'],
};
});
// citation-impact bar charts (one value each), per selected author
readonly avgPercentileOption = computed<EChartsOption>(() =>
this.buildImpactBar(
this.impact(),
(author) => author.avg_percentile,
'Ø Perzentil',
),
);
readonly top10Option = computed<EChartsOption>(() =>
this.buildImpactBar(
this.impact(),
(author) => author.top10_count,
'Top-10%-Works',
),
);
readonly top1Option = computed<EChartsOption>(() =>
this.buildImpactBar(
this.impact(),
(author) => author.top1_count,
'Top-1%-Works',
),
);
private buildImpactBar(
authors: AuthorImpactStats[],
valueFn: (author: AuthorImpactStats) => number,
yName: string,
): EChartsOption {
if (authors.length === 0) {
return {};
}
const bars = authors.map((author, index) => ({
value: valueFn(author),
itemStyle: { color: LINE_COLORS[index % LINE_COLORS.length] },
}));
return {
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: {
type: 'category',
data: authors.map((author) => author.display_name),
axisLabel: { interval: 0, rotate: 30 },
},
yAxis: { type: 'value', name: yName },
series: [
{ type: 'bar', data: bars },
] as unknown as EChartsOption['series'],
};
}
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') ?? '';
@@ -97,6 +183,30 @@ export class CompareAuthorsComponent implements OnInit {
this.loading.set(false);
},
});
this.rankingService
.correspondingAuthors({ author_ids: fullIds, keywords: keywords })
.subscribe({
next: (results) => {
this.corresponding.set(results);
},
error: (error) => {
console.error(error);
this.corresponding.set([]);
},
});
this.rankingService
.impactStats({ author_ids: fullIds, keywords: keywords })
.subscribe({
next: (results) => {
this.impact.set(results);
},
error: (error) => {
console.error(error);
this.impact.set([]);
},
});
}
private parseList(raw: string): string[] {