-
Notifications
You must be signed in to change notification settings - Fork 120
/
test_particle_file.py
403 lines (319 loc) · 16.2 KB
/
test_particle_file.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
from parcels import (FieldSet, ScipyParticle, JITParticle, Variable, ErrorCode, AdvectionRK4)
from parcels.particlefile import _set_calendar
from parcels.tools.converters import _get_cftime_calendars, _get_cftime_datetimes
from parcels import ParticleSetSOA, ParticleFileSOA, KernelSOA # noqa
from parcels import ParticleSetAOS, ParticleFileAOS, KernelAOS # noqa
from parcels import ParticleSetNodes, ParticleFileNodes, KernelNodes # noqa
from parcels import GenerateID_Service, SequentialIdGenerator, LibraryRegisterC # noqa
import numpy as np
import pytest
import os
from netCDF4 import Dataset
import cftime
import random as py_random
from datetime import timedelta as delta
pset_modes = ['soa', 'aos', 'nodes']
ptype = {'scipy': ScipyParticle, 'jit': JITParticle}
pset_type = {'soa': {'pset': ParticleSetSOA, 'pfile': ParticleFileSOA, 'kernel': KernelSOA},
'aos': {'pset': ParticleSetAOS, 'pfile': ParticleFileAOS, 'kernel': KernelAOS},
'nodes': {'pset': ParticleSetNodes, 'pfile': ParticleFileNodes, 'kernel': KernelNodes}}
def fieldset(xdim=40, ydim=100):
U = np.zeros((ydim, xdim), dtype=np.float32)
V = np.zeros((ydim, xdim), dtype=np.float32)
lon = np.linspace(0, 1, xdim, dtype=np.float32)
lat = np.linspace(-60, 60, ydim, dtype=np.float32)
depth = np.zeros(1, dtype=np.float32)
data = {'U': np.array(U, dtype=np.float32), 'V': np.array(V, dtype=np.float32)}
dimensions = {'lat': lat, 'lon': lon, 'depth': depth}
return FieldSet.from_data(data, dimensions)
@pytest.fixture(name="fieldset")
def fieldset_ficture(xdim=40, ydim=100):
return fieldset(xdim=xdim, ydim=ydim)
def close_and_compare_netcdffiles(filepath, ofile, assystemcall=False):
if assystemcall:
os.system('parcels_convert_npydir_to_netcdf %s -c %s' % (ofile.tempwritedir_base, ofile.__class__.__name__,))
else:
import parcels.scripts.convert_npydir_to_netcdf as convert
convert.convert_npydir_to_netcdf(ofile.tempwritedir_base, pfile_class=ofile.__class__.__name__)
ncfile1 = Dataset(filepath, 'r', 'NETCDF4')
ofile.name = filepath + 'b.nc'
ofile.export()
ncfile2 = Dataset(filepath + 'b.nc', 'r', 'NETCDF4')
for v in ncfile2.variables.keys():
assert np.allclose(ncfile1.variables[v][:], ncfile2.variables[v][:])
for a in ncfile2.ncattrs():
if a != 'parcels_version':
assert getattr(ncfile1, a) == getattr(ncfile2, a)
ncfile2.close()
return ncfile1
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_pfile_nointegerremainer_timeswritten(fieldset, pset_mode, mode, tmpdir, npart=10):
filepath = tmpdir.join("pfile_nointegerremainer_timeswritten.nc")
def DeleteP(particle, fieldset, time):
particle.delete()
lon = np.linspace(0.05, 0.95, npart)
lat = np.linspace(0.95, 0.05, npart)
# while in float64 or decimal arithmetic (100*0.005) == (10*0.05) [hence only 1 final outfile.write()),
# in float32 digital arithmetic (100*0.005) != (10*0.05) [as in datetime.timedelta],
# leading to a 'ghost'-'outfile.write()' command. This is tested to be taken care off here, similar to:
# parcels/examples/example_dask_chunk_OCMs.py::test_swash(...)
(dt, outdt, runtime) = (delta(seconds=0.005), delta(seconds=0.05), delta(seconds=0.5))
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode], lon=lon, lat=lat)
outfile = pset.ParticleFile(name=filepath, outputdt=outdt)
pset.execute(AdvectionRK4, runtime=runtime, dt=dt, output_file=outfile,
recovery={ErrorCode.ErrorOutOfBounds: DeleteP})
outfile.close()
del pset
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_pfile_array_remove_particles(fieldset, pset_mode, mode, tmpdir, npart=10):
filepath = tmpdir.join("pfile_array_remove_particles.nc")
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode],
lon=np.linspace(0, 1, npart),
lat=0.5*np.ones(npart), time=0)
pfile = pset.ParticleFile(filepath)
pfile.write(pset, 0)
if pset_mode != 'nodes':
pset.remove_indices(3)
else:
ndata = pset.begin().next.next
pset.remove(ndata)
for p in pset:
p.time = 1
pfile.write(pset, 1)
ncfile = close_and_compare_netcdffiles(filepath, pfile)
timearr = ncfile.variables['time'][:]
if pset_mode != 'nodes':
assert type(timearr[3, 1]) is not type(timearr[3, 0]) # noqa
ncfile.close()
del pset
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_pfile_set_towrite_False(fieldset, pset_mode, mode, tmpdir, npart=10):
filepath = tmpdir.join("pfile_set_towrite_False.nc")
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode],
lon=np.linspace(0, 1, npart),
lat=0.5*np.ones(npart))
pset.set_variable_write_status('depth', False)
pset.set_variable_write_status('lat', False)
pfile = pset.ParticleFile(filepath, outputdt=1)
def Update_lon(particle, fieldset, time):
particle.lon += 0.1
pset.execute(Update_lon, runtime=10, output_file=pfile)
ncfile = close_and_compare_netcdffiles(filepath, pfile)
assert 'time' in ncfile.variables
assert 'depth' not in ncfile.variables
assert 'lat' not in ncfile.variables
ncfile.close()
# For pytest purposes, we need to reset to original status
pset.set_variable_write_status('depth', True)
pset.set_variable_write_status('lat', True)
del pset
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_pfile_array_remove_all_particles(fieldset, pset_mode, mode, tmpdir, npart=10):
filepath = tmpdir.join("pfile_array_remove_particles.nc")
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode],
lon=np.linspace(0, 1, npart),
lat=0.5*np.ones(npart), time=0)
pfile = pset.ParticleFile(filepath)
pfile.write(pset, 0)
if pset_mode != 'nodes':
for _ in range(npart):
pset.remove_indices(-1)
else:
ndata = pset.end()
while ndata is not None:
del_item = ndata
ndata = ndata.prev
pset.remove(del_item)
pfile.write(pset, 1)
pfile.write(pset, 2)
ncfile = close_and_compare_netcdffiles(filepath, pfile)
assert ncfile.variables['time'][:].shape == (npart, 1)
ncfile.close()
del pset
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
@pytest.mark.parametrize('assystemcall', [True, False])
def test_variable_written_ondelete(fieldset, pset_mode, mode, tmpdir, assystemcall, npart=3):
filepath = tmpdir.join("pfile_on_delete_written_variables.nc")
def move_west(particle, fieldset, time):
tmp = fieldset.U[time, particle.depth, particle.lat, particle.lon] # to trigger out-of-bounds error
particle.lon -= 0.1 + tmp
def DeleteP(particle, fieldset, time):
particle.delete()
lon = np.linspace(0.05, 0.95, npart)
lat = np.linspace(0.95, 0.05, npart)
(dt, runtime) = (0.1, 0.8)
lon_end = lon - runtime/dt*0.1
noutside = len(lon_end[lon_end < 0])
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode], lon=lon, lat=lat)
outfile = pset.ParticleFile(name=filepath, write_ondelete=True)
outfile.add_metadata('runtime', runtime)
pset.execute(move_west, runtime=runtime, dt=dt, output_file=outfile,
recovery={ErrorCode.ErrorOutOfBounds: DeleteP})
ncfile = close_and_compare_netcdffiles(filepath, outfile, assystemcall=assystemcall)
assert ncfile.runtime == runtime
lon = ncfile.variables['lon'][:]
assert (lon.size == noutside)
ncfile.close()
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_variable_write_double(fieldset, pset_mode, mode, tmpdir):
filepath = tmpdir.join("pfile_variable_write_double.nc")
def Update_lon(particle, fieldset, time):
particle.lon += 0.1
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode], lon=[0], lat=[0], lonlatdepth_dtype=np.float64)
ofile = pset.ParticleFile(name=filepath, outputdt=0.00001)
pset.execute(pset.Kernel(Update_lon), endtime=0.001, dt=0.00001, output_file=ofile)
ncfile = close_and_compare_netcdffiles(filepath, ofile)
lons = ncfile.variables['lon'][:]
assert (isinstance(lons[0, 0], np.float64))
ncfile.close()
@pytest.mark.parametrize('pset_mode', ['aos', 'soa'])
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_write_dtypes_pfile(fieldset, mode, pset_mode, tmpdir):
filepath = tmpdir.join("pfile_dtypes.nc")
dtypes = ['float32', 'float64', 'int32', 'int64']
if mode == 'scipy':
dtypes.append('bool_') # bool only implemented in scipy
class MyParticle(ptype[mode]):
for d in dtypes:
# need an exec() here because we need to dynamically set the variable name
exec(f'v_{d} = Variable("v_{d}", dtype=np.{d}, initial=0.)')
pset = pset_type[pset_mode]['pset'](fieldset, pclass=MyParticle, lon=0, lat=0)
pfile = pset.ParticleFile(name=filepath, outputdt=1)
pfile.write(pset, 0)
ncfile = close_and_compare_netcdffiles(filepath, pfile)
for d in dtypes:
nc_fmt = d if d != 'bool_' else 'i1'
assert ncfile.variables[f'v_{d}'].dtype == nc_fmt
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
@pytest.mark.parametrize('npart', [1, 2, 5])
def test_variable_written_once(fieldset, pset_mode, mode, tmpdir, npart):
filepath = tmpdir.join("pfile_once_written_variables.nc")
def Update_v(particle, fieldset, time):
particle.v_once += 1.
particle.age += particle.dt
class MyParticle(ptype[mode]):
v_once = Variable('v_once', dtype=np.float64, initial=0., to_write='once')
age = Variable('age', dtype=np.float32, initial=0.)
lon = np.linspace(0, 1, npart)
lat = np.linspace(1, 0, npart)
time = np.arange(0, npart/10., 0.1, dtype=np.float64)
pset = pset_type[pset_mode]['pset'](fieldset, pclass=MyParticle, lon=lon, lat=lat, time=time, v_once=time)
ofile = pset.ParticleFile(name=filepath, outputdt=0.1)
pset.execute(pset.Kernel(Update_v), endtime=1, dt=0.1, output_file=ofile)
assert np.allclose(pset.v_once - time - pset.age*10, 0, atol=1e-5)
ncfile = close_and_compare_netcdffiles(filepath, ofile)
vfile = np.ma.filled(ncfile.variables['v_once'][:], np.nan)
assert (vfile.shape == (npart, ))
assert np.allclose(vfile, time)
ncfile.close()
del pset
@pytest.mark.parametrize('type', ['repeatdt', 'timearr'])
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
@pytest.mark.parametrize('repeatdt', range(1, 3))
@pytest.mark.parametrize('dt', [-1, 1])
@pytest.mark.parametrize('maxvar', [2, 4, 10])
def test_pset_repeated_release_delayed_adding_deleting(type, fieldset, pset_mode, mode, repeatdt, tmpdir, dt, maxvar, runtime=10):
fieldset.maxvar = maxvar
pset = None
class MyParticle(ptype[mode]):
sample_var = Variable('sample_var', initial=0.)
v_once = Variable('v_once', dtype=np.float64, initial=0., to_write='once')
if type == 'repeatdt':
pset = pset_type[pset_mode]['pset'](fieldset, lon=[0], lat=[0], pclass=MyParticle, repeatdt=repeatdt)
elif type == 'timearr':
pset = pset_type[pset_mode]['pset'](fieldset, lon=np.zeros(runtime), lat=np.zeros(runtime), pclass=MyParticle, time=list(range(runtime)))
outfilepath = tmpdir.join("pfile_repeated_release.nc")
pfile = pset.ParticleFile(outfilepath, outputdt=abs(dt))
def IncrLon(particle, fieldset, time):
particle.sample_var += 1.
if particle.sample_var > fieldset.maxvar:
particle.delete()
for i in range(runtime):
pset.execute(IncrLon, dt=dt, runtime=1., output_file=pfile)
ncfile = close_and_compare_netcdffiles(outfilepath, pfile)
samplevar = ncfile.variables['sample_var'][:]
for k in range(samplevar.shape[1]):
assert np.allclose([p for p in samplevar[:, k] if np.isfinite(p)], k)
if type == 'repeatdt':
# Comment: this would not work with node-based lists where ID != index and array indices are (necessarily) reused. #
assert samplevar.shape == (runtime // repeatdt+1, min(maxvar+1, runtime)+1)
assert np.allclose(pset.sample_var, np.arange(maxvar, -1, -repeatdt))
elif type == 'timearr':
# Comment: this would not work with node-based lists where ID != index and array indices are (necessarily) reused. #
assert samplevar.shape == (runtime, min(maxvar + 1, runtime) + 1)
filesize = os.path.getsize(str(outfilepath))
assert filesize < 1024 * 65 # test that chunking leads to filesize less than 65KB
ncfile.close()
del pset
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_write_timebackward(fieldset, pset_mode, mode, tmpdir):
outfilepath = tmpdir.join("pfile_write_timebackward.nc")
def Update_lon(particle, fieldset, time):
particle.lon -= 0.1 * particle.dt
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode],
lat=np.linspace(0, 1, 3), lon=[0, 0, 0], time=[1, 2, 3])
pfile = pset.ParticleFile(name=outfilepath, outputdt=1.)
pset.execute(pset.Kernel(Update_lon), runtime=4, dt=-1.,
output_file=pfile)
ncfile = close_and_compare_netcdffiles(outfilepath, pfile)
trajs = ncfile.variables['trajectory'][:, 0]
assert np.all(np.diff(trajs) > 0) # all particles written in order of traj ID
del pset
def test_set_calendar():
for calendar_name, cf_datetime in zip(_get_cftime_calendars(), _get_cftime_datetimes()):
date = getattr(cftime, cf_datetime)(1990, 1, 1)
assert _set_calendar(date.calendar) == date.calendar
assert _set_calendar('np_datetime64') == 'standard'
@pytest.mark.parametrize('pset_mode', pset_modes)
def test_error_duplicate_outputdir(fieldset, tmpdir, pset_mode):
outfilepath = tmpdir.join("error_duplicate_outputdir.nc")
idgen = None
c_lib_register = None
pset = None
if pset_mode != 'nodes':
pset1 = pset_type[pset_mode]['pset'](fieldset, pclass=JITParticle, lat=0, lon=0)
pset2 = pset_type[pset_mode]['pset'](fieldset, pclass=JITParticle, lat=0, lon=0)
else:
idgen = GenerateID_Service(SequentialIdGenerator)
idgen.setTimeLine(0.0, 1.0)
c_lib_register = LibraryRegisterC()
pset1 = pset_type[pset_mode]['pset'](fieldset, pclass=JITParticle, lat=0, lon=0, idgen=idgen, c_lib_register=c_lib_register)
pset2 = pset_type[pset_mode]['pset'](fieldset, pclass=JITParticle, lat=0, lon=0, idgen=idgen, c_lib_register=c_lib_register)
py_random.seed(1234)
pfile1 = pset1.ParticleFile(name=outfilepath, outputdt=1., convert_at_end=False)
py_random.seed(1234)
error_thrown = False
try:
pset2.ParticleFile(name=outfilepath, outputdt=1., convert_at_end=False)
except IOError:
error_thrown = True
assert error_thrown
pfile1.delete_tempwritedir()
del pset
if idgen is not None:
idgen.close()
del idgen
if c_lib_register is not None:
c_lib_register.clear()
del c_lib_register
@pytest.mark.parametrize('pset_mode', pset_modes)
@pytest.mark.parametrize('mode', ['scipy', 'jit'])
def test_reset_dt(fieldset, pset_mode, mode, tmpdir):
# Assert that p.dt gets reset when a write_time is not a multiple of dt
# for p.dt=0.02 to reach outputdt=0.05 and endtime=0.1, the steps should be [0.2, 0.2, 0.1, 0.2, 0.2, 0.1], resulting in 6 kernel executions
filepath = tmpdir.join("pfile_reset_dt.nc")
def Update_lon(particle, fieldset, time):
particle.lon += 0.1
pset = pset_type[pset_mode]['pset'](fieldset, pclass=ptype[mode], lon=[0], lat=[0], lonlatdepth_dtype=np.float64)
ofile = pset.ParticleFile(name=filepath, outputdt=0.05)
pset.execute(pset.Kernel(Update_lon), endtime=0.1, dt=0.02, output_file=ofile)
assert np.allclose(pset.lon, .6)