Utils Module¶
Utility functions and helpers.
Helpers¶
helpers
¶
create_dir
¶
Ensure that a directory exists, creating it if necessary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
The directory path to check and/or create. |
required |
Examples:
Source code in src/cofolder/modules/utils/helpers.py
parse_list_as_str
¶
parse_list_as_str(
list_as_str: str,
separator: str = ",",
item_type=str,
expected_length: int = None,
)
Convert a separated string into a typed Python list.
Parses a command-line string value containing delimited items and converts each item to the specified type. Useful for parsing CLI arguments like device lists, seeds, or other numeric sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
list_as_str
|
str
|
The raw string containing a list (e.g., "1,2,3"). |
required |
separator
|
str
|
Delimiter used to separate items in the string. |
","
|
item_type
|
type
|
The expected type of each element (str, int, float, etc.). |
str
|
expected_length
|
int
|
If provided, the parsed list must match this exact length. |
None
|
Returns:
| Type | Description |
|---|---|
list
|
The processed and type-casted list. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If type conversion fails or if the parsed list length doesn't match expected_length. |
Examples:
Source code in src/cofolder/modules/utils/helpers.py
resolve_seed_plan
¶
resolve_seed_plan(
repeats: int,
requested_base_seed: int | None = None,
logger: Logger | None = None,
) -> SeedPlan
Resolve one validated base seed and deterministic, distinct repeat seeds.
Source code in src/cofolder/modules/utils/helpers.py
get_seeds
¶
get_seeds(
repeats: int, seed: Optional[int] = None, logger: Optional[Logger] = None
) -> tuple[int, List[int]]
Generate a global seed and run seeds for repeated workflow runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repeats
|
int
|
Number of repeats for which seeds should be generated. |
required |
seed
|
int
|
Global seed to use. If None, a random global seed is generated. |
None
|
logger
|
Logger
|
Logger for informational/debug messages. If None, logging is skipped. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
global_seed |
int
|
The global seed used for generating run seeds. |
run_seeds |
list of int
|
List of seeds for each run (length == repeats). |
Notes
- If repeats == 1, the run seed list contains only the global seed.
- If repeats > 1, run seeds are generated deterministically from the global seed.
Source code in src/cofolder/modules/utils/helpers.py
generate_seeds
¶
Generate a list of random integer seeds for reproducibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_seeds
|
int
|
Number of seeds to generate (must be >= 1). |
required |
seed
|
int or None
|
Optional global seed for reproducibility. If None, a random global seed is generated. |
None
|
Returns:
| Type | Description |
|---|---|
List[int]
|
List of generated seeds. |
Source code in src/cofolder/modules/utils/helpers.py
drop_and_log_nans
¶
Drop rows with NaN values and log the number of rows removed.
Removes rows containing NaN values in any of the specified columns and logs the count of removed rows for debugging and quality control.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame to process. |
required |
cols
|
list of str
|
Column names to check for NaN values. |
required |
context
|
str
|
Optional context string to include in the log message for clarity. |
""
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame with rows containing NaN in specified columns removed. |
Examples:
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({'a': [1, 2, np.nan], 'b': [4, np.nan, 6]})
>>> drop_and_log_nans(df, ['a', 'b'], context="correlation analysis")
a b
0 1.0 4.0
Source code in src/cofolder/modules/utils/helpers.py
Logging¶
log
¶
Logging configuration utilities for cofolder.
This module provides utilities for setting up consistent logging across the cofolder package, including formatters and handlers for both console and file output.
CONCISE_FORMAT
module-attribute
¶
str: Concise format used for normal console progress.
DEFAULT_FORMAT
module-attribute
¶
DEFAULT_FORMAT = "%(asctime)s | %(levelname)-8s | %(filename)s:%(lineno)d | %(funcName)s | %(message)s"
str: Default log format for all cofolder loggers.
Format includes timestamp, log level, logger name, file location, function name, and the actual message, separated by pipes for readability.
Example output: 2025-01-15 10:30:45,123 | INFO | cofolder.validate | validate.py:42 | run | Starting validation
setup_root_logger
¶
Configure the root logger with console and optional file handlers.
Sets up the root logger with a standardized format for consistent logging across the entire application. Repeated calls update the root log level and ensure the requested console/file handlers exist without duplicating them. Only handlers created by COFOLDER are updated; unrelated application handlers remain untouched.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int
|
The logging level to set for the root logger. Common values: - logging.DEBUG (10): Detailed information for debugging - logging.INFO (20): General informational messages - logging.WARNING (30): Warning messages - logging.ERROR (40): Error messages - logging.CRITICAL (50): Critical errors |
logging.INFO
|
log_file
|
str or Path
|
If provided, adds a FileHandler that writes logs to this path. The directory must exist or be creatable. |
None
|
Returns:
| Type | Description |
|---|---|
None
|
|
See Also
DEFAULT_FORMAT : The standard log format used by all handlers