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
//! Scalar operations for COO matrices (scalar multiplication and addition)
use super::super::CooData;
use crate::error::Result;
use crate::ops::ScalarOps;
use crate::runtime::Runtime;
impl<R: Runtime> CooData<R> {
/// Scalar multiplication: C = A * scalar
///
/// Multiplies all non-zero values by a scalar constant.
/// Preserves the sparsity pattern.
///
/// # Arguments
///
/// * `scalar` - The scalar value to multiply with
///
/// # Performance
///
/// O(nnz) - simply scales the values tensor
///
/// # Example
///
/// ```
/// # use numr::prelude::*;
/// # #[cfg(feature = "sparse")]
/// # {
/// # use numr::sparse::SparseTensor;
/// # let device = CpuDevice::new();
/// # let sp = SparseTensor::<CpuRuntime>::from_coo_slices(&[0], &[0], &[1.0f32], [1, 1], &device)?;
/// # if let numr::sparse::SparseTensor::Coo(coo) = sp {
/// let result = coo.scalar_mul(2.0)?; // Multiply all values by 2
/// # }
/// # }
/// # Ok::<(), numr::error::Error>(())
/// ```
pub fn scalar_mul(&self, scalar: f64) -> Result<Self>
where
R::Client: ScalarOps<R>,
{
let device = self.values.device();
let client = R::default_client(device);
let scaled_values = client.mul_scalar(&self.values, scalar)?;
Ok(Self {
row_indices: self.row_indices.clone(),
col_indices: self.col_indices.clone(),
values: scaled_values,
shape: self.shape,
sorted: self.sorted,
})
}
/// Add scalar to non-zero elements only (sparsity-preserving)
///
/// # ⚠️ Important: This is NOT Standard Scalar Addition!
///
/// Standard mathematical scalar addition (`A + s`) adds `s` to **ALL** elements
/// including implicit zeros, creating a dense matrix. This operation only adds
/// to existing non-zero values, preserving the sparse structure.
///
/// Use this when you want to shift all non-zero values by a constant without
/// densifying the matrix. For true scalar addition, convert to dense first.
///
/// # Mathematical Behavior
///
/// - **Non-zero elements**: `A[i,j] + s`
/// - **Zero elements**: remain `0` (NOT `s`!)
///
/// # Performance
///
/// O(nnz) - simply adds to the values tensor
///
/// # Example
///
/// ```
/// # use numr::prelude::*;
/// # #[cfg(feature = "sparse")]
/// # {
/// # use numr::sparse::SparseTensor;
/// # let device = CpuDevice::new();
/// // Sparse matrix: After scalar_add(10):
/// // [1, 0, 2] [11, 0, 12]
/// // [0, 3, 0] [ 0, 13, 0]
/// //
/// // Note: Zeros stay 0, not 10!
/// # let sp = SparseTensor::<CpuRuntime>::from_coo_slices(&[0, 0, 1], &[0, 2, 1], &[1.0f32, 2.0, 3.0], [2, 3], &device)?;
/// # if let numr::sparse::SparseTensor::Coo(coo) = sp {
/// let result = coo.scalar_add(10.0)?;
/// # }
/// # }
/// # Ok::<(), numr::error::Error>(())
/// ```
///
/// # See Also
///
/// - [`add_to_nonzeros()`](Self::add_to_nonzeros) - Clearer alias for this method
pub fn scalar_add(&self, scalar: f64) -> Result<Self>
where
R::Client: ScalarOps<R>,
{
// Handle empty tensor case (no values to add to)
if self.values.numel() == 0 {
return Ok(Self {
row_indices: self.row_indices.clone(),
col_indices: self.col_indices.clone(),
values: self.values.clone(),
shape: self.shape,
sorted: self.sorted,
});
}
let device = self.values.device();
let client = R::default_client(device);
let shifted_values = client.add_scalar(&self.values, scalar)?;
Ok(Self {
row_indices: self.row_indices.clone(),
col_indices: self.col_indices.clone(),
values: shifted_values,
shape: self.shape,
sorted: self.sorted,
})
}
/// Alias for [`scalar_add()`](Self::scalar_add) with clearer naming
///
/// Adds a scalar value to all non-zero elements, preserving sparsity.
/// This name makes it explicit that only non-zero elements are modified.
///
/// # Example
///
/// ```
/// # use numr::prelude::*;
/// # #[cfg(feature = "sparse")]
/// # {
/// # use numr::sparse::SparseTensor;
/// # let device = CpuDevice::new();
/// // Clearer intent than scalar_add
/// # let sp = SparseTensor::<CpuRuntime>::from_coo_slices(&[0], &[0], &[1.0f32], [1, 1], &device)?;
/// # if let numr::sparse::SparseTensor::Coo(coo) = sp {
/// let result = coo.add_to_nonzeros(5.0)?;
/// # }
/// # }
/// # Ok::<(), numr::error::Error>(())
/// ```
#[inline]
pub fn add_to_nonzeros(&self, scalar: f64) -> Result<Self>
where
R::Client: ScalarOps<R>,
{
self.scalar_add(scalar)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dtype::DType;
use crate::runtime::cpu::CpuRuntime;
use crate::sparse::SparseStorage;
#[test]
fn test_coo_scalar_mul() {
let device = <CpuRuntime as Runtime>::Device::default();
let coo = CooData::<CpuRuntime>::from_slices(
&[0i64, 1, 2],
&[1i64, 0, 2],
&[5.0f32, 3.0, 7.0],
[3, 3],
&device,
)
.unwrap();
let result = coo.scalar_mul(2.0).unwrap();
assert_eq!(result.nnz(), 3);
assert_eq!(result.shape(), [3, 3]);
let vals: Vec<f32> = result.values().to_vec();
assert_eq!(vals, vec![10.0, 6.0, 14.0]);
}
#[test]
fn test_coo_scalar_mul_zero() {
let device = <CpuRuntime as Runtime>::Device::default();
let coo = CooData::<CpuRuntime>::from_slices(
&[0i64, 1],
&[0i64, 1],
&[5.0f32, 3.0],
[2, 2],
&device,
)
.unwrap();
let result = coo.scalar_mul(0.0).unwrap();
assert_eq!(result.nnz(), 2);
let vals: Vec<f32> = result.values().to_vec();
assert_eq!(vals, vec![0.0, 0.0]);
}
#[test]
fn test_coo_scalar_mul_negative() {
let device = <CpuRuntime as Runtime>::Device::default();
let coo = CooData::<CpuRuntime>::from_slices(
&[0i64, 1],
&[0i64, 1],
&[5.0f32, -3.0],
[2, 2],
&device,
)
.unwrap();
let result = coo.scalar_mul(-2.0).unwrap();
let vals: Vec<f32> = result.values().to_vec();
assert_eq!(vals, vec![-10.0, 6.0]);
}
#[test]
fn test_coo_scalar_add() {
let device = <CpuRuntime as Runtime>::Device::default();
let coo = CooData::<CpuRuntime>::from_slices(
&[0i64, 1, 2],
&[1i64, 0, 2],
&[5.0f32, 3.0, 7.0],
[3, 3],
&device,
)
.unwrap();
let result = coo.scalar_add(1.0).unwrap();
assert_eq!(result.nnz(), 3);
assert_eq!(result.shape(), [3, 3]);
let vals: Vec<f32> = result.values().to_vec();
assert_eq!(vals, vec![6.0, 4.0, 8.0]);
}
#[test]
fn test_coo_scalar_add_negative() {
let device = <CpuRuntime as Runtime>::Device::default();
let coo = CooData::<CpuRuntime>::from_slices(
&[0i64, 1],
&[0i64, 1],
&[5.0f32, 3.0],
[2, 2],
&device,
)
.unwrap();
let result = coo.scalar_add(-2.0).unwrap();
let vals: Vec<f32> = result.values().to_vec();
assert_eq!(vals, vec![3.0, 1.0]);
}
#[test]
fn test_coo_scalar_add_empty() {
let device = <CpuRuntime as Runtime>::Device::default();
let coo = CooData::<CpuRuntime>::empty([3, 3], DType::F32, &device);
let result = coo.scalar_add(5.0).unwrap();
assert_eq!(result.nnz(), 0); // Empty stays empty
}
#[test]
fn test_coo_scalar_mul_f64() {
let device = <CpuRuntime as Runtime>::Device::default();
let coo = CooData::<CpuRuntime>::from_slices(
&[0i64, 1],
&[0i64, 1],
&[2.5f64, 3.5],
[2, 2],
&device,
)
.unwrap();
let result = coo.scalar_mul(2.0).unwrap();
let vals: Vec<f64> = result.values().to_vec();
assert_eq!(vals, vec![5.0, 7.0]);
}
}