Trajectories API¶
Functions for analyzing disease progression trajectories.
Overview¶
The trajectories module provides analysis tools for:
- Trajectory network construction
- Patient connectivity analysis
- Temporal pathway enrichment
- Transition probability calculation
- Trajectory visualization
Network Construction¶
build_trajectory_network¶
Build directed graph of patient transitions.
build_trajectory_network ¶
build_trajectory_network(
patient_links: DataFrame,
) -> Tuple[Dict[str, List[str]], List[List[str]]]
Build trajectory network and find all complete disease progression paths.
Constructs a directed graph from patient links and identifies all possible complete trajectories from root nodes (earliest stage patients not appearing as targets) to leaf nodes (latest stage patients not appearing as sources).
Args: patient_links: DataFrame with 'source' and 'target' columns from linking functions
Returns: Tuple of: - network: Dict mapping each source patient to list of target patients - trajectories: List of complete trajectories, where each trajectory is a list of patient IDs ordered from earliest to latest stage
Network Structure: - Adjacency list representation: {source: [target1, target2, ...]} - Directed edges from earlier to later stages - Allows multiple outgoing edges (one patient → multiple next-stage patients)
Trajectory Discovery: - Uses depth-first search from root nodes - Root nodes: Patients in 'source' but not in 'target' (stage I or early) - Leaf nodes: Patients in 'target' but not in 'source' (stage IV or late) - Each trajectory represents a complete disease progression path
Example: >>> network, trajectories = build_trajectory_network(patient_links) >>> print(f"Network has {len(network)} nodes") >>> print(f"Found {len(trajectories)} complete trajectories") >>> print(f"Example trajectory: {trajectories[0]}") Network has 500 nodes Found 234 complete trajectories Example trajectory: ['PAT001', 'PAT045', 'PAT123', 'PAT289']
Trajectory Characteristics: - Length varies based on how many stages the path spans - Typical lengths: 2-4 patients for I→II→III→IV progressions - Length 2 for early→late progressions - Patients can appear in multiple trajectories
Note: - Cycles are prevented during trajectory search - All paths from root to leaf are enumerated - Trajectories respect chronological disease progression
Source code in renalprog/modeling/predict.py
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 | |
Example Usage:
from renalprog.modeling.predict import build_trajectory_network
import pandas as pd
from pathlib import Path
# Load patient connections
connections = pd.read_csv("data/processed/patient_connections.csv")
# Build network
network = build_trajectory_network(
connections=connections,
output_path=Path("data/processed/trajectory_network.graphml")
)
print(f"Network has {network.number_of_nodes()} nodes")
print(f"Network has {network.number_of_edges()} edges")
generate_trajectory_data¶
Generate complete trajectory dataset with metadata.
generate_trajectory_data ¶
generate_trajectory_data(
vae_model: Module,
recnet_model: Optional[Module],
trajectory: List[str],
gene_data: DataFrame,
n_timepoints: int = 50,
interpolation_method: str = "linear",
device: str = "cpu",
save_path: Optional[Path] = None,
scaler: Optional[MinMaxScaler] = None,
) -> pd.DataFrame
Generate synthetic gene expression data along a patient trajectory.
Creates N interpolated time points between consecutive patients in a trajectory by performing interpolation in the VAE latent space, then decoding back to gene expression space. Optionally applies reconstruction network for refinement.
Args: vae_model: Trained VAE model for encoding/decoding recnet_model: Optional reconstruction network for refining VAE output trajectory: List of patient IDs in chronological progression order gene_data: Gene expression DataFrame (genes × patients) n_timepoints: Number of interpolation points between each patient pair interpolation_method: 'linear' or 'spherical' interpolation in latent space device: Torch device for computation save_path: Optional path to save trajectory CSV file scaler: Pre-fitted MinMaxScaler from VAE training. If None, will fit on gene_data.
Returns: DataFrame with synthetic gene expression profiles for all time points. Shape: (n_timepoints * (len(trajectory)-1), n_genes) Index contains time point identifiers
Workflow: 1. Extract gene expression for each patient in trajectory 2. Normalize using the SAME scaler used during VAE training 3. Encode each patient to VAE latent space 4. For each consecutive pair: a. Interpolate in latent space (linear or spherical) b. Decode interpolated points back to gene space c. Optionally apply reconstruction network 5. Concatenate all segments into complete trajectory
Interpolation Methods: linear: Straight-line interpolation in latent space z(t) = (1-t)*z_source + t*z_target
spherical: Spherical linear interpolation (SLERP)
Preserves magnitude, interpolates on hypersphere
Recommended for normalized latent spaces
Note: CRITICAL: The scaler must be the same one used during VAE training. Using a different scaler will produce incorrect latent representations. If scaler=None, will fit on all gene_data (all patients), which approximates the training distribution.
Source code in renalprog/modeling/predict.py
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 | |
Patient Connectivity¶
link_patients_closest¶
Link patients using closest latent space neighbors.
link_patients_closest ¶
link_patients_closest(
transitions_df: DataFrame,
start_with_first_stage: bool = True,
early_late: bool = False,
closest: bool = True,
) -> pd.DataFrame
Link patients by selecting closest (or farthest) matches across stages.
For each patient at a source stage, this function identifies the closest (or farthest) patient at the target stage, considering metadata constraints (gender, race). This creates one-to-one patient linkages that form the basis for trajectory construction.
Args: transitions_df: DataFrame from calculate_all_possible_transitions() containing all possible patient pairs with distances start_with_first_stage: If True, build forward trajectories (early→late) If False, build backward trajectories (late→early) early_late: If True, uses early/late groupings. If False, uses I-IV stages closest: If True, connect closest patients. If False, connect farthest patients
Returns: DataFrame with selected patient links, containing one row per source patient with their optimal target patient match. Includes all columns from transitions_df.
Selection Strategy: - Forward (start_with_first_stage=True): For each source, find optimal target - Backward (start_with_first_stage=False): For each target, find optimal source - Closest (closest=True): Minimum distance match - Farthest (closest=False): Maximum distance match
Metadata Stratification: Links are selected independently within each combination of: - Gender (MALE, FEMALE) - Race (ASIAN, BLACK OR AFRICAN AMERICAN, WHITE) This ensures demographic consistency in trajectories.
Example: >>> links = link_patients_closest( ... transitions_df=all_transitions, ... start_with_first_stage=True, ... closest=True ... ) >>> print(f"Created {len(links)} patient links") Created 234 patient links
Note: - Processes transitions in order for forward: I→II→III→IV - Processes in reverse for backward: IV→III→II→I - Each patient appears at most once as a source in the result
Source code in renalprog/modeling/predict.py
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 | |
Example:
from renalprog.modeling.predict import link_patients_closest
import numpy as np
early_latent = np.random.randn(100, 128)
late_latent = np.random.randn(80, 128)
connections = link_patients_closest(
latent_early=early_latent,
latent_late=late_latent,
patient_ids_early=['E001', 'E002', ...],
patient_ids_late=['L001', 'L002', ...]
)
# Returns DataFrame with columns: early_patient, late_patient, distance
link_patients_random¶
Link patients randomly (control method).
link_patients_random ¶
link_patients_random(
results_df: DataFrame,
start_with_first_stage: bool = True,
link_next: int = 5,
transitions_possible: Optional[List[str]] = None,
) -> pd.DataFrame
Link patients to multiple random targets at the next stage.
Instead of linking each patient to only their closest match, this function randomly samples multiple patients at the next stage to link to each source patient. This creates a one-to-many mapping useful for generating multiple trajectory samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
results_df | DataFrame | DataFrame with possible sources and targets, their metadata, and distance. | required |
start_with_first_stage | bool | If True, initiate trajectories with first stage as sources. If False, initiate trajectories with last stage as sources. | True |
link_next | int | Number of patients at next stage to randomly link to each patient of current stage. | 5 |
transitions_possible | list | List of transitions to process (e.g., ['1_to_2', '2_to_3']). If None, defaults to ['early_to_late']. | None |
Returns:
| Type | Description |
|---|---|
DataFrame | DataFrame with randomly sampled patient links for each transition. Contains multiple rows per source patient (up to link_next). |
Notes
- Random sampling is primarily performed for WHITE race patients due to sample size
- If fewer than link_next targets are available, all available targets are selected
- Patients from other races are included with all their possible connections
- Empty DataFrame is returned if no WHITE patients are found
Source code in renalprog/modeling/predict.py
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 | |
Transition Analysis¶
calculate_all_possible_transitions¶
Calculate metrics for all possible patient transitions.
calculate_all_possible_transitions ¶
calculate_all_possible_transitions(
data: DataFrame,
metadata_selection: DataFrame,
distance: str = "wasserstein",
early_late: bool = False,
negative_trajectory: bool = False,
) -> pd.DataFrame
Calculate all possible patient-to-patient transitions for KIRC cancer.
This function computes pairwise distances between all patients at consecutive (or same) cancer stages, considering metadata constraints. Only patients with matching gender and race are considered as potential trajectory pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data | DataFrame | Gene expression data with patients as columns. | required |
metadata_selection | DataFrame | Clinical metadata with columns: histological_type, race, gender, stage. | required |
distance | (wasserstein, euclidean) | Distance metric to use for calculating patient-to-patient distances. | 'wasserstein' |
early_late | bool | If True, uses early/late stage groupings. If False, uses I-IV stages. | False |
negative_trajectory | bool | If True, generates same-stage transitions (negative controls). If False, generates progression transitions (positive trajectories). | False |
Returns:
| Type | Description |
|---|---|
DataFrame | DataFrame containing all possible transitions with columns: - source, target: Patient IDs - source_gender, target_gender: Gender - source_race, target_race: Race - transition: Stage transition label (e.g., '1_to_2', 'early_to_late') - distance: Calculated distance between patients Sorted by gender, race, transition, and distance. |
Raises:
| Type | Description |
|---|---|
ValueError | If distance metric is not 'wasserstein' or 'euclidean'. |
Notes
- For positive trajectories: links I→II, II→III, III→IV or early→late
- For negative trajectories: links I→I, II→II, III→III, IV→IV or early→early, late→late
- Only patients with identical gender and race are paired
Source code in renalprog/modeling/predict.py
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 | |
Example Usage:
from renalprog.modeling.predict import calculate_all_possible_transitions
# Calculate all transitions
transitions = calculate_all_possible_transitions(
latent_early=early_latent,
latent_late=late_latent,
patient_ids_early=early_ids,
patient_ids_late=late_ids,
output_dir=Path("data/processed/transitions")
)
# Analyze transition patterns
print(transitions.describe())
Dynamic Enrichment¶
dynamic_enrichment_analysis¶
Perform pathway enrichment at each trajectory timepoint.
dynamic_enrichment_analysis ¶
dynamic_enrichment_analysis(
trajectory_dir: Path,
pathways_file: Path,
output_dir: Path,
cancer_type: str = "kirc",
) -> pd.DataFrame
Perform dynamic enrichment analysis on synthetic trajectories.
This orchestrates: 1. DESeq2 analysis on each trajectory point 2. GSEA on differential expression results 3. Aggregation of enrichment across trajectories
Args: trajectory_dir: Directory containing trajectory CSV files pathways_file: Path to pathway GMT file output_dir: Directory to save results cancer_type: Cancer type identifier
Returns: DataFrame with aggregated enrichment results
Source code in renalprog/modeling/predict.py
Example Usage:
from renalprog.modeling.predict import dynamic_enrichment_analysis
from pathlib import Path
# Analyze pathway dynamics along trajectories
enrichment_results = dynamic_enrichment_analysis(
trajectories=trajectory_gene_expression, # Shape: (n_traj, n_steps, n_genes)
gene_names=gene_list,
pathway_file=Path("data/external/ReactomePathways.gmt"),
output_dir=Path("reports/dynamic_enrichment")
)
# Results contain enrichment at each timepoint
for timepoint, results in enrichment_results.items():
print(f"Timepoint {timepoint}: {len(results)} enriched pathways")
Interpolation Methods¶
interpolate_latent_linear¶
Linear interpolation between points.
interpolate_latent_linear ¶
Linear interpolation in latent space.
Args: z_source: Source latent vector z_target: Target latent vector n_steps: Number of interpolation steps
Returns: Array of interpolated latent vectors (n_steps x latent_dim)
Source code in renalprog/modeling/predict.py
interpolate_latent_spherical¶
Spherical interpolation (SLERP) for normalized spaces.
interpolate_latent_spherical ¶
interpolate_latent_spherical(
z_source: ndarray, z_target: ndarray, n_steps: int = 50
) -> np.ndarray
Spherical (SLERP) interpolation in latent space.
Args: z_source: Source latent vector z_target: Target latent vector n_steps: Number of interpolation steps
Returns: Array of interpolated latent vectors (n_steps x latent_dim)
Source code in renalprog/modeling/predict.py
Comparison:
from renalprog.modeling.predict import (
interpolate_latent_linear,
interpolate_latent_spherical
)
import numpy as np
z_start = np.random.randn(1, 128)
z_end = np.random.randn(1, 128)
# Linear interpolation
traj_linear = interpolate_latent_linear(z_start, z_end, n_steps=50)
# Spherical interpolation (preserves norm better)
traj_spherical = interpolate_latent_spherical(z_start, z_end, n_steps=50)
# Spherical is preferred for normalized latent spaces
Visualization¶
plot_trajectory¶
Visualize individual trajectory.
plot_trajectory ¶
plot_trajectory(
trajectory: ndarray,
gene_names: Optional[List[str]] = None,
save_path: Optional[Path] = None,
title: str = "Gene Expression Trajectory",
n_genes_to_show: int = 20,
) -> go.Figure
Plot gene expression changes along a trajectory.
Args: trajectory: Array of shape (n_timepoints, n_genes) gene_names: Optional list of gene names save_path: Optional path to save figure title: Plot title n_genes_to_show: Number of top varying genes to display
Returns: Plotly Figure object
Source code in renalprog/plots.py
Example:
from renalprog.plots import plot_trajectory
from pathlib import Path
# Plot single trajectory
plot_trajectory(
trajectory=trajectory_data[0], # Shape: (n_steps, n_features)
feature_names=selected_genes,
output_path=Path("reports/figures/trajectory_example.png"),
title="Disease Progression Trajectory"
)
See Also¶
- Prediction API - Apply trained models
- Plots API - Visualization functions
- Complete Pipeline Tutorial