Skip to content

IO

Module functions for working with configuration files.

write_config

write_config(args)

Write a configuration file to YAML.

Parameters:

Name Type Description Default
args Namespace | dict[str, Any]

A Namespace object parsed from argparse. If there are values for output_dir and filename these will be used to construct the path and filename to write the YAML file to. If not then output files are contingent on how the function is being called. If it is from layopt create_config then default_config.yaml will be written. If it is at the end of processing then config_YY-MM-DD-hhmmss.yaml will be used.

required
Source code in src/layopt/io.py
def write_config(args: Namespace | dict[str, Any] | None) -> None:
    """
    Write a configuration file to YAML.

    Parameters
    ----------
    args : Namespace | dict[str, Any], optional
        A Namespace object parsed from argparse. If there are values for ``output_dir`` and ``filename`` these will be
        used to construct the path and filename to write the YAML file to.  If not then output files are contingent on
        how the function is being called. If it is from ``layopt create_config`` then ``default_config.yaml`` will be
        written. If it is at the end of processing then ``config_YY-MM-DD-hhmmss.yaml`` will be used.
    """
    # If args is `Namespace` then we are writing config with 'layopt create_config' subcommand
    if isinstance(args, Namespace):
        output_dir = Path("./") if args.output_dir is None else Path(args.output_dir)
        filename = "default_config.yaml" if args.filename is None else args.filename
    # Otherwise we are writing after 'layopt optimise' and config is a dictionary, this won't have a 'filename'
    # key/value pair
    elif isinstance(args, dict):
        output_dir = (
            Path("./") if args["output_dir"] is None else Path(args["output_dir"])
        )
        # Add missing 'filename' key/value pair
        filename = f"config_{get_date_time(strftime='%Y-%m-%d-%H%M%S')}.yaml"
    else:
        msg = f"args is neither 'Namespace' or 'dict' : {type(args)}"
        raise TypeError(msg)
    if ".yaml" not in str(filename) and ".yml" not in str(filename):
        config_path = output_dir / f"{filename}.yaml"
    else:
        config_path = output_dir / filename
    logger_msg = "A sample configuration has been written to"
    try:
        config = get_data(package="layopt", resource="default_config.yaml")
    except FileNotFoundError as exc:
        msg = (
            "There was a problem loading 'default_config.yaml' try reinstalling LayOpt."
        )
        raise (FileNotFoundError(msg)) from exc
    with config_path.open("w", encoding="utf-8") as f:
        try:
            f.write(f"# Config generated {get_date_time()}\n")
            f.write(f"{CONFIG_DOCUMENTATION_REFERENCE}")
            f.write(config.decode("utf-8"))
        except:  # noqa: E722, pylint: disable=W0702
            logger.error(f"Failed to write config to : {config_path}")
    logger.info(f"{logger_msg} : {config_path!s}")

read_yaml

read_yaml(filename)

Read a YAML file.

Parameters:

Name Type Description Default
filename Union[str, Path]

YAML file to read.

required

Returns:

Type Description
Dict

Dictionary of the file.

Source code in src/layopt/io.py
def read_yaml(filename: str | Path) -> dict[str, Any]:
    """
    Read a YAML file.

    Parameters
    ----------
    filename : Union[str, Path]
        YAML file to read.

    Returns
    -------
    Dict
        Dictionary of the file.
    """
    with Path(filename).open(encoding="utf-8") as f:
        try:
            return yaml.full_load(f)
        except YAMLError as exception:
            logger.error(exception)
            return {}

convert_path

convert_path(path)

Ensure path is Path object.

Parameters:

Name Type Description Default
path str | Path

Path to be converted.

required

Returns:

Type Description
Path

Pathlib object of path.

Source code in src/layopt/io.py
def convert_path(path: str | Path) -> Path:
    """
    Ensure path is Path object.

    Parameters
    ----------
    path : str | Path
        Path to be converted.

    Returns
    -------
    Path
        Pathlib object of path.
    """
    return Path().cwd() if path == "./" else Path(path).expanduser()

get_date_time

get_date_time(strftime='%Y-%m-%d %H:%M:%S')

Get the current date-time as a string for the systems current timezone.

Parameters:

Name Type Description Default
strftime str

String for formatting date-time, default is %Y-%m-%d %H:%M:%S.

'%Y-%m-%d %H:%M:%S'

Returns:

Type Description
str

Date-time as a string for systems current timezone.

Source code in src/layopt/io.py
def get_date_time(strftime: str = "%Y-%m-%d %H:%M:%S") -> str:
    """
    Get the current date-time as a string for the systems current timezone.

    Parameters
    ----------
    strftime : str
        String for formatting date-time, default is ``%Y-%m-%d %H:%M:%S``.

    Returns
    -------
    str
        Date-time as a string for systems current timezone.
    """
    return datetime.now(tz=datetime.now().astimezone().tzinfo).strftime(strftime)

dict_to_df

dict_to_df(results)

Convert a dictionary of LayOpt results to Pandas DataFrame.

Typically a set of results is a dictionary with no nesting and the resulting data frame has a single row.

Parameters:

Name Type Description Default
results dict[str, Any]

Dictionary to convert to Pandas DataFrame.

required

Returns:

Type Description
DataFrame

Data as a Pandas dictionary.

Source code in src/layopt/io.py
def dict_to_df(results: dict[str, Any]) -> pd.DataFrame:
    """
    Convert a dictionary of LayOpt results to Pandas DataFrame.

    Typically a set of results is a dictionary with no nesting and the resulting data frame has a single row.

    Parameters
    ----------
    results : dict[str, Any]
        Dictionary to convert to Pandas DataFrame.

    Returns
    -------
    pd.DataFrame
        Data as a Pandas dictionary.
    """
    return pd.DataFrame.from_dict(results, orient="index").T