graphblas_sparse_linear_algebra 0.62.0

Wrapper for SuiteSparse:GraphBLAS
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use core::num;
use std::marker::{PhantomData, Send, Sync};
use std::mem::MaybeUninit;
use std::ptr::null_mut;
use std::sync::Arc;

use suitesparse_graphblas_sys::GrB_Type;

use crate::collections::collection::Collection;
use crate::error::SparseLinearAlgebraError;
use crate::graphblas_bindings::{
    GrB_Index, GrB_Matrix, GrB_Matrix_clear, GrB_Matrix_dup, GrB_Matrix_free, GrB_Matrix_new,
    GrB_Matrix_nvals,
};
use crate::operators::mask::MatrixMask;

use super::element::MatrixElementList;
use super::size::{GetMatrixDimensions, Size};

use crate::context::GetContext;
use crate::context::{CallGraphBlasContext, Context};

use crate::collections::sparse_matrix::operations::GetSparseMatrixElementList;
use crate::collections::sparse_matrix::operations::GetSparseMatrixSize;
use crate::index::{ElementCount, ElementIndex, IndexConversion};
use crate::value_type::utilities_to_implement_traits_for_all_value_types::implement_macro_for_all_value_types;
use crate::value_type::ValueType;

// static DEFAULT_GRAPHBLAS_OPERATOR_OPTIONS: Lazy<OperatorOptions> =
//     Lazy::new(|| OperatorOptions::new_default());

pub type ColumnIndex = ElementIndex;
pub type RowIndex = ElementIndex;

#[derive(Debug)]
pub struct SparseMatrix<T: ValueType> {
    context: Arc<Context>,
    matrix: GrB_Matrix,
    value_type: PhantomData<T>,
}

// Mutable access to GrB_Matrix shall occur through a write lock on RwLock<GrB_Matrix>.
// Code review must consider that the correct lock is made via
// SparseMatrix::get_write_lock() and SparseMatrix::get_read_lock().
// https://doc.rust-lang.org/nomicon/send-and-sync.html
unsafe impl<T: ValueType> Send for SparseMatrix<T> {}
unsafe impl<T: ValueType> Sync for SparseMatrix<T> {}

pub unsafe fn new_graphblas_matrix(
    context: &Arc<Context>,
    size: Size,
    graphblas_value_type: GrB_Type,
) -> Result<GrB_Matrix, SparseLinearAlgebraError> {
    let row_height = size.row_height_ref().to_graphblas_index()?;
    let column_width = size.column_width_ref().to_graphblas_index()?;

    let mut matrix: MaybeUninit<GrB_Matrix> = MaybeUninit::uninit();

    context.call_without_detailed_error_information(|| unsafe {
        GrB_Matrix_new(
            matrix.as_mut_ptr(),
            graphblas_value_type,
            row_height,
            column_width,
        )
    })?;

    let matrix = unsafe { matrix.assume_init() };
    return Ok(matrix);
}

impl<T: ValueType> SparseMatrix<T> {
    pub fn new(context: Arc<Context>, size: Size) -> Result<Self, SparseLinearAlgebraError> {
        let matrix = unsafe { new_graphblas_matrix(&context, size, T::to_graphblas_type()) }?;

        return Ok(SparseMatrix {
            context,
            matrix: matrix,
            value_type: PhantomData,
        });
    }

    pub unsafe fn from_graphblas_matrix(
        context: Arc<Context>,
        matrix: GrB_Matrix,
    ) -> Result<SparseMatrix<T>, SparseLinearAlgebraError> {
        Ok(SparseMatrix {
            context: context,
            matrix,
            value_type: PhantomData,
        })
    }

    // TODO
    // fn from_matrices(matrices: Vec<SparseMatrix<T>, >) -> Result<Self, SparseLinearAlgebraError> {

    // }
}

impl<T: ValueType> GetContext for SparseMatrix<T> {
    fn context(&self) -> Arc<Context> {
        self.context.clone()
    }
    fn context_ref(&self) -> &Arc<Context> {
        &self.context
    }
}

impl<T: ValueType> Collection for SparseMatrix<T> {
    fn clear(&mut self) -> Result<(), SparseLinearAlgebraError> {
        clear_sparse_matrix(self)
    }

    fn number_of_stored_elements(&self) -> Result<ElementCount, SparseLinearAlgebraError> {
        number_of_stored_elements_in_sparse_matrix(self)
    }
}

pub fn clear_sparse_matrix(
    matrix: &mut impl GetGraphblasSparseMatrix,
) -> Result<(), SparseLinearAlgebraError> {
    matrix.context_ref().call(
        || unsafe { GrB_Matrix_clear(matrix.graphblas_matrix_ptr()) },
        unsafe { matrix.graphblas_matrix_ptr_ref() },
    )?;
    Ok(())
}

pub fn number_of_stored_elements_in_sparse_matrix(
    matrix: &impl GetGraphblasSparseMatrix,
) -> Result<ElementCount, SparseLinearAlgebraError> {
    let mut number_of_values: MaybeUninit<GrB_Index> = MaybeUninit::uninit();
    matrix.context_ref().call(
        || unsafe {
            GrB_Matrix_nvals(number_of_values.as_mut_ptr(), matrix.graphblas_matrix_ptr())
        },
        unsafe { matrix.graphblas_matrix_ptr_ref() },
    )?;
    let number_of_values = unsafe { number_of_values.assume_init() };
    Ok(ElementCount::from_graphblas_index(number_of_values)?)
}

pub trait GetGraphblasSparseMatrix: GetContext {
    unsafe fn graphblas_matrix_ptr(&self) -> GrB_Matrix;
    unsafe fn graphblas_matrix_ptr_ref(&self) -> &GrB_Matrix;
    unsafe fn graphblas_matrix_ptr_mut(&mut self) -> &mut GrB_Matrix;
}

impl<T: ValueType> GetGraphblasSparseMatrix for SparseMatrix<T> {
    unsafe fn graphblas_matrix_ptr(&self) -> GrB_Matrix {
        self.matrix
    }

    unsafe fn graphblas_matrix_ptr_ref(&self) -> &GrB_Matrix {
        &self.matrix
    }

    unsafe fn graphblas_matrix_ptr_mut(&mut self) -> &mut GrB_Matrix {
        &mut self.matrix
    }
}

pub trait IntoGraphblasSparseMatrix {
    unsafe fn into_graphblas_matrix(self) -> (GrB_Matrix, Arc<Context>);
}

impl<T: ValueType> IntoGraphblasSparseMatrix for SparseMatrix<T> {
    unsafe fn into_graphblas_matrix(mut self) -> (GrB_Matrix, Arc<Context>) {
        let raw_pointer = self.matrix;
        self.matrix = null_mut();
        (raw_pointer, self.context.clone())
    }
}

impl<T: ValueType> Drop for SparseMatrix<T> {
    fn drop(&mut self) -> () {
        unsafe { drop_graphblas_matrix(&self.context, &mut self.matrix) };
    }
}

pub unsafe fn drop_graphblas_matrix(context: &Arc<Context>, matrix: &mut GrB_Matrix) -> () {
    if !matrix.is_null() {
        let _ =
            context.call_without_detailed_error_information(|| unsafe { GrB_Matrix_free(matrix) });
    }
}

impl<T: ValueType> Clone for SparseMatrix<T> {
    fn clone(&self) -> Self {
        SparseMatrix {
            context: self.context.clone(),
            matrix: unsafe {
                clone_graphblas_matrix(
                    self.context_ref(),
                    GetGraphblasSparseMatrix::graphblas_matrix_ptr(self),
                )
                .unwrap()
            },
            value_type: PhantomData,
        }
    }
}

pub unsafe fn clone_graphblas_matrix(
    context: &Arc<Context>,
    matrix: GrB_Matrix,
) -> Result<GrB_Matrix, SparseLinearAlgebraError> {
    let mut matrix_copy: MaybeUninit<GrB_Matrix> = MaybeUninit::uninit();
    context
        .call(|| GrB_Matrix_dup(matrix_copy.as_mut_ptr(), matrix), &matrix)
        .unwrap();
    return Ok(matrix_copy.assume_init());
}

// TODO improve printing format
// summary data, column aligning
macro_rules! implement_display {
    ($value_type:ty) => {
        impl std::fmt::Display for SparseMatrix<$value_type> {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                let element_list: MatrixElementList<$value_type>;
                match self.element_list() {
                    Err(_error) => return Err(std::fmt::Error),
                    Ok(list) => {
                        element_list = list;
                    }
                }

                let row_indices = element_list.row_indices_ref();
                let column_indices = element_list.column_indices_ref();
                let values = element_list.values_ref();

                writeln! {f,"Matrix size: {:?}", self.size()?};
                writeln! {f,"Number of stored elements: {:?}", self.number_of_stored_elements()?};

                for element_index in 0..values.len() {
                    write!(
                        f,
                        "({}, {}, {})\n",
                        row_indices[element_index],
                        column_indices[element_index],
                        values[element_index]
                    );
                }
                return writeln!(f, "");
            }
        }
    };
}

implement_macro_for_all_value_types!(implement_display);

impl<T: ValueType> MatrixMask for SparseMatrix<T> {
    unsafe fn graphblas_matrix_ptr(&self) -> GrB_Matrix {
        GetGraphblasSparseMatrix::graphblas_matrix_ptr(self)
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::collections::sparse_matrix::operations::{
        DropSparseMatrixElement, FromDiagonalVector, FromMatrixElementList, GetSparseMatrixElement,
        GetSparseMatrixElementValue, GetSparseMatrixSize, ResizeSparseMatrix,
        SetSparseMatrixElement,
    };
    use crate::collections::sparse_matrix::{
        Coordinate, GetMatrixElementCoordinate, MatrixElement,
    };
    use crate::collections::sparse_vector::operations::FromVectorElementList;
    use crate::collections::sparse_vector::{SparseVector, VectorElementList};

    use crate::error::{GraphblasErrorType, LogicErrorType, SparseLinearAlgebraErrorType};
    use crate::operators::binary_operator::First;

    #[test]
    fn new_matrix() {
        let context = Context::init_default().unwrap();

        let target_height = 10;
        let target_width = 5;
        let size: Size = (target_height, target_width).into();

        let sparse_matrix = SparseMatrix::<i32>::new(context, size).unwrap();

        assert_eq!(target_height, sparse_matrix.row_height().unwrap());
        assert_eq!(target_width, sparse_matrix.column_width().unwrap());
        assert_eq!(0, sparse_matrix.number_of_stored_elements().unwrap());
        assert_eq!(size, sparse_matrix.size().unwrap())
    }

    #[test]
    fn clone_matrix() {
        let context = Context::init_default().unwrap();

        let target_height = 10;
        let target_width = 5;
        let size: Size = (target_height, target_width).into();

        let sparse_matrix = SparseMatrix::<u8>::new(context, size).unwrap();

        let clone_of_sparse_matrix = sparse_matrix.clone();

        // TODO: implement and test equality operator
        assert_eq!(target_height, clone_of_sparse_matrix.row_height().unwrap());
        assert_eq!(target_width, clone_of_sparse_matrix.column_width().unwrap());
        assert_eq!(
            0,
            clone_of_sparse_matrix.number_of_stored_elements().unwrap()
        );
        assert_eq!(size, clone_of_sparse_matrix.size().unwrap())
    }

    #[test]
    fn resize_matrix() {
        let context = Context::init_default().unwrap();

        let target_height = 10;
        let target_width = 5;
        let size: Size = (target_height, target_width).into();

        let mut sparse_matrix = SparseMatrix::<u8>::new(context, size).unwrap();

        let new_size: Size = (1, 2).into();
        sparse_matrix.resize(new_size).unwrap();

        assert_eq!(new_size.row_height(), sparse_matrix.row_height().unwrap());
        assert_eq!(
            new_size.column_width(),
            sparse_matrix.column_width().unwrap()
        );
        assert_eq!(new_size, sparse_matrix.size().unwrap());
        // TODO: make this a meaningful test by inserting actual values
        assert_eq!(0, sparse_matrix.number_of_stored_elements().unwrap());
    }

    #[test]
    fn build_matrix() {
        let context = Context::init_default().unwrap();
        let element_list = MatrixElementList::<u8>::from_element_vector(vec![
            (1, 1, 1).into(),
            (2, 2, 2).into(),
            (2, 4, 10).into(),
            (2, 4, 11).into(), // duplicate
                               // (10, 10, 10).into(), // out-of-bounds
        ]);
        // println!("{:?}", element_list.to_owned());

        let _matrix = SparseMatrix::<u8>::from_element_list(
            context,
            (3, 5).into(),
            element_list,
            &First::<u8>::new(),
        )
        .unwrap();

        // println!("{:?}",matrix.get_element_list().unwrap());
        // println!("{:?}", matrix.number_of_stored_elements().unwrap());
        // println!("{:?}", matrix.number_of_stored_elements().unwrap());
        // println!("{:?}", matrix.number_of_stored_elements().unwrap());
        // assert_eq!(matrix.number_of_stored_elements().unwrap(), 3);
    }

    #[test]
    fn from_diagonal_vector() {
        let context = Context::init_default().unwrap();

        let element_list = VectorElementList::<isize>::from_element_vector(vec![
            (1, 1).into(),
            (2, 2).into(),
            (5, 5).into(),
        ]);

        let vector_length = 10;
        let vector = SparseVector::<isize>::from_element_list(
            context,
            vector_length,
            element_list,
            &First::<isize>::new(),
        )
        .unwrap();

        let matrix = SparseMatrix::<isize>::from_diagonal_vector(&vector, &0).unwrap();
        assert_eq!(
            matrix.size().unwrap(),
            Size::new(vector_length, vector_length)
        );
        assert_eq!(matrix.element_value(5, 5).unwrap().unwrap(), 5);

        let matrix = SparseMatrix::<isize>::from_diagonal_vector(&vector, &2).unwrap();
        assert_eq!(
            matrix.size().unwrap(),
            Size::new(vector_length + 2, vector_length + 2)
        );
        assert_eq!(matrix.element_value(5, 7).unwrap().unwrap(), 5);

        let matrix = SparseMatrix::<isize>::from_diagonal_vector(&vector, &-2).unwrap();
        assert_eq!(
            matrix.size().unwrap(),
            Size::new(vector_length + 2, vector_length + 2)
        );
        println!("{}", matrix.clone());
        assert_eq!(matrix.element_value(7, 5).unwrap().unwrap(), 5);
    }

    #[test]
    fn set_element_in_matrix() {
        let context = Context::init_default().unwrap();

        let target_height = 10;
        let target_width = 5;
        let size: Size = (target_height, target_width).into();

        let mut sparse_matrix = SparseMatrix::<i32>::new(context, size).unwrap();

        sparse_matrix
            .set_element(MatrixElement::from_triple(1, 2, 3))
            .unwrap();

        assert_eq!(1, sparse_matrix.number_of_stored_elements().unwrap());

        sparse_matrix
            .set_element(MatrixElement::from_triple(1, 3, 3))
            .unwrap();

        assert_eq!(2, sparse_matrix.number_of_stored_elements().unwrap());

        match sparse_matrix.set_element(MatrixElement::from_triple(1, 10, 3)) {
            Err(error) => {
                match error.error_type() {
                    SparseLinearAlgebraErrorType::LogicErrorType(LogicErrorType::GraphBlas(
                        error_type,
                    )) => {
                        assert_eq!(error_type, GraphblasErrorType::InvalidIndex)
                    }
                    _ => assert!(false),
                }
                // match error.error_type() {
                //     SparseLinearAlgebraErrorType::LogicErrorType(error_type) => {
                //         match error_type {
                //             LogicErrorType::GraphBlas(error_type) => {
                //                 assert_eq!(error_type, GraphBlasErrorType::InvalidIndex)
                //             }
                //             _ => assert!(false)
                //         }
                //     }
                //     _ => assert!(false)
                // }
                // assert_eq!(error.error_type(), SparseLinearAlgebraErrorType::LogicErrorType)
            }
            Ok(_) => assert!(false),
        }
    }

    #[test]
    fn remove_element_from_matrix() {
        let context = Context::init_default().unwrap();

        let target_height: RowIndex = 10;
        let target_width: ColumnIndex = 5;
        let size = Size::new(target_height, target_width);

        let mut sparse_matrix = SparseMatrix::<i32>::new(context, size).unwrap();

        sparse_matrix
            .set_element(MatrixElement::from_triple(1, 2, 3))
            .unwrap();
        sparse_matrix
            .set_element(MatrixElement::from_triple(1, 4, 4))
            .unwrap();

        sparse_matrix
            .drop_element_with_coordinate(Coordinate::new(1, 2))
            .unwrap();

        assert_eq!(sparse_matrix.number_of_stored_elements().unwrap(), 1)
    }

    #[test]
    fn get_element_from_matrix() {
        let context = Context::init_default().unwrap();

        let target_height: RowIndex = 10;
        let target_width: ColumnIndex = 5;
        let size = Size::new(target_height, target_width);

        let mut sparse_matrix = SparseMatrix::<i32>::new(context, size).unwrap();

        let element_1 = MatrixElement::from_triple(1, 2, 1);
        let element_2 = MatrixElement::from_triple(2, 3, 2);

        sparse_matrix.set_element(element_1).unwrap();
        sparse_matrix.set_element(element_2).unwrap();

        assert_eq!(
            element_1,
            sparse_matrix
                .element(element_1.coordinate())
                .unwrap()
                .unwrap()
        );
        assert_eq!(
            element_2,
            sparse_matrix
                .element(element_2.coordinate())
                .unwrap()
                .unwrap()
        );
    }

    #[test]
    fn get_element_from_usize_matrix() {
        let context = Context::init_default().unwrap();

        let target_height: RowIndex = 10;
        let target_width: ColumnIndex = 5;
        let size = Size::new(target_height, target_width);

        let mut sparse_matrix = SparseMatrix::<usize>::new(context, size).unwrap();

        let element_1 = MatrixElement::<usize>::from_triple(1, 2, 1);
        let element_2 = MatrixElement::<usize>::from_triple(2, 3, 2);

        sparse_matrix.set_element(element_1).unwrap();
        sparse_matrix.set_element(element_2).unwrap();

        assert_eq!(
            element_1,
            sparse_matrix
                .element(element_1.coordinate())
                .unwrap()
                .unwrap()
        );
        assert_eq!(
            element_2,
            sparse_matrix
                .element(element_2.coordinate())
                .unwrap()
                .unwrap()
        );
    }

    #[test]
    fn get_element_list_from_matrix() {
        // TODO: check for a size of zero
        let context = Context::init_default().unwrap();

        let element_list = MatrixElementList::<u8>::from_element_vector(vec![
            (1, 1, 1).into(),
            (2, 2, 2).into(),
            (2, 4, 10).into(),
            (2, 5, 11).into(),
        ]);

        let matrix = SparseMatrix::<u8>::from_element_list(
            context.clone(),
            (10, 15).into(),
            element_list.clone(),
            &First::<u8>::new(),
        )
        .unwrap();

        // println!("original element list: {:?}", element_list);
        // println!(
        //     "stored element list: {:?}",
        //     matrix.get_element_list().unwrap()
        // );
        assert_eq!(
            matrix.number_of_stored_elements().unwrap(),
            element_list.length()
        );

        assert_eq!(matrix.element_list().unwrap(), element_list);

        let empty_element_list = MatrixElementList::<u8>::new();
        let _empty_matrix = SparseMatrix::<u8>::from_element_list(
            context,
            (10, 15).into(),
            empty_element_list,
            &First::<u8>::new(),
        )
        .unwrap();
        assert_eq!(
            matrix.number_of_stored_elements().unwrap(),
            element_list.length()
        );
    }

    #[test]
    fn get_test_error_reporting_while_reading_an_element() {
        let context = Context::init_default().unwrap();

        let target_height: RowIndex = 10;
        let target_width: ColumnIndex = 5;
        let size = Size::new(target_height, target_width);

        let mut sparse_matrix = SparseMatrix::<i32>::new(context, size).unwrap();

        let element_1 = MatrixElement::from_triple(1, 2, 1);
        let element_2 = MatrixElement::from_triple(20, 3, 2);

        sparse_matrix.set_element(element_1).unwrap();

        match sparse_matrix.set_element(element_2) {
            Ok(_) => assert!(false),
            Err(error) => {
                println!("{}", error.to_string());
                assert!(error
                    .to_string()
                    .contains("Row index 20 out of range; must be < 10"))
            }
        }
    }

    #[test]
    fn use_graphblas_matrix_after_dropping_sparse_matrix() {
        let context = Context::init_default().unwrap();
        let element_list =
            MatrixElementList::<u8>::from_element_vector(vec![(1, 1, 1).into(), (2, 2, 2).into()]);

        let graphblas_matrix;

        {
            let matrix = SparseMatrix::<u8>::from_element_list(
                context.clone(),
                (5, 5).into(),
                element_list,
                &First::<u8>::new(),
            )
            .unwrap();

            (graphblas_matrix, _) = unsafe { matrix.into_graphblas_matrix() };
        }

        let matrix_copy = unsafe {
            SparseMatrix::<u8>::from_graphblas_matrix(context, graphblas_matrix).unwrap()
        };

        assert_eq!(matrix_copy.element_value(1, 1).unwrap(), Some(1u8))
    }
}