feat(publication-type-counts): implement API for counting works by publication type
This commit is contained in:
@@ -24,6 +24,7 @@ from .model import (
|
||||
FilterType,
|
||||
KeywordOperator,
|
||||
PublicationType,
|
||||
PublicationTypeCount,
|
||||
RankedAuthor,
|
||||
RankingWeights,
|
||||
SubfieldShare,
|
||||
@@ -788,6 +789,84 @@ def _build_query(
|
||||
}
|
||||
|
||||
|
||||
def _build_publication_type_counts_query(
|
||||
keywords: list[str],
|
||||
operator: KeywordOperator,
|
||||
author_ids: list[str],
|
||||
timespan: Timespan | None,
|
||||
config: MatchConfig = _KEYWORD_MATCH,
|
||||
) -> dict:
|
||||
"""Builds the query that counts matching works per publication type.
|
||||
|
||||
Mirrors _build_query's work filters but leaves out the publication_types
|
||||
filter itself, since it aggregates over all types instead of one score.
|
||||
"""
|
||||
work_filters = [
|
||||
_build_keyword_query(keywords, operator, config),
|
||||
_author_filter(author_ids),
|
||||
]
|
||||
if timespan is not None:
|
||||
work_filters.append(_timespan_filter(timespan))
|
||||
|
||||
return {
|
||||
"size": 0,
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": work_filters,
|
||||
},
|
||||
},
|
||||
"aggs": {
|
||||
"by_type": {
|
||||
"terms": {
|
||||
"field": "type",
|
||||
"size": len(PublicationType),
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
async def publication_type_counts_for_keywords(
|
||||
keywords: list[str],
|
||||
operator: KeywordOperator,
|
||||
institution_id: str,
|
||||
career_stages: list[CareerStage],
|
||||
timespan: Timespan | None,
|
||||
filter_type: FilterType = FilterType.KEYWORD,
|
||||
) -> list[PublicationTypeCount]:
|
||||
"""Counts the university's matching works per publication type, largest first."""
|
||||
author_ids = await _get_author_ids_from_institution(institution_id)
|
||||
|
||||
if not author_ids:
|
||||
return []
|
||||
|
||||
if career_stages:
|
||||
author_ids = await _filter_author_ids_by_career_stage(author_ids, career_stages)
|
||||
|
||||
query_body = _build_publication_type_counts_query(
|
||||
keywords, operator, author_ids, timespan, _match_config(filter_type),
|
||||
)
|
||||
|
||||
response: dict[str, Any] = await elasticsearch.search(
|
||||
index=config.settings.openalex_works_search_index,
|
||||
body=query_body,
|
||||
cluster=ESCluster.NES,
|
||||
)
|
||||
|
||||
type_buckets = response.get("aggregations", {}).get("by_type", {}).get("buckets", [])
|
||||
|
||||
counts = []
|
||||
for bucket in type_buckets:
|
||||
try:
|
||||
publication_type = PublicationType(bucket["key"])
|
||||
except ValueError:
|
||||
continue
|
||||
counts.append(PublicationTypeCount(type=publication_type, count=bucket["doc_count"]))
|
||||
|
||||
counts.sort(key=lambda c: c.count, reverse=True)
|
||||
return counts
|
||||
|
||||
|
||||
def _display_name_from_bucket(author_bucket: dict) -> str:
|
||||
"""Reads the authors display name out of the name sub-aggregation."""
|
||||
name_buckets = author_bucket.get("author_name", {}).get("buckets", [])
|
||||
|
||||
@@ -195,6 +195,42 @@ class AuthorMetricsRequest(BaseModel):
|
||||
)
|
||||
|
||||
|
||||
class PublicationTypeCountsRequest(BaseModel):
|
||||
keywords: list[str] = Field(
|
||||
min_length=1,
|
||||
description="One or more keywords to match works against.",
|
||||
)
|
||||
operator: KeywordOperator = Field(
|
||||
default=KeywordOperator.AND,
|
||||
description="How to combine the keywords: 'and' or 'or'. Defaults to 'and'.",
|
||||
)
|
||||
filter_type: FilterType = Field(
|
||||
default=FilterType.KEYWORD,
|
||||
description="What the 'keywords' values match against: 'keyword' (OpenAlex "
|
||||
"keyword display names) or 'topic' (OpenAlex topic display names). Defaults to 'keyword'.",
|
||||
)
|
||||
career_stages: list[CareerStage] = Field(
|
||||
default_factory=list,
|
||||
description="Optional filter: only count works of authors in one of these career stages. Empty = no filter.",
|
||||
)
|
||||
timespan: Timespan | None = Field(
|
||||
default=None,
|
||||
description="Optional filter: only count works whose publication_year is within [from, to].",
|
||||
)
|
||||
|
||||
@field_validator("operator", "filter_type", mode="before")
|
||||
@classmethod
|
||||
def operator_case_insensitive(cls, value):
|
||||
if isinstance(value, str):
|
||||
return value.lower()
|
||||
return value
|
||||
|
||||
|
||||
class PublicationTypeCount(BaseModel):
|
||||
type: PublicationType = Field(description="The OpenAlex work type.")
|
||||
count: int = Field(description="Number of matching works of this type.")
|
||||
|
||||
|
||||
class AuthorTopicStats(BaseModel):
|
||||
"""Section 1: combined stats over an author's works that match the topic filter."""
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ from .model import (
|
||||
AuthorTopicProfile,
|
||||
AuthorTopicStats,
|
||||
KeywordToAuthorRequest,
|
||||
PublicationTypeCount,
|
||||
PublicationTypeCountsRequest,
|
||||
RankedAuthor,
|
||||
SelectedAuthorsRequest,
|
||||
)
|
||||
@@ -68,6 +70,40 @@ async def rank_author(
|
||||
filter_type=request.filter_type,
|
||||
)
|
||||
|
||||
# Publication-type facet counts for the "Art der Work" filter
|
||||
@router.post("/publication-type-counts", response_model=list[PublicationTypeCount])
|
||||
async def publication_type_counts(
|
||||
request: PublicationTypeCountsRequest,
|
||||
access_token_metadata: Annotated[
|
||||
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||
],
|
||||
):
|
||||
institution_id = access_token_metadata.effective_institution_id
|
||||
if not institution_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="No OpenAlex institution is assigned to the current organization.",
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"publication-type-counts keywords=%s operator=%s filter_type=%s institution_id=%s "
|
||||
"career_stages=%s timespan=%s",
|
||||
request.keywords,
|
||||
request.operator,
|
||||
request.filter_type,
|
||||
institution_id,
|
||||
request.career_stages,
|
||||
request.timespan,
|
||||
)
|
||||
return await logic.publication_type_counts_for_keywords(
|
||||
keywords=request.keywords,
|
||||
operator=request.operator,
|
||||
institution_id=institution_id,
|
||||
career_stages=request.career_stages,
|
||||
timespan=request.timespan,
|
||||
filter_type=request.filter_type,
|
||||
)
|
||||
|
||||
# Compare authors table 1 (topic stats)
|
||||
@router.post("/topic-stats", response_model=list[AuthorTopicStats])
|
||||
async def topic_stats(request: SelectedAuthorsRequest):
|
||||
|
||||
@@ -39,6 +39,10 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { KeywordToAuthorRequest } from '../model/keywordToAuthorRequest';
|
||||
// @ts-ignore
|
||||
import { PublicationTypeCount } from '../model/publicationTypeCount';
|
||||
// @ts-ignore
|
||||
import { PublicationTypeCountsRequest } from '../model/publicationTypeCountsRequest';
|
||||
// @ts-ignore
|
||||
import { RankedAuthor } from '../model/rankedAuthor';
|
||||
// @ts-ignore
|
||||
import { SelectedAuthorsRequest } from '../model/selectedAuthorsRequest';
|
||||
@@ -191,6 +195,136 @@ export class RankingService extends BaseService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publication Type Counts
|
||||
* @endpoint post /api/rank/publication-type-counts
|
||||
* @param publicationTypeCountsRequest
|
||||
* @param secureFgpAcc
|
||||
* @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 publicationTypeCountsApiRankPublicationTypeCountsPost(
|
||||
publicationTypeCountsRequest: PublicationTypeCountsRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Array<PublicationTypeCount>>;
|
||||
public publicationTypeCountsApiRankPublicationTypeCountsPost(
|
||||
publicationTypeCountsRequest: PublicationTypeCountsRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Array<PublicationTypeCount>>>;
|
||||
public publicationTypeCountsApiRankPublicationTypeCountsPost(
|
||||
publicationTypeCountsRequest: PublicationTypeCountsRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Array<PublicationTypeCount>>>;
|
||||
public publicationTypeCountsApiRankPublicationTypeCountsPost(
|
||||
publicationTypeCountsRequest: PublicationTypeCountsRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (
|
||||
publicationTypeCountsRequest === null ||
|
||||
publicationTypeCountsRequest === undefined
|
||||
) {
|
||||
throw new Error(
|
||||
'Required parameter publicationTypeCountsRequest was null or undefined when calling publicationTypeCountsApiRankPublicationTypeCountsPost.',
|
||||
);
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
|
||||
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/publication-type-counts`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Array<PublicationTypeCount>>(
|
||||
'post',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: publicationTypeCountsRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rank Author
|
||||
* @endpoint post /api/rank/rank-author
|
||||
|
||||
@@ -202,6 +202,8 @@ export * from './projectsSortBy';
|
||||
export * from './publicationDetailByFunder';
|
||||
export * from './publicationIdsByAuthorPosition';
|
||||
export * from './publicationType';
|
||||
export * from './publicationTypeCount';
|
||||
export * from './publicationTypeCountsRequest';
|
||||
export * from './publicationsByAuthorResponse';
|
||||
export * from './rankedAuthor';
|
||||
export * from './rankingResponse';
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
import { PublicationType } from './publicationType';
|
||||
|
||||
export interface PublicationTypeCount {
|
||||
/**
|
||||
* The OpenAlex work type.
|
||||
*/
|
||||
type: PublicationType;
|
||||
/**
|
||||
* Number of matching works of this type.
|
||||
*/
|
||||
count: number;
|
||||
}
|
||||
export namespace PublicationTypeCount {}
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
import { Timespan } from './timespan';
|
||||
import { FilterType } from './filterType';
|
||||
import { CareerStage } from './careerStage';
|
||||
import { KeywordOperator } from './keywordOperator';
|
||||
|
||||
export interface PublicationTypeCountsRequest {
|
||||
/**
|
||||
* One or more keywords to match works against.
|
||||
*/
|
||||
keywords: Array<string>;
|
||||
/**
|
||||
* How to combine the keywords: \'and\' or \'or\'. Defaults to \'and\'.
|
||||
*/
|
||||
operator?: KeywordOperator;
|
||||
/**
|
||||
* What the \'keywords\' values match against: \'keyword\' (OpenAlex keyword display names) or \'topic\' (OpenAlex topic display names). Defaults to \'keyword\'.
|
||||
*/
|
||||
filter_type?: FilterType;
|
||||
/**
|
||||
* Optional filter: only count works of authors in one of these career stages. Empty = no filter.
|
||||
*/
|
||||
career_stages?: Array<CareerStage>;
|
||||
timespan?: Timespan | null;
|
||||
}
|
||||
export namespace PublicationTypeCountsRequest {}
|
||||
+4
-2
@@ -104,8 +104,10 @@
|
||||
}
|
||||
</div>
|
||||
|
||||
@for (pt of filteredPubTypes(); track pt) {
|
||||
<mat-option [value]="pt">{{ pt }}</mat-option>
|
||||
@for (pt of filteredPubTypes(); track pt.type) {
|
||||
<mat-option [value]="pt.type"
|
||||
>{{ pt.type }} ({{ pt.count }})</mat-option
|
||||
>
|
||||
}
|
||||
</mat-select>
|
||||
</mat-form-field>
|
||||
|
||||
+37
-31
@@ -25,6 +25,8 @@ import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slide
|
||||
import {
|
||||
CareerStage,
|
||||
KeywordToAuthorRequest,
|
||||
PublicationTypeCount,
|
||||
PublicationTypeCountsRequest,
|
||||
RankedAuthor,
|
||||
RankingService,
|
||||
} from '../../../../api';
|
||||
@@ -177,33 +179,8 @@ export class KeywordsToPersonsResultsComponent implements OnInit {
|
||||
];
|
||||
readonly companyStatus = signal<'all' | 'active' | 'deleted'>('all');
|
||||
|
||||
// publication types
|
||||
readonly ALL_PUBLICATION_TYPES = [
|
||||
'article',
|
||||
'other',
|
||||
'dataset',
|
||||
'book-chapter',
|
||||
'book',
|
||||
'dissertation',
|
||||
'preprint',
|
||||
'paratext',
|
||||
'libguides',
|
||||
'review',
|
||||
'letter',
|
||||
'reference-entry',
|
||||
'editorial',
|
||||
'peer-review',
|
||||
'report',
|
||||
'standard',
|
||||
'erratum',
|
||||
'retraction',
|
||||
'supplementary-materials',
|
||||
'book-section',
|
||||
'database',
|
||||
'software',
|
||||
'report-component',
|
||||
'grant',
|
||||
];
|
||||
// publication types: counted from the index (count-by), largest first
|
||||
readonly publicationTypeCounts = signal<PublicationTypeCount[]>([]);
|
||||
|
||||
readonly pubTypeSearchTerm = signal('');
|
||||
|
||||
@@ -216,10 +193,9 @@ export class KeywordsToPersonsResultsComponent implements OnInit {
|
||||
|
||||
readonly filteredPubTypes = computed(() => {
|
||||
const term = this.pubTypeSearchTerm().toLowerCase();
|
||||
if (!term) return this.ALL_PUBLICATION_TYPES;
|
||||
return this.ALL_PUBLICATION_TYPES.filter((pt) =>
|
||||
pt.toLowerCase().includes(term),
|
||||
);
|
||||
const counts = this.publicationTypeCounts();
|
||||
if (!term) return counts;
|
||||
return counts.filter((pt) => pt.type.toLowerCase().includes(term));
|
||||
});
|
||||
|
||||
onPubTypesChange(selected: string[]) {
|
||||
@@ -256,6 +232,7 @@ export class KeywordsToPersonsResultsComponent implements OnInit {
|
||||
replaceUrl: true,
|
||||
});
|
||||
this.loadAuthors();
|
||||
this.loadPublicationTypeCounts();
|
||||
}
|
||||
|
||||
readonly CAREER_STAGE_OPTIONS = [
|
||||
@@ -317,6 +294,8 @@ export class KeywordsToPersonsResultsComponent implements OnInit {
|
||||
if (operator === 'and' || operator === 'or') {
|
||||
this.keywordOperator.set(operator);
|
||||
}
|
||||
|
||||
this.loadPublicationTypeCounts();
|
||||
}
|
||||
|
||||
// reads a year query param, clamped to the valid range; falls back on invalid input
|
||||
@@ -403,6 +382,7 @@ export class KeywordsToPersonsResultsComponent implements OnInit {
|
||||
}
|
||||
this.writeTimespanToUrl();
|
||||
this.loadAuthors();
|
||||
this.loadPublicationTypeCounts();
|
||||
}
|
||||
|
||||
// the backend returns the full OpenAlex url; the profile route needs only the id
|
||||
@@ -497,4 +477,30 @@ export class KeywordsToPersonsResultsComponent implements OnInit {
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// counts, by publication type, of the works matching the current keyword/
|
||||
// career-stage/timespan filters — drives the "Art der Work" filter options
|
||||
private loadPublicationTypeCounts(): void {
|
||||
const request: PublicationTypeCountsRequest = {
|
||||
keywords: this.state.topicsList(),
|
||||
operator: this.keywordOperator(),
|
||||
filter_type: 'topic',
|
||||
career_stages:
|
||||
this.careerStages().length > 0 ? this.careerStages() : undefined,
|
||||
timespan: {
|
||||
from: this.timespanFrom(),
|
||||
to: this.timespanTo(),
|
||||
},
|
||||
};
|
||||
|
||||
this.rankingService
|
||||
.publicationTypeCountsApiRankPublicationTypeCountsPost(request)
|
||||
.subscribe({
|
||||
next: (counts) => this.publicationTypeCounts.set(counts),
|
||||
error: (error) => {
|
||||
console.error(error);
|
||||
this.publicationTypeCounts.set([]);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user