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

#loss = "quad"
loss = "fixed"

# -------------- Sort Variables ---------------------
# V = 5
# N = 12 #2*V-1

if loss == "quad":
    Gamma = [1E-2 * n**2 for n in range(1, N+1) ] # quadratically incresing.
else:
    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


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


if loss == "quad":
    over_direct += "_quad_loss"

Delta = np.array(Delta)

print("Delta = ", Delta)
print("V =", V)
print("N =", N)

# Work out data set:
if V >= 2*N-1:
    print('You are using the WRONG function!')
    print('When p<2*N use the simple 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 loss == "quad":
    fp_dir = "Fixed_Point_Data/gamma_sqr/gamma_sqr_V=1_N=" + str(m) + "_Attempt=1_"
else:
    fp_dir = "Fixed_Point_Data/V=1_N=" + str(m) + "_Attempt=1_"


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
def interp_Amp( Lambda ):
    return np.array([ interpolate.interp1d( fp_LambTs, fp_sols[:,n] )(Lambda) for n in range(fp_sols.shape[1]) ])

# Un-tilde, and go to less than the full way.
Lmax = 0.65 * Lambda_bif_tilde * np.exp( +0.5 * sum([d**2 for d in Delta]) )


# Artificial correction to put EJ range sensible
scale_dict = {3: 0.3, 4:0.25, 5:0.225}

if loss=="quad":
    Lmax *= 0.1 * scale_dict[V]

Lambs = np.linspace(0, Lmax, 100)

print( "EJ (2\Delta)^2 / gamma, max value: ", Lambs[-1] / Gamma[0] )


print( fp_LambTs[-1], Lambs[-1] )

# -------------- End Sort Variables ---------------------


if loss == "quad":
    save_dir = "Multi_alpha_quad_loss/" + "V=" + str(V) + " N=" + str(N) +"/"
else:
    save_dir = "Multi_alpha/" + "V=" + str(V) + " N=" + str(N) +"/"

Lambs = np.load( save_dir + "Lambs.npy")
stabs = np.load( save_dir + "stabs.npy")
covmats = np.load( save_dir + "covmats.npy")
covmats = [np.real(c) for c in covmats]
expects_quad = np.load( save_dir + "expects_quad.npy")
free_squeezes = np.load( save_dir + "free_squeezes.npy")
try:
    all_stab_eigs = np.load( save_dir + "all_stab_eigs.npy")
    all_stab_vecs = np.load( save_dir + "all_stab_vecs.npy")
except:
    all_stab_eigs = []
    all_stab_vecs = []
# end try

Lambs = list(Lambs)
Lamb_increment = ( Lambs[1] - Lambs[0] ) * 1.1 # use 10% larger steps.

free_squeezes = list(free_squeezes)
squeeze_directions = []

expects_quad = list(expects_quad)

stabs = list(stabs)
all_stab_eigs = list(all_stab_eigs)
all_stab_vecs = list(all_stab_vecs)


EJTs = []
As = []

M, const, C_vecs, H_str = build_matrix_general( N, V, slim = True )
stab_mat = find_stability_matrix( H_str,  C_vecs, N)
H_mat    = find_Hamiltonian_matrix( H_str,  C_vecs, N)

print("starting")

while stabs[-1]==False:
    # Find Classical amplitude A of resonant mode.
    
    Lambs.append( Lambs[-1] + Lamb_increment )
    Lambda = Lambs[-1]
    
    # Make increment bigger for next time:
    Lamb_increment *= 1.01
    
    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')
        try:
            AV = interp_Amp( Lambda_tild )
        except:
            AV = interp_Amp( Lambda_bif_tilde )
    # 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, V = V )
    #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, V = V ) )
    
    stab_vecs, stab_eigs = solve_stab_matrix( stab_mat, AV, Delta, EJ_tilde, Gamma, V = V, give_vecs=True )
    
    stab_vecs = [ list(item) for item in  stab_vecs ]
    stab_eigs, stab_vecs = zip(*sorted(zip( stab_eigs, stab_vecs )))
    
    print(Lambda, stabs[-1])
    all_stab_eigs.append( stab_eigs )
    all_stab_vecs.append( stab_vecs )
    
    
    # psi_g1( AV, Delta, fs, expects_quad[-1], C_vecs, V )
    
    # Bogoliubov-like things:
    #B_vecs, eig_vals, new_mat = solve_stab_matrix( H_mat, AV, Delta, EJ_tilde, Gamma, give_vecs = True ) 


### ------- SAVE DATA ------

if loss == "quad":
    save_dir = "Multi_alpha_quad_loss/" + "V=" + str(V) + " N=" + str(N) +"/"
else:
    save_dir = "Multi_alpha/" + "V=" + str(V) + " N=" + str(N) +"/extended"

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)


### -------

font = {'family' : 'normal',
    'weight' : 'normal',
    'size'   : 16}
mpl.rc('font', **font)

cols = 'rgbcyk:o' * 5

##################### 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$'
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, scale_Lamb[0] + 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 ######################

if len(all_stab_eigs): # if variable exists:
    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, scale_Lamb[0] + 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 ######################
if len(all_stab_eigs): # if variable exists:
    fig, ax = plt.subplots(2, 3, figsize=(9,6))
    
    use_range = [item+0.5 for item in range(0,N+1)]
    
    if True in stabs:
        stability_change = list(stabs).index( True )
    else:
        stability_change = len(stabs)-1
    
    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 ######################


fig, ax = plt.subplots(figsize=(5,5))
ax.plot( scale_Lamb, free_squeezes)
ax.set_xlabel(xlab)

#ax.set_xlim(0, scale_Lamb[0] + 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-')
ax.plot( scale_Lamb, 5*np.array(stabs), '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, scale_Lamb[0] + 0.5)
ax.set_ylim(0, 1 ) #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) ]

vmax = 0.6

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, vmax = vmax )
    
    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], maximum = vmax, 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:
        neg_muls = partial_fully_seperable( [item -1 for item in group], covmats[EJ_num] )
        print(k, EJ_num, neg_muls > 0, neg_muls )
        
    
# 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 block form ######################

######################  Multinegativity by k group ######################
# Negativities

fig, ax = plt.subplots(figsize=(5,5))

for group in k_groups:
    quad_neg = [ partial_fully_seperable( [item -1 for item in group], Covmat ) for Covmat in covmats]
    ax.plot( scale_Lamb, quad_neg, label = str(group) )

#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-')
ax.plot( scale_Lamb, 5*np.array(stabs), '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)$ (multi)')
ax.legend()

#ax.set_xlim(0, scale_Lamb[0] + 0.5)
ax.set_ylim(0, 1 ) #0.8)

fig.savefig( save_dir + "MultiNegativity.pdf", bbox_inches='tight')
######################  END Multinegativity by k group ######################

######################  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 ######################

######################  Covariance Matrix - Block form ######################
# Negativities

fig, ax = plt.subplots( int(V/2)+1, 3, figsize=(9,3 * (int(V/2)+1) ))

for num, EJ_num in enumerate(dos):
    covmat = np.real(covmats[EJ_num])
    
    print(covmat.max())
    
    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.zeros( (len(group)*2, len(group)*2) ) + 100
        
        for n1, g1 in enumerate(group):
            for n2, g2 in enumerate(group):
                use_mat[ 2*n1: 2*n1+2, 2*n2 : 2*n2+2 ] = covmat[ 2*(g1-1): 2*(g1-1) + 2 , 2*(g2-1) : 2*(g2-1) + 2]
        

        print(use_mat.max())
        print(use_mat.min())
        
        max_ab = np.abs(use_mat).max()
        
        #ax[].imshow( use_mat )
        pcm = ax[k, num].pcolormesh( range(2*len(group)+1), range(2*len(group)+1), use_mat, vmin = - max_ab, vmax = max_ab )
    
        ax[k, num].set_xticks( [2*item + 1 for item in range(len(group)) ] )
        ax[k, num].set_xticklabels( group )
        ax[k, num].set_yticks(  [2*item + 1 for item in range(len(group)) ]  )
        ax[k, num].set_yticklabels( group )
        
        length = len(group) + 1
        for pos in range(length):
            ax[k, num].plot( [2*pos]*length, [2*i for i in range(length)], 'k', linewidth = 0.5 )
            ax[k, num].plot( [2*i for i in range(length)], [2*pos]*length, 'k', linewidth = 0.5 )
    
# Add colourbar
#fig.subplots_adjust(right=0.88)
#cbar_ax = fig.add_axes([0.9, 0.175, 0.025, 0.65])
#fig.colorbar( pcm, cax=cbar_ax)

fig.savefig( save_dir + "cov_by_block.pdf", bbox_inches='tight')
######################  END Negativity ######################


######################  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 ######################
