vuegen.utils package#

File system utilities, file conversion functions, graph related utilities, config file writing, and command line parser and logging messages (completion).

streamlit report footer is also in this file.

vuegen.utils.assert_enum_value(enum_class: Type[StrEnum], value: str, logger: Logger) StrEnum[source]#

Validate that the given value is a valid member of the specified enumeration class.

Parameters:
  • enum_class (Type[StrEnum]) – The enumeration class to validate against.

  • value (str) – The value to be validated.

  • logger (logging.Logger) – A logger object to track warnings, errors, and info messages.

Returns:

The corresponding member of the enumeration if valid.

Return type:

StrEnum

Raises:

ValueError – If the value is not a valid member of the enumeration class.

vuegen.utils.check_path(filepath: Path) bool[source]#

Checks if the given file or folder path exists.

Parameters:

filepath (Path) – The file or folder path to check.

Returns:

True if the path exists, False otherwise.

Return type:

bool

vuegen.utils.create_folder(directory_path: str, is_nested: bool = False) bool[source]#

Create a folder. Optionally create nested directories if the specified path includes subdirectories.

Parameters:
  • directory_path (str) – The path of the directory to create.

  • is_nested (bool) – A flag indicating whether to create nested directories. True uses os.makedirs, False uses os.mkdir.

Returns:

True if the folder was created or False if it already existed.

Return type:

bool

Raises:

OSError – If there is an error creating the directory.

vuegen.utils.cyjs_to_networkx(file_path: str, name: str = 'name', ident: str = 'id') Graph[source]#

Create a NetworkX graph from a .cyjs file in Cytoscape format, including all attributes present in the JSON data. This function is modified from the cytoscape_graph networkx function to handle the ‘value’ key explicitly and to include all additional attributes found in the JSON data for both nodes and edges.

Parameters:
  • file_path (str) – The path to a .cyjs file (Cytoscape JSON format) containing the network data.

  • name (str, optional) – A string which is mapped to the ‘name’ node element in Cytoscape JSON format.

  • ident (str, optional) – A string which is mapped to the ‘id’ node element in Cytoscape JSON format. Must not have the same value as name. Default is “id”.

Returns:

graph – The graph created from the Cytoscape JSON data, including all node and edge attributes.

Return type:

networkx.Graph

Raises:
  • NetworkXError – If the name and ident attributes are identical.

  • ValueError – If the data format is invalid or missing required elements, such as ‘id’ or ‘name’ for nodes.

vuegen.utils.fetch_file_stream(file_path: str, timeout: int = 60) StringIO[source]#

Fetches a file-like stream from a given file path or URL.

Parameters:

file_path (str) – The path to a local file or a URL to fetch content from.

Returns:

A file-like object containing the content of the file or URL.

Return type:

StringIO

Raises:

Generate an HTML footer for a report.

This function creates a styled HTML footer that includes a link to VueGen and the Multiomics Network Analytics Group (MoNA).

Returns:

A formatted HTML string representing the footer.

Return type:

str

vuegen.utils.generate_log_filename(folder: str = 'logs', suffix: str = '') str[source]#

Creates log file name and path

Parameters:
  • (str) (suffix)

  • (str)

Returns:

The file path to the log file

Return type:

str

vuegen.utils.get_basename(fname: None | str = None) str[source]#
  • For a given filename, returns basename WITHOUT file extension

  • If no fname given (i.e., None) then return basename that the function is called in

Parameters:

fname (str, optional) – The filename to get basename from. Default is None.

Returns:

basename of given filepath or the current file the function is executed

Return type:

str

Examples

1) >>> get_basename() utils

2) >>> get_basename(‘this/is-a-filepath.csv’) is-a-filepath

vuegen.utils.get_completion_message(report_type: str, config_path: str) str[source]#

Generate a formatted completion message after report generation.

Parameters:
  • report_type (str) – The type of report generated (e.g., “streamlit”, “html”).

  • config_path (str) – The path to the configuration file used for generating the report.

Returns:

A formatted string containing the completion message.

Return type:

str

vuegen.utils.get_logger(log_suffix, folder='logs', display=True, logger_id='vuegen') tuple[Logger, str][source]#

Initialize the logger with a log file name that includes an optional suffix.

Parameters:

log_suffix (str) – A string to append to the log file name.

Returns:

A tuple containing the logger instance and the log file path.

Return type:

tuple[logging.Logger, str]

vuegen.utils.get_parser(prog_name: str, others: dict | None = None) Namespace[source]#

Initiates argparse.ArgumentParser() and adds common arguments.

Parameters:
  • prog_name (str) – The name of the program.

  • others (dict, optional) – Additional keyword arguments for ArgumentParser initialization.

Returns:

Parsed command-line arguments.

Return type:

argparse.Namespace

Raises:

AssertionError – If prog_name is not a string or others is not a dictionary.

vuegen.utils.get_relative_file_path(file_path: str, base_path: str = '', relative_to: str = '.') Path[source]#

Returns the relative file path of a given file with respect to the current working directory (CWD).

This method will resolve the absolute path of the given file and return a relative path with respect to the directory where the script is being executed. Optionally, a base path can be added (e.g., “../”).

Parameters:
  • file_path (str) – The full file path to be converted to a relative path.

  • base_path (str, optional) – The base path to be prepended to the relative path, default is an empty string.

  • relativ_to (str, optional) – The directory to which the file path should be relative, default is the current directory (“.”).

Returns:

The file path relative to the CWD.

Return type:

Path

vuegen.utils.get_time(incl_time: bool = True, incl_timezone: bool = True) str[source]#

Gets current date, time (optional) and timezone (optional) for file naming

Parameters:
  • (bool) (- incl_timezone)

  • (bool)

Returns:

fname that includes date, timestamp and/or timezone connected by ‘_’ in one string e.g. yyyyMMdd_hhmm_timezone

Return type:

str

Examples

1) >>> get_time() ‘20231019_101758_CEST’

2) >>> get_time(incl_time=False) ‘20231019_CEST’

vuegen.utils.init_log(filename: str, display: bool = False, logger_id: str | None = None) Logger[source]#
  • Custom python logger configuration (basicConfig())

    with two handlers (for stdout and for file)

  • from: https://stackoverflow.com/a/44760039

  • Keeps a log record file of the python application, with option to

    display in stdout

Parameters:
  • (str) (- logger_id)

  • (bool) (- display)

  • (str) – if None then defaults to ‘root’

Returns:

The logger object

Return type:

logging.Logger

Examples

>>> logger = init_log('logs/tmp.log', display=True)
>>> logger.info('Loading things')
[2023-10-20 10:38:03,074] root: INFO - Loading things
vuegen.utils.is_pyvis_html(filepath: str) bool[source]#

Check if the provided HTML file is a Pyvis network visualization.

Parameters:

filepath (str) – The path to the HTML file to check.

Returns:

True if the input HTML file is a Pyvis network, meaning: - It contains a <div> element with id=”mynetwork”. - The <body> only contains <div> and <script> elements. Returns False otherwise.

Return type:

bool

vuegen.utils.is_url(filepath: Path) bool[source]#

Check if the provided path is a valid URL.

Parameters:

filepath (Path) – The filepath to check.

Returns:

True if the input path is a valid URL, meaning it contains both a scheme (e.g., http, https, ftp) and a network location (e.g., example.com). Returns False if either the scheme or the network location is missing or invalid.

Return type:

bool

vuegen.utils.load_yaml_config(file_path: str) dict[source]#

Load a YAML configuration file and return its contents as a dictionary.

Parameters:

file_path (str) – The path to the YAML configuration file.

Returns:

config – The contents of the YAML file as a dictionary.

Return type:

dict

Raises:
vuegen.utils.pyvishtml_to_networkx(html_file: str) Graph[source]#

Converts a PyVis HTML file to a NetworkX graph.

Parameters:

html_file (str) – Path to the PyVis HTML file.

Returns:

graph – NetworkX graph object reconstructed from the PyVis network data.

Return type:

nx.Graph

Raises:

ValueError – If the HTML file does not contain the expected network data, or if nodes lack ‘id’ attribute.

vuegen.utils.sort_imports(imp: Iterable[str]) tuple[list[str], list[str]][source]#

Separte ‘from’ and ‘import’ statements from setup code.

Parameters:

imp (Iterable[str]) – A list of import statements and setup statements.

Returns:

A tuple of two lists: one for import statements and one for setup statements.

Return type:

Tuple[List[str], List[str]]

Examples

>>> imp = [
...     'import logging',
...     'import shutil',
...     'logging.basicConfig(level=logging.INFO)',
...     'import pandas as pd',
...     'import numpy as np',
... ]
>>> sort_imports(imp)
(['import logging', 'import numpy as np', 'import pandas as pd', 'import shutil
], ['logging.basicConfig(level=logging.INFO)'])
vuegen.utils.write_yaml_config(yaml_data: dict, directory_path: Path) Path[source]#

Writes the generated YAML structure to a file.

Parameters:
  • yaml_data (dict) – The YAML data to write.

  • directory_path (Path) – The path where the YAML file should be saved.

Returns:

output_yaml – The path to the written YAML file.

Return type:

Path

Submodules#