diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-15 12:01:03 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-15 12:01:03 +0000 |
| commit | 6de7a3440048f870463f0c4ceb6efa86dc2d57da (patch) | |
| tree | 19974a597b08c82907e78d032e110a1147b69fae /src | |
| parent | ba9016c729c020a62cb2b4481214a19f5e027ba6 (diff) | |
| download | genenetwork4-6de7a3440048f870463f0c4ceb6efa86dc2d57da.tar.gz | |
gemma: return .assoc.txt rows positionally, columns in meta.columns
Cuts repeated key names out of large /compute/gemma(/ravanan) responses: data is now a list of positional row arrays instead of one keyed object per row, with the column names moved to a new meta.columns field shared with any other endpoint that wants the same shape. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/gemma.rs | 106 | ||||
| -rw-r--r-- | src/response.rs | 15 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 22 |
3 files changed, 91 insertions, 52 deletions
diff --git a/src/gemma.rs b/src/gemma.rs index b0b27a2..de7d433 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -215,36 +215,34 @@ fn assoc_file_basenames(record: &Value) -> Vec<&str> { .unwrap_or_default() } -/// One row of a GEMMA `.assoc.txt` file, keyed by its header column -/// names. Columns vary with `-lmm` (stock 1/2/3 run one test, 4 runs -/// all three; this build's `9`, GeneNetwork's convention, was observed -/// to carry `p_lrt`), so this stays a generic map rather than a fixed -/// struct. -pub type AssocRow = serde_json::Map<String, Value>; - /// Parse a GEMMA `.assoc.txt` file (tab-separated, header row first) -/// into one row per marker. A value that parses as a number is kept -/// numeric; "NA" and anything else stays a string. -fn parse_assoc_file(contents: &str) -> Vec<AssocRow> { +/// into its column names and one row per marker, each row a +/// `Value::Array` in that same column order (not keyed by column name: +/// columns vary with `-lmm` -- stock 1/2/3 run one test, 4 runs all +/// three; this build's `9`, GeneNetwork's convention, was observed to +/// carry `p_lrt` -- so callers needing a name match it up against the +/// returned column list themselves). A value that parses as a number is +/// kept numeric; "NA" and anything else stays a string. +fn parse_assoc_file(contents: &str) -> (Vec<String>, Vec<Vec<Value>>) { let mut lines = contents.lines(); let Some(header) = lines.next() else { - return Vec::new(); + return (Vec::new(), Vec::new()); }; - let columns: Vec<&str> = header.split('\t').collect(); - lines + let columns: Vec<String> = header.split('\t').map(str::to_string).collect(); + let rows = lines .filter(|line| !line.is_empty()) .map(|line| { - let mut row = AssocRow::new(); - for (column, value) in columns.iter().zip(line.split('\t')) { - let json_value = value - .parse::<f64>() - .map(|n| serde_json::json!(n)) - .unwrap_or_else(|_| Value::String(value.to_string())); - row.insert((*column).to_string(), json_value); - } - row + line.split('\t') + .map(|value| { + value + .parse::<f64>() + .map(|n| serde_json::json!(n)) + .unwrap_or_else(|_| Value::String(value.to_string())) + }) + .collect() }) - .collect() + .collect(); + (columns, rows) } /// Extract `archive` (a `.tar.xz`, relative to `cache_dir`) into @@ -273,6 +271,25 @@ async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Resu Ok(()) } +/// Read and parse every `basenames` file under `extract_dir` (one per +/// `--loco` chromosome), returning the column names (from the first +/// file; every chromosome's `.assoc.txt` shares the same header) and +/// every file's rows concatenated, each row a `Value::Array`. +fn parse_assoc_files(extract_dir: &Path, basenames: Vec<&str>) -> Result<(Vec<String>, Vec<Value>), GemmaError> { + let mut columns = Vec::new(); + let mut rows = Vec::new(); + for basename in basenames { + let contents = std::fs::read_to_string(extract_dir.join(basename)) + .map_err(GemmaError::AssocFile)?; + let (file_columns, file_rows) = parse_assoc_file(&contents); + if columns.is_empty() { + columns = file_columns; + } + rows.extend(file_rows.into_iter().map(Value::Array)); + } + Ok((columns, rows)) +} + fn nanos_since_epoch() -> u128 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -280,10 +297,13 @@ fn nanos_since_epoch() -> u128 { .unwrap_or(0) } -/// The mapped QTL rows, plus the exact gemma-wrapper invocations used -/// to produce them (see `compute`'s `notes` below), so a caller can see -/// precisely what was run without reading server logs. +/// The mapped QTL rows (each a `Value::Array` in `columns`' order, not +/// a keyed object -- see `parse_assoc_file`), plus the exact +/// gemma-wrapper invocations used to produce them (see `compute`'s +/// `notes` below), so a caller can see precisely what was run without +/// reading server logs. pub struct GemmaOutput { + pub columns: Vec<String>, pub rows: Value, pub notes: Vec<String>, } @@ -427,17 +447,13 @@ pub async fn compute( std::fs::create_dir_all(&extract_dir).map_err(GemmaError::Io)?; extract_archive(cache_dir, archive, &extract_dir.to_string_lossy()).await?; - let mut rows = Vec::new(); - for basename in basenames { - let contents = std::fs::read_to_string(extract_dir.join(basename)) - .map_err(GemmaError::AssocFile)?; - rows.extend(parse_assoc_file(&contents).into_iter().map(Value::Object)); - } + let (columns, rows) = parse_assoc_files(&extract_dir, basenames)?; let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless streaming::mark_complete(&log_path); Ok(GemmaOutput { + columns, rows: Value::Array(rows), notes: vec![kinship_note, gwa_note], }) @@ -561,17 +577,13 @@ pub async fn compute_ravanan( }); } - let mut rows = Vec::new(); - for basename in basenames { - let contents = std::fs::read_to_string(extract_dir.join(basename)) - .map_err(GemmaError::AssocFile)?; - rows.extend(parse_assoc_file(&contents).into_iter().map(Value::Object)); - } + let (columns, rows) = parse_assoc_files(&extract_dir, basenames)?; let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless streaming::mark_complete(&log_path); Ok(GemmaOutput { + columns, rows: Value::Array(rows), notes: vec![ravanan_note, format!("workflow: {workflow_path}")], }) @@ -593,17 +605,23 @@ mod tests { #[test] fn parse_assoc_file_parses_header_and_numeric_rows() { let contents = "chr\trs\tps\tp_wald\n1\trs001\t3010274\t0.05\n1\trs002\t3492195\tNA\n"; - let rows = parse_assoc_file(contents); + let (columns, rows) = parse_assoc_file(contents); + assert_eq!(columns, vec!["chr", "rs", "ps", "p_wald"]); assert_eq!(rows.len(), 2); - assert_eq!(rows[0]["chr"], serde_json::json!(1.0)); - assert_eq!(rows[0]["rs"], serde_json::json!("rs001")); - assert_eq!(rows[0]["p_wald"], serde_json::json!(0.05)); - assert_eq!(rows[1]["p_wald"], serde_json::json!("NA")); + assert_eq!(rows[0], vec![ + serde_json::json!(1.0), + serde_json::json!("rs001"), + serde_json::json!(3010274.0), + serde_json::json!(0.05), + ]); + assert_eq!(rows[1][3], serde_json::json!("NA")); } #[test] fn parse_assoc_file_empty_contents_yields_no_rows() { - assert_eq!(parse_assoc_file("").len(), 0); + let (columns, rows) = parse_assoc_file(""); + assert_eq!(columns.len(), 0); + assert_eq!(rows.len(), 0); } #[test] diff --git a/src/response.rs b/src/response.rs index cb2adce..bff1767 100644 --- a/src/response.rs +++ b/src/response.rs @@ -38,6 +38,13 @@ pub struct Meta { pub took_ms: u64, /// The request's id, also in the `x-request-id` response header. pub request_id: Option<String>, + /// Column names for a `data` that is a list of rows, each row a + /// positional array rather than a keyed object (e.g. + /// `/compute/gemma`'s GEMMA `.assoc.txt` rows) -- cuts repeated key + /// names out of a large response. Absent for endpoints whose `data` + /// is already keyed or isn't tabular. + #[serde(skip_serializing_if = "Option::is_none")] + pub columns: Option<Vec<String>>, } /// A success response: the payload, facts about the response, notes on @@ -75,6 +82,13 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> { self } + /// Sets `meta.columns` for a `data` of positional rows (see + /// `Meta::columns`). + pub fn with_columns(mut self, columns: Vec<String>) -> Self { + self.meta.columns = Some(columns); + self + } + /// Marks the response `partial` and records why in `notes`. pub fn partial(mut self, note: &str) -> Self { self.meta.state = State::Partial; @@ -148,6 +162,7 @@ impl Ctx { state: State::Complete, took_ms: self.info.took_ms(), request_id: self.info.id(), + columns: None, }, notes: Vec::new(), next: Vec::new(), diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index ffa3cad..83ec902 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -67,7 +67,7 @@ trait values, and returns the resulting rows of GEMMA's own \ params(ComputeGemmaParams), request_body = GemmaRequest, responses( - (status = 200, description = "Mapped QTL rows from GEMMA's .assoc.txt output, as a JSON array of row objects", body = Envelope<serde_json::Value>), + (status = 200, description = "Mapped QTL rows from GEMMA's .assoc.txt output, as positional arrays (column names in meta.columns)", body = Envelope<serde_json::Value>), Unauthorized, (status = 409, description = "id is already in use by another run", body = ApiError), (status = 422, description = "lmm not one of the known-working values (1, 2, 3, 4, 9), or id not alnum/-/_ (max 64 chars)", body = ApiError), @@ -122,9 +122,12 @@ pub async fn compute_gemma( ) .await .map(|output| { - let mut envelope = ctx.envelope(output.rows).with_note( - "Rows come from GEMMA's own .assoc.txt output; column names depend on the lmm value used.", - ); + let mut envelope = ctx + .envelope(output.rows) + .with_columns(output.columns) + .with_note( + "Rows come from GEMMA's own .assoc.txt output, positional (see meta.columns for names); column names depend on the lmm value used.", + ); for note in &output.notes { envelope = envelope.with_note(note); } @@ -157,7 +160,7 @@ ravanan's own store between requests beyond its --store directory, and \ params(ComputeGemmaParams), request_body = GemmaRequest, responses( - (status = 200, description = "Mapped QTL rows from GEMMA's .assoc.txt output, as a JSON array of row objects", body = Envelope<serde_json::Value>), + (status = 200, description = "Mapped QTL rows from GEMMA's .assoc.txt output, as positional arrays (column names in meta.columns)", body = Envelope<serde_json::Value>), Unauthorized, (status = 409, description = "id is already in use by another run", body = ApiError), (status = 422, description = "lmm not one of the known-working values (1, 2, 3, 4, 9), or id not alnum/-/_ (max 64 chars)", body = ApiError), @@ -210,9 +213,12 @@ pub async fn compute_gemma_ravanan( ) .await .map(|output| { - let mut envelope = ctx.envelope(output.rows).with_note( - "Rows come from GEMMA's own .assoc.txt output; column names depend on the lmm value used.", - ); + let mut envelope = ctx + .envelope(output.rows) + .with_columns(output.columns) + .with_note( + "Rows come from GEMMA's own .assoc.txt output, positional (see meta.columns for names); column names depend on the lmm value used.", + ); for note in &output.notes { envelope = envelope.with_note(note); } |
