def lag_plot(i): f = plt.figure() ax=f.add_axes([.125,.1,.775,.8]) #plotcoast(ax,filename='pacific.nc',color='k') #ax.triplot(data['trigridxy'],lw=.25,zorder=1) ax.axis(region['regionxy']) lseg1=PC(tmparray,facecolor = 'g',edgecolor='None') ax.add_collection(lseg1) ax.scatter(savelag1['x'][(subset*sub):(subset*(sub+1)),i],savelag1['y'][(subset*sub):(subset*(sub+1)),i],color='b',label='No drag',s=.25,zorder=10) ax.scatter(savelag2['x'][(subset*sub):(subset*(sub+1)),i],savelag2['y'][(subset*sub):(subset*(sub+1)),i],color='r',label='Drag',s=.25,zorder=15) handles, labels = ax.get_legend_handles_labels() handles[0:2]=[handles[0],handles[-1]] labels[0:2]=[labels[0],labels[-1]] legend=ax.legend(handles[0:2], labels[0:2],prop={'size':10},loc=4,numpoints=1) legend.set_zorder(25) tstr=time.strftime("%d-%H:%M", time.gmtime(savelag1['time'][i]-savelag1['time'][0])) ax.annotate(("Time: %s"%tstr),xy=(.025,.95),xycoords='axes fraction',bbox={'facecolor':'white','edgecolor':'None', 'alpha':1, 'pad':3}) f.savefig(savepath +''+name+'_'+name2+'_'+regionname+'_'+lname+'_timestep_'+("%05d"%i)+'.png',dpi=150) plt.close(f)
def speed_plot(i): print(i) f = plt.figure() ax = plt.axes([.125, .1, .775, .8]) if coastflag == True: plotcoast(ax, filename='mid_nwatl6c_sjh_lr.nc', color='k', fcolor='0.75', fill=True, zorder=100) triax = ax.tripcolor(data['trigrid'], np.sqrt(data['ua'][i, :]**2 + data['va'][i, :]**2), vmin=cmin, vmax=cmax) if np.shape(cages) != (): lseg_t = LC(tmparray, linewidths=lw, linestyles=ls, color=color) ax.add_collection(lseg_t) if vectorflag == True: Q1 = ax.quiver(data['uvnodell'][vidx, 0], data['uvnodell'][vidx, 1], data['ua'][i, vidx], data['va'][i, vidx], angles='xy', scale_units='xy', scale=vector_scale, zorder=100, width=.0025) if uniformvectorflag == True: norm = np.sqrt(data['ua'][i, vidx]**2 + data['va'][i, vidx]**2) Q1 = ax.quiver(data['uvnodell'][vidx, 0], data['uvnodell'][vidx, 1], np.divide(data['ua'][i, vidx], norm), np.divide(data['va'][i, vidx], norm), angles='xy', scale_units='xy', scale=vector_scale, zorder=100, width=.002, color='k') sand = np.argwhere(data['wet_cells'][i, :] == 0) tmparray = [ list( zip(data['nodell'][data['nv'][j, [0, 1, 2]], 0], data['nodell'][data['nv'][j, [0, 1, 2]], 1])) for j in sand ] lseg_sand = PC(tmparray, facecolor='0.75', edgecolor='0.75') ax.add_collection(lseg_sand) prettyplot_ll(ax, setregion=region, cblabel=r'Speed (ms$^{-1}$)', cb=triax) f.savefig(savepath + grid + '_' + region['regionname'] + '_speed_' + ("%04d" % (i)) + '.png', dpi=150) plt.close(f)
def plot_kelp(data, cages, filename): tmparray = [ list( zip(data['nodell'][data['nv'][i, [0, 1, 2]], 0], data['nodell'][data['nv'][i, [0, 1, 2]], 1])) for i in cages ] seg = PC(tmparray, facecolor='g', edgecolor='None') f = plt.figure() ax = f.add_axes([.125, .1, .775, .8]) ax.add_collection(seg) ax.triplot(data['trigrid'], color='k', lw=.25) prettyplot_ll(ax, setregion=region) plotcoast(ax, color='None', fill=True) f.savefig(filename, dpi=600) plt.close(f)
def update_plot(t): for i in range(n_agts): pos_patch[i] = Circle(pos[i, :, t], radius=rad_p, fc=col_grp[groups.index(gID[i])], alpha=0.4) mode_patch[i] = Circle(pos[i, :, t], radius=rad_m, fc=col_mode[list(mode[i, :, t]).index(1)]) gaze_patch[i] = Arrow(pos[i, 0, t], pos[i, 1, t], 25 * gaze[i, 0, t], 25 * gaze[i, 1, t], width=30, fc='k', ec='k') ax.clear() p_coll = PC(pos_patch + mode_patch + gaze_patch, match_original=True) #p_coll = PC(pos_patch+gaze_patch, match_original=True) ax.add_collection(p_coll)
def load_coastline(): """ Load and plot a coastline. """ filename = () filename = askopenfilename(initialdir=w.init_dir) if filename != (): w.coastline = ut.load_coastline(filename=filename) w.TF['coast'] = True w.CBVar['coast'].set(1) #Reduce number of segments - helps but not enough #axis=[-68.5,-64,44,46.5] #yep=[] #def isin(axis,line): #return ((line[:,0]>=axis[0]) & (line[:,0]<=axis[1]) & (line[:,1]>=axis[2]) & (line[:,1]<=axis[3])).sum() #for i,line in enumerate(w.coastline): #if isin(axis,np.array(line)): #yep+=[i] if w.config['coast']['fill'] == 'True': w.FIGS['coast'] = PC(w.coastline, facecolor=w.config['coast']['facecolor'], edgecolor=w.config['coast']['edgecolor'], linewidths=float( w.config['coast']['linewidth']), zorder=int(w.config['coast']['zorder'])) else: w.FIGS['coast'] = LC(w.coastline, color=w.config['coast']['edgecolor'], linewidths=float( w.config['coast']['linewidth']), zorder=int(w.config['coast']['zorder'])) w.ax.add_collection(w.FIGS['coast']) w.figure.canvas.draw() return
savepath = 'figures/timeseries/' + grid + '_' + '/zoom/' + regionname1 + '_' + regionname2 + '_' + stype + '_' + ( "%d" % spacing) + '/' if not os.path.exists(savepath): os.makedirs(savepath) region1 = regions(regionname1) region2 = regions(regionname2) f = plt.figure() ax = f.add_axes([.125, .1, .775, .8]) ax.triplot(data['trigrid'], lw=.1) #prettyplot_ll(ax,setregion=region) #scalebar(ax,region,200) plotcoast(ax, filename='pacific.nc', color='None', fill=True) if np.shape(cages) != (): lsega = PC(tmparray, facecolor=color, edgecolor='None') ax.add_collection(lsega) _formatter = mpl.ticker.FormatStrFormatter("%.2f") ax.yaxis.set_major_formatter(_formatter) ax.xaxis.set_major_formatter(_formatter) ax.set_xlabel(r'Longitude ($^{\circ}$W)') ax.set_ylabel(r'Latitude ($^{\circ}$N)') tempregion = {} if 'linear' in stype: #constant speed spaces = np.array([ s * (region1['region'] - region2['region']) / spacing for s in range(spacing) ])
### load the .nc file ##### data = loadnc('runs/'+grid+'/'+name+'/output/',singlename=grid + '_0001.nc') data2 = loadnc('runs/'+grid+'/'+name2+'/output/',singlename=grid + '_0001.nc') print('done load') data = ncdatasort(data) print('done sort') cages=np.genfromtxt('runs/'+grid+'/' +name+ '/input/' +grid+ '_cage.dat',skiprows=1) cages=(cages[:,0]-1).astype(int) savepath='figures/png/' + grid + '_' + datatype + '/ebbfldres_dragnodrag_subplot/' if not os.path.exists(savepath): os.makedirs(savepath) tmparray=[list(zip(data['nodell'][data['nv'][i,[0,1,2]],0],data['nodell'][data['nv'][i,[0,1,2]],1])) for i in cages ] lsegf=PC(tmparray,facecolor = 'g',edgecolor='None') lsege=PC(tmparray,facecolor = 'g',edgecolor='None') lsegr=PC(tmparray,facecolor = 'g',edgecolor='None') uv1=np.load('/home/moflaher/Desktop/workspace_python/data/ttide/'+grid+'_'+name+'_'+datatype+'_uv.npy') uv1=uv1[()] uv2=np.load('/home/moflaher/Desktop/workspace_python/data/ttide/'+grid+'_'+name2+'_'+datatype+'_uv.npy') uv2=uv2[()] nidx=get_nodes(data,region) eidx=equal_vectors(data,region,vectorspacing) if usemean==True: data['uvzeta']=(data['zeta'][starttime:,data['nv'][eidx,0]] + data['zeta'][starttime:,data['nv'][eidx,1]] + data['zeta'][starttime:,data['nv'][eidx,2]]) / 3.0 data2['uvzeta']=(data2['zeta'][starttime:,data2['nv'][eidx,0]] + data2['zeta'][starttime:,data2['nv'][eidx,1]] + data2['zeta'][starttime:,data2['nv'][eidx,2]]) / 3.0 zeta_grad1=np.gradient(data['uvzeta'])[0]
savelag[i] = fileload['savelag'][i].value.T starts = sio.loadmat( '/home/moflaher/workspace_matlab/lagtracker/element_starts/oil_elements_beaufort3.mat' )['cage_elements'] startsbool = np.ones((len(data['nv']), )) startsbool[starts - 1] = 0 unidx = np.flatnonzero(startsbool) idx = np.where(data['trigrid'].neighbors == -1) tmparray = [ list( zip(data['nodell'][data['nv'][i, [0, 1, 2]], 0], data['nodell'][data['nv'][i, [0, 1, 2]], 1])) for i in idx[0] ] modelcoast = PC(tmparray, facecolor='g', edgecolor='None') #f=plt.figure() #ax=f.add_axes([.125,.1,.8,.8]) #ax.add_collection(modelcoast) #ax.triplot(data['trigrid'],lw=.5) #f.show() host = data['trigridxy'].get_trifinder().__call__(savelag['x'], savelag['y']) whenall = np.in1d(host, idx[0]).reshape(host.shape) when = np.argmax(whenall[:, 1:], axis=1) whenidx = np.where((when == 0) & (np.sum(whenall, axis=1) == 0))[0] trihost = np.zeros((len(data['nv']), )) tricnt = np.zeros((len(data['nv']), )) for i in range(len(host[:, 0])):
### load the .nc file ##### data = loadnc('runs/'+grid+'/'+name+'/output/',singlename=grid + '_0001.nc') data2 = loadnc('runs/'+grid+'/'+name2+'/output/',singlename=grid + '_0001.nc') print('done load') data = ncdatasort(data) print('done sort') cages=np.genfromtxt('runs/'+grid+'/' +name+ '/input/' +grid+ '_cage.dat',skiprows=1) cages=(cages[:,0]-1).astype(int) savepath='figures/png/' + grid + '_' + '/res_dragnodrag_spatial/' if not os.path.exists(savepath): os.makedirs(savepath) tmparray=[list(zip(data['nodell'][data['nv'][i,[0,1,2]],0],data['nodell'][data['nv'][i,[0,1,2]],1])) for i in cages ] lsegr=PC(tmparray,facecolor = fcolor,edgecolor='None') uv1=np.load('data/ttide/'+grid+'_'+name+'_'+'_uv.npy') uv1=uv1[()] uv2=np.load('data/ttide/'+grid+'_'+name2+'_'+'_uv.npy') uv2=uv2[()] nidx=get_nodes(data,region) eidx=get_elements(data,region) resu=np.empty((len(eidx),len(data['time'][starttime:]))) resv=np.empty((len(eidx),len(data['time'][starttime:]))) resu2=np.empty((len(eidx),len(data['time'][starttime:])))
region = regions(regionname) cage1n = 'kit4_cage_5m_30m' cage2n = 'kit4_cage_5m_15m' cages1 = np.genfromtxt('data/cage_files/' + cage1n + '.dat', skiprows=1) cages1 = (cages1[:, 0] - 1).astype(int) cages2 = np.genfromtxt('data/cage_files/' + cage2n + '.dat', skiprows=1) cages2 = (cages2[:, 0] - 1).astype(int) tmparray1 = [ list( zip(data['nodell'][data['nv'][i, [0, 1, 2]], 0], data['nodell'][data['nv'][i, [0, 1, 2]], 1])) for i in cages1 ] lseg1 = PC(tmparray1, facecolor='g', edgecolor='None') tmparray2 = [ list( zip(data['nodell'][data['nv'][i, [0, 1, 2]], 0], data['nodell'][data['nv'][i, [0, 1, 2]], 1])) for i in cages2 ] lseg2 = PC(tmparray2, facecolor='b', edgecolor='None') f = plt.figure() ax = f.add_axes([.125, .1, .8, .8]) plotcoast(ax, filename='pacific.nc', color='k') ax.triplot(data['trigrid'], lw=.25, zorder=1) ax.axis(region['region']) ax.add_collection(lseg1) ax.add_collection(lseg2)
subtimes = np.linspace(0, 1800, nos) expand = 5000 region['regionxy'] = [ region['regionxy'][0] - expand, region['regionxy'][1] + expand, region['regionxy'][2] - expand, region['regionxy'][3] + expand ] f, ax = plt.subplots(nrows=rows, ncols=cols, sharex=True, sharey=True) ax = ax.flatten() for i in range(0, len(ax)): print(i) ax[i].triplot(data['trigridxy'], lw=.05) if np.shape(cages) != (): lseg1 = PC(tmparray, facecolor='g', edgecolor='None') ax[i].add_collection(lseg1) ax[i].scatter(savelag1['x'][:, subtimes[i].astype(int)], savelag1['y'][:, subtimes[i].astype(int)], color='b', label='No drag', s=.25, zorder=10) ax[i].scatter(savelag2['x'][:, subtimes[i].astype(int)], savelag2['y'][:, subtimes[i].astype(int)], color='r', label='Drag', s=.25, zorder=15) ax[i].axis(region['regionxy']) ax[i].set_title('Hour ' + ("%.0f" %
tridiv2[idx[0]] = 1 f = plt.figure() ax = f.add_axes([.125, .1, .8, .8]) clims = np.percentile(tridiv[tricnt != 0], [2, 98]) triaxis = ax.tripcolor(data['trigrid'], tridiv2 * 100) #tmparray=[list(zip(data['nodexy'][data['nv'][i,[0,1,2]],0],data['nodexy'][data['nv'][i,[0,1,2]],1])) for i in np.unique(np.hstack([unidx,np.flatnonzero(tridiv==0)]))] tmparray = [ list( zip(data['nodell'][data['nv'][i, [0, 1, 2]], 0], data['nodell'][data['nv'][i, [0, 1, 2]], 1])) for i in np.flatnonzero(tridiv2 == 0) ] modelcoast = PC(tmparray, facecolor='w', edgecolor='k', linewidth=.5) ax.add_collection(modelcoast) cb = plt.colorbar(triaxis) cb.set_label('Percent of particles to reach coastal element') #for i in (idx[0]+1): # ax.plot(savelag['x'][i,:],savelag['y'][i,:]) ax.axis(region['region']) #ax.plot(savelag['x'][:,0],savelag['y'][:,0],'k.',markersize=4) #ax.plot(savelag['x'][when>0,0],savelag['y'][when>0,0],'g.',markersize=6) plotcoast(ax, filename='world_GSHHS_f_L1.nc', color='k') ax.plot(oilmat['lonmap'], oilmat['latmap'] + .1, 'g.', alpha=.5, markersize=3) box = {} box['region'] = [-134, -133.66, 69.625 + .1, 69.675 + .1] plot_box(ax, box, 'k', lw=2)
def main(): # Define names and types of data name='kit4_45days_3' name2='kit4_kelp_20m_0.018' grid='kit4' regionname='kit4_kelp_tight6' datatype='2d' lfolder='kit4_kelp_0.0' lname='kit4_kelp_0.0_0_all_in_a_box' ### load the .nc file ##### data = loadnc('runs/'+grid+'/' + name +'/output/',singlename=grid + '_0001.nc') print('done load') data = ncdatasort(data) print('done sort') savepath='figures/timeseries/' + grid + '_' + datatype + '/lagtracker/' + name + '_'+name2+'/' if not os.path.exists(savepath): os.makedirs(savepath) data['trigridxy'] = mplt.Triangulation(data['x'], data['y'],data['nv']) region=regions(regionname) region=regionll2xy(data,region) if 'savelag1' not in globals(): print "Loading savelag1" fileload=h5.File('/media/moe46/Hardy/spet_18_work/savedir/'+name+'/allelements_s0in_aristazabal_west.mat') savelag1={} for i in fileload['savelag'].keys(): savelag1[i]=fileload['savelag'][i].value.T if 'savelag2' not in globals(): print "Loading savelag2" fileload=h5.File('/media/moe46/Hardy/spet_18_work/savedir/'+name2+'/allelements_s0in_aristazabal_west.mat') savelag2={} for i in fileload['savelag'].keys(): savelag2[i]=fileload['savelag'][i].value.T cages=np.genfromtxt('runs/'+grid+'/' +name2+ '/input/' +grid+ '_cage.dat',skiprows=1) cages=(cages[:,0]-1).astype(int) tmparray=[list(zip(data['nodexy'][data['nv'][i,[0,1,2]],0],data['nodexy'][data['nv'][i,[0,1,2]],1])) for i in cages ] sidx=np.where((savelag1['x'][:,0]>region['regionxy'][0])&(savelag1['x'][:,0]<region['regionxy'][1])&(savelag1['y'][:,0]>region['regionxy'][2])&(savelag1['y'][:,0]<region['regionxy'][3])) expand=10000 region['regionxy']=[region['regionxy'][0]-expand,region['regionxy'][1]+expand,region['regionxy'][2]-expand,region['regionxy'][3]+expand] for i in range(0,10):#len(savelag1['time']),2): print ("%d"%i)+" "+("%f"%(i/len(savelag1['time'])*100)) f = plt.figure() ax=f.add_axes([.125,.1,.8,.8]) #plotcoast(ax,filename='pacific.nc',color='k') ax.triplot(data['trigridxy'],lw=.25,zorder=1) ax.axis(region['regionxy']) lseg1=PC(tmparray,facecolor = 'g',edgecolor='None') ax.add_collection(lseg1) ax.scatter(savelag1['x'][sidx,i],savelag1['y'][sidx,i],color='k',label='No drag',s=5,zorder=10) ax.scatter(savelag2['x'][sidx,i],savelag2['y'][sidx,i],color='r',label='Drag',s=5,zorder=15) handles, labels = ax.get_legend_handles_labels() handles[0:2]=[handles[0],handles[-1]] labels[0:2]=[labels[0],labels[-1]] legend=ax.legend(handles[0:2], labels[0:2],prop={'size':10},loc=4,numpoints=1) f.savefig(savepath +'_'+name+'_'+name2+'_'+regionname+'_timestep_'+("%05d"%i)+'.png',dpi=100) plt.close(f)
figW, figH = f.get_size_inches() f.canvas.draw() Q0=ax[0].quiver(data['uvnodell'][vidx,0],data['uvnodell'][vidx,1],data['u'][i,0,vidx],data['v'][i,0,vidx],angles='xy',scale_units='xy',scale=vector_scale,zorder=0,width=.0025) Q1=ax[1].quiver(data['uvnodell'][vidx,0],data['uvnodell'][vidx,1],data['u'][i,-1,vidx],data['v'][i,-1,vidx],angles='xy',scale_units='xy',scale=vector_scale,zorder=0,width=.0025) Qkey0=ax[0].quiverkey(Q0,.9,.85,1.0, r'1.0 ms$^{-1}$',fontproperties={'size':8}) Qkey1=ax[1].quiverkey(Q1,.9,.85,1.0, r'1.0 ms$^{-1}$',fontproperties={'size':8}) for j,axi in enumerate(ax): if coast: plotcoast(ax[j],filename='mid_nwatl6c_sjh_lr.nc',color='k',fill=True,lw=.5,zorder=100,filepath=coastpath) axbb=ax[j].get_axes().get_position().bounds ax[j].annotate(ABC[j],xy=(axbb[0]+.0075,axbb[1]+axbb[3]-.03),xycoords='figure fraction') sand=np.argwhere(data['wet_cells'][i,:]==0) tmparray=[list(zip(data['nodell'][data['nv'][k,[0,1,2]],0],data['nodell'][data['nv'][k,[0,1,2]],1])) for k in sand ] lseg_sand=PC(tmparray,facecolor = 'tan',edgecolor='tan') ax[j].add_collection(lseg_sand) f.canvas.draw() background0 = f.canvas.copy_from_bbox(ax[0].bbox) background1 = f.canvas.copy_from_bbox(ax[1].bbox) for i in range(starttime,endtime,spacing): print(i) f.canvas.restore_region(background0) f.canvas.restore_region(background1) fcolors0=np.mean(data['salinity'][i,0,data['nv']],axis=1) triax0.set_array(fcolors0) ax[0].draw_artist(triax0)
def speed_plot(i): print(i) f, ax = place_axes(region, 2) triax0 = ax[0].tripcolor(data['trigrid'], data['salinity'][i, 0, :], vmin=cmin, vmax=cmax) triax1 = ax[1].tripcolor(data['trigrid'], data['salinity'][i, -1, :], vmin=cmin, vmax=cmax) ppll_sub(ax, setregion=region, cb=triax0, cblabel=r'Salinity', llfontsize=10, fontsize=8, cblabelsize=6, cbticksize=6, cbtickrotation=-45) ABC = ['A', 'B'] figW, figH = f.get_size_inches() f.canvas.draw() Q0 = ax[0].quiver(data['uvnodell'][vidx, 0], data['uvnodell'][vidx, 1], data['u'][i, 0, vidx], data['v'][i, 0, vidx], angles='xy', scale_units='xy', scale=vector_scale, zorder=100, width=.0025) Q1 = ax[1].quiver(data['uvnodell'][vidx, 0], data['uvnodell'][vidx, 1], data['u'][i, -1, vidx], data['v'][i, -1, vidx], angles='xy', scale_units='xy', scale=vector_scale, zorder=100, width=.0025) Qkey0 = ax[0].quiverkey(Q0, .9, .85, 1.0, r'1.0 ms$^{-1}$', fontproperties={'size': 8}) Qkey1 = ax[1].quiverkey(Q1, .9, .85, 1.0, r'1.0 ms$^{-1}$', fontproperties={'size': 8}) for j, axi in enumerate(ax): if coastflag: plotcoast(ax[j], filename='mid_nwatl6c_sjh_lr.nc', color='k', fill=True, lw=.5, zorder=100, filepath=coastpath) axbb = ax[j].get_axes().get_position().bounds ax[j].annotate(ABC[j], xy=(axbb[0] + .0075, axbb[1] + axbb[3] - .03), xycoords='figure fraction') sand = np.argwhere(data['wet_cells'][i, :] == 0) tmparray = [ list( zip(data['nodell'][data['nv'][k, [0, 1, 2]], 0], data['nodell'][data['nv'][k, [0, 1, 2]], 1])) for k in sand ] lseg_sand = PC(tmparray, facecolor='tan', edgecolor='tan') ax[j].add_collection(lseg_sand) f.savefig(savepath + grid + '_' + region['regionname'] + '_salinity_' + ("%04d" % (i)) + '.png', dpi=300) plt.close(f)
scale_units='xy', scale=scale1, zorder=10) Q2 = ax.quiver(savelag2['x'][sidx, 0], savelag2['y'][sidx, 0], q2x2, q2y2, angles='xy', scale_units='xy', scale=scale1, color='r', zorder=10) ax.axis(region['regionxy']) ax.triplot(data['trigridxy'], lw=.25) lseg = PC(tmparray, facecolor='g', edgecolor='None', zorder=5) ax.add_collection(lseg) #fix_osw(ax) #ax.set_aspect(get_aspectratio(region)) #plt.draw() rec = mpl.patches.Rectangle((kl[0], kl[1]), kl[2], kl[3], transform=ax.transAxes, fc='w', zorder=20) ax.add_patch(rec) ax.annotate(r'' + ebbfldscale + ' m', xy=(kl[0] + .035, kl[1] + .07), xycoords='axes fraction',