Skip to content

Commit 5b7148e

Browse files
committed
Determine filename in plates before iterating
This eliminates the need for the awkward InchoateFiles context manager.
1 parent 494a02e commit 5b7148e

File tree

2 files changed

+7
-100
lines changed

2 files changed

+7
-100
lines changed

stagpy/misc.py

Lines changed: 0 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
"""Miscellaneous definitions."""
22

33
from inspect import getdoc
4-
import pathlib
5-
import shutil
6-
import tempfile
74

85
import matplotlib.pyplot as plt
96

@@ -152,82 +149,3 @@ def __get__(self, instance, _):
152149
def __set__(self, instance, _):
153150
raise AttributeError(
154151
f'Cannot set {self._name} property of {instance!r}')
155-
156-
157-
class InchoateFiles:
158-
"""Context manager handling files whose names are not known yet.
159-
160-
Example:
161-
InchoateFiles is used here to manage three files::
162-
163-
with InchoateFiles(3) as incho:
164-
# for convenience, incho[x] is the same as incho.fids[x]
165-
incho[0].write('First file')
166-
incho[1].write('Second file')
167-
incho[2].write('Third file')
168-
169-
# the three files will be named 'tata', 'titi' and 'toto'
170-
incho.fnames = ['tata', 'titi', 'toto']
171-
172-
Args:
173-
nfiles (int): number of files. Defaults to 1.
174-
tmp_prefix (str): prefix name of temporary files. Use this
175-
parameter if you want to easily track down the temporary files
176-
created by the manager.
177-
"""
178-
179-
def __init__(self, nfiles=1, tmp_prefix=None):
180-
self._fnames = [f'inchoate{i}' for i in range(nfiles)]
181-
self._tmpprefix = tmp_prefix
182-
self._fids = []
183-
184-
@property
185-
def fids(self):
186-
"""List of files id.
187-
188-
Use this to perform operations on files when the context manager is
189-
used. :meth:`InchoateFiles.__getitem__` is implemented in order to
190-
provide direct access to this property content (``self[x]`` is the
191-
same as ``self.fids[x]``).
192-
"""
193-
return self._fids
194-
195-
@property
196-
def fnames(self):
197-
"""List of filenames.
198-
199-
Set this to the list of final filenames before exiting the context
200-
manager. If this list is not set by the user, the produced files will
201-
be named ``'inchoateN'`` with ``N`` the index of the file. If the list
202-
of names you set is too long, it will be truncated. If it is too short,
203-
extra files will be named ``'inchoateN'``.
204-
"""
205-
return self._fnames
206-
207-
@fnames.setter
208-
def fnames(self, names):
209-
"""Ensure constant size of fnames."""
210-
names = list(names[:len(self._fnames)])
211-
self._fnames = names + self._fnames[len(names):]
212-
213-
def __getitem__(self, idx):
214-
return self._fids[idx]
215-
216-
def __enter__(self):
217-
"""Create temporary files."""
218-
for fname in self.fnames:
219-
pfx = fname if self._tmpprefix is None else self._tmpprefix
220-
self._fids.append(
221-
tempfile.NamedTemporaryFile(
222-
mode='w', prefix=pfx, delete=False))
223-
return self
224-
225-
def __exit__(self, *exc_info):
226-
"""Give temporary files their final names."""
227-
for tmp in self._fids:
228-
tmp.close()
229-
if exc_info[0] is None:
230-
for fname, tmp in zip(self.fnames, self._fids):
231-
shutil.copyfile(tmp.name, fname)
232-
for tmp in self._fids:
233-
pathlib.Path(tmp.name).unlink()

stagpy/plates.py

Lines changed: 7 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Plate analysis."""
22

3-
import pathlib
3+
from contextlib import ExitStack
44

55
import matplotlib.pyplot as plt
66
import numpy as np
@@ -611,19 +611,19 @@ def main_plates(sdat):
611611
isurf = -1
612612
vrms_surface = uprof_averaged.iloc[isurf]
613613

614-
with misc.InchoateFiles(8, 'plates') as fids:
615-
fids.fnames = ['plate_velocity', 'distance_subd', 'continents',
616-
'flux', 'topography', 'age', 'velderiv', 'velocity']
614+
# determine names of files
615+
fnames = ['plate_velocity', 'distance_subd', 'continents',
616+
'flux', 'topography', 'age', 'velderiv', 'velocity']
617+
fnames = [f'plates_{stem}_{sdat.walk.stepstr}' for stem in fnames]
618+
with ExitStack() as stack:
619+
fids = [stack.enter_context(open(fname)) for fname in fnames]
617620
fids[0].write('# it time ph_trench vel_trench age_trench\n')
618621
fids[1].write('# it time time [My] distance '
619622
'ph_trench ph_cont age_trench [My]\n')
620623

621-
istart, iend = None, None
622624
for step in sdat.walk.filter(fields=['T']):
623625
# could check other fields too
624626
timestep = step.isnap
625-
istart = timestep if istart is None else istart
626-
iend = timestep
627627
print('Treating snapshot', timestep)
628628

629629
rcmb = step.geom.rcmb
@@ -760,17 +760,6 @@ def main_plates(sdat):
760760

761761
misc.saveplot(fig, 'sx', timestep)
762762

763-
# determine names of files
764-
ptn = misc.out_name('{}_{}_{}')
765-
stem = ptn.format(fids.fnames[0], istart, iend)
766-
idx = 0
767-
fmt = '{}.dat'
768-
while pathlib.Path(fmt.format(stem, idx)).is_file():
769-
fmt = '{}_{}.dat'
770-
idx += 1
771-
fids.fnames = [fmt.format(ptn.format(fname, istart, iend), idx)
772-
for fname in fids.fnames]
773-
774763

775764
def cmd():
776765
"""Implementation of plates subcommand.

0 commit comments

Comments
 (0)