### ----------------------------------------------------
### -- Math::SparseMatrix
### -- Licenses: Artistic-2.0
### -- Authors: Anton Antonov
### -- File: t/05-CSR-element-wise-multiplication.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.5;
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 mult-by-rules($matrix1, $matrix2) {
    my %rules;
    my %r1 = $matrix1.rules;
    my %r2 = $matrix2.rules;
    my @keys = [|%r1.keys, |%r2.keys].unique;

    my $use-iv = !($matrix1.implicit-value == 0 || $matrix2.implicit-value == 0);

    for @keys -> $pos {
        if (%r1{$pos}:exists) && (%r2{$pos}:exists) {
            %rules{$pos} = %r1{$pos} * %r2{$pos};
        } elsif (%r2{$pos}:exists) && $use-iv {
            %rules{$pos} = $matrix1.implicit-value * %r2{$pos};
        } elsif (%r1{$pos}:exists) && $use-iv {
            %rules{$pos} = %r1{$pos} * $matrix2.implicit-value;
        }
    }
    return %rules;
}

plan *;

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

## 2
isa-ok $matrix1, 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.multiply($matrix2).rules.Hash,
        mult-by-rules($matrix1, $matrix2),
        "Same rules of mult-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.multiply($matrix2iv).rules.Hash,
            mult-by-rules($matrix1iv, $matrix2iv),
            "Same rules of mult-by-rules";
    is
            $matrix1iv.multiply($matrix2iv).implicit-value,
            $matrix1iv.implicit-value * $matrix2iv.implicit-value,
            "Implicit value";
}, "Multiplication with implicit values";

## 7
subtest {
    my $matrix1iv = $matrix1.clone;
    $matrix1iv.implicit-value = 1.5;
    is-deeply
            $matrix1iv.multiply($matrix2).rules.Hash,
            mult-by-rules($matrix1iv, $matrix2),
            "Same rules of mult-by-rules";
    is
            $matrix1iv.multiply($matrix2).implicit-value,
            0,
            "Implicit value";
}, "Multiplication with non-zero implicit value of one of the matrices";

done-testing;


