Skip to content

Commit 1f1293b

Browse files
Chris BlantonChris Blanton
Chris Blanton
authored and
Chris Blanton
committed
#31 Use pathlib for filepath parsing, and cleanup
- remove undesired fms-user remap cache "feature" - remove some commented code - add automatic exit code checking for the fregrid system calls
1 parent c18dedd commit 1f1293b

File tree

1 file changed

+33
-51
lines changed

1 file changed

+33
-51
lines changed

app/regrid-xy/regrid_xy.py

+33-51
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@
1515
import metomi.rose.config as rose_cfg
1616
from netCDF4 import Dataset
1717

18-
FREGRID_SHARED_FILES='/home/fms/shared_fregrid_remap_files'
19-
2018
# formerly in shared.sh
2119
def truncate_date(date, freq):
2220
format=freq_to_date_format(freq)
@@ -164,9 +162,7 @@ def regrid_xy( ):
164162
'''
165163

166164
## rose config load check
167-
config_name = os.getcwd()
168-
config_name += '/rose-app-run.conf'
169-
#config_name += '/rose-app.conf'
165+
config_name = Path.cwd().joinpath('rose-app-run.conf')
170166
print(f'config_name = {config_name}')
171167
try:
172168
rose_app_config = rose_cfg.load(config_name)
@@ -176,24 +172,19 @@ def regrid_xy( ):
176172

177173

178174
# mandatory arguments- code exits if any of these are not present
179-
input_dir = os.getenv( 'inputDir' )
180-
output_dir = os.getenv( 'outputDir' )
175+
input_dir = Path(os.getenv( 'inputDir' ))
176+
output_dir = Path(os.getenv( 'outputDir' ))
181177
begin = os.getenv( 'begin' )
182-
tmp_dir = os.getenv( 'TMPDIR' )
183-
remap_dir = os.getenv( 'fregridRemapDir' )
178+
tmp_dir = Path(os.getenv( 'TMPDIR' ))
179+
remap_dir = Path(os.getenv( 'fregridRemapDir' ))
184180
source = os.getenv( 'source' )
185-
grid_spec = os.getenv( 'gridSpec' )
181+
grid_spec = Path(os.getenv( 'gridSpec' ))
186182
def_xy_interp = os.getenv( 'defaultxyInterp' )
187183
if None in [ input_dir , output_dir ,
188184
begin , tmp_dir ,
189185
remap_dir , source ,
190186
grid_spec , def_xy_interp ]:
191187
raise Exception(f'a mandatory input argument is not present in {config_name})')
192-
# if any( [ input_dir is None, output_dir is None,
193-
# begin is None, tmp_dir is None,
194-
# remap_dir is None, source is None,
195-
# grid_spec is None, def_xy_interp is None ] ):
196-
# raise Exception(f'a mandatory input argument is not present in {config_name}')
197188

198189
def_xy_interp = def_xy_interp.split(',')
199190
def_xy_interp[0] = def_xy_interp[0].replace('"', '')
@@ -213,39 +204,39 @@ def regrid_xy( ):
213204
f'default xy interpolation has invalid format: \n def_xy_interp = {def_xy_interp}')
214205

215206
# input dir must exist
216-
if not Path( input_dir ).exists():
207+
if not input_dir.exists():
217208
raise Exception(f'input_dir={input_dir} \n does not exist')
218209

219210
# tmp_dir check
220-
if not Path( tmp_dir ).exists():
211+
if not tmp_dir.exists():
221212
raise Exception(f'tmp_dir={tmp_dir} \n does not exist.')
222213

223214
# output dir check
224-
Path( output_dir ).mkdir( parents = True, exist_ok = True )
225-
if not Path( output_dir ).exists() :
215+
output_dir.mkdir( parents = True, exist_ok = True )
216+
if not output_dir.exists() :
226217
raise Exception('the following does not exist and/or could not be created:' +
227218
f'output_dir=\n{output_dir}')
228219

229220
# work/ dir check
230-
work_dir = tmp_dir + 'work/'
231-
Path( work_dir ).mkdir( exist_ok = True )
232-
if not Path( work_dir ).exists():
221+
work_dir = tmp_dir.joinpath('work')
222+
work_dir.mkdir( exist_ok = True )
223+
if not work_dir.exists():
233224
raise Exception('the following does not exist and/or could not be created:' +
234225
f'work_dir=\n{work_dir}')
235226

236227

237228
# fregrid remap dir check
238-
Path(remap_dir).mkdir( exist_ok = True )
239-
if not Path( remap_dir ).exists():
229+
remap_dir.mkdir( exist_ok = True )
230+
if not remap_dir.exists():
240231
raise Exception(f'{remap_dir} could not be created')
241232

242233

243234
# grid_spec file management
244-
starting_dir = os.getcwd()
235+
starting_dir = Path.cwd()
245236
os.chdir(work_dir)
246237
if '.tar' in grid_spec:
247238
untar_sp = \
248-
subprocess.run( ['tar', '-xvf', grid_spec], check = False , capture_output = True)
239+
subprocess.run( ['tar', '-xvf', grid_spec], check = True , capture_output = True)
249240
if untar_sp.returncode != 0:
250241
raise Exception(
251242
f'untarring of {grid_spec} file failed, ret_code={untar_sp.returncode}, stderr={untar_sp.stderr}')
@@ -257,7 +248,7 @@ def regrid_xy( ):
257248
raise Exception(f'grid_spec_file cannot be determined from grid_spec={grid_spec}')
258249
else:
259250
try:
260-
grid_spec_file=grid_spec.split('/').pop()
251+
grid_spec_file = grid_spec.name()
261252
shutil.copy(grid_spec, grid_spec_file )
262253
except Exception as exc:
263254
raise Exception(f'grid_spec={grid_spec} could not be copied.') \
@@ -299,18 +290,17 @@ def regrid_xy( ):
299290

300291
#target input variable resolution
301292
is_tiled = 'cubedsphere' in input_grid
302-
target_file = input_dir
303-
target_file += f"/{truncate_date(begin,'P1D')}.{source}.tile1.nc" \
293+
target_file = input_dir.joinpath(truncate_date(begin, 'P1D') + f".{source}.tile1.nc")
304294
if is_tiled \
305-
else f"/{truncate_date(begin,'P1D')}.{source}.nc"
295+
else input_dir.joinpath(truncate_date(begin,'P1D') + f".{source}.nc")
306296
if not Path( target_file ).exists():
307297
raise Exception(f'regrid_xy target does not exist. \ntarget_file={target_file}')
308298
print(f'target_file={target_file}') #DELETE
309299

310300

311301
# optional per-component inputs
312302
output_grid_type = safe_rose_config_get( rose_app_config, component, 'outputGridType')
313-
remap_file = safe_rose_config_get( rose_app_config, component, 'fregridRemapFile')
303+
remap_file = Path(safe_rose_config_get( rose_app_config, component, 'fregridRemapFile'))
314304
more_options = safe_rose_config_get( rose_app_config, component, 'fregridMoreOptions')
315305
regrid_vars = safe_rose_config_get( rose_app_config, component, 'variables')
316306
output_grid_lon = safe_rose_config_get( rose_app_config, component, 'outputGridLon')
@@ -359,7 +349,7 @@ def regrid_xy( ):
359349
if remap_file is not None:
360350
try:
361351
shutil.copy( remap_file,
362-
remap_file.split('/').pop() )
352+
remap_file.name() )
363353
except Exception as exc:
364354
raise Exception('remap_file={remap_file} could not be copied to local dir') \
365355
from exc
@@ -372,24 +362,16 @@ def regrid_xy( ):
372362
else \
373363
f'fregrid_remap_file_{def_xy_interp(0)}_by_{def_xy_interp(1)}.nc'
374364
remap_cache_file = \
375-
f'{remap_dir}/{input_grid}/{input_realm}/' + \
376-
f'{source_nx}-by-{source_ny}/{interp_method}/{remap_file}'
377-
central_remap_cache_file = \
378-
f'{FREGRID_SHARED_FILES}/{input_grid}/' + \
379-
f'{source_nx}_by_{source_ny}/{remap_file}'
365+
remap_dir.joinpath(input_grid, input_realm}, \
366+
f'{source_nx}-by-{source_ny}, interp_method, remap_file')
380367

381368
print(f'remap_file = {remap_file }' + \
382-
f'remap_cache_file = {remap_cache_file }' + \
383-
f'central_remap_cache_file = {central_remap_cache_file}' )
369+
f'remap_cache_file = {remap_cache_file }')
384370

385371
if Path( remap_cache_file ).exists():
386372
print(f'NOTE: using cached remap file {remap_cache_file}')
387373
shutil.copy(remap_cache_file,
388-
remap_cache_file.split('/').pop())
389-
elif Path( central_remap_cache_file ).exists():
390-
print(f'NOTE: using centrally cached remap file {remap_cache_file}')
391-
shutil.copy(central_remap_cache_file,
392-
central_remap_cache_file.split('/').pop())
374+
remap_cache_file.name())
393375

394376

395377

@@ -410,13 +392,13 @@ def regrid_xy( ):
410392
input_file = target_file.replace('.tile1.nc','') \
411393
if '.tile1' in target_file \
412394
else target_file
413-
input_file=input_file.split('/').pop()
395+
input_file=input_file.name()
414396

415397
# create output file argument...
416398
output_file = target_file.replace('.tile1','') \
417399
if 'tile1' in target_file \
418400
else target_file
419-
output_file = output_file.split('/').pop()
401+
output_file = output_file.name()
420402

421403
fregrid_command = [
422404
'fregrid',
@@ -436,25 +418,25 @@ def regrid_xy( ):
436418
fregrid_command.append(f'{more_options}')
437419

438420
print(f"\n\nabout to run the following command: \n{' '.join(fregrid_command)}\n")
439-
fregrid_proc = subprocess.run( fregrid_command, check = False )#i hate it
421+
fregrid_proc = subprocess.run( fregrid_command, check = True )
440422
fregrid_rc =fregrid_proc.returncode
441423
print(f'fregrid_result.returncode()={fregrid_rc}')
442424

443425

444426
# output wrangling
445427

446428
# copy the remap file to the cache location
447-
if not Path( remap_cache_file ).exists():
448-
remap_cache_file_dir='/'.join(remap_cache_file.split('/')[0:-1])
449-
Path( remap_cache_file_dir ).mkdir( parents = True , exist_ok = True)
429+
if not remap_cache_file.exists():
430+
remap_cache_file_dir=remap_cache_file.parent()
431+
remap_cache_file_dir.mkdir( parents = True , exist_ok = True)
450432
print(f'copying \nremap_file={remap_file} to')
451433
print(f'remap_cache_file_dir={remap_cache_file_dir}')
452434
shutil.copy(remap_file, remap_cache_file_dir)
453435

454436
# more output wrangling
455437
final_output_dir = output_dir \
456438
if output_grid_type is None \
457-
else output_dir + '/' + output_grid_type
439+
else output_dir.joinpath(output_grid_type)
458440
Path( final_output_dir ).mkdir( exist_ok = True)
459441

460442
print(f'TRYING TO COPY {output_file} TO {final_output_dir}')

0 commit comments

Comments
 (0)