utils – Utilities

Utility modules for DifferentialLab.

exception utils.DifferentialLabError[source]

Bases: Exception

Base exception for all DifferentialLab errors.

Catch this to handle any application-defined error.

exception utils.EquationParseError[source]

Bases: DifferentialLabError

Raised when an ODE/difference/PDE expression cannot be parsed or evaluated.

exception utils.SolverFailedError[source]

Bases: DifferentialLabError

Raised when the numerical solver fails to converge or encounters an error.

exception utils.ValidationError[source]

Bases: DifferentialLabError

Raised when user input fails validation (domain, ICs, parameters, etc.).

utils.build_eval_namespace(params)[source]

Build the safe evaluation namespace combining SAFE_MATH and user params.

Return type:

dict[str, Any]

Parameters:

params (dict[str, float])

utils.export_csv_to_path(x, y, filepath, *, y_grid=None)[source]

Export solution data to CSV at the given path.

Parameters:
  • x (ndarray) – Independent variable values (1D) or x grid for 2D.

  • y (ndarray) – Solution values. For 2D PDE: shape (ny, nx).

  • filepath (Path) – Destination path.

  • y_grid (ndarray | None) – For 2D PDE, the y grid. If provided with 2D y, uses 2D CSV format.

Return type:

Path

Returns:

The path that was written.

utils.export_json_to_path(statistics, metadata, filepath)[source]

Export statistics and metadata to JSON at the given path.

Parameters:
  • statistics (dict[str, Any]) – Computed magnitudes/statistics.

  • metadata (dict[str, Any]) – Equation info, solver parameters, etc.

  • filepath (Path) – Destination path.

Return type:

Path

Returns:

The path that was written.

utils.get_logger(name)[source]

Return a child logger under the differential_lab namespace.

Parameters:

name (str) – Module name (typically __name__).

Return type:

Logger

Returns:

A logging.Logger instance.

utils.normalize_params(parameters)[source]

Return a mutable copy of parameters, or an empty dict if None.

Return type:

dict[str, float]

Parameters:

parameters (dict[str, float] | None)

utils.normalize_unicode_escapes(text)[source]

Replace \uXXXX escape sequences with their Unicode characters.

Allows users to enter expressions like \u03C9**2 * y[0] and have them treated equivalently to ω**2 * y[0].

Parameters:

text (str) – Input string that may contain Unicode escape sequences.

Return type:

str

Returns:

String with all \uXXXX sequences replaced by the corresponding Unicode character.

utils.safe_eval(compiled, namespace)[source]

Evaluate a compiled expression in a sandboxed namespace.

Return type:

Any

Parameters:
utils.validate_exclusive_args(arg_a, arg_b, name_a, name_b)[source]

Ensure exactly one of two mutually exclusive arguments is provided.

Raises:

ValueError – If both or neither argument is provided.

Return type:

None

Parameters:
utils.validate_expression_ast(expression, context='expression')[source]

Check that the expression contains only allowed AST nodes.

Parameters:
  • expression (str) – Python expression string to validate.

  • context (str) – Short description for error messages (e.g. “ODE expression”).

Raises:

EquationParseError – If the expression contains disallowed constructs.

Return type:

None

utils.is_update_available(current_version)[source]

Check if a newer version is available.

Parameters:

current_version (str) – Current application version.

Return type:

str | None

Returns:

The latest version string if newer, else None.

utils.perform_git_pull()[source]

Perform git pull in the project root.

Before pulling, stashes any local changes in input/ and output/ to prevent them from being overwritten. After the pull completes, the stashed changes are restored. Files in .env and other .gitignore entries are automatically protected by git.

Return type:

tuple[bool, str]

Returns:

Tuple of (success, message). Message is user-friendly.

utils.record_check_done()[source]

Record that an update check was performed (touch the file).

Updates the modification time of .last_update_check so the next check is deferred by UPDATE_CHECK_INTERVAL_DAYS.

Return type:

None

utils.should_run_check()[source]

Return True if we should run the update check (once per week).

Return type:

bool

Returns:

True if enough time has passed since last check, or no previous check.

utils.exceptions

Custom exception hierarchy for DifferentialLab.

All application-specific exceptions inherit from DifferentialLabError, enabling broad except DifferentialLabError handling when desired.

exception utils.exceptions.DifferentialLabError[source]

Bases: Exception

Base exception for all DifferentialLab errors.

Catch this to handle any application-defined error.

exception utils.exceptions.ValidationError[source]

Bases: DifferentialLabError

Raised when user input fails validation (domain, ICs, parameters, etc.).

exception utils.exceptions.EquationParseError[source]

Bases: DifferentialLabError

Raised when an ODE/difference/PDE expression cannot be parsed or evaluated.

exception utils.exceptions.SolverFailedError[source]

Bases: DifferentialLabError

Raised when the numerical solver fails to converge or encounters an error.

utils.expression_parser_shared

Shared constants and validation for safe expression parsing.

Used by solver.equation_parser and transforms.function_parser to avoid duplication of _SAFE_MATH, _ALLOWED_NODE_TYPES, and AST validation logic.

utils.expression_parser_shared.normalize_unicode_escapes(text)[source]

Replace \uXXXX escape sequences with their Unicode characters.

Allows users to enter expressions like \u03C9**2 * y[0] and have them treated equivalently to ω**2 * y[0].

Parameters:

text (str) – Input string that may contain Unicode escape sequences.

Return type:

str

Returns:

String with all \uXXXX sequences replaced by the corresponding Unicode character.

utils.expression_parser_shared.normalize_params(parameters)[source]

Return a mutable copy of parameters, or an empty dict if None.

Return type:

dict[str, float]

Parameters:

parameters (dict[str, float] | None)

utils.expression_parser_shared.build_eval_namespace(params)[source]

Build the safe evaluation namespace combining SAFE_MATH and user params.

Return type:

dict[str, Any]

Parameters:

params (dict[str, float])

utils.expression_parser_shared.safe_eval(compiled, namespace)[source]

Evaluate a compiled expression in a sandboxed namespace.

Return type:

Any

Parameters:
utils.expression_parser_shared.validate_exclusive_args(arg_a, arg_b, name_a, name_b)[source]

Ensure exactly one of two mutually exclusive arguments is provided.

Raises:

ValueError – If both or neither argument is provided.

Return type:

None

Parameters:
utils.expression_parser_shared.validate_expression_ast(expression, context='expression')[source]

Check that the expression contains only allowed AST nodes.

Parameters:
  • expression (str) – Python expression string to validate.

  • context (str) – Short description for error messages (e.g. “ODE expression”).

Raises:

EquationParseError – If the expression contains disallowed constructs.

Return type:

None

utils.export

Export utilities for CSV, JSON, and plot files.

utils.export.export_csv_to_path(x, y, filepath, *, y_grid=None)[source]

Export solution data to CSV at the given path.

Parameters:
  • x (ndarray) – Independent variable values (1D) or x grid for 2D.

  • y (ndarray) – Solution values. For 2D PDE: shape (ny, nx).

  • filepath (Path) – Destination path.

  • y_grid (ndarray | None) – For 2D PDE, the y grid. If provided with 2D y, uses 2D CSV format.

Return type:

Path

Returns:

The path that was written.

utils.export.export_json_to_path(statistics, metadata, filepath)[source]

Export statistics and metadata to JSON at the given path.

Parameters:
  • statistics (dict[str, Any]) – Computed magnitudes/statistics.

  • metadata (dict[str, Any]) – Equation info, solver parameters, etc.

  • filepath (Path) – Destination path.

Return type:

Path

Returns:

The path that was written.

utils.logger

Application logging setup.

Configures a hierarchical logger under the differential_lab namespace. Log level, file output, and console output are controlled via environment variables (LOG_LEVEL, LOG_FILE, LOG_CONSOLE).

utils.logger.get_logger(name)[source]

Return a child logger under the differential_lab namespace.

Parameters:

name (str) – Module name (typically __name__).

Return type:

Logger

Returns:

A logging.Logger instance.

utils.update_checker

Update checker for DifferentialLab.

Checks weekly if a newer version is available in the repository. If so, shows a dialog (when enabled via env) and can perform git pull without overwriting user data (input/, output/, .env, etc.).

utils.update_checker.should_run_check()[source]

Return True if we should run the update check (once per week).

Return type:

bool

Returns:

True if enough time has passed since last check, or no previous check.

utils.update_checker.record_check_done()[source]

Record that an update check was performed (touch the file).

Updates the modification time of .last_update_check so the next check is deferred by UPDATE_CHECK_INTERVAL_DAYS.

Return type:

None

utils.update_checker.is_update_available(current_version)[source]

Check if a newer version is available.

Parameters:

current_version (str) – Current application version.

Return type:

str | None

Returns:

The latest version string if newer, else None.

utils.update_checker.perform_git_pull()[source]

Perform git pull in the project root.

Before pulling, stashes any local changes in input/ and output/ to prevent them from being overwritten. After the pull completes, the stashed changes are restored. Files in .env and other .gitignore entries are automatically protected by git.

Return type:

tuple[bool, str]

Returns:

Tuple of (success, message). Message is user-friendly.