Metadata-Version: 2.4
Name: rpstats
Version: 1.0.1
Summary: Clinical Data Programming and Statistical Analysis Practical Code Library.
License-Expression: MIT
Keywords: clinical-trials,biostatistics,clinical-data-programming,cdisc,sdtm,adam,pharmaceutical,r-programming,data-science,statistics
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Healthcare Industry
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: R
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Dynamic: license-file

# rpstats

[![PyPI Version](https://img.shields.io/badge/pypi-v1.0.1-blue.svg)](https://pypi.org/project/rpstats/)
[![Python Versions](https://img.shields.io/badge/python-3.8%20|%203.9%20|%203.10%20|%203.11%20|%203.12%20|%203.13-blue.svg)](https://pypi.org/project/rpstats/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)

**rpstats** (*Reproducible Practical Statistics*) is a lightweight, professional Python package designed for biostatistics students, clinical data programmers, and researchers preparing for practical examinations and laboratory coursework.

It contains **8 complete clinical data programming and statistical analysis practical experiments**, providing complete, clean, practical-ready code in **both Python and R**.

---

## Key Features

- **Dual-Language Practical Code**: Instant access to complete, tested implementations in Python and R for every experiment.
- **Zero Heavy Dependencies**: Installs instantly without requiring pandas, NumPy, SciPy, or R. Runs on any computer, standard college laboratory workstation, or laptop.
- **Exam & Laboratory Ready**: Formatted for quick copy-pasting directly into Jupyter Notebook, Google Colab, or RStudio.
- **Statistically & Clinically Sound**: Follows industry standards including CDISC SDTM / ADaM dataset architecture, standard clinical blood pressure guidelines, and statistical testing methodologies.

---

## Installation

### Standard Installation (via PyPI)

```bash
pip install rpstats
```

### Local Development Installation

Install in editable mode from the project directory:

```bash
pip install -e .
```

---

## Quick Start & Usage

Import the package in Python or inside a Jupyter Notebook:

```python
import rpstats

# 1. Display package version
rpstats.version()

# 2. View the catalog of all 8 experiments
rpstats.help()

# 3. Print complete Python & R programs for any experiment
rpstats.exp1()  # Data Import and Exploration
rpstats.exp2()  # Data Cleaning
rpstats.exp3()  # Data Transformation
rpstats.exp4()  # Data Visualization
rpstats.exp5()  # SDTM Dataset Creation
rpstats.exp6()  # ADaM Dataset Creation
rpstats.exp7()  # Statistical Analysis
rpstats.exp8()  # Clinical Tables and Figures
```

---

## Experiments Catalog

| Function | Experiment Title | Input Files | Primary Output Files |
| :--- | :--- | :--- | :--- |
| `rpstats.exp1()` | **Data Import and Exploration** | `clinical_data.csv` | Terminal inspection output |
| `rpstats.exp2()` | **Data Cleaning** | `clinical_trial_data_raw.csv` | `clinical_trial_data_cleaned.csv` |
| `rpstats.exp3()` | **Data Transformation** | `clinical_demographics.csv`, `clinical_vitals_labs.csv` | `clinical_trial_data_analysis.csv` |
| `rpstats.exp4()` | **Data Visualization** | `clinical_visualization_data.csv` | 5 High-res PNG plots (`dpi=300`) |
| `rpstats.exp5()` | **SDTM Dataset Creation** | 5 Raw clinical domains | `dm_sdtm.csv`, `vs_sdtm.csv`, `lb_sdtm.csv`, `ae_sdtm.csv`, `ex_sdtm.csv` |
| `rpstats.exp6()` | **ADaM Dataset Creation** | 5 SDTM domains | `adsl.csv`, `advs.csv`, `adlb.csv`, `adae.csv` |
| `rpstats.exp7()` | **Statistical Analysis** | `adam_exp7_analysis.csv` | `placebo_sbp_qqplot.png`, `statistical_analysis_results.csv` |
| `rpstats.exp8()` | **Clinical Tables and Figures** | `adsl_exp8.csv`, `advs_exp8.csv`, `adae_exp8.csv` | Tables 14.1.1, 14.2.1, 14.3.1 (CSV), Figures 14.2.1, 14.2.2 (PNG) |

---

## Experiment Details

### Experiment 1: Data Import and Exploration
- **Objective**: Import and inspect clinical trial datasets.
- **Python**: Uses `pandas` and `numpy` to display the first and last records, shape, column names, data types, summary statistics, and missing value counts.
- **R**: Uses base R to inspect dimensions, structure (`str()`), column names, summary statistics, missing values per column, and complete case counts.

### Experiment 2: Data Cleaning
- **Objective**: Perform essential clinical data cleaning tasks.
- **Key Operations**:
  - Impute numeric missing values using column medians.
  - Impute missing site identifiers (`SITEID`) with `"Unknown"`.
  - Identify and remove exact duplicate rows.
  - Deduplicate patient records (`USUBJID`), retaining the first record.
  - Standardize patient sex into `'M'` and `'F'`.
  - Save cleaned data to `clinical_trial_data_cleaned.csv`.

### Experiment 3: Data Transformation
- **Objective**: Merge demographics with clinical vitals/labs and derive key study indicators.
- **Key Operations**:
  - Verify subject identifier (`USUBJID`) uniqueness and merge datasets using an inner join.
  - Derive age groups (`<65`, `>=65`).
  - Derive clinical blood pressure categories (`Normal`, `Elevated`, `Stage 1 Hypertension`, `Stage 2 Hypertension`).
  - Calculate days on study (`DAYS_ON_STUDY`) against a configurable cutoff date.
  - Derive clinical high-risk flag (`HIGH_RISK_FLAG`).
  - Save merged dataset as `clinical_trial_data_analysis.csv`.

### Experiment 4: Clinical Data Visualization
- **Objective**: Generate publication-grade, high-resolution figures.
- **Figures Generated**:
  1. `age_histogram.png`: Age distribution with kernel density curve.
  2. `sex_barchart.png`: Subject count by sex.
  3. `bmi_by_agegroup_boxplot.png`: BMI distribution grouped by age category.
  4. `glucose_by_arm_histogram.png`: Fasting glucose distribution across treatment arms.
  5. `height_weight_scatterplot.png`: Height vs. weight scatter plot categorized by sex.

### Experiment 5: SDTM Dataset Creation
- **Objective**: Transform raw source data into standardized CDISC SDTM domain structures.
- **Domains Produced**:
  - `DM` (Demographics): Subject identifiers, age, sex, race, treatment arm, date ISO standardizations.
  - `VS` (Vital Signs): Wide-to-long transformation of SYSBP, DIABP, PULSE, and TEMP with sequence numbering (`VSSEQ`).
  - `LB` (Laboratory): Wide-to-long transformation of GLUC, ALT, AST, and BILI with sequence numbering (`LBSEQ`).
  - `AE` (Adverse Events): Standardized severity (`MILD`, `MODERATE`, `SEVERE`), start/end dates, sequence numbering (`AESEQ`).
  - `EX` (Exposure): Standardized treatment dosing records and sequence numbering (`EXSEQ`).

### Experiment 6: ADaM Dataset Creation
- **Objective**: Build CDISC ADaM datasets for statistical analysis.
- **Datasets Produced**:
  - `ADSL` (Subject-Level Analysis Dataset): Incorporates exposure metrics, treatment start/end dates, safety population flag (`SAFFL`), and risk categorizations.
  - `ADVS` (Vital Signs Analysis Dataset): Identifies baseline assessment (`BASE`), calculates post-baseline change (`CHG`), and percentage change (`PCHG`).
  - `ADLB` (Laboratory Analysis Dataset): Baseline identification, change (`CHG`), and percentage change (`PCHG`).
  - `ADAE` (Adverse Events Analysis Dataset): Numeric severity (`AESEVN`) and numerical causality mappings, treatment-emergent event flags (`TRTEMFL`).

### Experiment 7: Statistical Analysis
- **Objective**: Perform formal statistical hypothesis testing and inference.
- **Tests Implemented**:
  - Descriptive summary: N, Mean, SD, Median, IQR, Min, Max by treatment arm.
  - Normality evaluation: Histograms, Q-Q plots, and Shapiro-Wilk tests.
  - Variance homogeneity: Levene's test for equality of variances.
  - Two-sample comparison: Independent t-test, mean differences, 95% confidence intervals, and Cohen's d effect size.
  - Multi-group comparison: One-way ANOVA for SBP, DBP, and Glucose across all treatment arms.
  - Post-hoc testing: Tukey's Honestly Significant Difference (HSD) test.
  - Categorical association: Chi-square test and Fisher's exact test for adverse event incidence.

### Experiment 8: Clinical Tables and Figures
- **Objective**: Generate standard regulatory-style clinical trial tables and figures.
- **Deliverables**:
  - `table_14_1_1_demographics.csv`: Table 14.1.1 Summary of Demographics and Baseline Characteristics.
  - `table_14_2_1_efficacy.csv`: Table 14.2.1 Summary of Change in Systolic Blood Pressure and Treatment Comparisons vs. Placebo.
  - `table_14_3_1_adverse_events.csv`: Table 14.3.1 Overall Summary of Adverse Events by Severity and Preferred Term.
  - `figure_14_2_1_sbp_boxplot.png`: Box plot of SBP change by treatment arm.
  - `figure_14_2_2_forest_plot.png`: Forest plot illustrating treatment differences versus Placebo with 95% confidence intervals.

---

## Workflow Guide: Copying Code

### Jupyter Notebook / Google Colab (Python)
1. Run `rpstats.expX()` in a Python console or notebook cell (where `X` is 1 to 8).
2. Copy the text printed under `---------------- PYTHON CODE ----------------`.
3. Paste into a new Jupyter code cell and run.
4. Ensure the required input CSV file is placed in your working directory.

### RStudio / R Script (R Language)
1. Run `rpstats.expX()` in Python to display the code.
2. Copy the text printed under `---------------- R LANGUAGE CODE ----------------`.
3. Open RStudio, create a new R Script (`File -> New File -> R Script`), and paste.
4. Set your working directory using `setwd()` or place the input CSV in the R working directory, then execute the script.

---

## Requirements & Compatibility

- **rpstats Package Runtime**:
  - Python: `>= 3.8` (tested on 3.8, 3.9, 3.10, 3.11, 3.12, 3.13)
  - Operating Systems: Windows, macOS, Linux
  - No external runtime dependencies required to install or display code.

- **To Execute Printed Python Scripts**:
  - `pandas`, `numpy`, `matplotlib`, `seaborn`, `scipy`, `statsmodels`
  - Install via: `pip install pandas numpy matplotlib seaborn scipy statsmodels`

- **To Execute Printed R Scripts**:
  - R `>= 4.0`
  - Packages: `tidyverse`, `ggplot2`
  - Install in R via: `install.packages(c("tidyverse", "ggplot2"))`

---

## License

Distributed under the [MIT License](LICENSE).

