diff --git a/analysis/career_stage_analysis.py b/analysis/career_stage_analysis.py index 8cddcc56..e260c390 100644 --- a/analysis/career_stage_analysis.py +++ b/analysis/career_stage_analysis.py @@ -1,157 +1,181 @@ -#!/usr/bin/env python -import asyncio import csv +from datetime import datetime from pathlib import Path from typing import Any -from inse.works.logic import get_all_author_works - -ANALYSIS_ROOT = Path(__file__).resolve().parent -SAMPLE_CSV = ANALYSIS_ROOT / "career_stage_sample.csv" -RESULTS_CSV = ANALYSIS_ROOT / "career_stage_results.csv" - -FIELD_NAMES = [ - "name", - "discipline", - "known_status", - "openalex_author_id", - "first_publication_year", - "last_publication_year", - "career_age", - "active_span", - "publication_count", - "avg_publications_per_year", - "notes", -] +from openalex_client import get_all_author_works -def parse_year(value: Any) -> int | None: - if value is None: - return None - if isinstance(value, int): - return value - try: - text = str(value).strip() - if not text: - return None - return int(text) - except ValueError: - return None +BASE_DIR = Path(__file__).resolve().parent +INPUT_FILE = BASE_DIR / "career_stage_sample.csv" +OUTPUT_FILE = BASE_DIR / "career_stage_results.csv" -async def fetch_author_works(author_id: str): - return await get_all_author_works(author_id) +def extract_publication_years(works: list[dict[str, Any]]) -> list[int]: + """ + Extracts all valid publication years from the OpenAlex works response. + + One entry in the returned list represents one publication. + Therefore, duplicate years are intentionally kept. + Example: + [2020, 2020, 2021] means 3 publications in 2 active years. + """ + years: list[int] = [] + + for work in works: + year = work.get("publication_year") + + if isinstance(year, int): + years.append(year) + elif isinstance(year, str) and year.isdigit(): + years.append(int(year)) + + return years -def compute_metrics(years: list[int]) -> tuple[ - int | None, - int | None, - int | None, - int, - int, - float, -]: - years = sorted(set(years)) - publication_count = len(years) - if publication_count == 0: - return None, None, None, 0, 0, 0.0 +def compute_metrics(publication_years: list[int]) -> dict[str, int | float | None]: + """ + Computes publication-history-based career metrics. + + Important distinction: + - publication_count counts all publications + - active_years counts distinct years with at least one publication + - career_span counts the full inclusive span from first to last publication year + """ + current_year = datetime.now().year + + if not publication_years: + return { + "first_publication_year": None, + "last_publication_year": None, + "career_age": None, + "career_span": None, + "active_years": 0, + "publication_count": 0, + "avg_publications_per_year": None, + "publications_per_active_year": None, + "publications_per_career_year": None, + "years_since_last_publication": None, + } + + sorted_years = sorted(publication_years) + unique_years = sorted(set(publication_years)) + + first_year = sorted_years[0] + last_year = sorted_years[-1] + + publication_count = len(sorted_years) + active_years = len(unique_years) - first_year = years[0] - last_year = years[-1] career_age = last_year - first_year - active_span = len(years) - avg_publications_per_year = publication_count / active_span if active_span else 0.0 - return first_year, last_year, career_age, active_span, publication_count, avg_publications_per_year + career_span = last_year - first_year + 1 + + publications_per_active_year = ( + publication_count / active_years if active_years > 0 else None + ) + + publications_per_career_year = ( + publication_count / career_span if career_span > 0 else None + ) + + years_since_last_publication = current_year - last_year + + return { + "first_publication_year": first_year, + "last_publication_year": last_year, + "career_age": career_age, + "career_span": career_span, + "active_years": active_years, + "publication_count": publication_count, + "avg_publications_per_year": publications_per_career_year, + "publications_per_active_year": publications_per_active_year, + "publications_per_career_year": publications_per_career_year, + "years_since_last_publication": years_since_last_publication, + } -def load_sample_rows() -> list[dict[str, str]]: - if not SAMPLE_CSV.exists(): - raise FileNotFoundError(f"Missing sample file: {SAMPLE_CSV}") +def analyze_sample() -> None: + if not INPUT_FILE.exists(): + raise FileNotFoundError(f"Input file not found: {INPUT_FILE}") - with SAMPLE_CSV.open("r", newline="", encoding="utf-8") as csvfile: - return list(csv.DictReader(csvfile)) - - -def write_results(rows: list[dict[str, Any]]) -> None: - with RESULTS_CSV.open("w", newline="", encoding="utf-8") as csvfile: - writer = csv.DictWriter(csvfile, fieldnames=FIELD_NAMES) - writer.writeheader() - writer.writerows(rows) - - -def main() -> None: - sample_rows = load_sample_rows() results: list[dict[str, Any]] = [] - for index, row in enumerate(sample_rows, start=1): - name = row.get("name", "").strip() - status = row.get("known_status", "").strip() - discipline = row.get("discipline", "").strip() - author_id = row.get("openalex_author_id", "").strip() + with INPUT_FILE.open(mode="r", encoding="utf-8", newline="") as input_file: + reader = csv.DictReader(input_file) - display_name = name or author_id or f"row {index}" - print(f"[{index}/{len(sample_rows)}] Processing {display_name}") + for row in reader: + name = row.get("name", "").strip() + discipline = row.get("discipline", "").strip() + known_status = row.get("known_status", "").strip() + openalex_author_id = row.get("openalex_author_id", "").strip() - first_publication_year = None - last_publication_year = None - career_age = None - active_span = 0 - publication_count = 0 - avg_publications_per_year = 0.0 - notes = "" + if not openalex_author_id: + print(f"Skipping {name}: missing OpenAlex author ID") + continue + + print(f"Fetching works for {name} ({openalex_author_id})...") - if not author_id: - notes = "missing openalex_author_id" - print(f" skipped: {notes}") - else: try: - works_response = asyncio.run(fetch_author_works(author_id)) - works = works_response.results or [] - years = [parse_year(work.publication_year) for work in works] - years = [year for year in years if year is not None] + works = get_all_author_works(openalex_author_id) + publication_years = extract_publication_years(works) + metrics = compute_metrics(publication_years) - if years: - ( - first_publication_year, - last_publication_year, - career_age, - active_span, - publication_count, - avg_publications_per_year, - ) = compute_metrics(years) - print( - f" publications={publication_count}, first={first_publication_year}, last={last_publication_year}, avg={avg_publications_per_year:.2f}" - ) - else: - notes = "no publication_year values found" - print(f" warning: {notes}") - except Exception as exc: # pragma: no cover - notes = f"error: {exc.__class__.__name__}: {exc}" - print(f" failed: {notes}") + results.append( + { + "name": name, + "discipline": discipline, + "known_status": known_status, + "openalex_author_id": openalex_author_id, + **metrics, + } + ) - results.append( - { - "name": name, - "discipline": discipline, - "known_status": status, - "openalex_author_id": author_id, - "first_publication_year": first_publication_year or "", - "last_publication_year": last_publication_year or "", - "career_age": career_age if career_age is not None else "", - "active_span": active_span, - "publication_count": publication_count, - "avg_publications_per_year": ( - round(avg_publications_per_year, 3) - if avg_publications_per_year is not None - else "" - ), - "notes": notes, - } - ) + except Exception as error: + print(f"Error while processing {name}: {error}") - write_results(results) - print(f"Results written to {RESULTS_CSV}") + results.append( + { + "name": name, + "discipline": discipline, + "known_status": known_status, + "openalex_author_id": openalex_author_id, + "first_publication_year": None, + "last_publication_year": None, + "career_age": None, + "career_span": None, + "active_years": 0, + "publication_count": 0, + "avg_publications_per_year": None, + "publications_per_active_year": None, + "publications_per_career_year": None, + "years_since_last_publication": None, + } + ) + + fieldnames = [ + "name", + "discipline", + "known_status", + "openalex_author_id", + "first_publication_year", + "last_publication_year", + "career_age", + "career_span", + "active_years", + "publication_count", + "avg_publications_per_year", + "publications_per_active_year", + "publications_per_career_year", + "years_since_last_publication", + ] + + with OUTPUT_FILE.open(mode="w", encoding="utf-8", newline="") as output_file: + writer = csv.DictWriter(output_file, fieldnames=fieldnames) + writer.writeheader() + writer.writerows(results) + + print(f"Analysis finished. Results written to {OUTPUT_FILE}") if __name__ == "__main__": - main() + analyze_sample() \ No newline at end of file diff --git a/analysis/career_stage_results.csv b/analysis/career_stage_results.csv new file mode 100644 index 00000000..c4b2c494 --- /dev/null +++ b/analysis/career_stage_results.csv @@ -0,0 +1,23 @@ +name,discipline,known_status,openalex_author_id,first_publication_year,last_publication_year,career_age,career_span,active_years,publication_count,avg_publications_per_year,publications_per_active_year,publications_per_career_year,years_since_last_publication +Jens Krüger,Computer Graphics and Visualization,Professor,A5087449583,1964,2025,61,62,20,67,1.0806451612903225,3.35,1.0806451612903225,1 +Lucas Davi,Secure Software Systems,Professor,A5089242868,2009,2026,17,18,18,137,7.611111111111111,7.611111111111111,7.611111111111111,0 +Pedro José Marrón,Networked Embedded Systems,Professor,A5047117780,1996,2026,30,31,28,285,9.193548387096774,10.178571428571429,9.193548387096774,0 +Torben Weis,Distributed Systems,Professor,A5016729057,1980,2026,46,47,43,197,4.191489361702128,4.5813953488372094,4.191489361702128,0 +Gregor Schiele,Intelligent Embedded Systems,Professor,A5028943371,1999,2026,27,28,22,155,5.535714285714286,7.045454545454546,5.535714285714286,0 +Barbara König,Theoretical Computer Science,Professor,A5103103785,1906,2026,120,121,36,230,1.9008264462809918,6.388888888888889,1.9008264462809918,0 +Stefan Schneegaß,Human Computer Interaction,Professor,A5024328962,2008,2026,18,19,17,224,11.789473684210526,13.176470588235293,11.789473684210526,0 +Andreas Vogelsang,Software Systems Engineering,Professor,A5022998651,2005,2026,21,22,20,225,10.227272727272727,11.25,10.227272727272727,0 +Andreas Metzger,Software Systems Engineering2,Professor,A5082025709,1992,2026,34,35,28,202,5.771428571428571,7.214285714285714,5.771428571428571,0 +Alexandra Dmitrienko,Vertrauenswürdige Systeme,Professor,A5042835341,2010,2026,16,17,17,110,6.470588235294118,6.470588235294118,6.470588235294118,0 +Volker Gruhn,Software Engineering,Professor,A5049739067,1989,2025,36,37,36,410,11.08108108108108,11.38888888888889,11.08108108108108,1 +Soheil Salighe,Steuerung Regelung und Systemdynamik,Researcher,A5041884757,2017,2024,7,8,5,7,0.875,1.4,0.875,2 +Pascal Winkler,Secure Software Systems,Researcher,A5081189339,2009,2026,17,18,6,22,1.2222222222222223,3.6666666666666665,1.2222222222222223,0 +Christian Scholz,Secure Software Systems,Researcher,A5120610207,2025,2026,1,2,2,2,1.0,1.0,1.0,0 +Christian Niesler,Secure Software Systems,Researcher,A5069184110,2021,2026,5,6,5,9,1.5,1.8,1.5,0 +Jonas Keppel,Human Computer Interaction,Researcher,A5015767175,2022,2026,4,5,5,11,2.2,2.2,2.2,0 +Carina Liebers,Human Computer Interaction,Researcher,A5004350173,2022,2026,4,5,5,11,2.2,2.2,2.2,0 +Simon Janzon,Networked Embedded Systems,Researcher,A5044472300,2020,2025,5,6,5,6,1.0,1.2,1.0,1 +Stefan Hanenberg,Software Engineering,Researcher,A5027034338,2000,2025,25,26,25,105,4.038461538461538,4.2,4.038461538461538,1 +Wilhelm Koop,Software Engineering,Researcher,A5019228221,2016,2022,6,7,6,14,2.0,2.3333333333333335,2.0,4 +Carlos Medina Sánchez,Networked Embedded Systems,Researcher,A509347987,,,,,0,0,,,, +Venkata Marella,Vertrauenswürdige Systeme,Researcher,A5082156768,2017,2026,9,10,8,11,1.1,1.375,1.1,0 diff --git a/analysis/career_stage_sample.csv b/analysis/career_stage_sample.csv index 4a357979..13c1a7bb 100644 --- a/analysis/career_stage_sample.csv +++ b/analysis/career_stage_sample.csv @@ -1,9 +1,23 @@ name,discipline,known_status,openalex_author_id Jens Krüger,Computer Graphics and Visualization,Professor,A5087449583 +Lucas Davi,Secure Software Systems,Professor,A5089242868 Pedro José Marrón,Networked Embedded Systems,Professor,A5047117780 Torben Weis,Distributed Systems,Professor,A5016729057 Gregor Schiele,Intelligent Embedded Systems,Professor,A5028943371 -Barbara König,Theoretical Computer Science,Professor,A510310785 -Soheil Salighe,Steuerung Regelung und Systemdynamik,Doctoral Researcher,A5041884757 -Pascal Winkler,Secure Software Systems,Doctoral Researcher,A5081189339 -Jonas Keppel,Human Computer Interaction,Doctoral Researcher,A5015767175 \ No newline at end of file +Barbara König,Theoretical Computer Science,Professor,A5103103785 +Stefan Schneegaß,Human Computer Interaction,Professor,A5024328962 +Andreas Vogelsang,Software Systems Engineering,Professor,A5022998651 +Andreas Metzger,Software Systems Engineering2,Professor,A5082025709 +Alexandra Dmitrienko,Vertrauenswürdige Systeme,Professor,A5042835341 +Volker Gruhn,Software Engineering,Professor,A5049739067 +Soheil Salighe,Steuerung Regelung und Systemdynamik,Researcher,A5041884757 +Pascal Winkler,Secure Software Systems,Researcher,A5081189339 +Christian Scholz,Secure Software Systems,Researcher,A5120610207 +Christian Niesler,Secure Software Systems,Researcher,A5069184110 +Jonas Keppel,Human Computer Interaction,Researcher,A5015767175 +Carina Liebers,Human Computer Interaction,Researcher,A5004350173 +Simon Janzon,Networked Embedded Systems,Researcher,A5044472300 +Stefan Hanenberg,Software Engineering,Researcher,A5027034338 +Wilhelm Koop,Software Engineering,Researcher,A5019228221 +Carlos Medina Sánchez,Networked Embedded Systems,Researcher,A509347987 +Venkata Marella,Vertrauenswürdige Systeme,Researcher,A5082156768 \ No newline at end of file diff --git a/analysis/career_stage_visualization.py b/analysis/career_stage_visualization.py index fbc0282d..05808e28 100644 --- a/analysis/career_stage_visualization.py +++ b/analysis/career_stage_visualization.py @@ -1,91 +1,267 @@ -#!/usr/bin/env python from pathlib import Path import matplotlib.pyplot as plt import pandas as pd -ANALYSIS_ROOT = Path(__file__).resolve().parent -RESULTS_CSV = ANALYSIS_ROOT / "career_stage_results.csv" -PLOTS_DIR = ANALYSIS_ROOT / "plots" -PLOTS_DIR.mkdir(exist_ok=True) + +BASE_DIR = Path(__file__).resolve().parent +INPUT_FILE = BASE_DIR / "career_stage_results.csv" +PLOTS_DIR = BASE_DIR / "plots" -def load_data() -> pd.DataFrame: - if not RESULTS_CSV.exists(): - raise FileNotFoundError(f"Missing results file: {RESULTS_CSV}") +def prepare_data() -> pd.DataFrame: + if not INPUT_FILE.exists(): + raise FileNotFoundError( + f"Input file not found: {INPUT_FILE}. " + "Run career_stage_analysis.py first." + ) + + df = pd.read_csv(INPUT_FILE) - df = pd.read_csv(RESULTS_CSV) numeric_columns = [ + "first_publication_year", + "last_publication_year", "career_age", - "active_span", + "career_span", + "active_years", "publication_count", "avg_publications_per_year", + "publications_per_active_year", + "publications_per_career_year", + "years_since_last_publication", ] + for column in numeric_columns: - df[column] = pd.to_numeric(df[column], errors="coerce") + if column in df.columns: + df[column] = pd.to_numeric(df[column], errors="coerce") + return df -def save_plot(fig, filename: str) -> None: - output_path = PLOTS_DIR / filename - fig.tight_layout() - fig.savefig(output_path, dpi=200) - print(f"Saved plot: {output_path}") +def save_bar_plot( + df: pd.DataFrame, + metric: str, + title: str, + ylabel: str, + filename: str, +) -> None: + grouped = df.groupby("known_status")[metric].mean().sort_values(ascending=False) + + plt.figure(figsize=(10, 6)) + grouped.plot(kind="bar") + plt.title(title) + plt.xlabel("Known Status") + plt.ylabel(ylabel) + plt.xticks(rotation=30, ha="right") + plt.tight_layout() + plt.savefig(PLOTS_DIR / filename) + plt.close() -def career_age_by_status(df: pd.DataFrame) -> None: - grouped = df.groupby("known_status")["career_age"].mean().sort_values() - fig, ax = plt.subplots(figsize=(8, 5)) - grouped.plot(kind="bar", ax=ax, color="#4C72B0") - ax.set_title("Average Career Age by Known Status") - ax.set_xlabel("Known Status") - ax.set_ylabel("Average Career Age (years)") - save_plot(fig, "career_age_by_status.png") +def save_box_plot( + df: pd.DataFrame, + metric: str, + title: str, + ylabel: str, + filename: str, +) -> None: + statuses = df["known_status"].dropna().unique() + data = [df.loc[df["known_status"] == status, metric].dropna() for status in statuses] + + plt.figure(figsize=(10, 6)) + plt.boxplot(data, labels=statuses) + plt.title(title) + plt.xlabel("Known Status") + plt.ylabel(ylabel) + plt.xticks(rotation=30, ha="right") + plt.tight_layout() + plt.savefig(PLOTS_DIR / filename) + plt.close() -def publication_count_by_status(df: pd.DataFrame) -> None: - grouped = df.groupby("known_status")["publication_count"].mean().sort_values() - fig, ax = plt.subplots(figsize=(8, 5)) - grouped.plot(kind="bar", ax=ax, color="#DD8452") - ax.set_title("Average Publication Count by Known Status") - ax.set_xlabel("Known Status") - ax.set_ylabel("Average Publication Count") - save_plot(fig, "publication_count_by_status.png") +def save_scatter_plot( + df: pd.DataFrame, + x_metric: str, + y_metric: str, + title: str, + xlabel: str, + ylabel: str, + filename: str, +) -> None: + plt.figure(figsize=(10, 6)) - -def career_age_vs_publication_count(df: pd.DataFrame) -> None: - fig, ax = plt.subplots(figsize=(8, 6)) for status, group in df.groupby("known_status"): - ax.scatter( - group["career_age"], - group["publication_count"], - label=status, - alpha=0.75, - s=80, - edgecolor="black", - linewidth=0.5, - ) + plt.scatter(group[x_metric], group[y_metric], label=status) - ax.set_title("Career Age vs Publication Count") - ax.set_xlabel("Career Age (years)") - ax.set_ylabel("Publication Count") - ax.legend(title="Known Status") - save_plot(fig, "career_age_vs_publication_count.png") + for _, row in group.iterrows(): + name = row.get("name") + x_value = row.get(x_metric) + y_value = row.get(y_metric) + + if pd.notna(name) and pd.notna(x_value) and pd.notna(y_value): + plt.annotate( + str(name), + (x_value, y_value), + fontsize=8, + xytext=(5, 5), + textcoords="offset points", + ) + + plt.title(title) + plt.xlabel(xlabel) + plt.ylabel(ylabel) + plt.legend() + plt.tight_layout() + plt.savefig(PLOTS_DIR / filename) + plt.close() -def main() -> None: - df = load_data() +def save_histogram( + df: pd.DataFrame, + metric: str, + title: str, + xlabel: str, + filename: str, +) -> None: + plt.figure(figsize=(10, 6)) + df[metric].dropna().plot(kind="hist", bins=10) + plt.title(title) + plt.xlabel(xlabel) + plt.ylabel("Number of Researchers") + plt.tight_layout() + plt.savefig(PLOTS_DIR / filename) + plt.close() + + +def create_visualizations() -> None: + PLOTS_DIR.mkdir(exist_ok=True) + + df = prepare_data() + if df.empty: - raise ValueError(f"No data found in {RESULTS_CSV}") + print("No data available for visualization.") + return - df = df.dropna(subset=["known_status"]) - if df.empty: - raise ValueError("No rows with known_status in the results file.") + save_bar_plot( + df=df, + metric="career_span", + title="Average Career Span by Known Status", + ylabel="Average Career Span in Years", + filename="average_career_span_by_status.png", + ) - career_age_by_status(df) - publication_count_by_status(df) - career_age_vs_publication_count(df) + save_bar_plot( + df=df, + metric="publication_count", + title="Average Publication Count by Known Status", + ylabel="Average Number of Publications", + filename="average_publication_count_by_status.png", + ) + + save_bar_plot( + df=df, + metric="active_years", + title="Average Active Publication Years by Known Status", + ylabel="Average Number of Active Years", + filename="average_active_years_by_status.png", + ) + + save_bar_plot( + df=df, + metric="publications_per_active_year", + title="Average Publications per Active Year by Known Status", + ylabel="Average Publications per Active Year", + filename="average_publications_per_active_year_by_status.png", + ) + + save_bar_plot( + df=df, + metric="publications_per_career_year", + title="Average Publications per Career Year by Known Status", + ylabel="Average Publications per Career Year", + filename="average_publications_per_career_year_by_status.png", + ) + + save_bar_plot( + df=df, + metric="years_since_last_publication", + title="Average Years Since Last Publication by Known Status", + ylabel="Average Years Since Last Publication", + filename="average_years_since_last_publication_by_status.png", + ) + + save_box_plot( + df=df, + metric="career_span", + title="Distribution of Career Span by Known Status", + ylabel="Career Span in Years", + filename="boxplot_career_span_by_status.png", + ) + + save_box_plot( + df=df, + metric="publication_count", + title="Distribution of Publication Count by Known Status", + ylabel="Number of Publications", + filename="boxplot_publication_count_by_status.png", + ) + + save_box_plot( + df=df, + metric="active_years", + title="Distribution of Active Publication Years by Known Status", + ylabel="Active Publication Years", + filename="boxplot_active_years_by_status.png", + ) + + save_histogram( + df=df, + metric="career_span", + title="Career Span Distribution", + xlabel="Career Span in Years", + filename="histogram_career_span.png", + ) + + save_histogram( + df=df, + metric="publication_count", + title="Publication Count Distribution", + xlabel="Number of Publications", + filename="histogram_publication_count.png", + ) + + save_scatter_plot( + df=df, + x_metric="career_span", + y_metric="publication_count", + title="Career Span vs Publication Count", + xlabel="Career Span in Years", + ylabel="Number of Publications", + filename="scatter_career_span_vs_publication_count.png", + ) + + save_scatter_plot( + df=df, + x_metric="active_years", + y_metric="publication_count", + title="Active Publication Years vs Publication Count", + xlabel="Active Publication Years", + ylabel="Number of Publications", + filename="scatter_active_years_vs_publication_count.png", + ) + + save_scatter_plot( + df=df, + x_metric="career_span", + y_metric="publications_per_active_year", + title="Career Span vs Publications per Active Year", + xlabel="Career Span in Years", + ylabel="Publications per Active Year", + filename="scatter_career_span_vs_publications_per_active_year.png", + ) + + print(f"Visualizations saved to {PLOTS_DIR}") if __name__ == "__main__": - main() + create_visualizations() \ No newline at end of file diff --git a/analysis/openalex_client.py b/analysis/openalex_client.py new file mode 100644 index 00000000..a71d1250 --- /dev/null +++ b/analysis/openalex_client.py @@ -0,0 +1,96 @@ +import json +from typing import Any +from urllib.error import HTTPError, URLError +from urllib.parse import urlencode +from urllib.request import Request, urlopen + + +OPENALEX_WORKS_URL = "https://api.openalex.org/works" +REQUEST_TIMEOUT_SECONDS = 30 +PER_PAGE = 200 + + +def normalize_author_id(author_id: str) -> str: + """ + Normalizes OpenAlex author IDs. + + Supported inputs: + - A123456789 + - https://openalex.org/A123456789 + - https://api.openalex.org/authors/A123456789 + """ + cleaned_author_id = author_id.strip() + + if cleaned_author_id.startswith("https://api.openalex.org/authors/"): + return cleaned_author_id.replace( + "https://api.openalex.org/authors/", + "https://openalex.org/", + ) + + if cleaned_author_id.startswith("https://openalex.org/"): + return cleaned_author_id + + if cleaned_author_id.startswith("A"): + return f"https://openalex.org/{cleaned_author_id}" + + return cleaned_author_id + + +def fetch_openalex_page(author_id: str, cursor: str) -> dict[str, Any]: + normalized_author_id = normalize_author_id(author_id) + + query_params = urlencode( + { + "filter": f"authorships.author.id:{normalized_author_id}", + "per-page": PER_PAGE, + "cursor": cursor, + "sort": "publication_year:asc", + } + ) + + url = f"{OPENALEX_WORKS_URL}?{query_params}" + + request = Request( + url, + headers={ + "Accept": "application/json", + "User-Agent": "AIIS career stage analysis", + }, + ) + + try: + with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response: + response_body = response.read().decode("utf-8") + return json.loads(response_body) + + except HTTPError as error: + raise RuntimeError( + f"OpenAlex request failed with HTTP status {error.code}: {url}" + ) from error + + except URLError as error: + raise RuntimeError(f"OpenAlex request failed: {error}") from error + + +def get_all_author_works(author_id: str) -> list[dict[str, Any]]: + """ + Fetches all works for an OpenAlex author by using cursor pagination. + """ + works: list[dict[str, Any]] = [] + cursor = "*" + + while cursor: + data = fetch_openalex_page(author_id, cursor) + + page_results = data.get("results", []) + works.extend(page_results) + + meta = data.get("meta", {}) + next_cursor = meta.get("next_cursor") + + if not next_cursor or next_cursor == cursor: + break + + cursor = next_cursor + + return works \ No newline at end of file diff --git a/analysis/plots/average_active_years_by_status.png b/analysis/plots/average_active_years_by_status.png new file mode 100644 index 00000000..4b7bcc74 Binary files /dev/null and b/analysis/plots/average_active_years_by_status.png differ diff --git a/analysis/plots/average_career_span_by_status.png b/analysis/plots/average_career_span_by_status.png new file mode 100644 index 00000000..a9f62e1c Binary files /dev/null and b/analysis/plots/average_career_span_by_status.png differ diff --git a/analysis/plots/average_publication_count_by_status.png b/analysis/plots/average_publication_count_by_status.png new file mode 100644 index 00000000..51fa3267 Binary files /dev/null and b/analysis/plots/average_publication_count_by_status.png differ diff --git a/analysis/plots/average_publications_per_active_year_by_status.png b/analysis/plots/average_publications_per_active_year_by_status.png new file mode 100644 index 00000000..1aade1db Binary files /dev/null and b/analysis/plots/average_publications_per_active_year_by_status.png differ diff --git a/analysis/plots/average_publications_per_career_year_by_status.png b/analysis/plots/average_publications_per_career_year_by_status.png new file mode 100644 index 00000000..6eb3897f Binary files /dev/null and b/analysis/plots/average_publications_per_career_year_by_status.png differ diff --git a/analysis/plots/average_years_since_last_publication_by_status.png b/analysis/plots/average_years_since_last_publication_by_status.png new file mode 100644 index 00000000..db443a28 Binary files /dev/null and b/analysis/plots/average_years_since_last_publication_by_status.png differ diff --git a/analysis/plots/boxplot_active_years_by_status.png b/analysis/plots/boxplot_active_years_by_status.png new file mode 100644 index 00000000..210cba08 Binary files /dev/null and b/analysis/plots/boxplot_active_years_by_status.png differ diff --git a/analysis/plots/boxplot_career_span_by_status.png b/analysis/plots/boxplot_career_span_by_status.png new file mode 100644 index 00000000..c3565162 Binary files /dev/null and b/analysis/plots/boxplot_career_span_by_status.png differ diff --git a/analysis/plots/boxplot_publication_count_by_status.png b/analysis/plots/boxplot_publication_count_by_status.png new file mode 100644 index 00000000..1fd46ce6 Binary files /dev/null and b/analysis/plots/boxplot_publication_count_by_status.png differ diff --git a/analysis/plots/histogram_career_span.png b/analysis/plots/histogram_career_span.png new file mode 100644 index 00000000..74d4d598 Binary files /dev/null and b/analysis/plots/histogram_career_span.png differ diff --git a/analysis/plots/histogram_publication_count.png b/analysis/plots/histogram_publication_count.png new file mode 100644 index 00000000..595f5a11 Binary files /dev/null and b/analysis/plots/histogram_publication_count.png differ diff --git a/analysis/plots/scatter_active_years_vs_publication_count.png b/analysis/plots/scatter_active_years_vs_publication_count.png new file mode 100644 index 00000000..06ea938d Binary files /dev/null and b/analysis/plots/scatter_active_years_vs_publication_count.png differ diff --git a/analysis/plots/scatter_career_span_vs_publication_count.png b/analysis/plots/scatter_career_span_vs_publication_count.png new file mode 100644 index 00000000..b02853f2 Binary files /dev/null and b/analysis/plots/scatter_career_span_vs_publication_count.png differ diff --git a/analysis/plots/scatter_career_span_vs_publications_per_active_year.png b/analysis/plots/scatter_career_span_vs_publications_per_active_year.png new file mode 100644 index 00000000..233176f4 Binary files /dev/null and b/analysis/plots/scatter_career_span_vs_publications_per_active_year.png differ