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



Delta_fixed = False

if Delta_fixed == True:
    Delta = [Delta_1  for _ in range(1,N+1)]
    over_direct = "Delta_fixed"
    
elif Delta_fixed == "Special":
    
    DB = 0.4 # Delta_big
    Delta = np.array( [ DB, DB, Delta_1/np.sqrt(3), DB ] )
    
    over_direct = 'Weird_Delta'
else:
    Delta = [Delta_1 / np.sqrt(n) for n in range(1,N+1) ]

    over_direct = "Multi_alpha"
# end if
Delta = np.array(Delta)

print("Delta = ", Delta)
print("V =", V)
print("N =", N)

# Find m such that V<m*N
m = int( N  / V )
print( 'm = ', m)

# Work out data set:
if m == 1:
    print('When p<2*N consider the simpler function.')


fix_gamma = 'quad'

if fix_gamma == True:
    Gamma = [1E-2] * N # (for all modes)
    save_dir = over_direct + '/Stab_Data/'
    
    # Load Appropriate Data set for resonant modes (using m, not N)
    fp_dir = "Fixed_Point_Data/V=1_N=" + str(m) + "_Attempt=1_"
elif fix_gamma == 'quad':
    Gamma = [1E-2 * n**2 for n in range(1, N+1) ] # Proportional to n^2
    save_dir = over_direct + '/Stab_Data_gamma_sqr/'
    fp_dir = "Fixed_Point_Data/gamma_sqr/gamma_sqr_V=1_N=" + str(m) + "_Attempt=1_"
else:
    Gamma = [1E-2 * (0.99 +  n**2 / 100) for n in range(1,N+1)]  # Proportional to const + n^2
    save_dir = over_direct + '/Stab_Data_gamma_hyb/'
# end if

print('Save directory is', save_dir)


fp_sols =  np.load( fp_dir + "FPs.npy")
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 * ( Delta_1 / Delta[V-1] )**2  * (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

# Un-tilde
Lmax = Lambda_bif_tilde * np.exp( +0.5 * sum([d**2 for d in Delta]) ) / Gamma[V-1]

# I generally pick an Lmax that is too high (especially at higher p). So lower it
#Lmax = Lmax / V

L_unnromed = np.linspace(0, Lmax, 200)
Lambs = [l*Gamma[V-1] for l in L_unnromed]

print( "EJ (2\Delta)^2 / gamma, max value: ", Lambda_bif_tilde / Gamma[V-1] )


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)

to_plot = False

if to_plot:  As = []

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 )
        break
    # end if
    
    if to_plot:  As.append( AV )
    
    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
    

## ------- Which subspace is the transition in?

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(k_space)


### ------- SAVE DATA ------

np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_Lambs.npy", Lambs)
np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_stabs.npy", stabs)
np.save( save_dir + "V=" + str(V) + "_N=" + str(N) + "_k.npy", k_space)

if to_plot:
    fig, ax = plt.subplots(figsize=(4,4))
    ax.plot( fp_LambTs * np.exp( +0.5 * sum([d**2 for d in Delta]) ), fp_sols )
    ax.plot( Lambs[:len(As)], As, 'x' )
    
    
    