# Quantum Quadratic Eigenvalue Analsis
# Ben Lang May 2021
# A program intended to find the quadratic order quantum solutions in the vicinity of the fixed point


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 scipy.optimize
from scipy.optimize import minimize, minimize_scalar
import functools
from qutip import qeye
from mpmath import mp
import itertools

import sys
#sys.path.append('C:/Users/ppzbjl/Documents/Python Scripts/JJ_Photonics/Plotting_Script_Saves/')
from phase_amp import phase_amp

i = 1j

real = np.real
imag = np.imag
conj = np.conj

# special Bessel thing, JS
Z1D = lambda p, alpha: special.jn( p, np.abs(alpha) ) * np.exp( 1j * p * np.angle(alpha) )


def KND( qs, p, As ):
    # N-dimensional Z-functon as an integral.
    function = lambda t: mp.exp( 
                            sum( [ (A/2) * mp.exp(i*q*t) - (conj(A)/2) * mp.exp(-i*q*t)  for A, q in zip(As, qs)] )
                               -i*p*t
                               )
    
    return np.complex(   mp.quad(function, [-mp.pi, mp.pi]) / (2*mp.pi)   )


def sum_Z( alpha, shift ):
    
    if np.abs(shift - int(shift))<1E-5:
        return  Z1D( shift , alpha ) + Z1D( 2-shift , conj(alpha) )
    else:
        # Not an integer
        print("Error! Shift index should be integer!")
        return 0
    
    
def sum__vec_Z( alpha, q, V, shift ):
    return  KND( q, V + shift, alpha ) + KND( q, V - shift, conj(alpha) )


def all_quads( N ):
    # Returns all quadratic vecots with N modes.
    # (There seem to always be 2*(N**2) + N  elements)
    outs = []
    
    for a in range(2*N):
        for b in range(2*N):
            new = [0] * 2*N
            new[a] = 1
            new[b] += 1
            
            C_vec = np.array(new[:N]) + 1j*np.array(new[N:])
            
            if True not in [np.array_equal(C_vec, item) for item in outs]:
                outs.append( C_vec )
    
    return outs
    

def vec_mod_power( Delta, vec ):
    out = 1
    for D, V in zip(Delta, vec):
        out *= D**(real(V)) * D**(imag(V))
    return out
    

def ab_from_vec( Ham_part ):
    mods = list( real(Ham_part) + imag(Ham_part) )
    
    if 2 in mods:
        n = mods.index(2)
        m = n
    else:
        n = mods.index(1)
        mods[n] += -1
        m = mods.index(1)
    return n, m


##### Define Commutators: #####
def comutator( vec1, vec2, basis ):
    # Does comutators using my odd vector notation.
    
    out = [0 for _ in basis]
    const = 0
    
    # main bit of loop gets everything EXCEPT the terms emerging from 2 of the +1 comuatros meeting
    # For n=2 this means its missing constant terms.
    # Extra "if 1+1j..." catches it
    for n in range(len(vec1)):
        if np.imag(vec1[n]*vec2[n]):
            neg = imag( vec1[n] ) * real( vec2[n] )
            pos = real( vec1[n] ) * imag( vec2[n] )
            
            remvec = list(  np.array(vec1) + np.array(vec2)  )
            remvec[n] += -1 - 1j
            
            matches = [np.array_equal(remvec, item) for item in basis]
            if True in matches:
                index = matches.index(True)
                out[index] += pos - neg
            
            if 1+1j in remvec:
                const += (pos - neg) / 2

    return out, const


def build_matrix( N, V, qd ):
    # This builds a function that outputs the correct matrix given Gamma, Delta and EJ
    # Its built from an array of strings. Each string is the equation for that
    # matrix element.
    # qd seems to just be V again for some reason??? (Resonant mode number)
    
    qs = list( range(1,N+1) )
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
    dot_terms = all_quads(N)
    S = []
    for item in dot_terms:
        
        Bess_index = ( V - np.dot( real(item) - imag(item) , qs ) ) / qd
        
        if Bess_index - int(Bess_index) == 0:
            # An energy conserving move is possible with those operators
            S.append( np.array( list(item) + [Bess_index] ) )
        else:
            S.append( [0] * (N+1) )
    # end for
    
    # Interpret dot terms as follows:
    # [n, m, k+ip] means < a_1^n, a_2^m, a_3^k, (a_3^dag)^p >
    
    ##### Build the Hamiltonian as a list of Strings #####
    Ham_string = ['' for _ in dot_terms]
    
    for num, Ham_part in enumerate(S):
        if imag(Ham_part[-1]):
            print('Something has gone hideously wrong')
        
        if np.array_equal(Ham_part[:-1], [0]*N):
            Ham_string[ num ] = '0'
        else:
            # Multiplier
            Z_index = int(real(Ham_part[-1]))
            Z_bit = ' sum_Z( 2j * Delta[' + str(qd - 1) + '] * alpha, ' + str(Z_index) + ' ) '
            
            a, b = ab_from_vec( Ham_part[:-1] )
            Delta_bit = '-1 * Delta[' + str(a) + '] * Delta[' + str(b) + '] '
            
            # This combinatorial bit falls out naturally in the paper notes.
            # In the Hessian approach this part arrises from the (1/2!) in the
            # Fourier transform. Which is cancelled for "off-diagonal" terms by
            # the repetiition of each term.
            combinatorial_bit = str(1/max( list(real(Ham_part[:-1])) + list(imag(Ham_part[:-1])) ))
            
            text = '(-1j*EJT/2) *' + Delta_bit + '*' + Z_bit + '* ' + combinatorial_bit
    
            Ham_string[ num ] = text
    # end for
    
    ##### finally build the matrix: #####
    matrix = []
    const = ['0'] * len(dot_terms)
    
    for n, x in enumerate( dot_terms ):
        new_row = ['0'] * len(dot_terms)
        
        for Ham_str, Ham_part in zip(Ham_string, S):
            n_part, const_part = comutator( Ham_part[:-1], x, dot_terms )
            
            if const_part:
                const[n] += "+ ( " + str(const_part) + '*' + Ham_str + " ) "
            
            for number, item in enumerate( n_part ):
                if item:
                    new_row[number] += "+ ( " + str(item) + '*' + Ham_str + " ) "
            # end mini-for.
        # end for
        matrix.append( new_row )
    # for for
    
    # Put loss down the matrix diagonal:
    for n, x in enumerate( dot_terms ):
        a, b = ab_from_vec( x )
        matrix[n][n] += '-0.5 * ( Gamma[' + str(a) +'] + Gamma[' + str(b) + '] ) '

    return matrix, const, dot_terms, Ham_string



def build_matrix_general( N, V, slim = False ):
    # This builds a function that outputs the correct matrix given Gamma, Delta and EJ
    # Its built from an array of strings. Each string is the equation for that
    # matrix element.
    # General to any fixed point.
    
    qs = list( range(1,N+1) )
    
    S = all_quads(N)
       
    # Number of modes at multiple of drive:
    Nres = sum( [ (n%V)==0 for n in range(1,N+1) ] )
    
    # reduced qs (inlcuding only modes at multiples of drive)
    red_q = [n for n in range(1, Nres+1)]
    
    # Interpret dot terms as follows:
    # [n, m, k+ip] means < a_1^n, a_2^m, a_3^k, (a_3^dag)^p >
    
    ##### Build the Hamiltonian as a list of Strings #####
    Ham_string = ['' for _ in S]
    
    for num, Ham_part in enumerate(S):
        if np.array_equal(Ham_part, [0]*N):
            Ham_string[ num ] = '0'
        else:
            # Multiplier
            
            Z_shift = int(real(  -1 * np.dot( real(Ham_part) - imag(Ham_part) , qs )  ))
            
            if slim:
                
                if not (Z_shift/V).is_integer():
                    # not an integer
                    Ham_string[ num ] = '0'
                    continue
                
                print('Integer:', (Z_shift/V) )
                
                # Assume Alpha is only over the modes that divide by V.
                # This SHOULD, by default be a Z-function difference with something like
                # q = [3,6,9,12] and V = 3.
                # I divide through by V to simplify/speedup.
                #print( 'Integer? : ', Z_shift/V ) # check this is integer.
                
                Z_bit = ' sum__vec_Z( 2j * Delta[V-1::V] * alpha, ' + str(red_q) + ', 1, ' + str(int( Z_shift/V )) + ' ) '
            else:
                Z_bit = ' sum__vec_Z( 2j * Delta * alpha, qs, V, ' + str(Z_shift) + ' ) '
            # end if
            
            a, b = ab_from_vec( Ham_part )
            Delta_bit = '-1 * Delta[' + str(a) + '] * Delta[' + str(b) + '] '
            
            # This combinatorial bit falls out naturally in the paper notes.
            # In the Hessian approach this part arrises from the (1/2!) in the
            # Fourier transform. Which is cancelled for "off-diagonal" terms by
            # the repetiition of each term.
            combinatorial_bit = str(1/max( list(real(Ham_part)) + list(imag(Ham_part)) ))
            
            text = '(-1j*EJT/2) *' + Delta_bit + '*' + Z_bit + '* ' + combinatorial_bit
    
            Ham_string[ num ] = text
    # end for
    
    ##### finally build the matrix: #####
    matrix = []
    const = ['0'] * len(S)
    
    for n, x in enumerate( S ):
        new_row = ['0'] * len(S)
        
        for Ham_str, Ham_part in zip(Ham_string, S):
            n_part, const_part = comutator( Ham_part, x, S )
            
            if const_part:
                const[n] += "+ ( " + str(const_part) + '*' + Ham_str + " ) "
            
            for number, item in enumerate( n_part ):
                if item:
                    new_row[number] += "+ ( " + str(item) + '*' + Ham_str + " ) "
            # end mini-for.
        # end for
        matrix.append( new_row )
    # for for
    
    # Put loss down the matrix diagonal:
    for n, x in enumerate( S ):
        a, b = ab_from_vec( x )
        matrix[n][n] += '-0.5 * ( Gamma[' + str(a) +'] + Gamma[' + str(b) + '] ) '

    return matrix, const, S, Ham_string

### end experimental


def solve_built_matrix( matrix, const, alpha, Delta, EJT, Gamma, qs = None, V=2 ):
    
    if not(qs):
        qs = [item for item in range(len(Delta))]

    ## TO DO:
    #   This bit with eval can be very slow. Because each Z-function is a high-dimensional
    #   integral and it carries out each integration loads of seperate times (the same z-function typically
    #   appears in the matrix many times).
    new_mat = []
    for row in matrix:
        new_mat.append([])
        for item in row:
            new_mat[-1].append( eval( item ) )
    # end fors
    
    new_const = []
    for item in const:
        new_const.append( eval(item) )
    # end for
    
    new_mat   = np.array(new_mat, dtype=np.complex128 )
    new_const = np.array(new_const, dtype=np.complex128 )
    
    # Clear away negligable elements:
    new_mat[np.abs(new_mat) < 1E-10] == 0
    new_const[np.abs(new_const) < 1E-10] == 0
    
    Vec = np.linalg.solve( new_mat, -1*new_const )
    print("Solution works?:", np.allclose(np.dot(new_mat, Vec), -1*new_const))
    
    return Vec
    

def vec_2_ops( c_vector, a_ops ):
    # Turn a C_vec into a QUTIP operator. Useful for QUTIP comparisons.
    out = qeye( a_ops[0].dims[0] )
    
    for val, op in zip(c_vector, a_ops):
        out *= op.dag()**( int(imag(val)) ) * op**( int(real(val)) )
    
    return out
    

def vec_to_string( vec ):
    # Turn a c_vec into a readable string describing the operator.
    string = ''
    
    def mystr( number ):
        number = int(number)
        if number == 1:
            return ""
        else:
            return str(number)
    
    for n, item in enumerate(vec):
        if imag(item): string += r"$(a_{" + str(n+1) + r"}^{\dagger})^{ " + mystr(imag(item)) + r" }$"
        if real(item): string += r"$a_{" + str(n+1) + r"}^{ " + mystr(real(item)) + r" }$"
        
    return string


def get_op( C_vecs, search, vals ):
    
    matches = [np.array_equal(item, search) for item in C_vecs]
    
    if True in matches:
        ind = matches.index( True )
        return vals[ind]
        
    else:
        print("Possible Error. Can't find", search)
        return 0
    
def covariance_form( C_vecs, vals, displacements = None, nmodes = 3 ):
    # Organise the quadratic moments into the form of a Covariance matrix.
    # If displacements are provided they are used. If not assumed zero.
    
    # Some properties of the Covariance Matrix:
    # (1) Its 1/sqrt(determinant) is the purity of the state.
    # (2) Its eigenvector with smallest eigenvalue is the direction
    # of most squeezing. That eigenvalue the squeezing. (1/2 for classical)
    
    if not displacements:
        displacements = [0 for _ in range(nmodes)]
    
    # Build the matrix in 2 by 2 blocks:
    mat = np.eye(2*nmodes, dtype=complex)
    
    for n in range(0, nmodes):
        an_v  = np.zeros((nmodes), dtype=complex)
        an_dv = np.zeros((nmodes), dtype=complex)
        
        an_v[n] = 1
        an_dv[n] = 1j
        
        dispn = displacements[n]
        
        for m in range(0, nmodes):
            am_v  = np.zeros((nmodes), dtype=complex)
            am_dv = np.zeros((nmodes), dtype=complex)
            
            am_v[m] = 1
            am_dv[m] = 1j
            
            dispm = displacements[m]
            
            an_am   = get_op( C_vecs, an_v  + am_v  , vals )
            and_amd = get_op( C_vecs, an_dv + am_dv , vals )
            and_am  = get_op( C_vecs, an_dv + am_v  , vals )
            an_amd  = get_op( C_vecs, an_v  + am_dv , vals )
            
            mat[2*n,2*m]     +=  and_am + an_amd + an_am + and_amd             -  real(dispn) * real(dispm)
            mat[2*n,2*m+1]   +=  1j * ( and_amd + an_amd - an_am - and_am )    -  imag(dispn) * imag(dispm)
            mat[2*n+1,2*m]   +=  1j * ( and_amd + and_am - an_am - an_amd )    -  imag(dispn) * real(dispm)
            mat[2*n+1,2*m+1] +=  and_am + an_amd - an_am - and_amd             -  real(dispn) * imag(dispm)
    # end both fors.
    Omega = np.kron( np.eye(nmodes), np.array([[0, 1], [-1, 0]]) )    
    test_eigs, _ = np.linalg.eig( 1j * np.matmul( Omega,  mat ) )
    
    if min( np.abs(test_eigs) ) < 1:
        print('Covariance Matrix is unphysical!', min(np.abs(test_eigs)) - 1 )
    
    return mat
            

def Guassian_Entanglement( Covmat, mode_number, get_eigs = False ):
    # Find the entanglement between mode number mode_number, and the others.
    # Returns the log-negativity, which estiamtes the entanglement.
    # When multiple modes are provided uses the partition {mode_numers} : {rest}
    # in this case a non-zero log-negativity is SUFFICIENT to show entanglement
    # but it is not NESSESARY. (So some entangled states might be missed)
    
    # In the case where 1 mode is provided it is SUFFICIENT and NESSESARY,
    # so will not miss anything. In this case also the actual value of the 
    # log negativity is meaningful. Not just whether or not it is >0.
    
    if not type(mode_number) == list:
        mode_numbers = [ mode_number ]
    else:
        mode_numbers = mode_number
    # end if
    
    n_modes = int( Covmat.shape[0]/2 )
    
    mul = np.ones( Covmat.shape[0] )
    for mode_number in mode_numbers:
        # Flip the sign of all rows/collums involving momentum of mode_number.
        mul[2*mode_number+1] = -1
    
    newmat = np.matmul( np.diag(mul), np.matmul( Covmat,  np.diag(mul) ) )
    
    # Find Symplectic Eigenvalues
    # These are the eigenvalues of:  i * Omega * newmat
    # Omega is Symplectic:
    Omega = np.kron( np.eye(n_modes), np.array([[0, 1], [-1, 0]]) )
    
    
    eig_vals, eig_vects = np.linalg.eig( 1j * np.matmul( Omega, newmat ) )
    eig_vals = real(eig_vals)
    
    # Symplectic eigenvalues less than 1 are indicators of entanglement.
    #print('vals', np.real(eig_vals))
     
    # Eigenvalues comes in pairs, +V and -V. Taking only the +Vs
    neg_eigs = [eig for eig in eig_vals if eig>0 ]
    
    print(neg_eigs)
       
    if not get_eigs:
        # and only those of modulus less than 1.
        neg_eigs = [eig for eig in neg_eigs if eig<1 ]
        return -1*sum( np.log( neg_eigs ) )
    else:
        return neg_eigs


def Partial_Guassian_Entanglement( Covmat, mode_numbers, keep_modes ):
    # Entanglement, but include only some modes.
    if not type(mode_numbers) == list:
        mode_numbers = [mode_numbers]
    # end if
    
    if not all(elem in keep_modes  for elem in mode_numbers):
        print('This makes no sense.')
        return np.NaN
    
    n_modes = int( Covmat.shape[0]/2 )
    delete_modes = [number for number in range(n_modes) if number not in keep_modes ]
    
    destroy_rowcols = [ [2*n, 2*n+1] for n in delete_modes ]
    destroy_rowcols = [item for sublist in destroy_rowcols for item in sublist] # flatten
    
    # Eliminate the rows/collumns of the unusued modes
    Covmat = np.delete( Covmat, destroy_rowcols, axis=0)
    Covmat = np.delete( Covmat, destroy_rowcols, axis=1)
    
    return Guassian_Entanglement( Covmat, [keep_modes.index( mode_number ) for mode_number in mode_numbers] )
    


def all_bipartitions( N ):
    # Generates lits for all birpartitions of N modes.
    # Lists include some set of modes. The excluded modes are 
    # the other side of the partition.
    
    out = []
    
    max_size = int(N / 2)
    mode_list = [item for item in range(N)]
    
    for list_size in range(1, max_size+1):
        # Get all possible combinations of length list size.
        
        if not list_size == N / 2:
            # The normal case
            for subset in itertools.combinations( mode_list , list_size):
                out.append( subset )
        else:
            # list_size = N/2 means that eg. [0], and [1] represent the same
            # partition of the modes [0, 1].
            # Take the combinations involving mode "0".
            # This will be half of them, and is garanteed to avoid "mirrors".
            
            for subset in itertools.combinations( mode_list , list_size):
                if 0 in subset:
                    out.append( subset )
            
    return out


def partial_fully_seperable( mode_group, covmat ):
    # Provided a covmat this consideres the subset of modes given my mode group.
    # It checks if their is full inseperability within that group of modes.
    
    # It further calculates a generalisation of the so-called "tripartite negativity"
    # which in a rough sense gives an idea of how much inseperability their is.
    Negs = []
    
    for bip in all_bipartitions( len(mode_group )):
        use_bip = [ mode_group[k] for k in bip ]
        Negs.append( Partial_Guassian_Entanglement( covmat, use_bip, mode_group ) )
    
    ## check they are all greater than zero.
    #return all([N > 1E-4 for N in Negs])
    
    # Multiply all Negs, and then put to the power (1/#of neges)
    output = 1
    for N in Negs:
        output *= N
    output = output**( 1 / len(Negs) )
    
    return output # should be zero for less than fully inseperable states.


def partial_squeezing( Covmat, keep_modes ):
    # Squeezing, but inlcuding only some modes.
    
    n_modes = int( Covmat.shape[0]/2 )
    delete_modes = [number for number in range(n_modes) if number not in keep_modes ]
    
    destroy_rowcols = [ [2*n, 2*n+1] for n in delete_modes ]
    destroy_rowcols = [item for sublist in destroy_rowcols for item in sublist] # flatten
    
    # Eliminate the rows/collumns of the unusued modes
    Covmat = np.delete( Covmat, destroy_rowcols, axis=0)
    Covmat = np.delete( Covmat, destroy_rowcols, axis=1)
    
    eig_vals, _ = np.linalg.eig( Covmat )
    eig_vals = real(eig_vals)

    return 0.5 * min(eig_vals)
    


# A Note on Factors of 2
#   In both the stability_matrix and the Hessian there are NO special factors
#   of 2 in front of some of the terms. The Hessian (Ham_mat) has a global factor 
#   of 1/2 relative to the stabilitiy Jacobian (in its Hamiltonian parts). 
# However when either matrix representation is "flattened" into a list some 
# parts need a factor of 1/2 relative to others to reflect the fact that all 
# off-diagonals appear twice. When the matrix representations are generated (below)
# from this flattened list factor of 2 stuff needs doing.

def find_stability_matrix( H_str, C_vecs, n_modes = 3 ):
    # Turn a Hamiltonian String into a stability matrix (string):
    
    Mat = [['0' for _ in range(n_modes*2)] for _ in range(n_modes*2)]
    
    for n in range(0, 2*n_modes):
        for m in range(0, 2*n_modes):
            new = [0] * 2*n_modes
            
            # The Eq O M for alpha_n is given by diffentiation wrt alpha_n^*
            if n%2==0:
                n_op = n + 1
                mul = +1
            else:
                n_op = n - 1
                mul = -1
                
            new[ n_op ] = 1
            
            # However the derivatives for stability are "normal", acting on each mode with the derivative wrt itself
            new[m] += 1
            this_vec = np.array(new[::2]) + 1j*np.array(new[1::2])

            Mat[n][m] = str(mul) + " * " + get_op( C_vecs, this_vec, H_str )

            if n_op==m:
                # Extra factor of 2 from second derivative
                Mat[n][m] += " * 2"
            #end if
            if n==m:
                # And dissipation:
                Mat[n][m] += " - 0.5 * Gamma[" + str( int(n/2) ) + "]"
            # end if
        # end
    #end

    return Mat

def find_Hamiltonian_matrix( H_str, C_vecs, n_modes = 3, stab_matrix = True ):
    # Turn a Hamiltonian String into a Hamiltonain matrix (string):
    # WARNING!! This function is exactly close enough to find_stability_matrix to be 
    # maximally confusing. They are very similar, but are NOT the same in purpose, function
    # and output.
    # The stability matrix involves derivatives (factors of 2) and loss, for example.
    
    Mat = [['0' for _ in range(n_modes*2)] for _ in range(n_modes*2)]
    
    for n in range(0, 2*n_modes):
        for m in range(0, 2*n_modes):
            new = [0] * 2*n_modes
            
            if n%2==0:
                n_op = n + 1
            else:
                n_op = n - 1
                
            new[ n_op ] = 1
            new[m] += 1
            
            this_vec = np.array(new[::2]) + 1j*np.array(new[1::2])

            # H_str already includs the -i factor multiplying the Hamiltonain in the eom
            # so multiply by i to cancel that.
            Mat[n][m] = " 1j * " + get_op( C_vecs, this_vec, H_str )
            
            # Each term appears twice, so half them (unless they are already halved)
            # (This is the 1/2! appearing in Fourier Transform)
            if not n_op==m:
                Mat[n][m] += " * 1/2"
            #end if
        # end for
    #end for

    return Mat


def set_phase( eigenvec ):
    # Sets global phase of eigenvec to make the first non-zero element real.
    # (arbitary convenction, but ensures consistency)
    
    nonzero = [ np.abs(e) > 1E-10 for e in eigenvec ]
    first_nz = nonzero.index(True)
    
    return eigenvec * np.exp( -1j* np.angle( eigenvec[first_nz] ) )
    

def solve_stab_matrix( stab_mat, alpha, Delta, EJT, Gamma, qs = None, V=2, give_vecs = False ):
    # Can take a stability matrix, or a Hamiltonian Matrix, to solve.
    
    if not(qs):
        qs = [item for item in range(len(Delta))]
    
    new_mat = []
    for row in stab_mat:
        new_mat.append([])
        for item in row:
            new_mat[-1].append( eval( item ) )
    # end fors
    new_mat   = np.array(new_mat, dtype=np.complex128 )
    
    eig_vals, eig_vects = np.linalg.eig(new_mat)
    
    if give_vecs:    
        # Use Gram Schmidt to make the eigenvecotrs ortho-normal
        eig_vects = eig_vects.transpose()
        vec_list = list(eig_vects)
    
        out_list = [ set_phase(vec_list[0]) ]
        
        in_prod = lambda a, b: np.dot( a.conj(), b )
        
        for item in vec_list[1:]:
            new_item =   item  - sum( [ other * in_prod(other, item) for other in out_list] )
            
            # Normalise
            new_item = new_item / np.sqrt( in_prod( new_item, new_item ) )
            
            out_list.append( set_phase(new_item) )
        # end for

        return out_list, eig_vals
    else:
        return not all(eig_vals < 0 )


def veiw_H_stab_mat( stab_mat, alpha, Delta, EJT, Gamma = None, qs = None, V=2, plot= True ):
    Delta = np.array(Delta)
    
    # Veiw Hamiltoniain Part of Stability matrix
    if not(qs):
        qs = [item for item in range(len(Delta))]
    
    if not(Gamma):
        Gamma = [1E-2 for item in range(len(Delta)) ]
    
    new_mat = []
    for row in stab_mat:
        new_mat.append([])
        for item in row:
            new_mat[-1].append( eval( item ) )
    # end fors
    new_mat   = np.array(new_mat, dtype=np.complex128 )
    
    #fig, ax = plt.subplots(figsize=(4,4))
    #ax.pcolormesh( np.linspace(0, 2*len(Delta), 2*len(Delta)), np.linspace(0, 2*len(Delta), 2*len(Delta)), new_mat )
    #ax.spy( new_mat )
    if plot:
        phase_amp( new_mat , np.linspace(0, 2*len(Delta), 2*len(Delta)) )

    return new_mat

def extract_k_group( group, mat, full = True ):
    # Extract the submatrix described by group from the mat
    # Use partial to only get part of it (one set of modes only create, others only destroy)
    
    if full:
        use_mat = [['' for _ in range(len(group)*2)] for _ in range(len(group)*2)]
    else:
        use_mat = [['' for _ in range(len(group))] for _ in range(len(group))]

    for n1, g1 in enumerate(group):
        for n2, g2 in enumerate(group):
            if full:
                use_mat[ 2*n1   ][ 2*n2   ] = mat[ 2*(g1-1)   ][ 2*(g2-1)   ]
                use_mat[ 2*n1   ][ 2*n2+1 ] = mat[ 2*(g1-1)   ][ 2*(g2-1)+1 ]
                use_mat[ 2*n1+1 ][ 2*n2   ] = mat[ 2*(g1-1)+1 ][ 2*(g2-1)   ]
                use_mat[ 2*n1+1 ][ 2*n2+1 ] = mat[ 2*(g1-1)+1 ][ 2*(g2-1)+1 ]
            else:
                use_mat[ n1 ][ n2 ] = mat[ 2*(g1-1) + (n1%2) ][ 2*(g2-1) + (n2%2) ]
            # end if
    # end both fors
            
    return use_mat

cos = np.cos
sin = np.sin

def cov_rotate( theta_vec, cov_in ):

    R_list = [ np.array( [[cos(theta),  -1* sin(theta)],
                          [sin(theta),      cos(theta)]]) for theta in theta_vec ]


    # kronecker sum of rotations
    R = scipy.linalg.block_diag( *R_list )
    
    return np.matmul( np.matmul( R, cov_in), R.transpose() )
    

def rotate_away_off_diags( cov_in ):
    N = int(cov_in.shape[0]/2)
    
    theta_vec = []
    
    for num in range(N):
        X = cov_in[2*num    , 2*num    ]
        Z = cov_in[2*num + 1, 2*num + 1]
        Y = 0.5 * ( cov_in[2*num + 1, 2*num] + cov_in[2*num, 2*num+1] )
        
        if np.abs(Y) < 1E-15:
            theta_vec.append( 0 )
        elif (Z-X) == 0:
            theta_vec.append(np.pi / 4)
        else:
            theta_vec.append( 0.5 * np.arctan( 2 * Y / (Z-X) ) )
    
    cov = cov_rotate( theta_vec, cov_in )
    
    # Values of theta generated thus far will make the diagonal blocks nice
    # to make the other blocks nice need extra angles.
    # Have freedom to add units of np.pi/2 to the existing angles without damamging diagonals.
    # (Also, if the main-diag blocks each looks like a scaled I matrix then I don't have to worry
    # about damaing the main diagonal)
    
    # Experiments sugges the phase [(n-3)*np.pi/4 for n in range(5)] works for V=2, N=5 data.
    abs_c = np.abs(cov)
    flip_mat = []
    for num1 in range(N):
        flip_mat.append( [] )
        for num2 in range(N):
            flip_mat[-1].append( abs_c[2*num1, 2*num2] + abs_c[2*num1+1, 2*num2+1] - abs_c[2*num1+1, 2*num2] - abs_c[2*num1, 2*num2+1] )
    # end both fors
    flip_mat = np.array(flip_mat)
    np.fill_diagonal( flip_mat, 0 )
    
    sign_vec = np.ones(N)
    #sign_vec = [-1, -1, +1, +1, +1, +1, -1, -1, -1, -1]
    try_num = 0
    
    while ( np.outer( sign_vec, sign_vec ) * flip_mat).min() < 0:
        try_num += 1
        sign_vec = np.ones(N)
        
        for n, item in enumerate(bin(try_num)[2:]):
            if item=='1':
                sign_vec[n] = -1
        
    # end while
    theta_vec2 = [0 for _ in range(N)]
    
    for n, item in enumerate(bin(try_num)[2:]):
        if item=='1':
            theta_vec2[n] = np.pi/2
    
    return cov_rotate( theta_vec2, cov )
    

##### Genuine N partite entanglement

from scipy.optimize import minimize
from scipy.optimize import differential_evolution

def gen_N_partite( cov, tryhard ):
    N = int(cov.shape[0]/2)
    
    
    cov_xx = np.real( cov[0::2, 0::2] )
    cov_pp = np.real( cov[1::2, 1::2] )
    
    # The optimise is bad at solving the full general optimisation problem.
    # Artificially limiting its options actually makes it more powerful as a result.
    # limit options as done in PR. App 10, 044019 (2018)
    
    # These only work for N=3
    
    # if N==3:
        
    #     def optimiser_goal_lim1(hv, gv, cov_xx, cov_pp ):
            
    #         h = np.array( [1, hv, hv])
    #         g = np.array( [1, gv, gv])
            
    #         du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
    #         dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
        
    #         return  du_sqr + dv_sqr - 2
        
    #     combined_goal_lim1 = lambda x, cov_xx, cov_pp: optimiser_goal_lim1(x[0], x[1], cov_xx, cov_pp) 
        
    #     # Need to restribt to gv * hv < 0
        
    #     result = minimize( combined_goal_lim1, np.ones(2), args = (cov_xx, cov_pp), bounds = [(-1,+1),(-1,+1)] )
        
    #     if result.fun < 0 and np.prod( result.x ) < 0:
    #         return True, 1, result.x
    
    #     def optimiser_goal_lim2(hv, gv, cov_xx, cov_pp ):
            
    #         h = np.array( [1, hv, -gv])
    #         g = np.array( [1, gv, -hv])
            
    #         du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
    #         dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
        
    #         return  du_sqr + dv_sqr - 2
            
        
    #     combined_goal_lim2 = lambda x, cov_xx, cov_pp: optimiser_goal_lim2(x[0], x[1], cov_xx, cov_pp) 
        
    #     result = minimize( combined_goal_lim1, np.ones(2), args = (cov_xx, cov_pp), bounds = [(-1,+1),(-1,+1)])
        
    #     if result.fun < 0:
    #         return True, 2
    # # end if N==3
    
    if N==4:
        # From PRA 90 062337, supposedly a good 4 partite one:
        def optimiser_goal_lim3(v, cov_xx, cov_pp ):
            
            h = np.array( [1, +v, +v, +v])
            g = np.array( [1, -v, -v, -v])
            
            du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
            dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
        
            return  du_sqr + dv_sqr - 2 * (1 - v**2)
        
        result = minimize( optimiser_goal_lim3, np.ones(1), args = (cov_xx, cov_pp) )
        # minimize_scalar
        
        if result.fun < 0:
            return True, 3
    # end if N==4
    
    # Try it the fully general way (this seems solver dependent)
    # Note. Multiplying the test vectors h, g through by a constant factor cannot change the negative/positivness.
    # Consider a limitation such that |g|+|h| = 1 or something.
    bips = all_bipartitions(N)
    
    def sbs_find(h, g):
        Sbs = []
        for partition in bips:
            Sbs.append(  
                  np.abs( sum( [ g[i]*h[i] for i in partition ] ) )
              +   np.abs( sum( [ g[i]*h[i] for i in range(N) if i not in partition ] ) )
                )
        return np.min(Sbs)
    
    def optimiser_goal(h, g, cov_xx, cov_pp ):
    
        du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
        dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
        
        return  du_sqr + dv_sqr - 2 * sbs_find( g, h )
        
    
    combined_goal = lambda x, cov_xx, cov_pp: optimiser_goal(x[:N], x[N:], cov_xx, cov_pp) 
    
    # special approach for N=4 given in PRA 90 062337 implies a good start guess is:
    # (and the N=3 guesses also imply this is a good start point)
    
    guess = np.array(  [1] * (N+1) +  [-1] * (N-1)  )
    
    if N==3:
        # These vecs have worked in the past
        clean_vecs = [ [ 1.46930263, -2.93126726, -1.72300383, -1.15996177, -1.90392543,  0.99146518],
                       [-0.44191988,  0.77557979,  0.43008805, -0.45875174, -0.81837747,  0.47137207],
                       [ -0.125, 0.25, 0.125, 0.125, 0.25, -0.125],
                       [-0.6955002,   0.30675263,  0.30675263, -0.6955002,  -0.30675263, -0.30675263],
                       [1.25666167, -0.48625156, -0.48591705,  1.2571428,   0.48625564,  0.48659038],
                       [-0.417,  1, -0.42, -0.42, -1,-0.417], # simpler version of one bellow. Just as good.
                       [-0.41740361,  1, -0.42064997, -0.41940128, -1,-0.41615701], 
                       [ 1, -0.37,  0.37, -1, -0.37, 0.37],# simpler version of one bellow. Just as good.
                       [ 1, -0.36608943,  0.37513097, -1.00591715, -0.38094551, 0.37176289],
                       [-1,  1.77,  0.9,  0.9,  1.77 ,  -1],
                       [-0.98884899,  1.74489539,  0.89654641,  0.88381408,  1.7663834 ,  -0.97480564],
                       [-0.3,  0.47,  0.27,  0.26,  0.46, -0.28 ],
                       [-0.6, 0.1, 0.6, 0.6, 1, -0.6],
                       [-0.2, 0.3, 0.2, -0.2, -0.3, 0.2],
                       [0.61, -1, -0.61, -0.61, -1, 0.61],
                       # From here on they are for the quadratically increasing loss
                       [-1, +1, 153, -1, 1, -153],
                       [1, 1.333, -212, 1.8, 1.36, 212],
                       [-1, 0.7, 213, -0.5, 0.7, -213]]
    elif N==4:
        clean_vecs = [[ -1, +1, +1, +1, +1, -1, -1, -1] ]
    else:
        clean_vecs = []
    # end if
    
    for clean_vec in clean_vecs:
        if combined_goal(clean_vec, cov_xx, cov_pp) < -1e-14:
            print( True, 0, clean_vec, combined_goal(clean_vec, cov_xx, cov_pp))
            return True, 0, clean_vec, combined_goal(clean_vec, cov_xx, cov_pp)
    
    # The vecs that worked in the past give my some idea of things to try.
    # I think a fairly large battery can be tried much cheaper than an optimisation attempt
    
    #### Does NOT WORK. Too many options to spin through if I want a reasonable resoltion. 
    # # Each entry can be anywhere between -1 and +1, and have a modulus of 1/6, 2/6, 3/6 ...
    # poss_vals = [ (item-3)/3 for item in range(0,7) ]
    # poss_vals = [ (item-1) for item in range(0,3) ]
    
    # print("N = ", N)
    # for vec in list( itertools.product( [1] , *[poss_vals]*(2*N - 1) ) ):
    #     # Multiplation of the whole vector by a constant changes nothing, ideally skip those ones.
    #     if combined_goal(vec, cov_xx, cov_pp) < 0:
    #         print( True, 0, vec, combined_goal(vec, cov_xx, cov_pp))
    #         return True, 0, vec, combined_goal(vec, cov_xx, cov_pp)
    
            
    for solver in [ 'Nelder-Mead', 'Powell', 'trust-constr']:
        result = minimize( combined_goal, guess, args = (cov_xx, cov_pp), method = solver )
        #result = minimize_scalar( combined_goal, guess, args = (cov_xx, cov_pp), method = solver )
        
        if result.fun < -1e-14:
            print( True, solver, "\n", result.x, ",   ", result.fun , "\n")
            return True, solver, result.x, result.fun
    # end for
    
    # Try the differential thingy form the other paper: differential_evolution
    # Differential evolution is slow, only use it if "tryhard" is true.
    if tryhard:
        combined_goal_single_input = lambda x: optimiser_goal(x[:N], x[N:], cov_xx, cov_pp)
        sol = differential_evolution( combined_goal_single_input, [(-1, +1)]*2*N )
        
        if sol.fun < -1e-14 :
            print( True, "differential_evo", "\n", sol.x, ",   ", sol.fun , "\n")
            return True, "differential_evo", sol.x, sol.fun
    
    return False # All approaches found no entanglement.



def gen_N_partite_mul( cov ):
    N = int(cov.shape[0]/2)
    
    cov_xx = np.real( cov[0::2, 0::2] )
    cov_pp = np.real( cov[1::2, 1::2] )
    
    
    # Try it the fully general way (this seems solver dependent)
    # Note. Multiplying the test vectors h, g through by a constant factor cannot change the negative/posivness.
    # Consider a limitation such that |g|+|h| = 1 or something.
    bips = all_bipartitions(N)
    
    def sbs_find(h, g):
        Sbs = []
        for partition in bips:
            Sbs.append(  
                  np.abs( sum( [ g[i]*h[i] for i in partition ] ) )
              +   np.abs( sum( [ g[i]*h[i] for i in range(N) if i not in partition ] ) )
                )
        return np.min(Sbs)
    
    def optimiser_goal(h, g, cov_xx, cov_pp ):
    
        du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
        dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
        
        return  ( du_sqr + dv_sqr )  / ( 2 * sbs_find( g, h ) )
        
    
    combined_goal = lambda x, cov_xx, cov_pp: optimiser_goal(x[:N], x[N:], cov_xx, cov_pp) 
    
    # special approach for N=4 given in PRA 90 062337 implies a good start guess is:
    # (and the N=3 guesses also imply this is a good start point)
    
    guess = np.array(  [1] * (N+1) +  [-1] * (N-1)  )
    
    for solver in [ 'Nelder-Mead', 'Powell', 'trust-constr']:
        result = minimize( combined_goal, guess, args = (cov_xx, cov_pp), method = solver )
        
        if result.fun < 1:
            print( True, solver, "\n", result.x, "\n")
            return True, solver
    # end for
    
    return False # All approaches found no entanglement.



def angs_to_vec( angles ):
    # Converts N-1 angles into an N dimesnional unit-vector.
    
    output = [1]
    
    for angle in angles:
        output = [np.sin(angle)] + [item * np.cos(angle) for item in output]
    
    return np.array(output)


def gen_N_partite_angles( cov ):
    N = int(cov.shape[0]/2)
    
    
    cov_xx = np.real( cov[0::2, 0::2] )
    cov_pp = np.real( cov[1::2, 1::2] )
    

    # Try it the fully general way (this seems solver dependent)
    # Note. Multiplying the test vectors h, g through by a constant factor cannot change the negative/positivness.
    # So I impose a limitation such that |kron(g,h)| = 1

    # This is done by providing 2*N-1 angles, that determien the unit kron(g,h) vector.

    bips = all_bipartitions(N)
    
    def sbs_find(h, g):
        Sbs = []
        for partition in bips:
            Sbs.append(  
                  np.abs( sum( [ g[i]*h[i] for i in partition ] ) )
              +   np.abs( sum( [ g[i]*h[i] for i in range(N) if i not in partition ] ) )
                )
        return np.min(Sbs)
    
    def optimiser_goal(angles, cov_xx, cov_pp ):
        
        h_g = angs_to_vec(angles)
        h = h_g[0::2]
        g = h_g[1::2]
        
        du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
        dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
        
        return  du_sqr + dv_sqr - 2 * sbs_find( g, h )
        
    
    combined_goal = lambda angles, cov_xx, cov_pp: optimiser_goal(angles, cov_xx, cov_pp) 
    
    # special approach for N=4 given in PRA 90 062337 implies a good start guess is:
    # (and the N=3 guesses also imply this is a good start point)
    
    for solver in [ 'Nelder-Mead', 'Powell', 'trust-constr']:
        guess = [(r -0.5) * 4*np.pi / (n+1) for n, r in enumerate( np.random.random(2*N - 1) )]
        result = minimize( combined_goal, guess, args = (cov_xx, cov_pp), method = solver )
        
        print(result.fun, result.x)
        print(">>>break")
        if result.fun < 0:
            print( True, solver, "\n", result.x, "\n")
            return True, solver, result.x
    # end for
    return False # All approaches found no entanglement.





guess_library = [ [1] * (N+1) +  [-1] * (N-1) for N in range(3,5) ]

# From optimisations:
guess_library.append( [-0.29339028,  0.52366081,  0.28288565, -0.27028984, -0.50644771,  0.28032673] )
guess_library.append( [-0.50833692,  0.89953106,  0.50612923,  0.511694,    0.90867395, -0.51392592] )

# From gaussian random
guess_library.append([ 1.24989697, -0.52154232, -0.60639123,  1.55112726,  0.81443839, 0.64119465] )
guess_library.append([-1.24766777,  0.83258646,  1.03930695, -1.64514096, -1.2811386 , -0.69891964] )

def gen_N_partite_randsearch( cov ):
    N = int(cov.shape[0]/2)
    
    global guess_library
    cov_xx = np.real( cov[0::2, 0::2] )
    cov_pp = np.real( cov[1::2, 1::2] )

    bips = all_bipartitions(N)
    
    def optimiser_goal(h, g, cov_xx, cov_pp ):
    
        du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
        dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
    
        Sbs = []
        for partition in bips:
            Sbs.append(  
                  np.abs( sum( [ g[i]*h[i] for i in partition ] ) )
              +   np.abs( sum( [ g[i]*h[i] for i in range(N) if i not in partition ] ) )
                )
    
        return  du_sqr + dv_sqr - 2 * np.min(Sbs)
        
    
    combined_goal = lambda x, cov_xx, cov_pp: optimiser_goal(x[:N], x[N:], cov_xx, cov_pp) 
    
    tries = 0
    
    # for item in guess_library:
    #     if len(item) == 2*N:
    #         if combined_goal(item, cov_xx, cov_pp) < 0:
    #             print("library value works")
    #             return True
    
    while tries < 20:
        x = -1 + 2 * np.random.rand(2*N)
        if combined_goal(x, cov_xx, cov_pp) < 0:
            print(True, "randsearch!")
            guess_library.append( x )
            return True
        tries += 1
        
    tries = 0
    while tries < 2000:
        x = np.random.normal(0, 1, 2*N)
        if combined_goal(x, cov_xx, cov_pp) < 0:
            print(True, "randsearch! Gauss")
            guess_library.append( x )
            return True
        tries += 1
        
    return False # 200 tries, no entanglement found.


def partial_genuine_entanglement( Covmat, keep_modes, tryhard = True ):
    # Genuine N-partie entanglement, beteen the keep modes.
    
    if len(keep_modes) < 2:
        return np.NaN
    
    use_mat = Covmat.copy()
    
    n_modes = int( Covmat.shape[0]/2 )
    delete_modes = [number for number in range(n_modes) if number not in keep_modes ]
    
    destroy_rowcols = [ [2*n, 2*n+1] for n in delete_modes ]
    destroy_rowcols = [item for sublist in destroy_rowcols for item in sublist] # flatten
    
    # Eliminate the rows/collumns of the unusued modes
    use_mat = np.delete( use_mat, destroy_rowcols, axis=0)
    use_mat = np.delete( use_mat, destroy_rowcols, axis=1)
    
    #return gen_N_partite_mul( use_mat )
    return gen_N_partite( use_mat, tryhard )
    #return gen_N_partite_angles( use_mat )
    #return gen_N_partite_randsearch( use_mat )












# import cvxpy as cp

# def brute_outer_product( h ):
#     # for some reason cp.kron does not work.
#     # implement by loop.
#     out = []
#     for item1 in h:
#         out.append( [] )
#         for item2 in h:
#             out[-1].append( item1 * item2 )
#     return cp.bmat(out)



# def gen_N_partite( cov ):
#     N = int(cov.shape[0]/2)
    
#     bips = all_bipartitions(N)
    
#     #h = np.array([1]*N)
#     #g = np.array([1]*N)

#     h = cp.Variable(N)
#     g = cp.Variable(N)
    
#     cov_xx = np.real( cov[0::2, 0::2] )
#     cov_pp = np.real( cov[1::2, 1::2] )
    
#     def optimiser_goal(h, g, cov_xx, cov_pp ):
#         #du_sqr = cp.sum(  np.outer(h, h) * cov_xx  )
#         #dv_sqr = cp.sum(  np.outer(g, g) * cov_pp  )
        
#         # cp.kron(h.T, h)
        
#         # [cp.kron(h.reshape(n,1), cp.reshape(h, (n,1))
        
#         du_sqr = cp.sum(  cp.multiply( brute_outer_product( h ),  cov_xx ) )
#         dv_sqr = cp.sum(  cp.multiply( brute_outer_product( g ),  cov_pp ) )
        
#         Sbs = []
#         for partition in bips:
#             Sbs.append(  
#                   cp.abs( sum( [ g[i]*h[i] for i in partition ] ) )
#               +  cp.abs( sum( [ g[i]*h[i] for i in range(N) if i not in partition ] ) )
#                 )
        
#         Sbs = cp.hstack( Sbs )
        
#         return  du_sqr + dv_sqr - 2 * cp.min(Sbs)
        
#     objective = cp.Minimize( optimiser_goal( h, g, cov_xx, cov_pp ) )
#     prob = cp.Problem(objective)
#     result = prob.solve()
    
#     result = prob.solve()
    
#     return result < 0

# # # Optimise over h and g. Return "True" if it manages to bring the goal bellow 0 (genuine N party entanglement), otherwise return False.

# import pyomo.environ as pyo
# def gen_N_partite( cov ):
#     N = int(cov.shape[0]/2)
    
#     bips = all_bipartitions(N)
    
#     #h = np.array([1]*N)
#     #g = np.array([1]*N)
    
#     model = pyo.ConcreteModel()
#     model.h = pyo.Var(range(N), domain=pyo.Reals)
#     model.g = pyo.Var(range(N), domain=pyo.Reals)
    
#     cov_xx = np.real( cov[0::2, 0::2] )
#     cov_pp = np.real( cov[1::2, 1::2] )
    
#     # model.cov_xx = pyo.Param(default=cov_xx)
#     # model.cov_pp = pyo.Param(default=cov_pp)
    
#     def optimiser_goal(h, g, cov_xx, cov_pp ):
#         du_sqr = np.sum(  np.outer(h, h) * cov_xx  )
#         dv_sqr = np.sum(  np.outer(g, g) * cov_pp  )
        
        
#         # Sbs = []
#         # for partition in bips:
#         #     Sbs.append(  
#         #         np.abs( np.sum( [ g[i]*h[i] for i in partition ] ) )
#         #      +  np.abs( np.sum( [ g[i]*h[i] for i in range(N) if i not in partition ] ) )
#         #         )
            
#         return  du_sqr + dv_sqr #- 2 * min(Sbs)
        
#     model.goal = pyo.Objective( expr = optimiser_goal( model.h, model.g, cov_xx, cov_pp )) #, sense=minimize )
    
    
    
#     # Optimise over h and g. Return "True" if it manages to bring the goal bellow 0 (genuine N party entanglement), otherwise return False.










######## OLD STUFF ########


def psi_flucts( covmat, Delta, fs, ts ):
    
    N = len(Delta)
    
    sin = np.sin
    cos = np.cos
    
    psi_covmats = []
    
    for t in ts:
        new_covmat = np.zeros((2,2))
        
        for n in range(0, N):
            for m in range(0, N):
                
                new_covmat[0, 0] += covmat[2*n    ,2*m    ] * cos(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 1] += covmat[2*n + 1,2*m + 1] * cos(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[0, 1] += covmat[2*n    ,2*m + 1] * cos(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 0] += covmat[2*n + 1,2*m    ] * cos(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                
                new_covmat[0, 0] += covmat[2*n + 1,2*m + 1] * sin(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 1] += covmat[2*n    ,2*m    ] * sin(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[0, 1] -= covmat[2*n + 1,2*m    ] * sin(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 0] -= covmat[2*n    ,2*m + 1] * sin(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
                
                new_covmat[0, 0] += covmat[2*n + 1,2*m    ] * sin(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 1] -= covmat[2*n    ,2*m + 1] * sin(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[0, 1] -= covmat[2*n + 1,2*m + 1] * sin(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 0] += covmat[2*n    ,2*m    ] * sin(fs[n] * t) * cos(fs[m] * t) * Delta[n] * Delta[m]
                
                new_covmat[0, 0] += covmat[2*n    ,2*m + 1] * cos(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 1] -= covmat[2*n + 1,2*m    ] * cos(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[0, 1] += covmat[2*n    ,2*m    ] * cos(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
                new_covmat[1, 0] -= covmat[2*n + 1,2*m + 1] * cos(fs[n] * t) * sin(fs[m] * t) * Delta[n] * Delta[m]
        # end n, m
        
        psi_covmats.append( new_covmat )
    # end for t
    
    return psi_covmats

def psi_g1( AV, Delta, fs, expects_quad, C_vecs, V ):
    
    ts = np.linspace(0, 4*np.pi, 200)
    
    psi = 0
    
    for Amp, f in zip( AV * Delta[V-1::V], fs[V-1::V] ):
        psi += Amp * np.exp( 1j * f * ts )
        

    g1 = 0
    
    # 2D time field for two-time correlations
    tts = np.outer( ts, [1 for t in ts]) - np.outer( [1 for t in ts], ts)
    
    for variance, modes in zip( expects_quad, C_vecs):
        sum_freq = sum( fs * (np.real(modes) - np.imag(modes)) )
        
        g1 += variance * np.exp( 1j * sum_freq * tts   )
        
    
    fig, ax = plt.subplots(2, 1, figsize=(5,4))
    ax[0].plot( ts,  psi, 'k-')
    
    phase_amp( g1, ts, ts, ax= ax[1])
    
    #ax[1].phase_amp( ts, ts, g1 )
    
    return psi, g1



def numberToBase(n, b, length):
    if n == 0:
        return [0]*length
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return [0]*(length-len(digits)) + digits[::-1]


def m_vectors2( qs, p, trunk ):
    # Return all vectors of integers, m, such that: real(m) dot qs  - imag(m) dot qs = p
    # trunk limits the range of values considered for each m.
    
    ms = []
    N = len(qs)
    qs = np.array(qs)
    
    for n in range( (trunk+1)**(2*N) ):
        # Loop over all terms
        vec = np.array( [i for i in numberToBase(n, trunk+1, 2*N)] )
        
        if (vec[:N]*qs).sum() - (vec[N:]*qs).sum() == p:
            ms.append( vec[:N]  + 1j*vec[N:] )
    
    return ms


    
def solve_matrix( N, V, qd, alpha, Delta, EJT, Gamma, test_version = False ):
    
    # This builds and solves the matrix.
    # This can be considered depreciated, it is made redundant by the "build_matrix" 
    # and "solve_matrix" functions that together acheive the same outcome in a more versatile
    # and faster way.
    
    qs = list( range(1,N+1) )
    
    dot_terms = all_quads(N)
    
    S = []
    for item in dot_terms:
        
        Bess_index = ( V - np.dot( real(item) - imag(item) , qs ) ) / qd
        
        if Bess_index - int(Bess_index) == 0:
            # An energy conserving move is possible with those operators
            S.append( np.array( list(item) + [Bess_index] ) )
    
    # Interpret dot terms as follows:
    # [n, m, k+ip] means < a_1^n, a_2^m, a_3^k, (a_3^dag)^p >
    
    # Commutators:
    def comutator( vec1, vec2, basis ):
        # Does comutators using my odd vector notation.
        
        out = [0 for _ in basis]
        const = 0
        
        # main bit of loop gets everything EXCEPT the terms emerging from 2 of the +1 comuatros meeting
        # For n=2 this means its missing constant terms.
        # Extra "if 1+1j..." catches it
        for n in range(len(vec1)):
            if np.imag(vec1[n]*vec2[n]):
                neg = imag( vec1[n] ) * real( vec2[n] )
                pos = real( vec1[n] ) * imag( vec2[n] )
                
                remvec = list(  np.array(vec1) + np.array(vec2)  )
                remvec[n] += -1 - 1j
                
                matches = [np.array_equal(remvec, item) for item in basis]
                if True in matches:
                    index = matches.index(True)
                    out[index] += pos - neg
                
                if 1+1j in remvec:
                    const += (pos - neg) / 2

        return out, const
    
    # finally build the matrix:
    matrix = []
    const =  np.zeros( (len(dot_terms)), dtype=np.complex128 )
    
    for n, x in enumerate( dot_terms ):
        
        new_row = np.zeros( (len(dot_terms)), dtype=np.complex128 )
        for Ham_part in S:
            n_part, const_part = comutator( Ham_part[:-1], x, dot_terms )
            
            if imag(Ham_part[-1]):
                print('Something has gone hideously wrong')
            
            # Multiplier
            if test_version == False:
                Z_index = real(Ham_part[-1])
                
                Z_bit = sum_Z( 2j * Delta[qd-1] * alpha, Z_index )
                Delta_bit = -1 * vec_mod_power( [D for D in Delta], Ham_part[:-1] )
                
            else:
                Delta_Z_bit = vec_mod_power( [+1j*D for D in Delta], Ham_part[:-1] )
            # end if
            
            combinatorial_bit = (1/max( list(real(Ham_part[:-1])) + list(imag(Ham_part[:-1])) ))
            
            multiplier = (-1j*EJT/2) * Delta_bit * Z_bit * combinatorial_bit

            const[n] += const_part * multiplier
            new_row  += np.array(n_part) * multiplier
        # end for
        
        matrix.append( new_row )
    # for for
    
    matrix = np.array( matrix )
    # Put loss down the matrix diagonal:
    for n, x in enumerate( dot_terms ):
        matrix[n,n] += -0.5 * ( Gamma * (real(x) + imag(x)) ).sum()
       
    
    # Want to find Vec such that matrix.Vec + const = 0
    Vec = np.linalg.solve( matrix, -1*const )
    print("Solution works?:", np.allclose(np.dot(matrix, Vec), -1*const))
    
    return Vec, dot_terms, matrix, const

    