def main(argv=None): """Load in arguments to calculate mean wind direction from ensemble realizations.""" cli_specific_arguments = [(['--backup_method'], {'dest': 'backup_method', 'default': 'neighbourhood', 'choices': ['neighbourhood', 'first_realization'], 'help': ('Backup method to use if ' 'there is low confidence in' ' the wind_direction. ' 'Options are first_realization' ' or neighbourhood, ' 'first_realization should only ' 'be used with global lat-lon data. ' 'Default is neighbourhood.')})] cli_definition = {'central_arguments': ('input_file', 'output_file'), 'specific_arguments': cli_specific_arguments, 'description': ('Run wind direction to calculate mean' ' wind direction from ' 'ensemble realizations')} args = ArgParser(**cli_definition).parse_args(args=argv) wind_direction = load_cube(args.input_filepath) # Returns 3 cubes - r_vals and confidence_measure cubes currently # only contain experimental data to be used for further research. bmethod = args.backup_method cube_mean_wdir, _, _ = ( WindDirection(backup_method=bmethod).process(wind_direction)) save_netcdf(cube_mean_wdir, args.output_filepath)
def main(argv=None): """Load in the arguments and ensure they are set correctly. Then run the time-lagged ensembles on the input cubes. """ parser = ArgParser( description='This combines the realizations from different forecast ' 'cycles into one cube. It does this by taking an input ' 'CubeList containing forecasts from different cycles and ' 'merges them into a single cube, removing any metadata ' 'that does not match.') parser.add_argument('input_filenames', metavar='INPUT_FILENAMES', nargs="+", type=str, help='Paths to input NetCDF files for the time-lagged ' 'ensemble to combine the realizations.') parser.add_argument('output_file', metavar='OUTPUT_FILE', help='The output file for the processed NetCDF.') args = parser.parse_args(args=argv) # Load the cubes cubes = iris.cube.CubeList([]) for filename in args.input_filenames: new_cube = load_cube(filename) cubes.append(new_cube) # Process Cube result = process(cubes) # Save Cube save_netcdf(result, args.output_file)
def main(argv=None): """Load in arguments for wind-gust diagnostic. Wind-gust and Wind-speed data should be supplied along with the required percentile value. The wind-gust diagnostic will be the Max of the specified percentile data. Currently: * Typical gusts is MAX(wind-gust(50th percentile),wind-speed(95th percentile)) * Extreme gust is MAX(wind-gust(95th percentile),wind-speed(100th percentile)) If no percentile values are supplied the code defaults to values for Typical gusts. """ parser = ArgParser( description="Calculate revised wind-gust data using a specified " "percentile of wind-gust data and a specified percentile " "of wind-speed data through the WindGustDiagnostic plugin. " "The wind-gust diagnostic will be the Max of the specified " "percentile data." "Currently Typical gusts is " "MAX(wind-gust(50th percentile),wind-speed(95th percentile))" "and Extreme gust is " "MAX(wind-gust(95th percentile),wind-speed(100th percentile)). " "If no percentile values are supplied the code defaults " "to values for Typical gusts.") parser.add_argument("input_filegust", metavar="INPUT_FILE_GUST", help="A path to an input Wind Gust Percentile" " NetCDF file") parser.add_argument("input_filews", metavar="INPUT_FILE_WINDSPEED", help="A path to an input Wind Speed Percentile" " NetCDF file") parser.add_argument("output_filepath", metavar="OUTPUT_FILE", help="The output path for the processed NetCDF") parser.add_argument("--percentile_gust", metavar="PERCENTILE_GUST", default="50.0", help="Percentile of wind-gust required." " Default=50.0", type=float) parser.add_argument("--percentile_ws", metavar="PERCENTILE_WIND_SPEED", default="95.0", help="Percentile of wind-speed required." " Default=95.0", type=float) args = parser.parse_args(args=argv) # Load Cube gust_cube = load_cube(args.input_filegust) speed_cube = load_cube(args.input_filews) # Process Cube result = process(gust_cube, speed_cube, args.percentile_gust, args.percentile_ws) # Save Cube save_netcdf(result, args.output_filepath)
def main(argv=None): """Load in arguments and get going.""" parser = ArgParser(description=('Read the input landmask, and correct ' 'to boolean values.')) parser.add_argument('--force', dest='force', default=False, action='store_true', help=('If True, ancillaries will be generated ' 'even if doing so will overwrite existing ' 'files.')) parser.add_argument('input_filepath_standard', metavar='INPUT_FILE_STANDARD', help='A path to an input NetCDF file to be processed') parser.add_argument('output_filepath', metavar='OUTPUT_FILE', help='The output path for the processed NetCDF') args = parser.parse_args(args=argv) # Check if improver ancillary already exists. if not os.path.exists(args.output_filepath) or args.force: landmask = load_cube(args.input_filepath_standard) land_binary_mask = CorrectLandSeaMask().process(landmask) save_netcdf(land_binary_mask, args.output_filepath) else: print('File already exists here: ', args.output_filepath)
def main(argv=None): """ Calculate the UV index using the data in the input cubes.""" parser = ArgParser( description="Calculates the UV index.") parser.add_argument("radiation_flux_upward", metavar="RADIATION_FLUX_UPWARD", help="Path to a NetCDF file of radiation flux " "in uv upward at surface.") parser.add_argument("radiation_flux_downward", metavar="RADIATION_FLUX_DOWNWARD", help="Path to a NetCDF file of radiation flux " "in uv downward at surface.") parser.add_argument("output_filepath", metavar="OUTPUT_FILE", help="The output path for the processed NetCDF") args = parser.parse_args(args=argv) # Load Cube rad_uv_up = load_cube(args.radiation_flux_upward) rad_uv_down = load_cube(args.radiation_flux_downward) # Process Cube result = process(rad_uv_up, rad_uv_down) # Save Cube save_netcdf(result, args.output_filepath)
def main(argv=None): """ Translate meta-data relating to the grid_id attribute from StaGE version 1.1.0 to StaGE version 1.2.0. """ cli_definition = { 'central_arguments': ['input_file', 'output_file'], 'specific_arguments': [], 'description': ('Translates meta-data relating to the ' 'grid_id attribute from StaGE version ' '1.1.0 to StaGE version 1.2.0. ' 'Files that have no "grid_id" attribute ' 'are not recognised as v1.1.0 and are ' 'not changed. Has no effect if ' 'input_file and output_file are the ' 'same and contain a cube with non ' 'v1.1.0 meta-data') } args = ArgParser(**cli_definition).parse_args(args=argv) cube = load_cube(args.input_filepath) cube_changed = update_stage_v110_metadata(cube) # Create normalised file paths to make them comparable in_file_norm = os.path.normpath(args.input_filepath) out_file_norm = os.path.normpath(args.output_filepath) if cube_changed or in_file_norm != out_file_norm: # Ensure data are not lazy in case we are writing back to the same # file. cube.data save_netcdf(cube, args.output_filepath)
def main(argv=None): """Load arguments""" parser = ArgParser(description='Calculates probabilities of occurrence ' 'between thresholds') parser.add_argument('input_file', metavar='INPUT_FILE', help='Path to NetCDF file containing probabilities ' 'above or below thresholds') parser.add_argument('output_file', metavar='OUTPUT_FILE', help='Path to NetCDF file to write probabilities of ' 'occurrence between thresholds') parser.add_argument('threshold_ranges', metavar='THRESHOLD_RANGES', help='Path to json file specifying threshold ranges') parser.add_argument('--threshold_units', metavar='THRESHOLD_UNITS', type=str, default=None, help='Units in which thresholds are specified') args = parser.parse_args(args=argv) # Load Cube and json cube = load_cube(args.input_file) with open(args.threshold_ranges) as input_file: # read list of thresholds from json file threshold_ranges = json.load(input_file) # Process Cube result = process(cube, threshold_ranges, threshold_units=args.threshold_units) # Save Cube save_netcdf(result, args.output_file)
def main(argv=None): """ Load in the arguments for feels like temperature and ensure they are set correctly. Then calculate the feels like temperature using the data in the input cubes.""" parser = ArgParser( description="This calculates the feels like temperature using a " "combination of the wind chill index and Steadman's " "apparent temperature equation.") parser.add_argument("temperature", metavar="TEMPERATURE", help="Path to a NetCDF file of air temperatures at " "screen level.") parser.add_argument("wind_speed", metavar="WIND_SPEED", help="Path to the NetCDF file of wind speed at 10m.") parser.add_argument("relative_humidity", metavar="RELATIVE_HUMIDITY", help="Path to the NetCDF file of relative humidity " "at screen level.") parser.add_argument("pressure", metavar="PRESSURE", help="Path to a NetCDF file of mean sea level " "pressure.") parser.add_argument("output_filepath", metavar="OUTPUT_FILE", help="The output path for the processed NetCDF") args = parser.parse_args(args=argv) # Load Cubes temperature = load_cube(args.temperature) wind_speed = load_cube(args.wind_speed) relative_humidity = load_cube(args.relative_humidity) pressure = load_cube(args.pressure) # Process Cube result = process(temperature, wind_speed, relative_humidity, pressure) # Save Cube save_netcdf(result, args.output_filepath)
def main(argv=None): """ Translate meta-data relating to the grid_id attribute from StaGE version 1.1.0 to StaGE version 1.2.0. """ cli_definition = { 'central_arguments': ['input_file', 'output_file'], 'specific_arguments': [], 'description': ('Translates meta-data relating to the ' 'grid_id attribute from StaGE version ' '1.1.0 to StaGE version 1.2.0. ' 'Files that have no "grid_id" attribute ' 'are not recognised as v1.1.0 and are ' 'not changed. Has no effect if ' 'input_file and output_file are the ' 'same and contain a cube with non ' 'v1.1.0 meta-data') } args = ArgParser(**cli_definition).parse_args(args=argv) # Load Cube cube = load_cube(args.input_filepath, no_lazy_load=True) # Process Cube cube_changed = process(cube) # Save Cube # Create normalised file paths to make them comparable in_file_norm = os.path.normpath(args.input_filepath) out_file_norm = os.path.normpath(args.output_filepath) if cube_changed or in_file_norm != out_file_norm: save_netcdf(cube, args.output_filepath)
def test_adding_multiple_arguments(self): """Test that we can successfully add multiple arguments to the ArgParser.""" # we will not actually pass anything in, so the Namespace will receive # the defaults (if any) - only check the keys of the Namespace derived # dictionary args_to_add = [(['--foo'], {}), (['--bar', '--b'], {})] expected_namespace_keys = ['foo', 'bar'] # + compulsory... # explicitly pass nothing in - will only have compulsory arguments # and the ones we added... parser = ArgParser(central_arguments=None, specific_arguments=None) parser.add_arguments(args_to_add) result_args = parser.parse_args() result_args = vars(result_args).keys() # we could also add compulsory arguments to expected_namespace_keys # and then assertItemsEqual - (order unimportant), but this # is unnecessary - just use loop: # (or we could patch compulsory arguments to be an empty dictionary) for expected_arg in expected_namespace_keys: self.assertIn(expected_arg, result_args)
def main(argv=None): """Generate target grid with a halo around the source file grid.""" parser = ArgParser(description='Generate grid with halo from a source ' 'domain input file. The grid is populated with zeroes.') parser.add_argument('input_file', metavar='INPUT_FILE', help="NetCDF file " "containing data on a source grid.") parser.add_argument('output_file', metavar='OUTPUT_FILE', help="NetCDF " "file defining the target grid with additional halo.") parser.add_argument('--halo_radius', metavar='HALO_RADIUS', default=162000, type=float, help="Size of halo (in m) with which to " "pad the input grid. Default is 162 000 m.") args = parser.parse_args(args=argv) # Load Cube cube = load_cube(args.input_file) # Process Cube result = process(cube, args.halo_radius) # Save Cube save_netcdf(result, args.output_file)
def main(argv=None): r""" Load arguments and run ProbabilitiesFromPercentiles plugin. Plugin generates probabilities at a fixed threshold (height) from a set of (height) percentiles. Example: Snow-fall level:: Reference field: Percentiled snow fall level (m ASL) Other field: Orography (m ASL) 300m ----------------- 30th Percentile snow fall level 200m ----_------------ 20th Percentile snow fall level 100m ---/-\----------- 10th Percentile snow fall level 000m --/---\---------- 0th Percentile snow fall level ______/ \_________ Orogaphy The orography heights are compared against the heights that correspond with percentile values to find the band in which they fall, then interpolated linearly to obtain a probability of snow level at / below the ground surface. """ parser = ArgParser( description="Calculate probability from a percentiled field at a " "2D threshold level. Eg for 2D percentile levels at different " "heights, calculate probability that height is at ground level, where" " the threshold file contains a 2D topography field.") parser.add_argument("percentiles_filepath", metavar="PERCENTILES_FILE", help="A path to an input NetCDF file containing a " "percentiled field") parser.add_argument("threshold_filepath", metavar="THRESHOLD_FILE", help="A path to an input NetCDF file containing a " "threshold value at which probabilities should be " "calculated.") parser.add_argument("output_filepath", metavar="OUTPUT_FILE", help="The output path for the processed NetCDF") parser.add_argument("output_diagnostic_name", metavar="OUTPUT_DIAGNOSTIC_NAME", type=str, help="Name for data in output file e.g. " "probability_of_snow_falling_level_below_ground_level") args = parser.parse_args(args=argv) # Load Cubes threshold_cube = load_cube(args.threshold_filepath) percentiles_cube = load_cube(args.percentiles_filepath) # Process Cubes probability_cube = process(percentiles_cube, threshold_cube, args.output_diagnostic_name) # Save Cubes save_netcdf(probability_cube, args.output_filepath)
def main(argv=None): """Load in arguments and get going.""" parser = ArgParser( description="Calculate the continuous falling snow level ") parser.add_argument("temperature", metavar="TEMPERATURE", help="Path to a NetCDF file of air temperatures at" " heights (m) at the points for which the continuous " "falling snow level is being calculated.") parser.add_argument("relative_humidity", metavar="RELATIVE_HUMIDITY", help="Path to a NetCDF file of relative_humidities at" " heights (m) at the points for which the continuous " "falling snow level is being calculated.") parser.add_argument("pressure", metavar="PRESSURE", help="Path to a NetCDF file of air pressures at" " heights (m) at the points for which the continuous " "falling snow level is being calculated.") parser.add_argument("orography", metavar="OROGRAPHY", help="Path to a NetCDF file containing " "the orography height in m of the terrain " "over which the continuous falling snow level is " "being calculated.") parser.add_argument("land_sea_mask", metavar="LAND_SEA_MASK", help="Path to a NetCDF file containing " "the binary land-sea mask for the points " "for which the continuous falling snow level is " "being calculated. Land points are set to 1, sea " "points are set to 0.") parser.add_argument("output_filepath", metavar="OUTPUT_FILE", help="The output path for the processed NetCDF") parser.add_argument("--precision", metavar="NEWTON_PRECISION", default=0.005, type=float, help="Precision to which the wet bulb temperature " "is required: This is used by the Newton iteration " "default value is 0.005") parser.add_argument("--falling_level_threshold", metavar="FALLING_LEVEL_THRESHOLD", default=90.0, type=float, help=("Cutoff threshold for the wet-bulb integral used" " to calculate the falling snow level. This " "threshold indicates the level at which falling " "snow is deemed to have melted to become rain. " "The default value is 90.0, an empirically " "derived value.")) args = parser.parse_args(args=argv) # Load Cubes temperature = load_cube(args.temperature, no_lazy_load=True) relative_humidity = load_cube(args.relative_humidity, no_lazy_load=True) pressure = load_cube(args.pressure, no_lazy_load=True) orog = load_cube(args.orography, no_lazy_load=True) land_sea = load_cube(args.land_sea_mask, no_lazy_load=True) # Process Cube result = process(temperature, relative_humidity, pressure, orog, land_sea, args.precision, args.falling_level_threshold) # Save Cube save_netcdf(result, args.output_filepath)
def test_adding_empty_argument_list_does_nothing(self): """Test that attempting to add an empty list of argspecs to the ArgParser does not add any new arguments.""" args_to_add = [] # add a specific (optional) argument - ensures that even if there are # no compulsory arguments, we have something... # adding arguments after calling parse_args/args will do nothing, so # instead create 2 instances: parser1 = ArgParser(central_arguments=None, specific_arguments=[[['--optional'], {}]]) parser2 = ArgParser(central_arguments=None, specific_arguments=[[['--optional'], {}]]) parser2.add_arguments(args_to_add) self.assertEqual(parser1.parse_args(), parser2.parse_args())
def test_argparser_compulsory_args_has_profile(self): """Test that creating an ArgParser instance with the compulsory arguments adds the profiling options.""" expected_profile_options = ['profile', 'profile_file'] parser = ArgParser(central_arguments=None, specific_arguments=None) args = parser.parse_args() args = vars(args).keys() self.assertCountEqual(args, expected_profile_options)
def main(argv=None): """Parser to accept input data and an output destination before invoking the weather symbols plugin. """ diagnostics = interrogate_decision_tree('high_resolution') n_files = len(diagnostics) dlist = (' - {}\n' * n_files) diagnostics_global = interrogate_decision_tree('global') n_files_global = len(diagnostics_global) dlist_global = (' - {}\n' * n_files_global) parser = ArgParser( description='Calculate gridded weather symbol codes.\nThis plugin ' 'requires a specific set of input diagnostics, where data\nmay be in ' 'any units to which the thresholds given below can\nbe converted:\n' + dlist.format(*diagnostics) + '\n\n or for global data\n\n' + dlist_global.format(*diagnostics_global), formatter_class=RawTextHelpFormatter) parser.add_argument( 'input_filepaths', metavar='INPUT_FILES', nargs="+", help='Paths to files containing the required input diagnostics.') parser.add_argument('output_filepath', metavar='OUTPUT_FILE', help='The output path for the processed NetCDF.') parser.add_argument("--wxtree", metavar="WXTREE", default="high_resolution", choices=["high_resolution", "global"], help="Weather Code tree.\n" "Choices are high_resolution or global.\n" "Default=high_resolution.", type=str) args = parser.parse_args(args=argv) # Load Cube cubes = load_cubelist(args.input_filepaths, no_lazy_load=True) required_number_of_inputs = n_files if args.wxtree == 'global': required_number_of_inputs = n_files_global if len(cubes) != required_number_of_inputs: msg = ('Incorrect number of inputs: files {} gave {} cubes' + ', {} required').format(args.input_filepaths, len(cubes), required_number_of_inputs) raise argparse.ArgumentTypeError(msg) # Process Cube result = process(cubes, args.wxtree) # Save Cube save_netcdf(result, args.output_filepath)
def test_error_raised(self, args='foo', method='bar'): """Test that an exception is raised containing the args and method.""" msg = ("Method: {} does not accept arguments: {}".format(method, args)) # argparser will write to stderr independently of SystemExit with open(os.devnull, 'w') as file_handle: with patch('sys.stderr', file_handle): with self.assertRaises(SystemExit, msg=msg): ArgParser().wrong_args_error(args, method)
def test_adding_single_argument_with_unexpected_length_argspec(self): """Test that attempting to add an argument to the ArgParser when the wrong format argspec raises an exception.""" # length of argspec is 3 - this is unexpected args_to_add = [(['--foo'], 'bar', {})] parser = ArgParser(central_arguments=None, specific_arguments=None) with self.assertRaises(AttributeError): parser.add_arguments(args_to_add)
def main(argv=None): """Invoke data extraction.""" parser = ArgParser(description='Extracts subset of data from a single ' 'input file, subject to equality-based constraints.') parser.add_argument('input_file', metavar='INPUT_FILE', help="File containing a dataset to extract from.") parser.add_argument('output_file', metavar='OUTPUT_FILE', help="File to write the extracted dataset to.") parser.add_argument('constraints', metavar='CONSTRAINTS', nargs='+', help='The constraint(s) to be applied. These must be' ' of the form "key=value", eg "threshold=1". Scalars' ', boolean and string values are supported. Comma-' 'separated lists (eg "key=[value1,value2]") are ' 'supported. These comma-separated lists can either ' 'extract all values specified in the list or ' 'all values specified within a range e.g. ' 'key=[value1:value2]. When a range is specified, ' 'this is inclusive of the endpoints of the range.') parser.add_argument('--units', metavar='UNITS', nargs='+', default=None, help='Optional: units of coordinate constraint(s) to ' 'be applied, for use when the input coordinate ' 'units are not ideal (eg for float equality). If ' 'used, this list must match the CONSTRAINTS list in ' 'order and length (with null values set to None).') parser.add_argument('--ignore-failure', action='store_true', default=False, help='Option to ignore constraint match failure and ' 'return the input cube.') args = parser.parse_args(args=argv) # Load Cube cube = load_cube(args.input_file) # Process Cube output_cube = process(cube, args.constraints, args.units) # Save Cube if output_cube is None and args.ignore_failure: save_netcdf(cube, args.output_file) elif output_cube is None: msg = "Constraint(s) could not be matched in input cube" raise ValueError(msg) else: save_netcdf(output_cube, args.output_file)
def test_adding_argument_with_defined_kwargs_dict_has_defualt(self): """Test that we can successfully add an argument to the ArgParser, when the argspec contained kwargs, and that the default value is captured.""" args_to_add = [(['--one'], {'default': 1})] parser = ArgParser(central_arguments=None, specific_arguments=None) parser.add_arguments(args_to_add) result_args = parser.parse_args() # `--one` was not passed in, so we pick up the default - let's check # they agree... self.assertEqual(1, result_args.one)
def test_adding_argument_with_defined_kwargs_dict(self): """Test that we can successfully add an argument to the ArgParser, when the argspec contained kwargs.""" # length of argspec is 2... args_to_add = [(['--foo'], {'default': 1})] expected_arg = 'foo' parser = ArgParser(central_arguments=None, specific_arguments=None) parser.add_arguments(args_to_add) result_args = parser.parse_args() result_args = vars(result_args).keys() self.assertIn(expected_arg, result_args)
def test_create_argparser_fails_with_unknown_centralized_argument(self): """Test that we raise an exception when attempting to retrieve centralized arguments which are not centralized argument dictionary.""" centralized_arguments = {'foo': (['--foo'], {})} central_args_to_fetch = ('missing_central_arg', ) # patch the CENTRALIZED_ARGUMENTS so we know that `missing_central_arg` # is not there, and we can raise an exception with patch('improver.argparser.ArgParser.CENTRALIZED_ARGUMENTS', centralized_arguments): with self.assertRaises(KeyError): ArgParser(central_arguments=central_args_to_fetch, specific_arguments=None)
def test_create_argparser_with_no_arguments(self): """Test that creating an ArgParser with no arguments has no arguments.""" compulsory_arguments = {} # it doesn't matter what the centralized arguments are, because we # select None of them - we only need to patch the COMPULSORY_ARGUMENTS # to ensure there are none of them with patch('improver.argparser.ArgParser.COMPULSORY_ARGUMENTS', compulsory_arguments): parser = ArgParser(central_arguments=None, specific_arguments=None) args = parser.parse_args() args = vars(args).keys() self.assertEqual(len(args), 0)
def test_create_argparser_only_compulsory_arguments(self): """Test that creating an ArgParser with only compulsory arguments adds only the compulsory arguments.""" compulsory_arguments = {'foo': (['--foo'], {})} # it doesn't matter what the centralized arguments are, because we # select None of them - only patch COMPULSORY_ARGUMENTS so we know # what to expect with patch('improver.argparser.ArgParser.COMPULSORY_ARGUMENTS', compulsory_arguments): parser = ArgParser(central_arguments=None, specific_arguments=None) args = parser.parse_args() args = vars(args).keys() self.assertCountEqual(args, ['foo'])
def test_create_argparser_only_specific_arguments(self): """Test that creating an ArgParser with only specific arguments adds only the specific arguments.""" compulsory_arguments = {} specific_arguments = [(['--foo'], {})] # it doesn't matter what the centralized arguments are, because we # select None of them - patch the COMPULSORY_ARGUMENTS to be an empty # dict so that we don't add any of them with patch('improver.argparser.ArgParser.COMPULSORY_ARGUMENTS', compulsory_arguments): parser = ArgParser(central_arguments=None, specific_arguments=specific_arguments) args = parser.parse_args() args = vars(args).keys() self.assertCountEqual(args, ['foo'])
def test_create_argparser_compulsory_and_specfic_arguments(self): """Test that creating an ArgParser with compulsory and specific arguments adds both of these and no others.""" compulsory_arguments = {'foo': (['--foo'], {})} specific_arguments = [(['--bar'], {})] # it doesn't matter what the centralized arguments are, because we # select None of them - patch only the COMPULSORY_ARGUMENTS so we know # that `foo` is added from here with patch('improver.argparser.ArgParser.COMPULSORY_ARGUMENTS', compulsory_arguments): parser = ArgParser(central_arguments=None, specific_arguments=specific_arguments) args = parser.parse_args() args = vars(args).keys() self.assertCountEqual(args, ['foo', 'bar'])
def main(argv=None): """Parser to accept input data and an output destination before invoking the wet bulb temperature plugin. Also accepted is an optional convergence_condition argument that can be used to specify the tolerance of the Newton iterator used to calculate the wet bulb temperatures.""" parser = ArgParser( description='Calculate a field of wet bulb temperatures.') parser.add_argument('temperature', metavar='TEMPERATURE', help='Path to a NetCDF file of air temperatures at ' 'the points for which the wet bulb temperatures are ' 'being calculated.') parser.add_argument('relative_humidity', metavar='RELATIVE_HUMIDITY', help='Path to a NetCDF file of relative humidities at ' 'the points for for which the wet bulb temperatures ' 'are being calculated.') parser.add_argument('pressure', metavar='PRESSURE', help='Path to a NetCDF file of air pressures at the ' 'points for which the wet bulb temperatures are being' ' calculated.') parser.add_argument('output_filepath', metavar='OUTPUT_FILE', help='The output path for the processed NetCDF.') parser.add_argument('--convergence_condition', metavar='CONVERGENCE_CONDITION', type=float, default=0.05, help='The convergence condition for the Newton ' 'iterator in K. When the wet bulb temperature ' 'stops changing by more than this amount between' ' iterations, the solution is accepted.') args = parser.parse_args(args=argv) # Load Cubes temperature = load_cube(args.temperature) relative_humidity = load_cube(args.relative_humidity) pressure = load_cube(args.pressure) # Process Cube result = process(temperature, relative_humidity, pressure, args.convergence_condition) # Save Cube save_netcdf(result, args.output_filepath)
def test_create_argparser_compulsory_and_centralized_arguments(self): """Test that creating an ArgParser with compulsory and centralized arguments adds both of these and no others.""" compulsory_arguments = {'foo': (['--foo'], {})} centralized_arguments = {'bar': (['--bar'], {})} # patch the COMPULSORY_ARGUMENTS so we know that `foo` exists # and the CENTRALIZED_ARGUMENTS so we know that `bar` exists. with patch('improver.argparser.ArgParser.COMPULSORY_ARGUMENTS', compulsory_arguments): with patch('improver.argparser.ArgParser.CENTRALIZED_ARGUMENTS', centralized_arguments): parser = ArgParser(central_arguments=['bar'], specific_arguments=None) args = parser.parse_args() args = vars(args).keys() self.assertCountEqual(args, ['foo', 'bar'])
def test_create_argparser_only_centralized_arguments(self): """Test that creating an ArgParser with only centralized arguments adds only the selected centralized arguments.""" compulsory_arguments = {} centralized_arguments = {'foo': (['--foo'], {})} # patch the COMPULSORY_ARGUMENTS to an empty dict (so there are none) # and patch CENTRALIZED_ARGUMENTS so we know that `foo` can be selected # from it with patch('improver.argparser.ArgParser.COMPULSORY_ARGUMENTS', compulsory_arguments): with patch('improver.argparser.ArgParser.CENTRALIZED_ARGUMENTS', centralized_arguments): parser = ArgParser(central_arguments=['foo'], specific_arguments=None) args = parser.parse_args() args = vars(args).keys() self.assertCountEqual(args, ['foo'])
def test_create_argparser_all_arguments(self): """Test that creating an ArgParser with compulsory, centralized and specific arguments adds the arguments from all 3 collections.""" compulsory_arguments = {'foo': (['--foo'], {})} centralized_arguments = {'bar': (['--bar'], {})} specific_arguments = [(['--baz'], {})] # patch both the COMPULSORY_ARGUMENTS and CENTRALIZED_ARGUMENTS, so # that `foo` and `bar` are added from these (respectively) with patch('improver.argparser.ArgParser.COMPULSORY_ARGUMENTS', compulsory_arguments): with patch('improver.argparser.ArgParser.CENTRALIZED_ARGUMENTS', centralized_arguments): parser = ArgParser(central_arguments=['bar'], specific_arguments=specific_arguments) args = parser.parse_args() args = vars(args).keys() self.assertCountEqual(args, ['foo', 'bar', 'baz'])