remove unused "things"

This commit is contained in:
Steven Tischer
2026-07-19 17:03:55 +02:00
parent 504809e473
commit 8d4fb333a2
8 changed files with 0 additions and 880 deletions
-353
View File
@@ -14,10 +14,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 (
AuthorCorrespondingCount,
AuthorImpactStats,
AuthorTopicStats,
AuthorYearlyWorks,
CareerStage,
CompanyStatusFilter,
KeywordOperator,
@@ -25,7 +22,6 @@ from .model import (
RankedAuthor,
RankingWeights,
Timespan,
YearCount,
)
logger = logging.getLogger(__name__)
@@ -118,355 +114,6 @@ def _author_filter(author_ids: List[str]) -> dict:
}
def _yearly_works_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> dict:
"""Builds a query that returns, per selected author, the year distribution of their topic works."""
filters = [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
]
if publication_types:
filters.append(_publication_type_filter(publication_types))
if timespan:
filters.append(_timespan_filter(timespan))
return {
"size": 0,
"query": {
"bool": {
"filter": filters,
},
},
"aggs": {
"authors": {
"nested": {"path": "authorships"},
"aggs": {
"selected": {
# keep only the authorships of the selected authors
"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": {
"publication_years": {
"terms": {
"field": "publication_year",
"size": 200,
"order": {"_key": "desc"},
},
},
},
},
},
},
},
},
},
},
},
}
async def yearly_works_for_authors(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> List[AuthorYearlyWorks]:
"""For each selected author, returns the per-year count of their works on the topic.
Only years with at least one work are returned, newest year first.
"""
if not author_ids:
return []
response: dict[str, Any] = await elasticsearch.search(
index=config.settings.openalex_works_search_index,
body=_yearly_works_query(author_ids, keywords, operator, publication_types, timespan),
cluster=ESCluster.NES,
)
author_buckets = (
response.get("aggregations", {})
.get("authors", {})
.get("selected", {})
.get("by_author", {})
.get("buckets", [])
)
results = []
for author_bucket in author_buckets:
year_buckets = (
author_bucket.get("to_work", {})
.get("publication_years", {})
.get("buckets", [])
)
years = []
for year_bucket in year_buckets:
years.append(
YearCount(
year=int(year_bucket.get("key")),
count=year_bucket.get("doc_count", 0),
)
)
results.append(
AuthorYearlyWorks(
author_id=author_bucket.get("key", ""),
display_name=_display_name_from_bucket(author_bucket),
years=years,
)
)
return results
def _corresponding_query(
author_ids: List[str],
keywords: List[str],
operator: KeywordOperator,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> dict:
"""Builds a query that counts, per selected author, the topic works where they are the corresponding author."""
filters = [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
]
if publication_types:
filters.append(_publication_type_filter(publication_types))
if timespan:
filters.append(_timespan_filter(timespan))
return {
"size": 0,
"query": {
"bool": {
"filter": filters,
},
},
"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,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> 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, publication_types, timespan),
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,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> 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.
"""
filters = [
_build_keyword_query(keywords, operator),
_author_filter(author_ids),
]
if publication_types:
filters.append(_publication_type_filter(publication_types))
if timespan:
filters.append(_timespan_filter(timespan))
return {
"size": 0,
"query": {
"bool": {
"filter": filters,
},
},
"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,
publication_types: List[PublicationType],
timespan: Optional[Timespan],
) -> 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, publication_types, timespan),
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 _topic_stats_query(
author_ids: List[str],
keywords: List[str],
-35
View File
@@ -167,41 +167,6 @@ class SelectedAuthorsRequest(BaseModel):
return value
class YearCount(BaseModel):
year: int = Field(description="Publication year.")
count: int = Field(description="Number of the author's works on the topic in that year.")
class AuthorYearlyWorks(BaseModel):
author_id: str = Field(description="The OpenAlex ID of the author.")
display_name: str = Field(description="The name of the author.")
years: List[YearCount] = Field(
description="Per-year count of the author's works on the topic, newest year first.",
)
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 AuthorTopicStats(BaseModel):
"""Section 1: combined stats over an author's works that match the topic filter."""
-54
View File
@@ -6,10 +6,7 @@ from fastapi import APIRouter
from inse.tags import Tags
from . import logic
from .model import (
AuthorCorrespondingCount,
AuthorImpactStats,
AuthorTopicStats,
AuthorYearlyWorks,
KeywordToAuthorRequest,
RankedAuthor,
SelectedAuthorsRequest,
@@ -64,54 +61,3 @@ async def topic_stats(request: SelectedAuthorsRequest):
request.publication_types,
request.timespan,
)
@router.post("/rank-selected-author", response_model=List[AuthorYearlyWorks])
async def rank_selected_author(request: SelectedAuthorsRequest):
logger.info(
"rank-selected-author author_ids=%s keywords=%s operator=%s",
request.author_ids,
request.keywords,
request.operator,
)
return await logic.yearly_works_for_authors(
request.author_ids,
request.keywords,
request.operator,
request.publication_types,
request.timespan,
)
@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,
request.publication_types,
request.timespan,
)
@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,
request.publication_types,
request.timespan,
)
-355
View File
@@ -29,12 +29,6 @@ import { RankedAuthor } from '../model/rankedAuthor';
// @ts-ignore
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 { AuthorTopicStats } from '../model/authorTopicStats';
// @ts-ignore
@@ -171,355 +165,6 @@ export class RankingService extends BaseService {
);
}
/**
* Returns, per selected author, the per-year count of their works on the topic.
* @endpoint post /api/rank/rank-selected-author
* @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 rankSelectedAuthor(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorYearlyWorks>>;
public rankSelectedAuthor(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorYearlyWorks>>>;
public rankSelectedAuthor(
rankSelectedAuthorRequest: RankSelectedAuthorRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorYearlyWorks>>>;
public rankSelectedAuthor(
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 rankSelectedAuthor.',
);
}
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;
// to determine the Content-Type header
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/rank-selected-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorYearlyWorks>>(
'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: 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,
},
);
}
/**
* Section 1: combined stats over each selected author\'s topic-filtered works.
* @endpoint post /api/rank/topic-stats
@@ -1,24 +0,0 @@
/**
* 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;
}
@@ -1,32 +0,0 @@
/**
* 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 AuthorImpactStats {
/**
* The OpenAlex ID of the author.
*/
author_id: string;
/**
* The name of the author.
*/
display_name: string;
/**
* Average field-normalized citation percentile (0-1) over the author\'s topic works.
*/
avg_percentile: number;
/**
* Number of the author\'s topic works in the top 1% most-cited.
*/
top1_count: number;
/**
* Number of the author\'s topic works in the top 10% most-cited.
*/
top10_count: number;
}
@@ -1,24 +0,0 @@
/**
* 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 AuthorYearlyWorks {
/**
* The OpenAlex ID of the author.
*/
author_id: string;
/**
* The name of the author.
*/
display_name: string;
/**
* Per-year count of the author\'s works on the topic, newest year first.
*/
years: Array<{ year: number; count: number }>;
}
-3
View File
@@ -220,7 +220,4 @@ export * from './rankingWeights';
export * from './rankedAuthor';
export * from './keywordToAuthorRequest';
export * from './rankSelectedAuthorRequest';
export * from './authorYearlyWorks';
export * from './authorCorrespondingCount';
export * from './authorImpactStats';
export * from './authorTopicStats';