Commit 337ebcf1 authored by Daniel Scheffler's avatar Daniel Scheffler
Browse files

Revised previous solution for correctly parsing boolean values with argparse. Updated version info.



Signed-off-by: Daniel Scheffler's avatarDaniel Scheffler <danschef@gfz-potsdam.de>
parent bf3fbf06
Pipeline #5564 passed with stage
in 11 minutes and 45 seconds
......@@ -69,7 +69,7 @@ def get_enpt_argparser():
help='input path of digital elevation model in map or sensor geometry; GDAL compatible file format '
'(must cover the EnMAP L1B data completely if given in map geometry or must have the same pixel '
'dimensions like the EnMAP L1B data if given in sensor geometry)')
add('-dummyfmt', '--is_dummy_dataformat', type=_false_or_true, default=False,
add('-dummyfmt', '--is_dummy_dataformat', type=_str2bool, default=False, nargs='?', const=True,
help='Set to true in case of the preliminary, GFZ-internal dataformat as used for the Alpine test dataset. '
'(default: False. Note: This will be removed in future.)')
add('-ele', '--average_elevation', type=int, default=0,
......@@ -81,7 +81,7 @@ def get_enpt_argparser():
help='directory to be used for temporary files')
add('-nla', '--n_lines_to_append', type=int, default=None,
help='number of lines to be added to the main image [if None, use the whole imgap]. Requires --imgap to be set')
add('-dpb', '--disable_progress_bars', type=_false_or_true, default=False,
add('-dpb', '--disable_progress_bars', type=_str2bool, default=False, nargs='?', const=True,
help='whether to disable all progress bars during processing')
add('--path_earthSunDist', type=str, default=None,
help='input path of the earth sun distance model')
......@@ -89,26 +89,26 @@ def get_enpt_argparser():
help='input path of the solar irradiance model')
add('--scale_factor_toa_ref', type=int, default=None,
help='scale factor to be applied to TOA reflectance result')
add('--enable_keystone_correction', type=_false_or_true, default=False,
add('--enable_keystone_correction', type=_str2bool, default=False, nargs='?', const=True,
help='Enable keystone correction')
add('--enable_vnir_swir_coreg', type=_false_or_true, default=False,
add('--enable_vnir_swir_coreg', type=_str2bool, default=False, nargs='?', const=True,
help='Enable VNIR/SWIR co-registration')
add('--path_reference_image', type=str, default=None,
help='Reference image for co-registration.')
add('--enable_ac', type=_false_or_true, default=True,
add('--enable_ac', type=_str2bool, default=True, nargs='?', const=True,
help="Enable atmospheric correction using SICOR algorithm (default: True). If False, the L2A output contains "
"top-of-atmosphere reflectance")
add('--auto_download_ecmwf', type=_false_or_true, default=False,
add('--auto_download_ecmwf', type=_str2bool, default=False, nargs='?', const=True,
help='Automatically download ECMWF data for atmospheric correction')
add('--enable_ice_retrieval', type=_false_or_true, default=True,
add('--enable_ice_retrieval', type=_str2bool, default=True, nargs='?', const=True,
help='Enable ice retrieval (default); increases accuracy of water vapour retrieval')
add('--enable_cloud_screening', type=_false_or_true, default=False,
add('--enable_cloud_screening', type=_str2bool, default=False, nargs='?', const=True,
help='Enable cloud screening during atmospheric correction')
add('--scale_factor_boa_ref', type=int, default=10000,
help='Scale factor to be applied to BOA reflectance result')
add('--run_smile_P', type=_false_or_true, default=False,
add('--run_smile_P', type=_str2bool, default=False, nargs='?', const=True,
help='Enable extra smile detection and correction (provider smile coefficients are ignored)')
add('--run_deadpix_P', type=_false_or_true, default=True,
add('--run_deadpix_P', type=_str2bool, default=True, nargs='?', const=True,
help='Enable dead pixel correction')
add('--deadpix_P_algorithm', type=str, default="spectral",
help="Algorithm for dead pixel correction ('spectral' or 'spatial')")
......@@ -165,13 +165,26 @@ def run_job(config: EnPTConfig):
CTR.run_all_processors()
def _false_or_true(val):
return val.lower() in ("yes", "true", "t", "1")
def _str2bool(v):
"""Convert string parameter to bool.
From: https://stackoverflow.com/a/43357954/2952871
:param v:
:return:
"""
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
if __name__ == '__main__':
parsed_args = get_enpt_argparser().parse_args()
print(parsed_args)
# parsed_args.func(get_config(parsed_args))
parsed_args.func(get_config(parsed_args))
print('\nready.')
......@@ -24,6 +24,6 @@
# You should have received a copy of the GNU Lesser General Public License along
# with this program. If not, see <http://www.gnu.org/licenses/>.
__version__ = '0.9.12'
__versionalias__ = '20200113.04'
__version__ = '0.9.13'
__versionalias__ = '20200113.05'
__author__ = 'Daniel Scheffler'
......@@ -33,6 +33,7 @@ Tests for enpt.bin.enpt_cli.py
"""
from unittest import TestCase
from argparse import ArgumentError
import os
from runpy import run_path
from multiprocessing import cpu_count
......@@ -66,12 +67,31 @@ class Test_CLIParser(TestCase):
self.assertEqual(config.CPUs, cpu_count())
def test_param_boolean(self):
parsed_args = self.parser_run.parse_args(self.baseargs +
['--enable_ac', 'True'])
config = self.get_config(parsed_args)
self.assertIsInstance(config.enable_ac, bool)
self.assertEqual(config.enable_ac, True)
parsed_args = self.parser_run.parse_args(self.baseargs +
['--enable_ac', 'false'])
config = self.get_config(parsed_args)
self.assertIsInstance(config.enable_ac, bool)
self.assertEqual(config.enable_ac, False)
parsed_args = self.parser_run.parse_args(self.baseargs +
['--enable_ac', '0'])
config = self.get_config(parsed_args)
self.assertIsInstance(config.enable_ac, bool)
self.assertEqual(config.enable_ac, False)
try:
self.parser_run.parse_args(self.baseargs + ['--enable_ac', 'treu'])
except SystemExit as e:
assert isinstance(e.__context__, ArgumentError)
else:
raise ValueError("Exception not raised")
def test_json_opts(self):
parsed_args = self.parser_run.parse_args(
self.baseargs + ['--json_config', '{"general_opts": {"CPUs": 10}}'])
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment