Skip to main content

data_beans/
convert.rs

1use crate::hdf5_io::*;
2use crate::sparse_io::*;
3use crate::sparse_util::*;
4use crate::utilities::name_matching::{
5    compose_id_name, filter_row_indices_by_type, make_names_unique,
6};
7use crate::zarr_io::*;
8
9use legume_numeric::matrix::common_io::*;
10use log::info;
11
12/// The sparse matrix of a 10x file as read, before rows are named and kept:
13/// its triplets, how far they reach, and whatever names the file lists.
14pub struct TenxMatrix {
15    pub triplets: Vec<(u64, u64, f32)>,
16    /// Rows and columns the triplets span: every compressed vector, and up
17    /// to the largest index on the other axis.
18    pub reach: (usize, usize),
19    pub row_ids: Option<Vec<Box<str>>>,
20    pub row_names: Option<Vec<Box<str>>>,
21    pub row_types: Option<Vec<Box<str>>>,
22    pub column_names: Option<Vec<Box<str>>>,
23    /// Rows to keep whatever their type, as a probe set's targets; `None`
24    /// for all.
25    pub keep_rows: Option<Vec<bool>>,
26}
27
28/// The length of one axis: the number of names the file lists for it (one
29/// per row or column, so trailing all-zero rows and columns, which leave no
30/// trace in the triplets, still count), else as far as the triplets reach.
31/// An error when the triplets reach past the names.
32fn axis_len(named: Option<usize>, reach: usize, what: &str) -> anyhow::Result<usize> {
33    match named {
34        Some(n) if n >= reach => Ok(n),
35        Some(n) => anyhow::bail!("the file names {n} {what} but its data reaches {reach}"),
36        None => Ok(reach),
37    }
38}
39
40/// Write `m` as a new backend at `backend_file`: rows named `{id}_{name}`
41/// (just `id` when the name is empty or repeats it; made unique) and kept by
42/// type (comma-separated, case-insensitive patterns; a file without types
43/// keeps all), columns named as the file names them. Shared by the 10x
44/// readers, so every format and entry point names and keeps rows alike.
45pub fn write_10x_matrix(
46    m: TenxMatrix,
47    select_row_type: &str,
48    remove_row_type: &str,
49    backend_file: &str,
50    backend: &SparseIoBackend,
51) -> anyhow::Result<()> {
52    let TenxMatrix {
53        mut triplets,
54        reach,
55        row_ids,
56        row_names,
57        row_types,
58        column_names,
59        keep_rows,
60    } = m;
61    let nrows = axis_len(row_ids.as_ref().map(Vec::len), reach.0, "rows")?;
62    let ncols = axis_len(column_names.as_ref().map(Vec::len), reach.1, "columns")?;
63    let index = |n: usize| {
64        (0..n)
65            .map(|i| i.to_string().into_boxed_str())
66            .collect::<Vec<_>>()
67    };
68    let row_ids = row_ids.unwrap_or_else(|| index(nrows));
69    let row_names = row_names.unwrap_or_else(|| vec![Box::from(""); nrows]);
70    anyhow::ensure!(
71        row_names.len() == nrows
72            && row_types.as_ref().is_none_or(|t| t.len() == nrows)
73            && keep_rows.as_ref().is_none_or(|k| k.len() == nrows),
74        "the file lists {nrows} row ids but {} row names and {} row types",
75        row_names.len(),
76        row_types.as_ref().map_or(0, Vec::len)
77    );
78    let column_names = column_names.unwrap_or_else(|| index(ncols));
79
80    let mut row_ids = compose_id_name(row_ids, row_names);
81    make_names_unique(&mut row_ids);
82    let mut keep = match &row_types {
83        Some(types) => filter_row_indices_by_type(types, select_row_type, remove_row_type),
84        None => (0..nrows).collect(),
85    };
86    if let Some(keep_rows) = &keep_rows {
87        keep.retain(|&i| keep_rows[i]);
88    }
89    // The other rows leave the triplets before anything is written.
90    if keep.len() < nrows {
91        info!("Keeping {} of {nrows} rows", keep.len());
92        let mut new_row = vec![None; nrows];
93        for (new, &old) in keep.iter().enumerate() {
94            new_row[old] = Some(new as u64);
95        }
96        triplets.retain_mut(|(i, _, _)| match new_row[*i as usize] {
97            Some(new) => {
98                *i = new;
99                true
100            }
101            None => false,
102        });
103        row_ids = keep
104            .iter()
105            .map(|&i| std::mem::take(&mut row_ids[i]))
106            .collect();
107    }
108
109    let nnz = triplets.len();
110    info!("Matrix: {} x {ncols}, {nnz} non-zeros", row_ids.len());
111    let mut out = create_sparse_from_triplets_owned(
112        triplets,
113        (row_ids.len(), ncols, nnz),
114        Some(backend_file),
115        Some(backend),
116    )?;
117    info!("Created sparse matrix: {}", backend_file);
118    out.register_row_names_vec(&row_ids);
119    out.register_column_names_vec(&column_names);
120    Ok(())
121}
122
123/// Where a 10x file keeps its sparse matrix and the names of its rows and
124/// columns, and which rows to keep: [`MatrixLayout::cell_ranger_h5`] and
125/// [`MatrixLayout::xenium_zarr`].
126#[derive(Clone, Debug)]
127pub struct MatrixLayout {
128    pub data_field: Box<str>,
129    pub indices_field: Box<str>,
130    pub indptr_field: Box<str>,
131    pub pointer_type: IndexPointerType,
132    pub row_id_field: Box<str>,
133    pub row_name_field: Box<str>,
134    pub row_type_field: Box<str>,
135    /// Comma-separated, case-insensitive; a row whose type contains any is kept.
136    pub select_row_type: Box<str>,
137    /// Comma-separated, case-insensitive; a row whose type contains any is dropped.
138    pub remove_row_type: Box<str>,
139    pub column_name_field: Box<str>,
140}
141
142impl MatrixLayout {
143    /// The group a Cell Ranger HDF5 file keeps its matrix under; the
144    /// `H5_*` fields are relative to it.
145    pub const H5_ROOT: &'static str = "matrix";
146    pub const H5_DATA: &'static str = "data";
147    pub const H5_INDICES: &'static str = "indices";
148    pub const H5_INDPTR: &'static str = "indptr";
149    pub const H5_ROW_IDS: &'static str = "features/id";
150    pub const H5_ROW_NAMES: &'static str = "features/name";
151    pub const H5_ROW_TYPES: &'static str = "features/feature_type";
152    pub const H5_COLUMN_NAMES: &'static str = "barcodes";
153    pub const XENIUM_DATA: &'static str = "/cell_features/data";
154    pub const XENIUM_INDICES: &'static str = "/cell_features/indices";
155    pub const XENIUM_INDPTR: &'static str = "/cell_features/indptr";
156    pub const XENIUM_ROW_IDS: &'static str = "/cell_features/feature_ids";
157    pub const XENIUM_ROW_NAMES: &'static str = "/cell_features/feature_keys";
158    pub const XENIUM_ROW_TYPES: &'static str = "/cell_features/feature_types";
159    pub const XENIUM_COLUMN_NAMES: &'static str = "/cell_features/cell_id";
160    /// Gene Expression (Xenium `gene`) and ATAC Peaks.
161    pub const SELECT_ROW_TYPES: &'static str = "gene,peak";
162    /// Xenium's per-gene aggregates (`aggregate_gene`).
163    pub const REMOVE_ROW_TYPES: &'static str = "aggregate";
164
165    /// Cell Ranger / Space Ranger / Xenium `*feature_bc_matrix.h5`:
166    /// features × barcodes under [`Self::H5_ROOT`], pointers over barcodes.
167    pub fn cell_ranger_h5() -> Self {
168        Self {
169            data_field: Self::H5_DATA.into(),
170            indices_field: Self::H5_INDICES.into(),
171            indptr_field: Self::H5_INDPTR.into(),
172            pointer_type: IndexPointerType::Column,
173            row_id_field: Self::H5_ROW_IDS.into(),
174            row_name_field: Self::H5_ROW_NAMES.into(),
175            row_type_field: Self::H5_ROW_TYPES.into(),
176            select_row_type: Self::SELECT_ROW_TYPES.into(),
177            remove_row_type: Self::REMOVE_ROW_TYPES.into(),
178            column_name_field: Self::H5_COLUMN_NAMES.into(),
179        }
180    }
181
182    /// Xenium's `cell_feature_matrix.zarr`: features × cells, pointers over
183    /// features, feature names as attributes of `/cell_features`.
184    pub fn xenium_zarr() -> Self {
185        Self {
186            data_field: Self::XENIUM_DATA.into(),
187            indices_field: Self::XENIUM_INDICES.into(),
188            indptr_field: Self::XENIUM_INDPTR.into(),
189            pointer_type: IndexPointerType::Row,
190            row_id_field: Self::XENIUM_ROW_IDS.into(),
191            row_name_field: Self::XENIUM_ROW_NAMES.into(),
192            row_type_field: Self::XENIUM_ROW_TYPES.into(),
193            select_row_type: Self::SELECT_ROW_TYPES.into(),
194            remove_row_type: Self::REMOVE_ROW_TYPES.into(),
195            column_name_field: Self::XENIUM_COLUMN_NAMES.into(),
196        }
197    }
198}
199
200/// Read the sparse matrix of a 10x HDF5 file, its fields under
201/// `root_group`, into a new backend at `backend_file`
202/// ([`write_10x_matrix`]). Shared by `data-beans from-10x-matrix` and
203/// [`try_open_or_convert`]. The caller prepares and finalizes the output
204/// ([`prepare_output`], [`finalize_output`]).
205#[cfg(feature = "hdf5")]
206pub fn build_from_h5_matrix(
207    h5_file: &str,
208    root_group: &str,
209    layout: &MatrixLayout,
210    backend_file: &str,
211    backend: &SparseIoBackend,
212) -> anyhow::Result<()> {
213    let file = hdf5::File::open(h5_file)?;
214    info!("Opened 10x HDF5 file: {}", h5_file);
215    let root = file
216        .group(root_group)
217        .map_err(|_| anyhow::anyhow!("no group `{root_group}` in {h5_file}"))?;
218    let dataset = |field: &str| {
219        root.dataset(field)
220            .map_err(|_| anyhow::anyhow!("no dataset `{root_group}/{field}` in {h5_file}"))
221    };
222    // The arrays go once their triplets are made.
223    let CooTripletsShape { triplets, shape } = {
224        let values: Vec<f32> = dataset(&layout.data_field)?.read_raw()?;
225        let indices: Vec<u64> = dataset(&layout.indices_field)?.read_raw()?;
226        let indptr: Vec<u64> = dataset(&layout.indptr_field)?.read_raw()?;
227        ValuesIndicesPointers {
228            values: &values,
229            indices: &indices,
230            indptr: &indptr,
231        }
232        .to_coo(layout.pointer_type)?
233    };
234    info!(
235        "Read {} non-zero elements reaching {} x {}",
236        shape.nnz, shape.nrows, shape.ncols
237    );
238    let names = |field: &str| root.dataset(field).ok().map(read_hdf5_strings).transpose();
239    write_10x_matrix(
240        TenxMatrix {
241            triplets,
242            reach: (shape.nrows, shape.ncols),
243            row_ids: names(&layout.row_id_field)?,
244            row_names: names(&layout.row_name_field)?,
245            row_types: names(&layout.row_type_field)?,
246            column_names: names(&layout.column_name_field)?,
247            keep_rows: None,
248        },
249        &layout.select_row_type,
250        &layout.remove_row_type,
251        backend_file,
252        backend,
253    )
254}
255
256/// Read the sparse matrix of a 10x-style Zarr store into a new backend at
257/// `backend_file` ([`write_10x_matrix`]), columns named by Xenium cell id
258/// when they are encoded so. Shared by `data-beans from-zarr` and
259/// [`try_open_or_convert`], so both read a store alike. The caller prepares
260/// and finalizes the output ([`prepare_output`], [`finalize_output`]).
261pub fn build_from_zarr_matrix(
262    zarr_file: &str,
263    layout: &MatrixLayout,
264    backend_file: &str,
265    backend: &SparseIoBackend,
266) -> anyhow::Result<()> {
267    if !std::path::Path::new(zarr_file).exists() {
268        let zip_variant = format!("{}.zip", zarr_file);
269        let hint: Box<str> = if std::path::Path::new(&zip_variant).exists() {
270            format!(" (did you mean {}?)", zip_variant).into()
271        } else {
272            Box::from("")
273        };
274        anyhow::bail!("Zarr file not found: {}{}", zarr_file, hint);
275    }
276    let store = open_zarr_store(zarr_file)?;
277    info!("Opened zarr store: {}", zarr_file);
278
279    // The arrays go once their triplets are made.
280    let CooTripletsShape { triplets, shape } = {
281        let indices: Vec<u64> = read_zarr_numerics(store.clone(), &layout.indices_field)?;
282        let indptr: Vec<u64> = read_zarr_numerics(store.clone(), &layout.indptr_field)?;
283        let values: Vec<f32> = read_zarr_numerics(store.clone(), &layout.data_field)?;
284        ValuesIndicesPointers {
285            values: &values,
286            indices: &indices,
287            indptr: &indptr,
288        }
289        .to_coo(layout.pointer_type)?
290    };
291    let TripletsShape { nrows, ncols, nnz } = shape;
292    info!("Read {nnz} non-zero elements reaching {nrows} x {ncols}");
293
294    // Names stored as a group attribute (Xenium) or as a string array.
295    let names = |field: &str| {
296        read_zarr_group_attr::<Vec<Box<str>>>(store.clone(), field)
297            .or_else(|_| read_zarr_strings(store.clone(), field))
298            .ok()
299    };
300    let column_names = read_zarr_flat_u32(store.clone(), &layout.column_name_field)
301        .and_then(|(ids, shape)| {
302            anyhow::ensure!(shape.len() == 2 && shape[1] == 2, "cell_id must be [N, 2]");
303            parse_10x_cell_id_flat(&ids, shape[0] as usize)
304        })
305        .ok()
306        .or_else(|| names(&layout.column_name_field));
307    write_10x_matrix(
308        TenxMatrix {
309            triplets,
310            reach: (nrows, ncols),
311            row_ids: names(&layout.row_id_field),
312            row_names: names(&layout.row_name_field),
313            row_types: names(&layout.row_type_field),
314            column_names,
315            keep_rows: None,
316        },
317        &layout.select_row_type,
318        &layout.remove_row_type,
319        backend_file,
320        backend,
321    )
322}
323
324/// Convert to a Zarr backend at `output` with `build`, which writes it.
325fn convert_with(
326    output: &str,
327    build: impl FnOnce(&str, &SparseIoBackend) -> anyhow::Result<()>,
328) -> anyhow::Result<()> {
329    let (output, backend, backend_file) = prepare_output(output, SparseIoBackend::Zarr, false)?;
330    build(&backend_file, &backend)?;
331    finalize_output(&backend_file, &output)?;
332    info!("Conversion done: {}", output);
333    Ok(())
334}
335
336/// Convert a 10x HDF5 file (Cell Ranger / Space Ranger / Xenium
337/// `*feature_bc_matrix.h5`) to a data-beans backend, read as `data-beans
338/// from-10x-matrix` reads it with its defaults
339/// ([`MatrixLayout::cell_ranger_h5`]).
340#[cfg(feature = "hdf5")]
341pub fn convert_h5_to_backend(h5_file: &str, output: &str) -> anyhow::Result<()> {
342    convert_with(output, |backend_file, backend| {
343        let layout = MatrixLayout::cell_ranger_h5();
344        build_from_h5_matrix(
345            h5_file,
346            MatrixLayout::H5_ROOT,
347            &layout,
348            backend_file,
349            backend,
350        )
351    })
352}
353
354/// Convert a 10x-style Zarr file (Xenium `cell_feature_matrix.zarr.zip` or
355/// directory) to a data-beans backend, read as `data-beans from-zarr` reads
356/// it with its defaults ([`MatrixLayout::xenium_zarr`]).
357pub fn convert_zarr_to_backend(zarr_file: &str, output: &str) -> anyhow::Result<()> {
358    convert_with(output, |backend_file, backend| {
359        build_from_zarr_matrix(
360            zarr_file,
361            &MatrixLayout::xenium_zarr(),
362            backend_file,
363            backend,
364        )
365    })
366}
367
368/// Try to open a data file directly; if that fails, attempt automatic
369/// conversion from raw 10x formats (h5/h5ad, zarr/zarr.zip).
370///
371/// Converted backends are cached as `{data_file}.db.zarr` next to
372/// the original file so subsequent calls skip conversion.
373pub fn try_open_or_convert(
374    data_file: &str,
375) -> anyhow::Result<Box<dyn SparseIo<IndexIter = Vec<usize>>>> {
376    let ext = file_ext(data_file)?;
377    let backend = match ext.as_ref() {
378        "h5" | "h5ad" => SparseIoBackend::HDF5,
379        _ => SparseIoBackend::Zarr,
380    };
381
382    match open_sparse_matrix(data_file, &backend) {
383        Ok(data) => Ok(data),
384        Err(original_err) => {
385            let base = strip_backend_suffix(data_file);
386            let converted = format!("{}.db.zarr", base);
387
388            if std::path::Path::new(&converted).exists() {
389                info!("Using cached conversion: {}", converted);
390                return open_sparse_matrix(&converted, &SparseIoBackend::Zarr);
391            }
392
393            match ext.as_ref() {
394                "h5" | "h5ad" => {
395                    #[cfg(feature = "hdf5")]
396                    {
397                        info!(
398                            "Converting h5/h5ad to backend: {} -> {}",
399                            data_file, converted
400                        );
401                        convert_h5_to_backend(data_file, &converted)?;
402                    }
403                    #[cfg(not(feature = "hdf5"))]
404                    {
405                        anyhow::bail!(
406                            "{} is an HDF5 file but data-beans was built without the `hdf5` \
407                             feature. Reinstall with `--features hdf5` (and a working libhdf5) \
408                             to read .h5/.h5ad inputs.",
409                            data_file
410                        );
411                    }
412                }
413                "zarr" | "zip" => {
414                    info!("Converting zarr to backend: {} -> {}", data_file, converted);
415                    convert_zarr_to_backend(data_file, &converted)?;
416                }
417                _ => return Err(original_err),
418            }
419
420            open_sparse_matrix(&converted, &SparseIoBackend::Zarr)
421        }
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use std::path::Path;
429
430    /// An uncompressed Zarr v2 array of little-endian u32 under `dir/name`.
431    fn write_u32_array(dir: &Path, name: &str, shape: &[usize], values: &[u32]) {
432        let d = dir.join(name);
433        std::fs::create_dir_all(&d).unwrap();
434        let meta = serde_json::json!({
435            "zarr_format": 2, "shape": shape, "chunks": shape, "dtype": "<u4",
436            "compressor": null, "fill_value": 0, "order": "C", "filters": null
437        });
438        std::fs::write(d.join(".zarray"), meta.to_string()).unwrap();
439        let chunk = vec!["0"; shape.len()].join(".");
440        let bytes: Vec<u8> = values.iter().flat_map(|v| v.to_le_bytes()).collect();
441        std::fs::write(d.join(chunk), bytes).unwrap();
442    }
443
444    /// A store laid out as Xenium writes `cell_feature_matrix.zarr`: 3
445    /// features × 4 cells, pointers over features, names as attributes of
446    /// `/cell_features`, cell ids as a `[N, 2]` u32 array.
447    fn xenium_like_store(dir: &Path) -> Vec<u32> {
448        let cf = dir.join("cell_features");
449        std::fs::create_dir_all(&cf).unwrap();
450        std::fs::write(dir.join(".zgroup"), r#"{"zarr_format": 2}"#).unwrap();
451        std::fs::write(cf.join(".zgroup"), r#"{"zarr_format": 2}"#).unwrap();
452        let attrs = serde_json::json!({
453            "feature_ids": ["FID1", "FID2", "FID3"],
454            "feature_keys": ["GENE1", "GENE2", "NEG1"],
455            "feature_types": ["gene", "gene", "negative_control_probe"],
456            "number_cells": 4, "number_features": 3
457        });
458        std::fs::write(cf.join(".zattrs"), attrs.to_string()).unwrap();
459        // Rows (features): GENE1 [1 0 2 0], GENE2 [0 3 0 4], NEG1 [5 0 0 0].
460        write_u32_array(&cf, "indptr", &[4], &[0, 2, 4, 5]);
461        write_u32_array(&cf, "indices", &[5], &[0, 2, 1, 3, 0]);
462        write_u32_array(&cf, "data", &[5], &[1, 2, 3, 4, 5]);
463        let ids = vec![16844, 1, 22527, 1, 16845, 1, 22528, 1];
464        write_u32_array(&cf, "cell_id", &[4, 2], &ids);
465        ids
466    }
467
468    #[test]
469    fn a_xenium_store_converts_to_genes_by_cells_with_their_names() {
470        let dir = tempfile::tempdir().unwrap();
471        let store = dir.path().join("matrix.zarr");
472        let ids = xenium_like_store(&store);
473        let out = dir.path().join("out.db.zarr");
474        let out = out.to_str().unwrap();
475        convert_zarr_to_backend(store.to_str().unwrap(), out).unwrap();
476
477        let data = open_sparse_matrix(out, &SparseIoBackend::Zarr).unwrap();
478        // The control feature is dropped; genes are rows, cells columns.
479        assert_eq!(
480            data.row_names().unwrap(),
481            vec![Box::from("FID1_GENE1"), Box::from("FID2_GENE2")]
482        );
483        assert_eq!(
484            data.column_names().unwrap(),
485            parse_10x_cell_id_flat(&ids, 4).unwrap()
486        );
487        let m = data.read_columns_dmatrix((0..4).collect()).unwrap();
488        assert_eq!(m.shape(), (2, 4));
489        assert_eq!(
490            m.row(0).iter().copied().collect::<Vec<f32>>(),
491            [1., 0., 2., 0.]
492        );
493        assert_eq!(
494            m.row(1).iter().copied().collect::<Vec<f32>>(),
495            [0., 3., 0., 4.]
496        );
497    }
498
499    fn names(xs: &[&str]) -> Option<Vec<Box<str>>> {
500        Some(xs.iter().map(|&x| Box::from(x)).collect())
501    }
502
503    #[test]
504    fn trailing_empty_rows_and_columns_are_kept() {
505        let dir = tempfile::tempdir().unwrap();
506        let out = dir.path().join("out.zarr");
507        let out = out.to_str().unwrap();
508        // The data reaches 2 x 2, but the file names 3 rows and 3 columns;
509        // the last row and column have nothing in them. Rows whose name is
510        // empty or repeats the id are named by id alone.
511        let m = TenxMatrix {
512            triplets: vec![(0, 0, 1.0), (1, 1, 2.0)],
513            reach: (2, 2),
514            row_ids: names(&["FID1", "FID2", "FID3"]),
515            row_names: names(&["GENE1", "FID2", ""]),
516            row_types: names(&["Gene Expression"; 3]),
517            column_names: names(&["BC1", "BC2", "BC3"]),
518            keep_rows: None,
519        };
520        write_10x_matrix(m, "gene", "", out, &SparseIoBackend::Zarr).unwrap();
521
522        let data = open_sparse_matrix(out, &SparseIoBackend::Zarr).unwrap();
523        assert_eq!(
524            data.row_names().unwrap(),
525            ["FID1_GENE1", "FID2", "FID3"].map(Box::from)
526        );
527        assert_eq!(
528            data.column_names().unwrap(),
529            ["BC1", "BC2", "BC3"].map(Box::from)
530        );
531        let m = data.read_columns_dmatrix((0..3).collect()).unwrap();
532        assert_eq!(m.shape(), (3, 3));
533        assert_eq!(
534            m.row(2).iter().sum::<f32>() + m.column(2).iter().sum::<f32>(),
535            0.
536        );
537    }
538
539    #[test]
540    fn data_reaching_past_the_names_is_an_error() {
541        let dir = tempfile::tempdir().unwrap();
542        let out = dir.path().join("out.zarr");
543        let m = TenxMatrix {
544            triplets: vec![(2, 0, 1.0)],
545            reach: (3, 1),
546            row_ids: names(&["FID1", "FID2"]),
547            row_names: None,
548            row_types: None,
549            column_names: None,
550            keep_rows: None,
551        };
552        let e = write_10x_matrix(m, "gene", "", out.to_str().unwrap(), &SparseIoBackend::Zarr);
553        assert!(e.unwrap_err().to_string().contains("names 2 rows"));
554    }
555}