Skip to content
Merged

Dev #222

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions examples/example_nc_particles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""
Analysing trajectories in nc_particles format
=============================================
"""

import matplotlib.pyplot as plt
import xarray as xr
import trajan as ta

#%%
# Demonstrating analysis of a trajecory_dataset from GNOME in the nc_particles format
# https://noaa-orr-erd.github.io/nc_particles/nc_particle_standard.html
# This is a contiguous ragged format with a deviation from the CF-convention:
# all elements for a given time are stored together, instead of the time series of individual elements

ds = xr.open_dataset('../tests/test_data/gnome_nc_particles.nc')
print(ds)

print(ds.traj)

#%%
# Basic plot
ds.traj.plot(land='mask')

#%%
# Convert from Ragged to Orthogonal
ds_ortho = ds.traj.gridtime('1h')

#%%
# Plotting a mean trajectory
ds_ortho.mean('trajectory').traj.plot(color='r', label='Mean trajectory')

#%%
# Plotting initial and final element locations, and a convex hull
ds_ortho.isel(time=0).traj.plot.scatter(color='k', s=80, zorder=100, label='Initial positions')
ds_ortho.isel(time=-1).traj.plot.scatter(color='b', s=80, zorder=100, label='Final positions')
ds_ortho.isel(time=-1).traj.plot.convex_hull(color='g', label='Convex hull of final positions')
#ds_ortho.isel(time=10).traj.plot.convex_hull(color='y', label='Convex hull after 10 hours')

plt.legend()
plt.title('Sample trajectory dataset from nc_particles repository')
plt.show()

#%%
# Plotting the element concentration after 8 hours
grid = ds_ortho.isel(time=8).traj.make_grid(dx=1000)
ds_concentration = ds_ortho.isel(time=8).traj.concentration(grid)
ds_concentration.number.plot()
plt.title('Element concentration after 10 hours')
plt.show()

#%%
# Basic animation
ds_ortho.traj.animate().set_title('nc_particles sample dataset').show()
9 changes: 9 additions & 0 deletions tests/test_convert_ragged.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,12 @@ def test_convert_ragged(test_data, plot):
print("the trajanized ds:")
print(ds.traj.ds)
print("----------------------------------------")

assert ds.traj.ds.trajan_converted_from == 'contiguous'

def test_convert_ncparticles(test_data, plot):
ds = xr.open_dataset(test_data / 'gnome_nc_particles.nc')

print(ds.traj)

assert ds.traj.ds.trajan_converted_from == 'nc_particles'
Binary file added tests/test_data/gnome_nc_particles.nc
Binary file not shown.
2 changes: 1 addition & 1 deletion tests/test_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
def test_repr_orthogonal(opendrift_sim):
repr = str(opendrift_sim.traj)
assert '2015-11-16T00:00' in repr
assert 'Timestep: 1:00:00' in repr
assert 'Timestep: 1:00:00' in repr
assert "67 timesteps [obs_dim: time]" in repr

def test_repr_ragged(test_data):
Expand Down
46 changes: 39 additions & 7 deletions trajan/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,27 @@

from .traj import Traj, detect_tx_variable
from .traj.orthogonal import Orthogonal
from .traj.ragged import Ragged
from .traj.ragged import Ragged, detect_ncparticles_vars


def detect_time_variable(ds, obs_dim):
logger.debug(f'Detecting time-variable for "{obs_dim}"..')
# TODO: should use cf-xarray here
for v in ds.variables:
if obs_dim in ds[v].dims and 'time' in v:
return v
time_variables = ds.cf.standard_names.get('time', None)
if time_variables is not None:
for varname in time_variables:
if obs_dim in ds[varname].dims:
return varname
logger.warning(f'No time CF-variable with dimension {obs_dim}')

for varname, var in ds.variables.items():
if obs_dim in var.dims and 'time' in varname:
logger.warning(f'Found instead variable with time in name: {varname}')
return varname

if time_variables is not None:
time_variables = time_variables[0]
logger.warning(f'Returning time coordinate name: {time_variables}')
return time_variables

raise ValueError("No time variable detected")

Expand All @@ -27,6 +39,7 @@ def detect_trajectory_dim(ds):
if 'trajectory_id' in ds.cf.cf_roles: # This is the proper CF way
trajectory_var = ds.cf['trajectory_id']
if trajectory_var.name in trajectory_var.sizes: # Check that this is a dimension
logger.debug(f'Found CF trajectory dimension "{trajectory_var.name}"')
return trajectory_var.name
else:
if len(trajectory_var.dims) > 1:
Expand Down Expand Up @@ -58,6 +71,11 @@ class TrajA(Traj):
def __new__(cls, ds) -> "Traj":

trajectory_dim = detect_trajectory_dim(ds)
tx = detect_tx_variable(ds)
if len(tx.dims) > 0:
obs_dim_candidate = tx.dims[0]
else:
obs_dim_candidate = None

if trajectory_dim is None:
if 'trajectory_id' in ds.cf.cf_roles:
Expand All @@ -76,6 +94,21 @@ def __new__(cls, ds) -> "Traj":
ds = ds.expand_dims(trajectory_dim,
create_index_for_new_dim=False)
else:
# Check if this could be a ncparticles file
ncparticles = detect_ncparticles_vars(ds, obs_dim_candidate)
if ncparticles is not None:
id_varname, count_varname, time_varname = ncparticles
logger.debug(
f"1D storage dataset; detected nc_particles-style ragged-by-time "
f"layout: {obs_dim_candidate = }, {id_varname = }, "
f"{count_varname = }, {time_varname = }")
return Ragged.from_ncparticles(ds,
obs_dim=obs_dim_candidate,
time_varname=time_varname,
id_varname=id_varname,
count_varname=count_varname,
data_dim=obs_dim_candidate)

logger.debug('Creating new trajectory dimension "trajectory"')
trajectory_dim = 'trajectory'
ds = ds.expand_dims({trajectory_dim: 1})
Expand All @@ -84,14 +117,13 @@ def __new__(cls, ds) -> "Traj":
obs_dim = None
time_varname = None

tx = detect_tx_variable(ds)

# if we have a 1D arrays, this is most likely some contiguous data
# there may be a few exceptions though, so be ready to default to the classical Ragged parser below
if len(tx.dims) == 1:
# we have a dataset where data are stored in 1D arrays
# NOTE: this is probably not standard; something to point to the CF conventions?
# NOTE: for now, there is no discovery of the "index" dim, this is hardcorded; any way to do better?

if "index" in tx.dims:
obs_dim = "index"

Expand Down
14 changes: 13 additions & 1 deletion trajan/scripts/trajaninfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,15 @@

@click.command()
@click.argument('tf')
@click.option('-p', is_flag=True, help="Plot the dataset")
@click.option('-l', is_flag=True, help="Show debug logging")


def main(tf, p, l):
if l is True:
import logging
logging.basicConfig(level=logging.DEBUG)

def main(tf):
tf = Path(tf)
if tf.suffix == '.xz':
with lzma.open(tf) as fd:
Expand All @@ -23,5 +30,10 @@ def main(tf):

print(ds.traj)

if p is True:
ds.traj.plot(land='mask')
import matplotlib.pyplot as plt
plt.show()

if __name__ == '__main__':
main()
18 changes: 13 additions & 5 deletions trajan/traj/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ def inherit_docstrings(cls):


def detect_tx_variable(ds):
# TODO: should use cf-xarray and standard_name
if 'lon' in ds:
return ds.lon
elif 'longitude' in ds:
Expand Down Expand Up @@ -128,27 +129,34 @@ def __repr__(self):
output = '=======================\n'
output += 'TrajAn info:\n'
output += '------------\n'

output += f'Type: {type(self).__name__}'
converted_from = self.ds.attrs.get('trajan_converted_from', None)
if converted_from is not None:
output += f' (converted from {converted_from} by TrajAn)'
output += '\n'

if self.trajectory_dim is None:
output += 'Single trajectory (no trajectory dimension)\n'
else:
output += f'{self.ds.sizes[self.trajectory_dim]} trajectories [trajectory_dim: {self.trajectory_dim}]\n'
if self.time_varname is not None:
output += f'{self.ds.sizes[self.obs_dim]} timesteps [obs_dim: {self.obs_dim}]\n'
timevar = self.ds[self.time_varname]
output += f'Time variable: {timevar.name}{list(timevar.sizes)} ({len(timevar.sizes)}D)\n'
output += f'Time variable: {timevar.name}{list(timevar.sizes)}\n'
try:
timestep = self.timestep()
timestep = timedelta(seconds=timestep.total_seconds())
except:
timestep = '[self.timestep returns error]' # TODO
output += f'Timestep: {timestep}\n'
output += f'Timestep: {timestep}\n'
start_time = self.ds.time.min(skipna=True).data
end_time = self.ds.time.max(skipna=True).data
output += f'Time coverage: {start_time} - {end_time}\n'
output += f'Time coverage: {start_time} - {end_time}\n'
else:
output += f'Dataset has no time variable'
output += f'Longitude span: {self.tx.min(skipna=True).data} to {self.tx.max(skipna=True).data}\n'
output += f'Latitude span: {self.ty.min(skipna=True).data} to {self.ty.max(skipna=True).data}\n'
output += f'Longitude span: {self.tx.min(skipna=True).data} to {self.tx.max(skipna=True).data}\n'
output += f'Latitude span: {self.ty.min(skipna=True).data} to {self.ty.max(skipna=True).data}\n'
output += 'Variables:\n'
for var in self.ds.variables:
if var not in ['trajectory', self.obs_dim]:
Expand Down
Loading
Loading