# Copyright (c) 2014 Evalf
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from .. import numeric
import abc, treelog, functools, numpy, collections

class MatrixError(Exception):
  '''
  General error message for matrix-related failure.
  '''

class BackendNotAvailable(MatrixError):
  '''
  Error message reporting that the selected matrix backend is not available on
  the system.
  '''

class ToleranceNotReached(MatrixError):
  '''
  Error message reporting that the configured linear solver tolerance was not
  reached. The ``.best`` attribute carries the non-conforming solution.
  '''
  def __init__(self, best):
    super().__init__('solver failed to reach tolerance')
    self.best = best

class Matrix:
  'matrix base class'

  def __init__(self, shape):
    assert len(shape) == 2
    self.shape = shape
    self._precon_args = None

  def __reduce__(self):
    from . import assemble
    data, index = self.export('coo')
    return assemble, (data, index, self.shape)

  @abc.abstractmethod
  def __add__(self, other):
    'add two matrices'

    raise NotImplementedError

  @abc.abstractmethod
  def __mul__(self, other):
    'multiply matrix with a scalar'

    raise NotImplementedError

  @abc.abstractmethod
  def __matmul__(self, other):
    'multiply matrix with a dense tensor'

    raise NotImplementedError

  @abc.abstractmethod
  def __neg__(self):
    'negate matrix'

    raise NotImplementedError

  def __sub__(self, other):
    return self.__add__(-other)

  def __rmul__(self, other):
    return self.__mul__(other)