|
| 1 | +import argparse |
| 2 | +import sys |
| 3 | +import os |
| 4 | +sys.path.append('../scTab') |
| 5 | +sys.path.append('../model_evaluation') |
| 6 | +import pandas as pd |
| 7 | +import matplotlib.pyplot as plt |
| 8 | +import numpy as np |
| 9 | +from utils import ( |
| 10 | + data_preparation, |
| 11 | + run_model, |
| 12 | + print_clf_report_per_class |
| 13 | +) |
| 14 | + |
| 15 | +def parse_args(): |
| 16 | + """Parse command line arguments.""" |
| 17 | + parser = argparse.ArgumentParser(description='Evaluate cell type classification models') |
| 18 | + |
| 19 | + # Data paths |
| 20 | + parser.add_argument('--dataset_ids', type=str, help='Dataset ID or "diff_2023-05-15"') |
| 21 | + parser.add_argument('--features_file', type=str, required=True, |
| 22 | + help='Path to features.parquet') |
| 23 | + parser.add_argument('--var_file', type=str, required=True, |
| 24 | + help='Path to var.parquet') |
| 25 | + parser.add_argument('--cell_type_mapping_file', type=str, required=True, |
| 26 | + help='Path to cell_type.parquet') |
| 27 | + parser.add_argument('--cell_type_hierarchy_file', type=str, required=True, |
| 28 | + help='Path to child_matrix.npy') |
| 29 | + |
| 30 | + # Model paths and configuration |
| 31 | + parser.add_argument('--model_type', type=str, required=True, |
| 32 | + choices=['tabnet', 'linear', 'mlp', 'celltypist'], |
| 33 | + help='Type of model to evaluate') |
| 34 | + parser.add_argument('--checkpoint_path', type=str, required=True, |
| 35 | + help='Path to model checkpoint') |
| 36 | + parser.add_argument('--hparams_file', type=str, |
| 37 | + help='Path to hyperparameters file (not needed for CellTypist)') |
| 38 | + |
| 39 | + # Output configuration |
| 40 | + parser.add_argument('--output_dir', type=str, default='evaluation_results', |
| 41 | + help='Directory to save evaluation results') |
| 42 | + parser.add_argument('--census_version', type=str, default='2023-05-15', |
| 43 | + help='CellXGene census version') |
| 44 | + parser.add_argument('--force_download', action='store_true', |
| 45 | + help='Force re-download of data') |
| 46 | + |
| 47 | + # Add output root argument |
| 48 | + parser.add_argument('--output_root', type=str, required=True, |
| 49 | + help='Root directory for storing AnnData chunks and results') |
| 50 | + |
| 51 | + return parser.parse_args() |
| 52 | + |
| 53 | +def save_results(clf_report_overall, clf_report_per_class, y_probs, y_pred, y_true, metadata, cell_type_mapping, args): |
| 54 | + """Save evaluation results to files.""" |
| 55 | + os.makedirs(args.output_dir, exist_ok=True) |
| 56 | + |
| 57 | + # Save overall metrics |
| 58 | + overall_path = os.path.join(args.output_dir, f'{args.model_type}_overall_metrics.csv') |
| 59 | + clf_report_overall.to_csv(overall_path) |
| 60 | + print(f"\nOverall metrics saved to: {overall_path}") |
| 61 | + print("\nOverall Results:") |
| 62 | + print(clf_report_overall) |
| 63 | + |
| 64 | + # Save per-class metrics |
| 65 | + per_class_path = os.path.join(args.output_dir, f'{args.model_type}_per_class_metrics.csv') |
| 66 | + clf_report_per_class.to_csv(per_class_path) |
| 67 | + print(f"\nPer-class metrics saved to: {per_class_path}") |
| 68 | + |
| 69 | + # Generate and save visualization |
| 70 | + plt.figure(figsize=(20, 10)) |
| 71 | + print_clf_report_per_class( |
| 72 | + clf_report_per_class, |
| 73 | + args.cell_type_mapping_file, |
| 74 | + title=f'{args.model_type.capitalize()} Performance by Cell Type' |
| 75 | + ) |
| 76 | + plot_path = os.path.join(args.output_dir, f'{args.model_type}_performance_plot.png') |
| 77 | + plt.savefig(plot_path, bbox_inches='tight', dpi=300) |
| 78 | + plt.close() |
| 79 | + print(f"\nPerformance plot saved to: {plot_path}") |
| 80 | + |
| 81 | + # Create and save detailed results dataframe |
| 82 | + print("\nCreating detailed results dataframe...") |
| 83 | + |
| 84 | + # Convert numeric indices to cell type labels |
| 85 | + cell_type_mapping_df = pd.read_parquet(args.cell_type_mapping_file) |
| 86 | + cell_type_mapping_dict = dict(zip(range(len(cell_type_mapping_df)), cell_type_mapping_df['label'])) |
| 87 | + |
| 88 | + # Create the detailed results dataframe |
| 89 | + detailed_df = pd.DataFrame({ |
| 90 | + 'y_true': [cell_type_mapping_dict[idx] for idx in y_true], |
| 91 | + 'y_pred': [cell_type_mapping_dict[idx] for idx in y_pred] |
| 92 | + }) |
| 93 | + |
| 94 | + # Add other columns from metadata |
| 95 | + detailed_df = pd.concat([detailed_df, metadata.reset_index(drop=True)], axis=1) |
| 96 | + |
| 97 | + # Add probabilities as a column |
| 98 | + detailed_df['y_probs'] = list(y_probs) |
| 99 | + |
| 100 | + # Save the detailed results |
| 101 | + detailed_path = os.path.join(args.output_dir, f'{args.model_type}_detailed_results.parquet') |
| 102 | + detailed_df.to_parquet(detailed_path, index=False) |
| 103 | + print(f"\nDetailed results saved to: {detailed_path}") |
| 104 | + |
| 105 | +def main(): |
| 106 | + """Main execution function.""" |
| 107 | + args = parse_args() |
| 108 | + |
| 109 | + print(f"\nPreparing data for {args.model_type} model evaluation...") |
| 110 | + output_folder, genes, cell_mapping = data_preparation( |
| 111 | + args.dataset_ids, |
| 112 | + args.features_file, |
| 113 | + args.var_file, |
| 114 | + args.cell_type_mapping_file, |
| 115 | + census_version=args.census_version, |
| 116 | + force_download=args.force_download, |
| 117 | + output_root=args.output_root |
| 118 | + ) |
| 119 | + |
| 120 | + print(f"\nRunning evaluation for {args.model_type} model...") |
| 121 | + results = run_model( |
| 122 | + args.model_type, |
| 123 | + args.checkpoint_path, |
| 124 | + args.hparams_file, |
| 125 | + args.cell_type_hierarchy_file, |
| 126 | + genes, |
| 127 | + cell_mapping, |
| 128 | + output_folder |
| 129 | + ) |
| 130 | + |
| 131 | + # Unpack results (now including probabilities and additional metadata) |
| 132 | + clf_report_overall, clf_report_per_class, y_probs, y_pred, y_true, metadata = results |
| 133 | + |
| 134 | + save_results(clf_report_overall, clf_report_per_class, y_probs, y_pred, y_true, metadata, cell_mapping, args) |
| 135 | + |
| 136 | +if __name__ == '__main__': |
| 137 | + main() |
0 commit comments