diff --git a/examples/example_nc_particles.py b/examples/example_nc_particles.py new file mode 100644 index 0000000..1b84775 --- /dev/null +++ b/examples/example_nc_particles.py @@ -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() diff --git a/tests/test_convert_ragged.py b/tests/test_convert_ragged.py index 29f9088..5aedad2 100644 --- a/tests/test_convert_ragged.py +++ b/tests/test_convert_ragged.py @@ -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' diff --git a/tests/test_data/gnome_nc_particles.nc b/tests/test_data/gnome_nc_particles.nc new file mode 100644 index 0000000..804d36e Binary files /dev/null and b/tests/test_data/gnome_nc_particles.nc differ diff --git a/tests/test_repr.py b/tests/test_repr.py index 6cb5614..78d6445 100644 --- a/tests/test_repr.py +++ b/tests/test_repr.py @@ -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): diff --git a/trajan/accessor.py b/trajan/accessor.py index fdc5d03..218c51e 100644 --- a/trajan/accessor.py +++ b/trajan/accessor.py @@ -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") @@ -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: @@ -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: @@ -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}) @@ -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" diff --git a/trajan/scripts/trajaninfo.py b/trajan/scripts/trajaninfo.py index c022d30..dd5466e 100644 --- a/trajan/scripts/trajaninfo.py +++ b/trajan/scripts/trajaninfo.py @@ -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: @@ -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() diff --git a/trajan/traj/__init__.py b/trajan/traj/__init__.py index ecf3ad7..bf8df92 100644 --- a/trajan/traj/__init__.py +++ b/trajan/traj/__init__.py @@ -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: @@ -128,6 +129,13 @@ 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: @@ -135,20 +143,20 @@ def __repr__(self): 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]: diff --git a/trajan/traj/ragged.py b/trajan/traj/ragged.py index c33a83d..990316e 100644 --- a/trajan/traj/ragged.py +++ b/trajan/traj/ragged.py @@ -18,6 +18,54 @@ def wrapper(*args, **kwargs): return wrapper +def detect_ncparticles_vars(ds, obs_dim): + """ + Try to detect whether `ds` follows the nc_particles ragged-by-time + layout: a count variable indexed by a TIME dimension gives the number + of particles present at each time step, and an `id`-variable with + dims=(obs_dim,) identifies which particle each flattened-array entry + belongs to (needed since particle count varies over time). + + Returns (id_varname, count_varname, time_varname) if detected, + otherwise None. + """ + # id-variable: conventionally named "id" in nc_particles files + id_candidates = [ + v for v in ds.variables + if ds[v].dims == (obs_dim, ) and v == 'id' + ] + if not id_candidates: + # fall back to any single (obs_dim,) integer-like variable that + # isn't the id itself, in case naming isn't "id" exactly + id_candidates = [ + v for v in ds.variables if ds[v].dims == (obs_dim, ) + and np.issubdtype(ds[v].dtype, np.integer) and v != 'time' + ] + + # count-variable: single-dim var whose values sum to len(obs_dim), + # and whose dimension looks like a genuine time dimension + count_candidates = [] + for v in ds.variables: + if len(ds[v].dims) != 1 or ds[v].dims[0] == obs_dim: + continue + dim = ds[v].dims[0] + try: + if int(np.sum(ds[v].to_numpy())) != ds.sizes[obs_dim]: + continue + except (TypeError, ValueError): + continue + is_time_dim = (dim == 'time' or v == 'particle_count' or + (dim in ds.coords + and ds[dim].attrs.get('standard_name') == 'time')) + if is_time_dim: + count_candidates.append(v) + + if len(id_candidates) == 1 and len(count_candidates) == 1: + time_dim = ds[count_candidates[0]].dims[0] + return id_candidates[0], count_candidates[0], time_dim + + return None + @inherit_docstrings class Ragged(Traj): @@ -140,13 +188,129 @@ def from_contiguous(ds, trajectory_dim, obs_dim, time_varname, ds_converted_to_trajRagged = ds_converted_to_trajRagged.assign_attrs( global_attrs) ds_converted_to_trajRagged = ds_converted_to_trajRagged.assign_attrs( - trajan_modified= - "this was initially a contiguous ragged Dataset, which was converted to a Ragged dataset by trajan" + trajan_converted_from='contiguous' ) return Ragged(ds_converted_to_trajRagged, trajectory_dim, obs_dim, time_varname) + @staticmethod + def from_ncparticles(ds, + obs_dim='obs', + time_varname='time', + id_varname='id', + count_varname='particle_count', + data_dim='data') -> Traj: + """ + An unstructured dataset following the nc_particles standard + (https://noaa-orr-erd.github.io/nc_particles/nc_particle_standard.html). + + nc_particles files are "ragged by time": `count_varname(time)` gives the + number of particles present at each time step, and all per-particle data + (lat, lon, depth, mass, ...) is stored contiguously in a single flattened + `data_dim` array, one time step's worth of particles after another. + `id_varname(data)` gives the particle ID for each entry, allowing + particles created/destroyed during the run to be tracked across time + even though they don't occupy a fixed row/index. + + This method inverts that "ragged-by-time" layout into the + "ragged-by-trajectory" representation used by trajan, where each row + holds the time-ordered observations for a single particle ID. + """ + global_attrs = ds.attrs + + if count_varname not in ds: + raise ValueError(f"{count_varname} not found in dataset") + if id_varname not in ds: + raise ValueError( + f"{id_varname} not found in dataset; particle identity across " + "time steps cannot be reconstructed without it") + + time = ds[time_varname].to_numpy() + particle_count = ds[count_varname].to_numpy() + + if particle_count.sum() != ds.sizes[data_dim]: + raise ValueError( + f"Sum of {count_varname} ({particle_count.sum()}) does not " + f"match size of {data_dim} dimension ({ds.sizes[data_dim]})") + + # time index (into the `time` dim) for every entry of the flattened data array + time_index_of_data = np.repeat(np.arange(len(time)), particle_count) + + # trajectory index for every entry, preserving order of first appearance + traj_index_of_data, unique_ids = pd.factorize(ds[id_varname].to_numpy(), + sort=False) + nbr_trajectories = len(unique_ids) + + # column (position within its own trajectory) for every entry; since the + # flattened array is ordered by increasing time, cumcount gives the + # correct time-ordered column index per trajectory, vectorized + col_of_data = pd.Series(traj_index_of_data).groupby( + traj_index_of_data).cumcount().to_numpy() + + longest_trajectory = col_of_data.max() + 1 + + array_time = np.full((nbr_trajectories, longest_trajectory), + np.datetime64('nat'), + dtype='datetime64[ns]') + array_time[traj_index_of_data, col_of_data] = time[time_index_of_data] + + ds_converted_to_trajRagged = xr.Dataset({ + 'trajectory': + xr.DataArray( + data=unique_ids, + dims=['trajectory'], + attrs={ + "cf_role": "trajectory_id", + "standard_name": "platform_id", + "units": "1", + "long_name": + "ID of each particle in the nc_particles dataset.", + }), + 'time': + xr.DataArray(dims=['trajectory', obs_dim], + data=array_time, + attrs={ + "standard_name": "time", + "long_name": + "Time for the particle position records.", + }), + }) + + for crrt_data_var in ds.data_vars: + if crrt_data_var in (count_varname, id_varname, time_varname): + continue + if len(ds[crrt_data_var].dims) != 1 or ds[crrt_data_var].dims[ + 0] != data_dim: + logger.warning( + f"Skipping {crrt_data_var}: expected single dim ({data_dim},), " + f"got {ds[crrt_data_var].dims}") + continue + + attrs = ds[crrt_data_var].attrs + values = ds[crrt_data_var].to_numpy() + + crrt_var = np.full((nbr_trajectories, longest_trajectory), np.nan) + crrt_var[traj_index_of_data, col_of_data] = values + + # same renaming quirk as in from_contiguous + if crrt_data_var == "longitude": + crrt_data_var = "lon" + if crrt_data_var == "latitude": + crrt_data_var = "lat" + + ds_converted_to_trajRagged[crrt_data_var] = xr.DataArray( + dims=['trajectory', obs_dim], data=crrt_var, attrs=attrs) + + ds_converted_to_trajRagged = ds_converted_to_trajRagged.assign_attrs( + global_attrs) + ds_converted_to_trajRagged = ds_converted_to_trajRagged.assign_attrs( + trajan_converted_from='nc_particles' + ) + + return Ragged(ds_converted_to_trajRagged, 'trajectory', obs_dim, + time_varname) + def timestep(self, average=np.nanmedian): td = self.ds.time.diff(dim=self.obs_dim) return pd.Timedelta(average(td)) @@ -345,7 +509,6 @@ def append(self, da, obs_dims=None): # Increase obs_dims to size of max for o in obs_dims: - print(o) N = max(ds.sizes[o], da.sizes[o]) ds = ds.pad({o: (0, N - ds.sizes[o])}) da = da.pad({o: (0, N - da.sizes[o])})