mi2graph 0.3.0

Generate MIC relations between features with dynamic feature filtering for graph initialization
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
use chrono::Local;
use ndarray::prelude::*;
use ndarray_npy::NpzWriter;
use polars::prelude::*;
use rayon::prelude::*;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fs::File;
use std::path::Path;

mod mutualinfo;
mod processing;
mod slidingwindow;
mod sortf64;

use mutualinfo::iter_feat_pairs_mi;
use processing::{remove_feat_similar, rm_feat_low_cv};
use slidingwindow::init_windows_from_ratio;
use sortf64::get_sort_indices_vecf64;

/// Generate NMIC relations between features with dynamic feature filtering for the next graph initialization.
///
/// **Steps**:
/// 1. Remove features with low coefficients of variation (using dynamic sliding windows).
/// 2. Detect similar features pairs [Optional] (using dynamic 2D sliding windows for maxmizing PCC(`abs=true`)) then remove redundant features.
/// 3. Compute NMIC for each feature pair (using dynamic sliding windows).
/// 4. Filter out weak NMIC values and corresponding feature pairs.
/// 5. Save sorted NMIC values, feature pairs, processed input data, feature indices, similar feature pairs and input arguments.
///
/// **Input**:
/// + `path_output`: path to save the result files
/// + `data`: input data with shape (n_var, n_obs)
/// + `obs_names`: observation names
/// + `var_names`: variable names
/// + `check_sim`: whether to detect similar features pairs and remove redundant features
/// + `thre_cv`: threshold for removing features with low coefficients of variation
/// + `thre_pcc`: threshold for removing redundant features
/// + `thre_mi`: threshold for removing feature pairs with low mutual information
/// + `ratio_max_window`: maximum (window_size / num_samples)
/// + `ratio_min_window`: minimum (window_size / num_samples)
/// + `ratio_step_window`: window_size_step_len / num_samples
/// + `ratio_step_sliding`: sliding_step_len / num_samples
/// + `n_threads`: number of threads
///
/// **Output**:
/// + NPZ file
///     + `mi_values`: sorted mutual information values
///     + `feat_pairs`: corresponding feature pairs (edges)
///     + `processed_mat`: The processed input matrix after *Step 3*
///     + `mat_feat_indices`: The feature indices of the processed matrix
///     + `mat_simi_feat_pairs`: Similar feature pairs given by *Step 3*
///     + input_args: The input arguments
/// + Parquet file
///     + The named dataframe of `processed_mat`
///
pub fn mic_mat_with_data_filter(
    path_output: &str,
    data: &Array2<f64>,
    obs_names: &DataFrame,
    var_names: &Vec<String>,
    check_sim: bool,
    n_features_to_select: usize,
    thre_cv: f64,
    thre_pcc: f64,
    thre_mi: f64,
    ratio_max_window: f64,
    ratio_min_window: f64,
    ratio_step_window: f64,
    ratio_step_sliding: f64,
    n_threads: usize,
) -> Result<(), Box<dyn Error>> {
    // Check available threads
    let mut num_threads = std::thread::available_parallelism().unwrap().get();
    if num_threads > 2 {
        num_threads -= 1;
    }
    if num_threads > n_threads && n_threads > 0 {
        num_threads = n_threads;
    }
    rayon::ThreadPoolBuilder::new()
        .num_threads(num_threads)
        .build_global()
        .unwrap();
    println!("\n⚡️  Using {} threads", num_threads);

    // Initialize various sliding windows
    let sliding_windows = init_windows_from_ratio(
        data.ncols(),
        ratio_min_window,
        ratio_max_window,
        ratio_step_window,
        ratio_step_sliding,
    );

    // Pre-compute the sort indices for each feature.
    let features: Vec<Vec<f64>> = (0..data.nrows()).map(|i| data.row(i).to_vec()).collect();
    let mut features_sort_indices: Vec<Vec<usize>> = features
        .par_iter()
        .map(|feat| get_sort_indices_vecf64(feat))
        .collect();

    // Print start time
    println!("\nStart feature selection at: {:?}\n", Local::now());

    // 1. Remove low-CV features
    let (mut data_0, feat_indices_0, tmp_features_sort_indices) = rm_feat_low_cv(
        data,
        thre_cv,
        n_features_to_select,
        &sliding_windows,
        &features_sort_indices,
    );
    features_sort_indices = tmp_features_sort_indices;
    println!(
        "✅ Shape of data after removing features with low CV (coefficient of variation) values: {:?} (n_feat x n_obs)",
        data_0.shape()
    );

    // 2. Detect similar features pairs and remove redundant features
    let mut feat_indices_1 = feat_indices_0.clone();
    let mut simi_feat_pairs = Array2::<i64>::zeros((0, 2));

    if check_sim {
        println!("\nStart removing similar features.");
        (
            data_0,
            feat_indices_1,
            simi_feat_pairs,
            features_sort_indices,
        ) = remove_feat_similar(&data_0, thre_pcc, &sliding_windows, &features_sort_indices);
        println!(
            "✅ Shape of data after removing similar features: {:?}",
            data_0.shape()
        );
    } else {
        println!("\n✅ Skip removing similar features.");
    }

    // Print time
    let time_start = Local::now();
    println!("\nStart computing NMIC relations: {:?}", time_start);

    // 3. Compute NMIC for each feature pair
    let (mi_values, feat_pairs) =
        iter_feat_pairs_mi(&data_0, &sliding_windows, &features_sort_indices, true);

    // Print end time
    let time_end = Local::now();
    println!("End time:   {:?}", time_end);
    // Print time cost in seconds and hours
    let time_cost = time_end - time_start;
    let time_cost_seconds = time_cost.num_seconds();
    let time_cost_hours = time_cost_seconds as f64 / 3600.0;
    println!(
        "⏱️ Elapsed time:  {} seconds, or {:.2} hours\n",
        time_cost_seconds, time_cost_hours
    );

    // 4. Remove low-NMIC feature pairs.
    // mi_values and feat_pairs have been sorted. We check elements from the end.
    let last2keep = check_sorted_vals(&mi_values, thre_mi);
    // Keep pairs that idx >= last2keep
    let mi_values_o: Array1<f64> = mi_values.slice(s![..last2keep]).to_owned();
    let mut feat_pairs_o: Array2<i64> = feat_pairs.slice(s![..last2keep, ..]).to_owned();
    println!(
        "Number of feature pairs after removing weak NMIC values: {}",
        last2keep + 1
    );

    // Get sorted unique features in pairs
    let flattened: Array1<i64> = feat_pairs_o.iter().copied().collect();
    let uniq_features: HashSet<i64> = flattened.into_iter().collect();
    let mut sorted_uniq_features: Vec<usize> = uniq_features.iter().map(|&x| x as usize).collect();
    sorted_uniq_features.sort();

    // Convert feat_pairs_o based on feat_indices_1
    let mut map_1: HashMap<usize, usize> = HashMap::new();
    sorted_uniq_features.iter().for_each(|&i| {
        map_1.insert(i, *feat_indices_1.get(i).unwrap());
    });
    feat_pairs_o.outer_iter_mut().for_each(|mut row| {
        row[0] = *map_1.get(&(row[0] as usize)).unwrap() as i64;
        row[1] = *map_1.get(&(row[1] as usize)).unwrap() as i64;
    });

    // Remove features of data_1 that are not in sorted_uniq_features
    data_0 = data_0.select(Axis(0), &sorted_uniq_features);

    // Convert features indices after NMIC filtering
    sorted_uniq_features.par_iter_mut().for_each(|i| {
        *i = *map_1.get(&(*i)).unwrap();
    });

    // Convert feature indices to original indices.
    if check_sim {
        // Create a map from new indices (feat_indices_1) to original indices (feat_indices_0).
        let mut map_new2orig: HashMap<usize, usize> = HashMap::new();
        sorted_uniq_features.iter().for_each(|&i| {
            map_new2orig.insert(i, *feat_indices_0.get(i).unwrap());
        });
        // unwrap() is not safe because of the possibility of a None value.
        // if None occurs, the program will panic.

        // Update indices
        feat_pairs_o.outer_iter_mut().for_each(|mut row| {
            row[0] = *map_new2orig.get(&(row[0] as usize)).unwrap() as i64;
            row[1] = *map_new2orig.get(&(row[1] as usize)).unwrap() as i64;
        });
        sorted_uniq_features.par_iter_mut().for_each(|i| {
            *i = *map_new2orig.get(i).unwrap();
        });
        simi_feat_pairs.outer_iter_mut().for_each(|mut row| {
            row[0] = *map_new2orig.get(&(row[0] as usize)).unwrap() as i64;
            row[1] = *map_new2orig.get(&(row[1] as usize)).unwrap() as i64;
        });
    }

    println!("Number of features: {}", sorted_uniq_features.len());

    let data_1_feat_indices_o: Array1<i64> =
        Array1::from_vec(sorted_uniq_features.par_iter().map(|&i| i as i64).collect());

    // 5. Save results
    // 5.1 Save results to a NPZ file
    save_npz(
        path_output,
        &mi_values_o,
        &feat_pairs_o,
        &data_0,
        &data_1_feat_indices_o,
        &simi_feat_pairs,
        thre_cv,
        thre_pcc,
        thre_mi,
        ratio_max_window,
        ratio_min_window,
        ratio_step_window,
        ratio_step_sliding,
    )?;
    // 5.2 Save processed matrix to a parquet file
    save_parquet(
        &format!("{}.parquet", path_output),
        &data_0,
        obs_names,
        var_names,
        &sorted_uniq_features,
    )?;

    Ok(())
}

/// Save all data to a NPZ file
fn save_npz(
    path_output_npz: &str,
    mi_values: &Array1<f64>,
    feat_pairs: &Array2<i64>,
    processed_mat: &Array2<f64>,
    feat_indices: &Array1<i64>,
    simi_feat_pairs: &Array2<i64>,
    thre_cv: f64,
    thre_pcc: f64,
    thre_mi: f64,
    ratio_max_window: f64,
    ratio_min_window: f64,
    ratio_step_window: f64,
    ratio_step_sliding: f64,
) -> Result<(), Box<dyn Error>> {
    let mut path_npz = format!("{}.npz", path_output_npz);
    // Check if path_output_npz ends with .npz
    if path_output_npz.ends_with(".npz") {
        path_npz = path_output_npz.to_string();
    }
    // Check if the file exists. If it does, add timestamp to the file name.
    if Path::new(&path_npz).exists() {
        let timestamp = Local::now().format("%Y%m%d%H%M%S");
        if path_output_npz.ends_with(".npz") {
            path_npz = path_output_npz.replace(".npz", &format!("_{}.npz", timestamp));
        } else {
            path_npz = format!("{}_{}.npz", path_output_npz, timestamp);
        }
    }
    let path_npz_c = &path_npz.clone();

    let file_npz = File::create(path_npz_c)?;
    let mut npz = NpzWriter::new_compressed(file_npz);
    npz.add_array("mi_values", mi_values)?;
    npz.add_array("feat_pairs", feat_pairs)?;
    npz.add_array("processed_mat", &processed_mat)?;
    npz.add_array("mat_feat_indices", &feat_indices)?;
    npz.add_array("mat_simi_feat_pairs", &simi_feat_pairs)?;
    // Save input parameters as length 1 ndarray
    npz.add_array("thre_cv", &Array1::from_vec(vec![thre_cv]))?;
    npz.add_array("thre_pcc", &Array1::from_vec(vec![thre_pcc]))?;
    npz.add_array("thre_mi", &Array1::from_vec(vec![thre_mi]))?;
    npz.add_array(
        "ratio_max_window",
        &Array1::from_vec(vec![ratio_max_window]),
    )?;
    npz.add_array(
        "ratio_min_window",
        &Array1::from_vec(vec![ratio_min_window]),
    )?;
    npz.add_array(
        "ratio_step_window",
        &Array1::from_vec(vec![ratio_step_window]),
    )?;
    npz.add_array(
        "ratio_step_sliding",
        &Array1::from_vec(vec![ratio_step_sliding]),
    )?;
    // Finish writing
    npz.finish()?;

    println!("Results have been saved to \"{}\"", path_npz_c);

    Ok(())
}

/// Save processed matrix to a parquet file
fn save_parquet(
    path_output_parquet: &str,
    processed_mat: &Array2<f64>,
    obs_names: &DataFrame,
    var_names: &Vec<String>,
    feat_indices: &Vec<usize>,
) -> Result<(), Box<dyn Error>> {
    // Check if path_output_parquet ends with .parquet
    let mut path_parquet = format!("{}.parquet", path_output_parquet);
    if path_output_parquet.ends_with(".parquet") {
        path_parquet = path_output_parquet.to_string();
    }
    // Check if the file exists. If it does, add timestamp to the file name.
    if Path::new(&path_parquet).exists() {
        let timestamp = Local::now().format("%Y%m%d%H%M%S");
        if path_output_parquet.ends_with(".parquet") {
            path_parquet =
                path_output_parquet.replace(".parquet", &format!("_{}.parquet", timestamp));
        } else {
            path_parquet = format!("{}_{}.parquet", path_output_parquet, timestamp);
        }
    }
    let path_parquet_c = &path_parquet.clone();

    // Pick saved var (feature) names based on feat_indices
    let saved_var_names = var_names
        .iter()
        .enumerate()
        .filter(|(i, _)| feat_indices.contains(i))
        .map(|(_, x)| x.clone())
        .collect::<Vec<_>>();

    // Create a new DataFrame with processed_mat, obs_names and the selected var_names
    let vec_columns: Vec<Column> = saved_var_names
        .iter()
        .zip(processed_mat.outer_iter())
        .map(|(name, values)| Column::new(name.into(), values.to_vec()))
        .collect();

    let mut df1 = obs_names.hstack(&vec_columns)?;

    let mut file = File::create(path_parquet_c)?;
    ParquetWriter::new(&mut file).finish(&mut df1)?;

    println!(
        "Processed matrix has been saved as a polars dataframe containing observation names and feature names: \"{}\"",
        path_parquet_c
    );
    Ok(())
}

/// Read parquet file (n_obs x (1 + n_vars)) into ndarray (n_obs x n_vars)
pub fn read_parquet_to_array2d(
    path_parquet: &str,
) -> Result<(Array2<f64>, DataFrame, Vec<String>), Box<dyn Error>> {
    let mut file = std::fs::File::open(path_parquet).unwrap();
    let df = ParquetReader::new(&mut file).finish().unwrap();
    // let mat = df.to_ndarray::<f64>().unwrap();
    // let lf1 = LazyFrame::scan_parquet(path_parquet, Default::default())?;
    let obs_names = df.select(["obs_names"])?;
    let binding = df.drop("obs_names")?;
    let var_names_0 = binding.get_column_names();
    // Convert Vec<&PlSmallStr> to Vec<String>
    let var_names: Vec<String> = var_names_0.iter().map(|x| x.to_string()).collect();
    let mat = binding
        .to_ndarray::<Float64Type>(IndexOrder::Fortran)
        .unwrap()
        .t()
        .to_owned();
    Ok((mat, obs_names, var_names))
}

/// mi_values and feat_pairs have been sorted. We can check elements from the end.
fn check_sorted_vals(vals: &Array1<f64>, threshold: f64) -> usize {
    let num_pairs = vals.len();
    // Start from the end
    let mut chk_i = num_pairs - 1;
    while chk_i > 0 {
        // Stop if the current pair has a higher MI than the threshold
        if vals[chk_i] > threshold {
            break;
        }
        chk_i -= 1;
    }
    chk_i
}