Skip to content

Commit 99ddb03

Browse files
committed
BUG: Fix corrupt ParticleFile writing
1 parent b75dcb7 commit 99ddb03

2 files changed

Lines changed: 31 additions & 25 deletions

File tree

src/parcels/_core/particlefile.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,12 @@ def close(self):
183183
self._writer.close()
184184
self._writer = None
185185

186+
def __enter__(self):
187+
return self
188+
189+
def __exit__(self, *args):
190+
self.close()
191+
186192

187193
def _get_vars_to_write(particle: ParticleClass) -> list[Variable]:
188194
return [v for v in particle.variables if v.to_write is not False]

src/parcels/_core/particleset.py

Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import types
44
import warnings
55
from collections.abc import Iterable
6+
from contextlib import nullcontext
67
from typing import Literal
78

89
import numpy as np
@@ -433,32 +434,31 @@ def execute(
433434
next_output = start_time + outputdt * sign_dt
434435

435436
time = start_time
436-
while sign_dt * (time - end_time) < 0:
437-
if next_output is not None:
438-
f = min if sign_dt > 0 else max
439-
next_time = f(next_output, end_time)
440-
else:
441-
next_time = end_time
442-
443-
self._kernel.execute(self, endtime=next_time, dt=dt)
444-
445-
if next_output is not None:
446-
if np.abs(next_time - next_output) < 0.001:
447-
if output_file:
448-
output_file.write(self, next_output)
449-
if np.isfinite(outputdt):
450-
next_output += outputdt * sign_dt
451437

452-
if verbose_progress:
453-
pbar.set_description_str(
454-
"Integration time: " + str(float_to_datelike(time, self.fieldset.time_interval))
455-
)
456-
pbar.update(sign_dt * (next_time - time))
457-
458-
time = next_time
459-
460-
if output_file is not None:
461-
output_file.close()
438+
with output_file if output_file is not None else nullcontext():
439+
while sign_dt * (time - end_time) < 0:
440+
if next_output is not None:
441+
f = min if sign_dt > 0 else max
442+
next_time = f(next_output, end_time)
443+
else:
444+
next_time = end_time
445+
446+
self._kernel.execute(self, endtime=next_time, dt=dt)
447+
448+
if next_output is not None:
449+
if np.abs(next_time - next_output) < 0.001:
450+
if output_file:
451+
output_file.write(self, next_output)
452+
if np.isfinite(outputdt):
453+
next_output += outputdt * sign_dt
454+
455+
if verbose_progress:
456+
pbar.set_description_str(
457+
"Integration time: " + str(float_to_datelike(time, self.fieldset.time_interval))
458+
)
459+
pbar.update(sign_dt * (next_time - time))
460+
461+
time = next_time
462462

463463
if verbose_progress:
464464
pbar.close()

0 commit comments

Comments
 (0)