Skip to content

utils

Modules:

Name Description
enums

General-purpose enumerations shared across the library.

environment
logging

Project-wide logging utilities built on top of Rich.

matplotlib_config

Configure Matplotlib cache paths for restricted environments.

utils

Functions

Modules

enums

General-purpose enumerations shared across the library.

Classes:

Name Description
VerbosityEnum

Console output verbosity level.

Classes

VerbosityEnum

Console output verbosity level.

Controls how much information is printed during operations such as data loading, fitting, and saving.

Members

FULL Multi-line output with headers, tables, and details. SHORT Single-line status messages per action. SILENT No console output.

Methods:

Name Description
default

Return the default verbosity (FULL).

description

Return a human-readable description of this verbosity level.

Functions
default() classmethod

Return the default verbosity (FULL).

description()

Return a human-readable description of this verbosity level.

environment

Classes:

Name Description
FigureEmbedMode

How interactive figure HTML embeds its JavaScript runtime.

Functions:

Name Description
in_pytest

Determine whether the code is running inside a pytest session.

in_warp

Determine whether the terminal is the Warp terminal emulator.

in_pycharm

Check whether the current environment is PyCharm.

in_colab

Check whether the current environment is Google Colab.

in_jupyter

Return True when running inside a Jupyter Notebook.

in_github_ci

Return True when running under GitHub Actions CI.

resolve_artifact_path

Resolve a path against the configured artifact root.

create_artifact_temp_dir

Create a temporary directory under the artifact root when set.

resolve_figure_embed_mode

Resolve the active figure embedding mode from the environment.

is_ipython_display_handle

Return True if obj is an IPython DisplayHandle instance.

can_update_ipython_display

Return True if IPython HTML display utilities are available.

can_use_ipython_display

Return True if we can update the given IPython DisplayHandle.

Classes

FigureEmbedMode

How interactive figure HTML embeds its JavaScript runtime.

INLINE renders eagerly for live Jupyter; SHARED emits a lazy placeholder activated by a once-per-page shared runtime for the docs site; STANDALONE renders an eager self-contained fragment for reports, with runtime delivery decided by the caller's offline flag.

Functions

in_pytest()

Determine whether the code is running inside a pytest session.

Returns:

Type Description
bool

True if pytest is loaded, False otherwise.

in_warp()

Determine whether the terminal is the Warp terminal emulator.

Returns:

Type Description
bool

True if the TERM_PROGRAM environment variable equals 'WarpTerminal', False otherwise.

in_pycharm()

Check whether the current environment is PyCharm.

Returns:

Type Description
bool

True if running inside PyCharm, False otherwise.

in_colab()

Check whether the current environment is Google Colab.

Returns:

Type Description
bool

True if running in Google Colab, False otherwise.

in_jupyter()

Return True when running inside a Jupyter Notebook.

Returns:

Type Description
bool

True if inside a Jupyter Notebook, False otherwise.

in_github_ci()

Return True when running under GitHub Actions CI.

Returns:

Type Description
bool

True if env var GITHUB_ACTIONS is set, False otherwise.

resolve_artifact_path(path)

Resolve a path against the configured artifact root.

Parameters:

Name Type Description Default
path str | Path

Path to resolve.

required

Returns:

Type Description
Path

The original path when no artifact root is configured or when path is absolute. Otherwise, the absolute path under the configured artifact root.

create_artifact_temp_dir(prefix)

Create a temporary directory under the artifact root when set.

Parameters:

Name Type Description Default
prefix str

Prefix for the temporary directory name.

required

Returns:

Type Description
Path

Path to the created temporary directory.

resolve_figure_embed_mode()

Resolve the active figure embedding mode from the environment.

Reads EASYDIFFRACTION_FIGURE_EMBED_MODE. An unset or empty value resolves to :attr:FigureEmbedMode.INLINE. Any other value must name a supported mode; an unknown value raises ValueError so a typo in a docs or CI environment fails the build loudly instead of silently falling back to eager output.

Returns:

Type Description
FigureEmbedMode

The resolved embedding mode.

Raises:

Type Description
ValueError

If the variable is set to a non-empty value that is not a supported mode.

is_ipython_display_handle(obj)

Return True if obj is an IPython DisplayHandle instance.

Tries to import IPython.display.DisplayHandle and uses isinstance when available. Falls back to a conservative module name heuristic if IPython is missing. Any errors result in False.

can_update_ipython_display()

Return True if IPython HTML display utilities are available.

This indicates we can safely construct IPython.display.HTML and update a display handle.

can_use_ipython_display(handle)

Return True if we can update the given IPython DisplayHandle.

Combines type checking of the handle with availability of IPython HTML utilities.

logging

Project-wide logging utilities built on top of Rich.

Provides a shared Rich console, a compact/verbose logger with consistent formatting, Jupyter traceback handling, and a small printing façade tailored to the configured console.

Classes:

Name Description
IconifiedRichHandler

RichHandler using icons (compact) or names (verbose).

ConsoleManager

Central provider for shared Rich Console instance.

LoggerConfig

Facade for logger configuration, delegates to helpers.

ExceptionHookManager

Handles installation and restoration of exception hooks.

Logger

Centralized logging with Rich formatting and two modes.

ConsolePrinter

Printer utility for the shared console with left padding.

Classes

IconifiedRichHandler(*args, mode='compact', **kwargs)

RichHandler using icons (compact) or names (verbose).

Methods:

Name Description
get_level_text

Return an icon or level name for the log record.

render_message

Render the log message body as a Rich Text object.

Functions
get_level_text(record)

Return an icon or level name for the log record.

Parameters:

Name Type Description Default
record logging.LogRecord

The log record being rendered.

required

Returns:

Type Description
Text

A Rich Text object with the level indicator.

render_message(record, message)

Render the log message body as a Rich Text object.

Parameters:

Name Type Description Default
record logging.LogRecord

The log record being rendered.

required
message str

Pre-formatted log message string.

required

Returns:

Type Description
Text

A Rich Text object with the rendered message.

ConsoleManager

Central provider for shared Rich Console instance.

Methods:

Name Description
get

Return a shared Rich Console instance.

Functions
get() classmethod

Return a shared Rich Console instance.

LoggerConfig

Facade for logger configuration, delegates to helpers.

Methods:

Name Description
setup_handlers

Install Rich handler and optional Jupyter traceback support.

configure

Configure the logger with RichHandler and exception hooks.

Functions
setup_handlers(logger, *, level, rich_tracebacks, mode='compact') staticmethod

Install Rich handler and optional Jupyter traceback support.

Parameters:

Name Type Description Default
logger logging.Logger

Logger instance to attach handlers to.

required
level int

Minimum log level to emit.

required
rich_tracebacks bool

Whether to enable Rich tracebacks.

required
mode str

Output mode name ("compact" or "verbose").

'compact'
configure(logger, *, mode, level, rich_tracebacks) staticmethod

Configure the logger with RichHandler and exception hooks.

Parameters:

Name Type Description Default
logger logging.Logger

Logger instance to configure.

required
mode Logger.Mode

Output mode (compact or verbose).

required
level Logger.Level

Minimum log level to emit.

required
rich_tracebacks bool

Whether to enable Rich tracebacks.

required
ExceptionHookManager

Handles installation and restoration of exception hooks.

Methods:

Name Description
install_verbose_hook

Install a verbose exception hook that prints rich tracebacks.

install_compact_hook

Install a compact exception hook that logs message-only.

restore_original_hook

Restore the original sys.excepthook if it was overridden.

install_jupyter_traceback_suppressor

Install a Jupyter/IPython exception handler for tracebacks.

Functions
install_verbose_hook(logger) staticmethod

Install a verbose exception hook that prints rich tracebacks.

Parameters:

Name Type Description Default
logger logging.Logger

Logger used to emit the exception information.

required
install_compact_hook(logger) staticmethod

Install a compact exception hook that logs message-only.

Parameters:

Name Type Description Default
logger logging.Logger

Logger used to emit the error message.

required
restore_original_hook() staticmethod

Restore the original sys.excepthook if it was overridden.

install_jupyter_traceback_suppressor(logger) staticmethod

Install a Jupyter/IPython exception handler for tracebacks.

Parameters:

Name Type Description Default
logger logging.Logger

Logger used to emit error messages.

required
Logger

Centralized logging with Rich formatting and two modes.

Environment variables: ED_LOG_MODE: set default mode ('verbose' or 'compact') ED_LOG_LEVEL: set default level ('DEBUG', 'INFO', etc.)

Classes:

Name Description
Mode

Output modes (see :class:Logger).

Level

Mirror stdlib logging levels.

Reaction

Reaction to errors (see :class:Logger).

Methods:

Name Description
configure

Configure logger.

set_mode

Set the output mode and reconfigure the logger.

set_level

Set the minimum log level and reconfigure the logger.

mode

Return the currently active output mode.

handle

Route a log message (see class docs for policy).

debug

Log one or more messages at DEBUG level.

info

Log one or more messages at INFO level.

warning

Log one or more messages at WARNING level.

error

Log one or more messages at ERROR level.

critical

Log one or more messages at CRITICAL level.

Classes
Mode

Output modes (see :class:Logger).

Methods:

Name Description
default

Return the default output mode (compact).

Functions
default() classmethod

Return the default output mode (compact).

Level

Mirror stdlib logging levels.

Methods:

Name Description
default

Return the default log level (WARNING).

Functions
default() classmethod

Return the default log level (WARNING).

Reaction

Reaction to errors (see :class:Logger).

Methods:

Name Description
default

Return the default error reaction (RAISE).

Functions
default() classmethod

Return the default error reaction (RAISE).

Functions
configure(*, mode=None, level=None, reaction=None, rich_tracebacks=None) classmethod

Configure logger.

mode: default COMPACT in Jupyter else VERBOSE level: minimum log level rich_tracebacks: override automatic choice

Environment variables: ED_LOG_MODE: set default mode ('verbose' or 'compact') ED_LOG_LEVEL: set default level ('DEBUG', 'INFO', etc.)

set_mode(mode) classmethod

Set the output mode and reconfigure the logger.

Parameters:

Name Type Description Default
mode Mode

The desired output mode (VERBOSE or COMPACT).

required
set_level(level) classmethod

Set the minimum log level and reconfigure the logger.

Parameters:

Name Type Description Default
level Level

The desired minimum log level.

required
mode() classmethod

Return the currently active output mode.

Returns:

Type Description
Mode

The current Logger.Mode value.

handle(*messages, level=Level.ERROR, exc_type=AttributeError) classmethod

Route a log message (see class docs for policy).

debug(*messages) classmethod

Log one or more messages at DEBUG level.

Parameters:

Name Type Description Default
*messages str

Message parts joined with a space before logging.

()
info(*messages) classmethod

Log one or more messages at INFO level.

Parameters:

Name Type Description Default
*messages str

Message parts joined with a space before logging.

()
warning(*messages, exc_type=None) classmethod

Log one or more messages at WARNING level.

Parameters:

Name Type Description Default
*messages str

Message parts joined with a space before logging.

()
exc_type type[BaseException] | None

If provided, raise this exception type instead of logging.

None
error(*messages, exc_type=AttributeError) classmethod

Log one or more messages at ERROR level.

Parameters:

Name Type Description Default
*messages str

Message parts joined with a space before logging.

()
exc_type type[BaseException]

Exception type to raise in VERBOSE/COMPACT mode.

AttributeError
critical(*messages, exc_type=RuntimeError) classmethod

Log one or more messages at CRITICAL level.

Parameters:

Name Type Description Default
*messages str

Message parts joined with a space before logging.

()
exc_type type[BaseException]

Exception type to raise in VERBOSE/COMPACT mode.

RuntimeError
ConsolePrinter

Printer utility for the shared console with left padding.

Methods:

Name Description
print

Print objects to the console with left padding.

paragraph

Print a bold blue paragraph heading.

section

Format a section header with bold green text.

small

Print one or more lines as dim, smaller supplementary text.

chapter

Format a chapter header in bold magenta, uppercase.

Functions
print(*objects, **kwargs) classmethod

Print objects to the console with left padding.

  • Renderables (Rich types like Text, Table, Panel, etc.) are kept as-is. - Non-renderables (ints, floats, Path, etc.) are converted to str().
paragraph(title) classmethod

Print a bold blue paragraph heading.

Parameters:

Name Type Description Default
title str

Heading text; substrings enclosed in single quotes are rendered without the bold deep_sky_blue3 style.

required
section(title) classmethod

Format a section header with bold green text.

small(*lines) classmethod

Print one or more lines as dim, smaller supplementary text.

Intended for table footnote glossaries and inline warning notes that should read as subordinate to the table or block they sit beneath. In Jupyter the lines render inside a single <small>-style HTML element so the font size matches Jupyter's .dataframe table-cell text. In a terminal the lines render with Rich's dim style. Rich [red]…[/red] markup inside lines is preserved in both renderers.

Parameters:

Name Type Description Default
*lines str

Pre-formatted display lines. Each may contain Rich [red]…[/red] markup; other Rich markup is rendered in the terminal and stripped in the HTML output.

()
chapter(title) classmethod

Format a chapter header in bold magenta, uppercase.

Functions

matplotlib_config

Configure Matplotlib cache paths for restricted environments.

Functions:

Name Description
ensure_matplotlib_config_dir

Set a stable Matplotlib cache dir.

Functions

ensure_matplotlib_config_dir()

Set a stable Matplotlib cache dir.

utils

Functions:

Name Description
display_path

Format a filesystem path for user-facing display.

print_metrics_table

Render a two-column Metric | Value table.

print_table_footnote

Print a glossary block below a fit-results-style table.

format_bulleted_warning

Format a warning as a header followed by indented bullets.

download_data

Download a dataset by numeric ID using the remote diffraction index.

list_data

Display a table of available example data records.

package_version

Get the installed version string of the specified package.

stripped_package_version

Get installed package version, stripped of local version parts.

list_tutorials

Display a table of available tutorial notebooks.

download_tutorial

Download a tutorial notebook by numeric ID.

download_all_tutorials

Download all available tutorial notebooks.

show_version

Print the installed version of the easydiffraction package.

render_table

Render tabular data to the active display backend.

build_table_renderable

Build a table renderable for the active display backend.

render_object_help

Print public properties and methods for a plain helper object.

render_cif

Display CIF text as a formatted table in Jupyter or terminal.

tof_to_d

Convert time-of-flight to d-spacing using quadratic calibration.

twotheta_to_d

Convert 2-theta to d-spacing using Bragg's law.

sin_theta_over_lambda_to_d_spacing

Convert sin(theta)/lambda to d-spacing.

str_to_ufloat

Parse a CIF-style numeric string into a ufloat.

Classes

Functions

display_path(path)

Format a filesystem path for user-facing display.

Returns the path relative to the current working directory so messages stay compact and avoid forced line breaks. Paths outside the cwd subtree use .. segments to walk up to a common ancestor (e.g. ../sibling/data.cif) rather than falling back to an absolute path. The absolute path is only used when no relative form is possible — on Windows that happens when the path is on a different drive from the cwd.

Parameters:

Name Type Description Default
path pathlib.Path | str

Filesystem path to format.

required

Returns:

Type Description
str

Display string suitable for inline use in console messages.

print_metrics_table(rows)

Render a two-column Metric | Value table.

Used for fit-results, settings, and similar summary blocks where each row is one labelled scalar. Skips rendering entirely when rows is empty.

Parameters:

Name Type Description Default
rows list[list[str]]

Each inner list is [label, value_string].

required
print_table_footnote(entries)

Print a glossary block below a fit-results-style table.

Each entry renders as a left-aligned • header = description bullet line. The block uses :meth:ConsolePrinter.small so it shows as dim, smaller supplementary text — in Jupyter the font size matches the table-cell text.

Parameters:

Name Type Description Default
entries list[tuple[str, str]]

Each tuple is (column header, one-line description).

required
format_bulleted_warning(header, items)

Format a warning as a header followed by indented bullets.

Parameters:

Name Type Description Default
header str

First warning line. Use a trailing colon when bullets follow.

required
items list[str]

Bullet line bodies.

required

Returns:

Type Description
str

Multiline warning text.

download_data(id, destination='data', *, overwrite=False)

Download a dataset by numeric ID using the remote diffraction index.

Example: path = download_data(id=12, destination="data")

Parameters:

Name Type Description Default
id int | str

Numeric dataset id (e.g. 12).

required
destination str

Directory to save the downloaded file or extracted project into (created if missing). Relative destinations are resolved against the configured artifact root when EASYDIFFRACTION_ARTIFACT_ROOT is set.

'data'
overwrite bool

Whether to overwrite the file if it already exists.

False

Returns:

Type Description
str

Full path to the downloaded file, or to the extracted project directory for project ZIP archives, as string.

Raises:

Type Description
KeyError

If the id is not found in the index.

list_data()

Display a table of available example data records.

package_version(package_name)

Get the installed version string of the specified package.

Parameters:

Name Type Description Default
package_name str

The name of the package to query.

required

Returns:

Type Description
str | None

The raw version string (may include local part, e.g., '1.2.3+abc123'), or None if the package is not installed.

stripped_package_version(package_name)

Get installed package version, stripped of local version parts.

Returns only the public version segment (e.g., '1.2.3' or '1.2.3.post4'), omitting any local segment (e.g., '+d136').

Parameters:

Name Type Description Default
package_name str

The name of the package to query.

required

Returns:

Type Description
str | None

The public version string, or None if the package is not installed.

list_tutorials()

Display a table of available tutorial notebooks.

In the terminal each row shows the tutorial ID, filename, and a combined entry with the title on the first line and a dimmed description on the second. In Jupyter the table shows the plain title only, since the HTML backend cannot render the terminal styling.

download_tutorial(id, destination='tutorials', *, overwrite=False)

Download a tutorial notebook by numeric ID.

Example: path = download_tutorial(id=1, destination="tutorials")

Parameters:

Name Type Description Default
id int | str

Numeric tutorial id (e.g. 1).

required
destination str

Directory to save the file into (created if missing). Relative destinations are resolved against the configured artifact root when EASYDIFFRACTION_ARTIFACT_ROOT is set.

'tutorials'
overwrite bool

Whether to overwrite the file if it already exists.

False

Returns:

Type Description
str

Full path to the downloaded file as string.

Raises:

Type Description
KeyError

If the id is not found in the index.

download_all_tutorials(destination='tutorials', *, overwrite=False)

Download all available tutorial notebooks.

Example: paths = download_all_tutorials(destination="tutorials")

Parameters:

Name Type Description Default
destination str

Directory to save the files into (created if missing). Relative destinations are resolved against the configured artifact root when EASYDIFFRACTION_ARTIFACT_ROOT is set.

'tutorials'
overwrite bool

Whether to overwrite files if they already exist.

False

Returns:

Type Description
list[str]

List of full paths to the downloaded files.

show_version()

Print the installed version of the easydiffraction package.

render_table(columns_data, columns_alignment, columns_headers=None, display_handle=None, width=None)

Render tabular data to the active display backend.

Parameters:

Name Type Description Default
columns_data object

A list of rows, where each row is a list of cell values.

required
columns_alignment object

A list of alignment strings (e.g. 'left', 'right', 'center') matching the number of columns.

required
columns_headers object

Optional list of column header strings.

None
display_handle object

Optional display handle for in-place updates (e.g. in Jupyter or a terminal Live context).

None
width int | None

Optional target table width. Honored by fixed-width backends (Rich); ignored by reflowing ones (HTML).

None
build_table_renderable(columns_data, columns_alignment, columns_headers=None)

Build a table renderable for the active display backend.

Parameters:

Name Type Description Default
columns_data object

A list of rows, where each row is a list of cell values.

required
columns_alignment object

A list of alignment strings (e.g. 'left', 'right', 'center') matching the number of columns.

required
columns_headers object

Optional list of column header strings.

None

Returns:

Type Description
object

Backend-native renderable, such as a Rich table or HTML.

render_object_help(obj)

Print public properties and methods for a plain helper object.

Parameters:

Name Type Description Default
obj object

Object whose public API should be summarized.

required
render_cif(cif_text)

Display CIF text as a formatted table in Jupyter or terminal.

Parameters:

Name Type Description Default
cif_text str

The CIF text to display.

required
tof_to_d(tof, offset, linear, quad, quad_eps=1e-20)

Convert time-of-flight to d-spacing using quadratic calibration.

Model: TOF = offset + linear * d + quad * d²

The function: - Uses a linear fallback when the quadratic term is effectively zero. - Solves the quadratic for d and selects the smallest positive, finite root. - Returns NaN where no valid solution exists. - Expects tof as a NumPy array; output matches its shape.

Parameters:

Name Type Description Default
tof np.ndarray

Time-of-flight values (μs). Must be a NumPy array.

required
offset float

Calibration offset (μs).

required
linear float

Linear calibration coefficient (μs/Å).

required
quad float

Quadratic calibration coefficient (μs/Ų).

required
quad_eps float

Threshold to treat quad as zero.

1e-20

Returns:

Type Description
np.ndarray

d-spacing values (Å), NaN where invalid.

Raises:

Type Description
TypeError

If tof is not a NumPy array or coefficients are not real numbers.

twotheta_to_d(twotheta, wavelength)

Convert 2-theta to d-spacing using Bragg's law.

Parameters:

Name Type Description Default
twotheta object

2-theta angle in degrees (float or np.ndarray).

required
wavelength float

Wavelength in Å.

required

Returns:

Type Description
object

d-spacing in Å (float or np.ndarray).

sin_theta_over_lambda_to_d_spacing(sin_theta_over_lambda)

Convert sin(theta)/lambda to d-spacing.

Parameters:

Name Type Description Default
sin_theta_over_lambda object

sin(theta)/lambda in 1/Å (float or np.ndarray).

required

Returns:

Type Description
object

d-spacing in Å (float or np.ndarray).

str_to_ufloat(s, default=None)

Parse a CIF-style numeric string into a ufloat.

Examples of supported input: - "3.566" → ufloat(3.566, nan) - "3.566(2)" → ufloat(3.566, 0.002) - "3.566()" → ufloat(3.566, nan) - None → ufloat(default, nan)

Behavior: - If the input string contains a value with parentheses (e.g. "3.566(2)"), the number in parentheses is interpreted as an estimated standard deviation (esd) in the last digit(s). - Empty parentheses (e.g. "3.566()") are treated as "no esd provided". - If the input string has no parentheses, an uncertainty of NaN is assigned to indicate "no esd provided". - If parsing fails, the function falls back to the given default value with uncertainty NaN.

Parameters:

Name Type Description Default
s str | None

Numeric string in CIF format (e.g. "3.566", "3.566(2)", "3.566()") or None.

required
default float | None

Default value to use if s is None or parsing fails.

None

Returns:

Type Description
UFloat

An uncertainties.UFloat object with the parsed value and uncertainty. The uncertainty will be NaN if not specified or parsing failed.