legume-numeric 0.8.11

Numeric and ML foundation for the legume ecosystem (matrix, Leiden, candle, MCMC)
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
use crate::matrix::traits::IoOps;
use anyhow::Result;
use candle_core::Tensor;
use parquet::basic::{Compression, ConvertedType, Type as ParquetType, ZstdLevel};
use parquet::data_type::{ByteArray, ByteArrayType, FloatType};
use parquet::file::properties::WriterProperties;
use parquet::file::writer::SerializedFileWriter;
use parquet::schema::types::Type;
use std::fs::File;
use std::path::Path;
use std::sync::Arc;

use super::traits::VariationalDistribution;

//
// Traits
//

/// Trait for outputting variational distribution parameters.
pub trait VariationalOutput {
    /// Write mean parameters to file (format detected from extension).
    fn write_mean(&self, path: &str) -> Result<()>;

    /// Write variance parameters to file.
    fn write_var(&self, path: &str) -> Result<()>;

    /// Write standard deviation parameters to file.
    fn write_std(&self, path: &str) -> Result<()>;

    /// Write all standard outputs with a header prefix.
    fn write_all(&self, header: &str) -> Result<()>;

    /// Write to parquet in melted (long) format with row/column names.
    fn to_melted_parquet(
        &self,
        file_path: &str,
        row_names: (Option<&[Box<str>]>, Option<&str>),
        column_names: (Option<&[Box<str>]>, Option<&str>),
    ) -> Result<()>;

    /// Write to parquet with default names
    fn to_parquet(&self, file_path: &str) -> Result<()> {
        self.to_melted_parquet(file_path, (None, None), (None, None))
    }
}

/// Extended output trait for sparse variational distributions (e.g., Susie).
pub trait SparseVariationalOutput: VariationalOutput {
    /// Write posterior inclusion probabilities to file.
    fn write_pip(&self, path: &str) -> Result<()>;

    /// Write component selection probabilities (alpha) to file.
    fn write_alpha(&self, path: &str) -> Result<()>;

    /// Write all outputs including sparse-specific ones.
    fn write_all_sparse(&self, header: &str) -> Result<()>;

    /// Write to parquet in melted format (delegates to to_melted_parquet).
    fn to_parquet_sparse(
        &self,
        file_path: &str,
        row_names: Option<&[Box<str>]>,
        column_names: Option<&[Box<str>]>,
    ) -> Result<()> {
        self.to_melted_parquet(file_path, (row_names, None), (column_names, None))
    }
}

//
// Helper functions
//

fn get_format_ext(path: &Path) -> String {
    let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
    let name_lower = name.to_lowercase();
    if name_lower.ends_with(".gz") {
        let stem = &name[..name.len() - 3];
        Path::new(stem)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase()
    } else {
        path.extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase()
    }
}

fn write_tensor(tensor: &Tensor, path: &str) -> Result<()> {
    let path = Path::new(path);
    let ext = get_format_ext(path);
    let tensor = tensor.to_device(&candle_core::Device::Cpu)?;

    match ext.as_str() {
        "csv" => tensor.to_csv(path.to_str().unwrap())?,
        "parquet" | "pq" => tensor.to_parquet(path.to_str().unwrap())?,
        _ => tensor.to_tsv(path.to_str().unwrap())?,
    }
    Ok(())
}

fn melt_tensor(tensor: &Tensor) -> Result<(Vec<f32>, Vec<usize>, Vec<usize>)> {
    let tensor = tensor.to_device(&candle_core::Device::Cpu)?;
    let dims = tensor.dims();
    let (nrows, ncols) = (dims[0], dims[1]);

    let data: Vec<f32> = tensor.flatten_all()?.to_vec1()?;

    let mut row_idx = Vec::with_capacity(data.len());
    let mut col_idx = Vec::with_capacity(data.len());

    for i in 0..nrows {
        for j in 0..ncols {
            row_idx.push(i);
            col_idx.push(j);
        }
    }

    Ok((data, row_idx, col_idx))
}

fn indices_to_names(indices: &[usize], names: Option<&[Box<str>]>) -> Vec<ByteArray> {
    indices
        .iter()
        .map(|&i| {
            if let Some(names) = names {
                ByteArray::from(names[i].as_ref())
            } else {
                ByteArray::from(i.to_string().as_bytes())
            }
        })
        .collect()
}

/// Write melted data to parquet file.
fn write_melted_parquet(
    file_path: &str,
    schema_name: &str,
    row_title: &str,
    col_title: &str,
    rows: &[ByteArray],
    cols: &[ByteArray],
    value_columns: &[(&str, &[f32])],
) -> Result<()> {
    let mut fields: Vec<(&str, ParquetType, ConvertedType)> = vec![
        (row_title, ParquetType::BYTE_ARRAY, ConvertedType::UTF8),
        (col_title, ParquetType::BYTE_ARRAY, ConvertedType::UTF8),
    ];
    for (name, _) in value_columns {
        fields.push((name, ParquetType::FLOAT, ConvertedType::NONE));
    }

    let schema = Arc::new(
        Type::group_type_builder(schema_name)
            .with_fields(
                fields
                    .iter()
                    .map(|(name, ptype, ctype)| {
                        Arc::new(
                            Type::primitive_type_builder(name, *ptype)
                                .with_repetition(parquet::basic::Repetition::REQUIRED)
                                .with_converted_type(*ctype)
                                .build()
                                .unwrap(),
                        )
                    })
                    .collect(),
            )
            .build()?,
    );

    let file = File::create(file_path)?;
    let zstd_level = ZstdLevel::try_new(5)?;
    let props = Arc::new(
        WriterProperties::builder()
            .set_compression(Compression::ZSTD(zstd_level))
            .build(),
    );
    let mut writer = SerializedFileWriter::new(file, schema, props)?;
    let mut row_group = writer.next_row_group()?;

    // Write string columns
    for data in [rows, cols] {
        if let Some(mut col_writer) = row_group.next_column()? {
            col_writer
                .typed::<ByteArrayType>()
                .write_batch(data, None, None)?;
            col_writer.close()?;
        }
    }

    // Write value columns
    for (_, values) in value_columns {
        if let Some(mut col_writer) = row_group.next_column()? {
            col_writer
                .typed::<FloatType>()
                .write_batch(values, None, None)?;
            col_writer.close()?;
        }
    }

    row_group.close()?;
    writer.close()?;
    Ok(())
}

//
// GaussianVar implementation
//

impl VariationalOutput for super::GaussianVar {
    fn write_mean(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::mean(self)?, path)
    }

    fn write_var(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::var(self)?, path)
    }

    fn write_std(&self, path: &str) -> Result<()> {
        write_tensor(&self.std()?, path)
    }

    fn write_all(&self, header: &str) -> Result<()> {
        self.write_mean(&format!("{}.mean.gz", header))?;
        self.write_std(&format!("{}.std.gz", header))
    }

    fn to_melted_parquet(
        &self,
        file_path: &str,
        row_names: (Option<&[Box<str>]>, Option<&str>),
        column_names: (Option<&[Box<str>]>, Option<&str>),
    ) -> Result<()> {
        let mean = VariationalDistribution::mean(self)?;
        let std = self.std()?;

        let (mean_vals, row_idx, col_idx) = melt_tensor(&mean)?;
        let (std_vals, _, _) = melt_tensor(&std)?;

        let rows = indices_to_names(&row_idx, row_names.0);
        let cols = indices_to_names(&col_idx, column_names.0);

        write_melted_parquet(
            file_path,
            "GaussianVar",
            row_names.1.unwrap_or("row"),
            column_names.1.unwrap_or("column"),
            &rows,
            &cols,
            &[("mean", &mean_vals), ("std", &std_vals)],
        )
    }
}

//
// SusieVar implementation
//

impl VariationalOutput for super::SusieVar {
    fn write_mean(&self, path: &str) -> Result<()> {
        write_tensor(&self.theta_mean()?, path)
    }

    fn write_var(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::var(self)?, path)
    }

    fn write_std(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::var(self)?.sqrt()?, path)
    }

    fn write_all(&self, header: &str) -> Result<()> {
        self.write_mean(&format!("{}.mean.gz", header))?;
        self.write_std(&format!("{}.std.gz", header))
    }

    fn to_melted_parquet(
        &self,
        file_path: &str,
        row_names: (Option<&[Box<str>]>, Option<&str>),
        column_names: (Option<&[Box<str>]>, Option<&str>),
    ) -> Result<()> {
        let mean = self.theta_mean()?;
        let std = VariationalDistribution::var(self)?.sqrt()?;
        let pip = self.pip()?;

        let (mean_vals, row_idx, col_idx) = melt_tensor(&mean)?;
        let (std_vals, _, _) = melt_tensor(&std)?;
        let (pip_vals, _, _) = melt_tensor(&pip)?;

        let rows = indices_to_names(&row_idx, row_names.0);
        let cols = indices_to_names(&col_idx, column_names.0);

        write_melted_parquet(
            file_path,
            "SusieVar",
            row_names.1.unwrap_or("row"),
            column_names.1.unwrap_or("column"),
            &rows,
            &cols,
            &[("mean", &mean_vals), ("std", &std_vals), ("pip", &pip_vals)],
        )
    }
}

impl SparseVariationalOutput for super::SusieVar {
    fn write_pip(&self, path: &str) -> Result<()> {
        write_tensor(&self.pip()?, path)
    }

    fn write_alpha(&self, path: &str) -> Result<()> {
        let alpha = self.alpha()?;
        let dims = alpha.dims();
        if dims.len() == 3 {
            let (l, p, k) = (dims[0], dims[1], dims[2]);
            write_tensor(&alpha.reshape((l * p, k))?, path)
        } else {
            write_tensor(&alpha, path)
        }
    }

    fn write_all_sparse(&self, header: &str) -> Result<()> {
        self.write_all(header)?;
        self.write_pip(&format!("{}.pip.gz", header))?;
        self.write_alpha(&format!("{}.alpha.gz", header))
    }
}

impl VariationalOutput for super::MultiLevelSusieVar {
    fn write_mean(&self, path: &str) -> Result<()> {
        write_tensor(&self.theta_mean()?, path)
    }

    fn write_var(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::var(self)?, path)
    }

    fn write_std(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::var(self)?.sqrt()?, path)
    }

    fn write_all(&self, header: &str) -> Result<()> {
        self.write_mean(&format!("{}.mean.gz", header))?;
        self.write_std(&format!("{}.std.gz", header))
    }

    fn to_melted_parquet(
        &self,
        file_path: &str,
        row_names: (Option<&[Box<str>]>, Option<&str>),
        column_names: (Option<&[Box<str>]>, Option<&str>),
    ) -> Result<()> {
        let mean = self.theta_mean()?;
        let std = VariationalDistribution::var(self)?.sqrt()?;
        let pip = self.pip()?;

        let (mean_vals, row_idx, col_idx) = melt_tensor(&mean)?;
        let (std_vals, _, _) = melt_tensor(&std)?;
        let (pip_vals, _, _) = melt_tensor(&pip)?;

        let rows = indices_to_names(&row_idx, row_names.0);
        let cols = indices_to_names(&col_idx, column_names.0);

        write_melted_parquet(
            file_path,
            "MultiLevelSusieVar",
            row_names.1.unwrap_or("row"),
            column_names.1.unwrap_or("column"),
            &rows,
            &cols,
            &[("mean", &mean_vals), ("std", &std_vals), ("pip", &pip_vals)],
        )
    }
}

impl SparseVariationalOutput for super::MultiLevelSusieVar {
    fn write_pip(&self, path: &str) -> Result<()> {
        write_tensor(&self.pip()?, path)
    }

    fn write_alpha(&self, path: &str) -> Result<()> {
        let alpha = self.alpha()?;
        let dims = alpha.dims();
        if dims.len() == 3 {
            let (l, p, k) = (dims[0], dims[1], dims[2]);
            write_tensor(&alpha.reshape((l * p, k))?, path)
        } else {
            write_tensor(&alpha, path)
        }
    }

    fn write_all_sparse(&self, header: &str) -> Result<()> {
        self.write_all(header)?;
        self.write_pip(&format!("{}.pip.gz", header))?;
        self.write_alpha(&format!("{}.alpha.gz", header))
    }
}

impl VariationalOutput for super::BiSusieVar {
    fn write_mean(&self, path: &str) -> Result<()> {
        write_tensor(&self.theta_mean()?, path)
    }

    fn write_var(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::var(self)?, path)
    }

    fn write_std(&self, path: &str) -> Result<()> {
        write_tensor(&VariationalDistribution::var(self)?.sqrt()?, path)
    }

    fn write_all(&self, header: &str) -> Result<()> {
        self.write_mean(&format!("{}.mean.gz", header))?;
        self.write_std(&format!("{}.std.gz", header))
    }

    fn to_melted_parquet(
        &self,
        file_path: &str,
        row_names: (Option<&[Box<str>]>, Option<&str>),
        column_names: (Option<&[Box<str>]>, Option<&str>),
    ) -> Result<()> {
        let mean = self.theta_mean()?;
        let std = VariationalDistribution::var(self)?.sqrt()?;
        let pip = self.pip()?;

        let (mean_vals, row_idx, col_idx) = melt_tensor(&mean)?;
        let (std_vals, _, _) = melt_tensor(&std)?;
        let (pip_vals, _, _) = melt_tensor(&pip)?;

        let rows = indices_to_names(&row_idx, row_names.0);
        let cols = indices_to_names(&col_idx, column_names.0);

        write_melted_parquet(
            file_path,
            "BiSusieVar",
            row_names.1.unwrap_or("predictor"),
            column_names.1.unwrap_or("outcome"),
            &rows,
            &cols,
            &[("mean", &mean_vals), ("std", &std_vals), ("pip", &pip_vals)],
        )
    }
}

impl SparseVariationalOutput for super::BiSusieVar {
    fn write_pip(&self, path: &str) -> Result<()> {
        write_tensor(&self.pip()?, path)
    }

    fn write_alpha(&self, path: &str) -> Result<()> {
        let alpha = self.alpha_joint()?;
        let dims = alpha.dims();
        if dims.len() == 3 {
            let (l, p, k) = (dims[0], dims[1], dims[2]);
            write_tensor(&alpha.reshape((l * p, k))?, path)
        } else {
            write_tensor(&alpha, path)
        }
    }

    fn write_all_sparse(&self, header: &str) -> Result<()> {
        self.write_all(header)?;
        self.write_pip(&format!("{}.pip.gz", header))?;
        self.write_alpha(&format!("{}.alpha.gz", header))
    }
}

//
// Tests
//

#[cfg(test)]
mod tests {
    use super::*;
    use candle_core::{DType, Device};
    use candle_nn::{VarBuilder, VarMap};
    use tempfile::tempdir;

    #[test]
    fn test_gaussian_var_output() -> Result<()> {
        let varmap = VarMap::new();
        let vb = VarBuilder::from_varmap(&varmap, DType::F32, &Device::Cpu);
        let gaussian = super::super::GaussianVar::new(vb, 10, 3)?;

        let dir = tempdir()?;
        let header = dir.path().join("test_gaussian");
        gaussian.write_all(header.to_str().unwrap())?;

        assert!(dir.path().join("test_gaussian.mean.gz").exists());
        assert!(dir.path().join("test_gaussian.std.gz").exists());

        let pq_path = dir.path().join("test_gaussian.parquet");
        gaussian.to_parquet(pq_path.to_str().unwrap())?;
        assert!(pq_path.exists());

        Ok(())
    }

    #[test]
    fn test_susie_var_output() -> Result<()> {
        let varmap = VarMap::new();
        let vb = VarBuilder::from_varmap(&varmap, DType::F32, &Device::Cpu);
        let susie = super::super::SusieVar::new(vb, 3, 10, 2)?;

        let dir = tempdir()?;
        let header = dir.path().join("test_susie");
        susie.write_all_sparse(header.to_str().unwrap())?;

        assert!(dir.path().join("test_susie.mean.gz").exists());
        assert!(dir.path().join("test_susie.std.gz").exists());
        assert!(dir.path().join("test_susie.pip.gz").exists());
        assert!(dir.path().join("test_susie.alpha.gz").exists());

        let pq_path = dir.path().join("test_susie.parquet");
        susie.to_parquet(pq_path.to_str().unwrap())?;
        assert!(pq_path.exists());

        Ok(())
    }

    #[test]
    fn test_parquet_with_names() -> Result<()> {
        let varmap = VarMap::new();
        let vb = VarBuilder::from_varmap(&varmap, DType::F32, &Device::Cpu);
        let susie = super::super::SusieVar::new(vb, 2, 5, 2)?;

        let row_names: Vec<Box<str>> = (0..5).map(|i| format!("gene_{}", i).into()).collect();
        let col_names: Vec<Box<str>> = vec!["output_0".into(), "output_1".into()];

        let dir = tempdir()?;
        let pq_path = dir.path().join("named.parquet");
        susie.to_melted_parquet(
            pq_path.to_str().unwrap(),
            (Some(&row_names), Some("row")),
            (Some(&col_names), None),
        )?;
        assert!(pq_path.exists());

        Ok(())
    }
}