Skip to content

Commit edcfec9

Browse files
committed
pylint feedback and tidy up
1 parent 1ff19b1 commit edcfec9

File tree

6 files changed

+69
-73
lines changed

6 files changed

+69
-73
lines changed

fre/cmor/cmor_helpers.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,11 +43,11 @@
4343
import glob
4444
import json
4545
import logging
46-
import numpy as np
4746
import os
4847
from pathlib import Path
49-
from typing import Optional, Any, List, Union
48+
from typing import Optional, List, Union
5049

50+
import numpy as np
5151
from netCDF4 import Dataset, Variable
5252

5353
fre_logger = logging.getLogger(__name__)
@@ -351,15 +351,6 @@ def get_json_file_data( json_file_path: Optional[str] = None) -> dict:
351351
) from exc
352352

353353

354-
def get_exp_cfg_mip_era(json_file_path: Optional[str] = None) -> str:
355-
"""
356-
:param json_file_path: Path to the experiment metadata JSON file.
357-
:type json_file_path: str
358-
:return: string representing mip era for which the JSON file is intended
359-
:rtype: str
360-
"""
361-
mip_era=get_json_file_data(json_file_path)['mip_era']
362-
363354
def update_grid_and_label( json_file_path: str,
364355
new_grid_label: str,
365356
new_grid: str,
@@ -419,7 +410,7 @@ def update_grid_and_label( json_file_path: str,
419410
fre_logger.info('Updated "nominal_resolution": %s', data["nominal_resolution"])
420411
except KeyError as e:
421412
fre_logger.error("Failed to update 'nominal_resolution': %s", e)
422-
raise KeyError("Error while updating 'nominal_resolution'. Ensure the field exists and is modifiable.") from e
413+
raise KeyError("Error updating 'nominal_resolution'. Ensure the field exists and is modifiable.") from e
423414

424415
output_file_path = output_file_path or json_file_path
425416

@@ -554,7 +545,7 @@ def conv_mip_to_bronx_freq(cmor_table_freq: str) -> Optional[str]:
554545
}
555546
bronx_freq = cmor_to_bronx_dict.get(cmor_table_freq)
556547
if bronx_freq is None:
557-
fre_logger.warning(f'MIP table frequency = {cmor_table_freq} does not have a FRE-bronx equivalent')
548+
fre_logger.warning('MIP table frequency = %s does not have a FRE-bronx equivalent', cmor_table_freq)
558549
if cmor_table_freq not in cmor_to_bronx_dict.keys():
559550
raise KeyError(f'MIP table frequency = "{cmor_table_freq}" is not a valid MIP frequency')
560551
return bronx_freq

fre/cmor/cmor_mixer.py

Lines changed: 19 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,7 @@
4242

4343
from .cmor_helpers import ( print_data_minmax, from_dis_gimme_dis, find_statics_file, create_lev_bnds,
4444
get_iso_datetime_ranges, check_dataset_for_ocean_grid, get_vertical_dimension,
45-
create_tmp_dir, get_json_file_data, update_grid_and_label, update_calendar_type,
46-
get_exp_cfg_mip_era )
45+
create_tmp_dir, get_json_file_data, update_grid_and_label, update_calendar_type )
4746

4847
fre_logger = logging.getLogger(__name__)
4948

@@ -151,7 +150,8 @@ def rewrite_netcdf_file_var( mip_var_cfgs: dict = None,
151150
fre_logger.error('should not happen')
152151
raise ValueError
153152
else:
154-
fre_logger.error('cmip7 case detected but no brands found in the CMOR mip table config had the right dimensions. nothing to do for this var!')
153+
fre_logger.error('cmip7 case detected, but dimensions of input data do not match '
154+
'any of those found for the associated brands.')
155155
raise ValueError
156156
else:
157157
fre_logger.debug('non-cmip7 case detected, skipping variable brands')
@@ -621,9 +621,9 @@ def rewrite_netcdf_file_var( mip_var_cfgs: dict = None,
621621
units = mip_var_cfgs["variable_entry"][target_var]["units"]
622622
fre_logger.info("units = %s", units)
623623

624-
#positive = mip_var_cfgs["variable_entry"][target_var]["positive"]
624+
#positive = mip_var_cfgs["variable_entry"][target_var]["positive"]
625625
if GLOBAL_MIP_ERA == 'CMIP7':
626-
positive = mip_var_cfgs["variable_entry"][f'{target_var}_{var_brand}']["positive"]
626+
positive = mip_var_cfgs["variable_entry"][f'{target_var}_{var_brand}']["positive"]
627627
else:
628628
positive = mip_var_cfgs["variable_entry"][target_var]["positive"]
629629
fre_logger.info("positive = %s", positive)
@@ -890,8 +890,6 @@ def cmorize_all_variables_in_dir(vars_to_run: Dict[str, Any],
890890
except Exception as exc: #uncovered
891891
return_status = 1
892892
fre_logger.warning('!!!EXCEPTION CAUGHT!!! !!!READ THE NEXT LINE!!!')
893-
# if str(exc) == "made it to break-point for current work, good job": # inl: annoying and i did this to myself
894-
# assert False, "made it to break-point for current work, good job"
895893
fre_logger.warning('exc=%s', exc)
896894
fre_logger.warning('this message came from within cmorize_target_var_files')
897895
fre_logger.warning('COULD NOT PROCESS: %s/%s...moving on', local_var, target_var)
@@ -976,17 +974,20 @@ def cmor_run_subtool(indir: str = None,
976974
fre_logger.debug('cmip7_case = %s', cmip7_case)
977975
cmip6_case = exp_cfg_mip_era.upper() == 'CMIP6'
978976
fre_logger.debug('cmip6_case = %s', cmip6_case)
979-
assert cmip7_case != cmip6_case # dont keep this assert, TEMP TODO
980977

981-
global GLOBAL_MIP_ERA
982-
GLOBAL_MIP_ERA = exp_cfg_mip_era # i don't care that i'm changing a "constant", it's more like a static class member
983-
if GLOBAL_MIP_ERA is None:
978+
if exp_cfg_mip_era is None:
984979
raise Exception('CMOR input experimental configuration must contain a field called "mip_era"')
985-
fre_logger.debug('GLOBAL_MIP_EREA=%s',GLOBAL_MIP_ERA)
986980

987-
if cmip7_case:
981+
if exp_cfg_mip_era.upper() not in ['CMIP6', 'CMIP7']:
982+
raise ValueError('cmor_mixer only supports CMIP6 and CMIP7 cases')
983+
984+
if exp_cfg_mip_era.upper() == 'CMIP7':
988985
fre_logger.warning('CMIP7 configuration detected, will be expecting and enforcing variable brands.')
989986

987+
global GLOBAL_MIP_ERA
988+
GLOBAL_MIP_ERA = exp_cfg_mip_era.upper() # maybe, change to yet another input arg for down-stream function calls ?
989+
fre_logger.debug('GLOBAL_MIP_EREA=%s',GLOBAL_MIP_ERA)
990+
990991
# CHECK optional grid/grid_label/nom_res inputs from exp config, the function raises the potential error conditions
991992
if any( [ grid_label is not None,
992993
grid is not None,
@@ -1003,24 +1004,21 @@ def cmor_run_subtool(indir: str = None,
10031004
# open CMOR table config file - need it here for checking the TABLE's variable list
10041005
json_table_config = str(Path(json_table_config).resolve())
10051006
fre_logger.info('loading json_table_config = \n%s', json_table_config)
1006-
10071007
mip_var_cfgs = get_json_file_data(json_table_config)
10081008
mip_fullvar_list = mip_var_cfgs["variable_entry"].keys()
10091009
fre_logger.debug('the following variables were read from the table: %s', mip_fullvar_list)
1010-
mip_var_list = None
1011-
mip_var_brand_list = None
1012-
if cmip7_case:
1013-
fre_logger.warning('cmip7 capabilities in-development now. extracting brands from variables within MIP cmor table configs')
1010+
mip_var_list, mip_var_brand_list = None, None
1011+
if GLOBAL_MIP_ERA == 'CMIP7':
1012+
fre_logger.warning('cmip7 capabilities in-development now. extracting brands from variables '
1013+
'within MIP cmor table configs')
10141014
mip_var_list = [ var.split('_')[0] for var in mip_fullvar_list ]
10151015
fre_logger.debug('the following unbranded variables were read from the table: %s', mip_var_list)
10161016
mip_var_brand_list = [ var.split('_')[1] for var in mip_fullvar_list ]
10171017
fre_logger.debug('the following brands were extracted from the variables: %s', mip_var_brand_list)
10181018
if len(mip_var_list) != len(mip_var_brand_list):
10191019
raise ValueError('the number of brands is not one-to-one with the number of variables. check config.')
1020-
elif cmip6_case:
1020+
elif GLOBAL_MIP_ERA == "CMIP6":
10211021
mip_var_list = mip_fullvar_list
1022-
#else:
1023-
# raise ValueError('uh oh')
10241022

10251023
fre_logger.debug('variables in mip_var_cfgs["variable_entry"] is = \n %s', mip_var_list)
10261024

fre/cmor/cmor_yamler.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ def cmor_yaml_subtool( yamlfile: str = None,
225225
f' calendar_type={calendar_type} '
226226
')\n' )
227227
continue
228-
cmor_run_subtool(
228+
cmor_run_subtool( #uncovered
229229
indir = indir ,
230230
json_var_list = json_var_list ,
231231
json_table_config = json_table_config ,

fre/cmor/tests/test_cmor_helpers_update_grid_label.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
1+
'''
2+
unit tests for cmor_helpers.update_grid_and_label
3+
'''
4+
15
import json
2-
import pytest
6+
37
from pathlib import Path
8+
import pytest
9+
410
from fre.cmor.cmor_helpers import update_grid_and_label
511

612
# Sample data for testing

fre/cmor/tests/test_cmor_run_subtool.py

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
''' tests for fre.cmor.cmor_run_subtool '''
1+
'''
2+
tests for fre.cmor.cmor_run_subtool
3+
'''
24
import subprocess
35
import shutil
46
from pathlib import Path
@@ -20,7 +22,9 @@
2022
f'{CMIP6_TABLE_REPO_PATH}/Tables/CMIP6_Omon.json'
2123

2224
def test_setup_cmor_cmip_table_repo():
23-
''' setup routine, make sure the recursively cloned tables exist '''
25+
'''
26+
setup routine, make sure the recursively cloned tables exist
27+
'''
2428
assert all( [ Path(CMIP6_TABLE_REPO_PATH).exists(),
2529
Path(TABLE_CONFIG).exists()
2630
] )
@@ -53,7 +57,8 @@ def test_setup_cmor_cmip_table_repo():
5357

5458

5559
def test_setup_fre_cmor_run_subtool(capfd):
56-
''' The routine generates a netCDF file from an ascii (cdl) file. It also checks for a ncgen
60+
'''
61+
The routine generates a netCDF file from an ascii (cdl) file. It also checks for a ncgen
5762
output file from prev pytest runs, removes it if it's present, and ensures the new file is
5863
created without error.
5964
'''
@@ -285,19 +290,18 @@ def test_git_cleanup():
285290
git's record of changed files. It's supposed to change as part of the test.
286291
'''
287292
is_ci = os.environ.get("GITHUB_WORKSPACE") is not None
288-
if is_ci:
289-
#doesn't run happily in CI and not needed
290-
assert True
291-
else:
292-
git_cmd = f"git restore {EXP_CONFIG}"
293-
restore = subprocess.run(git_cmd,
294-
shell=True,
295-
check=False)
296-
check_cmd = f"git status | grep {EXP_CONFIG}"
297-
check = subprocess.run(check_cmd,
298-
shell = True, check = False)
299-
#first command completed, second found no file in git status
300-
assert all([restore.returncode == 0, check.returncode == 1])
293+
if not is_ci:
294+
git_cmd = f"git restore {EXP_CONFIG}"
295+
restore = subprocess.run(git_cmd,
296+
shell=True,
297+
check=False)
298+
check_cmd = f"git status | grep {EXP_CONFIG}"
299+
check = subprocess.run(check_cmd,
300+
shell = True,
301+
check = False)
302+
#first command completed, second found no file in git status
303+
assert all([restore.returncode == 0,
304+
check.returncode == 1])
301305

302306
def test_cmor_run_subtool_raise_value_error():
303307
'''

fre/cmor/tests/test_cmor_run_subtool_further_examples.py

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
11
'''
2-
expanded set of tests for fre cmor run
3-
focus on
2+
expanded set of tests for fre cmor run focus on cases beyond test_cmor_run_subtool.py
43
'''
54

65
from datetime import date
76
from pathlib import Path
87
import shutil
9-
108
import glob
9+
#import time
10+
#import platform
11+
import subprocess
12+
import os
1113

1214
import pytest
1315

1416
from fre.cmor import cmor_run_subtool
1517

16-
import time
17-
18-
import platform
19-
20-
import subprocess
21-
import os
2218

2319
# global consts for these tests, with no/trivial impact on the results
2420
ROOTDIR='fre/tests/test_files'
@@ -187,15 +183,16 @@ def test_git_cleanup():
187183
git's record of changed files. It's supposed to change as part of the test.
188184
'''
189185
is_ci = os.environ.get("GITHUB_WORKSPACE") is not None
190-
if is_ci: #git status/restore doesn't run happily in CI and is not needed
191-
assert True
192-
else:
193-
git_cmd = f"git restore {EXP_CONFIG_DEFAULT}"
194-
restore = subprocess.run(git_cmd,
195-
shell=True,
196-
check=False)
197-
check_cmd = f"git status | grep {EXP_CONFIG_DEFAULT}"
198-
check = subprocess.run(check_cmd,
199-
shell = True, check = False)
200-
#first command completed, second found no file in git status
201-
assert all([restore.returncode == 0, check.returncode == 1])
186+
if not is_ci:
187+
git_cmd = f"git restore {EXP_CONFIG_DEFAULT}"
188+
restore = subprocess.run(git_cmd,
189+
shell=True,
190+
check=False)
191+
check_cmd = f"git status | grep {EXP_CONFIG_DEFAULT}"
192+
check = subprocess.run(check_cmd,
193+
shell = True,
194+
check = False)
195+
#first command completed, second found no file in git status
196+
assert all( [ restore.returncode == 0,
197+
check.returncode == 1 ] )
198+

0 commit comments

Comments
 (0)