Esempio n. 1
0
def install_script():
    set_mpi_disabled(True)
    warn_deprecation()
    # Parse arguments
    import argparse
    parser = argparse.ArgumentParser(
        description="Cobaya's installation tool for external packages.")
    parser.add_argument(
        "files_or_components",
        action="store",
        nargs="+",
        metavar="input_file.yaml|component_name",
        help="One or more input files or component names "
        "(or simply 'cosmo' to install all the requisites for basic"
        " cosmological runs)")
    parser.add_argument(
        "-" + _packages_path_arg[0],
        "--" + _packages_path_arg_posix,
        action="store",
        nargs=1,
        required=False,
        metavar="/packages/path",
        default=[None],
        help="Desired path where to install external packages. "
        "Optional if one has been set globally or as an env variable"
        " (run with '--show_%s' to check)." % _packages_path_arg_posix)
    # MARKED FOR DEPRECATION IN v3.0
    modules = "modules"
    parser.add_argument("-" + modules[0],
                        "--" + modules,
                        action="store",
                        nargs=1,
                        required=False,
                        metavar="/packages/path",
                        default=[None],
                        help="To be deprecated! "
                        "Alias for %s, which should be used instead." %
                        _packages_path_arg_posix)
    # END OF DEPRECATION BLOCK -- CONTINUES BELOW!
    output_show_packages_path = resolve_packages_path()
    if output_show_packages_path and os.environ.get(_packages_path_env):
        output_show_packages_path += " (from env variable %r)" % _packages_path_env
    elif output_show_packages_path:
        output_show_packages_path += " (from config file)"
    else:
        output_show_packages_path = "(Not currently set.)"
    parser.add_argument(
        "--show-" + _packages_path_arg_posix,
        action="version",
        version=output_show_packages_path,
        help="Prints default external packages installation folder "
        "and exits.")
    parser.add_argument(
        "-" + _force[0],
        "--" + _force,
        action="store_true",
        default=False,
        help="Force re-installation of apparently installed packages.")
    parser.add_argument(
        "--skip",
        action="store",
        nargs="*",
        metavar="keyword",
        help="Keywords of components that will be skipped during "
        "installation.")
    parser.add_argument(
        "--no-progress-bars",
        action="store_true",
        default=False,
        help="No progress bars shown. Shorter logs (used in Travis).")
    parser.add_argument("--just-check",
                        action="store_true",
                        default=False,
                        help="Just check whether components are installed.")
    parser.add_argument(
        "--no-set-global",
        action="store_true",
        default=False,
        help="Do not store the installation path for later runs.")
    group_just = parser.add_mutually_exclusive_group(required=False)
    group_just.add_argument("-C",
                            "--just-code",
                            action="store_false",
                            default=True,
                            help="Install code of the components.",
                            dest=_data)
    group_just.add_argument("-D",
                            "--just-data",
                            action="store_false",
                            default=True,
                            help="Install data of the components.",
                            dest=_code)
    arguments = parser.parse_args()
    # Configure the logger ASAP
    logger_setup()
    logger = logging.getLogger(__name__.split(".")[-1])
    # Gather requests
    infos = []
    for f in arguments.files_or_components:
        if f.lower() == "cosmo":
            logger.info("Installing basic cosmological packages.")
            from cobaya.cosmo_input import install_basic
            infos += [install_basic]
        elif f.lower() == "cosmo-tests":
            logger.info("Installing *tested* cosmological packages.")
            from cobaya.cosmo_input import install_tests
            infos += [install_tests]
        elif os.path.splitext(f)[1].lower() in _yaml_extensions:
            from cobaya.input import load_input
            infos += [load_input(f)]
        else:
            try:
                kind = get_kind(f)
                infos += [{kind: {f: None}}]
            except Exception:
                logger.warning("Could not identify component %r. Skipping.", f)
    if not infos:
        logger.info("Nothing to install.")
        return
    # MARKED FOR DEPRECATION IN v3.0
    if getattr(arguments, modules) != [None]:
        logger.warning(
            "*DEPRECATION*: -m/--modules will be deprecated in favor of "
            "-%s/--%s in the next version. Please, use that one instead.",
            _packages_path_arg[0], _packages_path_arg_posix)
        # BEHAVIOUR TO BE REPLACED BY ERROR:
        if getattr(arguments, _packages_path_arg) == [None]:
            setattr(arguments, _packages_path_arg, getattr(arguments, modules))
    # END OF DEPRECATION BLOCK
    # Launch installer
    install(*infos,
            path=getattr(arguments, _packages_path_arg)[0],
            **{
                arg: getattr(arguments, arg)
                for arg in [
                    "force", _code, _data, "no_progress_bars", "just_check",
                    "no_set_global", "skip"
                ]
            })
Esempio n. 2
0
def doc_script():
    from cobaya.mpi import is_main_process
    if not is_main_process():
        return
    warn_deprecation()
    # Parse arguments
    import argparse
    parser = argparse.ArgumentParser(
        description="Prints defaults for Cobaya's components.")
    parser.add_argument("component",
                        action="store",
                        nargs="?",
                        default="",
                        metavar="component_name",
                        help="The component whose defaults are requested.")
    kind_opt, kind_opt_ishort = "kind", 0
    parser.add_argument(
        "-" + kind_opt[kind_opt_ishort],
        "--" + kind_opt,
        action="store",
        nargs=1,
        default=None,
        metavar="component_kind",
        help=("Kind of component whose defaults are requested: " +
              ", ".join(['%s' % kind for kind in kinds]) + ". " +
              "Use only when component name is not unique (it would fail)."))
    parser.add_argument("-p",
                        "--python",
                        action="store_true",
                        default=False,
                        help="Request Python instead of YAML.")
    expand_flag, expand_flag_ishort = "expand", 1
    parser.add_argument("-" + expand_flag[expand_flag_ishort],
                        "--" + expand_flag,
                        action="store_true",
                        default=False,
                        help="Expand YAML defaults.")
    arguments = parser.parse_args()
    # Remove plurals (= name of src subfolders), for user-friendliness
    if arguments.component.lower() in subfolders.values():
        arguments.component = next(k for k in subfolders
                                   if arguments.component == subfolders[k])
    # Kind given, list all
    if not arguments.component:
        msg = "Available components: (some may need external code/data)"
        print(msg + "\n" + "-" * len(msg))
        for kind in kinds:
            print("%s:" % kind)
            print(_indent +
                  ("\n" +
                   _indent).join(get_available_internal_class_names(kind)))
        return
    # Kind given: list all components of that kind
    if arguments.component.lower() in kinds:
        print("%s:" % arguments.component.lower())
        print(_indent + ("\n" + _indent).join(
            get_available_internal_class_names(arguments.component.lower())))
        return
    # Otherwise, check if it's a unique component name
    try:
        if arguments.kind:
            arguments.kind = arguments.kind[0].lower()
            if arguments.kind not in kinds:
                print("Kind %r not recognized. Try one of %r" %
                      (arguments.kind, tuple(kinds)))
                raise ValueError
        else:
            arguments.kind = get_kind(arguments.component)
        to_print = get_default_info(arguments.component,
                                    arguments.kind,
                                    return_yaml=not arguments.python,
                                    yaml_expand_defaults=arguments.expand)
        if arguments.python:
            print(pformat({arguments.kind: {arguments.component: to_print}}))
        else:
            print(arguments.kind + ":\n" + _indent + arguments.component +
                  ":\n" + 2 * _indent +
                  ("\n" + 2 * _indent).join(to_print.split("\n")))
            if "!defaults" in to_print:
                print("# This file contains defaults. "
                      "To populate them, use the flag --%s (or -%s)." %
                      (expand_flag, expand_flag[expand_flag_ishort]))
    except Exception:
        if isinstance(Exception, LoggedError.__class__):
            pass
        else:
            if not arguments.kind:
                print("Specify its kind with '--%s [component_kind]'." %
                      kind_opt)
        return 1
    return