Skip to content

Commit e67eb82

Browse files
Changing public particleset.data to private _data
1 parent 53483b8 commit e67eb82

3 files changed

Lines changed: 41 additions & 39 deletions

File tree

parcels/kernel.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def fieldset(self):
7070

7171
def remove_deleted(self, pset):
7272
"""Utility to remove all particles that signalled deletion."""
73-
bool_indices = pset.data["state"] == StatusCode.Delete
73+
bool_indices = pset._data["state"] == StatusCode.Delete
7474
indices = np.where(bool_indices)[0]
7575
if len(indices) > 0 and self.fieldset.particlefile is not None:
7676
self.fieldset.particlefile.write(pset, None, indices=indices)
@@ -303,7 +303,7 @@ def from_list(cls, fieldset, ptype, pyfunc_list, *args, **kwargs):
303303

304304
def execute(self, pset, endtime, dt):
305305
"""Execute this Kernel over a ParticleSet for several timesteps."""
306-
pset.data["state"][:] = StatusCode.Evaluate
306+
pset._data["state"][:] = StatusCode.Evaluate
307307

308308
if abs(dt) < np.timedelta64(1, "ns"): # TODO still needed?
309309
warnings.warn(

parcels/particleset.py

Lines changed: 35 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ def __init__(
7575
pid_orig=None,
7676
**kwargs,
7777
):
78-
self.data = None
78+
self._data = None
7979
self._repeat_starttime = None
8080
self._repeatlon = None
8181
self._repeatlat = None
@@ -136,7 +136,7 @@ def __init__(
136136
lon.size == kwargs[kwvar].size
137137
), f"{kwvar} and positions (lon, lat, depth) don't have the same lengths."
138138

139-
self.data = xr.Dataset(
139+
self._data = xr.Dataset(
140140
{
141141
"lon": (
142142
["trajectory", "obs"],
@@ -169,12 +169,12 @@ def __init__(
169169
self._kernel = None
170170

171171
def __del__(self):
172-
if self.data is not None and isinstance(self.data, xr.Dataset):
173-
del self.data
174-
self.data = None
172+
if self._data is not None and isinstance(self._data, xr.Dataset):
173+
del self._data
174+
self._data = None
175175

176176
def __iter__(self):
177-
return iter(self.data) # TODO write an iter that iterates over particles (instead of variables)
177+
return iter(self._data) # TODO write an iter that iterates over particles (instead of variables)
178178

179179
def __getattr__(self, name):
180180
"""
@@ -185,16 +185,16 @@ def __getattr__(self, name):
185185
name : str
186186
Name of the property
187187
"""
188-
if name in self.data:
189-
return self.data[name]
188+
if name in self._data:
189+
return self._data[name]
190190
if name in self.__dict__ and name[0] != "_":
191191
return self.__dict__[name]
192192
else:
193193
return False
194194

195195
def __getitem__(self, index):
196196
"""Get a single particle by index."""
197-
return self.data.sel(trajectory=index)
197+
return self._data.sel(trajectory=index)
198198

199199
@staticmethod
200200
def lonlatdepth_dtype_from_field_interp_method(field):
@@ -204,7 +204,7 @@ def lonlatdepth_dtype_from_field_interp_method(field):
204204

205205
@property
206206
def size(self):
207-
return (len(self.data["trajectory"]), len(self.data["obs"]))
207+
return (len(self._data["trajectory"]), len(self._data["obs"]))
208208

209209
@property
210210
def pclass(self):
@@ -214,7 +214,7 @@ def __repr__(self):
214214
return particleset_repr(self)
215215

216216
def __len__(self):
217-
return len(self.data["trajectory"])
217+
return len(self._data["trajectory"])
218218

219219
def add(self, particles):
220220
"""Add particles to the ParticleSet. Note that this is an
@@ -233,10 +233,10 @@ def add(self, particles):
233233
234234
"""
235235
if isinstance(particles, type(self)):
236-
particles.data["trajectory"] = (
237-
particles.data["trajectory"].values + self.data["trajectory"].values.max() + 1
236+
particles._data["trajectory"] = (
237+
particles._data["trajectory"].values + self._data["trajectory"].values.max() + 1
238238
)
239-
self.data = xr.concat([self.data, particles.data], dim="trajectory")
239+
self._data = xr.concat([self._data, particles._data], dim="trajectory")
240240
# Adding particles invalidates the neighbor search structure.
241241
self._dirty_neighbor = True
242242
return self
@@ -262,11 +262,11 @@ def __iadd__(self, particles):
262262

263263
def remove_indices(self, indices):
264264
"""Method to remove particles from the ParticleSet, based on their `indices`."""
265-
self.data = self.data.drop_sel(trajectory=indices)
265+
self._data = self._data.drop_sel(trajectory=indices)
266266

267267
def _active_particles_mask(self, time, dt):
268-
active_indices = (time - self.data["time"]) / dt >= 0
269-
non_err_indices = np.isin(self.data["state"], [StatusCode.Success, StatusCode.Evaluate])
268+
active_indices = (time - self._data["time"]) / dt >= 0
269+
non_err_indices = np.isin(self._data["state"], [StatusCode.Success, StatusCode.Evaluate])
270270
active_indices = np.logical_and(active_indices, non_err_indices)
271271
self._active_particle_idx = np.where(active_indices)[0]
272272
return active_indices
@@ -276,9 +276,9 @@ def _compute_neighbor_tree(self, time, dt):
276276

277277
self._values = np.vstack(
278278
(
279-
self.data["depth"],
280-
self.data["lat"],
281-
self.data["lon"],
279+
self._data["depth"],
280+
self._data["lat"],
281+
self._data["lon"],
282282
)
283283
)
284284
if self._dirty_neighbor:
@@ -292,14 +292,14 @@ def _neighbors_by_index(self, particle_idx):
292292
neighbor_idx = self._active_particle_idx[neighbor_idx]
293293
mask = neighbor_idx != particle_idx
294294
neighbor_idx = neighbor_idx[mask]
295-
if "horiz_dist" in self.data._ptype.variables:
296-
self.data["vert_dist"][neighbor_idx] = distances[0, mask]
297-
self.data["horiz_dist"][neighbor_idx] = distances[1, mask]
295+
if "horiz_dist" in self._data._ptype.variables:
296+
self._data["vert_dist"][neighbor_idx] = distances[0, mask]
297+
self._data["horiz_dist"][neighbor_idx] = distances[1, mask]
298298
return True # TODO fix for v4 ParticleDataIterator(self.particledata, subset=neighbor_idx)
299299

300300
def _neighbors_by_coor(self, coor):
301301
neighbor_idx = self._neighbor_tree.find_neighbors_by_coor(coor)
302-
neighbor_ids = self.data["id"][neighbor_idx]
302+
neighbor_ids = self._data["id"][neighbor_idx]
303303
return neighbor_ids
304304

305305
# TODO: This method is only tested in tutorial notebook. Add unit test?
@@ -317,13 +317,13 @@ def populate_indices(self):
317317
IN = np.all(~np.isnan(tree_data), axis=1)
318318
tree = KDTree(tree_data[IN, :])
319319
# stack all the particle positions for a single query
320-
pts = np.stack((self.particledata.data["lon"], self.particledata.data["lat"]), axis=-1)
320+
pts = np.stack((self._data["lon"], self._data["lat"]), axis=-1)
321321
# query datatype needs to match tree datatype
322322
_, idx_nan = tree.query(pts.astype(tree_data.dtype))
323323

324324
idx = np.where(IN)[0][idx_nan]
325325

326-
self.particledata.data["ei"][:, i] = idx # assumes that we are in the surface layer (zi=0)
326+
self._data["ei"][:, i] = idx # assumes that we are in the surface layer (zi=0)
327327

328328
@classmethod
329329
def from_list(
@@ -663,19 +663,19 @@ def Kernel(self, pyfunc):
663663
if isinstance(pyfunc, list):
664664
return Kernel.from_list(
665665
self.fieldset,
666-
self.data.ptype,
666+
self._data.ptype,
667667
pyfunc,
668668
)
669669
return Kernel(
670670
self.fieldset,
671-
self.data.ptype,
671+
self._data.ptype,
672672
pyfunc=pyfunc,
673673
)
674674

675675
def InteractionKernel(self, pyfunc_inter):
676676
if pyfunc_inter is None:
677677
return None
678-
return InteractionKernel(self.fieldset, self.data.ptype, pyfunc=pyfunc_inter)
678+
return InteractionKernel(self.fieldset, self._data.ptype, pyfunc=pyfunc_inter)
679679

680680
def ParticleFile(self, *args, **kwargs):
681681
"""Wrapper method to initialise a :class:`parcels.particlefile.ParticleFile` object from the ParticleSet."""
@@ -704,7 +704,9 @@ def data_indices(self, variable_name, compare_values, invert=False):
704704
compare_values = (
705705
np.array([compare_values]) if type(compare_values) not in [list, dict, np.ndarray] else compare_values
706706
)
707-
return np.where(np.isin(self.particledata.data[variable_name], compare_values, invert=invert))[0]
707+
return np.where(np.isin(self._data[variable_name], compare_values, invert=invert))[
708+
0
709+
] # TODO check if this can be faster with xarray indexing?
708710

709711
@property
710712
def _error_particles(self):
@@ -727,7 +729,7 @@ def _num_error_particles(self):
727729
int
728730
Number of error particles.
729731
"""
730-
return np.sum(np.isin(self.data["state"], [StatusCode.Success, StatusCode.Evaluate], invert=True))
732+
return np.sum(np.isin(self._data["state"], [StatusCode.Success, StatusCode.Evaluate], invert=True))
731733

732734
def set_variable_write_status(self, var, write_status):
733735
"""Method to set the write status of a Variable.
@@ -739,7 +741,7 @@ def set_variable_write_status(self, var, write_status):
739741
write_status :
740742
Write status of the variable (True, False or 'once')
741743
"""
742-
self.particledata.set_variable_write_status(var, write_status)
744+
self._data[var].set_variable_write_status(write_status)
743745

744746
def execute(
745747
self,
@@ -826,7 +828,7 @@ def execute(
826828

827829
outputdt = output_file.outputdt if output_file else None
828830

829-
self.data["dt"][:] = dt
831+
self._data["dt"][:] = dt
830832

831833
# Set up pbar
832834
if output_file:

tests/v4/test_particleset.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,16 +104,16 @@ def test_pset_add_explicit(fieldset):
104104
particle = ParticleSet(pclass=Particle, lon=lon[i], lat=lat[i], fieldset=fieldset)
105105
pset.add(particle)
106106
assert len(pset) == npart
107-
assert np.allclose(pset.data["lon"][:, 0], lon, atol=1e-12)
108-
assert np.allclose(pset.data["lat"][:, 0], lat, atol=1e-12)
109-
assert np.allclose(np.diff(pset.data.trajectory), np.ones(pset.data.trajectory.size - 1), atol=1e-12)
107+
assert np.allclose(pset._data["lon"][:, 0], lon, atol=1e-12)
108+
assert np.allclose(pset._data["lat"][:, 0], lat, atol=1e-12)
109+
assert np.allclose(np.diff(pset._data.trajectory), np.ones(pset._data.trajectory.size - 1), atol=1e-12)
110110

111111

112112
def test_pset_add_implicit(fieldset):
113113
pset = ParticleSet(fieldset, lon=np.zeros(3), lat=np.ones(3), pclass=Particle)
114114
pset += ParticleSet(fieldset, lon=np.ones(4), lat=np.zeros(4), pclass=Particle)
115115
assert len(pset) == 7
116-
assert np.allclose(np.diff(pset.data.trajectory), np.ones(6), atol=1e-12)
116+
assert np.allclose(np.diff(pset._data.trajectory), np.ones(6), atol=1e-12)
117117

118118

119119
@pytest.mark.parametrize("verbose_progress", [True, False])

0 commit comments

Comments
 (0)