def getp_fromapbp(fileAP): try: aps=pp(file=fileAP,var="aps",x=0,y=0).getf() bps=pp(file=fileAP,var="bps",x=0,y=0).getf() nz = len(aps) except: print("info: read apbp.txt") ap,bp = np.loadtxt("apbp.txt",unpack=True) nz = len(ap) aps = 0.5*(ap[0:nz-1]+ap[1:nz]) bps = 0.5*(bp[0:nz-1]+bp[1:nz]) nz = len(aps) #print("... ps") ps=pp(file=fileAP,var="ps").getf() nt,ny,nx = ps.shape p = np.zeros((nt,nz,ny,nx)) if method == 1: ps=ppcompute.mean(ps,axis=2) p = np.zeros((nt,nz,ny)) #print("... compute p") for tt in range(nt): for kk in range(nz): if method == 1: p[tt,kk,:] = aps[kk]+bps[kk]*ps[tt,:] elif method == 2: p[tt,kk,:,:] = aps[kk]+bps[kk]*ps[tt,:,:] return p
#! /usr/bin/env python from ppclass import pp m = pp() m.file = "/home/aymeric/Big_Data/POLAR_APPERE_lowres_wrfout_d01_2024-03-04_06.nc" m.var = ["tk", "tk"] m.y = ["80", "82"] m.t = ["2", "5"] m.getplot()
#"3240,3600"=8e annee en entier (moyenne annuelle) #"3360,3380"=134 EteHN #"3540,3560"=308 hiverHN #"3570,3600"=histins195 (330-360) correspond a DYNAMICO-195 #"3560,3590"=histins195 (320-350) correspond a DYNAMICO-170 infz = 13 #borne inf de Z ###0 niveau 16 = 140 mbar = 76km topz = 48 #borne sup de Z ###64 niveau 56 = 0.01mbar = 316km nn = 3 #Indice pour retirer les poles sur les latitudes # -> Recuperation des variables dans le fichier moyennes zonalement avec ls corrige teta, lon, lat, zmod, t = pp(file=fff, var="teta", t=time_step, x="-180,180", verbose=True, changetime="correctls").getfd() zdtsw = pp(file=fff, var="zdtsw", t=time_step, x="-180,180", verbose=True, changetime="correctls").getf() zdtlw = pp(file=fff, var="zdtlw", t=time_step, x="-180,180", verbose=True, changetime="correctls").getf() Q = zdtsw + zdtlw
tint=[["0.25,1.5"],["0.25,5.5"],["0.25,10.5"]] #Time must be as written in the input file zint=[["0.1,10"],["0.1,10"],["0.1,10"]] #alt in km xarea="-180,180" yarea="-90,90" step=5 var="u" #variable ############################ x=np.zeros(nb_dataset,dtype='object') #object of all datasets bornemax=0. # initialisation boundary values bornemin=0. for i in range(nb_dataset): myvar = pp(file=filename,var=var,t=tint[i],z=zint[i],x=xarea,y=yarea,compute="nothing").getf() # get data to be changed according to selected variable data=np.ravel(myvar) x[i]=np.array(data) #upper lower bounds: maxval=np.amax(myvar) romax=round(maxval,0) if abs(romax/maxval) < 1: romax=romax+1 minval=np.amin(myvar) romin=round(minval,0) if abs(romin/minval) < 1: romin=romin-1 bornemax=np.amax([romax,bornemax]) bornemin=np.amin([romin,bornemin])
import scipy.stats import matplotlib.pyplot as plt import math as m # arguments from optparse import OptionParser ### TBR by argparse parser = OptionParser() (opt, args) = parser.parse_args() if len(args) == 0: args = "histmth.nc" fi = args # Choix des donnees #------------------------------------------------------------------ month = 1. # numero du mois tt = 86400. * 30. * (month + 0.5) windvel, x, y, z, t = pp(file=fi, var="wind10m", t=tt).getfd() slp = pp(file=fi, var="slp", t=tt).getf() u10m = pp(file=fi, var="u10m", t=tt).getf() v10m = pp(file=fi, var="v10m", t=tt).getf() slp = slp / 1E2 contfrac = pp(file=fi, var="contfracATM").getf() #------------------------------------------------------------------ # Pour tracer des cartes #------------------------------------------------------------------ p = plot2d() p.f = slp p.c = contfrac p.x = x p.y = y p.fmt = "%.2f"
#! /usr/bin/env python from ppclass import pp thres = 0.1 ww = pp() ww.xp = 24 ww.yp = 12 ww.file = "tata.nc" ww.var = "E366" ww.useindex = "1000" ww.z = 0 ww.proj = "cyl" ww.out = "jpg" #"png" ww.res = 100 #150 #300 #75 ww.fmt = "%.0f" ww.colorbar = "gist_gray" ww.quiet = True ww.showcb = False ww.div = 50 #10 #30 ww.vmin = -thres ww.vmax = 1 #ww.trans = 0.5 ww.back = "blue_local" ww.nopickle = True # loop nn=360 nn=25 tabcase = ["full","np","sp","trop"] tabcase = ["full"]
#! /usr/bin/env python from ppclass import pp ww = pp() ww.file = "series30m_1km.nc" ww.var = ["HGT","Um","Vm","TSURF","Um","Vm"] ww.vargoal = ["main","vector","vector","main","vector","vector"] ww.z = 0. #ww.vmin = [-6500.,150.] #does not work #ww.vmax = [-1500.,300.] #does not work ww.proj = "npstere" ww.blat = 67. #ww.title = ["topo+winds","surftemp+winds"] #does not work ww.out = "png" ww.includedate = False ww.res = 75 ww.wscale = 10. ww.svx = 3 ww.svy = 3 ww.quiet = True # loop count = 0 for ttt in range(474): print count ww.filename = "mov"+"%03d"%(count) ww.t = ttt ww.getdefineplot() ww.p[0].vmin = -6500. ww.p[0].vmax = -1500. ww.p[1].vmin = 140.
################################################################## ################################################################## files = ["diagfi_start150.nc","diagfi_start175.nc","diagfi_start200.nc"] labs = ['$T_{ini}=150$ K','$T_{ini}=175$ K','$T_{ini}=200$ K'] name = "profile_tini" #files = ["diagfi_start200.nc","diagfi_start200_Rayleigh.nc","diagfi_start200_A034.nc"] #labs = ['ref ($T_{ini}=200$ K)','ref + Rayleigh scatt.','ref + $A_{surf} = 0.34$'] #name = "profile_tests" ################################################################## ################################################################## # OK retrieve pressure and temperatures press = pp(file=files,var="p",x=0,y=0,t=1.e15).get() temp = pp(file=files,var="temp",x=0,y=0,t=1.e15).get() # this must be done before the next step # ... because the next step is doing defineplot temp.superpose = True #temp.out = "png" temp.filename = name temp.includedate = False temp.colorbar = "hot" # this is doing defineplot amongst other things temp.func(press) # customize plots count=0
#! /usr/bin/env python from ppclass import pp anewversion = pp() anewversion.defineplot(loadfile="../../demo_data/gw.ppobj") for plot in anewversion.p: plot.colorbar = "Paired" plot.title = "Psychedelic plot!" anewversion.makeplot()
#! /usr/bin/env python from ppclass import pp ###### gcm = pp() gcm.file = "amipYEAR/IPSL-CM5A-MR.nc" gcm.var = "rlut" gcm.t = 1 # gcm.out = "pdf" gcm.filename = "atlas" gcm.back = "coast" gcm.proj = "robin" gcm.fmt = "%.0f" gcm.div = 20 gcm.vmin = 100 gcm.vmax = 300 gcm.colorbar = "hot" gcm.title = "OLR (GCM)" gcm.units = r'W m$^{-2}$' # gcm.getplot(extraplot=3) ###### obs = pp() obs << gcm obs.file = "amipYEAR/OBS.nc" obs.plotin = gcm obs.title = "OLR (OBS)" obs.getplot()
#! /usr/bin/env python from ppclass import pp tsurf = pp() tsurf.file = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" tsurf.var = "tsurf" tsurf.x = None tsurf.y = 10. tsurf.t = 2. tsurf.getdefineplot() ps = pp() ps << tsurf ps.var = "ps" ps.getdefineplot() S = ps.func(tsurf) S.p[0].linestyle="" S.p[0].marker="h" S.p[0].color="g" S.makeplot() icetot = pp() icetot << tsurf icetot.var = "icetot" icetot.getdefineplot() S2 = icetot.func(tsurf) S2.p[0].linestyle="" S2.p[0].marker="D" S2.p[0].color="r"
parser = OptionParser() (opt,args) = parser.parse_args() if len(args) == 0: args = "resultat.nc" fi=args #t = pp(var="tsurf",file=fi,x="-180,180",y=-80,superpose=True,quiet=True,ylabel=r'surface temperature ($^{\circ}$C)',legend="lat=-80",changetime="correctls",fmt="%.1f").get()-273.15 #t.plot(extraplot=3) #t2 = pp(var="tsurf",file=fi,x="-180,180",y=-60,superpose=True,quiet=True,ylabel=r'surface temperature ($^{\circ}$C)',legend="lat=-60",plotin=t,changetime="correctls",fmt="%.1f").get()-273.15 #t2.plot() #t2 = pp(var="tsurf",file=fi,x="-180,180",y=-20,superpose=True,quiet=True,ylabel=r'surface temperature ($^{\circ}$C)',legend="lat=-20",plotin=t,changetime="correctls",fmt="%.1f").get()-273.15 #t2.plot() #t2 = pp(var="tsurf",file=fi,x="-180,180",y=0,superpose=True,quiet=True,ylabel=r'surface temperature ($^{\circ}$C)',legend="lat=0",plotin=t,changetime="correctls",fmt="%.1f").get()-273.15 #t2.plot() t = pp() t.var = "tsurf" t.file = fi t.x = "-180,180" t.y = -80 ## latitude t.superpose = True t.quiet = True t.ylabel = r'surface temperature ($^{\circ}$C)' t.legend = "lat="+str(t.y) t.changetime = "correctls" t.fmt="%.1f" t.ymin = -100. t.ymax = 60. t = t.get() - 273.15 t.plot(extraplot=3)
def finddd(filefile,\ timelist=None,\ dt_out=50.,\ lt_start=8.,\ halolim=None,\ method=1,\ plotplot=False,\ filewind=None,\ filemean=None,\ save=True): if method == 3: print "importing additional scikit-image packages" from skimage import filter,transform,feature import matplotlib.patches as mpatches from scipy import ndimage ############################################################################### ########################## FOR METHOD 1 FOR METHOD 2 ########################## ## FACLIST : how many sigmas below mean we start to consider this could be a vortex ## ... < 3.0 dubious low-intensity minima are caught ## ... 3 ~ 3.1 is a bit too low but helps? because size of pressure drop could be an underestimate of actual dust devil ## ... 3.2 ~ 3.3 is probably right, this is the one we choose for exploration [3.25] ## ... NB: values 3.2 to 3.6 yields the same number of devils but measured sizes could vary a bit ## ... > 3.6 makes strong minima disappear... especially >3.8 ## ... EVENTUALLY 3.5-4 is better for problematic cases ############################################################################### faclist = [3.75] ################################ FOR ALL METHODS ## (see below) NEIGHBOR_FAC is the multiple of std used to evaluate size #### METHOD 1 #neighbor_fac = 2.7 ## --> 1: limit not discriminative enough. plus does not separate neighbouring vortices. ## ... but interesting: gives an exponential law (because vortices are artificially merged?) ## --> 2.7: very good for method 1. corresponds usually to ~0.3 ## --> 2: so-so. do not know what to think. but usually too low. #### METHOD 3 --> optimizing neighbor_fac with visual checks and superimposing wind friction (max must be at boundaries) ##neighbor_fac = 1.5 # too low --> vortices too large + false positives neighbor_fac = 2.7 # optimal --> good for separation, only a slight underestimation of size ##neighbor_fac = 3.0 # too high --> excellent for separation, but size quite underestimated ############################################################################### ############################################################################### ############################################################################### ############################################################################### if save: myfile1 = open(filefile+'m'+str(method)+'_'+'1.txt', 'w') myfile2 = open(filefile+'m'+str(method)+'_'+'2.txt', 'w') ############################################################################### ############################################################################### ## get the resolution within the file dx = ncattr(filefile,'DX') ; print "resolution in meters is: ",dx ## if no halolim is given, guess it from resolution if halolim is None: extentlim = 2000. # the putative maximum extent of a vortex in m halolim = extentlim / dx print "maximum halo size is: ",halolim ## mean and std calculations ## -- std is used in both methods for limits ## -- mean is only used in method 1 print "calculate mean and std, please wait." ## -- get time series of 2D surface pressure ## -- (a different file to calculate mean might be provided) if filemean is None: psfc = pp(file=filefile,var="PSFC",verbose=True).getf() else: psfc = pp(file=filemean,var="PSFC",verbose=True).getf() ## -- calculate mean and standard deviation ## -- ... calculating std at all time is not right! ## -- ... for mean value though, similar results with both methods mean = np.mean(psfc,dtype=np.float64) std = np.std(psfc,dtype=np.float64) damax = np.max(psfc) damin = np.min(psfc) ## some information about inferred limits print "**************************************************************" print "MEAN",mean print "STD",std print "LIMIT FOR PRESSURE MINIMUM:",-np.array(faclist)*std print "LIMIT FOR EVALUATING SIZE OF A GIVEN LOCAL MINIMUM",-neighbor_fac*std print "**************************************************************" # if no timelist is given, take them all if timelist is None: test = netCDF4.Dataset(filefile) sizet = len(test.dimensions['Time']) print "treat all time values: ",sizet timelist = range(0,sizet-1,1) ## LOOP ON TIME for time in timelist: ## get 2D surface pressure at a given time ## (this is actually so quick we don't use psfc above) psfc2d = pp(file=filefile,var="PSFC",t=time).getf() if filewind is not None: ustm = pp(file=filewind,var="USTM",t=time).getf() ## MAIN ANALYSIS. LOOP ON FAC. OR METHOD. for fac in faclist: ###fac = 3.75 ###for method in [2,1]: ## initialize arrays tabij = [] ; tabsize = [] ; tabdrop = [] tabijcenter = [] ; tabijvortex = [] ; tabdim = [] tabwind = [] ################ FIND RELEVANT POINTS TO BE ANALYZED ## lab is 1 for points to be treated by minimum_position routine ## we set elements at 1 where pressure is under mean-fac*std ## otherwise we set to 0 because this means we are close enough to mean pressure (background) lab = np.zeros(psfc2d.shape) if method == 1: # method 1: standard deviation lab[np.where(psfc2d < mean-fac*std)] = 1 elif method == 2: # method 2: polynomial fit # ... tried smooth but too difficult, not accurate and too expensive deg = 5 #plutot bien (deg 10 ~pareil) mais loupe les gros (~conv cell) #deg = 2 #pas mal mais false positive (pareil 3-4 mm si un peu mieux) # #(OK now with fixing the false positive bug) nx = psfc2d.shape[1] ; ny = psfc2d.shape[0] xxx = np.array(range(nx)) ; yyy = np.array(range(ny)) anopsfc2d = psfc2d*0. ; polypsfc2d = psfc2d*0. for iii in range(0,nx,1): poly = np.poly1d(np.polyfit(yyy,psfc2d[iii,:],deg)) polypsfc2d[iii,:] = poly(yyy) for jjj in range(0,ny,1): poly = np.poly1d(np.polyfit(xxx,psfc2d[:,jjj],deg)) polypsfc2d[:,jjj] = 0.5*polypsfc2d[:,jjj] + 0.5*poly(xxx) ## smooth a little to avoid 'crosses' (plus, this removes PBC problems) polypsfc2d = ppcompute.smooth2diter(polypsfc2d,n=deg) # compute anomaly and find points to be explored anopsfc2d = psfc2d - polypsfc2d limlim = fac*std ## same as method 1 lab[np.where(anopsfc2d < -limlim)] = 1 elif method == 3: # method 3 : find centers of circle features using image processing techniques # initialize the array containing point to be further analyzed lab = np.zeros(psfc2d.shape) # enclose computations in a test to save time when no obvious vortices datab = psfc2d[np.where(psfc2d < mean-fac*std)] #datab = np.array([42]) #uncomment this to always include search! if datab.shape[0] == 0: ### if no point has significantly lower value than mean ### well, no need to do anything, keep lab filled with 0 pass else: ### field to analyze: pressure ### --- apply a Laplace transform to highlight drops field = ndimage.laplace(psfc2d) ### prepare the field to be analyzed ### by the Hough transform or Blob detection ### --> normalize it in an interval [-1,1] ### --> NB: dasigma serves later for Hough transform ### --> NB: polynomial de-trending does not seem to help # ... test 1. local max / min used for normalization. mmax = np.max(field) ; mmin = np.min(field) ; dasigma = 2.5 ## ... test 2. global max / min used for normalization. bof. #mmax = damax ; mmin = damin ; dasigma = 1.0 #1.5 trop restrictif spec = 2.*((field-mmin)/(mmax-mmin) - 0.5) #### **** BLOB DETECTION **** #### Better than Hough transform for multiple adjacent vortices #### log: best / dog or doh: miss small vortices, hence the majority #### SITE: http://scikit-image.org/docs/dev/auto_examples/plot_blob.html #### PUBLISHED: https://peerj.com/articles/453/ ### -------------------------------------------- ### the parameters below are aimed for efficiency ### ... because anyway the actual size is not detected ### ... so setting max_sigma to a high value is not needed ### -------------------------------------------- blobs = feature.blob_log(spec, max_sigma=3, num_sigma=3, threshold=0.05) ### a plot to check detection if plotplot: fig, ax = mpl.subplots(1, 1) what_I_plot = psfc2d #spec #field ax.imshow(what_I_plot, cmap=mpl.cm.gray) ### store the detected points in lab for blob in blobs: center_x, center_y, r = blob #lab[center_x,center_y] = 1 # a test for faster calculations (at the expense of missing 1% vortices maybe) if psfc2d[center_x,center_y] < mean-fac*std: lab[center_x,center_y] = 1 if plotplot: circ = mpatches.Circle((center_y, center_x), r*np.sqrt(2), fill=False, edgecolor='green', linewidth=2) ax.add_patch(circ) if plotplot: mpl.show() #################################### BEGIN TEST HOUGH TRANSFORM # # perform an edge detection on the field # # ... returns an array with True on edges and False outside # # http://sciunto.wordpress.com/2013/03/01/detection-de-cercles-par-une-transformation-de-hough-dans-scikit-image/ # edges = filter.canny(filter.sobel(spec),sigma=dasigma) # # initialize plot for checks # if plotplot: # fig, ax = mpl.subplots(ncols=1, nrows=1, figsize=(10,8)) # ax.imshow(field, cmap=mpl.cm.gray) # ## detect circle with radius 3dx. works well. 5dx detection pretty similar. # ## use an Hough circle transform # radii = np.array([2,3]) # hough_res = transform.hough_circle(edges, radii) # # analyze results of the Hough transform # nnn = 0 # sigselec = neighbor_fac # #sigselec = 3. # for radius, h in zip(radii, hough_res): # # number of circle features to keep # # ... quite large. but we want to be sure not to miss anything. # nup = 30 # maxima = feature.peak_local_max(h, num_peaks=nup) # # loop on detected circle features # for maximum in maxima: # center_x, center_y = maximum #- radii.max() # # nup is quite high so there are false positives. # # ... but those are easy to detect # # ... if pressure drop is unclear (or inexistent) # # ... we do not take the point into account for further analysis # # ... NB: for inspection give red vs. green color to displayed circles # diag = field[center_x,center_y] - (mean-sigselec*std) # ## uncomment below to keep all detections # #diag = -1 # if diag < 0: # col = 'green' # nnn = nnn + 1 # lab[center_x,center_y] = 1 # else: # col = 'red' # # draw circles # if plotplot: # circ = mpatches.Circle((center_y, center_x), radius,fill=False, edgecolor=col, linewidth=2) # ax.add_patch(circ) # if plotplot: # mpl.title(str(nnn)+" vortices") # if nnn>0: mpl.show() # mpl.close() #################################### END TEST HOUGH TRANSFORM ## while there are still points to be analyzed... while 1 in lab: ## ... get the point with the minimum field values ## ... within values of field at labels lab if method == 1 or method == 3: ij = minimum_position(psfc2d,labels=lab) elif method == 2: ij = minimum_position(anopsfc2d,labels=lab) ## ... store the indexes of the point in tabij tabij.append(ij) ## ... remove the point from labels to be further explored by minimum_position lab[ij] = 0 ################ GET SIZES BASED ON THOSE FOUND POINTS ## reslab is the same as lab ## except for scanning purpose we keep the information ## about how went the detection ## --> and we set a lower fac ## --> above a high fac is good to catch only strong vortices ## --> but here a casual fac=3 is better to get accurate sizes ## --> or even lower as shown by plotting reslab reslab = np.zeros(psfc2d.shape) #reslabf = np.zeros(psfc2d.shape) # TESTS if method == 1 or method == 3: reslab[np.where(psfc2d < mean-neighbor_fac*std)] = 1 #reslabf[np.where(psfc2d < mean-neighbor_fac_fine*std)] = 1 # TESTS elif method == 2: reslab[np.where(anopsfc2d < -neighbor_fac*std)] = 1 ## initialize halomax and while loop ## HALOMAX : maximum halo defined around a minima to evaluate the size ## ... halomax must be large enough to encompass a vortex ## ... but not too large otherwise neighboring vortex are caught halomax = 3 ; notconv = 9999 ; yorgl = 9999 ## WHILE LOOP on HALOMAX exploration while ( notconv > 0 and halomax < halolim and yorgl != 0 ): # now browse through all points caught in previous loop for ij in tabij: ## ... OK. take each indexes found before with minimum_position i,j = ij[0],ij[1] ## EITHER ## ... if reslab is already 0, we do not have to do anything ## ... because this means point is already part of detected vortex ## OR ## ... if the ij couple is already in a previously detected vortex ## ... we don't actually need to consider it again ## ... this is necessary otherwise (sometimes a lot) of false positives if reslab[i,j] <= 0 or ij in tabijvortex: pass else: ## GET HALOS. SEE FUNCTION ABOVE. nmesh,maxw,maxh,reslab,tabijvortex=gethalo(ij,reslab,halomax,tabijvortex) ## OK. check this is actually a vortex. ## get the size. get the drop. ## store results in file if nmesh is not None: ## calculate size ## we multiply by mesh area, then square to get approx. size of vortex ## [if one wants to obtain equivalent diameter, multiply by 2.*np.sqrt(np.pi)] size = np.sqrt(nmesh*dx*dx) ## check size. if not OK recompute halo with more stringent zone around pressure minimum. ## -- NB: reslab and tabijvortex do not need to be changed again, was done just before ## -- however, we could have been a little bit more subtle to disentangle twin vortices # if (np.abs(maxw-maxh)*dx/size > 0.33): # #if (np.sqrt(maxw*maxh*dx*dx) > size): # #print "asymmetry!",np.abs(maxw-maxh)*dx,size # nmesh,maxw,maxh,dummy,dummy=gethalo(ij,reslabf,halomax,tabijvortex) # if nmesh is not None: size = int(np.sqrt(nmesh*dx*dx)) # #print "new values",np.abs(maxw-maxh)*dx,size ## calculate drop. if method == 1 or method == 3: drop = -psfc2d[i,j]+mean else: drop = -anopsfc2d[i,j] ############################################################# ##### Check this is the actual minimum (only tested so far with method=3) #if method == 1 or method ==3: # ## ... define a halo around the minimum point # ix,ax,iy,ay = i-maxw,i+maxw+1,j-maxh,j+maxh+1 # ## ... treat the boundary case (TBD: periodic boundary conditions) # nx = reslab.shape[1] ; ny = reslab.shape[0] # if ix < 0: ix = 0 # if iy < 0: iy = 0 # if ax > nx: ax = nx # if ay > ny: ay = ny # ## ... keep real minimal value # ## DOMAINMIN --> does not change a lot results (not worth it) # domainmin = np.max(-psfc2d[ix:ax,iy:ay])+mean # if drop < domainmin: # print "corrected drop",drop,domainmin # drop = domainmin # ### DOMAINDROP --> leads to underestimate drops in most cases # #domaindrop = np.max(psfc2d[ix:ax,iy:ay])-np.min(psfc2d[ix:ax,iy:ay]) # #drop = domaindrop ############################################################# ## if available get info on friction velocity if filewind is not None: ## ... define a halo around the minimum point ix,ax,iy,ay = i-maxw,i+maxw+1,j-maxh,j+maxh+1 ## ... treat the boundary case (TBD: periodic boundary conditions) nx = reslab.shape[1] ; ny = reslab.shape[0] if ix < 0: ix = 0 if iy < 0: iy = 0 if ax > nx: ax = nx if ay > ny: ay = ny ## WINDMAX windmax = np.max(ustm[ix:ax,iy:ay]) tabwind.append(windmax) else: tabwind.append(0.) ## store info in dedicated arrays tabdim.append((maxw*dx,maxh*dx)) tabsize.append(size) tabdrop.append(drop) tabijcenter.append(ij) #print "... VORTEX!!!! size %.0f drop %.1f coord %.0f %.0f" % (size,drop,i,j) ## count how many points are not converged and left to be analyzed notconv = len(np.where(reslab > 1)[0]) yorgl = len(np.where(reslab == 1)[0]) ## increment halomax ## to speed-up the increment is slightly increasing with considered halomax halomax = halomax + halomax / 2 ## just for simpler plots. reslab[reslab > 2] = 4 reslab[reslab < -2] = -4 ## give some info to the user if len(tabsize) > 0: nvortex = len(tabsize) maxsize = np.max(tabsize) maxdrop = np.max(tabdrop) maxwind = np.max(tabwind) else: nvortex = 0 maxsize = 0 maxdrop = 0. maxwind = 0. notconv = len(np.where(reslab > 1)[0]) print "t=%3.0f / n=%2.0f / s_max=%4.0f / d_max=%4.1f / halo_out=%3.0f / notconvp=%3.1f / wind=%4.1f" \ % (time,nvortex,maxsize,maxdrop,halomax,100.*notconv/float(reslab.size),maxwind) ## save results in a text file if save: # convert t in local time ttt = lt_start + time*dt_out/3700. # write files myfile2.write( "%7.4f ; %5.0f ; %6.1f ; %8.3f ; %8.3f\n" % (ttt,nvortex,maxsize,maxdrop,maxwind) ) for iii in range(len(tabsize)): myfile1.write( "%7.4f ; %6.1f ; %8.3f ; %5.0f ; %5.0f ; %8.3f\n" \ % (ttt,tabsize[iii],tabdrop[iii],tabdim[iii][0],tabdim[iii][1],tabwind[iii]) ) #### PLOT PLOT PLOT PLOT damaxsize = 10000. #damaxsize = 400. if (nvortex>0 and plotplot) or (nvortex>0 and maxsize > damaxsize): #if nvortex > 200: mpl.figure(figsize=(12,8)) myplot = plot2d() myplot.x = np.array(range(psfc2d.shape[1]))*dx/1000. myplot.y = np.array(range(psfc2d.shape[0]))*dx/1000. myplot.title = str(nvortex)+" vortices found (indicated diameter / pressure drop)" myplot.xlabel = "x distance (km)" myplot.ylabel = "y distance (km)" if method != 2: #myplot.f = ustm myplot.f = psfc2d #myplot.vmin = damin #myplot.vmax = damax myplot.vmin = mean - 6.*std myplot.vmax = mean + 6.*std else: myplot.field = anopsfc2d myplot.vmin = -1.5 myplot.vmax = 0.5 myplot.fmt = "%.1f" myplot.div = 20 myplot.colorbar = "spectral" myplot.make() ### ANNOTATIONS for iii in range(len(tabsize)): ij = tabijcenter[iii] coord1 = ij[1]*dx/1000. coord2 = ij[0]*dx/1000. txt = "%.0f/%.2f/%.0f" % (tabsize[iii],tabdrop[iii],100*np.abs(tabdim[iii][0]-tabdim[iii][1])/tabsize[iii]) txt = "%.0f m / %.2f Pa" % (tabsize[iii],tabdrop[iii]) mpl.annotate(txt,xy=(coord1,coord2), xytext=(-10,-30),textcoords='offset points',ha='center',va='bottom',\ bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3),\ arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.3',color='red'),\ size='small') ###show detection lev = [-4,-2,-1,0,1,2,4] ## all colours for detection cases lev = [-1,0] # show dubious areas as detection areas lev = [-1,1] # show dubious areas as no-detection areas mpl.contourf(myplot.x,myplot.y,reslab,alpha=0.9,cmap=mpl.cm.get_cmap("binary_r"),levels=lev) ### SHOW OR SAVE IN FILE mpl.show() #save(mode="png",filename="detectm"+"_"+str(time)+"_"+str(method),folder="detect/",includedate=False) ## close data files if save: myfile1.close() myfile2.close()
## options from optparse import OptionParser ### TBR by argparse parser = OptionParser() parser.usage = "les.py netCDF_file(s)" #les.py becomes a commandline applicable to a netcdf file (opt,files) = parser.parse_args() ## constants t0 = 220. p0 = 610. r_cp = 1.0/4.4 grav = 3.72 R = 192. ## dimensions foo1,foo2,foo3,z,t = pp(file=files[0],var="T",x=0,y=0).getfd() nz,nt = z.size,t.size nf = len(files) print nf ntt = nt*nf ## arrays for time series tprimemean,tmean = np.zeros([ntt,nz]),np.zeros([ntt,nz]) wprimemean,wmean = np.zeros([ntt,nz]),np.zeros([ntt,nz]) wmax = np.zeros([ntt,nz]) vehfmean = np.zeros([ntt,nz]) pblh,pblh1,pblh2,pblh3 = np.zeros(ntt),np.zeros(ntt),np.zeros(ntt),np.zeros(ntt) ## loop indt = -1
import numpy as np import planets #################################################### myplanet = planets.Saturn rad = myplanet.a #################################################### #fff = "DRAG90days_DISSIP10000_year8_1842401736_512_z5" fff = "DRAG90days_DISSIP10000_year9_z5_256_every20d_278921160-316973159" uuu,vvv = "u","v" ttt = 1 zzz = 1.5e5 ##################################################### # get wind fields u,lon,lat,foo,foo = pp(file=fff+".nc",var="u",t=ttt,z=zzz,compute="pert_x").getfd() v = pp(file=fff+".nc",var="v",t=ttt,z=zzz,compute="pert_x").getf() #temp = pp(file=fff+".nc",var="temp",t=ttt,z=zzz,compute="pert_x").getf() # work out the pole problem # -- spurious high values if extrem lati close to +/-90 ny,nx = u.shape u,v = u[1:ny-2,:],v[1:ny-2,:] lonsave,latsave = lon,lat lon,lat = lon[1:ny-2,:],lat[1:ny-2,:] ######################################### # compute vorticity and divergence div, vorti = divort(u,v,lon,lat,rad) #########################################
#! /usr/bin/env python from ppclass import pp prof = pp() prof.verbose = True #prof.file = "/home/aymeric/Big_Data/case_night.nc" prof.file = "/home/aymeric/Big_Data/GALE/wrfout_d03_2024-06-09_00:00:00_z" prof.var = "tk" prof.t = [10., 20.] prof.x = -5. #30 prof.y = 138. #30 prof.filename = "vertpress" prof.get() prof.superpose = True prof.defineplot() prof.p[0].logy = True prof.makeplot() ## a small workaround if one wants to change axis names ## (it is difficult because of swapping axis) prof.p[0].swaplab = False prof.p[0].xlabel = "Temperature (K)" prof.p[0].ylabel = "Pressure (Pa)" prof.makeplot()
#! /usr/bin/env python from ppclass import pp # define object p = pp() # define file, variable, slice p.file = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" p.var = "icetot" p.t = 0.5 # get field. convert from kg m-2 to pr_mic p.get() p = 1000. * p # customize plot # -- map projection, background image p.proj = "robin" p.back = "vishires" p.trans = 0.5 # -- title, colorbar p.title = 'Water ice clouds on Mars' p.units = "pr-$\mu$m" p.colorbar = "spectral" p.vmin = 0. p.vmax = 8. p.div = 32 p.fmt = '%.1f' # -- save info p.filename = "weblowres" p.includedate = False
if opt.var is None: for filename in files: inspect(filename) exit() ###################################### # use ppclass to get field and plot it ###################################### # treat the case of additional vectors or contours (contours must be before vectors) var = [] ; vargoal = [] for element in opt.var: var.append(element) ; vargoal.append("main") if opt.contour is not None: var.append(opt.contour) ; vargoal.append("contour") if opt.vecx is not None: var.append(opt.vecx) ; vargoal.append("vector") if opt.vecy is not None: var.append(opt.vecy) ; vargoal.append("vector") # set pp object user = pp() user.file = files user.var = var ; user.vargoal = vargoal user.x = opt.x ; user.y = opt.y user.z = opt.z ; user.t = opt.t user.verbose = opt.verbose if not user.verbose: user.quiet = True user.compute = opt.compute user.changetime = opt.changetime user.useindex = opt.useindex user.sx = opt.sx ; user.sy = opt.sy user.sz = opt.sz ; user.st = opt.st user.svx = opt.svx ; user.svy = opt.svy user.savtxt = opt.savtxt if opt.xp is not None: user.xp = opt.xp if opt.yp is not None: user.yp = opt.yp
#! /usr/bin/env python from ppclass import pp import planets import ppplot fi = "DRAG90days_DISSIP10000_year7_912791376_512_z5" u,lon,lat,p,t = pp(file=fi+".nc",var="u",t=0,z=0,x="-180,180").getfd() # index = acosphi*((omega*acosphi)+u) / (omega*a*a) sindex = planets.Saturn.superrot(u=u,lat=lat) pl = ppplot.plot1d() pl.f = sindex*1000. pl.x = lat pl.ylabel = r'Local superrotation index $s = \mathcal{M}_u / \Omega a^2$ ($\times 10^{-3}$)' pl.xmin = -10. pl.xmax = 10. pl.fmt = '%.0f' pl.ymin = -30. pl.ymax = 10. pl.marker = '' pl.xlabel = "Latitude (deg)" pl.make() ppplot.save(mode="png",filename=fi+"_superrot")
#! /usr/bin/env python from ppclass import pp var1 = pp(\ file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",\ var="ps",\ x=None,\ y=10.,\ t=2.) var1.get() var2 = pp(\ file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",\ var="phisinit",\ x=None,\ y=10.,\ t=2.) var2.get() var2 = var2 / 3.72 S = var2.func(var1) S.p[0].marker = 'o' S.p[0].linestyle = '' S.p[0].ylabel = "Surface geopotential height (km)" S.p[0].ycoeff = 1./1000. S.p[0].fmt = '%.0f' S.filename = "function" S.makeplot()
# * Script header # * Import `pp` object from `ppclass` # * Define a `pp` object named `ex` # (and make it quiet) # * Define attributes # - netCDF file to read # - variable to read # - value on y axis # - value on z axis # * Get data from netCDF file + Make plot # In[16]: #! /usr/bin/env python from ppclass import pp ex = pp() ex.quiet = True ex.file = 'diagfired.nc' ex.var = 'temp' ex.y = 15. ex.z = 75. ex.getplot() # Here is an example on how to customize this plot # In[17]: ex.title = r'Hovmoller plot for $T_{75km}$' ex.xcoeff = 24. ex.xlabel = 'Time (hours)' ex.ylabel = 'Altitude (km)'
#! /usr/bin/env python from ppclass import pp import matplotlib.pyplot as mpl import numpy as np icetot = pp(file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",var="icetot",t="0.5,2.5",compute="nothing").getf() mpl.hist(np.ravel(icetot)) mpl.show()
#! /usr/bin/env python from ppclass import pp fi = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" v = ["ps","phisinit"] vg = ["main","contour"] meanps = pp(file=fi,var=v,vargoal=vg,t="0,1").get() waveref = pp(file=fi,var=v,vargoal=vg,t=0.5).get() - meanps waveref.smooth(5) waveref.title = "$p_s$ diurnal anomaly" waveref.proj = "moll" waveref.vmin = -10 waveref.vmax = 10 waveref.div = 10 waveref.filename = "tide" waveref.plot(extraplot=3) eqmeanps = pp(file=fi,var="ps",t="0,1",y=0.).get() addplot = pp(file=fi,var="ps",t=0.5,y=0.).get() - eqmeanps addplot.plotin = waveref addplot.title = "Tide signal at the equator" addplot.ylabel = "$p_s$ diurnal anomaly (Pa)" addplot.linestyle = "" addplot.marker = "." addplot.plot() for choice_t in [0.6,0.7]: wave = pp(file=fi,var=v,vargoal=vg,t=choice_t).get() - meanps wave << waveref
#! /usr/bin/env python from ppclass import pp prof = pp() prof.verbose = True #prof.file = "/home/aymeric/Big_Data/case_night.nc" prof.file = "/home/aymeric/Big_Data/GALE/wrfout_d03_2024-06-09_00:00:00_z" prof.var = "tk" prof.t = [10.,20.] prof.x = -5. #30 prof.y = 138. #30 prof.filename = "vertpress" prof.get() prof.superpose = True prof.defineplot() prof.p[0].logy = True prof.makeplot() ## a small workaround if one wants to change axis names ## (it is difficult because of swapping axis) prof.p[0].swaplab = False prof.p[0].xlabel = "Temperature (K)" prof.p[0].ylabel = "Pressure (Pa)" prof.makeplot()
#! /usr/bin/env python from ppclass import pp brief = pp() brief.file = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" brief.define()
#! /usr/bin/env python from ppclass import pp ### LMD simulation results ### ---------------------- ### set object lmdu = pp() ### set file var coord lmdu.file = 'LMD/wrfout_d01_2024-09-08_01:00:00_z' lmdu.var = 'Um' lmdu.x = -6. lmdu.y = -2. lmdu.t = 0. ### get data lmdu.get() ### MRAMS simulation results ### ------------------------ ### set object mramsu = pp() ### get attributes from lmd object mramsu << lmdu ### OK just change what changes in MRAMS mramsu.file = 'MRAMS/mramsout_d01_2024-09-08_01:00:00_z' mramsu.var = 'u_areo' ### get data mramsu.get() ### THE SAME BUT FOR V ### ------------------ lmdv = pp()
etape(varname,time0) return #################################################### #################################################### #################################################### #################################################### #lstab = pp(file=fileAP,var="ls",x=0,y=0,z=0).getf() #lstab = lstab*180./np.pi #lstab = fix_time_axis(lstab,360.) # in years #################################################### time0 = time.time() psbc = pp(file=fileAP,var="ps",t="0,1e10",x=charx).getf() ny = psbc.shape[0] ap,bp = np.loadtxt("apbp.txt",unpack=True) nz = len(ap) aps = 0.5*(ap[0:nz-1]+ap[1:nz]) bps = 0.5*(bp[0:nz-1]+bp[1:nz]) nz = len(aps) press = np.zeros((nz,ny)) for kk in range(nz): for yy in range(ny): press[kk,yy] = aps[kk]+bps[kk]*psbc[yy] ####################################################
#! /usr/bin/env python from ppclass import pp pp(file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc", var="u", t="0.5", z="10").getplot()
#! /usr/bin/env python from ppclass import pp ### Active Clouds ### ------------- act = pp() act.file = "/planeto/tnalmd/runs/newref/MY26.ifort.modelprecise/monthlybox/concat_LT14_P.nc" act.var = "temp" act.x = "-180,180" act.y = "-20,20" act.z = 50.0 ###### Change time axis from Sols to Ls: act.changetime = "mars_sol2ls" act.label = "GCM active clouds" act.title = "Equatorial daytime temperature at 50 Pa" act.marker = "-" act.color = "g" act.out = "png" act.get() ### Inactive Clouds ### --------------- inac = pp() inac << act inac.file = "/planeto/tnalmd/runs/newref/MY26.inac/monthlybox/concat_LT14_P.nc" inac.label = "GCM inactive clouds" inac.marker = "" inac.color = "r" inac.get()
### Petite fonction utilisee plus tard pour convertir les tableaux DYNAMICO dans la taille de ceux radiatif (Cherche l indice de la valeur lat la plus proche de celle prise) def find_x(array, x): y = int(np.argmin(np.abs(np.ceil(array[None].T - x)), axis=0)) return int(y) ###Initialisation du domaine, des profils vertical et latitudinal + caracteristiques planete #Recuperation des coefficients pour calculer le champ de pression 2D coeffbp = loadtxt("coeffbp.txt", delimiter=",") fff = "../simulations_dynamiques/Xhistins_195.nc" time_step = 300 #"761040,500000000" #309 #"420,500" "360,420" ### VARIABLES DYNAMICO lsub = pp(file=fff, var="ls", x=0, y=0, verbose=True).getf() ls = (lsub / np.pi) * 180. u, lon, lat, zmod, t = pp(file=fff, var="u", t=time_step, x="-180,180", verbose=True).getfd() v, lon, lat, zmod, t = pp(file=fff, var="v", t=time_step, x="-180,180", verbose=True).getfd() temp, lon, lat, zmod, t = pp(file=fff, var="temperature", t=time_step, x="-180,180",
import numpy as np from ppclass import pp import ppplot shiftday = 258 + 27 shiftday = 258 ### GET COORDINATES lines = open("input_coord", "r").readlines() lon = float(split(lines[0])[0]) ; lat = float(split(lines[1])[0]) xdate = float(split(lines[2])[0]) ; loct = float(split(lines[3])[0]) utc = loct - lon/15. ### GCM req = pp() req.file = "diagfi.nc" req.var = "vmr_h2ovap" req.var = "temp" req.x = lon req.y = lat req.t = shiftday + utc/24. req.verbose = True req.changetime = "mars_dayini" #prof,xx,yy,zz,tt = req.getfd() ### MCD z,tpot,q,u,v = np.loadtxt("input_sounding",skiprows=1,unpack=True) r,cp,p,rho,t = np.loadtxt("input_therm",unpack=True) hgt,tsurf = np.loadtxt("input_more",unpack=True) q = 0.001*q
# arguments from optparse import OptionParser ### TBR by argparse parser = OptionParser() (opt,args) = parser.parse_args() if len(args) == 0: args = "resultat.nc" fi=args ################################################## # REGLAGES ################################################## tt = 120. vmin = 0. ; vmax = 1400. ################################################## lev = 1013e2 temp,x,y,z,t = pp(file=fi,var="temp",t=tt,z=lev,verbose=True,changetime="correctls").getfd() albedo = pp(file=fi,var="ALB",t=tt,changetime="correctls").getf() fluxabs = pp(file=fi,var="ASR",t=tt,changetime="correctls").getf() fluxrecu = fluxabs / (1.-albedo) p = plot2d() p.f = fluxrecu p.x = x p.y = y p.proj = "cyl" p.back = "coast" p.fmt = "%.0f" p.title = 'Surface insolation' p.units = 'W/m2'
var = [] vargoal = [] for element in opt.var: var.append(element) vargoal.append("main") if opt.contour is not None: var.append(opt.contour) vargoal.append("contour") if opt.vecx is not None: var.append(opt.vecx) vargoal.append("vector") if opt.vecy is not None: var.append(opt.vecy) vargoal.append("vector") # set pp object user = pp() user.file = files user.var = var user.vargoal = vargoal user.x = opt.x user.y = opt.y user.z = opt.z user.t = opt.t user.verbose = opt.verbose if not user.verbose: user.quiet = True user.compute = opt.compute user.changetime = opt.changetime user.useindex = opt.useindex user.sx = opt.sx user.sy = opt.sy user.sz = opt.sz
#! /usr/bin/env python from ppclass import pp u = pp() u.file = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" u.var = ["temp","phisinit","u","v"] u.vargoal = ["main","contour","vector","vector"] u.t = "0.5,0.8" u.z = "50000" u.filename = "vector" # stride both x and y # this impacts field + vector u.sx = 3 u.sy = 3 u.getplot() u.sx = 1 # (reinitialise) u.sy = 1 # (reinitialise) # stride vectors only # not field (here topography) u.sx = 3 u.sy = 3 u.getplot() u.z = "50" u.filename = "myplot" u.getplot() u.colorbar = "jet" u.trans = 0.0
#! /usr/bin/env python from ppclass import pp les = pp(file="/home/aymeric/Big_Data/LES_dd/psfc_f18.nc", var="PSFC", y=["50,250"], x=["50", "100"]) les.verbose = True les.getplot() les.x = None les.y = ["200", "250"] les.t = "10" les.getplot() les.x = None les.y = None les.t = ["10"] #les.stridex = 3 #les.stridey = 3 les.filename = "les_psfc" les.getplot()
# Operations on PLANETOPLOT objects `pp()` make it easy to show the difference or ratio between two PLANETOPLOT requests: this can be difference between two simulations, ratio between two variables, etc... The five operations -- plus minus multiply divide power -- are coded in the `pp()` class. Below we give several examples # # This is done by setting up a `python` script or using `ipython` for interactive use. First import `pp()` class. # In[46]: from ppclass import pp # Now perform two distinct requests and apply the `get()` method to load data from netCDF file(s). NB: we use the same data file as in the main tutorial. # In[47]: req1 = pp(file="diagfired.nc",var="tsurf",t=0.7).get() req2 = pp(file="diagfired.nc",var="tsurf",t=0.9).get() # Now create a new `pp()` object containing the difference between the two requests. # In[48]: diff = req2-req1 # It is then easy to plot the difference between the two requested fields! Simply call the `plot()` method for the `diff` object. # In[49]: diff.plot()
#! /usr/bin/env python from ppclass import pp tsurf = pp() tsurf.file = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" tsurf.var = "tsurf" tsurf.x = None tsurf.y = 10. tsurf.t = 2. tsurf.getdefineplot() ps = pp() ps << tsurf ps.var = "ps" ps.getdefineplot() S = ps.func(tsurf) S.p[0].linestyle = "" S.p[0].marker = "h" S.p[0].color = "g" S.makeplot() icetot = pp() icetot << tsurf icetot.var = "icetot" icetot.getdefineplot() S2 = icetot.func(tsurf) S2.p[0].linestyle = "" S2.p[0].marker = "D" S2.p[0].color = "r"
#! /usr/bin/env python from ppclass import pp import matplotlib.pyplot as mpl icetot = pp(file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc", var="icetot", t=0.5).getf() mpl.pcolor(icetot) mpl.show()
#! /usr/bin/env python import ppclass import numpy as np ## POINTS tablat, tablon = np.loadtxt("dune_lat_long.txt", unpack=True) nnn = tablat.size forplot = open('add_text.txt', 'w') for iii in range(nnn): forplot.write("%+07.2f ; %+07.2f ; * ; r \n" % (tablon[iii], tablat[iii])) forplot.close() ## MAP pl = ppclass.pp() pl.file = "/home/aymeric/Science/MODELES/MESOSCALE/LMD_MM_MARS/WPS_GEOG/surface_new.nc" pl.var = "z0" pl.proj = "robin" pl.colorbar = "Greys" pl.vmin = 1.e-2 pl.vmax = 2. pl.showcb = False pl.title = "" pl.div = 40 pl.out = "png" pl.filename = "z0dune" pl.includedate = False pl.getplot() pl2 = ppclass.pp() pl2 << pl pl2.trans = 0.0
#! /usr/bin/env python from ppclass import pp import matplotlib.pyplot as mpl icetot = pp(file="/home/aymeric/Big_Data/DATAPLOT/diagfired.nc",var="icetot",t=0.5).getf() mpl.pcolor(icetot) mpl.show()
ti = 1 ti = 10 ti = 7 zi = 25. # in meters zi = 130. #ok vert velo deltaT = 3. deltaT = 4. grav = 3.72 tpottest = 195. #test potential temperature for finding height of katabatic layer #tpottest = 188. tpottest = 200. #tpottest = 205. ### LOAD tpot = pp(file=fi,var='tpot',t=ti,z=zi,verbose=True).getf() Um = pp(file=fi,var='Um',t=ti,z=zi).getf() Vm = pp(file=fi,var='Vm',t=ti,z=zi).getf() W = pp(file=fi,var='W',t=ti,z=zi).getf() PT,xx,yy,zz,tt = pp(file=fi,var='tpot',t=ti).getfd() HGT = pp(file=fi,var='HGT',t=ti).getf() potheight = pp(file=fi,var='HGT',t=ti).getf() # just to get an array the right size ### CALCULATE vel = Um**2 + Vm**2 vel = np.sqrt(vel) print "searching for height of katabatic layer" for i in range(xx.shape[1]): for j in range(yy.shape[0]): w = np.where( PT[:,j,i] > tpottest) potheight[j,i] = zz[w][0]
from ppplot import plot2d import numpy as np import scipy.stats import matplotlib.pyplot as plt import math as m # arguments from optparse import OptionParser ### TBR by argparse parser = OptionParser() (opt,args) = parser.parse_args() if len(args) == 0: args = "histday.nc" fi=args # Pour l'evolution en un point #------------------------------------------------------------------ fluxsurf,x,y,z,t = pp(file=fi,var="SWdnSFC",changetime="earth_calendar").getfd() fluxtop = pp(file=fi,var="SWdnTOA",changetime="earth_calendar").getf() t2m = pp(file=fi,var="t2m",changetime="earth_calendar").getf() area = pp(file=fi,var="aire",changetime="earth_calendar").getf() #------------------------------------------------------------------ lati = np.deg2rad(y[:,0]) weights = np.cos(lati) fluxtop_zonal = fluxtop.mean(axis=2) fluxtop_mean = np.average(fluxtop_zonal, axis=1, weights=weights) #------------------------------------------------------------------ fig = plt.figure() ax = fig.gca() ax.set_ylabel("Eclairement moyen (W/m2)") #ax.set_ylim([402.,404.])
#! /usr/bin/env python from ppclass import pp # define object, file, var m = pp() m.file = "/home/aymeric/Big_Data/GALE/wrfout_d03_2024-06-09_00:00:00" m.var = "W" # define dimensions m.x = "136.,139." # computing over x interval m.y = -5. # setting a fixed y value m.z = None # leaving z as a free dimension m.t = [6.,9.,12.,15.,18.,21.,24.] # setting 4 fixed t values # define settings m.superpose = True # superpose 1D plots m.verbose = True # making the programe verbose #m.out = "pdf" # output format m.colorbar = "spectral" # color cycle according to a color map # get data and make plot with default settings m.getplot() # get potential temperature at same point. # don't plot it. do an operation on it. tpot = pp() tpot << m tpot.var = "T" tpot.get() tpot = tpot + 220.
action='store', dest='yp', type="int", default=None, help="y size of figure (integer)") (opt, args) = parser.parse_args() # ----------------------------------------------------------------------- clb = ["Greys","Blues","YlOrRd",\ "jet","spectral","hot",\ "RdBu","RdYlBu","Paired",\ "gist_ncar","gist_rainbow","gist_stern"] # ----------------------------------------------------------------------- for files in args: yeah = pp() yeah.quiet = True yeah.defineplot(loadfile=files) yeah.out = opt.out yeah.filename = opt.filename yeah.res = opt.res yeah.xp = opt.xp yeah.yp = opt.yp if opt.proj is not None: for plot in yeah.p: plot.proj = opt.proj if opt.colorbar is not None: yeah.colorbar = opt.colorbar for plot in yeah.p: plot.colorbar = opt.colorbar
#! /usr/bin/env python from ppclass import pp u = pp() u.file = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" u.var = "u" u.t = "0.5,0.8" u.z = "10,20" u.getdefineplot(extraplot=2) # prepare 2 extraplots (do not show) u.p[0].proj = "ortho" u.p[0].title = "$u$" u.makeplot() v = pp() v << u # NB: initialize v object with u object's attributes v.var = "v" v.get() v.plotin = u # plotin must be defined before .defineplot() v.defineplot() v.p[1].proj = "ortho" v.p[1].title = "$v$" v.makeplot() # plot within the previous one (do not show) wind = u**2 + v**2 wind = wind**0.5 wind.plotin = v wind.filename = "windspeed" wind.defineplot() wind.p[2].proj = "ortho" wind.p[2].title = "$\sqrt{u^2+v^2}$" wind.makeplot() # plot within the previous one (show because complete)
[90.,135.,180.],\ [90.,135.,180.],\ [90.,135.,180.]] ############################################ motif = r"$L_s = %.0f ^{\circ}$" n = 0 for fff in ffftab: tabt = tabtabt[n] n = n + 1 print fff fp = pp() #fp.quiet = True fp.verbose = True fp.file = folder + fff + suffix fp.var = "temp" fp.changetime = "correctls_noadd" fp.x = 0. fp.logy = True fp.invert = True fp.colorbar = "gist_rainbow_r" fp.xmin = -45. fp.xmax = 45. fp.ycoeff = 0.01 fp.ymax = 50. fp.ymin = 2.e-3 fp.vmin = 85.
#! /usr/bin/env python from ppclass import pp #pp.py diagfi210_240_LT3_precast.nc -v psim -x 999 -t 0 \ # -Z -C seismic -N -20 -M 20 --xp 16 --yp 8 -m 1e-9 \ # -U "$10^9$ kg/s" -F "%.0f" --ymin 1 -T nighttime \ # -T daytime --ylabel "pressure (Pa)" -o psim_day_night \ # -O png -c psim -D 40 lvl = 60 #20 fac = 1.e-9 ps = pp() ps.nopickle = True ps.xp = 16 ps.yp = 8 ps.var = ["psim", "psim"] ps.vargoal = ["main", "contour"] ps.c = "psim" ps.x = 999 ps.t = 0 ps.invert = True ps.logy = True ps.colorbar = "seismic" ps.vmin = -lvl ps.vmax = +lvl ps.out = "png" ps.div = 24 ps.ylabel = "pressure (Pa)" ps.xlabel = "latitude"
#fileAP="UHD_DRAG18days_DISSIP5000.nc" #fileAP="DRAG90days_DISSIP50000_lat10_z5.nc" #fileAP="DRAG90days_DISSIP2500_z5.nc" fileAP = "DRAG90days_DISSIP10000_year7_743726340_512_z5.nc" fileAP = "DRAG90days_DISSIP10000_year5-6_uv_z5_512_every400d.nc" ############### computemass = False #computemass = True ############### #zzz = 15 #zzz = 8 ############### print "get full fields --> q" verb = False u4D, longit, latit, pniv, time = pp(file=fileAP, var="u", verbose=verb, z=zzz).getfd() v4D = pp(file=fileAP, var="v", verbose=verb, z=zzz).getf() print " -- got shape", u4D.shape lat = latit[:, 0] # for further use print "get axis characteristics" timeaxis = (time.size > 1) if pniv.size == 1: vertaxis = False elif zzz is None: vertaxis = False else: vertaxis = True print "get zonal anomaly fields --> q*=q-[q]" staru4D = pp(file=fileAP, var="u", verbose=verb, compute="pert_x",
########################################################################## var = ["151"] fieldtype = "2d" lev = ["9999."] tim = ["00"] date = ['01','09','2009','01','09','2009'] #area = "Whole" date = ['01','04','2011','01','04','2011'] ########################################################################## nc = get_ecmwf (var, fieldtype, [-90.,90.], [-180.,180.], lev, date, tim) press = pp(file="output.nc",var="var"+var[0]).getf() press = press / 1e2 pl = plot2d() pl.f = press #pl.trans = 0.0 pl.colorbar = "RdBu_r" pl.c = press pl.x = np.linspace(-180.,180.,press.shape[1]) pl.y = np.linspace(-90.,90.,press.shape[0]) pl.mapmode = True pl.vmin = 950.
#! /usr/bin/env python from ppclass import pp from ppplot import plot2d from ppcompute import divort import numpy as np #################################################### fff = "/home/aymeric/Big_Data/DATAPLOT/diagfired.nc" rad = 3389500 ttt = 1 zzz = 10. ##################################################### # get wind fields u = pp(file=fff, var="u", t=ttt, z=zzz).getf() v = pp(file=fff, var="v", t=ttt, z=zzz).getf() s = pp(file=fff, var="phisinit", t=ttt).getf() # set latitude and longitude arrays # -- asuming regular grid! ny, nx = u.shape lon = np.linspace(-180., 180., nx) lat = np.linspace(90., -90., ny) # compute vorticity and divergence div, vorti = divort(u, v, lon, lat, rad) ########## # figure # ########## pl = plot2d()
if opt.b is None: betaPV = 45. * m.pi / 180. else: betaPV = [float(i) for i in opt.b][0] # gammaPV if opt.g is None: gammaPV = -9999 else: gammaPV = [float(i) for i in opt.g][0] # Pour l'evolution en un point #------------------------------------------------------------------ fluxsurf, x, y, z, t = pp(file=fi, var="SWdnSFC", x=xloc, y=yloc, changetime="earth_calendar").getfd() fluxtop = pp(file=fi, var="SWdnTOA", x=xloc, y=yloc, changetime="earth_calendar").getf() t2m = pp(file=fi, var="t2m", x=xloc, y=yloc, changetime="earth_calendar").getf() sza = pp(file=fi, var="sza", x=xloc, y=yloc, changetime="earth_calendar").getf() #------------------------------------------------------------------ doy = np.array([t[i].timetuple().tm_yday for i in range(0, len(t))]) pdeclin = 23.45 * np.sin(360. * (284. + doy) / 365. * m.pi / 180.) * m.pi / 180.
#! /usr/bin/env python from ppclass import pp thres = 0.1 ww = pp() ww.xp = 24 ww.yp = 12 ww.file = "tata.nc" ww.var = "E366" ww.useindex = "1000" ww.z = 0 ww.proj = "cyl" ww.out = "jpg" #"png" ww.res = 100 #150 #300 #75 ww.fmt = "%.0f" ww.colorbar = "gist_gray" ww.quiet = True ww.showcb = False ww.div = 50 #10 #30 ww.vmin = -thres ww.vmax = 1 #ww.trans = 0.5 ww.back = "blue_local" ww.nopickle = True # loop nn = 360 nn = 25 tabcase = ["full", "np", "sp", "trop"] tabcase = ["full"]
#! /usr/bin/env python import ppclass import numpy as np ## POINTS tablat,tablon = np.loadtxt("dune_lat_long.txt",unpack=True) nnn = tablat.size forplot = open('add_text.txt', 'w') for iii in range(nnn): forplot.write( "%+07.2f ; %+07.2f ; * ; r \n" % (tablon[iii],tablat[iii]) ) forplot.close() ## MAP pl = ppclass.pp() pl.file = "/home/aymeric/Science/MODELES/MESOSCALE/LMD_MM_MARS/WPS_GEOG/surface_new.nc" pl.var = "z0" pl.proj = "robin" pl.colorbar = "Greys" pl.vmin = 1.e-2 pl.vmax = 2. pl.showcb = False pl.title = "" pl.div = 40 pl.out = "png" pl.filename = "z0dune" pl.includedate = False pl.getplot() pl2 = ppclass.pp() pl2 << pl pl2.trans = 0.0