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
from nodes_graph_plot import relation_graph

# ----- Sort some functions

bes =  special.jn
pi = np.pi


# -------------- Sort Variables ---------------------
# V = 5
# N = 11
Gamma = [1E-2] * N # (for all modes)


#  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


if (V, N) == (2, 3):
    thresh = 7.75526  # (Grace has 7.75000, near identical)
elif (V, N) == (3, 5):
    thresh = 11.07237
elif (V,N) == (4,7):
    thresh =  13.84646
elif (V,N) == (5, 9):
    thresh = 16.3955 
else:
    thresh, _, _ = Find_switch_V( V, True, N )
# end if

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 = "Delta_over_root(n)"
# end if


As = []
zp = special.jnp_zeros(1, 1)[0]

Amax = zp / (2*Delta[V-1])
print('About ', int(Amax**2), " photons in active cavity")

# Find resonant-mode bifuraction
EJ_2nd_bif =  Gamma[V-1] * (Amax**2) / ( special.jn(1, zp) )
Lambda_bif =  EJ_2nd_bif * (2*Delta[V-1])**2 

Lmax = int( thresh *1.1 + 1 )
L_unnromed = np.linspace(0, Lmax, 100)

Lambs = [l*Gamma[V-1] for l in L_unnromed]



# -------------- End Sort Variables ---------------------


quad_sols = []
expects_quad = []
covmats = []
free_squeezes = []
squeeze_directions = []
stabs = []
Bog_likes = []
all_stab_eigs = []
all_stab_vecs = []


EJTs = []

M, const, C_vecs, H_str = build_matrix( N, V, V )
stab_mat = find_stability_matrix( H_str,  C_vecs, N)
H_mat    = find_Hamiltonian_matrix( H_str,  C_vecs, N)

for Lambda in Lambs:
    # Find Classical amplitude A of resonant mode.
    # NOTE: I have no 1/V in the fixed point finder.
    # Instead I have the ( Delta[V-1] / Delta[0] )**2  thing.
    
    Lambda_tild = Lambda * np.exp( -0.5 * sum([d**2 for d in Delta]) )
    Lambda_tild *= ( Delta[V-1] / Delta_1 )**2
    
    if Lambda_tild < Lambda_bif:
        FA = lambda AV: (Lambda_tild / (2 * Gamma[V-1])) * ( bes(0, AV) + bes(2, AV) ) - AV
        
        if As:
            AV = scipy.optimize.newton_krylov(FA, [As[-1]], maxiter = 1200)[0]
        else:
            AV = scipy.optimize.newton_krylov(FA, [0.1], maxiter = 1200)[0]
        #end if
        AV = AV / (2*Delta[V-1])
    else:
        AV = Amax # Post bifurcation
    # end if    
    As.append( AV )
    
    EJ = Lambda / (2*Delta_1)**2
    EJ_tilde = EJ * np.exp( -0.5 * sum([d**2 for d in Delta]) )
    
    EJTs.append( EJ_tilde )

    # Quadratic order solution:
    quad_sol = solve_built_matrix( M, const, AV, Delta, EJ_tilde, Gamma )
    quad_sols.append( quad_sol )
    
    covmat = covariance_form( C_vecs, quad_sol, displacements = [0]*N, nmodes = N )
    covmats.append( covmat )
    
    eig_vals, eig_vects = np.linalg.eig( covmat )
    
    eig_vals = real(eig_vals)
    eig_index = list(eig_vals).index( min(eig_vals) )
    
    free_squeezes.append( 0.5 * min(eig_vals) )
    squeeze_directions.append( np.real(eig_vects[eig_index, :]  ))

    
    # <n_x> for x in 1,2,3 from QUads
    basic_vec = lambda n, m: np.array( [0]*m + [1] + [0]*(n-m-1) )
    
    expects_quad.append( [get_op(C_vecs, item, quad_sol ) for item in [ (1+1j) * basic_vec(N,m) for m in range(N) ] ] )
    
    # Stability
    stabs.append( solve_stab_matrix( stab_mat, AV, Delta, EJ_tilde, Gamma ) )
    
    stab_vecs, stab_eigs = solve_stab_matrix( stab_mat, AV, Delta, EJ_tilde, Gamma, give_vecs=True )
    
    stab_vecs = [ list(item) for item in  stab_vecs ]
    stab_eigs, stab_vecs = zip(*sorted(zip( stab_eigs, stab_vecs )))
    
    
    all_stab_eigs.append( stab_eigs )
    all_stab_vecs.append( stab_vecs )
    
    # Bogoliubov-like things:
    #B_vecs, eig_vals, new_mat = solve_stab_matrix( H_mat, AV, Delta, EJ_tilde, Gamma, give_vecs = True ) 


### -------

font = {'family' : 'normal',
    'weight' : 'normal',
    'size'   : 16}
mpl.rc('font', **font)

cols = 'rgbcyk:o' * 5

save_dir = over_direct + "/V=" + str(V) + ' N=' + str(N) + "/"

np.save( save_dir + "Lambs.npy", Lambs)
np.save( save_dir + "stabs.npy", stabs)
np.save( save_dir + "covmats.npy", covmats)
np.save( save_dir + "expects_quad.npy", expects_quad)
np.save( save_dir + "free_squeezes.npy", free_squeezes)
np.save( save_dir + "all_stab_eigs.npy", all_stab_eigs)
np.save( save_dir + "all_stab_vecs.npy", all_stab_vecs)

##################### X axis #####################
# Use first mode to scale x-axis?
first_mode = True

if first_mode:
    # scale_Lamb = [ (l / Gamma[0]) * np.exp(-0.5 * sum([d**2 for d in Delta]) ) for l in Lambs]
    # xlab = r'$ \tilde{E}_J (2\Delta_1)^2 / \gamma$'
    
    scale_Lamb = [ 0.25 * (l / Gamma[0]) * np.exp(-0.5 * sum([d**2 for d in Delta]) ) for l in Lambs]
    Lmax *= 0.25
    xlab = r'$ \tilde{E}_J (\Delta_1)^2 / \gamma$'
else:
    scale_Lamb = [ (l / Gamma[0]) * (Delta[V-1] / Delta_1 )**2 * np.exp(-0.5 * sum([d**2 for d in Delta]) ) for l in Lambs]
    Lmax *= (Delta[V-1] / Delta_1 )**2
    xlab = r'$ \tilde{E}_J (2\Delta_V)^2 / \gamma$'

###################### Mode Amplitudes ######################

fig, ax = plt.subplots(figsize=(5,5))

sqrt = np.sqrt

for mode in range(N):
    ax.plot( scale_Lamb, [ sqrt(e[mode]) for e in expects_quad], cols[mode], label = str(mode+1))
    
#ax.plot( [thresh, thresh], [0, 6], 'k-')
ax.set_ylabel(r'$\sqrt{\langle \hat{n} \rangle}$')
ax.set_xlabel(xlab)


ax.plot( scale_Lamb, 5*np.array(stabs), 'k' )

ax.set_xlim(0, Lmax + 0.5)
ax.set_ylim(0, int( np.sqrt( np.array(expects_quad).max() ) ) +1 )
ax.legend()

fig.savefig( save_dir + "Amplitudes.pdf", bbox_inches='tight')
###################### End Mode Amplitudes ######################

###################### Stability Eigenvalues ######################

fig, ax = plt.subplots(figsize=(5,5))

all_stab_eigs = np.array( all_stab_eigs )

sorted_vals = []

for m in [item for item in range(1, int((V+2)/2))] + [V]:
    sorted_vals.append( [] )
    
    dot_vec = np.array( [0]*(2*N) )
    for ele in [ (m-1), (V-m-1), (V+m-1), (2*V-m-1) ]:
        dot_vec[2*ele:2*ele+2] = 1
    
    
    for vals, vecs in zip( all_stab_eigs, all_stab_vecs ):
        sorted_vals[-1].append( [] )
        
        for val, vec in zip(vals, vecs):
            if sum(np.abs( vec * dot_vec )) > 1E-10:
                sorted_vals[-1][-1].append( val )

sorted_vals.reverse()
for m_set, colour in zip( sorted_vals, cols ):
    for val in range( len(m_set[0]) ):
        ax.plot( scale_Lamb, [ sorted(item)[val] for item in m_set], colour )

if Delta_fixed == True:
    fig, ax = plt.subplots(figsize=(5,5)) 
    ax.plot( scale_Lamb, all_stab_eigs )
          
          
#ax.plot( [thresh, thresh], [0, 6], 'k-')
ax.set_ylabel(r'Eigenvalue')
ax.set_xlabel(xlab)


ax.set_xlim(0, Lmax + 0.5)
ax.set_ylim( -1 * Gamma[0] , 0.1 * Gamma[0] )

fig.savefig( save_dir + "Eig_vals.pdf", bbox_inches='tight')

###################### End Stability Eigenvalues ######################

###################### Stability Eigenvectors ######################

fig, ax = plt.subplots(2, 3, figsize=(9,6))

use_range = [item+0.5 for item in range(0,N+1)]

stability_change = stabs.index( True )

for num, EJ_num in enumerate([10, 25, 50, 75, stability_change-5, stability_change]):
    #ax[ int(num/3), num%3 ].imshow( np.abs( all_stab_vecs[EJ_num] ) )
    
    phase_amp( all_stab_vecs[EJ_num] , [i for i in range(2*N)], ax = ax[ int(num/3), num%3 ] )
    
    eigs = list( all_stab_eigs[EJ_num] )
    greatest_eigval = eigs.index( max(eigs) ) + 0.5
    
    #ax[ int(num/3), num%3 ].plot( [0, 2*N], [2*N - 1.5, 2*N -1.5], 'k' )
    ax[ int(num/3), num%3 ].set_ylabel( r'$\lambda$' )
    ax[ int(num/3), num%3 ].set_xlabel( r'Mode' )
    
fig.savefig( save_dir + "Eig_vecs.pdf", bbox_inches='tight')

###################### End Stability Eigenvectors ######################

# ######################  Squeezing ######################

# # 2 Mode squeezing plot:
# angles = [2*np.pi/6, -2*np.pi/6]  # Found to be best for maximising 2-mode squeeze
   

# fig, ax = plt.subplots(figsize=(5,5))
# ax.plot( scale_Lamb, free_squeezes, label = 'Quad squeeze, free axis')
# ax.set_xlabel(xlab)

# ax.set_xlim(0, Lmax + 0.5)
# ax.set_ylim(0.15, 0.55)

# fig.savefig( save_dir + "Squeezing.pdf", bbox_inches='tight')
# ######################  END Squeezing ######################

# ######################  Purity  ######################
# quad_pure = [ 1 / np.sqrt(  np.real( np.linalg.det( mat ) )) for mat in covmats ]

# fig, ax = plt.subplots(figsize=(5,5))
# ax.plot( scale_Lamb, quad_pure )

# ax.set_xlabel(xlab)
# ax.set_xlabel(r'Purity')

# ax.set_xlim(0, Lmax + 0.5)
# ax.set_ylim(0.1, 1.1)


# fig.savefig( save_dir + "Purity.pdf", bbox_inches='tight')
# ######################  End Purity  ######################

######################  Negativity ######################
# Negativities

fig, ax = plt.subplots(figsize=(5,5))

for mode in range(N):
    quad_neg = [ Guassian_Entanglement( Covmat, mode ) for Covmat in covmats]
    ax.plot( scale_Lamb, quad_neg, cols[mode], label = str(mode+1) )


ax.plot( [thresh*np.exp(-0.5 * sum([d**2 for d in Delta]) ), thresh*np.exp(-0.5 * sum([d**2 for d in Delta]) )], [0,1], 'k-')



# for EJ_num in [25, 50, 75]:
#     ax.plot( scale_Lamb[EJ_num]*np.array([1,1]), [0, 0.02], 'k' )


ax.set_xlabel(xlab)
ax.set_ylabel(r'$E_{ \mathcal{N}}(\rho)$')
ax.legend()

ax.set_xlim(0, Lmax + 0.5)
ax.set_ylim(0, 0.8)

fig.savefig( save_dir + "Negativity.pdf", bbox_inches='tight')
######################  END Negativity ######################

#####################  Negativity Matrix ######################
# Negativities

fig_M, ax_M = plt.subplots(1, 3, figsize=(9,3))
fig_G, ax_G = plt.subplots(1, 3, figsize=(9,3))

use_range = [item+0.5 for item in range(0,N+1)]

if True in stabs:
    dont_go_past = list(stabs).index(True)
else:
    dont_go_past = len(stabs)
#

dos = [ int(dont_go_past * (n/4)) for n in range(1,4) ]


for num, EJ_num in enumerate(dos):
    Neg_Mat = [[ Partial_Guassian_Entanglement( covmats[EJ_num], y, [y] + [x] ) for x in range(0,N)] for y in range(0,N)]
    
    pcm = ax_M[num].pcolormesh( use_range, use_range, Neg_Mat, vmin = 0 )
    
    ax_M[num].set_xticks( range(1,N+1) )
    ax_M[num].set_yticks( range(1,N+1) )
    
    relation_graph( np.array(Neg_Mat), ax = ax_G[num], labels = [item+1 for item in range(2*N)] )
    
# Add colourbar
fig_M.subplots_adjust(right=0.88)
cbar_ax = fig_M.add_axes([0.9, 0.175, 0.025, 0.65])
fig_M.colorbar( pcm, cax=cbar_ax)

fig_M.savefig( save_dir + "Mode_mode_Negs.pdf", bbox_inches='tight')
fig_G.savefig( save_dir + "Mode_mode_Negs_graph.pdf", bbox_inches='tight')

######################  END Negativity ######################
######################  Negativity Matrix - Block form ######################
# Negativities

fig_M, ax_M = plt.subplots( int(V/2)+1, 3, figsize=(9,3 * (int(V/2)+1) ))
fig_G, ax_G = plt.subplots( int(V/2)+1, 3, figsize=(9,3 * (int(V/2)+1) ))

vmax = 0.6

base = range(0, N+V, V)
k_groups = []

for k in range(0, int(V/2)+1):
    if k>0:    new_ks=  [i - k for i in base] + [i + k for i in base]
    else:      new_ks=  [i for i in base]
    
    # remove duplicates
    new_ks = list(dict.fromkeys(new_ks))
    
    # sort
    new_ks.sort()
    new_ks = np.array( new_ks )
    
    # cut off surplus:
    start = [nk > 0 for nk in new_ks].index(True)
    if False in [nk < N+1 for nk in new_ks]:
        end   = [nk < N+1 for nk in new_ks].index(False)
    else:
        end = len(new_ks) + 1
    
    k_groups.append( new_ks[start:end] )
    

for num, EJ_num in enumerate(dos):
    Neg_Mat = [[ Partial_Guassian_Entanglement( covmats[EJ_num], y, [y] + [x] ) for x in range(0,N)] for y in range(0,N)]
    
    for k in range(int(V/2)+1):
        
        group = k_groups[k]
        
        #take = [g*2 - 1 for g in group] + [g*2 - 2 for g in group]
        use_mat = np.array( [[ Neg_Mat[ g1-1 ][ g2-1 ] for g1 in group] for g2 in group] )
        
        #print(use_mat)
        
        pcm = ax_M[k, num].pcolormesh( range(len(group)+1), range(len(group)+1), use_mat, vmin = 0, vmax = vmax )
    
        ax_M[k, num].set_xticks( range(len(group)) )
        ax_M[k, num].set_xticklabels( group )
        ax_M[k, num].set_yticks( range(len(group)) )
        ax_M[k, num].set_yticklabels( group )
        
        relation_graph( np.array(use_mat), ax = ax_G[k, num], maximum = vmax, labels = group )
        
        # Check fully multipartite entangled:
        #print(k, EJ_num, partial_fully_seperable( [item -1 for item in group], covmats[EJ_num] ) )
    
# Add colourbar
fig_M.subplots_adjust(right=0.88)
cbar_ax = fig_M.add_axes([0.9, 0.175, 0.025, 0.65])
fig_M.colorbar( pcm, cax=cbar_ax)

fig_M.savefig( save_dir + "Mode_mode_Negs_by_block.pdf", bbox_inches='tight')
fig_G.savefig( save_dir + "Mode_mode_graphs_by_block.pdf", bbox_inches='tight')

######################  END Negativity ######################

######################  Genuine Entanglement ######################

rot_covmats = [ rotate_away_off_diags(np.real(c)) for c in covmats ] # very wasteful, probably the same rotation angles are recalculated for every covmat!

# Full entanglement across k-groups
gen_group_entangles = []
for c, s in zip(rot_covmats, stabs):
    if not(s):
        gen_group_entangles.append( [ partial_genuine_entanglement( c, [g-1 for g in group] ) for group in k_groups ] )
    else:
        gen_group_entangles.append( [np.NaN] * len(k_groups) )
# end for


# gen_group_entangles = np.array(gen_group_entangles)

# fig, ax = plt.subplots(figsize = (5,5))
# ax.plot( scale_Lamb, gen_group_entangles )
# ax.set_xlabel(xlab)
np.save( save_dir + "gen_group_entangles.npy", gen_group_entangles)

# N partite entanglement accorss subsets of groups:
sub_gen_entangles = []
pods = []
    
for group in k_groups:
    
    num = len(group)
    bips = all_bipartitions(num)
    
    picks = [[ group[item]-1 for item in bip ] for bip in bips] # half the sets
    picks.extend( [[ g-1 for n, g in enumerate(group) if n not in bip ] for bip in bips] ) # the opposing sets
    
    # for completeness include full group as well
    picks.append( [g-1 for g in group] )
    
    # 1 mode subsets cannot host entanglement
    # 2 modes subsets are checked fine by the other method.
    picks = [item for item in picks if len(item)>2]
    
    for pick in picks:
        pods.append( pick )
        sub_gen_entangles.append( [] )

        for c, s in zip(rot_covmats, stabs):
            if s==False:
                sub_gen_entangles[-1].append( partial_genuine_entanglement( c, pick )  )
            else:
                sub_gen_entangles[-1].append( np.NaN  )
            
# end 3 fors

sub_gen_entangles = np.array(sub_gen_entangles)

np.save( save_dir + "sub_gen_entangles.npy", sub_gen_entangles)


for pod, entangles in zip(pods, sub_gen_entangles):
    found_entangles = [type(item)==tuple for item in entangles]
    
    if True in found_entangles[1:]:
        print('Entanglement in :', pod, " For V=", V, " and N=", N)
        


######################  END Genuine Entanglement ######################

######################  Psi Covariance Matrix ######################

# fs = [item for item in range(1, N+1)]

# for n in [25, 50, 85, 92]:
#     psi_covs = psi_flucts( covmats[n], Delta, fs, np.linspace( 0, 2*np.pi, 600 ) )

#     fig, ax = plt.subplots(figsize=(9,3))
#     xvars = [cov[0,0] for cov in psi_covs]
    
#     xvals = As[n] * np.cos( V * np.linspace( 0, 2*np.pi, 600 ) )
#     ts = np.linspace( 0, 2*np.pi, 600 )
    
#     ax.fill_between(ts, xvals + xvars,  xvals - xvars)
#     ax.plot( ts, xvals, 'k-' )
    
#     fig, ax = plt.subplots(figsize=(9,3))
#     ax.plot( ts, xvars, 'k-' )
    
    # fig, ax = plt.subplots(figsize=(9,3))
    # for t, cov in enumerate(psi_covs):
    #     eig_vals, eig_vects = np.linalg.eig( cov / (Delta[0])**2 )
        
        
    #     for val, vec in zip(eig_vals, eig_vects):
    #         ax.plot( [t, np.sqrt(val)*vec[0] + t], [0, np.sqrt(val)*vec[1]] )
    
    # ax.axis('equal')
    
######################  END Negativity ######################
