Compare commits

...
Author SHA1 Message Date
genja 66e56fda29 removed slashes from Elastic Urls
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-16 14:34:48 +02:00
genja 7f387ee45d regenerated model 2026-06-16 14:33:21 +02:00
genja 9269af4c5d replaced institution autocompletion logic with wildcards 2026-06-16 11:41:59 +02:00
genja 48aad9f164 Merge branch 'dev' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/user-accounts 2026-06-16 08:02:56 +02:00
tischer 27987080ea Merge pull request 'fix 404 on root : redirect from root path to dashboard' (#148) from fix/404_root_page into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #148
2026-06-16 07:30:46 +02:00
Steven Tischer c92bb39683 redirect from root path to dashboard
LocationBasedServices/smartguide/pipeline/head This commit looks good
LocationBasedServices/smartguide/pipeline/pr-dev Build started...
2026-06-16 07:03:25 +02:00
genja 1a174168f8 added uni ranking prototype to dashboard 2026-06-16 01:17:02 +02:00
26 changed files with 676 additions and 59 deletions
+2 -2
View File
@@ -1,7 +1,7 @@
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic/
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
@@ -99,49 +99,36 @@ class InstitutionsSearchClient:
stripped = query_text.strip()
must.append({
"bool": {
"should": [
# Fast prefix matching via search_as_you_type shingles
{
"multi_match": {
"query": stripped,
"type": "bool_prefix",
"fields": [
"display_name.search",
"display_name.search._2gram",
"display_name.search._3gram",
"display_name_alternatives.search",
"display_name_alternatives.search._2gram",
],
"boost": 2,
"bool": {
"should": [
{
"wildcard": {
"display_name.keyword": {
"value": f"*{stripped}*",
"boost": 2
}
},
# Exact acronym match — high confidence signal
{
"term": {
"display_name_acronyms.keyword": {
"value": stripped.upper(),
"boost": 10,
}
}
},
{
"wildcard": {
"display_name_alternatives.keyword": {
"value": f"*{stripped}*",
"boost": 2
}
},
# Fuzzy fallback for typos (only worth it for longer input)
*(
[{
"match": {
"display_name": {
"query": stripped,
"fuzziness": "AUTO",
"boost": 1,
}
}
}]
if len(stripped) >= 4 else []
),
],
"minimum_should_match": 1,
}
})
}
},
{
"wildcard": {
"display_name_acronyms.keyword": {
"value": f"*{stripped.upper()}*",
"boost": 10
}
}
}
],
"minimum_should_match": 1
}
})
filter_queries = []
+2 -2
View File
@@ -17,7 +17,7 @@ from inse.works.service import router as works_service_router
from inse.persons.service import router as persons_service_router
from inse.funders.service import router as funders_service_router
from inse.projects.router import router as projects_router
from inse.university_ranking.router import router as university_ranking_router
# caching
from inse.middleware.etag_cache import ETagCacheMiddleware
from inse.exceptions import NotFoundException
@@ -46,7 +46,7 @@ app.include_router(persons_service_router)
app.include_router(funders_service_router)
app.include_router(service_router)
app.include_router(account_router)
app.include_router(university_ranking_router)
app.include_router(projects_router)
app.add_middleware(
@@ -33,7 +33,7 @@ class Institution(BaseModel):
"""
A university, research organization, or other affiliation
""" # noqa: E501
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this institution.")
id: Optional[StrictStr] = Field(default=None, description="The OpenAlex ID for this institution.", json_schema_extra={"examples": ["https://openalex.org/I27837315"]})
ror: Optional[StrictStr] = Field(default=None, description="The ROR ID for this institution. This is the Canonical External ID for institutions.")
display_name: Optional[StrictStr] = Field(default=None, description="The primary name of the institution.")
country_code: Optional[StrictStr] = Field(default=None, description="ISO two-letter country code where this institution is located.")
@@ -55,20 +55,13 @@ class Institution(BaseModel):
updated_date: Optional[datetime] = Field(default=None, description="When this institution was last updated (ISO 8601 datetime).")
__properties: ClassVar[List[str]] = ["id", "ror", "display_name", "country_code", "type", "homepage_url", "image_url", "image_thumbnail_url", "display_name_acronyms", "display_name_alternatives", "works_count", "cited_by_count", "summary_stats", "geo", "lineage", "ids", "counts_by_year", "works_api_url", "created_date", "updated_date"]
@field_validator('created_date', mode='before')
@classmethod
def normalize_created_date(cls, v: Any) -> Any:
if isinstance(v, str) and len(v) > 10:
return v[:10]
return v
@field_validator('type')
def type_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in set(['education','funder', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']):
if value not in set(['education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other']):
raise ValueError("must be one of enum values ('education', 'healthcare', 'company', 'archive', 'nonprofit', 'government', 'facility', 'other')")
return value
@@ -161,3 +154,5 @@ class Institution(BaseModel):
"updated_date": obj.get("updated_date")
})
return _obj
@@ -0,0 +1,113 @@
import logging
from typing import List, Dict, Any
from .model import UniversityTopicData, YearlyData, UniversityRanking, ResearchTopic, DashboardMetric, RankingResponse
from inse.integrations import elasticsearch
logger = logging.getLogger(__name__)
START_YEAR = 2015
END_YEAR = 2026
async def get_ranking_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
"""
Fetches real data from Elasticsearch and computes metrics for the dashboard.
"""
query = {
"bool": {
"must": [
{
"match_phrase": {
"topics.display_name": topic
}
},
{
"term": {
"geo.country_code": "DE"
}
}
]
}
}
# Fetch top institutions for the topic by works_count
res = elasticsearch.search(
index="openalex-institutions",
query=query,
size=10,
sort=[{"works_count": "desc"}],
cluster="nes"
)
hits = res.get("hits", {}).get("hits", [])
timeseries: List[UniversityTopicData] = []
for hit in hits:
source = hit["_source"]
# Map the counts_by_year from ES to our model
# We ensure every year from START_YEAR to END_YEAR is present, defaulting to 0
es_counts = {c["year"]: c for c in source.get("counts_by_year", [])}
yearly_data = []
for year in range(START_YEAR, END_YEAR + 1):
count_item = es_counts.get(year, {})
yearly_data.append(YearlyData(
year=year,
publications=count_item.get("works_count", 0),
citations=count_item.get("cited_by_count", 0)
))
timeseries.append(UniversityTopicData(
university=source.get("display_name", "Unknown"),
topic=topic,
yearly_data=yearly_data
))
rankings = _compute_rankings(timeseries, metric)
return RankingResponse(timeseries=timeseries, rankings=rankings)
def _compute_rankings(data: List[UniversityTopicData], metric: DashboardMetric) -> List[UniversityRanking]:
"""Computes ranking metrics based on the timeseries data."""
latest_year = END_YEAR
five_years_ago = latest_year - 5
three_years_ago = latest_year - 3
processed: List[Dict[str, Any]] = []
for item in data:
latest = next((d for d in item.yearly_data if d.year == latest_year), YearlyData(year=latest_year, publications=0, citations=0))
prev = next((d for d in item.yearly_data if d.year == latest_year - 1), YearlyData(year=latest_year-1, publications=0, citations=0))
start_range = next((d for d in item.yearly_data if d.year == five_years_ago), YearlyData(year=five_years_ago, publications=0, citations=0))
mover_range = next((d for d in item.yearly_data if d.year == three_years_ago), YearlyData(year=three_years_ago, publications=0, citations=0))
curr_val = getattr(latest, metric) or 0
prev_val = getattr(prev, metric) or 0
old_val = getattr(start_range, metric) or 0
mover_old_val = getattr(mover_range, metric) or 0
growth_rate = ((curr_val - old_val) / old_val * 100) if old_val > 0 else 0
recent_growth = ((curr_val - mover_old_val) / mover_old_val * 100) if mover_old_val > 0 else 0
processed.append({
"university": item.university,
"publications": latest.publications,
"citations": latest.citations,
"growth_rate": growth_rate,
"trend": 'up' if curr_val > prev_val else ('down' if curr_val < prev_val else 'stable'),
"recent_growth": recent_growth,
"sort_val": curr_val
})
processed.sort(key=lambda x: x["sort_val"], reverse=True)
# Top movers: top 2 by recent growth
growth_sorted = sorted([p["recent_growth"] for p in processed], reverse=True)
threshold = growth_sorted[1] if len(growth_sorted) > 1 else 0
return [
UniversityRanking(
rank=i + 1,
is_top_mover=p["recent_growth"] >= threshold and p["recent_growth"] > 0,
**{k: v for k, v in p.items() if k != "sort_val" and k != "recent_growth"}
)
for i, p in enumerate(processed)
]
@@ -0,0 +1,30 @@
from pydantic import BaseModel
from typing import List, Literal
ResearchTopic = Literal['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology']
DashboardMetric = Literal['publications', 'citations']
class YearlyData(BaseModel):
year: int
publications: int
citations: int
class UniversityTopicData(BaseModel):
university: str
topic: ResearchTopic
yearly_data: List[YearlyData]
class UniversityRanking(BaseModel):
rank: int
university: str
publications: int
citations: int
growth_rate: float
trend: Literal['up', 'down', 'stable']
is_top_mover: bool
class RankingResponse(BaseModel):
# Raw timeseries data for the ECharts line race
timeseries: List[UniversityTopicData]
# Computed metrics for the ranking table
rankings: List[UniversityRanking]
@@ -0,0 +1,23 @@
from fastapi import APIRouter, Query
from . import service
from .model import RankingResponse, ResearchTopic, DashboardMetric
from inse.tags import Tags
router = APIRouter(
prefix="/api/inse-service/university-rankings",
tags=[Tags.INSTITUTIONS]
)
@router.get(
"",
response_model=RankingResponse,
summary="Returns data for the University Ranking Dashboard."
)
async def get_rankings(
topic: ResearchTopic = Query(
...,
description="Research topic (e.g., 'Artificial Intelligence')"
),
metric: DashboardMetric = Query("publications", description="Metric to rank by")
):
return await service.get_university_dashboard_data(topic, metric)
@@ -0,0 +1,6 @@
from . import logic
from .model import RankingResponse, ResearchTopic, DashboardMetric
async def get_university_dashboard_data(topic: ResearchTopic, metric: DashboardMetric) -> RankingResponse:
"""Orchestrates data retrieval and computation for the dashboard."""
return await logic.get_ranking_data(topic, metric)
@@ -85,6 +85,7 @@ model/programmeNested.ts
model/publicationDetailByFunder.ts
model/publicationIdsByAuthorPosition.ts
model/publicationsByAuthorResponse.ts
model/rankingResponse.ts
model/score.ts
model/topic.ts
model/topicCount.ts
@@ -95,6 +96,8 @@ model/topicSubfield.ts
model/topicsByTime.ts
model/topicsByYear.ts
model/topicsListResponse.ts
model/universityRanking.ts
model/universityTopicData.ts
model/user.ts
model/validationError.ts
model/validationErrorLocInner.ts
@@ -118,6 +121,7 @@ model/workTopicInformation.ts
model/workTopicSubfield.ts
model/worksFilterProperties.ts
model/worksListResponse.ts
model/yearlyData.ts
param.ts
provide-api.ts
variables.ts
@@ -24,6 +24,8 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
import { Institution } from '../model/institution';
// @ts-ignore
import { InstitutionsListResponse } from '../model/institutionsListResponse';
// @ts-ignore
import { RankingResponse } from '../model/rankingResponse';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
@@ -166,6 +168,69 @@ export class InstitutionsService extends BaseService {
);
}
/**
* Returns data for the University Ranking Dashboard.
* @endpoint get /api/inse-service/university-rankings
* @param topic Research topic (e.g., \&#39;Artificial Intelligence\&#39;)
* @param metric Metric to rank by
* @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 getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<RankingResponse>;
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<RankingResponse>>;
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<RankingResponse>>;
public getRankingsApiInseServiceUniversityRankingsGet(topic: 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology', metric?: 'publications' | 'citations', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (topic === null || topic === undefined) {
throw new Error('Required parameter topic was null or undefined when calling getRankingsApiInseServiceUniversityRankingsGet.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>topic, 'topic');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>metric, 'metric');
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;
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/inse-service/university-rankings`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<RankingResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/**
* Returns a list of OpenAlex institutions.
* @endpoint get /api/inse-service/institutions
+4
View File
@@ -65,6 +65,7 @@ export * from './programmeNested';
export * from './publicationDetailByFunder';
export * from './publicationIdsByAuthorPosition';
export * from './publicationsByAuthorResponse';
export * from './rankingResponse';
export * from './score';
export * from './topic';
export * from './topicCount';
@@ -75,6 +76,8 @@ export * from './topicSubfield';
export * from './topicsByTime';
export * from './topicsByYear';
export * from './topicsListResponse';
export * from './universityRanking';
export * from './universityTopicData';
export * from './user';
export * from './validationError';
export * from './validationErrorLocInner';
@@ -98,3 +101,4 @@ export * from './workTopicInformation';
export * from './workTopicSubfield';
export * from './worksFilterProperties';
export * from './worksListResponse';
export * from './yearlyData';
@@ -0,0 +1,18 @@
/**
* 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 { UniversityRanking } from './universityRanking';
import { UniversityTopicData } from './universityTopicData';
export interface RankingResponse {
timeseries: Array<UniversityTopicData>;
rankings: Array<UniversityRanking>;
}
@@ -0,0 +1,30 @@
/**
* 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 UniversityRanking {
rank: number;
university: string;
publications: number;
citations: number;
growth_rate: number;
trend: UniversityRanking.TrendEnum;
is_top_mover: boolean;
}
export namespace UniversityRanking {
export const TrendEnum = {
up: 'up',
down: 'down',
stable: 'stable'
} as const;
export type TrendEnum = typeof TrendEnum[keyof typeof TrendEnum];
}
@@ -0,0 +1,28 @@
/**
* 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 { YearlyData } from './yearlyData';
export interface UniversityTopicData {
university: string;
topic: UniversityTopicData.TopicEnum;
yearly_data: Array<YearlyData>;
}
export namespace UniversityTopicData {
export const TopicEnum = {
Artificial_Intelligence: 'Artificial Intelligence',
Quantum_Computing: 'Quantum Computing',
Renewable_Energy: 'Renewable Energy',
Biotechnology: 'Biotechnology'
} as const;
export type TopicEnum = typeof TopicEnum[keyof typeof TopicEnum];
}
+17
View File
@@ -0,0 +1,17 @@
/**
* 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 YearlyData {
year: number;
publications: number;
citations: number;
}
+5
View File
@@ -9,6 +9,11 @@ import { bundProjectsResolver } from './resolvers/bund-projects.resolver';
import { euProjectsResolver } from './resolvers/eu-projects.resolver';
import { dfgProjectsResolver } from './resolvers/dfg-projects.resolver';
export const routes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'dashboard',
},
{
path: 'login',
loadComponent: () =>
@@ -0,0 +1,28 @@
<div class="dashboard-wrapper">
<header class="dashboard-header">
<h2>University Performance Dashboard</h2>
<div class="controls">
<select (change)="onTopicChange($any($event.target).value)">
@for (t of topics; track t){
<option [value]="t">{{t}}</option>
}
</select>
<div class="toggle-group">
<button [class.active]="metric === 'publications'" (click)="setMetric('publications')">Publications</button>
<button [class.active]="metric === 'citations'" (click)="setMetric('citations')">Citations</button>
</div>
</div>
</header>
<div class="content-grid">
<section class="chart-section">
<app-university-line-chart [data]="rawDataSource" [metric]="metric"></app-university-line-chart>
</section>
<aside class="table-section">
<app-university-ranking-table [rankings]="computedRankings" [loading]="isLoading"></app-university-ranking-table>
</aside>
</div>
</div>
@@ -0,0 +1,73 @@
// src/app/modules/university-ranking/dashboard.component.scss
.dashboard-wrapper {
padding: 2rem;
font-family: 'Inter', sans-serif;
color: #333;
.dashboard-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
border-bottom: 1px solid #eee;
padding-bottom: 1rem;
}
.content-grid {
display: grid;
grid-template-columns: 2fr 1fr;
gap: 2rem;
@media (max-width: 1024px) {
grid-template-columns: 1fr;
}
}
.controls {
display: flex;
gap: 1rem;
select {
padding: 0.5rem;
border-radius: 4px;
border: 1px solid #ccc;
}
.toggle-group {
button {
padding: 0.5rem 1rem;
border: 1px solid #0056b3;
background: white;
color: #0056b3;
cursor: pointer;
&:first-child { border-radius: 4px 0 0 4px; }
&:last-child { border-radius: 0 4px 4px 0; }
&.active { background: #0056b3; color: white; }
}
}
}
}
// Table styling
.ranking-table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
th, td {
padding: 0.75rem;
text-align: left;
border-bottom: 1px solid #f0f0f0;
}
.top-tier { background-color: #f8fbff; font-weight: 600; }
.positive { color: #28a745; }
.negative { color: #dc3545; }
.mover-badge { margin-left: 4px; font-size: 0.8rem; }
.trend-col {
font-weight: bold;
&[data-trend="up"] { color: #28a745; }
&[data-trend="down"] { color: #dc3545; }
}
}
@@ -1,10 +1,53 @@
import { Component } from '@angular/core';
import { Component, OnInit } from '@angular/core';
import { UniversityRankingService } from '../university-ranking/services/uni-ranking-service';
import {UniversityLineChartComponent} from '../university-ranking/uni-line-chart/uni-line-chart.component';
import { UniversityRankingTableComponent } from '../university-ranking/uni-ranking-table/uni-ranking-table.component';
import { UniversityTopicData, UniversityRanking } from '../../api';
export type ResearchTopic = 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology';
export type DashboardMetric = 'publications' | 'citations';
@Component({
selector: 'app-dashboard',
imports: [],
selector: 'dashboard',
imports: [UniversityLineChartComponent,UniversityRankingTableComponent],
templateUrl: './dashboard.component.html',
styleUrl: './dashboard.component.scss',
standalone: true,
})
export class DashboardComponent {}
export class DashboardComponent implements OnInit {
topics: ResearchTopic[] = ['Artificial Intelligence', 'Quantum Computing', 'Renewable Energy', 'Biotechnology'];
selectedTopic: ResearchTopic = 'Artificial Intelligence';
metric: DashboardMetric = 'publications';
rawDataSource: UniversityTopicData[] = [];
computedRankings: UniversityRanking[] = [];
isLoading = false;
constructor(private dataService: UniversityRankingService) {}
ngOnInit() {
this.loadData();
}
onTopicChange(topic: ResearchTopic) {
this.selectedTopic = topic;
this.loadData(); // Re-fetch as rankings depend on the topic
}
setMetric(metric: DashboardMetric) {
this.metric = metric;
this.loadData(); // Re-fetch as ranking order changes based on metric
}
private loadData() {
this.isLoading = true;
this.dataService.getRankingData(this.selectedTopic, this.metric).subscribe(response => {
// Map backend snake_case properties to frontend camelCase if necessary,
// though OpenAPI Generator usually handles this.
console.log(response);
this.rawDataSource = (response.timeseries as any) || [];
this.computedRankings = (response.rankings as any) || [];
this.isLoading = false;
});
}
}
@@ -0,0 +1,20 @@
// src/app/modules/university-ranking/services/university-data.service.ts
import { inject, Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { InstitutionsService, RankingResponse } from '../../../api';
export type ResearchTopic = 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology';
export type DashboardMetric = 'publications' | 'citations';
@Injectable({ providedIn: 'root' })
export class UniversityRankingService {
private apiService = inject(InstitutionsService);
/**
* Fetches ranking and timeseries data directly from the backend.
* Calculations for growth and trends are now handled server-side.
*/
getRankingData(topic: ResearchTopic, metric: DashboardMetric): Observable<RankingResponse> {
return this.apiService.getRankingsApiInseServiceUniversityRankingsGet(topic, metric);
}
}
@@ -0,0 +1,6 @@
<div
echarts
[options]="chartOption"
[merge]="mergeOption"
class="chart-container">
</div>
@@ -0,0 +1 @@
.chart-container { height: 500px; width: 100%; }
@@ -0,0 +1,57 @@
// src/app/modules/university-ranking/components/line-chart/university-line-chart.component.ts
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { EChartsOption } from 'echarts';
import { NgxEchartsDirective} from 'ngx-echarts';
import { UniversityTopicData, YearlyData } from '../../../api';
export type ResearchTopic = 'Artificial Intelligence' | 'Quantum Computing' | 'Renewable Energy' | 'Biotechnology';
export type DashboardMetric = 'publications' | 'citations';
@Component({
selector: 'app-university-line-chart',
templateUrl: './uni-line-chart.component.html',
styleUrl: './uni-line-chart.component.scss',
imports: [NgxEchartsDirective],
standalone: true,
})
export class UniversityLineChartComponent implements OnChanges {
@Input() data: UniversityTopicData[] = [];
@Input() metric: DashboardMetric = 'publications';
chartOption: EChartsOption = {
title: { text: 'Research Output Over Time', left: 'center', textStyle: { fontWeight: 'lighter' } },
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
legend: { bottom: 0 },
grid: { left: '3%', right: '4%', bottom: '15%', containLabel: true },
xAxis: { type: 'category', boundaryGap: false, data: [] },
yAxis: { type: 'value', name: 'Volume' },
dataZoom: [{ type: 'slider', show: true, bottom: 40 }],
series: []
};
mergeOption: EChartsOption = {};
ngOnChanges(changes: SimpleChanges): void {
if (this.data.length > 0) {
this.updateChart();
console.log("CHANGES!")
}
}
private updateChart() {
const years = this.data[0].yearly_data.map(d => d.year);
const series = this.data.map(uni => ({
name: uni.university,
type: 'line',
smooth: true,
emphasis: { focus: 'series' },
animationDuration: 2000,
data: uni.yearly_data.map(d => d[this.metric])
}));
this.mergeOption = {
xAxis: { data: years.map(String) },
series: series as any
};
}
}
@@ -0,0 +1,42 @@
<div class="ranking-card">
<h4>Topic Rankings</h4>
@if (loading) {
<div class="skeleton-loader">Loading rankings...</div>
} @else{
<table class="ranking-table">
<thead>
<tr>
<th>Rank</th>
<th>University</th>
<th>Latest</th>
<th>5Y Growth</th>
<th>Trend</th>
</tr>
</thead>
<tbody>
@for (row of rankings; track $index) {
<tr [class.top-tier]="row.rank <= 3">
<td>#{{ row.rank }}</td>
<td>
{{ row.university }}
@if (row.is_top_mover) {
<span class="mover-badge" title="Top mover last 3 years"
>🔥</span
>
}
</td>
<td>{{ row.publications | number }}</td>
<td
[class.positive]="row.growth_rate > 0"
[class.negative]="row.growth_rate < 0">
{{ row.growth_rate | number: '1.0-1' }}%
</td>
<td class="trend-col" [attr.data-trend]="row.trend">
{{ getTrendIcon(row.trend) }}
</td>
</tr>
}
</tbody>
</table>
}
</div>
@@ -0,0 +1,22 @@
// src/app/modules/university-ranking/components/ranking-table/university-ranking-table.component.ts
import { Component, Input } from '@angular/core';
import { UniversityRanking } from '../../../api';
import { DecimalPipe } from '@angular/common';
@Component({
selector: 'app-university-ranking-table',
templateUrl: './uni-ranking-table.component.html',
styleUrls: ['./uni-ranking-table.component.scss'],
imports:[DecimalPipe],
})
export class UniversityRankingTableComponent {
@Input() rankings: UniversityRanking[] = [];
@Input() loading: boolean = false;
getTrendIcon(trend: string): string {
if (trend === 'up') return '↑';
if (trend === 'down') return '↓';
return '→';
}
}