h2integrate.core.utilities#

Functions

attr_filter(inst, value)

attr_serializer(inst, field, value)

check_file_format_for_csv_generator(...[, ...])

Check csv file format for the csv file used for the CSVGenerator generator.

check_plant_config_and_profast_params(...)

Checks for consistency between values in the plant configuration dictionary and the ProFAST parameters dictionary.

check_pysam_input_params(user_dict, ...)

Checks for different values provided in two dictionaries that have the general format.

create_xdsm_from_config(config[, output_file])

Create an XDSM diagram from a given plant configuration and save it to a pdf file.

dict_to_yaml_formatting(orig_dict)

Recursive method to convert arrays to lists and numerical entries to floats.

find_file(filename[, root_folder])

This function attempts to find a filepath matching filename from a variety of locations in the following order:

get_path(path)

Convert a string or Path object to an absolute Path object, prioritizing different locations.

load_yaml(filename[, loader])

make_unique_case_name(folder, ...)

Generate a filename that does not already exist in a user-defined folder.

merge_shared_inputs(config, input_type)

Merges two dictionaries from a configuration object and resolves potential conflicts.

print_results(model[, includes, excludes, ...])

Print hierarchical inputs plus explicit/implicit outputs (means only) using Rich.

remove_numpy(fst_vt)

Recursively converts numpy array elements within a nested dictionary to lists and ensures all values are simple types (float, int, dict, bool, str) for writing to a YAML file.

write_readable_yaml(instance, foutput)

Writes a dictionary to a YAML file using the yaml library.

write_yaml(instance, foutput[, convert_np, ...])

Writes a dictionary to a YAML file using the ruamel.yaml library.

Classes

BaseConfig()

A Mixin class to allow for kwargs overloading when a data class doesn't have a specific parameter defined.

Loader(stream)

Exceptions

DuplicateKeyError(message)

Exception raised when a duplicate YAML key is found.

h2integrate.core.utilities.create_xdsm_from_config(config, output_file='connections_xdsm')#

Create an XDSM diagram from a given plant configuration and save it to a pdf file.

Parameters:
  • config (dict) – Configuration dictionary containing technology interconnections.

  • output_file (str, optional) – The name of the output file where the XDSM diagram will be saved.

h2integrate.core.utilities.merge_shared_inputs(config, input_type)#

Merges two dictionaries from a configuration object and resolves potential conflicts.

This function combines the dictionaries associated with shared_parameters and performance_parameters, cost_parameters, or finance_parameters in the provided config dictionary. If both dictionaries contain the same keys, a ValueError is raised to prevent duplicate parameter definitions.

Parameters:
  • config (dict) – A dictionary containing configuration data. It must include keys like shared_parameters and {input_type}_parameters.

  • input_type (str) – The type of input parameters to merge. Valid values are ‘performance’, ‘control’, ‘cost’, or ‘finance’.

Returns:

dict

A merged dictionary containing parameters from both shared_parameters

and {input_type}_parameters. If one of the dictionaries is missing, the function returns the existing dictionary.

Raises:

ValueError – If duplicate keys are found in shared_parameters and {input_type}_parameters.

class h2integrate.core.utilities.BaseConfig#

A Mixin class to allow for kwargs overloading when a data class doesn’t have a specific parameter defined. This allows passing of larger dictionaries to a data class without throwing an error.

classmethod from_dict(data, strict=True, additional_cls_name=None)#

Maps a data dictionary to an attr-defined class.

Parameters:
  • data (dict) – dict The data dictionary to be mapped.

  • strict

    bool A flag enabling strict parameter processing, meaning that no extra parameters

    may be passed in or an AttributeError will be raised.

  • additional_cls_name (str | None) – The name of the model class creating the configuration data class. Provides an easier to diagnose error message for end users when the class name is provided.

Returns:

cls

The attr-defined class.

as_dict()#

Creates a JSON and YAML friendly dictionary that can be save for future reloading. This dictionary will contain only Python types that can later be converted to their proper Turbine formats.

Returns:

dict – All key, value pairs required for class re-creation.

Return type:

dict

h2integrate.core.utilities.attr_serializer(inst, field, value)#
Parameters:
  • inst (type)

  • field (Attribute)

  • value (Any)

h2integrate.core.utilities.attr_filter(inst, value)#
Parameters:
  • inst (Attribute)

  • value (Any)

Return type:

bool

h2integrate.core.utilities.check_pysam_input_params(user_dict, pysam_options)#

Checks for different values provided in two dictionaries that have the general format:

value = input_dict[group][group_param]
Parameters:
  • user_dict (dict) – top-level performance model inputs formatted to align with the corresponding PySAM module.

  • pysam_options (dict) – additional PySAM module options.

Raises:

ValueError – if there are two different values provided for the same key.

h2integrate.core.utilities.check_plant_config_and_profast_params(plant_config_dict, pf_param_dict, plant_config_key, pf_config_key)#

Checks for consistency between values in the plant configuration dictionary and the ProFAST parameters dictionary.

This function compares the value associated with plant_config_key in plant_config_dict to the value associated with pf_config_key in pf_param_dict. If pf_config_key is not present in pf_param_dict, the value from plant_config_dict is used as the default. If the values are inconsistent, a ValueError is raised with a descriptive message.

Parameters:
  • plant_config_dict (dict) – Dictionary containing plant configuration parameters.

  • pf_param_dict (dict) – Dictionary containing ProFAST parameter values.

  • plant_config_key (str) – Key to look up in plant_config_dict.

  • pf_config_key (str) – Key to look up in pf_param_dict.

Raises:

ValueError – If the values for the specified keys in the two dictionaries are inconsistent.

h2integrate.core.utilities.dict_to_yaml_formatting(orig_dict)#

Recursive method to convert arrays to lists and numerical entries to floats. This is primarily used before writing a dictionary to a YAML file to ensure proper output formatting.

Parameters:

orig_dict (dict) – input dictionary

Returns:

dict – input dictionary with reformatted values.

h2integrate.core.utilities.get_path(path)#

Convert a string or Path object to an absolute Path object, prioritizing different locations.

This function attempts to find the existence of a path in the following order: 1. As an absolute path. 2. Relative to the current working directory. 3. Relative to the H2Integrate package.

Parameters:

path (str | Path) – The input path, either as a string or a Path object.

Raises:

FileNotFoundError – If the path is not found in any of the locations.

Returns:

Path – The absolute path to the file.

Return type:

Path

h2integrate.core.utilities.find_file(filename, root_folder=None)#

This function attempts to find a filepath matching filename from a variety of locations in the following order:

  1. Relative to the root_folder (if provided)

  2. Relative to the current working directory.

  3. Relative to the H2Integrate package.

  4. As an absolute path if filename is already absolute

Parameters:
  • filename (str | Path) – Input filepath

  • root_folder (str | Path, optional) – Root directory to search for filename in. Defaults to None.

Raises:

FileNotFoundError – If the path is not found in any of the locations.

Returns:

Path – The absolute path to the file.

h2integrate.core.utilities.remove_numpy(fst_vt)#

Recursively converts numpy array elements within a nested dictionary to lists and ensures all values are simple types (float, int, dict, bool, str) for writing to a YAML file.

Parameters:

fst_vt (dict) – The dictionary to process.

Returns:

dict

The processed dictionary with numpy arrays converted to lists

and unsupported types to simple types.

Return type:

dict

exception h2integrate.core.utilities.DuplicateKeyError(message)#

Exception raised when a duplicate YAML key is found.

Parameters:

( (message) – obj:str): The duplicate key error message to be displayed.

class h2integrate.core.utilities.Loader(stream)#
include(node)#
compose_node(parent, index)#

Custom implementation to include line numbers that account for all lines, including blank spaces that align with user anticipated 1-indexing.

construct_mapping(node, deep=False)#

Hooks into the yaml.SafeLoader.construct_mapping routine to create line number mappings for all keys and values, which enables duplicate key error handling.

Two copies of node are created to avoid errors when run through the validation schema as the __line__{key} and __line__ keys in the key and value nodes are not represented by the schema, and therefore raise an error during validation.

check_duplicate_keys(numbered_node, node, deep=False)#

Raises an error for duplicate keys and calls the SafeLoader.construct_mapping() routine to create the final dictionary mappings.

yaml_constructors = {'!include': <function Loader.include>, 'tag:yaml.org,2002:binary': <function SafeConstructor.construct_yaml_binary>, 'tag:yaml.org,2002:bool': <function SafeConstructor.construct_yaml_bool>, 'tag:yaml.org,2002:float': <function SafeConstructor.construct_yaml_float>, 'tag:yaml.org,2002:int': <function SafeConstructor.construct_yaml_int>, 'tag:yaml.org,2002:map': <function SafeConstructor.construct_yaml_map>, 'tag:yaml.org,2002:null': <function SafeConstructor.construct_yaml_null>, 'tag:yaml.org,2002:omap': <function SafeConstructor.construct_yaml_omap>, 'tag:yaml.org,2002:pairs': <function SafeConstructor.construct_yaml_pairs>, 'tag:yaml.org,2002:seq': <function SafeConstructor.construct_yaml_seq>, 'tag:yaml.org,2002:set': <function SafeConstructor.construct_yaml_set>, 'tag:yaml.org,2002:str': <function SafeConstructor.construct_yaml_str>, 'tag:yaml.org,2002:timestamp': <function SafeConstructor.construct_yaml_timestamp>, None: <function SafeConstructor.construct_undefined>}#
h2integrate.core.utilities.load_yaml(filename, loader=<class 'h2integrate.core.utilities.Loader'>)#
Return type:

dict

h2integrate.core.utilities.write_yaml(instance, foutput, convert_np=True, check_formatting=False)#

Writes a dictionary to a YAML file using the ruamel.yaml library.

Parameters:
  • instance (dict) – Dictionary to be written to the YAML file.

  • foutput (str) – Path to the output YAML file.

  • convert_np (bool) – Whether to convert numpy objects to simple types. Defaults to True.

  • check_formatting (bool) – Whether to check formatting to convert numpy arrays to lists. Defaults to False.

Returns:

None

Return type:

None

h2integrate.core.utilities.write_readable_yaml(instance, foutput)#

Writes a dictionary to a YAML file using the yaml library.

Parameters:
  • instance (dict) – Dictionary to be written to the YAML file.

  • foutput (str | Path) – Path to the output YAML file.

Returns:

None

h2integrate.core.utilities.make_unique_case_name(folder, proposed_fname, fext)#

Generate a filename that does not already exist in a user-defined folder.

Parameters:
  • folder (str | Path) – directory that a file is expected to be created in.

  • proposed_fname (str) – filename (with extension) to check for existence and to use as the base file description of a new an unique file name.

  • fext (str) – file extension, such as “.csv”, “.sql”, “.yaml”, etc.

Returns:

str – unique filename that does not yet exist in folder.

h2integrate.core.utilities.check_file_format_for_csv_generator(csv_fpath, driver_config, check_only=True, overwrite_file=False)#

Check csv file format for the csv file used for the CSVGenerator generator.

Note

Future development could include further checking the values within the rows of the csv file and more rigorous checking of columns with empty headers.

Parameters:
  • csv_fpath (str | Path) – filepath to csv file used for ‘csvgen’ generator.

  • driver_config (dict) – driver configuration dictionary

  • check_only (bool, optional) – If True, only check if file is error-free and return a boolean. If False, also create a valid csv file if errors are found in the original csv file. Defaults to True.

  • overwrite_file (bool, optional) – If True, overwrites the input csv file with possible errors removed. If False, writes a new csv file with a unique name. Only used if check_only is False. Defaults to False.

Raises:

ValueError – If there are errors in the csv file beyond general formatting errors.

Returns:

bool | Path

returns a boolean if check_only is True, or a Path object is check_only is

False. If check_only is True, returns True if the file appears error-free or False if errors are found. If check_only is False, returns the filepath of the new csv file that should not have errors.

h2integrate.core.utilities.print_results(model, includes=None, excludes=None, show_units=True)#

Print hierarchical inputs plus explicit/implicit outputs (means only) using Rich.

Order of rows preserves OpenMDAO’s original ordering from list_inputs/list_outputs. Group rows are emitted lazily the first time a variable within that path appears.