nlsq.cli

Command-line interface for YAML-based curve fitting workflows.

Added in version 0.4.1.

The CLI module provides commands for executing curve fitting workflows defined in YAML configuration files, enabling reproducible and scriptable fitting pipelines.

Quick Start

# Launch Qt desktop GUI
nlsq gui

# Run a single workflow
nlsq fit experiment.yaml

# Output results to stdout for piping
nlsq fit experiment.yaml --stdout

# Batch process multiple workflows
nlsq batch configs/*.yaml --summary results.json

# Show system information
nlsq info

# Copy configuration templates
nlsq config

Commands

nlsq gui

Launch the interactive Qt desktop GUI for visual curve fitting. Provides a 5-page workflow: Data Loading → Model Selection → Fitting Options → Results → Export.

nlsq fit

Execute a single curve fitting workflow from YAML configuration. Options: -o/--output to override results path, --stdout for JSON output.

nlsq batch

Run multiple workflows in parallel with aggregate summary reporting. Options: -w/--workers for parallelism, -s/--summary for output path.

nlsq info

Display system information including NLSQ version, JAX backend, and available builtin models.

nlsq config

Generate configuration templates for new workflows. Options: --workflow, --model, -o/--output, -f/--force.

See Also

Module Structure

nlsq.cli.main

CLI entry point for NLSQ workflow commands.

This module provides the main command-line interface for NLSQ, supporting: - nlsq gui - Launch the interactive Qt desktop GUI - nlsq fit workflow.yaml - Execute single curve fit from YAML config - nlsq batch w1.yaml w2.yaml … - Execute parallel batch fitting - nlsq info - Display system and environment information - nlsq config - Copy configuration templates to current directory

Example Usage

From command line:

$ nlsq gui
$ nlsq fit workflow.yaml
$ nlsq fit workflow.yaml --output results.json
$ nlsq fit workflow.yaml --stdout
$ nlsq batch configs/\*.yaml --workers 4
$ nlsq info
$ nlsq config
$ nlsq config --workflow
$ nlsq config --model -o my_model.py
$ nlsq --version
$ nlsq --verbose fit workflow.yaml
nlsq.cli.main.create_parser()[source]

Create the argument parser with subcommands.

Returns:

Configured argument parser with fit, batch, gui, and info subcommands.

Return type:

argparse.ArgumentParser

nlsq.cli.main.handle_gui(args)[source]

Handle the ‘gui’ subcommand.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Returns:

Exit code (0 for success, non-zero for failure).

Return type:

int

nlsq.cli.main.handle_fit(args)[source]

Handle the ‘fit’ subcommand.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Returns:

Exit code (0 for success, non-zero for failure).

Return type:

int

nlsq.cli.main.handle_batch(args)[source]

Handle the ‘batch’ subcommand.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Returns:

Exit code (0 for success, non-zero for failure).

Return type:

int

nlsq.cli.main.handle_info(args)[source]

Handle the ‘info’ subcommand.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Returns:

Exit code (always 0 for info command).

Return type:

int

nlsq.cli.main.handle_config(args)[source]

Handle the ‘config’ subcommand.

Parameters:

args (argparse.Namespace) – Parsed command-line arguments.

Returns:

Exit code (0 for success, non-zero for failure).

Return type:

int

nlsq.cli.main.main(argv=None)[source]

Main entry point for the NLSQ CLI.

Parameters:

argv (list[str], optional) – Command-line arguments. If None, uses sys.argv.

Returns:

Exit code (0 for success, non-zero for failure).

Return type:

int

Examples

>>> main(["gui"])
0
>>> main(["fit", "workflow.yaml"])
0
>>> main(["info"])
0

nlsq.cli.workflow_runner

Workflow runner module for NLSQ CLI.

This module provides the WorkflowRunner class that orchestrates the complete curve fitting workflow: data loading, model resolution, parameter extraction, fitting execution, and result export.

Example Usage

>>> from nlsq.cli.workflow_runner import WorkflowRunner
>>>
>>> config = {
...     "data": {"input_file": "data.txt", "format": "ascii"},
...     "model": {"type": "builtin", "name": "exponential_decay"},
...     "fitting": {"p0": "auto", "method": "trf"},
...     "export": {"results_file": "results.json", "format": "json"},
... }
>>> runner = WorkflowRunner()
>>> result = runner.run(config)
>>> print(result["popt"])
class nlsq.cli.workflow_runner.WorkflowRunner[source]

Bases: object

Runner for curve fitting workflows.

Orchestrates the complete workflow execution: 1. Load data using DataLoader 2. Resolve model using ModelRegistry 3. Extract fitting parameters from config 4. Execute curve fit using nlsq.curve_fit() 5. Export results using ResultExporter

data_loader

Instance of DataLoader for data file loading.

Type:

DataLoader

model_registry

Instance of ModelRegistry for model resolution.

Type:

ModelRegistry

result_exporter

Instance of ResultExporter for result export.

Type:

ResultExporter

run(config)[source]

Execute complete workflow and return result dict.

Examples

>>> runner = WorkflowRunner()
>>> config = {
...     "data": {"input_file": "data.txt", "format": "ascii"},
...     "model": {"type": "builtin", "name": "linear"},
...     "fitting": {"p0": [1.0, 0.0]},
...     "export": {"results_file": "results.json"},
... }
>>> result = runner.run(config)
>>> print(f"Fitted parameters: {result['popt']}")
__init__()[source]

Initialize WorkflowRunner with component instances.

run(config)[source]

Execute complete curve fitting workflow.

Parameters:

config (dict) – Workflow configuration dictionary containing: - data: Data loading configuration - model: Model configuration - fitting: Fitting parameters (p0, bounds, method, etc.) - export: Export configuration (optional) - metadata: Workflow metadata (optional) - validation: Data validation settings (optional)

Returns:

Fit result dictionary containing: - popt: Fitted parameters (list) - pcov: Covariance matrix (list of lists) - success: bool indicating fit success - message: Convergence message - nfev: Number of function evaluations - Additional statistics and metadata

Return type:

dict

Raises:

nlsq.cli.data_loaders

Data loading module for NLSQ CLI.

This module provides a DataLoader class for loading data from multiple formats: - ASCII text files (.txt, .dat, .asc) - CSV files (.csv) - NumPy compressed archives (.npz) - HDF5 files (.h5, .hdf5)

The module supports: - Automatic format detection from file extension - Configurable column/key selection - Optional sigma/uncertainty loading - Data validation (NaN/Inf rejection, minimum points) - Both 1D (x, y, sigma) and 2D/3D surface (x, y, z, sigma) data

Example Usage

1D Data (curve fitting): >>> from nlsq.cli.data_loaders import DataLoader >>> loader = DataLoader() >>> config = { … “format”: “auto”, … “columns”: {“x”: 0, “y”: 1, “sigma”: 2}, … “ascii”: {“comment_char”: “#”}, … } >>> xdata, ydata, sigma = loader.load(“data.txt”, config)

2D Data (surface fitting): >>> config = { … “format”: “auto”, … “columns”: {“x”: 0, “y”: 1, “z”: 2, “sigma”: 3}, # z present = 2D mode … } >>> xdata, ydata, sigma = loader.load(“surface.txt”, config) >>> # xdata shape: (2, n_points) - stacked x, y coordinates >>> # ydata shape: (n_points,) - z values (dependent variable)

class nlsq.cli.data_loaders.DataLoader[source]

Bases: object

Data loader supporting multiple file formats and data dimensions.

Loads data from ASCII, CSV, NPZ, and HDF5 formats with automatic format detection and configurable column/key selection. Supports both 1D curve fitting data (x, y, sigma) and 2D surface fitting data (x, y, z, sigma).

Data Modes

1D Mode (default):
  • Columns: x, y, sigma (optional)

  • xdata: 1D array of shape (n_points,)

  • ydata: 1D array of shape (n_points,)

  • Model signature: f(x, *params)

2D Mode (when z column is specified):
  • Columns: x, y, z, sigma (optional)

  • xdata: 2D array of shape (2, n_points) where xdata[0]=x, xdata[1]=y

  • ydata: 1D array of shape (n_points,) containing z values

  • Model signature: f(xy, *params) where xy[0]=x, xy[1]=y

load(file_path, config)[source]

Load data from file and return (xdata, ydata, sigma) tuple.

detect_format(file_path, config)[source]

Detect file format from extension or config.

is_2d_data(config)[source]

Check if configuration specifies 2D surface data.

Examples

1D data (curve fitting): >>> loader = DataLoader() >>> config = { … “format”: “csv”, … “columns”: {“x”: “time”, “y”: “signal”, “sigma”: None}, … “csv”: {“header”: True, “delimiter”: “,”}, … } >>> x, y, sigma = loader.load(“experiment.csv”, config)

2D data (surface fitting): >>> config = { … “format”: “csv”, … “columns”: {“x”: “pos_x”, “y”: “pos_y”, “z”: “intensity”, “sigma”: “error”}, … } >>> xy, z, sigma = loader.load(“surface.csv”, config) >>> # xy.shape = (2, n_points), z.shape = (n_points,)

is_2d_data(config)[source]

Check if configuration specifies 2D surface data.

2D mode is enabled when a ‘z’ column/key is specified in the configuration. In 2D mode, x and y are independent variables (coordinates) and z is the dependent variable.

Parameters:

config (dict) – Configuration dictionary.

Returns:

True if 2D surface data mode, False for 1D curve data.

Return type:

bool

load(file_path, config)[source]

Load data from file.

Parameters:
  • file_path (str or Path) – Path to the data file.

  • config (dict) – Configuration dictionary containing format-specific options. Required keys depend on format: - All formats: “format” (or “auto” for detection) - ASCII/CSV: “columns” dict with “x”, “y”, “z” (optional), “sigma” keys - NPZ: “npz” dict with “x_key”, “y_key”, “z_key” (optional), “sigma_key” - HDF5: “hdf5” dict with “x_path”, “y_path”, “z_path” (optional), “sigma_path”

Returns:

For 1D data: (xdata, ydata, sigma) where xdata/ydata are 1D arrays. For 2D data: (xdata, ydata, sigma) where xdata is shape (2, n_points) with xdata[0]=x, xdata[1]=y and ydata is shape (n_points,) containing z values. sigma may be None if not provided.

Return type:

tuple[ndarray, ndarray, ndarray | None]

Raises:

DataLoadError – If file cannot be loaded or data is invalid.

detect_format(file_path, config)[source]

Detect file format from extension or config.

Parameters:
  • file_path (Path) – Path to the data file.

  • config (dict) – Configuration dictionary with optional “format” key.

Returns:

Detected format string (“ascii”, “csv”, “npz”, “hdf5”).

Return type:

str

Raises:

DataLoadError – If format cannot be determined.

nlsq.cli.model_registry

Model registry for NLSQ CLI.

This module provides model function resolution for curve fitting workflows: - Builtin models from nlsq.functions module - Custom models loaded from external Python files - Polynomial models generated by degree

The ModelRegistry class handles discovery, loading, and validation of model functions for use in curve fitting workflows.

Security Features

Custom models are validated before loading to prevent arbitrary code execution: - AST-based pattern detection for dangerous operations - Path traversal prevention - Resource limits (timeout, memory) for model execution - Audit logging for model loading attempts

Example Usage

>>> from nlsq.cli.model_registry import ModelRegistry
>>>
>>> registry = ModelRegistry()
>>>
>>> # Get a builtin model
>>> linear = registry.get_model("linear", {"type": "builtin", "name": "linear"})
>>>
>>> # Get a custom model from file (with security validation)
>>> custom = registry.get_model(
...     "/path/to/model.py",
...     {"type": "custom", "path": "/path/to/model.py", "function": "my_model"}
... )
>>>
>>> # Get a polynomial model
>>> poly3 = registry.get_model("poly", {"type": "polynomial", "degree": 3})
class nlsq.cli.model_registry.ModelRegistry[source]

Bases: object

Registry for model functions used in curve fitting.

The ModelRegistry handles three types of models: 1. Builtin: Models from nlsq.functions (linear, gaussian, etc.) 2. Custom: Models loaded from external Python files 3. Polynomial: Dynamically generated polynomial functions

Each model function may have optional methods attached: - estimate_p0(xdata, ydata): Estimate initial parameters - bounds(): Return default parameter bounds

_builtin_cache

Cache of loaded builtin model functions.

Type:

dict

Examples

>>> registry = ModelRegistry()
>>> model = registry.get_model("gaussian", {"type": "builtin", "name": "gaussian"})
>>> print(model.estimate_p0([1,2,3], [1,4,9]))
__init__()[source]

Initialize ModelRegistry.

list_builtin_models()[source]

List all available builtin model names.

Discovers models by introspecting nlsq.functions.__all__.

Returns:

Names of available builtin models.

Return type:

list[str]

Examples

>>> registry = ModelRegistry()
>>> models = registry.list_builtin_models()
>>> print("linear" in models)
True
get_model(name_or_path, config)[source]

Get a model function by name or path.

Parameters:
  • name_or_path (str) – For builtin models: the model name (e.g., “linear”, “gaussian”). For custom models: path to the Python file. For polynomial: any identifier (degree is in config).

  • config (dict) – Model configuration with keys: - type: str - Model type (“builtin”, “custom”, “polynomial”) - name: str - Model name (for builtin) - path: str - File path (for custom) - function: str - Function name (for custom) - degree: int - Polynomial degree (for polynomial)

Returns:

The model function with optional estimate_p0 and bounds methods.

Return type:

ModelFunction

Raises:

ModelError – If the model cannot be resolved.

Examples

>>> registry = ModelRegistry()
>>> # Builtin model
>>> linear = registry.get_model("linear", {"type": "builtin", "name": "linear"})
>>> # Custom model
>>> custom = registry.get_model(
...     "path/model.py",
...     {"type": "custom", "path": "path/model.py", "function": "my_func"}
... )
>>> # Polynomial model
>>> poly = registry.get_model("poly", {"type": "polynomial", "degree": 2})

nlsq.cli.visualization

Publication-quality visualization module for NLSQ CLI.

This module provides the FitVisualizer class for generating publication-quality plots of curve fitting results, including: - Combined main plot + residuals layout - Separate histogram of residuals - Confidence bands from covariance matrix error propagation - Multiple style presets (publication, presentation, nature, science, minimal) - Multi-format output (PDF vector, PNG raster) - Fit statistics annotation (R-squared, RMSE) - Colorblind-safe palette support

Example Usage

>>> from nlsq.cli.visualization import FitVisualizer
>>>
>>> visualizer = FitVisualizer()
>>> result = {"popt": [1.0, 0.5, 0.1], "pcov": [[0.01, 0, 0], [0, 0.02, 0], [0, 0, 0.005]], ...}
>>> data = {"xdata": x, "ydata": y, "sigma": sigma}
>>> config = {"visualization": {"enabled": True, "output_dir": "figures", ...}}
>>> output_paths = visualizer.generate(result, data, model, config)
class nlsq.cli.visualization.FitVisualizer[source]

Bases: object

Visualizer for curve fitting results.

Generates publication-quality plots including combined fit + residuals layouts, histograms, and confidence bands.

None
generate(result, data, model, config)[source]

Generate all configured visualizations and save to files.

Examples

>>> visualizer = FitVisualizer()
>>> result = {"popt": [1.0, 0.5], "pcov": [[0.01, 0], [0, 0.02]], ...}
>>> data = {"xdata": x, "ydata": y}
>>> config = {"visualization": {"enabled": True, "output_dir": "figures"}}
>>> output_paths = visualizer.generate(result, data, model, config)
generate(result, data, model, config)[source]

Generate visualizations based on configuration.

Parameters:
  • result (dict) – Fit result dictionary containing: - popt: Fitted parameters - pcov: Covariance matrix - fun: Residuals (optional) - statistics: Dict with r_squared, rmse, etc.

  • data (dict) – Data dictionary containing: - xdata: Independent variable array - ydata: Dependent variable array - sigma: Uncertainties (optional)

  • model (callable) – Model function f(x, *params).

  • config (dict) – Configuration dictionary with visualization section.

Returns:

List of output file paths that were generated.

Return type:

list[str]

nlsq.cli.result_exporter

Result exporter module for NLSQ CLI.

This module provides the ResultExporter class for exporting curve fitting results in multiple formats (JSON, CSV, stdout).

Supported Export Formats

  • JSON: Full metadata with nested structure

  • CSV: Flattened parameter name/value/uncertainty rows

  • stdout: JSON format for piping to other tools

Example Usage

>>> from nlsq.cli.result_exporter import ResultExporter
>>>
>>> exporter = ResultExporter()
>>> result = {"popt": [1.0, 0.5], "pcov": [[0.01, 0], [0, 0.02]], ...}
>>> config = {"export": {"results_file": "output.json", "format": "json"}}
>>> exporter.export(result, config)
class nlsq.cli.result_exporter.NumpyJSONEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

Custom JSON encoder that handles numpy arrays and types.

default(obj)[source]

Convert numpy types to JSON-serializable types.

Parameters:

obj (Any) – Object to convert.

Returns:

JSON-serializable object.

Return type:

Any

class nlsq.cli.result_exporter.ResultExporter[source]

Bases: object

Exporter for curve fitting results.

Exports fit results to JSON, CSV, or stdout formats with full metadata including parameters, covariance, uncertainties, statistics, and convergence information.

None
export(result, config)[source]

Export fit result to configured format(s).

Examples

>>> exporter = ResultExporter()
>>> result = {"popt": [1.0, 0.5], "pcov": [[0.01, 0], [0, 0.02]]}
>>> config = {"export": {"results_file": "results.json", "format": "json"}}
>>> exporter.export(result, config)
export(result, config)[source]

Export fit result to configured format(s).

Parameters:
  • result (dict) – Fit result dictionary containing: - popt: Fitted parameters (ndarray or list) - pcov: Covariance matrix (ndarray or list) - success: bool indicating fit success - message: str with convergence message - nfev: Number of function evaluations - njev: Number of Jacobian evaluations (optional) - cost: Final cost value (optional) - fun: Residual vector (optional)

  • config (dict) – Export configuration containing: - export.results_file: Output file path - export.format: “json” or “csv” - export.stdout: bool to output to stdout - export.skip_file_on_stdout: bool to skip file when stdout active - metadata: Workflow metadata (optional) - model: Model configuration (optional)

Return type:

None

Raises:

CLIError – If export fails due to file or format issues.

nlsq.cli.errors

CLI-specific exceptions and logging infrastructure for NLSQ.

This module provides: - CLI-specific exception classes with actionable error messages - Dual logging system (file + console) - Structured JSON logging support - Log rotation support - Verbosity level control

Exception Hierarchy

  • CLIError (base)

    • ConfigError (YAML configuration issues)

    • DataLoadError (data file loading failures)

    • ModelError (model resolution issues)

    • FitError (curve fitting failures)

Logging System

The dual logging system provides: - File logging: Python logging module to configurable log file - Console logging: Formatted output with colored severity levels - Structured logging: JSON format for external tool ingestion - Log rotation: Automatic rotation with configurable size and backup count

Verbosity Levels

  • 0: Silent (errors only)

  • 1: Progress (default, warnings and progress messages)

  • 2: Detailed (info-level messages)

  • 3: Debug (debug-level messages)

class nlsq.cli.errors.Colors[source]

Bases: object

ANSI color codes for console output.

RESET = '\x1b[0m'
RED = '\x1b[91m'
GREEN = '\x1b[92m'
YELLOW = '\x1b[93m'
BLUE = '\x1b[94m'
MAGENTA = '\x1b[95m'
CYAN = '\x1b[96m'
BOLD = '\x1b[1m'
classmethod is_terminal()[source]

Check if stdout is a terminal (supports colors).

exception nlsq.cli.errors.CLIError(message, context=None, suggestion=None)[source]

Bases: Exception

Base exception class for NLSQ CLI errors.

All CLI-specific exceptions inherit from this class, allowing users to catch all CLI errors with a single except clause.

message

Human-readable error message.

Type:

str

context

Additional context information for debugging.

Type:

dict

suggestion

Actionable suggestion for resolving the error.

Type:

str, optional

__init__(message, context=None, suggestion=None)[source]

Initialize CLIError.

Parameters:
  • message (str) – Human-readable error message.

  • context (dict, optional) – Additional context information for debugging.

  • suggestion (str, optional) – Actionable suggestion for resolving the error.

to_dict()[source]

Convert exception to dictionary for JSON serialization.

exception nlsq.cli.errors.ConfigError(message, config_file=None, key=None, context=None, suggestion=None)[source]

Bases: CLIError

Exception raised for YAML configuration issues.

Raised when: - YAML file cannot be parsed (syntax errors) - Required configuration keys are missing - Configuration values are invalid - Configuration file does not exist

Examples

>>> raise ConfigError(
...     "Missing required key 'data.input_file'",
...     context={"config_file": "workflow.yaml"},
...     suggestion="Add 'input_file' under the 'data' section"
... )
__init__(message, config_file=None, key=None, context=None, suggestion=None)[source]

Initialize ConfigError.

Parameters:
  • message (str) – Human-readable error message.

  • config_file (str or Path, optional) – Path to the configuration file.

  • key (str, optional) – The configuration key that caused the error.

  • context (dict, optional) – Additional context information.

  • suggestion (str, optional) – Actionable suggestion for resolving the error.

exception nlsq.cli.errors.DataLoadError(message, file_path=None, file_format=None, context=None, suggestion=None)[source]

Bases: CLIError

Exception raised for data file loading failures.

Raised when: - Data file does not exist - Data file format cannot be detected - Data file cannot be parsed - Required columns are missing - Data contains invalid values (NaN/Inf when not allowed)

Examples

>>> raise DataLoadError(
...     "Column 'time' not found in data.csv",
...     file_path="data/experiment.csv",
...     context={"available_columns": ["x", "y", "sigma"]},
...     suggestion="Use one of the available columns: x, y, sigma"
... )
__init__(message, file_path=None, file_format=None, context=None, suggestion=None)[source]

Initialize DataLoadError.

Parameters:
  • message (str) – Human-readable error message.

  • file_path (str or Path, optional) – Path to the data file.

  • file_format (str, optional) – Expected or detected file format.

  • context (dict, optional) – Additional context information.

  • suggestion (str, optional) – Actionable suggestion for resolving the error.

exception nlsq.cli.errors.ModelError(message, model_name=None, model_type=None, context=None, suggestion=None)[source]

Bases: CLIError

Exception raised for model resolution issues.

Raised when: - Builtin model name is not recognized - Custom model file does not exist - Custom model function cannot be found - Model function signature is invalid - Polynomial degree is invalid

Examples

>>> raise ModelError(
...     "Model 'exponential_growth' not found in builtin models",
...     model_name="exponential_growth",
...     context={"available_models": ["linear", "exponential_decay", "gaussian"]},
...     suggestion="Did you mean 'exponential_decay'?"
... )
__init__(message, model_name=None, model_type=None, context=None, suggestion=None)[source]

Initialize ModelError.

Parameters:
  • message (str) – Human-readable error message.

  • model_name (str, optional) – Name of the model that caused the error.

  • model_type (str, optional) – Type of model (builtin, custom, polynomial).

  • context (dict, optional) – Additional context information.

  • suggestion (str, optional) – Actionable suggestion for resolving the error.

exception nlsq.cli.errors.FitError(message, model_name=None, context=None, suggestion=None)[source]

Bases: CLIError

Exception raised for curve fitting failures.

Raised when: - curve_fit() fails to converge - Covariance matrix cannot be estimated - Fit produces invalid results (NaN/Inf) - Maximum iterations exceeded

Examples

>>> raise FitError(
...     "Curve fitting failed to converge",
...     context={"iterations": 1000, "final_cost": 1e10},
...     suggestion="Try different initial parameters or relax tolerances"
... )
__init__(message, model_name=None, context=None, suggestion=None)[source]

Initialize FitError.

Parameters:
  • message (str) – Human-readable error message.

  • model_name (str, optional) – Name of the model being fitted.

  • context (dict, optional) – Additional context information (iterations, cost, etc.).

  • suggestion (str, optional) – Actionable suggestion for resolving the error.

class nlsq.cli.errors.JsonFormatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)[source]

Bases: Formatter

JSON formatter for structured logging.

Outputs log records as single-line JSON objects for easy parsing by external tools (log aggregators, monitoring systems, etc.).

format(record)[source]

Format log record as JSON.

Parameters:

record (logging.LogRecord) – The log record to format.

Returns:

JSON-formatted log line.

Return type:

str

class nlsq.cli.errors.ColoredConsoleFormatter(use_colors=True)[source]

Bases: Formatter

Console formatter with colored severity levels.

Applies ANSI color codes based on log level for better visibility in terminal output.

LEVEL_COLORS: ClassVar[dict[int, str]] = {10: '\x1b[96m', 20: '\x1b[92m', 30: '\x1b[93m', 40: '\x1b[91m', 50: '\x1b[1m\x1b[91m'}
__init__(use_colors=True)[source]

Initialize ColoredConsoleFormatter.

Parameters:

use_colors (bool) – Whether to use ANSI color codes.

format(record)[source]

Format log record with optional colors.

Parameters:

record (logging.LogRecord) – The log record to format.

Returns:

Formatted log line.

Return type:

str

class nlsq.cli.errors.CLILogger(name='nlsq.cli')[source]

Bases: object

Logger wrapper providing dual logging (file + console).

This class manages the logging infrastructure for the CLI, supporting both file and console output with configurable formats and verbosity levels.

__init__(name='nlsq.cli')[source]

Initialize CLILogger.

Parameters:

name (str) – Logger name.

property verbosity: int

Get current verbosity level.

debug(message, **kwargs)[source]

Log debug message.

info(message, **kwargs)[source]

Log info message.

warning(message, **kwargs)[source]

Log warning message.

error(message, **kwargs)[source]

Log error message.

critical(message, **kwargs)[source]

Log critical message.

exception(message, **kwargs)[source]

Log exception with traceback.

nlsq.cli.errors.setup_logging(log_file=None, console=True, verbosity=1, structured=False, rotation_enabled=False, max_bytes=10485760, backup_count=5, use_colors=True)[source]

Set up dual logging system.

Configures both file and console logging handlers based on the provided configuration options.

Parameters:
  • log_file (str or Path, optional) – Path to log file. If None, file logging is disabled.

  • console (bool) – Whether to enable console logging.

  • verbosity (int) – Verbosity level (0=silent, 1=progress, 2=detailed, 3=debug).

  • structured (bool) – Whether to use structured JSON format for file logging.

  • rotation_enabled (bool) – Whether to enable log rotation.

  • max_bytes (int) – Maximum bytes per log file before rotation (default: 10 MB).

  • backup_count (int) – Number of backup files to keep (default: 5).

  • use_colors (bool) – Whether to use ANSI colors in console output.

Returns:

Configured logger instance.

Return type:

CLILogger

Examples

>>> logger = setup_logging(
...     log_file="logs/workflow.log",
...     console=True,
...     verbosity=2,
...     structured=False,
...     rotation_enabled=True,
... )
>>> logger.info("Starting workflow")
nlsq.cli.errors.get_logger()[source]

Get the global CLI logger instance.

If logging has not been set up, initializes with default settings.

Returns:

The global CLI logger instance.

Return type:

CLILogger

Examples

>>> logger = get_logger()
>>> logger.info("Processing file")
nlsq.cli.errors.setup_logging_from_config(logging_config)[source]

Set up logging from a configuration dictionary.

Parameters:

logging_config (dict) – Configuration dictionary with keys: - log_file: str - Path to log file - console: bool - Enable console logging - structured.enabled: bool - Enable JSON format - rotation.enabled: bool - Enable log rotation - rotation.max_bytes: int - Max bytes per file - rotation.backup_count: int - Number of backups

Returns:

Configured logger instance.

Return type:

CLILogger

Examples

>>> config = {
...     "log_file": "workflow.log",
...     "console": True,
...     "structured": {"enabled": False},
...     "rotation": {"enabled": True, "max_bytes": 10485760, "backup_count": 5},
... }
>>> logger = setup_logging_from_config(config)

nlsq.cli.commands

NLSQ CLI command handlers.

This package provides command handler modules for the NLSQ CLI: - fit: Execute single curve fit from YAML workflow configuration - batch: Execute parallel batch fitting from multiple YAML files - info: Display system and environment information - config: Copy configuration templates to current directory

Example Usage

>>> from nlsq.cli.commands import fit, batch, info, config
>>> result = fit.run_fit("workflow.yaml")
>>> results = batch.run_batch(["w1.yaml", "w2.yaml"])
>>> info.run_info()
>>> config.run_config()