コード例 #1
0
def parse_command_line():
###############################################################################

    """Parse the command line, return object holding arguments"""

    description = """
Script to create runtime inputs when running CTSM via LILAC
"""

    parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter,
                                     description=description)

    parser.add_argument("--rundir", type=str, default=os.getcwd(),
                        help="Full path of the run directory (containing ctsm.cfg & user_nl_ctsm)")

    add_logging_args(parser)

    arguments = parser.parse_args()

    # Perform some error checking on arguments

    if not os.path.isdir(arguments.rundir):
        abort("rundir {} does not exist".format(arguments.rundir))

    return arguments
コード例 #2
0
def _commandline_args():
    """Parse and return command-line arguments
    """

    description = """
Script to download any missing input data for CTSM and LILAC
"""

    parser = argparse.ArgumentParser(
        description=description, formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument(
        "--rundir",
        default=os.getcwd(),
        help="Full path of the run directory\n"
        "(This directory should contain clm.input_data_list and lilac_in,\n"
        "among other files.)\n"
        "(Note: it is assumed that this directory exists alongside the other\n"
        "directories created by build_ctsm: 'case' and 'inputdata'.)")

    add_logging_args(parser)

    args = parser.parse_args()

    return args
コード例 #3
0
ファイル: fsurdat_modifier.py プロジェクト: andrewsoong/ctsm
def main ():
    """
    Description
    -----------
    Calls function that modifies an fsurdat (surface dataset)
    """

    # set up logging allowing user control
    setup_logging_pre_config()

    # read the command line argument to obtain the path to the .cfg file
    parser = argparse.ArgumentParser()
    parser.add_argument('cfg_path',
                        help='/path/name.cfg of input file, eg ./modify.cfg')
    add_logging_args(parser)
    args = parser.parse_args()
    process_logging_args(args)
    fsurdat_modifier(args.cfg_path)
コード例 #4
0
def main():
    """
    Main function for gen_mksurf_namelist.
    """
    # -- add logging flags from ctsm_logging
    setup_logging_pre_config()
    parser = get_parser()
    add_logging_args(parser)

    args = parser.parse_args()
    process_logging_args(args)

    res = args.res
    glc_nec = args.glc_nec
    input_path = args.input_path
    ssp_rcp = args.ssp_rcp
    crop_flag = args.crop_flag
    vic_flag = args.vic_flag
    glc_flag = args.glc_flag
    hres_flag = args.hres_flag

    start_year = args.start_year
    end_year = args.end_year

    # -- determine end_year if not given as an argument:
    if not end_year:
        end_year = start_year

    # -- check if the input path exist
    if not os.path.exists(input_path):
        sys.exit("ERROR: \n" +
                 "\t raw_dir does not exist on this machine. \n" +
                 "\t Please point to the correct raw_dir using --raw-dir" +
                 "or --rawdata-dir flags.")

    ctsm_case = CtsmCase(res, glc_nec, ssp_rcp, crop_flag, input_path,
                         vic_flag, glc_flag, start_year, end_year, hres_flag)

    logger.info("--------------------------")
    logger.info(" ctsm case : %s", ctsm_case)
    logger.info("--------------------------")

    ctsm_case.create_namelist_file()
コード例 #5
0
def _commandline_args():
    """Parse and return command-line arguments
    """

    description = """
Driver for running CTSM system tests

Typical usage:

./run_sys_tests -s aux_clm -c COMPARE_NAME -g GENERATE_NAME

    This automatically detects the machine and launches the appropriate components of the
    aux_clm test suite on that machine. This script also implements other aspects of the
    typical CTSM system testing workflow, such as running create_test via qsub on
    cheyenne, and setting up a directory to hold all of the tests in the test suite. A
    symbolic link will be created in the current directory pointing to the testroot
    directory containing all of the test directories in the test suite.

    Note that the -c/--compare and -g/--generate arguments are required, unless you specify
    --skip-compare and/or --skip-generate.

    Any other test suite can be given as well: clm_short, aux_glc, etc.

This can also be used to run tests listed in a text file (via the -f/--testfile argument),
or tests listed individually on the command line (via the -t/--testname argument).
"""

    parser = argparse.ArgumentParser(
        description=description, formatter_class=argparse.RawTextHelpFormatter)

    machine_name = get_machine_name()

    default_machine = create_machine(machine_name,
                                     defaults=MACHINE_DEFAULTS,
                                     allow_missing_entries=True)

    tests_to_run = parser.add_mutually_exclusive_group(required=True)

    tests_to_run.add_argument('-s',
                              '--suite-name',
                              help='Name of test suite to run')

    tests_to_run.add_argument('-f',
                              '--testfile',
                              help='Path to file listing tests to run')

    tests_to_run.add_argument(
        '-t',
        '--testname',
        '--testnames',
        nargs='+',
        help='One or more test names to run (space-delimited)')

    compare = parser.add_mutually_exclusive_group(required=True)

    compare.add_argument('-c',
                         '--compare',
                         metavar='COMPARE_NAME',
                         help='Baseline name (often tag) to compare against\n'
                         '(required unless --skip-compare is given)')

    compare.add_argument('--skip-compare',
                         action='store_true',
                         help='Do not compare against baselines')

    generate = parser.add_mutually_exclusive_group(required=True)

    generate.add_argument('-g',
                          '--generate',
                          metavar='GENERATE_NAME',
                          help='Baseline name (often tag) to generate\n'
                          '(required unless --skip-generate is given)')

    generate.add_argument('--skip-generate',
                          action='store_true',
                          help='Do not generate baselines')

    parser.add_argument(
        '--suite-compiler',
        '--suite-compilers',
        nargs='+',
        help='Compiler(s) from the given test suite for which tests are run\n'
        'Only valid in conjunction with -s/--suite-name;\n'
        'if not specified, use all compilers defined for this suite and machine\n'
    )

    parser.add_argument(
        '--account',
        help='Account number to use for job submission.\n'
        'This is needed on some machines; if not provided explicitly,\n'
        'the script will attempt to guess it using the same rules as in CIME.\n'
        'Default for this machine: {}'.format(default_machine.account))

    parser.add_argument(
        '--testid-base',
        help='Base string used for the test id.\n'
        'Default is to auto-generate this with a date and time stamp.')

    parser.add_argument('--testroot-base',
                        help='Path in which testroot should be put.\n'
                        'For supported machines, this can be left out;\n'
                        'for non-supported machines, it must be provided.\n'
                        'Default for this machine: {}'.format(
                            default_machine.scratch_dir))

    parser.add_argument(
        '--baseline-root',
        help='Path in which baselines should be compared and generated.\n'
        'Default is to use the default for this machine.')

    parser.add_argument(
        '--walltime',
        help='Walltime for each test.\n'
        'If running a test suite, you can generally leave this unset,\n'
        'because it is set in the file defining the test suite.\n'
        'For other uses, providing this helps decrease the time spent\n'
        'waiting in the queue.')

    parser.add_argument('--queue',
                        help='Queue to which tests are submitted.\n'
                        'If not provided, uses machine default.')

    parser.add_argument(
        '--extra-create-test-args',
        default='',
        help='String giving extra arguments to pass to create_test\n'
        '(To allow the argument parsing to accept this, enclose the string\n'
        'in quotes, with a leading space, as in " --my-arg foo".)')

    parser.add_argument(
        '--job-launcher-queue',
        help='Queue to which the create_test command is submitted.\n'
        'Only applies on machines for which we submit the create_test command\n'
        'rather than running it on the login node.\n'
        'Default for this machine: {}'.format(
            default_machine.job_launcher.get_queue()))

    parser.add_argument(
        '--job-launcher-walltime',
        help='Walltime for the create_test command.\n'
        'Only applies on machines for which we submit the create_test command\n'
        'rather than running it on the login node.\n'
        'Default for this machine: {}'.format(
            default_machine.job_launcher.get_walltime()))

    parser.add_argument(
        '--job-launcher-extra-args',
        help='Extra arguments for the command that launches the\n'
        'create_test command.\n'
        '(To allow the argument parsing to accept this, enclose the string\n'
        'in quotes, with a leading space, as in " --my-arg foo".)\n'
        'Default for this machine: {}'.format(
            default_machine.job_launcher.get_extra_args()))

    parser.add_argument(
        '--skip-testroot-creation',
        action='store_true',
        help='Do not create the directory that will hold the tests.\n'
        'This should be used if the desired testroot directory already exists.'
    )

    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='Print what would happen, but do not run any commands.\n'
        '(Generally should be run with --verbose.)\n')

    parser.add_argument('--machine-name',
                        default=machine_name,
                        help='Name of machine for which create_test is run.\n'
                        'This typically is not needed, but can be provided\n'
                        'for the sake of testing this script.\n'
                        'Defaults to current machine: {}'.format(machine_name))

    add_logging_args(parser)

    args = parser.parse_args()

    _check_arg_validity(args)

    return args
コード例 #6
0
def _commandline_args(args_to_parse=None):
    """Parse and return command-line arguments

    Args:
    args_to_parse: list of strings or None: Generally only used for unit testing; if None,
        reads args from sys.argv
    """
    # pylint: disable=line-too-long
    # pylint: disable=too-many-statements

    description = """
Script to build CTSM library and its dependencies

Typical usage:

    For a fresh build with a machine that has been ported to cime
    (http://esmci.github.io/cime/versions/master/html/users_guide/porting-cime.html):

        build_ctsm /path/to/nonexistent/directory --machine MACHINE --compiler COMPILER

        (Some other optional arguments are also allowed in this usage, but many are not.)

    For a fresh build with a machine that has NOT been ported to cime:

        build_ctsm /path/to/nonexistent/directory --os OS --compiler COMPILER --netcdf-path NETCDF_PATH --esmf-lib-path ESMF_LIB_PATH --max-mpitasks-per-node MAX_MPITASKS_PER_NODE --pnetcdf-path PNETCDF_PATH

        If PNetCDF is not available, set --no-pnetcdf instead of --pnetcdf-path.

        (Other optional arguments are also allowed in this usage.)

    For rebuilding:

        build_ctsm /path/to/existing/directory --rebuild

        (Most other arguments are NOT allowed in this usage.)
"""

    parser = argparse.ArgumentParser(
        description=description, formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument(
        'build_dir',
        help='Path to build directory\n'
        'If --rebuild is given, this should be the path to an existing build,\n'
        'otherwise this directory must not already exist.')

    main_opts = parser.add_mutually_exclusive_group()

    main_opts.add_argument(
        '--machine',
        help=
        'Name of machine; this must be a machine that has been ported to cime\n'
        '(http://esmci.github.io/cime/versions/master/html/users_guide/porting-cime.html)\n'
        'If given, then none of the machine-definition optional arguments should be given.\n'
    )

    main_opts.add_argument(
        '--rebuild',
        action='store_true',
        help='Rebuild in an existing build directory\n'
        'If given, none of the machine-definition or build-related optional arguments\n'
        'should be given.\n')

    non_rebuild_required = parser.add_argument_group(
        title='required arguments when not rebuilding',
        description='These arguments are required if --rebuild is not given; '
        'they are not allowed with --rebuild:')
    non_rebuild_required_list = []

    # For now, only support the compilers that we regularly test with, even though cime
    # supports many other options
    non_rebuild_required.add_argument('--compiler',
                                      type=str.lower,
                                      choices=['gnu', 'intel', 'nag', 'pgi'],
                                      help='Compiler type')
    non_rebuild_required_list.append('compiler')

    non_rebuild_optional = parser.add_argument_group(
        title='optional arguments when not rebuilding',
        description='These arguments are optional if --rebuild is not given; '
        'they are not allowed with --rebuild:')
    non_rebuild_optional_list = []

    non_rebuild_optional.add_argument(
        '--no-pnetcdf',
        action='store_true',
        help='Use NetCDF instead of PNetCDF for CTSM I/O.\n'
        'On a user-defined machine, you must either set this flag\n'
        'or set --pnetcdf-path. On a cime-ported machine,\n'
        'this flag must be set if PNetCDF is not available\n'
        'for this machine/compiler.')
    non_rebuild_optional_list.append('no-pnetcdf')

    non_rebuild_optional.add_argument(
        '--build-debug',
        action='store_true',
        help='Build with flags for debugging rather than production runs')
    non_rebuild_optional_list.append('build-debug')

    non_rebuild_optional.add_argument(
        '--build-with-openmp',
        action='store_true',
        help='By default, CTSM is built WITHOUT support for OpenMP threading;\n'
        'if this flag is set, then CTSM is built WITH this support.\n'
        'This is important for performance if you will be running with\n'
        'OpenMP threading-based parallelization, or hybrid MPI/OpenMP.')
    non_rebuild_optional_list.append('build-with-openmp')

    non_rebuild_optional.add_argument(
        '--inputdata-path',
        help='Path to directory containing CTSM\'s NetCDF inputs.\n'
        'For a machine that has been ported to cime, the default is to\n'
        'use this machine\'s standard inputdata location; this argument\n'
        'can be used to override this default.\n'
        'For a user-defined machine, the default is to create an inputdata\n'
        'directory in the build directory; again, this argument can be\n'
        'used to override this default.')
    non_rebuild_optional_list.append('inputdata-path')

    non_rebuild_optional.add_argument(
        '--no-build',
        action='store_true',
        help='Do the pre-build setup, but do not actually build CTSM\n'
        '(This is useful for testing, or for expert use.)')
    non_rebuild_optional_list.append('no-build')

    new_machine_required = parser.add_argument_group(
        title='required arguments for a user-defined machine',
        description=
        'These arguments are required if neither --machine nor --rebuild are given; '
        'they are not allowed with either of those arguments:')
    new_machine_required_list = []

    new_machine_required.add_argument(
        '--os',
        type=str.lower,
        choices=['linux', 'aix', 'darwin', 'cnl'],
        help='Operating system type')
    new_machine_required_list.append('os')

    new_machine_required.add_argument(
        '--netcdf-path',
        help='Path to NetCDF installation\n'
        '(path to top-level directory, containing subdirectories\n'
        'named lib, include, etc.)')
    new_machine_required_list.append('netcdf-path')

    new_machine_required.add_argument(
        '--esmf-lib-path',
        help='Path to ESMF library directory\n'
        'This directory should include an esmf.mk file')
    new_machine_required_list.append('esmf-lib-path')

    new_machine_required.add_argument(
        '--max-mpitasks-per-node',
        type=int,
        help='Number of physical processors per shared-memory node\n'
        'on this machine')
    new_machine_required_list.append('max-mpitasks-per-node')

    new_machine_optional = parser.add_argument_group(
        title='optional arguments for a user-defined machine',
        description=
        'These arguments are optional if neither --machine nor --rebuild are given; '
        'they are not allowed with either of those arguments:')
    new_machine_optional_list = []

    new_machine_optional.add_argument(
        '--gmake',
        default='gmake',
        help='Name of GNU Make tool on your system\n'
        'Default: gmake')
    new_machine_optional_list.append('gmake')

    new_machine_optional.add_argument(
        '--gmake-j',
        default=8,
        type=int,
        help='Number of threads to use when building\n'
        'Default: 8')
    new_machine_optional_list.append('gmake-j')

    new_machine_optional.add_argument(
        '--pnetcdf-path',
        help='Path to PNetCDF installation, if present\n'
        'You must either specify this or set --no-pnetcdf')
    new_machine_optional_list.append('pnetcdf-path')

    new_machine_optional.add_argument(
        '--pio-filesystem-hints',
        type=str.lower,
        choices=['gpfs', 'lustre'],
        help='Enable filesystem hints for the given filesystem type\n'
        'when building the Parallel IO library')
    new_machine_optional_list.append('pio-filesystem-hints')

    new_machine_optional.add_argument(
        '--gptl-nano-timers',
        action='store_true',
        help='Enable nano timers in build of the GPTL timing library')
    new_machine_optional_list.append('gptl-nano-timers')

    new_machine_optional.add_argument(
        '--extra-fflags',
        default='',
        help='Any extra, non-standard flags to include\n'
        'when compiling Fortran files\n'
        'Tip: to allow a dash at the start of these flags,\n'
        'use a quoted string with an initial space, as in:\n'
        '    --extra-fflags " -flag1 -flag2"')
    new_machine_optional_list.append('extra-fflags')

    new_machine_optional.add_argument(
        '--extra-cflags',
        default='',
        help='Any extra, non-standard flags to include\n'
        'when compiling C files\n'
        'Tip: to allow a dash at the start of these flags,\n'
        'use a quoted string with an initial space, as in:\n'
        '    --extra-cflags " -flag1 -flag2"')
    new_machine_optional_list.append('extra-cflags')

    add_logging_args(parser)

    args = parser.parse_args(args_to_parse)
    if args.rebuild:
        _confirm_args_absent(
            parser, args, "cannot be provided if --rebuild is set",
            (non_rebuild_required_list + non_rebuild_optional_list +
             new_machine_required_list + new_machine_optional_list))
    else:
        _confirm_args_present(parser, args,
                              "must be provided if --rebuild is not set",
                              non_rebuild_required_list)
        if args.machine:
            _confirm_args_absent(
                parser, args, "cannot be provided if --machine is set",
                new_machine_required_list + new_machine_optional_list)
        else:
            _confirm_args_present(
                parser, args,
                "must be provided if neither --machine nor --rebuild are set",
                new_machine_required_list)
            if not args.no_pnetcdf and args.pnetcdf_path is None:
                parser.error(
                    "For a user-defined machine, need to specify either --no-pnetcdf or --pnetcdf-path"
                )
            if args.no_pnetcdf and args.pnetcdf_path is not None:
                parser.error(
                    "--no-pnetcdf cannot be given if you set --pnetcdf-path")

    return args
コード例 #7
0
def _commandline_args():
    """Parse and return command-line arguments
    """

    description = """
Driver for running CTSM system tests

Typical usage:

./run_sys_tests -s aux_clm -c COMPARE_NAME -g GENERATE_NAME

    This automatically detects the machine and launches the appropriate components of the
    aux_clm test suite on that machine. This script also implements other aspects of the
    typical CTSM system testing workflow, such as running create_test via qsub on
    cheyenne, and setting up a directory to hold all of the tests in the test suite. A
    symbolic link will be created in the current directory pointing to the testroot
    directory containing all of the test directories in the test suite.

    Note that the -c/--compare and -g/--generate arguments are required, unless you specify
    --skip-compare and/or --skip-generate.

    Any other test suite can be given as well: clm_short, aux_glc, etc.

This can also be used to run tests listed in a text file (via the -f/--testfile argument),
or tests listed individually on the command line (via the -t/--testname argument).
"""

    parser = argparse.ArgumentParser(
        description=description, formatter_class=argparse.RawTextHelpFormatter)

    machine_name = get_machine_name()

    default_machine = create_machine(machine_name,
                                     defaults=MACHINE_DEFAULTS,
                                     allow_missing_entries=True)

    tests_to_run = parser.add_mutually_exclusive_group(required=True)

    tests_to_run.add_argument('-s',
                              '--suite-name',
                              help='Name of test suite to run')

    tests_to_run.add_argument('-f',
                              '--testfile',
                              help='Path to file listing tests to run')

    tests_to_run.add_argument(
        '-t',
        '--testname',
        '--testnames',
        nargs='+',
        help='One or more test names to run (space-delimited)')

    compare = parser.add_mutually_exclusive_group(required=True)

    compare.add_argument('-c',
                         '--compare',
                         metavar='COMPARE_NAME',
                         help='Baseline name (often tag) to compare against\n'
                         '(required unless --skip-compare is given)')

    compare.add_argument('--skip-compare',
                         action='store_true',
                         help='Do not compare against baselines')

    generate = parser.add_mutually_exclusive_group(required=True)

    generate.add_argument('-g',
                          '--generate',
                          metavar='GENERATE_NAME',
                          help='Baseline name (often tag) to generate\n'
                          '(required unless --skip-generate is given)')

    generate.add_argument('--skip-generate',
                          action='store_true',
                          help='Do not generate baselines')

    parser.add_argument(
        '--suite-compiler',
        '--suite-compilers',
        nargs='+',
        help='Compiler(s) from the given test suite for which tests are run\n'
        'Only valid in conjunction with -s/--suite-name;\n'
        'if not specified, use all compilers defined for this suite and machine\n'
    )

    parser.add_argument(
        '--account',
        help='Account number to use for job submission.\n'
        'This is needed on some machines; if not provided explicitly,\n'
        'the script will attempt to guess it using the same rules as in CIME.\n'
        'Default for this machine: {}'.format(default_machine.account))

    parser.add_argument(
        '--testid-base',
        help='Base string used for the test id.\n'
        'Default is to auto-generate this with a date and time stamp.')

    parser.add_argument('--testroot-base',
                        help='Path in which testroot should be put.\n'
                        'For supported machines, this can be left out;\n'
                        'for non-supported machines, it must be provided.\n'
                        'Default for this machine: {}'.format(
                            default_machine.scratch_dir))

    parser.add_argument(
        '--rerun-existing-failures',
        action='store_true',
        help='Rerun failed tests from the last PEND or FAIL state.\n'
        'This triggers the --use-existing option to create_test.\n'
        'To use this option, provide the same options to run_sys_tests\n'
        'as in the initial run, but also adding --testid-base\n'
        'corresponding to the base testid used initially.\n'
        '(However, many of the arguments to create_test are ignored,\n'
        'so it is not important for all of the options to exactly match\n'
        'those in the initial run.)\n'
        'This option implies --skip-testroot-creation (that option does not\n'
        'need to be specified separately if using --rerun-existing-failures).')

    if default_machine.baseline_dir:
        baseline_root_default_msg = 'Default for this machine: {}'.format(
            default_machine.baseline_dir)
    else:
        baseline_root_default_msg = "Default for this machine: use cime's default"
    parser.add_argument(
        '--baseline-root',
        help='Path in which baselines should be compared and generated.\n' +
        baseline_root_default_msg)

    parser.add_argument(
        '--walltime',
        help='Walltime for each test.\n'
        'If running a test suite, you can generally leave this unset,\n'
        'because it is set in the file defining the test suite.\n'
        'For other uses, providing this helps decrease the time spent\n'
        'waiting in the queue.')

    parser.add_argument(
        '--queue',
        help='Queue to which tests are submitted.\n'
        'The special value "{}" means do not add a --queue option to create_test,\n'
        'instead allowing CIME to pick an appropriate queue for each test\n'
        'using its standard mechanisms.\n'
        'Default for this machine: {}'.format(
            CREATE_TEST_QUEUE_UNSPECIFIED, default_machine.create_test_queue))

    parser.add_argument(
        '--retry',
        type=int,
        help='Argument to create_test: Number of times to retry failed tests.\n'
        'Default for this machine: {}'.format(
            default_machine.create_test_retry))

    parser.add_argument(
        '--extra-create-test-args',
        default='',
        help='String giving extra arguments to pass to create_test\n'
        '(To allow the argument parsing to accept this, enclose the string\n'
        'in quotes, with a leading space, as in " --my-arg foo".)')

    parser.add_argument(
        '--job-launcher-nobatch',
        action='store_true',
        help='Run create_test on the login node, even if this machine\n'
        'is set up to submit create_test to a compute node by default.')

    parser.add_argument(
        '--job-launcher-queue',
        help='Queue to which the create_test command is submitted.\n'
        'Only applies on machines for which we submit the create_test command\n'
        'rather than running it on the login node.\n'
        'Default for this machine: {}'.format(
            default_machine.job_launcher.get_queue()))

    parser.add_argument(
        '--job-launcher-walltime',
        help='Walltime for the create_test command.\n'
        'Only applies on machines for which we submit the create_test command\n'
        'rather than running it on the login node.\n'
        'Default for this machine: {}'.format(
            default_machine.job_launcher.get_walltime()))

    parser.add_argument(
        '--job-launcher-extra-args',
        help='Extra arguments for the command that launches the\n'
        'create_test command.\n'
        '(To allow the argument parsing to accept this, enclose the string\n'
        'in quotes, with a leading space, as in " --my-arg foo".)\n'
        'Default for this machine: {}'.format(
            default_machine.job_launcher.get_extra_args()))

    parser.add_argument(
        '--skip-testroot-creation',
        action='store_true',
        help='Do not create the directory that will hold the tests.\n'
        'This should be used if the desired testroot directory already exists.'
    )

    parser.add_argument(
        '--skip-git-status',
        action='store_true',
        help='Skip printing git and manage_externals status,\n'
        'both to screen and to the SRCROOT_GIT_STATUS file in TESTROOT.\n'
        'This printing can often be helpful, but this option can be used to\n'
        'avoid extraneous output, to reduce the time needed to run this script,\n'
        'or if git or manage_externals are currently broken in your sandbox.\n'
    )

    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='Print what would happen, but do not run any commands.\n'
        '(Generally should be run with --verbose.)\n')

    parser.add_argument('--machine-name',
                        default=machine_name,
                        help='Name of machine for which create_test is run.\n'
                        'This typically is not needed, but can be provided\n'
                        'for the sake of testing this script.\n'
                        'Defaults to current machine: {}'.format(machine_name))

    add_logging_args(parser)

    args = parser.parse_args()

    _check_arg_validity(args)

    return args
コード例 #8
0
def get_parser():
    """
    Get the parser object for subset_data.py script.

    Returns:
        parser (ArgumentParser): ArgumentParser which includes all the parser information.

    """
    parser = ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter)

    parser.print_usage = parser.print_help
    subparsers = parser.add_subparsers(
        help="Two possible ways to run this script, either:", dest="run_type")
    pt_parser = subparsers.add_parser("point",
                                      help="Run script for a single point.")
    rg_parser = subparsers.add_parser("region",
                                      help="Run script for a region.")

    # -- single point parser options
    pt_parser.add_argument(
        "--lat",
        help="Single point latitude. [default: %(default)s]",
        action="store",
        dest="plat",
        required=False,
        type=plat_type,
        default=42.5,
    )
    pt_parser.add_argument(
        "--lon",
        help="Single point longitude. [default: %(default)s]",
        action="store",
        dest="plon",
        required=False,
        type=plon_type,
        default=287.8,
    )
    pt_parser.add_argument(
        "--site",
        help="Site name or tag. [default: %(default)s]",
        action="store",
        dest="site_name",
        required=False,
        type=str,
        default="",
    )
    pt_parser.add_argument(
        "--uniform-snowpack",
        help="Modify surface data to have a uniform snow fraction.",
        action="store_true",
        dest="uni_snow",
        required=False,
    )
    pt_parser.add_argument(
        "--include-nonveg",
        help="Do not zero non-vegetation land units in the surface data.",
        action="store_true",
        dest="include_nonveg",
        required=False,
    )
    pt_parser.add_argument(
        "--cap-saturation",
        help="Modify surface data to not allow saturation excess.",
        action="store_true",
        dest="cap_saturation",
        required=False,
    )
    pt_parser.add_argument(
        "--dompft",
        help="Dominant PFT(s): if we set the grid to 100%% one or multiple PFTs \
        [default: %(default)s].",
        action="store",
        dest="dom_pft",
        type=int,
        default=None,
        nargs='*',
    )
    pt_parser.add_argument(
        "--pctpft",
        help="Percetages of each pft (set by --dompft) on the land unit.",
        action="store",
        dest="pct_pft",
        type=float,
        default=None,
        nargs='*',
    )
    # -- region-specific parser options
    rg_parser.add_argument(
        "--lat1",
        help="Region start latitude. [default: %(default)s]",
        action="store",
        dest="lat1",
        required=False,
        type=plat_type,
        default=-40,
    )
    rg_parser.add_argument(
        "--lat2",
        help="Region end latitude. [default: %(default)s]",
        action="store",
        dest="lat2",
        required=False,
        type=plat_type,
        default=15,
    )
    rg_parser.add_argument(
        "--lon1",
        help="Region start longitude. [default: %(default)s]",
        action="store",
        dest="lon1",
        required=False,
        type=plon_type,
        default=275.0,
    )
    rg_parser.add_argument(
        "--lon2",
        help="Region end longitude. [default: %(default)s]",
        action="store",
        dest="lon2",
        required=False,
        type=plon_type,
        default=330.0,
    )
    rg_parser.add_argument(
        "--reg",
        help="Region name or tag. [default: %(default)s]",
        action="store",
        dest="reg_name",
        required=False,
        type=str,
        default="",
    )
    rg_parser.add_argument(
        "--create-mesh",
        help="Subset a mesh file for a region.",
        action="store_true",
        dest="create_mesh",
        required=False,
    )

    # -- common options between both subparsers
    for subparser in [pt_parser, rg_parser]:
        subparser.add_argument(
            "--create-domain",
            help="Create CLM domain file at single point/region. \
            Domain files are not needed for NUOPC cases.",
            action="store_true",
            dest="create_domain",
            required=False,
        )
        subparser.add_argument(
            "--create-surface",
            help="Create surface data file at single point/region.",
            action="store_true",
            dest="create_surfdata",
            required=False,
        )
        subparser.add_argument(
            "--create-landuse",
            help="Create landuse data file at single point/region.",
            action="store_true",
            dest="create_landuse",
            required=False,
        )
        subparser.add_argument(
            "--create-datm",
            help="Create DATM forcing data at single point.",
            action="store_true",
            dest="create_datm",
            required=False,
        )
        subparser.add_argument(
            "--create-user-mods",
            help=
            "Create user mods directories and files for running CTSM with the subset data.",
            action="store_true",
            dest="create_user_mods",
            required=False,
        )
        subparser.add_argument(
            "--datm-syr",
            help=
            "Start year for creating DATM forcing at single point/region. [default: %("
            "default)s]",
            action="store",
            dest="datm_syr",
            required=False,
            type=int,
            default=1901,
        )
        subparser.add_argument(
            "--datm-eyr",
            help="End year for creating DATM forcing at single point/region. "
            "[default: %(default)s]",
            action="store",
            dest="datm_eyr",
            required=False,
            type=int,
            default=2014,
        )
        subparser.add_argument(
            "--crop",
            help=
            "Create datasets using the extensive list of prognostic crop types.",
            action="store_true",
            dest="crop_flag",
            required=False,
        )

        if subparser == pt_parser:
            parser_name = "single_point"
        else:
            parser_name = "regional"

        subparser.add_argument(
            "--outdir",
            help="Output directory. \n [default: %(default)s]",
            action="store",
            dest="out_dir",
            type=str,
            default=os.path.join(os.getcwd(), "subset_data_" + parser_name),
        )
        subparser.add_argument(
            "--user-mods-dir",
            help="User mods directory.",
            action="store",
            dest="user_mods_dir",
            type=str,
            default="",
        )
        subparser.add_argument(
            "--overwrite",
            help="Flag to overwrite if the files already exists.",
            action="store_true",
            dest="overwrite",
        )
        add_logging_args(subparser)

    # -- print help for both subparsers
    parser.epilog = textwrap.dedent(f"""\
         {pt_parser.format_help()}
         {rg_parser.format_help()}
         """)
    return parser