diff options
Diffstat (limited to 'src/plot.rs')
| -rw-r--r-- | src/plot.rs | 117 |
1 files changed, 117 insertions, 0 deletions
diff --git a/src/plot.rs b/src/plot.rs new file mode 100644 index 0000000..79edabc --- /dev/null +++ b/src/plot.rs @@ -0,0 +1,117 @@ +//! Running the plotter scripts (`scripts/plot-rqtl.py`, +//! `scripts/plot-gemma.py`) over a mapping response. +//! +//! The plotters take the **saved JSON response** of a mapping and write +//! an SVG, so this writes the envelope the compute endpoint just built to +//! a scratch file, runs the configured script over it, and hands back the +//! SVG text. Nothing is cached: a plot is cheap next to the mapping that +//! produced it, and the mapping itself is what gets cached. + +use std::path::Path; + +/// Why a plot could not be produced. +#[derive(Debug)] +pub enum PlotError { + /// Writing the response, or reading the SVG, failed. + Io(String), + /// The interpreter or script is missing, or the script failed. + Failed(String), +} + +impl std::fmt::Display for PlotError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PlotError::Io(what) => write!(f, "{what}"), + PlotError::Failed(what) => write!(f, "{what}"), + } + } +} + +/// A plot, and the one-line summary the script printed. +#[derive(Debug)] +pub struct Plot { + pub svg: String, + pub summary: String, +} + +/// Run `script` over `response` (the JSON envelope of a mapping) and +/// return the SVG it wrote. +pub async fn render( + python: &str, + script: &str, + scratch_dir: &Path, + response: &serde_json::Value, + trait_label: &str, + extra_args: &[&str], +) -> Result<Plot, PlotError> { + std::fs::create_dir_all(scratch_dir) + .map_err(|e| PlotError::Io(format!("{}: {e}", scratch_dir.display())))?; + let unique = format!( + "{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + ); + let json_path = scratch_dir.join(format!("{unique}-plot.json")); + let svg_path = scratch_dir.join(format!("{unique}-plot.svg")); + std::fs::write( + &json_path, + serde_json::to_vec(response).map_err(|e| PlotError::Io(e.to_string()))?, + ) + .map_err(|e| PlotError::Io(format!("{}: {e}", json_path.display())))?; + + let mut command = tokio::process::Command::new(python); + command + .arg(script) + .arg(&json_path) + .arg("-o") + .arg(&svg_path) + .arg("--trait") + .arg(trait_label) + .args(extra_args); + let output = command.output().await.map_err(|e| { + PlotError::Failed(format!( + "could not run {python} {script} (is the plotter configured? see PLOT_PYTHON, \ + RQTL_PLOTTER, GEMMA_PLOTTER): {e}" + )) + })?; + let summary = String::from_utf8_lossy(&output.stdout).trim().to_string(); + let svg = if output.status.success() { + std::fs::read_to_string(&svg_path) + .map_err(|e| PlotError::Io(format!("{}: {e}", svg_path.display())))? + } else { + let stderr = String::from_utf8_lossy(&output.stderr); + return Err(PlotError::Failed(format!( + "{script} failed: {}", + stderr.trim() + ))); + }; + let _ = std::fs::remove_file(&json_path); + let _ = std::fs::remove_file(&svg_path); + Ok(Plot { svg, summary }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn a_missing_script_is_a_failed_plot_not_a_panic() { + let dir = std::env::temp_dir().join(format!("gn4-plot-{}", std::process::id())); + let error = render( + "python3", + "scripts/does-not-exist.py", + &dir, + &serde_json::json!({"data": {}}), + "t", + &[], + ) + .await + .unwrap_err(); + assert!(matches!(error, PlotError::Failed(_)), "{error}"); + assert!(error.to_string().contains("failed"), "{error}"); + let _ = std::fs::remove_dir_all(&dir); + } +} |
