Beispiel #1
0
def EIG_DECOMP_main(U0_set, pi):

    # Need to loop over a set of background states.
    NU = len(U0_set)
    theta = np.zeros(
        (NU, N, dim),
        dtype=complex)  # Initialise the set of weights; these will be complex.
    val = np.zeros((NU, N, dim), dtype=complex)
    count = np.zeros((NU, N, dim), dtype=int)
    count2 = np.zeros((NU, N, dim), dtype=int)
    ratio = np.zeros((NU, N, dim))

    # Start the loop.
    for ui in range(0, NU):

        # Start by defining the background state.
        for j in range(0, N):
            U0[j] = U0_set[ui]
            H0[j] = -(U0[j] / g) * (f0 * y[j] + beta * y[j]**2 / 2) + Hflat
        U0_nd = U0 / U
        H0_nd = H0 / chi

        # The 1L SW solution
        #====================================================

        I = np.complex(0.0, 1.0)

        # Coefficients
        a1, a2, a3, a4, b4, c1, c2, c3, c4 = solver.SOLVER_COEFFICIENTS(
            Ro, Re, K_nd, f_nd, U0_nd, H0_nd, omega_nd, gamma_nd, dy_nd, N)
        # Solver (free-slip)
        solution = solver.FREE_SLIP_SOLVER4(a1, a2, a3, a4, f_nd, b4, c1, c2,
                                            c3, c4, Ro * Ftilde1_nd,
                                            Ro * Ftilde2_nd, Ftilde3_nd, N, N2)

        solution = eigDiagnostics.switchKsign(solution, N)

        # Analysis
        #====================================================

        # Loop over desired wavenumbers (for tests, this may not be the full r'ange of wavenumbers)
        # ii indexes arrays storing information at ALL wavenumbers k
        # i indexes arrays storing information ONLY at wavenumbers used in the decomposition.

        a1, a2, a3, a4, b1, b4, c1, c2, c3, c4 = eigSolver.EIG_COEFFICIENTS2(
            Ro, Re, K_nd, f_nd, U0_nd, H0_nd, gamma_nd, dy_nd, N)

        for i in range(0, N):

            k = K_nd[i]
            #print('k = ' + str(k))

            # Eigenmodes, eigenvalues and count.
            #====================================================

            # Use free-slip solver
            val[ui,
                i, :], vec = eigSolver.FREE_SLIP_EIG(a1, a2, a3, a4, b1, b4,
                                                     c1, c2, c3, c4, N, N2, i,
                                                     False)

            # Each eigenmode is currently a unit vector, but we normalise so that each mode contains unit energy.
            #==

            # Extract the three components.
            u_vec, v_vec, h_vec = eigDiagnostics.vec2vecs(vec, N, dim, BC)

            # Calculate the contained in each component.
            E = np.zeros(dim)
            for wi in range(0, dim):
                EE = energy.E_anomaly_EIG(u_vec[:, wi], v_vec[:, wi],
                                          h_vec[:, wi], H0_nd, U0_nd, Ro, y_nd,
                                          dy_nd)
                # Normalise each vector by the square root of the energy.
                u_vec[:,
                      wi], v_vec[:, wi], h_vec[:, wi] = u_vec[:, wi] / np.sqrt(
                          EE), v_vec[:,
                                     wi] / np.sqrt(EE), h_vec[:,
                                                              wi] / np.sqrt(EE)
            # Rebuild the vector. This should have unit energy perturbation.
            # (There are more direct ways of executing this normalisation, but this method is the safest.)
            vec = eigDiagnostics.vecs2vec(u_vec, v_vec, h_vec, N, dim, BC)

            # Order modes by meridional pseudo wavenumber (count).
            count[ui, i, :], count2[ui, i, :], ratio[
                ui, i, :], i_count = eigDiagnostics.orderEigenmodes(
                    u_vec, x_nd, k, N, dim)
            #count, i_count = eigDiagnostics.orderEigenmodes2(vec,val,N,False)

            # Comment out this line, depending on which EIG_COEFFICIENTS function is being called.
            #val = val / (2. * np.pi * I * Ro);

            #====================================================

            Phi = solution[:, i]
            # 1. Assign the solution corresponding to wavenumber k=K_nd[ii].

            theta[ui, i, :] = np.linalg.solve(vec, Phi)
            # 2.

    np.save('theta_array' + str(pi), theta)
    np.save('val_array' + str(pi), val)
    np.save('count_array' + str(pi), count)
    np.save('count2_array' + str(pi), count2)
    np.save('ratio_array' + str(pi), count)

    # Return the weights, eigenvalues, and meridional wavenumber.
    #return theta, val, count
    return
Beispiel #2
0
def EIG_DECOMP_main(U0_nd, H0_nd, dim):
    '''
	Load outputted theta and val and post-process. Function does multiple things. 
	(1) For a given U0-value calculate the SW solution. Rebuild solution with Nm-most dominant modes
	to see how many are required for p % accuracy. Does this depend on k, U0?
	(2) Plots of weights at specific wavenumber (and how quickly they decay), and plots of weights over all wavenumbers and BG flows.
	(3) Phase speeds and 'average' phase speeds. 
	'''
    # Dimensions
    Nm = dim
    # How many modes to use in the decomposition at each wavenumber (dim is maximum).
    Nk = N

    # The 1L SW solution
    #====================================================

    I = np.complex(0.0, 1.0)

    SOL = 'NEW'

    # Define the solution in (k,y)-space - can be from FILE or a NEW run.
    if SOL == 'FILE':
        solution = np.load(
            '/home/mike/Documents/GulfStream/Code/DATA/1L/REF/solution_NORTH256.npy'
        )
    if SOL == 'NEW':
        # Forcing
        #if FORCE_TYPE == 'CTS':
        #	F1_nd, F2_nd, F3_nd, Ftilde1_nd, Ftilde2_nd, Ftilde3_nd = forcing.forcing_cts(x_nd,y_nd,K_nd,y0_nd,r0_nd,N,FORCE,AmpF_nd,f_nd,f0_nd,dx_nd,dy_nd);
        #elif FORCE_TYPE == 'DCTS':
        #	F1_nd, F2_nd, F3_nd, Ftilde1_nd, Ftilde2_nd, Ftilde3_nd = forcing.forcing_dcts(x_nd,y_nd,K_nd,y0_nd,r0_nd,N,FORCE,AmpF_nd,f_nd,f0_nd,dx_nd,dy_nd)
        #elif FORCE_TYPE == 'DELTA':
        #	F1_nd, F2_nd, F3_nd, Ftilde1_nd, Ftilde2_nd, Ftilde3_nd = forcing.forcing_delta(AmpF_nd,y0_index,dx_nd,N);
        # Coefficients
        a1, a2, a3, a4, b4, c1, c2, c3, c4 = solver.SOLVER_COEFFICIENTS(
            Ro, Re, K_nd, f_nd, U0_nd, H0_nd, omega_nd, gamma_nd, dy_nd, N)
        # Solver
        if BC == 'NO-SLIP':
            solution = solver.NO_SLIP_SOLVER(a1, a2, a3, a4, f_nd, b4, c1, c2,
                                             c3, c4, Ro * Ftilde1_nd,
                                             Ro * Ftilde2_nd, Ftilde3_nd, N,
                                             N2)
        elif BC == 'FREE-SLIP':
            solution = solver.FREE_SLIP_SOLVER(a1, a2, a3, a4, f_nd, b4, c1,
                                               c2, c3, c4, Ro * Ftilde1_nd,
                                               Ro * Ftilde2_nd, Ftilde3_nd, N,
                                               N2)
        else:
            sys.exit('ERROR: choose valid BC')

    solution = solution / AmpF_nd

    print('solved')

    #====================================================

    # Eigenmode analysis
    #====================================================
    #====================================================

    # Initisialastion steps
    #====================================================

    VEC = 'FILE'
    # From FILE, requires pre-saved vectors which take up lots of memory.
    LOOP = 'FULL'
    # FULL, PART

    if LOOP == 'FULL':
        loop = range(0, N)
        Nk_neg = 9
        Nk_pos = 8
    elif LOOP == 'PART':
        Nk_neg = 6
        Nk_pos = 6
        # How many positive/negative wavenumbers to perform this decomposition at.
        loop = it.chain(range(0, Nk_pos + 1), range(N - Nk_neg, N))
        Nk = Nk_neg + Nk_pos + 1
    else:
        sys.exit('ERROR: LOOP must be FULL or PART.')

    theta = np.zeros((Nm, Nk), dtype=complex)
    # Initialise the set of weights; these will be complex.
    proj = np.zeros((dim, N), dtype=complex)
    # The projection. Sums the Nm most dominant modes, each of length dim, for Nk i-values.
    dom_index = np.zeros((Nm, Nk), dtype=int)
    # To store the indices of the Nm-most dominant modes.

    var = np.zeros((Nk))
    mean = np.zeros((Nk))

    scatter_k = np.zeros(Nm * Nk)
    # An empty array for saving k-values, for use in the scatter plot of dominant modes.
    scatter_l = np.zeros(Nm * Nk)
    # An empty array for storing the count, psuedo-wavenumber l.
    scatter_p = np.zeros(Nm * Nk)
    # An empty array for storing periods of the dominant wavenumbers.
    theta_abs = np.zeros((Nm, Nk))
    # For storing the absolute value of each weight.
    theta_abs_tot = np.zeros(Nk)
    # For storing sum of absolute values of each set of decomposition weights.
    cx = np.zeros((Nm, Nk))
    # For storing the zonal phase speed of each mode,
    cy = np.zeros((Nm, Nk))
    # and the meridional phase speed.
    p = np.zeros((Nk, 2))
    # For storing weighted phase speeds at each wavenumber. (i=0 => y)

    # Analysis
    #====================================================

    # Loop over desired wavenumbers (for tests, this may not be the full range of wavenumbers)
    # ii indexes arrays storing information at ALL wavenumbers k
    # i indexes arrays storing information ONLY at wavenumbers used in the decomposition.
    for ii in loop:

        print(' ')
        print('ii = ' + str(ii))
        k = K_nd[ii]
        print('k = ' + str(k))
        i = k % Nk
        print('i = ' + str(i))
        i = int(i + 0.01)

        # Eigenmodes, eigenvalues and count.
        #====================================================

        # This section returns three arrays: 1. val, 2. vec, 3. count
        # 1.) val = val[0:dim] stores the eigenvalues/frequencies.
        # 2.) vec = vec[]
        # 3.) count = count[]

        # Run the solver for the current k-value.
        if VEC == 'NEW':  # Solve the eigenmode problem anew.
            a1, a2, a3, a4, b1, b4, c1, c2, c3, c4 = eigSolver.EIG_COEFFICIENTS2(
                Ro, Re, K_nd, f_nd, U0_nd, H0_nd, gamma_nd, dy_nd, N)
            if BC == 'NO-SLIP':
                val, u_vec, v_vec, h_vec = eigSolver.NO_SLIP_EIG(
                    a1, a2, a3, a4, b1, b4, c1, c2, c3, c4, N, N2, ii, True)
            if BC == 'FREE-SLIP':
                val, vec = eigSolver.FREE_SLIP_EIG(a1, a2, a3, a4, b1, b4, c1,
                                                   c2, c3, c4, N, N2, ii,
                                                   False)

            # Order modes by meridional pseudo wavenumber (count).
            count, i_count = eigDiagnostics.orderEigenmodes(
                vec, val, x_nd, k, T_nd[ts], N, dim, BC)
            #count, i_count = eigDiagnostics.orderEigenmodes2(vec,val,N,False)
            count = count[i_count]
            vec = vec[:, i_count]
            val = val[i_count]

            # Each eigenmode is currently a unit vector, but we normalise so that each mode contains unit energy.
            #==

            # Extract the three components.
            u_vec, v_vec, h_vec = eigDiagnostics.vec2vecs(vec, N, dim, BC)

            # Calculate the contained in each component.
            E = np.zeros(dim)
            for wi in range(0, dim):
                EE = energy.E_anomaly_EIG(u_vec[:, wi], v_vec[:, wi],
                                          h_vec[:, wi], H0_nd, U0_nd, Ro, y_nd,
                                          dy_nd)
                # Normalise each vector by the square root of the energy.
                u_vec[:,
                      wi], v_vec[:, wi], h_vec[:, wi] = u_vec[:, wi] / np.sqrt(
                          EE), v_vec[:,
                                     wi] / np.sqrt(EE), h_vec[:,
                                                              wi] / np.sqrt(EE)

            # Rebuild the vector. This should have unit energy perturbation.
            # (There are more direct ways of executing this normalisation, but this method is the safest.)
            vec = eigDiagnostics.vecs2vec(u_vec, v_vec, h_vec, N, dim, BC)

            # Comment out this line, depending on which EIG_COEFFICIENTS function is being called.
            #val = val / (2. * np.pi * I * Ro);

        elif VEC == 'FILE':  # Load eigenmodes and eigenvalues from file.

            # Low-res
            path = '/home/mike/Documents/GulfStream/RSW/DATA/1L/EIG/128/west/'
            #path = '/home/mike/Documents/GulfStream/RSW/DATA/1L/EIG/128/nu='+str(int(nu))+'/';
            ncFile = path + 'RSW1L_Eigenmodes_k' + str(int(k)) + '_N129.nc'

            # High-res
            #path = '/media/mike/Seagate Expansion Drive/Documents/GulfStream/RSW/DATA/1L/EIG/256/16/'
            #path =  '/home/mike/Documents/GulfStream/RSW/DATA/1L/EIG/256/west/';
            #ncFile = path + 'RSW1L_Eigenmodes_k' + str(int(k)) + '_N257.nc';
            print('Reading from ' + ncFile + '...')
            val, vec, count = output_read.ncReadEigenmodes(ncFile)
        else:
            sys.exit('VEC must be FILE or NEW')

        # Expresses the eigenvalues (frequencies) in terms of periods (units days).
        freq = np.real(val)
        period_days = T_adv / (freq * 24. * 3600.)

        dim = np.size(val)

        #====================================================

        # Now we have the solution and the eigenmodes.
        # The decomposition follows the following steps:
        # 1. Define the solution to be decomposed as Phi.
        # 2. Decompose Phi into vec using a linear solver; theta_tmp stores the weights.
        # 3. Arrange the weights in descending order according to their complex amplitude.
        # 4. Sum the Nm-most dominant weights.

        Phi = solution[:, ii]
        # 1. Assign the solution corresponding to wavenumber k=K_nd[ii].

        theta_tmp = np.linalg.solve(vec, Phi)
        # 2.
        theta_abs_tmp = np.abs(theta_tmp)
        dom_index_tmp = np.argsort(-theta_abs_tmp)
        # 3. The indices of the modes, ordered by 'dominance'.
        theta_abs_tot[i] = sum(theta_abs_tmp[dom_index_tmp[0:dim]])
        # Change dim to Nm if necessary

        # Now loop over each mode (at wavenumber k)
        for mi in range(0, Nm):
            #print(dom_index_tmp[mi]);
            #print('count = ' + str(count[dom_index_tmp[mi]]));
            #print(np.abs(theta_tmp[dom_index_tmp[mi]]));

            dom_index[mi, i] = dom_index_tmp[mi]
            theta[mi, i] = theta_tmp[dom_index_tmp[mi]]
            # All weights are now ordered in terms of their absolute value.

            # Absolute value of each mode
            theta_abs[mi, i] = np.abs(theta[mi, i])

            # Zonal & meridional phase speed of each mode
            cx[mi, i] = freq[dom_index[mi, i]] / k
            if count[dom_index[mi, i]] != 0:
                cy[mi, i] = freq[dom_index[mi, i]] / count[dom_index[mi, i]]

            if mi < 95:
                # The projection.
                proj[:, ii] = proj[:, ii] + theta_tmp[
                    dom_index_tmp[mi]] * vec[:, dom_index_tmp[mi]]
                # 4.

            # Scatter plot arrays.
            scatter_k[i * Nm + mi] = k
            scatter_l[i * Nm + mi] = count[dom_index[mi, i]]
            scatter_p[i * Nm + mi] = period_days[dom_index[mi, i]]
            #plt.plot(vec[0:N,dom_index_tmp[mi]],y_nd);
            #plt.ylim(-0.5,0.5);
            #plt.show();
        #plt.plot(theta_abs[:,i]);
        #plt.show();

        # Statistics: mean, variance, weighted average
        # Should normalise so that all have the same mean (i.e. mean = 1/Nm);
        mean[i] = theta_abs_tot[i] / Nm
        var[i] = sum((theta_abs[:, i] - mean[i])**2) / (Nm * mean[i]**2)
        p[i, 1] = sum((theta_abs[:, i] * cx[:, i])) / theta_abs_tot[i]
        p[i, 0] = sum((theta_abs[:, i] * cy[:, i])) / theta_abs_tot[i]
        print(cy[10, i])

    return theta, mean, var, p, proj, solution, scatter_k, scatter_l, scatter_p
Beispiel #3
0
    count = np.zeros((dim))
    i_count = np.ones((dim))
    # Order all relevant arrays
    #count = count[i_count];
    #vec = vec[:,i_count];
    #val = val[i_count];
    #period_days = period_days[i_count]

    p_sort = np.argsort(-np.abs(period_days))
    #print(period_days[p_sort]);

    # Before saving the modes, they need to be normalised by their energy.
    ENERGY = 1
    if ENERGY == 1:
        E = np.zeros(dim)
        u_vec, v_vec, h_vec = eigDiagnostics.vec2vecs(vec, N, dim, BC)
        for wi in range(0, dim):
            #print(str(wi+1) + ' / ' + str(dim));
            EE = energy.E_anomaly_EIG(u_vec[:, wi], v_vec[:, wi], h_vec[:, wi],
                                      H0_nd, U0_nd, Ro, y_nd, dy_nd)
            u_vec[:, wi], v_vec[:, wi], h_vec[:, wi] = u_vec[:, wi] / np.sqrt(
                EE), v_vec[:, wi] / np.sqrt(EE), h_vec[:, wi] / np.sqrt(EE)
        # Rebuild
        vec = eigDiagnostics.vecs2vec(u_vec, v_vec, h_vec, N, dim, BC)

    ncSaveEigenmodes(vec, val, count, y_nd, k, N, dim, BC)

#====================================================

if str(raw_input('continue? y or n: ')) == 'n':
    sys.exit()
Beispiel #4
0
def EIG_DECOMP_main(y0_set, pi):

    I = np.complex(0.0, 1.0)

    # Need to loop over a set of background states.
    Ny = len(y0_set)
    theta = np.zeros(
        (Ny, N, dim),
        dtype=complex)  # Initialise the set of weights; these will be complex.

    # Only theta will have Ny dimension. Only need one set of eigenmodes, so no dependence on forcing latitude.
    val = np.zeros((N, dim), dtype=complex)
    count = np.zeros((N, dim), dtype=int)
    count2 = np.zeros((N, dim), dtype=int)
    ratio = np.zeros((N, dim))

    # Find solution at every y0-value and for all i. Store it.
    #========================================================

    # Coefficients - no dependence on y0
    a1, a2, a3, a4, b4, c1, c2, c3, c4 = solver.SOLVER_COEFFICIENTS(
        Ro, Re, K_nd, f_nd, U0_nd, H0_nd, omega_nd, gamma_nd, dy_nd, N)

    solution = np.zeros((Ny, dim, N), dtype=complex)

    # Start the loop.
    for yi in range(0, Ny):

        # Get forcing latitude.
        y0_nd = y0_set[yi]

        # Redefine forcing, moving one gridpoint each iteration.
        F1_nd, F2_nd, F3_nd, Ftilde1_nd, Ftilde2_nd, Ftilde3_nd = forcing.forcing_cts2(
            x_nd, y_nd, K_nd, y0_nd, r0_nd, N, FORCE, AmpF_nd, f_nd, f0_nd, bh,
            dx_nd, dy_nd)

        # The 1L SW solution.

        # Solver (free-slip)
        solution[yi, ] = solver.FREE_SLIP_SOLVER4(a1, a2, a3, a4, f_nd, b4, c1,
                                                  c2, c3, c4, Ro * Ftilde1_nd,
                                                  Ro * Ftilde2_nd, Ftilde3_nd,
                                                  N, N2)

        solution[yi, ] = eigDiagnostics.switchKsign(solution[yi, ], N)

    # Done finding solution.

    #====================================================

    # Find eigenmodes and decompose solution.
    #====================================================

    # Loop over desired wavenumbers (for tests, this may not be the full r'ange of wavenumbers)

    # Eig coefficients don't change. Define them just once.
    a1, a2, a3, a4, b1, b4, c1, c2, c3, c4 = eigSolver.EIG_COEFFICIENTS2(
        Ro, Re, K_nd, f_nd, U0_nd, H0_nd, gamma_nd, dy_nd, N)

    for i in range(0, N):

        k = K_nd[i]

        #print('k = ' + str(k))

        # Eigenmodes, eigenvalues and count.
        #====================================================

        # Use free-slip solver
        val[i, :], vec = eigSolver.FREE_SLIP_EIG(a1, a2, a3, a4, b1, b4, c1,
                                                 c2, c3, c4, N, N2, i, False)

        # Each eigenmode is currently a unit vector, but we normalise so that each mode contains unit energy.
        #==

        # Extract the three components.
        u_vec, v_vec, h_vec = eigDiagnostics.vec2vecs(vec, N, dim, BC)

        # Calculate the contained in each component.
        E = np.zeros(dim)
        for wi in range(0, dim):
            EE = energy.E_anomaly_EIG(u_vec[:, wi], v_vec[:, wi], h_vec[:, wi],
                                      H0_nd, U0_nd, Ro, y_nd, dy_nd)
            # Normalise each vector by the square root of the energy.
            u_vec[:, wi], v_vec[:, wi], h_vec[:, wi] = u_vec[:, wi] / np.sqrt(
                EE), v_vec[:, wi] / np.sqrt(EE), h_vec[:, wi] / np.sqrt(EE)
        # Rebuild the vector. This should have unit energy perturbation.
        # (There are more direct ways of executing this normalisation, but this method is the safest.)
        vec = eigDiagnostics.vecs2vec(u_vec, v_vec, h_vec, N, dim, BC)

        # Eigenmodes now have unit time-mean energy.
        #==

        # Meridional pseudo wavenumber (count).
        count[i, :], count2[i, :], ratio[
            i, :], i_count = eigDiagnostics.orderEigenmodes(
                u_vec, x_nd, k, N, dim)

        # Now decompose for each forcing latitude.
        for yi in range(0, Ny):

            # Decompose.
            theta[yi, i, :] = np.linalg.solve(vec, solution[yi, :, i])

    # End of eigenmode calculation and decomposition.
    #========================================================

    np.save('theta_array' + str(pi), theta)
    np.save('val_array', val)
    np.save('count_array', count)
    np.save('count2_array', count2)
    np.save('ratio_array', count)

    # Don't return anything, arrays are saved instead.
    return