cfd_util — Utilities#

This module provides colour handling, text wrapping, figure saving, and TOML-based style configuration loading.

Configuration#

pycohortflow.cfd_util.load_style_config(style='white', custom_config_path=None)[source]#

Load the TOML style configuration for the flow diagram.

The function reads one of the bundled style files shipped with the package and optionally deep-merges a user-provided TOML file on top. This lets users override only the keys they care about while inheriting sensible defaults for everything else.

Parameters:
  • style (str) – Name of the built-in style to use as the base. Currently available: "white" (no background colours, default), "colorful" (pastel gradient backgrounds), and "minimal" (white boxes, normal-weight headings, italic side text instead of exclusion boxes).

  • custom_config_path (str | os.PathLike | None) – Path to a custom TOML file. When None (the default), only the built-in style is used.

Returns:

Nested configuration dictionary with sections such as "figure", "layout", "box_geometry", "text", "lines", and "colors".

Return type:

dict

Raises:

ValueError – If style is not one of the recognised built-in style names.

Example

>>> cfg = load_style_config()
>>> cfg["figure"]["dpi"]
200
>>> cfg = load_style_config("colorful", "my_overrides.toml")

Colour Utilities#

pycohortflow.cfd_util.gradient_palette(start_hex, end_hex, n)[source]#

Generate n hex colours that blend linearly from start to end.

Parameters:
  • start_hex (str) – Starting colour (any Matplotlib colour spec).

  • end_hex (str) – Ending colour (any Matplotlib colour spec).

  • n (int) – Number of colours to generate.

Returns:

List of #RRGGBB hex colour strings.

Return type:

list[str]

Example

>>> gradient_palette("#000000", "#ffffff", 3)
['#000000', '#808080', '#ffffff']
pycohortflow.cfd_util.resolve_color(color_value, default_value, allow_named_colors=True)[source]#

Resolve and normalise a colour value to a #RRGGBB hex string.

The function first falls back to default_value when color_value is None, then validates the result against Matplotlib’s colour parser.

Parameters:
  • color_value (str | None) – User-supplied colour. None means “use the default”.

  • default_value (str) – Fallback colour when color_value is None.

  • allow_named_colors (bool) – If False, only hex strings (starting with #) are accepted; named colours such as "steelblue" raise ValueError.

Returns:

Normalised #RRGGBB hex colour string.

Return type:

str

Raises:

ValueError – If the resolved colour is invalid or if named colours are disallowed and a non-hex value is provided.

Example

>>> resolve_color(None, "#aabbcc")
'#aabbcc'
>>> resolve_color("red", "#000000")
'#ff0000'
pycohortflow.cfd_util.get_matplotlib_named_colors()[source]#

Return a sorted list of all Matplotlib named colour strings.

Useful for discovering valid colour names that can be used in the color or exclusion_color fields of cohort data dictionaries.

Returns:

Sorted colour names recognised by Matplotlib.

Return type:

list[str]

Example

>>> "steelblue" in get_matplotlib_named_colors()
True
pycohortflow.cfd_util.named_color(name)[source]#

Resolve a Matplotlib colour name or specification to a hex string.

Parameters:

name (str) – Any valid Matplotlib colour specification — e.g. "steelblue", "C0", "#aabbcc", or "tab:blue".

Returns:

A lowercase #RRGGBB hex string.

Return type:

str

Raises:

ValueError – If name is not a recognised colour specification.

Example

>>> named_color("white")
'#ffffff'

Figure I/O#

pycohortflow.cfd_util.save_figure(fig, save_dir, img_name, save_format, verbose=False)[source]#

Save a Matplotlib figure to disk in one or more formats.

The function creates save_dir if it does not already exist and writes the figure for every format listed in save_format.

Parameters:
  • fig (matplotlib.figure.Figure) – The figure object to save.

  • save_dir (str | os.PathLike | None) – Directory to write into. Defaults to the current working directory when None.

  • img_name (str) – Base file name without extension.

  • save_format (str | list[str]) – One format string (e.g. "png") or a list of format strings (e.g. ["png", "svg", "pdf"]).

  • verbose (bool) – When True, print a Saved: <path> line for every file written. Defaults to False (silent).

Returns:

None

Example

>>> save_figure(fig, "output", "my_chart", ["png", "svg"], verbose=True)
Saved: output/my_chart.png
Saved: output/my_chart.svg

Text Helpers#

pycohortflow.cfd_util.wrap_lines(text, width)[source]#

Wrap a string into a list of lines that fit within width characters.

Uses textwrap.wrap() with break_long_words=False so that words are never split mid-word.

Parameters:
  • text (str) – The input string to wrap.

  • width (int) – Maximum number of characters per line.

Returns:

Wrapped lines. Returns an empty list for blank input and a single-element list when the text cannot be broken.

Return type:

list[str]

Example

>>> wrap_lines("A rather long description text", width=15)
['A rather long', 'description', 'text']

Internal Helpers#

The following functions are used internally and are not part of the public API. They are documented here for contributors.

pycohortflow.cfd_util._hex_to_rgb(hex_color)[source]#

Convert a #RRGGBB (or #RRGGBBAA) hex string to an RGB tuple.

Parameters:

hex_color (str) – Hex colour string. An optional leading # and alpha channel are stripped automatically.

Returns:

(r, g, b) with each component in 0–255.

Return type:

tuple[int, int, int]

pycohortflow.cfd_util._rgb_to_hex(rgb)[source]#

Convert an (r, g, b) tuple (0–255 per channel) to #RRGGBB.

Parameters:

rgb (tuple[int, int, int]) – Red, green, blue channel values.

Returns:

Lowercase hex colour string.

Return type:

str

pycohortflow.cfd_util._interpolate_color(start_hex, end_hex, t)[source]#

Linearly interpolate between two hex colours.

Parameters:
  • start_hex (str) – Start colour in #RRGGBB format.

  • end_hex (str) – End colour in #RRGGBB format.

  • t (float) – Interpolation factor in [0, 1]. 0 returns start_hex, 1 returns end_hex.

Returns:

Interpolated colour as a #RRGGBB hex string.

Return type:

str

pycohortflow.cfd_util._recursive_update(default, override)[source]#

Recursively merge override into default, returning a new dict.

Nested dictionaries are merged key-by-key; all other value types in override simply replace those in default. The original default dictionary is not modified.

Parameters:
  • default (dict) – Base configuration dictionary (not modified).

  • override (dict) – Dictionary whose values take precedence.

Returns:

A new dictionary with merged values.

Return type:

dict