# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/04_sqrtm.ipynb.

# %% auto 0
__all__ = ['use_li', 'sqrtm_li', 'LICENCE_LI', 'LICENCE_SM', 'MatrixSquareRoot_li', 'compute_error',
           'sqrt_newton_schulz_autograd', 'sqrt_newton_schulz', 'sqrtm']

# %% ../nbs/04_sqrtm.ipynb 4
import torch
from torch.autograd import Function, Variable

# %% ../nbs/04_sqrtm.ipynb 6
use_li = True  # come back and turn this on if you want to see/use the full code

if use_li:      # lighten the load of imports since we won't use li's in production
    import numpy as np
    import scipy.linalg

# %% ../nbs/04_sqrtm.ipynb 7
class MatrixSquareRoot_li(Function):
    """
    From https://github.com/steveli/pytorch-sqrtm/blob/master/sqrtm.py, which sadly does not install as a package.  LICENSE included below
    Square root of a positive definite matrix.

    NOTE: matrix square root is not differentiable for matrices with
          zero eigenvalues.
    """
    @staticmethod
    def forward(ctx, input):
        m = input.detach().cpu().numpy().astype(np.float_)  # SHH: note how this immediately switches to CPU & numpy :-( 
        sqrtm = torch.from_numpy(scipy.linalg.sqrtm(m).real).to(input)
        ctx.save_for_backward(sqrtm)
        return sqrtm

    @staticmethod
    def backward(ctx, grad_output):
        grad_input = None
        if ctx.needs_input_grad[0]:
            sqrtm, = ctx.saved_tensors
            sqrtm = sqrtm.data.cpu().numpy().astype(np.float_)
            gm = grad_output.data.cpu().numpy().astype(np.float_)

            # Given a positive semi-definite matrix X,
            # since X = X^{1/2}X^{1/2}, we can compute the gradient of the
            # matrix square root dX^{1/2} by solving the Sylvester equation:
            # dX = (d(X^{1/2})X^{1/2} + X^{1/2}(dX^{1/2}).
            grad_sqrtm = scipy.linalg.solve_sylvester(sqrtm, sqrtm, gm)

            grad_input = torch.from_numpy(grad_sqrtm).to(grad_output)
        return grad_input


sqrtm_li = MatrixSquareRoot_li.apply


LICENCE_LI = """
MIT License

Copyright (c) 2022 Steven Cheng-Xian Li

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.
"""

# %% ../nbs/04_sqrtm.ipynb 12
# Compute error
def compute_error(A, sA):
    normA = torch.sqrt(torch.sum(torch.sum(A * A, dim=1),dim=1))
    error = A - torch.bmm(sA, sA)
    error = torch.sqrt((error * error).sum(dim=1).sum(dim=1)) / normA
    return torch.mean(error)


def sqrt_newton_schulz_autograd(A, 
                                numIters=20, # found experimentally by SHH, comparing w/ Li's method
                                calc_error=False,):
    """Modified from from https://people.cs.umass.edu/~smaji/projects/matrix-sqrt/
    "The drawback of the autograd approach [i.e., this approach] is that a naive implementation stores all the intermediate results. 
    Thus the memory overhead scales linearly with the number of iterations which is problematic for large matrices."
    """
    if len(A.data.shape) < 3: A = A.unsqueeze(0)
    batchSize, dim1, dim2 = A.data.shape
    assert dim1==dim2
    dim, dtype, device = dim1, A.dtype, A.device
    normA = A.mul(A).sum(dim=1).sum(dim=1).sqrt()
    Y = A.div(normA.view(batchSize, 1, 1).expand_as(A));
    I = Variable(torch.eye(dim,dim, device=device).view(1, dim, dim).
                 repeat(batchSize,1,1).type(dtype),requires_grad=False)
    Z = Variable(torch.eye(dim,dim, device=device).view(1, dim, dim).
                 repeat(batchSize,1,1).type(dtype),requires_grad=False)

    for i in range(numIters):
        T = 0.5*(3.0*I - Z.bmm(Y))
        Y = Y.bmm(T)
        Z = T.bmm(Z)
    
    sA = Y*torch.sqrt(normA).view(batchSize, 1, 1).expand_as(A)
    if calc_error:
        error = compute_error(A, sA)
        return sA, error
    return sA


def sqrt_newton_schulz(A,               # matrix to be sqrt-ified
                       numIters=20,      # numIters=7 found via experimentation
                       calc_error=False, # setting False disables Maji's error reporting
                      ):
    """
    Sqrt of matrix via Newton-Schulz algorithm
    Modified from https://github.com/msubhransu/matrix-sqrt/blob/cc2289a3ed7042b8dbacd53ce8a34da1f814ed2f/matrix_sqrt.py#LL72C1-L87C19
    # Forward via Newton-Schulz iterations (non autograd version)
    # Seems to be slighlty faster and has much lower memory overhead
    
    ... Original code didn't preserve device, had no batch dim checking -SHH
    """
    while len(A.data.shape) < 3:  # needs a batch dimension
        A = A.unsqueeze(0)
    batchSize, dim1, dim2 = A.data.shape
    assert dim1==dim2
    dim, dtype, device = dim1, A.dtype, A.device
    normA = A.mul(A).sum(dim=1).sum(dim=1).sqrt()
    Y = A.div(normA.view(batchSize, 1, 1).expand_as(A));
    I = torch.eye(dim,dim, device=device, dtype=dtype).view(1, dim, dim).repeat(batchSize,1,1)
    Z = torch.eye(dim,dim, device=device, dtype=dtype).view(1, dim, dim).repeat(batchSize,1,1)
    for i in range(numIters):
        T = 0.5*(3.0*I - Z.bmm(Y))
        Y = Y.bmm(T)
        Z = T.bmm(Z)
        
    sA = Y*torch.sqrt(normA).view(batchSize, 1, 1).expand_as(A)
    if calc_error: 
        error = compute_error(A, sA)
        return sA, error
    else:
        return sA

    
""" 
# Only used if backprop needed, which it isn't for FAD.  Leaving it here anyway. -SHH
def lyap_newton_schulz(z, dldz, numIters, dtype):
    # Backward via iterative Lyapunov solver.
    batchSize = z.shape[0]
    dim = z.shape[1]
    normz = z.mul(z).sum(dim=1).sum(dim=1).sqrt()
    a = z.div(normz.view(batchSize, 1, 1).expand_as(z))
    I = torch.eye(dim,dim).view(1, dim, dim).repeat(batchSize,1,1).type(dtype)
    q = dldz.div(normz.view(batchSize, 1, 1).expand_as(z))
    for i in range(numIters):
        q = 0.5*(q.bmm(3.0*I - a.bmm(a)) - a.transpose(1, 2).bmm(a.transpose(1,2).bmm(q) - q.bmm(a)) )
        a = 0.5*a.bmm(3.0*I - a.bmm(a))
    dlda = 0.5*q
    return dlda
"""


LICENCE_SM = """
MIT License

Copyright (c) 2017 Subhransu Maji

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.
"""

# %% ../nbs/04_sqrtm.ipynb 27
def sqrtm(A, method='maji', numIters=20):
    "wrapper function for matrix sqrt algorithm of choice. Also we'll turn off all gradients"
    with torch.no_grad():
        if method=='maji':
            return sqrt_newton_schulz(A, numIters=numIters, calc_error=False).squeeze()  # get rid of any useless batch dimensions
        elif method=='li': 
            return sqrtm_li(A)
        else:
            raise ValueError(f"Invalid method: {method}") 
