debug=True) # Calculate autocorrelation kmonth = hclim[o, a, :].argmax() # kmonth is the INDEX of the mongth autocorr = {} for model in range(4): # Get the data tsmodel = sst[model] tsmodel = proc.year2mon(tsmodel) # mon x year # Deseason (No Seasonal Cycle to Remove) tsmodel2 = tsmodel - np.mean(tsmodel, 1)[:, None] # Plot autocorr[model] = proc.calc_lagcovar(tsmodel2, tsmodel2, lags, kmonth + 1, 0) #%% Make Test Plot fig, ax = plt.subplots(1, 1) #ax.plot(lags,AVG0,color='b',label='CESM1 (YO)') ax.plot(lags, AVG1, color='c', label='No-Entrain (YO)') ax.plot(lags, AVG2, color='g', label='Entrain (YO)') ax.plot(lags, autocorr[2], '-r', label='No-Entrain (GL)') ax.plot(lags, np.roll(autocorr[3], 0), ':r', label='Entrain (GL)') ax.legend() titlestr = 'SST Autocorrelation; Month' + str( kmonth + 1) + '\n Lon: ' + "-30" + ' Lat: ' + "50" ax.set(xlabel='Lag (months)',
kmonth = mldcycle[klon,klat,...].argmax() print(kmonth) acs =scm.calc_autocorr(sstall,lags,kmonth+1) xtk2 = np.arange(0,37,2) # Plot fig,ax = plt.subplots(1,1) title = "Autocorrelation, Lag 0 = %s,\n Location: %s" % (mons3[kmonth],loctitle) ax,ax2 = viz.init_acplot(kmonth,xtk2,lags,ax=ax,title=title) ax.plot(lags,acs[0],lw=0.85,label="Flux Integration with Q Corretion",color='orange') ax.plot(lags,acs[1],ls='dashed',lw=0.85,label="Flux Integration",color='b') ax.plot(lags,acs[2],ls='dashed',lw=0.85,label="Flux Integration, Shifted Forcing",color='g') ax.plot(lags,slabac,label="CESM-SLAB, Actual Correlation",color='k') ax.plot(lags,acnoenso,label="CESM-SLAB,ENSO Removed",color='r') ax.set_ylabel('Correlation') ax.set_xlabel('Lags (months)') ax.legend() plt.savefig(outfigpath + "CESM_SLAB_FluxIntegration_Point%s_detrend_10x.png" % (locfn),dpi=200) #%% Calculate Autocorrelation but for point without enso # Get variable tspoint = tsenso0[klon360,klat,:] tspoint = tspoint.reshape(int(10776/12),12).T tspoint = tspoint-tspoint.mean(1)[:,None] # Calculate Lag correlation acnoenso = proc.calc_lagcovar(tspoint,tspoint,lags,kmonth+1,0)
kmonth = mld.argmax() acall = {} for i,applyfac in enumerate(applyfacs): ac = {} for m in range(4): sst = ssts[i][m] sst = np.roll(sst,-1) # Roll since first month is feb (use jan, no-entrain 1d) tsmodel = proc.year2mon(sst) # mon x year # Deseason tsmodel2 = tsmodel - np.mean(tsmodel,1)[:,None] # Compute autocorrelation and save data for region ac[m] = proc.calc_lagcovar(tsmodel2,tsmodel2,lags,kmonth+1,0) acall[i] = ac.copy() #%% Plot autocorrelation (Plot by Model) applyfaclab = ["Forcing Only","Incl. Seasonal MLD","Incl. Seasonal MLD and Integration Factor"] modelname = ("MLD Fixed","MLD Max", "MLD Seasonal", "MLD Entrain") mons3=('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec') monname=('January','February','March','April','May','June','July','August','September','October','November','December') mons3tile = np.tile(np.array(mons3),int(np.floor(len(lags)/12))) mons3tile = np.roll(mons3tile,-kmonth) outfigpath = "/Users/gliu/Downloads/02_Research/01_Projects/01_AMV/02_stochmod/02_Figures/20201123_AMVTele/"
lat = pz['lat'] # Find values at point lonf,latf = point klon,klat = proc.find_latlon(lonf,latf,lon,lat) # Get value at point sst = TS[:,klat,klon] tsmodel = proc.year2mon(sst) # mon x year # Deseason tsmodel2 = tsmodel - np.mean(tsmodel,1)[:,None] # Compute autocorrelation and save data for region ac = proc.calc_lagcovar(tsmodel2,tsmodel2,lags,kmonth+1,0) # Save file locstring = "pointlon%i_lat%i"%(point[0],point[1]) np.save("%sCESM-SLAB_PIC_autocorrelation_%s.npy"%(outpath,locstring),ac) # # Flux Calculation options # monwin = 3 # Window of months # lags = [1,2,3] # Lags to include # flux = 'NHFLX' #%% Calculate regional averages # Regional Analysis Settings
def scm_synt(hclim, dampingr, NAO1, randts, lags, applyfac, T0=0, returncomponents=False): t_end = randts.shape[0] # Get simulation length # ---------------------------- # % Set-up damping parameters and kprev # ---------------------------- # Converts damping parameters from raw form (Watts/m2) to (deg/sec) # Also calculates beta and FAC # Note: Consider combining with NAO Forcing conversion? # Find Kprev kpreva, _ = scm.find_kprev(hclim) viz.viz_kprev(hclim, kpreva) lbd, lbd_entr, FAC, beta = scm.set_stochparams(hclim, dampingr, dt, ND=False, rho=rho, cp0=cp0, hfix=hfix) """ Out Format: lbd -> Dict (keys 0-3) representing each mode, damping parameter lbd_entr -> array of entrainment damping FAC -> Dict (keys 0-3) representing each model, integration factor beta ->array [Mon] kprev -> array [Mon] """ # ---------------------------- # % Set Up Forcing ------------------------------------------------ # ---------------------------- # Convert NAO from W/m2 to degC/sec. Returns dict with keys 0-2 (same as scm.convert_NAO) NAOF = {} conversionfac = dt / cp0 / rho if applyfac == 0: # Dont apply MLD to NAOF for hi in range(3): NAOF[hi] = NAO1 * conversionfac else: # Apply each MLD case to NAOF NAOF[0] = NAO1 * conversionfac / hfix NAOF[1] = NAO1 * conversionfac / hclim.max() NAOF[2] = NAO1 * conversionfac / hclim # Use random time series to scale the forcing pattern F = {} tilecount = int(12 / NAOF[0].shape[0] * nyr) for hi in range(3): F[hi] = np.tile(NAOF[hi].squeeze(), tilecount) * randts * fscale # Save Forcing if option is set if saveforcing == 1: np.save(output_path + "stoch_output_%s_Forcing.npy" % (runid), F) """ Output: F - dict (keys = 0-2, representing each MLD treatment) [time (simulation length)] Fseas - dict (keys = 0-2, representing each MLD treatment) [ month] """ # ---------- # %RUN MODELS ----------------------------------------------------------------- # ---------- # Set mulFAC condition based on applyfac if applyfac == 2: multFAC = 1 # Don't apply integrationreduction factor if applyfac is set to 0 or 1 else: multFAC = 0 #% Run Models <SET> """ Inputs: FAC - Dict of Integration Factors (0-3) lbd - Dict of Damping Parameters (0-3) F - Dict of Forcings (0-2) kprev - Array/Vector of Entraining Months beta - Array/Vector of Entrainment velocities hclima - Array/Vector of MLD cycle Fixed Params: T0 (Initial SST), t_end (end timestep), multFAC (0 or 1) Output sst - Dict of model output (0-3) """ # Preallocate dictionary to store results (Use tuple instead?) sst = {} # Run Model Without Entrainment # Loop for each Mixed Layer Depth Treatment for hi in range(3): start = time.time() # Select damping and FAC based on MLD FACh = FAC[hi] lbdh = lbd[hi] # Select Forcing Fh = F[hi] # Run Point Model start = time.time() sst[hi], _, _ = scm.noentrain(t_end, lbdh, T0, Fh, FACh, multFAC=multFAC) elapsed = time.time() - start tprint = "\nNo Entrain Model, hvarmode %i, ran in %.2fs" % (hi, elapsed) print(tprint) # Run Model With Entrainment start = time.time() Fh = F[2] FACh = FAC[3] sst[3] = scm.entrain(t_end, lbd[3], T0, Fh, beta, hclim, kpreva, FACh, multFAC=multFAC) elapsed = time.time() - start tprint = "\nEntrain Model ran in %.2fs" % (elapsed) print(tprint) # Calculate Autocorrelation kmonth = hclim.argmax() # kmonth is the INDEX of the mongth autocorr = {} for model in range(4): # Get the data tsmodel = sst[model] tsmodel = proc.year2mon(tsmodel) # mon x year # Deseason (No Seasonal Cycle to Remove) tsmodel2 = tsmodel - np.mean(tsmodel, 1)[:, None] # Plot autocorr[model] = proc.calc_lagcovar(tsmodel2, tsmodel2, lags, kmonth + 1, 0) if returncomponents: return sst, autocorr, lbd, FAC, beta, kpreva, F return sst, autocorr