genopick 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
genopick/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """genopick: Genomic Selection Model Benchmarking CLI for Plant Breeding."""
2
+
3
+ __version__ = "0.3.0"
genopick/cli.py ADDED
@@ -0,0 +1,230 @@
1
+ """Command-line interface for genopick."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import shutil
6
+ import sys
7
+ from enum import Enum
8
+ import warnings
9
+ from pathlib import Path
10
+
11
+ import typer
12
+ from rich.console import Console
13
+ from rich.markup import escape
14
+ from rich.table import Table
15
+
16
+ from genopick import __version__
17
+ from genopick.crossval import BenchmarkResult, benchmark
18
+ from genopick.io import align_data, read_genotype, read_phenotype
19
+ from genopick.models import (
20
+ AVAILABLE_MODELS,
21
+ MODEL_ALIASES,
22
+ MODEL_NOTES,
23
+ get_available_models,
24
+ get_models,
25
+ )
26
+ from genopick.preprocess import preprocess_pipeline
27
+ from genopick.report import generate_report
28
+
29
+ app = typer.Typer(help="genopick: Genomic Selection Model Benchmarking CLI for Plant Breeding")
30
+ console = Console()
31
+
32
+ _DATA_DIR = Path(__file__).parent / "data"
33
+
34
+
35
+ class ImputeMethod(str, Enum):
36
+ mean = "mean"
37
+ median = "median"
38
+
39
+
40
+ class ScaleMethod(str, Enum):
41
+ center = "center"
42
+ standardize = "standardize"
43
+ none = "none"
44
+
45
+
46
+ class GenotypeFormat(str, Enum):
47
+ auto = "auto"
48
+ csv = "csv"
49
+ tsv = "tsv"
50
+ hapmap = "hapmap"
51
+ numeric = "numeric"
52
+
53
+
54
+ @app.command()
55
+ def run(
56
+ geno: Path = typer.Argument(..., exists=True, readable=True, help="Genotype file"),
57
+ pheno: Path = typer.Argument(..., exists=True, readable=True, help="Phenotype file"),
58
+ trait: str = typer.Option(..., help="Trait column name"),
59
+ models: str = typer.Option("all", help="Models: all or comma-separated"),
60
+ folds: int = typer.Option(5, help="Number of CV folds"),
61
+ repeats: int = typer.Option(1, help="Number of CV repeats"),
62
+ maf: float = typer.Option(0.05, help="MAF filter threshold"),
63
+ max_missing: float = typer.Option(0.2, help="Max missingness threshold"),
64
+ impute: ImputeMethod = typer.Option(ImputeMethod.mean, help="Imputation method"),
65
+ scale: ScaleMethod = typer.Option(ScaleMethod.center, help="Genotype scaling"),
66
+ output: Path = typer.Option("genopick_output", help="Output directory"),
67
+ seed: int = typer.Option(42, help="Random seed"),
68
+ format: GenotypeFormat = typer.Option(GenotypeFormat.auto, help="Genotype file format"),
69
+ ) -> None:
70
+ """Benchmark genomic selection models on your genotype/phenotype data."""
71
+ console.print(f"[bold cyan]genopick v{__version__}[/bold cyan]")
72
+
73
+ # 1. Read data
74
+ console.rule("[bold]Step 1: Loading Data")
75
+ geno_dict = read_genotype(geno, format=format.value)
76
+ pheno_df = read_phenotype(pheno, trait=trait)
77
+
78
+ # 2. Align samples
79
+ console.rule("[bold]Step 2: Aligning Samples")
80
+ try:
81
+ X, y, _sample_ids = align_data(geno_dict, pheno_df, trait)
82
+ except ValueError as exc:
83
+ _fail(str(exc))
84
+ console.print(f"Aligned dataset: {X.shape[0]} samples x {X.shape[1]} markers")
85
+
86
+ # 3. Preprocess
87
+ console.rule("[bold]Step 3: Preprocessing")
88
+ try:
89
+ prep = preprocess_pipeline(
90
+ X,
91
+ geno_dict["markers"],
92
+ maf=maf,
93
+ max_missing=max_missing,
94
+ impute=impute.value,
95
+ scale=scale.value,
96
+ )
97
+ except ValueError as exc:
98
+ _fail(str(exc))
99
+ X_processed = prep["X_processed"]
100
+ console.print(
101
+ f"Removed {prep['n_removed']} marker(s); "
102
+ f"{prep['preprocessing_summary']['n_markers_output']} remaining"
103
+ )
104
+
105
+ # 4. Get models
106
+ console.rule("[bold]Step 4: Selecting Models")
107
+ model_names = models if models == "all" else [m.strip() for m in models.split(",")]
108
+ with warnings.catch_warnings(record=True) as caught:
109
+ warnings.simplefilter("always", UserWarning)
110
+ model_list = get_models(model_names)
111
+ for warning in caught:
112
+ console.print(f"[yellow]Warning: {escape(str(warning.message))}[/yellow]")
113
+ if not model_list:
114
+ console.print("[red]No models available. Check installation or --models value.[/red]")
115
+ raise typer.Exit(code=1)
116
+ console.print(f"Models: {', '.join(m.abbreviation for m in model_list)}")
117
+
118
+ # 5. Run benchmark
119
+ console.rule("[bold]Step 5: Cross-Validating")
120
+ result = benchmark(
121
+ X_processed,
122
+ y,
123
+ model_list,
124
+ n_folds=folds,
125
+ n_repeats=repeats,
126
+ random_state=seed,
127
+ verbose=True,
128
+ trait_name=trait,
129
+ preprocessing_summary=prep["preprocessing_summary"],
130
+ )
131
+
132
+ # 6. Generate report
133
+ console.rule("[bold]Step 6: Generating Report")
134
+ report_dir = generate_report(result, str(output), title=f"genopick Report: {trait}")
135
+ console.print(f"[green]Report written to {report_dir / 'report.html'}[/green]")
136
+
137
+ # 7. Print summary to console
138
+ console.rule("[bold]Step 7: Summary")
139
+ _print_final_summary(result)
140
+
141
+
142
+ def _fail(message: str) -> None:
143
+ """Print an error message and exit with status 1 (no traceback)."""
144
+ console.print(f"[red]Error: {escape(message)}[/red]")
145
+ raise typer.Exit(code=1)
146
+
147
+
148
+ def _print_final_summary(result: BenchmarkResult) -> None:
149
+ table = Table(title="Final Summary")
150
+ table.add_column("Model", style="bold")
151
+ table.add_column("r", justify="right")
152
+ table.add_column("Spearman", justify="right")
153
+ table.add_column("RMSE", justify="right")
154
+ table.add_column("Time (s)", justify="right")
155
+
156
+ for cv_result in result.results:
157
+ m = cv_result.mean_metrics
158
+ table.add_row(
159
+ cv_result.model_abbreviation,
160
+ f"{m.get('r', float('nan')):.3f}",
161
+ f"{m.get('spearman', float('nan')):.3f}",
162
+ f"{m.get('rmse', float('nan')):.3f}",
163
+ f"{cv_result.total_time_seconds:.2f}",
164
+ )
165
+
166
+ console.print(table)
167
+
168
+
169
+ @app.command()
170
+ def list_models() -> None:
171
+ """Print available genomic selection models in a table."""
172
+ installed = set(get_available_models())
173
+
174
+ table = Table(title="Available Models")
175
+ table.add_column("Abbreviation", style="bold")
176
+ table.add_column("Name")
177
+ table.add_column("Status")
178
+ table.add_column("Notes")
179
+
180
+ def status(abbr: str) -> str:
181
+ return "[green]installed[/green]" if abbr in installed else "[yellow]requires extra[/yellow]"
182
+
183
+ for abbr, cls in AVAILABLE_MODELS.items():
184
+ table.add_row(abbr, cls.name, status(abbr), MODEL_NOTES.get(abbr, ""))
185
+ for alias, target in MODEL_ALIASES.items():
186
+ table.add_row(alias, f"= {target}", status(target), MODEL_NOTES.get(alias, ""))
187
+
188
+ console.print(table)
189
+ console.print("Install optional models: [bold]pip install genopick\\[full][/bold]")
190
+
191
+
192
+ @app.command()
193
+ def example(
194
+ output: Path = typer.Option(Path("."), help="Directory to copy the example dataset into"),
195
+ ) -> None:
196
+ """Copy the bundled example genotype/phenotype dataset to a local directory."""
197
+ output.mkdir(parents=True, exist_ok=True)
198
+
199
+ geno_dest = output / "example_geno.csv"
200
+ pheno_dest = output / "example_pheno.csv"
201
+ shutil.copyfile(_DATA_DIR / "example_geno.csv", geno_dest)
202
+ shutil.copyfile(_DATA_DIR / "example_pheno.csv", pheno_dest)
203
+
204
+ console.print(f"[green]Example dataset copied to {output}[/green]")
205
+ console.print(f" {geno_dest}")
206
+ console.print(f" {pheno_dest}")
207
+ console.print("\nRun the benchmark with:\n")
208
+ console.print(
209
+ f" genopick run {geno_dest} {pheno_dest} --trait yield --models GBLUP,RKHS,RF --folds 5"
210
+ )
211
+
212
+
213
+ def main() -> None:
214
+ app()
215
+
216
+
217
+ GSBENCH_DEPRECATION = (
218
+ "Warning: the 'gsbench' command is deprecated because gsbench was renamed to genopick. "
219
+ "Use 'genopick' instead; 'gsbench' will be removed in the next release."
220
+ )
221
+
222
+
223
+ def gsbench_alias() -> None:
224
+ """Entry point of the deprecated ``gsbench`` command: warn on stderr, then run genopick."""
225
+ print(GSBENCH_DEPRECATION, file=sys.stderr)
226
+ app()
227
+
228
+
229
+ if __name__ == "__main__":
230
+ main()
genopick/crossval.py ADDED
@@ -0,0 +1,177 @@
1
+ """Cross-validated benchmarking of genomic selection models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass, field
7
+
8
+ import numpy as np
9
+ from rich.console import Console
10
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeElapsedColumn
11
+ from rich.table import Table
12
+ from sklearn.model_selection import KFold, RepeatedKFold
13
+
14
+ from genopick.metrics import compute_metrics
15
+
16
+ console = Console()
17
+
18
+
19
+ @dataclass
20
+ class CVResult:
21
+ model_name: str
22
+ model_abbreviation: str
23
+ per_fold_metrics: list = field(default_factory=list)
24
+ mean_metrics: dict = field(default_factory=dict)
25
+ total_time_seconds: float = 0.0
26
+ predictions: dict = field(default_factory=dict)
27
+
28
+
29
+ @dataclass
30
+ class BenchmarkResult:
31
+ results: list = field(default_factory=list)
32
+ trait_name: str = ""
33
+ n_samples: int = 0
34
+ n_markers: int = 0
35
+ preprocessing_summary: dict = field(default_factory=dict)
36
+
37
+
38
+ def cross_validate(
39
+ X,
40
+ y,
41
+ model,
42
+ n_folds: int = 5,
43
+ n_repeats: int = 1,
44
+ random_state: int = 42,
45
+ verbose: bool = True,
46
+ ) -> CVResult:
47
+ """Run (repeated) k-fold cross-validation for a single model.
48
+
49
+ Returns a CVResult with per-fold and mean metrics, total wall-clock
50
+ time, and out-of-fold predictions keyed by original sample index. With
51
+ n_repeats > 1 each sample is predicted once per repeat, and its stored
52
+ prediction is the mean across repeats.
53
+ """
54
+ X = np.asarray(X, dtype=float)
55
+ y = np.asarray(y, dtype=float)
56
+
57
+ if n_repeats > 1:
58
+ splitter = RepeatedKFold(n_splits=n_folds, n_repeats=n_repeats, random_state=random_state)
59
+ n_total_folds = n_folds * n_repeats
60
+ else:
61
+ splitter = KFold(n_splits=n_folds, shuffle=True, random_state=random_state)
62
+ n_total_folds = n_folds
63
+
64
+ model_name = getattr(model, "name", model.__class__.__name__)
65
+ model_abbreviation = getattr(model, "abbreviation", model.__class__.__name__)
66
+
67
+ per_fold_metrics = []
68
+ pred_sums = np.zeros(len(y))
69
+ pred_counts = np.zeros(len(y), dtype=int)
70
+
71
+ with Progress(
72
+ SpinnerColumn(),
73
+ TextColumn("[progress.description]{task.description}"),
74
+ BarColumn(),
75
+ TextColumn("{task.completed}/{task.total} folds"),
76
+ TimeElapsedColumn(),
77
+ console=console,
78
+ disable=not verbose,
79
+ ) as progress:
80
+ task = progress.add_task(f"CV: {model_abbreviation}", total=n_total_folds)
81
+
82
+ start_time = time.perf_counter()
83
+ for train_idx, test_idx in splitter.split(X):
84
+ X_train, X_test = X[train_idx], X[test_idx]
85
+ y_train, y_test = y[train_idx], y[test_idx]
86
+
87
+ model.fit(X_train, y_train)
88
+ y_pred = np.asarray(model.predict(X_test), dtype=float)
89
+
90
+ per_fold_metrics.append(compute_metrics(y_test, y_pred))
91
+ pred_sums[test_idx] += y_pred
92
+ pred_counts[test_idx] += 1
93
+
94
+ progress.advance(task)
95
+ total_time_seconds = time.perf_counter() - start_time
96
+
97
+ predictions = {
98
+ int(idx): (float(y[idx]), float(pred_sums[idx] / pred_counts[idx]))
99
+ for idx in np.flatnonzero(pred_counts)
100
+ }
101
+
102
+ metric_keys = per_fold_metrics[0].keys()
103
+ mean_metrics = {
104
+ key: float(np.nanmean([fold[key] for fold in per_fold_metrics])) for key in metric_keys
105
+ }
106
+
107
+ return CVResult(
108
+ model_name=model_name,
109
+ model_abbreviation=model_abbreviation,
110
+ per_fold_metrics=per_fold_metrics,
111
+ mean_metrics=mean_metrics,
112
+ total_time_seconds=total_time_seconds,
113
+ predictions=predictions,
114
+ )
115
+
116
+
117
+ def benchmark(
118
+ X,
119
+ y,
120
+ models,
121
+ n_folds: int = 5,
122
+ n_repeats: int = 1,
123
+ random_state: int = 42,
124
+ verbose: bool = True,
125
+ trait_name: str = "",
126
+ preprocessing_summary: dict | None = None,
127
+ ) -> BenchmarkResult:
128
+ """Cross-validate each model in `models` and print a comparison table."""
129
+ X = np.asarray(X, dtype=float)
130
+ results = [
131
+ cross_validate(
132
+ X,
133
+ y,
134
+ model,
135
+ n_folds=n_folds,
136
+ n_repeats=n_repeats,
137
+ random_state=random_state,
138
+ verbose=verbose,
139
+ )
140
+ for model in models
141
+ ]
142
+
143
+ if verbose:
144
+ _print_summary_table(results)
145
+
146
+ return BenchmarkResult(
147
+ results=results,
148
+ trait_name=trait_name,
149
+ n_samples=X.shape[0],
150
+ n_markers=X.shape[1],
151
+ preprocessing_summary=preprocessing_summary or {},
152
+ )
153
+
154
+
155
+ def _print_summary_table(results: list) -> None:
156
+ table = Table(title="genopick Model Comparison")
157
+ table.add_column("Model", style="bold")
158
+ table.add_column("r", justify="right")
159
+ table.add_column("r2", justify="right")
160
+ table.add_column("RMSE", justify="right")
161
+ table.add_column("MAE", justify="right")
162
+ table.add_column("Spearman", justify="right")
163
+ table.add_column("Time (s)", justify="right")
164
+
165
+ for result in results:
166
+ m = result.mean_metrics
167
+ table.add_row(
168
+ result.model_abbreviation,
169
+ f"{m['r']:.3f}",
170
+ f"{m['r2']:.3f}",
171
+ f"{m['rmse']:.3f}",
172
+ f"{m['mae']:.3f}",
173
+ f"{m['spearman']:.3f}",
174
+ f"{result.total_time_seconds:.2f}",
175
+ )
176
+
177
+ console.print(table)