import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

from qutip import *

from scipy import interpolate
from scipy import special #For special functions


from quantum_quad_solver import *
from Squeezing_moments import two_mode_stat_moment

import sys
sys.path.append('C:/Users/ppzbjl/Documents/Python Scripts/JJ_Photonics/JJ_laser/')
from Eigenvalue_checker import Find_switch_V

sys.path.append('C:/Users/ppzbjl/Documents/Python Scripts/JJ_Photonics/Plotting_Script_Saves/')
from phase_amp import phase_amp

# ----- Sort some functions

bes =  special.jn
pi = np.pi


# -------------- Sort Variables ---------------------
# V = 2
# N = 12 #2*V-1


#  lambda / omega_n  =  EJ_n * (2 Delta_n)^2 / hbar
# so for omega_n = n, hbar = 1
# lambda  =  EJ * n * (2 Delta_n)^2
# fix EJ
# EJ = lambda / (2*Delta_1)^2

# other Deltas?
# n * (2 Delta_n)^2 = (2 Delta_1)^2
# Delta_n = Delta_1 / sqrt( n )
Delta_1 = 0.2


thresh = 1

Delta_fixed = False

if Delta_fixed == True:
    Delta = [Delta_1  for _ in range(1,N+1)]
    over_direct = "Delta_fixed"
    
    thresh = 5.8 # The single mode threshold.
else:
    Delta = [Delta_1 / np.sqrt(n) for n in range(1,N+1) ]
    
    # Take into account "lambda tilde" effect:
    # IE "un-tilde" it.
    thresh *= np.exp( +0.5 * sum([d**2 for d in Delta]) )

    over_direct = "Multi_alpha"
# end if

Delta = np.array(Delta)

print("Delta = ", Delta)
print("V =", V)
print("N =", N)

#fix_gamma = False

if fix_gamma:
    Gamma = [1E-2] * N # (for all modes)
    save_dir = over_direct + '/Stab_Data/'
    load_dir = over_direct + '/Stab_Data/'
else:
    Gamma = [1E-2 * n**2 for n in range(1, N+1) ] # Proportional to n^2
    save_dir = over_direct + '/Stab_Data_gamma_sqr/'
    load_dir = over_direct + '/Stab_Data_gamma_sqr/'
# end if


# Work out data set:
if V >= 2*N-1:
    print('When p<2*N consider the simpler function.')
    m = 1
else:
    # Find m such that V<m*N
    m = int( N  / V )
    print( 'm = ', m)
# end if

# Load Appropriate Data set for resonant modes (using m, not N)
if fix_gamma:
    fp_dir = "Fixed_Point_Data/V=1_N=" + str(m) + "_Attempt=1_"
else:
    fp_dir = "Fixed_Point_Data/gamma_sqr/gamma_sqr_V=1_N=" + str(m) + "_Attempt=1_"
# end

fp_sols =  np.load( fp_dir + "FPs.npy")
# fp_stabs maybe only knows about bifurcations in the resonant harmonics.
# The fixed point solver it comes from doesn't even know the others exist.
fp_stabs = np.load( fp_dir + "stabss.npy")
fp_LambTs = np.load( fp_dir + "Lambss.npy")

# Lambs already include scaling by (2*Delta_1)**2,
# BUT: should instead by scaled by (2*Delta_V)**2
# Also, Gamma is different
fp_LambTs = fp_LambTs * V * (Gamma[V-1] / 1E-3)

# cast to complex
fp_sols = np.squeeze( fp_sols[:,:,::2] + 1j * fp_sols[:,:,1::2] )


# Rescale:  
# sols found with Delta_1 = 0.5. Need to scale to Delta[V-1::V]
fp_sols = fp_sols / (2* np.array(Delta[V-1::V]) )
    

# Only good upto a bifurcation (first unstable solution)
if False in fp_stabs:
    Lambda_bif_tilde = fp_LambTs[ list(fp_stabs).index(False) ]
else:
    Lambda_bif_tilde = fp_LambTs[-1]
# end if


# Build interopolator to find alpha vectors
if m > 1:
    def interp_Amp( Lambda ):
        return np.array([ interpolate.interp1d( fp_LambTs, fp_sols[:,n] )(Lambda) for n in range(fp_sols.shape[1]) ])
else:
    def interp_Amp( Lambda ):
        return np.array([ interpolate.interp1d( fp_LambTs, fp_sols )(Lambda) ])

# end if

# Load previous search
Lambs_last = np.load( load_dir + "V=" + str(V) + "_N=" + str(N) + "_Lambs.npy")
stabs_last = np.load( load_dir + "V=" + str(V) + "_N=" + str(N) + "_stabs.npy")
# Lambs_last = np.load( load_dir + "V=" + str(V) + "_N=" + str(N) + "_Lambs2.npy")
# stabs_last = np.load( load_dir + "V=" + str(V) + "_N=" + str(N) + "_stabs2.npy")


if not True in stabs_last:
    print('No transition was detected, cannot up resolution')
    print('(for values N=' + str(N) + " and V = " + str(V)  + ")")
    
    over_direct = "Multi_alpha"
        
    save_dir = over_direct + '/Stab_Data/'
    
    np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_Lambs2.npy", Lambs_last)
    np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_stabs2.npy", stabs_last)

else:
    
    Thresh_num = list(stabs_last).index(True)
    
    Lambs = np.linspace( Lambs_last[ Thresh_num - 1 ], Lambs_last[ Thresh_num  ], 300)
    #Lambs = [ Lambs_last[ Thresh_num  ] ]
    
    print( fp_LambTs[-1], Lambs[-1] )
    
    # -------------- End Sort Variables ---------------------
    
    stabs = []
    
    M, const, C_vecs, H_str = build_matrix_general( N, V, slim = True )
    stab_mat = find_stability_matrix( H_str,  C_vecs, N)
    
    
    for Lambda in Lambs:
        # Find Classical amplitude A of resonant mode.
        
        Lambda_tild = Lambda * np.exp( -0.5 * sum([d**2 for d in Delta]) )
        
        if Lambda_tild < Lambda_bif_tilde:
            AV = interp_Amp(Lambda_tild )
        else:
            print('Past stable point. Solutions will be wrong')
            AV = interp_Amp(Lambda_tild )
        # end if
        
        EJ = Lambda / (2*Delta_1)**2
        EJ_tilde = EJ * np.exp( -0.5 * sum([d**2 for d in Delta]) )
        
        
        # Stability
        stabs.append( solve_stab_matrix( stab_mat, AV, Delta, EJ_tilde, Gamma, V = V ) )
        
        print('done')
        
        if stabs[-1]:
            # Might as well stop once it is unstable.
            break
        
    ## Find k-space of instability
    
    eig_vecs, eig_vals =  solve_stab_matrix( stab_mat, AV, Delta, EJ_tilde, Gamma, V = V, give_vecs = True )
        
    index = list(eig_vals).index( max(eig_vals) )
    rel_vec = eig_vecs[index] # relevant vector
    
    K_vec = [ [ np.exp(1j*2*pi*k/V), np.exp(-1j*2*pi*k/V) ] for k in range(1, N+1)   ]
    K_vec = [item for sublist in K_vec for item in sublist] # flatten
    
    
    k_space = np.angle( np.sum( K_vec * np.abs(rel_vec) ) ) * (V / (2*pi) )
    
    print("N", N, "p", V, "k", k_space)
    
    
    ### ------- SAVE DATA ------
    
    np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_Lambs2.npy", Lambs)
    np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_stabs2.npy", stabs)
    np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_k2.npy", k_space)
