mod analysis;
mod gate;
mod info;
mod scans;
mod stats;
mod table;
mod trace;
pub use analysis::{
ANALYSIS_MEASURES, AnalysisMeasure, QpcrQuery, WellStatsQuery, accepted_keys, parse_options,
};
pub use gate::GateMeasure;
pub use info::{DEFAULT_INFO_FIELDS, InfoMeasure};
pub use scans::ScansMeasure;
pub use stats::{StatsMeasure, StatsPer};
pub use table::TableMeasure;
pub use trace::TraceMeasure;
use std::path::PathBuf;
use openreadout_core::model::{FileInfo, ImageInfo};
use openreadout_core::{Error, Result};
use openreadout_fcs::analysis::{
CompensationChoice, TableOptions, TransformChoice, parse_transform_spec,
};
use crate::measure::Measure;
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct MeasureSpec {
pub measure: String,
pub image: Option<u32>,
pub select: Vec<String>,
pub level: u32,
pub per: Option<String>,
pub mip: Option<String>,
pub trace: Option<u32>,
pub sweep: Option<u32>,
pub channels: Vec<u32>,
pub table: Option<u32>,
pub parameters: Vec<String>,
pub compensate: Option<String>,
pub transform: Option<String>,
pub gating_file: Option<PathBuf>,
pub sample: Option<String>,
pub populations: Vec<String>,
pub medians: Vec<String>,
pub fields: Vec<String>,
pub wells: Vec<String>,
pub options: serde_json::Map<String, serde_json::Value>,
}
#[derive(Debug, Default, serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct BuiltinOptions {
image: Option<u32>,
#[serde(default)]
select: Vec<String>,
#[serde(default)]
level: u32,
per: Option<String>,
mip: Option<String>,
trace: Option<u32>,
sweep: Option<u32>,
#[serde(default)]
channels: Vec<u32>,
table: Option<u32>,
#[serde(default)]
parameters: Vec<String>,
compensate: Option<String>,
transform: Option<String>,
workspace: Option<PathBuf>,
gatingml: Option<PathBuf>,
sample: Option<String>,
#[serde(default)]
populations: Vec<String>,
#[serde(default)]
medians: Vec<String>,
#[serde(default)]
fields: Vec<String>,
#[serde(default)]
wells: Vec<String>,
}
pub fn spec_from_options(
measure: &str,
options: serde_json::Map<String, serde_json::Value>,
) -> Result<MeasureSpec> {
if ANALYSIS_MEASURES.contains(&measure) || measure == "scans" {
return Ok(MeasureSpec {
measure: measure.to_string(),
options,
..MeasureSpec::default()
});
}
let o: BuiltinOptions = serde_json::from_value(serde_json::Value::Object(options))
.map_err(|e| Error::Usage(format!("`{measure}` options: {e}")))?;
Ok(MeasureSpec {
measure: measure.to_string(),
image: o.image,
select: o.select,
level: o.level,
per: o.per,
mip: o.mip,
trace: o.trace,
sweep: o.sweep,
channels: o.channels,
table: o.table,
parameters: o.parameters,
compensate: o.compensate,
transform: o.transform,
gating_file: o.workspace.or(o.gatingml),
sample: o.sample,
populations: o.populations,
medians: o.medians,
fields: o.fields,
wells: o.wells,
options: serde_json::Map::new(),
})
}
pub fn build(spec: &MeasureSpec) -> Result<Box<dyn Measure>> {
if spec.measure == "scans" {
return Ok(Box::new(ScansMeasure::from_options(&spec.options)?));
}
if let Some(m) = AnalysisMeasure::build(&spec.measure, &spec.options) {
return Ok(Box::new(m?));
}
if !spec.options.is_empty() {
return Err(Error::Usage(format!(
"`{}` takes no `options`; they are for {}",
spec.measure,
ANALYSIS_MEASURES.join(", ")
)));
}
if spec.measure == "stats" && matches!(spec.per.as_deref(), Some("well" | "field")) {
let mut o = serde_json::Map::new();
o.insert("select".into(), serde_json::json!(spec.select));
o.insert("wells".into(), serde_json::json!(spec.wells));
o.insert(
"per_field".into(),
serde_json::json!(spec.per.as_deref() == Some("field")),
);
o.insert("level".into(), serde_json::json!(spec.level));
return Ok(Box::new(AnalysisMeasure::well_stats(&o)?));
}
if !spec.wells.is_empty() {
return Err(Error::Usage(
"`wells` goes with stats per `well` or `field`".into(),
));
}
Ok(match spec.measure.as_str() {
"stats" => Box::new(StatsMeasure {
image: spec.image,
select: spec.select.clone(),
level: spec.level,
per: match spec.per.as_deref().unwrap_or("channel") {
"channel" => StatsPer::Channel,
"image" => StatsPer::Image,
"plane" => StatsPer::Plane,
other => {
return Err(Error::Usage(format!(
"per `{other}`: use channel, image, plane, well or field"
)));
}
},
mip: match spec.mip.as_deref() {
None => None,
Some("z" | "Z") => Some(openreadout_core::stats::Projection::Z),
Some("t" | "T") => Some(openreadout_core::stats::Projection::T),
Some(other) => {
return Err(Error::Usage(format!("mip `{other}`: use z or t")));
}
},
}),
"trace" => Box::new(TraceMeasure {
trace: spec.trace,
sweep: spec.sweep,
channels: spec.channels.clone(),
first: 0,
count: None,
x_range: None,
}),
"table" => {
let mut o = TableOptions::default();
o.gating_file = spec.gating_file.clone();
o.sample = spec.sample.clone();
o.compensation = match spec.compensate.as_deref() {
None => None,
Some("auto") => Some(CompensationChoice::Auto),
Some("fcs") => Some(CompensationChoice::File),
Some("gating") => Some(CompensationChoice::GatingFile),
Some(other) => {
return Err(Error::Usage(format!(
"compensate `{other}`: use auto, fcs or gating"
)));
}
};
o.transform = match spec.transform.as_deref() {
None => None,
Some("workspace" | "gating") => Some(TransformChoice::GatingFile),
Some(s) => Some(TransformChoice::Uniform {
transform: parse_transform_spec(s)?,
parameters: Vec::new(),
}),
};
Box::new(TableMeasure {
table: spec.table,
parameters: spec.parameters.clone(),
options_text: format!(
"{:?}{:?}{:?}",
spec.compensate, spec.transform, spec.gating_file
),
fcs: o,
})
}
"gate" => Box::new(GateMeasure {
gating_file: spec.gating_file.clone().ok_or_else(|| {
Error::Usage("gate needs a FlowJo workspace or Gating-ML file".into())
})?,
sample: spec.sample.clone(),
populations: spec.populations.clone(),
medians: spec.medians.clone(),
table: spec.table.unwrap_or(0),
}),
"info" => Box::new(InfoMeasure {
fields: spec.fields.clone(),
}),
other => {
return Err(Error::Usage(format!(
"unknown measure `{other}`: stats, trace, table, gate, info, spectra, {}",
ANALYSIS_MEASURES.join(", ")
)));
}
})
}
pub(crate) fn not_applicable(measure: &str, info: &FileInfo, what: &str, hint: &str) -> Error {
Error::unsupported(
"batch",
format!(
"`{measure}` needs {what}; this {} file has none",
info.format.name
),
hint,
)
}
pub fn image_well(im: &ImageInfo) -> Option<String> {
let from = |v: &serde_json::Value| -> Option<String> {
if let Some(s) = v.as_str() {
return crate::well::parse(s).map(crate::well::Well::name);
}
if let Some(s) = v.get("name").and_then(|n| n.as_str())
&& let Some(w) = crate::well::parse(s)
{
return Some(w.name());
}
let idx = |k: &[&str]| {
k.iter()
.find_map(|k| v.get(*k).and_then(serde_json::Value::as_u64))
};
let (r, c) = (
idx(&["row", "row_index"])?,
idx(&["column", "column_index"])?,
);
let w = crate::well::Well {
row: u32::try_from(r).ok()?,
col: u32::try_from(c).ok()?,
};
(w.row < crate::well::MAX_ROWS && w.col < crate::well::MAX_COLS).then(|| w.name())
};
im.extra.get("well").and_then(from).or_else(|| {
im.extra
.get("scene")
.and_then(|s| s.get("well"))
.and_then(from)
})
}