space_trav_lr_rust 1.3.0

Spatial gene regulatory network inference and in-silico perturbation (Rust port of SpaceTravLR)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use clap::Parser;
use space_trav_lr_rust::betadata::write_betadata_feather;
use space_trav_lr_rust::perturb::{PerturbTarget, PerturbTimings, perturb_with_targets};
use space_trav_lr_rust::perturb_batch::{
    PerturbBatchFile, batch_from_perturb_table, effective_parallelism, expand_prepared_jobs,
    load_batch_file, load_perturb_cli_toml, resolve_effective_run_toml,
    resolve_prepared_job_cell_indices, run_batch_jobs, validate_jobs_genes,
};
use space_trav_lr_rust::config::expand_user_path;
use space_trav_lr_rust::perturb_mode::{PerturbRuntime, parse_obs_columns_csv, validate_perturb_simulated_matrix};
#[cfg(not(feature = "tui"))]
use space_trav_lr_rust::perturb_mode::{interactive_run_toml_prompt, run_interactive};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

#[derive(Parser, Debug)]
#[command(
    name = "spacetravlr-perturb",
    version,
    about = "SpaceTravLR perturbation: Ratatui UI (default) or --export/--out batch mode or --batch-toml. Same run TOML + betadata loading model as spatial_viewer.",
    after_long_help = r#"Use --config PATH (or pass PATH as the first argument) for a single TOML: `run_toml` (path to spacetravlr_run_repro.toml) plus optional `[data]` / `[perturbation]` / … sections that override the repro file. `--run-toml` overrides `run_toml` in that file when both are set.

Batch mode (fully non-interactive) uses --export PATH or --out PATH (same flag), or --batch-toml PATH for many single-gene jobs. Batch keys can live in --config instead of a separate batch file.

Single-job batch: requires a repro TOML (--run-toml or run_toml in --config), --gene, --export/--out. Optional: --desired-expr (default 0), --n-propagation, --cells-csv + --cells-csv-column, --verbose.

Batch TOML: repro path + --batch-toml (gene lists, zips, out_dir or out; parallelism inside the file or --batch-parallelism). Do not combine with --gene, --export/--out, or --cells-*.

Example:
  spacetravlr-perturb \
    --run-toml /path/to/spacetravlr_run_repro.toml \
    --out /tmp/simulated.feather \
    --gene SOX2 \
    --desired-expr 0 \
    --n-propagation 4 \
    --cells-csv /path/to/cells.csv \
    --cells-csv-column selected \
    --verbose

If --cells-csv is set, --cells-csv-column is required in single-job batch mode."#
)]
struct Cli {
    #[arg(
        long = "config",
        visible_alias = "perturb-toml",
        value_name = "PATH",
        help = "Perturbation TOML: `run_toml`, optional section overrides vs. repro, optional batch/job fields. See --help long help."
    )]
    config: Option<PathBuf>,

    #[arg(
        index = 1,
        value_name = "CONFIG",
        help = "Same as --config."
    )]
    config_positional: Option<PathBuf>,

    #[arg(
        long = "run-toml",
        value_name = "PATH",
        help = "Path to spacetravlr_run_repro.toml. Overrides run_toml in --config. If omitted and not in --config: TUI prompts; without TUI, stdin prompt."
    )]
    run_toml: Option<PathBuf>,

    #[arg(
        long = "export",
        visible_alias = "out",
        value_name = "PATH",
        help = "Write simulated expression as feather (rows = cells, columns = CellID + genes); exit. Same as --out. Requires --gene and a repro path (--run-toml and/or run_toml in --config); not for multi-job batch."
    )]
    export: Option<PathBuf>,

    #[arg(
        long = "gene",
        help = "Gene to perturb (single-job --export / --out). For multi-job output, use batch keys in --config or --batch-toml."
    )]
    gene: Option<String>,

    #[arg(
        long = "desired-expr",
        default_value_t = 0.0,
        help = "Batch: target expression. TUI: initial desired_expr."
    )]
    desired_expr: f64,

    #[arg(
        long = "n-propagation",
        help = "Override [perturbation].n_propagation from the TOML (batch or TUI initial value)."
    )]
    n_propagation: Option<usize>,

    #[arg(
        long,
        help = "Batch: print load and perturb timings (stderr). TUI: start with per-step timings (toggle Ctrl+V)."
    )]
    verbose: bool,

    #[arg(
        long = "cells-csv",
        value_name = "PATH",
        help = "Optional CSV (header row); each column lists obs_names from AnnData. TUI: pick column with Ctrl+O. Batch: if set, requires --cells-csv-column."
    )]
    cells_csv: Option<PathBuf>,

    #[arg(
        long = "cells-csv-column",
        value_name = "NAME",
        help = "Column name in --cells-csv (required in single-job batch mode when --cells-csv is set)."
    )]
    cells_csv_column: Option<String>,

    #[arg(
        long = "batch-toml",
        value_name = "PATH",
        help = "Batch perturbation spec (TOML): multiple single-gene runs with shared runtime load. Needs repro path (--run-toml or run_toml in --config). Incompatible with batch keys inside --config, --gene, --export/--out, --cells-csv/--cells-csv-column."
    )]
    batch_toml: Option<PathBuf>,

    #[arg(
        long = "batch-parallelism",
        value_name = "N",
        help = "Override batch TOML parallelism (max concurrent perturb threads)."
    )]
    batch_parallelism: Option<usize>,
}

fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();

    let perturb_config_path = cli.config.clone().or(cli.config_positional.clone());
    let parsed_opt = if let Some(ref p) = perturb_config_path {
        Some(load_perturb_cli_toml(p)?)
    } else {
        None
    };
    let overlay_ref: Option<&toml::Value> = parsed_opt.as_ref().map(|p| &p.overlay_source);

    let run_batch_branch = |batch_file: PerturbBatchFile,
                            batch_parent: &Path,
                            run_toml_eff: PathBuf|
     -> anyhow::Result<()> {
        if cli.export.is_some() {
            anyhow::bail!(
                "--export/--out cannot be used in multi-job batch mode (outputs come from the batch spec)."
            );
        }
        if cli.gene.is_some() {
            anyhow::bail!("--gene cannot be used in batch mode.");
        }
        if cli.cells_csv.is_some() || cli.cells_csv_column.is_some() {
            anyhow::bail!(
                "--cells-csv / --cells-csv-column cannot be used in batch mode (set cells in the batch TOML if needed)."
            );
        }
        let t_load = Instant::now();
        let mut runtime =
            PerturbRuntime::from_run_toml_with_config_overlay(run_toml_eff.as_path(), overlay_ref)?;
        let load_elapsed = t_load.elapsed();
        let default_n_prop = if let Some(n) = cli.n_propagation {
            runtime.perturb_cfg.n_propagation = n;
            n
        } else {
            runtime.perturb_cfg.n_propagation
        };

        let mut jobs = expand_prepared_jobs(&batch_file, batch_parent, default_n_prop)?;
        validate_jobs_genes(&jobs, &runtime.gene_names)?;
        resolve_prepared_job_cell_indices(
            &batch_file,
            batch_parent,
            &runtime.obs_names,
            &mut jobs,
        )?;

        let parallelism = effective_parallelism(batch_file.parallelism, cli.batch_parallelism);
        let rt = Arc::new(runtime);
        let t_batch = Instant::now();
        run_batch_jobs(Arc::clone(&rt), jobs, parallelism, cli.verbose)?;
        let batch_elapsed = t_batch.elapsed();
        if cli.verbose {
            eprintln!("--- spacetravlr-perturb batch timings ---");
            eprintln!("  load_runtime: {load_elapsed:?}");
            eprintln!("  perturb_batch_total: {batch_elapsed:?}");
        }
        Ok(())
    };

    if let Some(batch_path) = cli.batch_toml.as_ref() {
        if parsed_opt
            .as_ref()
            .and_then(|p| p.batch_table.as_ref())
            .is_some()
        {
            anyhow::bail!("do not combine --batch-toml with batch/job keys (gene, out, …) inside --config");
        }
        let run_toml_eff = resolve_effective_run_toml(
            cli.run_toml.clone(),
            parsed_opt.as_ref().and_then(|p| p.run_toml.clone()),
            perturb_config_path.as_deref(),
        )?;
        let batch_file = load_batch_file(batch_path.as_path())?;
        let batch_parent = batch_path
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        return run_batch_branch(batch_file, batch_parent, run_toml_eff);
    }

    if let Some(tbl) = parsed_opt.as_ref().and_then(|p| p.batch_table.as_ref()) {
        let run_toml_eff = resolve_effective_run_toml(
            cli.run_toml.clone(),
            parsed_opt.as_ref().and_then(|p| p.run_toml.clone()),
            perturb_config_path.as_deref(),
        )?;
        let batch_file = batch_from_perturb_table(tbl)?;
        let batch_parent = perturb_config_path
            .as_ref()
            .and_then(|p| p.parent())
            .filter(|p| !p.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        return run_batch_branch(batch_file, batch_parent, run_toml_eff);
    }

    let run_for_interactive = cli
        .run_toml
        .clone()
        .or_else(|| parsed_opt.as_ref().and_then(|p| p.run_toml.clone()));

    if cli.export.is_none() {
        #[cfg(feature = "tui")]
        {
            let opts = space_trav_lr_rust::perturb_tui::PerturbTuiOptions {
                run_toml: run_for_interactive.clone(),
                default_desired_expr: cli.desired_expr,
                n_propagation_initial: cli.n_propagation,
                verbose: cli.verbose,
                toml_path_hint_for_error: run_for_interactive
                    .as_ref()
                    .map(|p| p.display().to_string()),
                cells_csv: cli.cells_csv.clone(),
                cells_csv_column: cli.cells_csv_column.clone(),
                config_merge_overlay: parsed_opt
                    .as_ref()
                    .map(|p| p.overlay_source.clone()),
            };
            let rt = tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .build()?;
            return rt.block_on(space_trav_lr_rust::perturb_tui::run(opts));
        }
        #[cfg(not(feature = "tui"))]
        {
            let run_toml = match run_for_interactive {
                Some(p) => p,
                None => interactive_run_toml_prompt()?,
            };
            let mut runtime = PerturbRuntime::from_run_toml_with_config_overlay(
                run_toml.as_path(),
                overlay_ref,
            )?;
            if let Some(n) = cli.n_propagation {
                runtime.perturb_cfg.n_propagation = n;
            }
            return run_interactive(runtime);
        }
    }

    let run_toml = resolve_effective_run_toml(
        cli.run_toml.clone(),
        parsed_opt.as_ref().and_then(|p| p.run_toml.clone()),
        perturb_config_path.as_deref(),
    )?;

    let export_path = cli.export.as_ref().unwrap();
    let gene = cli
        .gene
        .as_deref()
        .ok_or_else(|| anyhow::anyhow!("--gene is required with --export / --out"))?;
    let t_load = Instant::now();
    let mut runtime = PerturbRuntime::from_run_toml_with_config_overlay(run_toml.as_path(), overlay_ref)?;
    let load_elapsed = t_load.elapsed();
    if let Some(n) = cli.n_propagation {
        runtime.perturb_cfg.n_propagation = n;
    }
    if !runtime.gene_names.iter().any(|g| g == gene) {
        anyhow::bail!("Gene '{}' is not present in AnnData var_names.", gene);
    }

    let run_parent = run_toml
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));

    let mut csv_path = cli.cells_csv.clone();
    let mut csv_column = cli.cells_csv_column.clone();
    if csv_path.is_none() && csv_column.is_none() {
        if let Some(ref rel) = runtime.cfg.perturbation.cells_csv {
            if !rel.trim().is_empty() {
                let exp = expand_user_path(rel.trim());
                let pb = Path::new(&exp);
                csv_path = Some(if pb.is_absolute() {
                    pb.to_path_buf()
                } else {
                    run_parent.join(pb)
                });
                csv_column = runtime.cfg.perturbation.cells_csv_column.clone();
            }
        }
    } else if csv_path.is_some() && csv_column.is_none() {
        csv_column = runtime.cfg.perturbation.cells_csv_column.clone();
    }

    if csv_path.is_some() && csv_column.is_none() {
        anyhow::bail!(
            "cells CSV column missing: use --cells-csv-column or set [perturbation].cells_csv_column in the run TOML"
        );
    }

    let cell_indices_batch = match (&csv_path, &csv_column) {
        (Some(csv_path), Some(col)) => {
            let parsed = parse_obs_columns_csv(csv_path.as_path(), &runtime.obs_names)?;
            let sl = parsed.indices_for_column(col.as_str()).ok_or_else(|| {
                anyhow::anyhow!("cells_csv column {:?} not found in CSV header", col)
            })?;
            Some(sl.to_vec())
        }
        (None, None) => None,
        _ => anyhow::bail!("internal: inconsistent cells CSV path / column state"),
    };

    let targets = vec![PerturbTarget {
        gene: gene.to_string(),
        desired_expr: cli.desired_expr,
        cell_indices: cell_indices_batch,
    }];
    let mut timings: Option<PerturbTimings> = if cli.verbose {
        Some(PerturbTimings::default())
    } else {
        None
    };
    let t_perturb = Instant::now();
    let result = perturb_with_targets(
        &runtime.bb,
        &runtime.gene_mtx,
        &runtime.gene_names,
        &runtime.xy,
        &runtime.rw_ligands_init,
        &runtime.rw_tfligands_init,
        &targets,
        &runtime.perturb_cfg,
        &runtime.lr_radii,
        None,
        None,
        None,
        Some(&runtime.baseline_splash_cache),
        &mut timings,
    )
    .map_err(|_| anyhow::anyhow!("perturbation failed"))?;
    validate_perturb_simulated_matrix(
        &runtime.gene_mtx,
        &runtime.gene_names,
        &result.simulated,
        gene,
        cli.desired_expr,
        targets[0].cell_indices.as_deref(),
    )?;
    let perturb_elapsed = t_perturb.elapsed();
    let p = export_path
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("export path must be UTF-8"))?;
    write_betadata_feather(
        p,
        "CellID",
        &runtime.obs_names,
        &runtime.gene_names,
        &result.simulated,
    )?;
    eprintln!(
        "Wrote {} ({} cells × {} genes, n_propagation={})",
        export_path.display(),
        runtime.obs_names.len(),
        runtime.gene_names.len(),
        runtime.perturb_cfg.n_propagation
    );
    if cli.verbose {
        eprintln!("--- spacetravlr-perturb timings ---");
        eprintln!("  load_runtime (PerturbRuntime::from_run_toml): {load_elapsed:?}");
        eprintln!("  perturb_total (perturb_with_targets): {perturb_elapsed:?}");
        if let Some(t) = timings.as_ref() {
            eprintln!("  per-step (within propagation loop):");
            for (label, d) in &t.entries {
                eprintln!("    {label}: {d:?}");
            }
            let sum_suffix = |suf: &str| -> Duration {
                t.entries
                    .iter()
                    .filter(|(k, _)| k.ends_with(suf))
                    .map(|(_, d)| *d)
                    .sum()
            };
            eprintln!("  sums over iterations:");
            eprintln!("    splash: {:?}", sum_suffix("/splash"));
            eprintln!(
                "    weighted_ligands_lr: {:?}",
                sum_suffix("/weighted_ligands_lr")
            );
            eprintln!(
                "    weighted_ligands_tfl: {:?}",
                sum_suffix("/weighted_ligands_tfl")
            );
            eprintln!("    grn_propagate: {:?}", sum_suffix("/grn_propagate"));
            eprintln!("    pin_nonneg: {:?}", sum_suffix("/pin_nonneg"));
        }
    }
    Ok(())
}