bio_tools 0.1.1

Install, run, and inspect computational biology and chemistry tools, e.g. AlphaFold, Boltz, RFdiffusion, and ProteinMPNN
Documentation
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
//! Installation of optional third-party biology and chemistry tools.
//!
//! The installer owns the orchestration that used to live in application-specific shell and
//! PowerShell scripts: isolated Python environments, CPU/CUDA PyTorch selection, downloads,
//! source checkouts, model assets, and post-install verification. Callers choose the outer data
//! directory and can therefore share the same recipes without sharing application-specific path
//! discovery or UI code.
//!
//! Commands are always launched directly with [`std::process::Command`]. A shell is used only when
//! an upstream project itself distributes a shell installer.

use std::{
    error::Error,
    fmt,
    path::{Path, PathBuf},
    str::FromStr,
    sync::Arc,
};

use crate::{run::CommandSpec, status};

mod alphafold3;
mod boltz2;
mod boltzgen;
mod common;
mod conda_tools;
mod igblast;
mod opendde;
mod protein_mpnn;
mod python_tools;
mod uninstall;

pub use uninstall::UninstallReport;

use crate::tool_definitions::Tool;

/// How per-tool environments and non-Python assets are laid out.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InstallLayout {
    /// Root containing source checkouts, binary distributions, and model data.
    pub tools_root: PathBuf,
    /// Root containing each isolated Python/micromamba environment.
    pub environments_root: PathBuf,
    /// Appended to a tool slug when naming its environment.
    pub environment_suffix: String,
}

impl InstallLayout {
    /// Layout used by Molchanica: `<root>/<slug>-venv` and `<root>/tools/<bundle>`.
    pub fn managed(root: impl Into<PathBuf>) -> Self {
        let root = root.into();
        Self {
            tools_root: root.join("tools"),
            environments_root: root,
            environment_suffix: "-venv".to_owned(),
        }
    }

    /// Layout used by applications that keep environments under a separate directory.
    pub fn split(tools_root: impl Into<PathBuf>, environments_root: impl Into<PathBuf>) -> Self {
        Self {
            tools_root: tools_root.into(),
            environments_root: environments_root.into(),
            environment_suffix: String::new(),
        }
    }

    /// Shared application layout: assets live directly under process_executables, while
    /// isolated Python and micromamba environments live under process_executables/python_envs.
    pub fn process_executables(root: impl Into<PathBuf>) -> Self {
        let root = root.into();
        Self::split(root.clone(), root.join("python_envs"))
    }

    pub fn environment(&self, slug: &str) -> PathBuf {
        self.environments_root
            .join(format!("{slug}{}", self.environment_suffix))
    }
}

/// Requested PyTorch wheel family.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum TorchBackendPreference {
    #[default]
    Auto,
    Cpu,
    Cuda126,
}

impl FromStr for TorchBackendPreference {
    type Err = InstallError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        match value.trim().to_ascii_lowercase().as_str() {
            "auto" => Ok(Self::Auto),
            "cpu" => Ok(Self::Cpu),
            "cuda" | "cu126" | "cuda126" => Ok(Self::Cuda126),
            _ => Err(InstallError::InvalidConfiguration(
                "the torch backend must be auto, cpu, or cu126".to_owned(),
            )),
        }
    }
}

/// Configuration shared by all installation recipes.
#[derive(Clone, Debug)]
pub struct InstallConfig {
    pub layout: InstallLayout,
    pub torch_backend: TorchBackendPreference,
    pub uv_executable: Option<PathBuf>,
    /// Only consulted by the recipes that hand control to an upstream `install.sh`; everything
    /// else resolves [`InstallConfig::micromamba_executable`] instead.
    pub conda_executable: Option<PathBuf>,
    /// Root for the managed Miniconda installation. On WSL, Conda cannot unpack environments
    /// onto a Windows-mounted filesystem because its packages contain Unix symlinks. When this is
    /// unset the installer automatically uses a per-layout directory on WSL's native filesystem.
    pub conda_root: Option<PathBuf>,
    pub micromamba_executable: Option<PathBuf>,
    /// Project/release root containing optional adapter helper scripts.
    pub support_root: Option<PathBuf>,
    pub opendde_root: Option<PathBuf>,
    pub prewarm_opendde: bool,
    pub igblast_version: String,
    pub netsolp_models_url: Option<String>,
    pub gromacs_version: String,
    pub gromacs_prefix: Option<PathBuf>,
}

impl InstallConfig {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            layout: InstallLayout::managed(root),
            torch_backend: TorchBackendPreference::Auto,
            uv_executable: None,
            conda_executable: None,
            conda_root: None,
            micromamba_executable: None,
            support_root: None,
            opendde_root: None,
            prewarm_opendde: true,
            igblast_version: "1.22.0".to_owned(),
            netsolp_models_url: None,
            gromacs_version: "2026.3".to_owned(),
            gromacs_prefix: None,
        }
    }

    /// Apply the compatibility environment variables used by the two original installers.
    pub fn apply_environment(mut self) -> Result<Self, InstallError> {
        if self.uv_executable.is_none() {
            self.uv_executable = first_env_path(&["BIO_TOOLS_UV", "MOLCHANICA_UV"]);
        }
        if self.conda_executable.is_none() {
            self.conda_executable = first_env_path(&["BIO_TOOLS_CONDA"]);
        }
        if self.conda_root.is_none() {
            self.conda_root = first_env_path(&["BIO_TOOLS_CONDA_ROOT"]);
        }
        if self.micromamba_executable.is_none() {
            self.micromamba_executable = first_env_path(&["BIO_TOOLS_MICROMAMBA"]);
        }
        if let Some(value) = first_env(&[
            "BIO_TOOLS_TORCH_BACKEND",
            "MOLCHANICA_TORCH_BACKEND",
            "BIO_WEB_TORCH_BACKEND",
        ]) {
            self.torch_backend = value.parse()?;
        }
        if self.opendde_root.is_none() {
            self.opendde_root = first_env_path(&["OPENDDE_ROOT_DIR"]);
        }
        if let Some(value) = first_env(&["IGBLAST_VERSION"]) {
            self.igblast_version = value;
        }
        if self.netsolp_models_url.is_none() {
            self.netsolp_models_url = first_env(&["NETSOLP_MODELS_URL"]);
        }
        if let Some(value) = first_env(&["GROMACS_VERSION"]) {
            self.gromacs_version = value;
        }
        if self.gromacs_prefix.is_none() {
            self.gromacs_prefix = first_env_path(&["GROMACS_INSTALL_PREFIX"]);
        }
        Ok(self)
    }
}

fn first_env(names: &[&str]) -> Option<String> {
    names
        .iter()
        .find_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty()))
}

fn first_env_path(names: &[&str]) -> Option<PathBuf> {
    first_env(names).map(PathBuf::from)
}

/// Machine-readable outcome of a tool availability probe.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum StatusKind {
    Pass,
    NotFound,
    Error,
}

/// Result returned by [Installer::status].
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ToolStatus {
    pub result: StatusKind,
    pub detail: String,
    /// GPU or CPU when the installed runtime can report it.
    pub device: Option<String>,
}

/// Progress emitted at stable tool/step boundaries.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum InstallEvent {
    ToolStarted(Tool),
    Step { tool: Tool, description: String },
    Note { tool: Option<Tool>, message: String },
    ToolFinished(Tool),
}

/// Error from a recipe or one of its direct child processes.
#[derive(Debug)]
pub enum InstallError {
    Unsupported {
        tool: Tool,
        reason: String,
    },
    InvalidConfiguration(String),
    Io {
        action: String,
        source: std::io::Error,
    },
    Command {
        command: String,
        status: Option<i32>,
    },
    Download {
        url: String,
        message: String,
    },
}

impl InstallError {
    pub(crate) fn io(action: impl Into<String>, source: std::io::Error) -> Self {
        Self::Io {
            action: action.into(),
            source,
        }
    }
}

impl fmt::Display for InstallError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unsupported { tool, reason } => write!(f, "cannot install {tool}: {reason}"),
            Self::InvalidConfiguration(message) => f.write_str(message),
            Self::Io { action, source } => write!(f, "{action}: {source}"),
            Self::Command { command, status } => match status {
                Some(code) => write!(f, "`{command}` exited with status {code}"),
                None => write!(
                    f,
                    "`{command}` was terminated before reporting an exit status"
                ),
            },
            Self::Download { url, message } => write!(f, "unable to download {url}: {message}"),
        }
    }
}

impl Error for InstallError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}

/// One failure in a multi-tool installation.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InstallFailure {
    pub tool: Tool,
    pub error: String,
}

/// Results from [`Installer::install_many`]. Each recipe is attempted independently.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct InstallReport {
    pub installed: Vec<Tool>,
    pub failed: Vec<InstallFailure>,
}

impl InstallReport {
    pub fn is_success(&self) -> bool {
        self.failed.is_empty()
    }
}

type Reporter = Arc<dyn Fn(InstallEvent) + Send + Sync>;

/// Stateful installation context. The located uv/micromamba/Conda executables and selected Torch
/// backend are cached across recipes in one run.
pub struct Installer {
    pub config: InstallConfig,
    reporter: Option<Reporter>,
    current_tool: Option<Tool>,
    uv: Option<PathBuf>,
    micromamba: Option<PathBuf>,
    conda: Option<PathBuf>,
    /// Anaconda's terms only need accepting once per run, and only on the Conda path.
    conda_terms_accepted: bool,
    torch_backend: Option<common::TorchBackend>,
}

impl Installer {
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self::from_config(InstallConfig::new(root))
    }

    /// Construct an installer using the compatibility environment variables documented by the
    /// original Molchanica and bio_web installers.
    pub fn from_environment(root: impl Into<PathBuf>) -> Result<Self, InstallError> {
        Ok(Self::from_config(
            InstallConfig::new(root).apply_environment()?,
        ))
    }
    /// Construct an installer for the shared process_executables/python_envs layout.
    pub fn for_process_executables(root: impl Into<PathBuf>) -> Result<Self, InstallError> {
        let root = root.into();
        let mut config = InstallConfig::new(&root).apply_environment()?;
        config.layout = InstallLayout::process_executables(root);
        Ok(Self::from_config(config))
    }

    pub fn from_config(config: InstallConfig) -> Self {
        Self {
            config,
            reporter: None,
            current_tool: None,
            uv: None,
            micromamba: None,
            conda: None,
            conda_terms_accepted: false,
            torch_backend: None,
        }
    }

    pub fn with_reporter(
        mut self,
        reporter: impl Fn(InstallEvent) + Send + Sync + 'static,
    ) -> Self {
        self.reporter = Some(Arc::new(reporter));
        self
    }

    pub fn environment_path(&self, tool: Tool) -> PathBuf {
        if let Some(name) = tool.conda_environment() {
            return self.conda_environment_root().join("envs").join(name);
        }
        self.config.layout.environment(tool.slug())
    }

    /// Locate a tool's installed console entry point in its managed environment.
    pub fn executable_path(&self, tool: Tool) -> PathBuf {
        self.venv_script(tool.slug(), tool.console_script())
    }
    /// Build a command for a tool's console entry point in its managed environment.
    ///
    /// The child receives `VIRTUAL_ENV` and a `PATH` whose first directory is the
    /// tool environment's scripts directory. This is equivalent to activating the
    /// environment before running its console script, and lets dependencies such
    /// as PyTorch find helper executables installed beside the script.
    pub fn tool_command(&self, tool: Tool) -> CommandSpec {
        self.with_tool_environment(tool, CommandSpec::new(self.executable_path(tool)))
    }

    /// Build a command for the managed Python interpreter of a tool.
    pub fn tool_python_command(&self, tool: Tool) -> CommandSpec {
        self.with_tool_environment(tool, CommandSpec::new(self.venv_python(tool.slug())))
    }

    fn with_tool_environment(&self, tool: Tool, command: CommandSpec) -> CommandSpec {
        let environment = self.venv_dir(tool.slug());
        let scripts = self.venv_scripts_dir(tool.slug());
        let inherited = std::env::var_os("PATH")
            .map(|path| std::env::split_paths(&path).collect::<Vec<_>>())
            .unwrap_or_default();
        let path = std::env::join_paths(std::iter::once(scripts.clone()).chain(inherited))
            .unwrap_or_else(|_| scripts.into_os_string());
        command.env("VIRTUAL_ENV", environment).env("PATH", path)
    }

    pub fn tools_root(&self) -> &Path {
        &self.config.layout.tools_root
    }

    /// Install or refresh one tool. Recipes are designed to be safely rerunnable.
    pub fn install(&mut self, tool: Tool) -> Result<(), InstallError> {
        if !tool.is_supported() {
            return Err(InstallError::Unsupported {
                tool,
                reason: "the required upstream wheels or binaries are Linux-only".to_owned(),
            });
        }

        self.current_tool = Some(tool);
        self.emit(InstallEvent::ToolStarted(tool));
        let result = match tool {
            Tool::AlphaFold3 => alphafold3::install(self),
            Tool::OpenDde => opendde::install(self),
            Tool::Boltz2 => boltz2::install(self),
            Tool::BoltzGen => boltzgen::install(self),
            Tool::ProteinMpnn => protein_mpnn::install_protein(self),
            Tool::LigandMpnn => protein_mpnn::install_ligand(self),
            Tool::IgBlast => igblast::install(self),
            Tool::HighFold
            | Tool::BindCraft
            | Tool::AntiFold
            | Tool::Germinal
            | Tool::Mber
            | Tool::Genie3
            | Tool::AggreScan3d => conda_tools::install(self, tool),
            _ => python_tools::install(self, tool),
        };
        if result.is_ok() {
            if let Err(error) = status::record_install(self, tool) {
                self.note(format!("Unable to record installation status: {error}"));
            }
            self.emit(InstallEvent::ToolFinished(tool));
        }
        self.current_tool = None;
        result
    }

    /// Inspect an installed tool without launching its application code.
    pub fn status_quick(&self, tool: Tool) -> ToolStatus {
        status::status_quick(self, tool)
    }

    /// Launch an installed tool's status probe and inspect its compute device.
    pub fn status_full(&self, tool: Tool) -> ToolStatus {
        status::status_full(self, tool)
    }

    /// Backwards-compatible alias for [`Installer::status_full`].
    pub fn status(&self, tool: Tool) -> ToolStatus {
        self.status_full(tool)
    }

    /// Quickly inspect every tool installed by this crate.
    pub fn list_quick(&self) -> Vec<(Tool, ToolStatus)> {
        status::list_quick(self)
    }

    /// Fully probe every tool installed by this crate.
    pub fn list_full(&self) -> Vec<(Tool, ToolStatus)> {
        status::list_full(self)
    }

    /// Backwards-compatible alias for [`Installer::list_full`].
    pub fn list(&self) -> Vec<(Tool, ToolStatus)> {
        self.list_full()
    }
    /// Remove one tool's environment, assets, and installation marker.
    ///
    /// Rerunnable in the same sense the recipes are: a tool that is already absent uninstalls
    /// successfully with an empty report, which is what makes this safe to offer as a button
    /// beside a status that may be a few minutes stale.
    pub fn uninstall(&mut self, tool: Tool) -> Result<UninstallReport, InstallError> {
        self.current_tool = Some(tool);
        self.emit(InstallEvent::ToolStarted(tool));
        let result = uninstall::uninstall(self, tool);
        if result.is_ok() {
            self.emit(InstallEvent::ToolFinished(tool));
        }
        self.current_tool = None;
        result
    }

    /// Install several tools without letting one broken upstream release suppress the rest.
    pub fn install_many(&mut self, tools: impl IntoIterator<Item = Tool>) -> InstallReport {
        let mut report = InstallReport::default();
        for tool in tools {
            match self.install(tool) {
                Ok(()) => report.installed.push(tool),
                Err(error) => report.failed.push(InstallFailure {
                    tool,
                    error: error.to_string(),
                }),
            }
        }
        report
    }

    pub(crate) fn step(&self, description: impl Into<String>) {
        if let Some(tool) = self.current_tool {
            self.emit(InstallEvent::Step {
                tool,
                description: description.into(),
            });
        }
    }

    pub(crate) fn note(&self, message: impl Into<String>) {
        self.emit(InstallEvent::Note {
            tool: self.current_tool,
            message: message.into(),
        });
    }

    fn emit(&self, event: InstallEvent) {
        if let Some(reporter) = &self.reporter {
            reporter(event);
            return;
        }
        match event {
            InstallEvent::ToolStarted(tool) => println!("\n{tool}\n{}", "=".repeat(56)),
            InstallEvent::Step { description, .. } => println!("  {description}"),
            InstallEvent::Note { message, .. } => println!("  {message}"),
            InstallEvent::ToolFinished(_) => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tool_command_activates_its_managed_environment() {
        let installer = Installer::new("managed-root");
        let command = installer.tool_command(Tool::OpenDde);
        assert_eq!(
            command.environment.get(std::ffi::OsStr::new("VIRTUAL_ENV")),
            Some(&installer.venv_dir(Tool::OpenDde.slug()).into_os_string())
        );
        let path = command
            .environment
            .get(std::ffi::OsStr::new("PATH"))
            .unwrap();
        assert_eq!(
            std::env::split_paths(path).next(),
            Some(installer.venv_scripts_dir(Tool::OpenDde.slug()))
        );
    }
    #[test]
    fn all_tools_contains_no_duplicates() {
        let unique: std::collections::HashSet<_> = Tool::ALL.into_iter().collect();
        assert_eq!(unique.len(), Tool::ALL.len());
    }
    #[test]
    fn every_tool_round_trips_through_its_slug() {
        for tool in Tool::ALL {
            assert_eq!(tool.slug().parse::<Tool>().unwrap(), tool);
            assert_eq!(tool.name().parse::<Tool>().unwrap(), tool);
        }
    }

    #[test]
    fn split_and_managed_layouts_are_explicit() {
        let managed = InstallLayout::managed("/data/app");
        assert_eq!(
            managed.environment("boltz2"),
            Path::new("/data/app/boltz2-venv")
        );
        assert_eq!(managed.tools_root, Path::new("/data/app/tools"));

        let split = InstallLayout::split("/data/tools", "/data/envs");
        assert_eq!(split.environment("boltz2"), Path::new("/data/envs/boltz2"));
    }

    #[test]
    fn named_conda_environment_uses_the_configured_conda_root() {
        let mut config = InstallConfig::new("/data/app");
        config.layout = InstallLayout::split("/data/tools", "/data/envs");
        config.conda_root = Some(PathBuf::from("/native/conda"));
        let installer = Installer::from_config(config);

        assert_eq!(
            installer.environment_path(Tool::BindCraft),
            Path::new("/native/conda/envs/BindCraft")
        );
        assert_eq!(
            installer.environment_path(Tool::Genie3),
            Path::new("/native/conda/envs/genie3")
        );
        assert_eq!(
            installer.environment_path(Tool::Boltz2),
            Path::new("/data/envs/boltz2")
        );

        let mut external = InstallConfig::new("/data/app");
        external.conda_executable = Some(PathBuf::from("/opt/miniconda/bin/conda"));
        let installer = Installer::from_config(external);
        assert_eq!(
            installer.environment_path(Tool::Genie3),
            Path::new("/opt/miniconda/envs/genie3")
        );
    }

    #[test]
    fn consumer_aliases_parse_to_the_canonical_tool() {
        assert_eq!("boltz".parse::<Tool>().unwrap(), Tool::Boltz2);
        assert_eq!("esmfold".parse::<Tool>().unwrap(), Tool::EsmFold2);
        assert_eq!("antibody_annotator".parse::<Tool>().unwrap(), Tool::Anarcii);
        assert_eq!("AbMPNN".parse::<Tool>().unwrap(), Tool::ProteinMpnn);
    }
}