torsh-sparse 0.1.3

Sparse tensor operations for ToRSh with SciRS2 integration
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
546
547
548
549
550
//! Sparse linear algebra and advanced element-wise operations
//!
//! This module contains operations that require more advanced mathematical
//! constructs: triangular solvers, addcmul/addcdiv, masking, clamping,
//! and unary element-wise ops (abs, sign, pow, sqrt).

use super::*;

/// Solve triangular system Ax = b where A is a sparse triangular matrix
///
/// # Arguments
/// * `a` - Triangular sparse matrix (either upper or lower triangular)
/// * `b` - Right-hand side vector or matrix
/// * `upper` - If true, A is upper triangular; if false, A is lower triangular
/// * `transpose` - If true, solve A^T x = b instead of Ax = b
///
/// # Returns
/// Solution x to the triangular system
pub fn triangular_solve(
    a: &dyn SparseTensor,
    b: &Tensor,
    upper: bool,
    transpose: bool,
) -> TorshResult<Tensor> {
    // Validate that matrix is square
    utils::validate_square(a)?;

    let n = a.shape().dims()[0];

    // Validate b dimensions
    if b.shape().dims()[0] != n {
        return Err(TorshError::InvalidArgument(format!(
            "Dimension mismatch: matrix size {} but RHS size {}",
            n,
            b.shape().dims()[0]
        )));
    }

    // Check if b is a vector or matrix
    let is_vector = b.shape().ndim() == 1;
    let nrhs = if is_vector { 1 } else { b.shape().dims()[1] };

    // Convert to CSR for efficient row access
    let a_csr = a.to_csr()?;

    // Initialize solution
    let x = if is_vector {
        zeros::<f32>(&[n])?
    } else {
        zeros::<f32>(&[n, nrhs])?
    };

    // Solve based on triangular type and transpose flag
    match (upper, transpose) {
        (false, false) => {
            // Lower triangular: forward substitution
            for i in 0..n {
                for j in 0..nrhs {
                    let mut sum = if is_vector {
                        b.get(&[i])?
                    } else {
                        b.get(&[i, j])?
                    };

                    let (cols, vals) = a_csr.get_row(i)?;
                    for (k, &col) in cols.iter().enumerate() {
                        if col < i {
                            let x_val = if is_vector {
                                x.get(&[col])?
                            } else {
                                x.get(&[col, j])?
                            };
                            sum -= vals[k] * x_val;
                        } else if col == i {
                            // Diagonal element
                            if vals[k].abs() < f32::EPSILON {
                                return Err(TorshError::ComputeError(
                                    "Singular matrix: zero diagonal element".to_string(),
                                ));
                            }
                            sum /= vals[k];
                            break;
                        }
                    }

                    if is_vector {
                        x.set(&[i], sum)?;
                    } else {
                        x.set(&[i, j], sum)?;
                    }
                }
            }
        }
        (true, false) => {
            // Upper triangular: backward substitution
            for i in (0..n).rev() {
                for j in 0..nrhs {
                    let mut sum = if is_vector {
                        b.get(&[i])?
                    } else {
                        b.get(&[i, j])?
                    };

                    let (cols, vals) = a_csr.get_row(i)?;
                    for (k, &col) in cols.iter().enumerate() {
                        if col > i {
                            let x_val = if is_vector {
                                x.get(&[col])?
                            } else {
                                x.get(&[col, j])?
                            };
                            sum -= vals[k] * x_val;
                        } else if col == i {
                            // Diagonal element
                            if vals[k].abs() < f32::EPSILON {
                                return Err(TorshError::ComputeError(
                                    "Singular matrix: zero diagonal element".to_string(),
                                ));
                            }
                            sum /= vals[k];
                        }
                    }

                    if is_vector {
                        x.set(&[i], sum)?;
                    } else {
                        x.set(&[i, j], sum)?;
                    }
                }
            }
        }
        (false, true) => {
            // Lower triangular transposed (acts as upper): backward substitution on transpose
            // A^T x = b where A is lower triangular, so A^T is upper triangular
            let a_csc = a.to_csc()?; // Use CSC for efficient column access (rows of A^T)

            for i in (0..n).rev() {
                for j in 0..nrhs {
                    let mut sum = if is_vector {
                        b.get(&[i])?
                    } else {
                        b.get(&[i, j])?
                    };

                    let (rows, vals) = a_csc.get_col(i)?;
                    for (k, &row) in rows.iter().enumerate() {
                        if row > i {
                            let x_val = if is_vector {
                                x.get(&[row])?
                            } else {
                                x.get(&[row, j])?
                            };
                            sum -= vals[k] * x_val;
                        } else if row == i {
                            if vals[k].abs() < f32::EPSILON {
                                return Err(TorshError::ComputeError(
                                    "Singular matrix: zero diagonal element".to_string(),
                                ));
                            }
                            sum /= vals[k];
                        }
                    }

                    if is_vector {
                        x.set(&[i], sum)?;
                    } else {
                        x.set(&[i, j], sum)?;
                    }
                }
            }
        }
        (true, true) => {
            // Upper triangular transposed (acts as lower): forward substitution on transpose
            let a_csc = a.to_csc()?;

            for i in 0..n {
                for j in 0..nrhs {
                    let mut sum = if is_vector {
                        b.get(&[i])?
                    } else {
                        b.get(&[i, j])?
                    };

                    let (rows, vals) = a_csc.get_col(i)?;
                    for (k, &row) in rows.iter().enumerate() {
                        if row < i {
                            let x_val = if is_vector {
                                x.get(&[row])?
                            } else {
                                x.get(&[row, j])?
                            };
                            sum -= vals[k] * x_val;
                        } else if row == i {
                            if vals[k].abs() < f32::EPSILON {
                                return Err(TorshError::ComputeError(
                                    "Singular matrix: zero diagonal element".to_string(),
                                ));
                            }
                            sum /= vals[k];
                            break;
                        }
                    }

                    if is_vector {
                        x.set(&[i], sum)?;
                    } else {
                        x.set(&[i, j], sum)?;
                    }
                }
            }
        }
    }

    Ok(x)
}

/// Performs element-wise multiplication and addition: out = input + value * tensor1 * tensor2
/// PyTorch equivalent: torch.addcmul(input, tensor1, tensor2, value=1.0)
///
/// # Arguments
/// * `input` - Base sparse tensor
/// * `tensor1` - First multiplicand sparse tensor
/// * `tensor2` - Second multiplicand sparse tensor
/// * `value` - Scalar multiplier for the element-wise product
///
/// # Returns
/// Result of input + value * (tensor1 * tensor2) as COO tensor
pub fn addcmul(
    input: &dyn SparseTensor,
    tensor1: &dyn SparseTensor,
    tensor2: &dyn SparseTensor,
    value: f32,
) -> TorshResult<CooTensor> {
    // Validate all tensors have the same shape
    utils::validate_same_shape(input, tensor1)?;
    utils::validate_same_shape(input, tensor2)?;

    // Convert all to COO for element-wise operations
    let input_coo = utils::to_coo_safe(input)?;
    let tensor1_coo = utils::to_coo_safe(tensor1)?;
    let tensor2_coo = utils::to_coo_safe(tensor2)?;

    // Create position maps for efficient lookup
    let input_map = utils::create_position_map(&input_coo);
    let tensor1_map = utils::create_position_map(&tensor1_coo);
    let tensor2_map = utils::create_position_map(&tensor2_coo);

    // Compute result: input + value * tensor1 * tensor2
    let mut result_map: HashMap<(usize, usize), f32> = HashMap::new();

    // Add input values
    for ((row, col), val) in input_map {
        result_map.insert((row, col), val);
    }

    // Add value * tensor1 * tensor2 for positions where both tensor1 and tensor2 are non-zero
    for ((row, col), val1) in tensor1_map {
        if let Some(&val2) = tensor2_map.get(&(row, col)) {
            let product = value * val1 * val2;
            *result_map.entry((row, col)).or_insert(0.0) += product;
        }
    }

    // Convert result map to COO format
    let (row_indices, col_indices, values): (Vec<_>, Vec<_>, Vec<_>) = result_map
        .into_iter()
        .filter(|(_, v)| v.abs() > f32::EPSILON)
        .fold(
            (Vec::new(), Vec::new(), Vec::new()),
            |(mut rows, mut cols, mut vals), ((r, c), v)| {
                rows.push(r);
                cols.push(c);
                vals.push(v);
                (rows, cols, vals)
            },
        );

    CooTensor::new(row_indices, col_indices, values, input.shape().clone())
}

/// Performs element-wise division and addition: out = input + value * tensor1 / tensor2
/// PyTorch equivalent: torch.addcdiv(input, tensor1, tensor2, value=1.0)
///
/// # Arguments
/// * `input` - Base sparse tensor
/// * `tensor1` - Numerator sparse tensor
/// * `tensor2` - Denominator sparse tensor
/// * `value` - Scalar multiplier for the element-wise quotient
///
/// # Returns
/// Result of input + value * (tensor1 / tensor2) as COO tensor
///
/// # Notes
/// - Division by zero results in 0 (sparse semantics)
/// - Only positions where tensor2 is non-zero contribute to the result
pub fn addcdiv(
    input: &dyn SparseTensor,
    tensor1: &dyn SparseTensor,
    tensor2: &dyn SparseTensor,
    value: f32,
) -> TorshResult<CooTensor> {
    // Validate all tensors have the same shape
    utils::validate_same_shape(input, tensor1)?;
    utils::validate_same_shape(input, tensor2)?;

    // Convert all to COO for element-wise operations
    let input_coo = utils::to_coo_safe(input)?;
    let tensor1_coo = utils::to_coo_safe(tensor1)?;
    let tensor2_coo = utils::to_coo_safe(tensor2)?;

    // Create position maps for efficient lookup
    let input_map = utils::create_position_map(&input_coo);
    let tensor1_map = utils::create_position_map(&tensor1_coo);
    let tensor2_map = utils::create_position_map(&tensor2_coo);

    // Compute result: input + value * tensor1 / tensor2
    let mut result_map: HashMap<(usize, usize), f32> = HashMap::new();

    // Add input values
    for ((row, col), val) in input_map {
        result_map.insert((row, col), val);
    }

    // Add value * tensor1 / tensor2 for positions where both tensor1 and tensor2 are non-zero
    for ((row, col), val1) in tensor1_map {
        if let Some(&val2) = tensor2_map.get(&(row, col)) {
            if val2.abs() > f32::EPSILON {
                let quotient = value * val1 / val2;
                *result_map.entry((row, col)).or_insert(0.0) += quotient;
            }
        }
    }

    // Convert result map to COO format
    let (row_indices, col_indices, values): (Vec<_>, Vec<_>, Vec<_>) = result_map
        .into_iter()
        .filter(|(_, v)| v.abs() > f32::EPSILON)
        .fold(
            (Vec::new(), Vec::new(), Vec::new()),
            |(mut rows, mut cols, mut vals), ((r, c), v)| {
                rows.push(r);
                cols.push(c);
                vals.push(v);
                (rows, cols, vals)
            },
        );

    CooTensor::new(row_indices, col_indices, values, input.shape().clone())
}

/// Apply a conditional fill operation: replace values that satisfy a condition
/// PyTorch equivalent: torch.masked_fill(tensor, mask, value)
///
/// # Arguments
/// * `tensor` - Input sparse tensor
/// * `condition` - Predicate function that returns true for values to be replaced
/// * `fill_value` - Value to use for replacement
///
/// # Returns
/// New sparse tensor with values replaced where condition is true
pub fn masked_fill<F>(
    tensor: &dyn SparseTensor,
    condition: F,
    fill_value: f32,
) -> TorshResult<CooTensor>
where
    F: Fn(f32) -> bool,
{
    let coo = utils::to_coo_safe(tensor)?;

    // Apply condition and replace matching values
    let triplets: Vec<_> = coo
        .triplets()
        .into_iter()
        .map(|(r, c, v)| {
            if condition(v) {
                (r, c, fill_value)
            } else {
                (r, c, v)
            }
        })
        .collect();

    // Filter out zeros
    let (row_indices, col_indices, values) =
        utils::extract_filtered_triplets(triplets, f32::EPSILON);

    CooTensor::new(row_indices, col_indices, values, tensor.shape().clone())
}

/// Clamp sparse tensor values to a specified range
/// PyTorch equivalent: torch.clamp(tensor, min, max)
///
/// # Arguments
/// * `tensor` - Input sparse tensor
/// * `min` - Optional minimum value (None means no lower bound)
/// * `max` - Optional maximum value (None means no upper bound)
///
/// # Returns
/// New sparse tensor with values clamped to [min, max]
pub fn clamp(
    tensor: &dyn SparseTensor,
    min: Option<f32>,
    max: Option<f32>,
) -> TorshResult<CooTensor> {
    let coo = utils::to_coo_safe(tensor)?;

    // Clamp values
    let triplets: Vec<_> = coo
        .triplets()
        .into_iter()
        .map(|(r, c, mut v)| {
            if let Some(min_val) = min {
                v = v.max(min_val);
            }
            if let Some(max_val) = max {
                v = v.min(max_val);
            }
            (r, c, v)
        })
        .collect();

    // Filter out zeros
    let (row_indices, col_indices, values) =
        utils::extract_filtered_triplets(triplets, f32::EPSILON);

    CooTensor::new(row_indices, col_indices, values, tensor.shape().clone())
}

/// Compute absolute value of sparse tensor elements
/// PyTorch equivalent: torch.abs(tensor)
///
/// # Arguments
/// * `tensor` - Input sparse tensor
///
/// # Returns
/// New sparse tensor with absolute values
pub fn abs(tensor: &dyn SparseTensor) -> TorshResult<CooTensor> {
    let coo = utils::to_coo_safe(tensor)?;

    let triplets: Vec<_> = coo
        .triplets()
        .into_iter()
        .map(|(r, c, v)| (r, c, v.abs()))
        .collect();

    let (row_indices, col_indices, values) = utils::extract_filtered_triplets(triplets, 0.0);

    CooTensor::new(row_indices, col_indices, values, tensor.shape().clone())
}

/// Compute sign of sparse tensor elements
/// PyTorch equivalent: torch.sign(tensor)
///
/// # Arguments
/// * `tensor` - Input sparse tensor
///
/// # Returns
/// New sparse tensor with signs (-1, 0, or 1)
///
/// # Notes
/// - sign(x) = -1 if x < 0
/// - sign(x) = 0 if x == 0
/// - sign(x) = 1 if x > 0
pub fn sign(tensor: &dyn SparseTensor) -> TorshResult<CooTensor> {
    let coo = utils::to_coo_safe(tensor)?;

    let triplets: Vec<_> = coo
        .triplets()
        .into_iter()
        .map(|(r, c, v)| {
            let sign_val = if v > 0.0 {
                1.0
            } else if v < 0.0 {
                -1.0
            } else {
                0.0
            };
            (r, c, sign_val)
        })
        .collect();

    // Filter out zeros (sign(0) = 0)
    let (row_indices, col_indices, values) =
        utils::extract_filtered_triplets(triplets, f32::EPSILON);

    CooTensor::new(row_indices, col_indices, values, tensor.shape().clone())
}

/// Apply power operation element-wise: tensor^exponent
/// PyTorch equivalent: torch.pow(tensor, exponent)
///
/// # Arguments
/// * `tensor` - Input sparse tensor
/// * `exponent` - Power to raise each element to
///
/// # Returns
/// New sparse tensor with each element raised to the power
pub fn pow(tensor: &dyn SparseTensor, exponent: f32) -> TorshResult<CooTensor> {
    let coo = utils::to_coo_safe(tensor)?;

    let triplets: Vec<_> = coo
        .triplets()
        .into_iter()
        .map(|(r, c, v)| (r, c, v.powf(exponent)))
        .collect();

    let (row_indices, col_indices, values) =
        utils::extract_filtered_triplets(triplets, f32::EPSILON);

    CooTensor::new(row_indices, col_indices, values, tensor.shape().clone())
}

/// Square each element of sparse tensor
/// PyTorch equivalent: torch.square(tensor) or tensor**2
///
/// # Arguments
/// * `tensor` - Input sparse tensor
///
/// # Returns
/// New sparse tensor with squared values
pub fn square(tensor: &dyn SparseTensor) -> TorshResult<CooTensor> {
    pow(tensor, 2.0)
}

/// Square root of each element of sparse tensor
/// PyTorch equivalent: torch.sqrt(tensor)
///
/// # Arguments
/// * `tensor` - Input sparse tensor
///
/// # Returns
/// New sparse tensor with square root values
///
/// # Notes
/// - Negative values will produce NaN (following PyTorch behavior)
pub fn sqrt(tensor: &dyn SparseTensor) -> TorshResult<CooTensor> {
    let coo = utils::to_coo_safe(tensor)?;

    let triplets: Vec<_> = coo
        .triplets()
        .into_iter()
        .map(|(r, c, v)| (r, c, v.sqrt()))
        .collect();

    let (row_indices, col_indices, values) =
        utils::extract_filtered_triplets(triplets, f32::EPSILON);

    CooTensor::new(row_indices, col_indices, values, tensor.shape().clone())
}