# -*- coding: utf-8 -*-
"""
Created on Tue Jul  7 15:13:55 2020

@author: ppzbjl
"""
from mpmath import mp
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 random
from scipy.optimize import fsolve

# Set accuracy to 10 decimal places.
mp.dps = 10

# A code to Solve the equations of motion for a multi-cavity system in the RWA.
i = 1j
conj = np.conj


# UNIT CONVERSIONS:
#  lambda / omega  =  EJ * (2 Delta)^2 / hbar
#  gammma the same in both cases.
#   I always use omega = 1 and  hbar = 1 for simplicity.

# The equations of motion you have are very slighty different from these. (I have an extra factor of 1/2 for 
# the drive terms of the Beta mode which I think isn't present in your problem).


def K2D( p, q, n, A, B ):
    
    function = lambda t: mp.exp( (A/2) * mp.exp(i*p*t) - (conj(A)/2) * mp.exp(-i*p*t) 
                               + (B/2) * mp.exp(i*q*t) - (conj(B)/2) * mp.exp(-i*q*t)
                               -i*n*t )
    
    return np.complex(   mp.quad(function, [-mp.pi, mp.pi]) / (2*mp.pi)   )


def KND( ps, n, As ):
    # N-dimensional Z-functon as an integral.
    function = lambda t: mp.exp( 
                            sum( [ (A/2) * mp.exp(i*p*t) - (conj(A)/2) * mp.exp(-i*p*t)  for A, p in zip(As, ps)] )
                               -i*n*t
                               )
    
    # Addapt integrator to maximum frequency (finer integration needed at high freq):
    mp.dps = max( [10, 4 * max(ps) ] )
    
    return np.complex(   mp.quad(function, [-mp.pi, mp.pi]) / (2*mp.pi)   )


def N_mode_fixed_points( N, V, Lambda = 1,  gamma = 'same', alpha = 'same', guess = 'none' ):
    
    if gamma == 'same':
        gamma = [1E-3 for _ in range(N)]
    
    if alpha == 'same':
        alpha = np.array( [1 for _ in range(N)] )
    
    if guess == 'none' or np.NaN in guess:
        guess = np.array([10*random.random() for _ in range(2*N)])
        
    time_dependencies = []
    
    ps = np.array(range(1, N+1))

    for n in ps:
        time_dependencies.append(
                lambda Amps, n=n : (-gamma[n-1] * Amps[n-1] - (Lambda/(2*n)) * ( KND( ps, V+n,  i*alpha*Amps ) 
                                                                             -   KND( ps, V-n, -i*alpha*conj(Amps) ) )
                                    )
                                )

    flatten = lambda l: [item for sublist in l for item in sublist]
    
    function = lambda Amps: flatten( [ [ np.real(item(Amps[::2] + i*Amps[1::2])), 
                                         np.imag(item(Amps[::2] + i*Amps[1::2])) ] for item in time_dependencies ] )


    solution = fsolve( function, guess )
    
    print( '        Max time deriv: ', np.abs( function(solution) ).max() )
    print( '        ', solution )
    
    trys = 0
    while np.abs( function(solution) ).max() > 1E-8 and trys < 7:
        print('        !This is too high!!!')
        print("        Trying again (Try number " + str(trys+2) + ")")
        guess = [g + 0.25*random.random() for g in guess]
        solution = fsolve( function, guess )
        trys += 1
        #return [np.NaN for _ in solution]
    
    if np.abs( function(solution) ).max() > 1E-8:
        return [np.NaN for _ in solution]
    else:
        return solution


def N_mode_stable( Lambda, ps, split_amp, V,  gamma = 'same', alpha = 'same'):
    # Seems to Work!!!

    N = len(ps)
    
    if gamma == 'same':
        gamma = [1E-3 for _ in range(2*N)]
    if alpha == 'same':
        alpha = np.array( [1 for _ in range(N)] )
    
    Jacob = np.zeros((2*N, 2*N), dtype=np.complex128)
    
    # Drive
    split_amp = np.array(split_amp)
    Amps  = split_amp[::2] + i*split_amp[1::2]
    CAmps = split_amp[::2] - i*split_amp[1::2]
    
    
    for n, p in enumerate(ps):
        # p is the mode being differentiated
        for m, pd in enumerate(ps):
            # m is the mode it is differentiated wrt
            # Diff WRT to ampha[m]
            Jacob[2*n, 2*m]   += (Lambda/(4*p)) * i * ( KND( ps, V+p-pd,  i*alpha* Amps )
                                                    +   KND( ps, V-p+pd, -i*alpha*CAmps ) )
            
            # WRT alpha[m]*
            Jacob[2*n, 2*m+1] += (Lambda/(4*p)) * i * ( KND( ps, V+p+pd,  i*alpha* Amps )
                                                    +   KND( ps, V-p-pd, -i*alpha*CAmps ) )
        
    # odd rows:
    for n in range(N):
        # Conjugate "criss cross" of row above
        Jacob[2*n+1, 1::2] += np.conj( Jacob[2*n,  ::2] )
        Jacob[2*n+1,  ::2] += np.conj( Jacob[2*n, 1::2] )

    # Add Loss (simple!)
    Jacob -= np.diag( gamma )
    
    if np.isfinite(Jacob).all():
        eig_vals, eig_vects = np.linalg.eig(Jacob)
    else:
        print('Non-finite elements!')
        print(Amps)
        print(Jacob)
        return np.nan
    
    return all( np.real(val) < 0 for val in eig_vals)


#
#gamma = 1E-3
#Lambs = np.linspace(0, 0.2, 100)
#sols = [(0,0,0,0)]
#
#for n, Lambda in enumerate( Lambs ):
#
#    alpha_dot  = lambda alpha, beta : -gamma * alpha + (Lambda/2) * ( K2D(1,2,2, i*alpha, i*beta) 
#                                                               - conj(K2D(1,2,0, i*alpha, i*beta)) )
#    
#    beta_dot   = lambda alpha, beta : -gamma * beta  + (Lambda/4) * ( K2D(1,2,3, i*alpha, i*beta) 
#                                                               - conj(K2D(1,2,1, i*alpha, i*beta)) )
#    
#    
#    function = lambda ab:  [ np.real( alpha_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) ), 
#                             np.imag( alpha_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) ), 
#                             np.real(  beta_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) ),
#                             np.imag(  beta_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) )  ]
#    
#    
#    solution = fsolve( function, sols[-1][:4] )
#    
#    stability  = check_stable( Lambda, gamma, 1, 2, solution[0]+i*solution[1], solution[2]+i*solution[3] )
#    
#    sols.append( [ s for s in solution] + [int(stability)])
#    
#    print(n, stability)
#    
#
#sols2 = [(15,10, 12, 8)]
#
#for n, Lambda in enumerate( Lambs[::-1] ):
#    
#    # Different form of the same equations in the other loop.
#    alpha_dot  = lambda alpha, beta : -gamma * alpha + (Lambda/2) * ( K2D(1,2,2,  i*alpha,  i*beta) 
#                                                                  -   K2D(1,2,0, -i*alpha, -i*beta) )
#    
#    beta_dot   = lambda alpha, beta : -gamma * beta  + (Lambda/4) * ( K2D(1,2, 3,  i*alpha,  i*beta) 
#                                                                  -   K2D(1,2,-1, -i*alpha, -i*beta) )
#    
#    
#    function = lambda ab:  [ np.real( alpha_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) ),
#                             np.imag( alpha_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) ),
#                             np.real(  beta_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) ),
#                             np.imag(  beta_dot(ab[0] + i*ab[1], ab[2] + i*ab[3]) )  ]
#    
#    
#    solution = fsolve( function, sols2[-1][:4] )
#    
#    stability  = check_stable( Lambda, gamma, 1, 2, solution[0]+i*solution[1], solution[2]+i*solution[3] )
#    
#    sols2.append( [ s for s in solution] + [int(stability)])
#    
#    print(n, stability)
#
#
#def plot_w_ang( ax, xdata, ydata, c = 'k' ):
#    # A silly way of plotting it... probably not so useful.
#    for x, y in zip(xdata, ydata):
#        t = mpl.markers.MarkerStyle(marker= '>')
#        t._transform = t.get_transform().rotate_deg( np.angle(y) * 360 / (2*np.pi)  )
#        
#        ax.scatter( x, np.abs( y ), marker = t, c = c )
#    
#
#sols  = np.array(sols[1:])
#sols2 = np.array(sols2[1:])
#
#fig, ax = plt.subplots(figsize=(7,5))
#plot_w_ang( ax, Lambs/gamma, sols[:,0] + i*sols[:,1], c = 'k' )
#plot_w_ang( ax, Lambs/gamma, sols[:,2] + i*sols[:,3], c = 'r' )
#
#plot_w_ang( ax, Lambs/gamma, sols2[::-1,0] + i*sols2[::-1,1], c = 'k' )
#plot_w_ang( ax, Lambs/gamma, sols2[::-1,2] + i*sols2[::-1,3], c = 'r' )


def simplify_set( sols, stabs ):
    # Reject copies:
    
    new_sols  = [[] for _ in sols ]
    new_stabs = [[] for _ in stabs]
    
    distance = lambda X:  ((X-s)**2).sum() > 1E-2
    
    # Add old stuff to new stuff, except where it matches one added previously (up to prescision)
    for n, (sol_set, stab_set) in enumerate(zip( sols, stabs )):
        for s, st in zip(sol_set, stab_set):
            
            if all( map( distance, new_sols[n] ) ):
                new_sols[n].append( s )
                new_stabs[n].append( st )
                
    # Pad out the rows that are shorter so the thing can be an array:
    length = max(map(len, new_sols))
    NaNray = np.array( [np.NaN]*4 )
    
    new_sols  = np.array([s + [NaNray] * (length-len(s)) for s in new_sols  ])
    new_stabs = np.array([s + [np.NaN] * (length-len(s)) for s in new_stabs ])  
    
    return new_sols, new_stabs
    

def fuse_sets( sols1, sols2, stabs1, stabs2, lambs1 = False, lambs2 = False):
    
    if lambs1 != lambs2:
        
        lambs1 =  list(lambs1) 
        lambs2 =  list(lambs2)
        
        lambs_out = lambs1 + lambs2
        lambs_out = list(dict.fromkeys(lambs_out))
        
        sols_out = [ [] for _ in lambs_out ]
        stabs_out = [ [] for _ in lambs_out ]
        
        for m, l in enumerate(lambs_out):
            if l in lambs1:
                n = lambs1.index(l)
                for item, item_s in zip(sols1[n,:,:], stabs1[n,:]):
                    sols_out[m].append( item )
                    stabs_out[m].append( item_s )
                    
            if l in lambs2:
                n = lambs2.index(l)
                for item, item_s in zip(sols2[n,:,:], stabs2[n,:]):
                    sols_out[m].append( item )
                    stabs_out[m].append( item_s )
        

        
        length = max(map(len, sols_out))
        NaNray = np.array( [np.NaN]*4 )

        
        sols_out  = np.array([s + [NaNray] * (length-len(s)) for s in sols_out  ])
        stabs_out = np.array([s + [np.NaN] * (length-len(s)) for s in stabs_out ])
        lambs_out = np.array( lambs_out )
        
    else:
        sols_out  = np.concatenate(( sols1, sols2 ), axis=1)
        stabs_out = np.concatenate(( stabs1, stabs2 ), axis=1)
        lambs_out = False
        
    return sols_out, stabs_out, lambs_out


def narrow_down( sols, stabs ):
    # When two intiail conditions arrive at the same point, just keep one instance of that point
    # for efficiency sake.
    distance = lambda S1, S2:  ((S1-S2)**2).sum() > 1E-3
    
    keep_sols = [sols[0]]
    keep_stabs = [stabs[0]]
    
    for item, stab in zip(sols[1:], stabs[1:]):
        distances = [distance(item, s) for s in keep_sols]
        if all(distances):
            keep_sols.append( item )
            keep_stabs.append( stab )
    
    if len(keep_sols) < len(sols):
        print('I narrowed down the number of guesses!')
        print('Old number: ', len(sols))
        print('New: ', len(keep_sols))
    
    return keep_sols, keep_stabs


if __name__ == "__main__" and True:
    

    #Lambs =np.linspace(0, 10, 400) * 1E-3
    
    N = 2
    V = 1
    
    print(N)
    
    Gamma = [1E-3] * N
    # Gamma = [1E-3 * n**2 for n in range(1, N+1)]
    dGamma = np.kron( Gamma, [1, 1] )
    
    
    Delta_1 = 0.5
    #Delta = [Delta_1 / np.sqrt(n) for n in range(1,N+1) ]
    Delta = [Delta_1 / n for n in range(1,N+1) ] # weird Delta relation!!!
    
    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 )
        thresh = 7.75526

    # end if
    
    Lstart = 0 #10 #N * 3
    Lmax   = (N+3) * 6  # 30 # int( thresh * np.exp( +0.5 * sum([d**2 for d in Delta]) ) + 1 )
    L_unnromed = np.linspace(Lstart, Lmax, 101)

    Lambs = [l*Gamma[V-1] for l in L_unnromed]
    
    
    # 9 random starts
    starts = [ [9*random.random()-4.5 for _ in range(2*N)] for _ in range(1) ]

    sols = [ starts ]
    
    
    stabs = [ [np.NAN for _ in starts] ]
    
    
    for num, Lamb in enumerate(Lambs[::-1][1:]):
        print('new Lambda  ' + str(num), '  value:', str(Lamb) )
        new_sols = []
        new_stabs = []
        for guess in sols[-1]:
            print('    new guess')
            new_sols.append( N_mode_fixed_points( N, V, Lambda = Lamb, guess = guess, gamma = dGamma ) )
            new_stabs.append( N_mode_stable( Lamb, [n+1 for n in range(N)], new_sols[-1], V, gamma = dGamma ) )
            print('        stab?:', new_stabs[-1], 'at lambda:', Lamb)
        
        print(new_stabs)
        
        new_sols, new_stabs = narrow_down( new_sols, new_stabs )
        
        sols.append(new_sols)
        stabs.append(new_stabs)
        
        print("Number of sols:" , len(sols), len(stabs) )
    
    attempt_number = "2"
    #g = 'gamma_sqr_'
    #g = "raw_short_"
    g = "Delta_linear_"
    Lambs = Lambs[:-1]
    
    if True:
        # Save!
        np.save( g + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_FPs.npy", sols)
        np.save( g + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_stabss.npy", stabs)
        np.save( g + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_Lambss.npy", Lambs)
    
    
    
    fix_sols = sols[1:]
    fix_stabs = stabs[1:]
    
    # Pad with np.NaN somewhere here.
    pad_sols = []
    pad_stabs = []
    for item, stb in zip(fix_sols, fix_stabs):
        pad_sols.append( list(item) + [[np.NaN] * 2*N ] * (len(starts) - len(item)) )
        pad_stabs.append( list(stb) + [np.NaN] * (len(starts) - len(stabs)) )
    
    fix_sols = np.array(pad_sols[::-1])
    fix_stabs = np.array(pad_stabs[::-1])
    
    
    attempt_number = "2"
    #g = 'gamma_sqr_'
    g = "short_"
    
    if True:
        # Save!
        np.save( g + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_FPs.npy", fix_sols)
        np.save( g + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_stabss.npy", fix_stabs)
        np.save( g + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_Lambss.npy", Lambs)
    
    sols = np.array( fix_sols )
    stabs = np.array( fix_stabs )
    
    Deltas = [0.5, 0.5 / np.sqrt(2)]
    omega_1 = 1
    
    Lambs = np.array(Lambs) 
    
    EJs = Lambs[::-1] / (omega_1 * (4*Deltas[0]**2))
    
    cols = 'rb'
    
    amps = []
    for theset in sols:
        amps.append( [] )
        for n in range(0,sols.shape[1]):
            amps[-1].append( np.sqrt(theset[n,::2]**2 + theset[n,1::2]**2) )
    amps = np.array(amps)
    
    fig, ax = plt.subplots(figsize=(7,5))
    for which in range(1):
        for num in range(0,N):
            ax.plot( Lambs / 1E-3, amps[:, which, num], label=str(num+1) )
            
        #ax.plot( Lambs / 1E-3, stabs[which, :], 'k--', label='Stability' )
        
    for which in range(1):
        for num in range(0,N):
            for n, L in enumerate(Lambs):
                if stabs[n, which] == True:
                    ax.plot( L / 1E-3, amps[n, which, num], cols[num] + 'x' , label=str(num+1) )
                else:
                    ax.plot( L / 1E-3, amps[n, which, num], cols[num] + 'o', label=str(num+1) )
        #ax.plot( Lambs / 1E-3, stabs[which, :], 'k--', label='Stability' )
    ax.legend()
    ax.set_title(r'$\lambda$ units')



def convert_amplitudes( amps, Deltas ):
    
    #return amps / (2*Deltas[1])
    for n in range(len(Deltas)):
        amps[:,:,n] *= 1/ (2 * Deltas[n])
        
    return amps


def make_EJ_plot( sols, stabs, Lambs, Deltas, ax = 'none' , amp_int = "amp" ):
    omega_1 = 1
    EJs = Lambs[::-1] / (omega_1 * (4*Deltas[0]**2))
    
    cols = 'rb'
    
    N = int( sols.shape[2] / 2 )
    
    amps = []
    for theset in sols:
        amps.append( [] )
        for n in range(0,sols.shape[1]):
            amps[-1].append( np.sqrt(theset[n,::2]**2 + theset[n,1::2]**2) )
    amps = np.array(amps)
    
    amps = convert_amplitudes( amps, Deltas )
    
    if amp_int == "int":
        amps = amps**2
    
    if ax == "none":
        fig, ax = plt.subplots(figsize=(7,5))
        
#    for which in range( amps.shape[1] ):
#        for num in range(0,N):
#            ax.plot( EJs[::-1][1:] / 1E-3, amps[1:, which, num], label=str(num+1) )
            
        #ax.plot( Lambs / 1E-3, stabs[which, :], 'k--', label='Stability' )
    
    for which in range(amps.shape[1]):
        for num in range(0,N):
            for m, L in enumerate(EJs[::-1][1:]):
                n = m + 1
                if stabs[n, which] == True:
                    ax.plot( L/ 1E-3, amps[n, which, num], cols[num] + 'x' , label=str(num+1) )
                else:
                    ax.plot( L/ 1E-3, amps[n, which, num], cols[num] + 'o', label=str(num+1) )
        #ax.plot( Lambs / 1E-3, stabs[which, :], 'k--', label='Stability' )
    ax.set_xlabel(r'$E_J / \gamma$')
    
    if amp_int == "amp":
        ax.set_ylabel(r'Amplitude')
    else:
        ax.set_ylabel(r'$n$')
    
    
def make_EJ_plot2( sols, stabs, Lambs, Deltas, ax = 'none', amp_int = "amp", N=2, thresh = None ):
    omega_1 = 1
    EJTs = Lambs / (omega_1 * (4*Deltas[0]**2))
    
    # NOTE! The plot is over EJ_tilde, not EJ!
            
    font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 16}
    mpl.rc('font', **font)
    
    if amp_int == "amp":
        sqrt_maybe = np.sqrt
    else:
        sqrt_maybe = lambda x: x
        
    amps = sqrt_maybe( sols[:,:,::2]**2 + sols[:,:,1::2]**2 )
    
    if amp_int == "amp":
        amps[:,:,0]  *= 1/ (2 * Deltas[0])
        amps[:,:,1]  *= 1/ (2 * Deltas[1])
    else:
        amps[:,:,0]  *= 1/ (2 * Deltas[0])**2
        amps[:,:,1]  *= 1/ (2 * Deltas[1])**2

    stables = amps.copy()
    unstables = amps.copy()
    
    stables[ stabs!= True ] = np.NaN
    unstables[ stabs!= False ] = np.NaN
    
    amps = np.array( amps )
    
    if ax == "none":
        fig, ax = plt.subplots(figsize=(7,5))
    
    if not( thresh ):
        scaling = 1E-3
    else:
        scaling = thresh
    
    cols = ['r', 'b', 'g']
    
    for n in range(stables.shape[2]):    
        ax.plot( EJTs / scaling, stables[:, :,n], cols[n] + '-')
        ax.plot( EJTs / scaling, unstables[:, :,n], cols[n] + '--')
        
    
    ax.set_xlabel(r'$\tilde{E}_J / \gamma$')
    
    if amp_int == "amp":
        ax.set_ylabel(r'Amplitude')
    else:
        ax.set_ylabel(r'$n$')
    
    if not( thresh ):
        ax.set_xlim( [0, 13 / (2*Deltas[0])**2] )
    else:
        ax.set_xlim( [0, (13*1E-3 / (2*Deltas[0])**2) / thresh] )
    ax.set_ylim( [-1E-2, 4 / (2*Deltas[0])] )
    
    #fig.savefig( "fixed_points_Delta0.5_more.pdf", bbox_inches='tight')
    
def make_EJ_plot3( sols, stabs, Lambs, Deltas, ax = 'none', amp_int = "amp", N=2,  ):
    omega_1 = 1
    EJs = Lambs / (omega_1 * (2*Deltas[0])**2 )
    
            
    font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 16}
    mpl.rc('font', **font)
    
    if amp_int == "amp":
        sqrt_maybe = np.sqrt
    else:
        sqrt_maybe = lambda x: x
        
    amps = sqrt_maybe( sols[:,:,::2]**2 + sols[:,:,1::2]**2 )
    
    if amp_int == "amp":
        amps[:,:,0]  *= 1/ (2 * Deltas[0])
        amps[:,:,1]  *= 1/ (2 * Deltas[1])
    else:
        amps[:,:,0]  *= 1/ (2 * Deltas[0])**2
        amps[:,:,1]  *= 1/ (2 * Deltas[1])**2

    stables = amps.copy()
    unstables = amps.copy()
    
    stables[ stabs!= True ] = np.NaN
    unstables[ stabs!= False ] = np.NaN
    
    amps = np.array( amps )
    
    if ax == "none":
        ax = plt.axes(projection='3d')
    
    print( stables.shape )
    for n in range( stables.shape[1]):
        ax.plot(EJs / 1E-3, stables[:, n, 0], 'r-', zdir='z')
        ax.plot(EJs / 1E-3, stables[:, n, 1], 'b-', zdir='y', zs=4)
        ax.plot3D( EJs / 1E-3, stables[:, n, 0], stables[:,n,1], 'k-')
        
    for n in range( unstables.shape[1]):
        ax.plot(EJs / 1E-3, unstables[:, n, 0], 'r--', zdir='z')
        ax.plot(EJs / 1E-3, unstables[:, n, 1], 'b--', zdir='y', zs=4)
        ax.plot3D( EJs / 1E-3, unstables[:,n, 0],  unstables[:, n, 1], 'k--')
    
    ax.set_xlabel(r'$E_J / \gamma$')
    
    if amp_int == "amp":
        ax.set_ylabel(r'Amplitude')
    else:
        ax.set_ylabel(r'$n$')
    
    ax.set_xlim( [0, 13] )
    ax.set_ylim( [-1E-2, 4] )
    
    #fig.savefig( "fixed_points_Delta0.5_more.pdf", bbox_inches='tight')
    

def my_plot():
    
    V = 2
    N = 2
    Deltas = [0.5, 0.5/np.sqrt(2)]
    
        
    direct = "My_Fixed_pt_data/"
    
    attempt_number = "3"
    sols1  = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_FPs.npy")
    stabs1 = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_stabss.npy")
    Lambs1  = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_Lambss.npy")
    
    attempt_number = "3.2"
    sols2  = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_FPs.npy")
    stabs2 = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_stabss.npy")
    
    attempt_number = "3.2_more_Lamb"
    sols3  = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_FPs.npy")
    stabs3 = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_stabss.npy")
    Lambs3 = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_Lambss.npy")
    
    attempt_number = "3.3_more_Lamb"
    sols4  = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_FPs.npy")
    stabs4 = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_stabss.npy")
    
    attempt_number = "3.3"
    sols5  = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_FPs.npy")
    stabs5 = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_stabss.npy")
    Lambs5 = np.load(direct + "V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_Lambss.npy")
    
    sols, stabs, _ = fuse_sets( sols1, sols2, stabs1, stabs2)
    sols, stabs, _ = fuse_sets( sols , sols5, stabs , stabs5, Lambs1, Lambs5 )
    sols_ex, stabs_ex, _ = fuse_sets( sols3, sols4, stabs3, stabs4 )
    
    sols, stabs, Lambs = fuse_sets( sols, sols_ex, stabs, stabs_ex, Lambs1, Lambs3 )
    
    sols, stabs = simplify_set(sols, stabs )
    
    # fig, ax = plt.subplots(figsize=(7,5))
    # make_EJ_plot2( sols, stabs, Lambs, Deltas, ax = ax )
    
    
    fig= plt.figure()
    ax= fig.add_subplot(111, projection= '3d')
    make_EJ_plot3( sols, stabs, Lambs, Deltas, ax = ax )
    

if False:
    # Save!
    np.save("V=" + str(V) + "_N=" + str(N) + "_Attempt=" + attempt_number + "_EJs.npy", EJs[::-1])

