### ----------------------------------------------------
### -- Math::SparseMatrix
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: t/04-CSR-element-wise-addition.rakutest
### ----------------------------------------------------
use v6.d;

use lib <. lib>;
use Math::SparseMatrix::CSR;
use Math::SparseMatrix::Utilities;
use Test;

my $nrow = 5;
my $ncol = 8;
my $density = 0.25;
my $tol = 0.01;

my $matrix1 = generate-random-sparse-matrix(:$nrow, :$ncol, :$density, :$tol):!decorated;
my $matrix2 = generate-random-sparse-matrix(:$nrow, :$ncol, :$density, :$tol):!decorated;

## Too contrived?
sub add-by-rules($matrix1, $matrix2) {
    my %rules;
    for $matrix1.rules -> $r1 {
        for $matrix2.rules -> $r2 {
            if $r1.key eqv $r2.key {
                %rules{$r1.key.Str} = $r1.value + $r2.value
            } else {
                if %rules{$r1.key.Str}:!exists { %rules{$r1.key.Str} = $r1.value + $matrix2.implicit-value}
                if %rules{$r2.key.Str}:!exists { %rules{$r2.key.Str} = $r2.value + $matrix1.implicit-value}
            }
        }
    }
    return %rules;
}

plan *;

## 1
isa-ok $matrix1, Math::SparseMatrix::CSR;

## 2
isa-ok $matrix2, Math::SparseMatrix::CSR;

## 3
isa-ok $matrix1.add(4.3), Math::SparseMatrix::CSR;

## 4
isa-ok $matrix1.add($matrix2), Math::SparseMatrix::CSR;

## 5
is-deeply
        $matrix1.add($matrix2).rules.Hash,
        add-by-rules($matrix1, $matrix2),
        "Same rules of add-by-rules";

## 6
subtest {
    my $matrix1iv = $matrix1.clone;
    $matrix1iv.implicit-value = 1.5;
    my $matrix2iv = $matrix2.clone;
    $matrix2iv.implicit-value = 2.2;
    is-deeply
            $matrix1iv.add($matrix2iv).rules.Hash,
            add-by-rules($matrix1iv, $matrix2iv),
            "Same rules of add-by-rules";
}, "Addition with implicit values";

done-testing;


