# Eigenvalue Analsis
# Ben Lang May 2020
# A program intended to find where the Zero-amplitude fixed point becomes unstable in the case where N=2V-1

# It can also do the cases where N is between V and 2V-1.



import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib as mpl
from scipy import special #For special functions
import numpy as np
import scipy.optimize
from scipy.optimize import minimize
import functools

i = 1j


# special Bessel thing, JS
JS = lambda p, A, theta: special.jn(p, A) * np.exp(1j*p*theta) * (1j)**(p)


def diff_Bessel( A2, p, theta2 ):
    # Have taken all p's to -ps.
    
    return  JS( p , A2, theta2) + JS( (p-2) , -A2, theta2)
    


def Find_switch_V( V, fixed_Gamma = True, N_use = 'all' ):
    Gamma = 1
        
    bes =  special.jn
    ### Build Full Matrix:
    
    negs = []
    all_eigs = []
    
    def factor( row, other_bit ):
        if row % 2 ==0: #Even
            div = (row/2) + 1
            return i * Lambda/(4*div) * other_bit
        else:
            div = ((row-1)/2) + 1
            return np.conj( i * Lambda/(4*div) * other_bit )
    
    found_it = False
    critical_vects = []
    
    As = [0.1]
    Max_allowed_A = special.jnp_zeros(1, 1)
    
    
    if fixed_Gamma == "Quad":
        Lmax = 120
    else:
        Lmax = 40
    
    Lambs = np.linspace(0, Lmax, int(3E3))
    
    if fixed_Gamma == True:
        Gamma_res = Gamma
    elif fixed_Gamma == "Quad":
        print("Quad gamma scaling")
        Gamma_res = V**2 * Gamma
    # end if
    
    for Lambda in Lambs:
        # Find A.
        FA = lambda AV: (Lambda / (2 * V * Gamma_res)) * ( bes(0, AV) + bes(2, AV) ) - AV
        AV = scipy.optimize.newton_krylov(FA, [As[-1]], maxiter = 1200)[0]
        
        As.append( AV )
        theta2 = np.pi
        
        if AV >= Max_allowed_A:
            Lambda = np.NaN
            As.append( np.NaN )
            break
        
        N = 2*V - 1
        
        Matrix = np.zeros((2*N,2*N), dtype=complex)
        
        if fixed_Gamma == True:
            # All loss rates the same
            Matrix += -Gamma * np.eye(2*N)
        elif fixed_Gamma == "Quad":
            # Loss rates increase quadratically
            Matrix += -Gamma * np.diag( functools.reduce(lambda x, y: x+y, [ [n**2, n**2] for n in range(1,N+1) ]) )
        else:
            # Assumes loss falls with n, so that loss and drive remain in the same ratio for each mode.
            # Relates to Q_n  =  n^2 Q_1
            Matrix += -Gamma * V * np.diag( functools.reduce(lambda x, y: x+y, [ [1/n, 1/n] for n in range(1,N+1) ]) )
            
        for j in range(0, 2*N, 2):
            Matrix[j  , j  ] += factor( j  , diff_Bessel( AV, 1, theta2 ) )
            Matrix[j+1, j+1] += factor( j+1, diff_Bessel( AV, 1, theta2 ) )
            
        for j in range(0, 2*N, 2):
            Matrix[j  , 2*N-1-j] += factor( j, diff_Bessel( AV, 3, theta2 ) )
            Matrix[j+1, 2*N-2-j] += factor( j+1, diff_Bessel( AV, 3, theta2 ) )
            
        for j in range(0, N-1, 2):
            Matrix[N-2-j, j  ] += factor( N-2-j  , diff_Bessel( AV, 2, theta2 ) )
            Matrix[N-3-j, j+1] += factor( N-3-j, diff_Bessel( AV, 2, theta2 ) )

            Matrix[N+1+j, j  ] += factor( N+1+j  , diff_Bessel( AV, 2, theta2 ) )
            Matrix[N+2+j, j+1] += factor( N+2+j, diff_Bessel( AV, 2, theta2 ) )
            
            Matrix[j,   N+1+j] += factor( j, diff_Bessel( AV, 2, theta2 ) )
            Matrix[j+1, N+2+j] += factor( j+1, diff_Bessel( AV, 2, theta2 ) )
            
        for j in range(0, N-1, 2):
            Matrix[2*N-1-j, N+1+j] += factor( 2*N-1-j, diff_Bessel( AV, 4, theta2 ) )
            Matrix[2*N-2-j, N+2+j] += factor( 2*N-2-j, diff_Bessel( AV, 4, theta2 ) )
    
        # Destroy the resonant mode (should not be included in matrix)
        Matrix = np.delete( Matrix, [N-1, N], axis=0)
        Matrix = np.delete( Matrix, [N-1, N], axis=1)

        
        if not N_use == 'all':
            if N_use < V:
                print('Not acceptable, too few modes')
                return np.NaN, np.NaN, np.NaN
            if N_use > N:
                print('Not acceptable. Too many modes')
                return np.NaN, np.NaN, np.NaN
            if N_use < N:
                #Cutting MATRIX down!!!
                Matrix = Matrix[ :(N_use-N)*2 , :(N_use-N)*2 ]
        #end
        
        eig_vals, eig_vects = np.linalg.eig(Matrix)
        
        #print(eig_vals)
        
        if any( eig_vals > 0 ): # Unstable:
            for val, vect in zip( eig_vals, eig_vects):
                if val > 0:
                    critical_vects.append( vect )
            break
        
        all_eigs.append( eig_vals )
    else:
        # Did not break from loop:
        Lambda = np.NaN
        As.append( np.NaN )
        #print( 'Compare:', functools.reduce(lambda x, y: x*y, eig_vals), DETM )
    
    print( Matrix.shape,  [2*N_use, 2*N_use] )
    print(V, Matrix.shape)
#    
#    fig, axes = plt.subplots(1, 2, figsize=(9,12))
#    axes[0].spy( np.abs( np.real( Matrix ) ) > 1E-10  )
#    axes[1].spy( np.abs( np.imag( Matrix )) > 1E-10  )
    
    # fig, ax = plt.subplots(figsize=(9,12))
    # ax.plot( Lambs[0:len(all_eigs)], np.array( all_eigs ) )
    
    #return Lambda, As[1:], critical_vects, Lambs
    return Lambda, As[1:], critical_vects


def Analytic_Switch2( V, fixed_Gamma = True, ax = "none", amp = True, plot = True ):
    Gamma = 1
    N = V
    
    As = [0]
    Conds = []
    
    bes =  special.jn
    
    if fixed_Gamma == "Quad":
        Lmax = 120
    else:
        Lmax = 60
    
    Lambs = np.linspace(0, Lmax, 1000)
    
    if fixed_Gamma == True:
        Gamma_res = Gamma
    elif fixed_Gamma == "Quad":
        Gamma_res = V**2 * Gamma
        
    
    for Lambda in Lambs:
        # Find A.
        FA = lambda AV: (Lambda / (2 * V * Gamma_res)) * ( bes(0, AV) + bes(2, AV) ) - AV
        AV = scipy.optimize.newton_krylov(FA, [As[-1]], maxiter = 1200)[0]
       
        As.append( AV )
        
        if fixed_Gamma == True:
            Conds.append( Lambda * special.jvp(1, AV, n=1) / (2 * np.sqrt(N-1) ) )
        elif fixed_Gamma == "Quad":
            Conds.append( Lambda * special.jvp(1, AV, n=1) / (2 * (N-1)**(3/2) ) )
    
    Unstable = [C>1 for C in Conds]
    
    if plot:
        if ax == "none": fig, ax = plt.subplots(figsize=(7,5))
        ax.plot( Lambs, Conds, '--', label = r'$S$', linewidth = 0.85) # ' (\tilde{E}_J (2\Delta_1)^2 / \hbar \gamma)  J_1\'(2 \Delta_p A_p) / (2 \sqrt{p-1}) $', linewidth = 0.5)
        
        if amp: ax.plot( Lambs, As[1:], label = r'$2 \Delta_p A_p$', linewidth = 0.85)
        
        ax.plot( Lambs, [1 for _ in Conds] , 'k', linewidth = 0.85)
        
        ax.set_xlabel(r'$\tilde{E}_J (2\Delta_1)^2 / \hbar \gamma$')
        #ax.legend()
        
        # ax.set_title(r'$N=p=$' + str(V) )
        #ax.text(3, 1.5, r'$N=p=$' + str(V) )
        ax.text(3, 1.15, "(" + str(V) + ")" )
        
        ax.set_xlim([0, 30])
        ax.set_xticks([0, 30])
        
        if amp:
            ax.set_ylim([0, 2])
            ax.set_yticks([0, 1, 2])
        else:
            ax.set_ylim([0, 1.5])
            ax.set_yticks([0, 1, 1.5])

        ax.plot( Lambs, Unstable , c='0.55', linewidth = 0.5)
        
        fig, ax2 = plt.subplots(figsize=(7,5))
        ax2.plot( special.jvp(2, As, n=1)**2  )
        ax2.plot( 8 * (V**2) * Gamma / Lambs )
    
    # print(" ")
    # print( Lambs[Unstable.index(1)] )
    # print( Lambs[ next(i for i in reversed(range(len(Unstable))) if Unstable[i] == 1)  ] )
        
    
    if 1 in Unstable:
        print( As[Unstable.index(1)] **2 * V / 4 )
        return Lambs[Unstable.index(1)]
    else:
        return np.NaN
    
    
def Analytic_Switch3( Delta, V, fixed_Gamma = True, ax = "none", amp = True, plot = True ):
    Gamma = 1
    N = V
    
    As = [0]
    Conds = []
    
    bes =  special.jn
    
    if fixed_Gamma == "Quad":
        Lmax = 120 / (2*Delta)
    else:
        Lmax = 60 / (2*Delta)
    
    Lambs = np.linspace(0, Lmax, 1000)
    
    if fixed_Gamma == True:
        Gamma_res = Gamma
    elif fixed_Gamma == "Quad":
        Gamma_res = V**2 * Gamma
        
    
    for Lambda in Lambs:
        # Find A.
        FA = lambda AV: (Lambda / (2 * V * Gamma_res *(2*Delta)**2 )) * ( bes(0, 2*Delta*AV) + bes(2, 2*Delta*AV) ) - AV
        AV = scipy.optimize.newton_krylov(FA, [As[-1]], maxiter = 1200)[0]
       
        As.append( AV )
        
        if fixed_Gamma == True:
            Conds.append( Lambda * special.jvp(1, 2*Delta*AV, n=1) / (2 * np.sqrt(N-1) ) )
        elif fixed_Gamma == "Quad":
            Conds.append( Lambda * special.jvp(1, 2*Delta*AV, n=1) / (2 * (N-1)**(3/2) ) )
    
    Unstable = [C>1 for C in Conds]
    
    if plot:
        if ax == "none": fig, ax = plt.subplots(figsize=(7,5))
        ax.plot( Lambs, Conds, '--', label = r'$S$', linewidth = 0.85) # ' (\tilde{E}_J (2\Delta_1)^2 / \hbar \gamma)  J_1\'(2 \Delta_p A_p) / (2 \sqrt{p-1}) $', linewidth = 0.5)
        
        if amp: ax.plot( Lambs, As[1:], label = r'$2 \Delta_p A_p$', linewidth = 0.85)
        
        ax.plot( Lambs, [1 for _ in Conds] , 'k', linewidth = 0.85)
        
        ax.set_xlabel(r'$\tilde{E}_J (2\Delta_1)^2 / \hbar \gamma$')
        #ax.legend()
        
        # ax.set_title(r'$N=p=$' + str(V) )
        #ax.text(3, 1.5, r'$N=p=$' + str(V) )
        ax.text(3, 1.15, "(" + str(V) + ")" )
        
        ax.set_xlim([0, 30])
        ax.set_xticks([0, 30])
        
        if amp:
            ax.set_ylim([0, 2])
            ax.set_yticks([0, 1, 2])
        else:
            ax.set_ylim([0, 1.5])
            ax.set_yticks([0, 1, 1.5])

        ax.plot( Lambs, Unstable , c='0.55', linewidth = 0.5)
    
    # print(" ")
    # print( Lambs[Unstable.index(1)] )
    # print( Lambs[ next(i for i in reversed(range(len(Unstable))) if Unstable[i] == 1)  ] )
        
    
    if 1 in Unstable:
        print( As[Unstable.index(1)] **2 * V / 4 )
        return Lambs[Unstable.index(1)]
    else:
        return np.NaN



def Thresh_over_V( fixed_Gamma = True, nmax= lambda V: 'all' ):
    
    crits = []
    Acrits = []
    Vcrits = []
    #fig, ax = plt.subplots(4, 5, figsize=(9,7))
    
    #fig, ax = plt.subplots(figsize=(9,7))
    
    Vs = range(2, 16)
    
    for n, V in enumerate(Vs):
        print('Test:', V,  nmax(V))
        Lamb, As, vects = Find_switch_V( V, fixed_Gamma, N_use= nmax(V))
        
        crits.append( Lamb )
        Acrits.append( As[-1] )
   
        print('V = ', V, 'Number of escape directions = ', len(vects))
        
        show = 0
        for vect in vects:
            show += np.abs(vect)
        Vcrits.append( show )
        
        # I should sort out a way of making all the vectors as simple as 
        # possible in the subspace of +'ve eignvals.
#        ax[ int(n/5), n%5 ].bar( range(0, len(show)), np.abs(show) )
        
    fig, ax = plt.subplots(figsize=(9,7))
    ax.plot(  Vs, crits, 'x-'  )
    ax.set_ylabel(r'Critical Drive ($\lambda / \gamma_1$)')
    
    fig, ax = plt.subplots(figsize=(9,7))
    ax.plot(  Vs, Acrits, 'x-'  )
    ax.plot(  Vs, [special.jnp_zeros(1, 1) for _  in Acrits], 'k-'  )
    ax.set_ylabel('Critical Amplitude')
    
    fig, ax = plt.subplots(figsize=(9,7))
    for V, Vect in zip(Vs, Vcrits):
        if not type(Vect) == int:
            for num, item in enumerate(Vect):
                if item > 0.01:
                    ax.plot(  V, num, 'o'  )
    
    return crits, Acrits

#
#A2 = 1.841
#theta2 = 0
#
#stabs = []
#eigs = []
#A2s = []
#
#Lambdas = np.linspace(0, 20, 1000)
#Gamma = 1
#
#for Lambda in Lambdas:
#    
#    F = lambda A2: (Lambda / (4 * Gamma)) * ( special.jn(0, A2) + special.jn(2, A2) ) - A2
#    
#    A2 = scipy.optimize.newton_krylov(F, [1], maxiter = 1200)[0]
#    
#    #print('A2:', A2, F(A2))
#    
#    A2s.append( A2 )
#    
#    eigs.append( Check_eigenvals( -1*Lambda, Gamma, A2, np.pi ) )
#    stabs.append( all( [np.real(item) < 0 for item in eigs[-1]] ))
#    
#    #stabs.append( Check_eigenvals( Lambda, 1, A2, 0 ) )
#
#
#fig, ax = plt.subplots(figsize=(9,12))
#ax.plot( Lambdas, np.array( eigs ) )
#
#fig, ax = plt.subplots(figsize=(9,12))
#ax.plot( Lambdas, np.array( stabs ) )
#
#fig, ax = plt.subplots(figsize=(9,12))
#ax.plot( Lambdas, np.array( A2s ) )
#
#
