Comments (1)
#This script shows the trajectory of a single particle through the ocean
#************************************************************************
import numpy as np
import matplotlib.pyplot as plt
import netCDF4 as nc4
from mpl_toolkits.basemap import Basemap
import matplotlib.colors as colors
from parcels import FieldSet, ParticleSet, JITParticle, AdvectionRK4_3D, ErrorCode, ScipyParticle, plotTrajectoriesFile
from glob import glob
from datetime import timedelta as delta
#from parcels import logger, XarrayDecodedFilter
#logger.addFilter(XarrayDecodedFilter()) # Add a filter for the xarray decoding warning
location = '/home/bejamino/Desktop/DataFiles/'
evel_Data = nc4.Dataset(location + 'EVELMASS/Monthly_Avg_Files/EVEL_01_avg.nc')
wvel_Data = nc4.Dataset(location + 'WVELMASS/Monthly_Avg_Files/WVEL_01_avg.nc')
nvel_Data = nc4.Dataset(location + 'NVELMASS/Monthly_Avg_Files/NVEL_01_avg.nc')
#loading the coordinates of the data
lonGrid = evel_Data.variables['longitude']
latGrid = evel_Data.variables['latitude']
#Making the streamplot at the surface in January
EVEL = evel_Data.variables['EVELMASS'][0,0,:,:]
NVEL = nvel_Data.variables['NVELMASS'][0,0,:,:]
ufiles = sorted(glob(location + 'EVELMASS/Monthly_Avg_Files/EVEL_*.nc'))
vfiles = sorted(glob(location + 'NVELMASS/Monthly_Avg_Files/NVEL_*.nc'))
wfiles = sorted(glob(location + 'WVELMASS/Monthly_Avg_Files/WVEL_*.nc'))
filenames = {'U': ufiles, 'V': vfiles,'W': wfiles}
variables = {'U': 'EVELMASS', 'V': 'NVELMASS','W': 'WVELMASS'}
dimensions = {'U': {'lon': 'longitude', 'lat': 'latitude', 'depth': 'Z', 'time': 'time'},
'V': {'lon': 'longitude', 'lat': 'latitude', 'depth': 'Z', 'time': 'time'},
'W': {'lon': 'longitude', 'lat': 'latitude', 'depth': 'Zl', 'time': 'time'}}
fset = FieldSet.from_netcdf(filenames, variables, dimensions, allow_time_extrapolation=True, time_periodic=False)
pset = ParticleSet.from_line(fieldset=fset, pclass=JITParticle,
size = 1, #the number of particles that are released
start = (-30, -40), #defining the starting location (lon,lat)
finish = (-30, 30), #defining the finishing location (lon,lat)
depth =100) #the depth
#here i defined the particle delete function
#def DeleteParticle(particle, fieldset, time):
# particle.delete()
#defining the particle locations for 8 particle sets (somewhere in the Atlantic)
#p_lons=np.array([-30,-30,-30,-30,-30,-30,-30,-30])
#p_lats=np.array([-40,-30,-20,-10,0,10,20,30])
#p_dep=np.array([100,100,100,100,100,100,100,100])
#pset = ParticleSet(fieldset=fset, pclass=JITParticle, lon=p_lons, lat=p_lats, depth=p_dep)
#kernels = pset.Kernel(AdvectionRK4_3D)
#pset.execute(kernels, runtime=delta(days=30), dt=delta(hours=6))
depth_level = 8
print("Level[%d] depth is: [%g %g]" % (depth_level, fset.W.grid.depth[depth_level],
fset.W.grid.depth[depth_level+1]))
def colorGradient(val, minval, maxval):
# min_depth = 100
#max_depth = 1000
if val < minval:
return (0,0,0) #returns black particle
if val > maxval:
return (1,0,0) #returns red particle
#interpolating continuously the depth
v = (val - minval) / (maxval - minval)
return (v,0,0)
#Generating the trajectories for the particles
nParticles = len(pset)
nDays = 40
nSteps = 20 #this show how often the particle is propagated for nDays (if it goes in total beyong 360 is crushes)
kernels = pset.Kernel(AdvectionRK4_3D)
plocations = [[] for _ in range(nParticles)]
#recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle}
for i in range(nSteps):
pset.execute(kernels, runtime=delta(days=nDays), dt=delta(hours=6))
for k, p in enumerate(pset):
if k == 0:
print(f"Step {i}, particle {k}:")
print(p)
print(f"lon: {p.lon}, lat: {p.lat}, depth: {p.depth}")
plocations[k].append((p.lon, p.lat, p.depth))
#making the plot
plt.ion()
fig = plt.figure(figsize=(12,8))
# miller projection with Basemaps
map = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,llcrnrlon=-180,urcrnrlon=180)
# plot coastlines, draw label meridians and parallels.
map.drawmeridians(np.arange(0,360,60),labels=[False,False,False,True],linewidth=(0.0))
map.drawparallels(np.arange(-80,80,20),labels=[True,False,False,False],linewidth=(0.0))
# Fill the continents
map.fillcontinents(color='0.7',lake_color='0.7')
map.drawmapboundary(fill_color='0.7')
map.fillcontinents(color='#ffe2ab',lake_color='0.7')
map.drawcoastlines()
magnitude = (EVEL ** 2 + NVEL ** 2) ** 0.5
#Plotting the stream pattern
map.streamplot(x=lonGrid, y=latGrid, u=EVEL, v=NVEL, linewidth=2, density=2, color=magnitude)
#plt.title('Put the title here', fontsize=8)
plt.xlabel('Longitude [$^\circ$]', labelpad=20, fontsize=12)
plt.ylabel('Latitude [$^\circ$]', labelpad=40, fontsize=12)
# Plot trajectories
min_depth, max_depth = 100, 1000
#colorBy = "depth"
colorBy = "step"
for j, pos in enumerate(plocations):
for i in range(nSteps):
lon, lat, depth = pos[i]
if colorBy == "depth":
map.scatter(lon, lat, s=4, color=colorGradient(depth, min_depth, max_depth))
elif colorBy == "step":
map.scatter(lon, lat, s=4, color=colorGradient(i, 0, nSteps))
from parcels.
Related Issues (20)
- [Errno 28] No space left on device HOT 2
- Support FieldSets without U or V
- Smarter time management in pset.execute() loop
- Investigate whether C-code creation and caching works as expected
- Consider using flake8-pyproject to combine .flake8 and pyproject.toml info HOT 1
- Crash on empty particleset
- Set smarter default for chunks[1] in zarr output file
- Reconsider the order of (trajectory, obs) in the zarr output file? HOT 1
- Removing `delta` alias for `timedelta` HOT 1
- Files with `.so.dSYM` extension aren't cleaned up after C compilation
- Add FieldSet.from_a_grid_dataset() method HOT 4
- Cleaning up top level `parcels` namespace
- Harmonise Field interpolation order to consistently be (time, depth, lat, lon) throughout the code HOT 1
- Migration from `ParcelsRandom` in documentation notebooks
- Parcels typing and mypy support HOT 5
- Python and code package version support (SPEC 0) HOT 1
- Choice of Zarr compressor HOT 2
- Invalid call of `VectorFieldEvalNode` HOT 3
- Refactoring of FieldSet field store HOT 2
- tutorial_diffusion: SmagDiff example not working HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from parcels.