Interfaces Module

The interfaces module provides command-line interface and shell completion functionality.

Command Line Interface

Command Line Interface for XRayLabTool.

This module provides a comprehensive CLI for calculating X-ray optical properties of materials, including single material calculations, batch processing, utility functions for X-ray analysis, and shell completion installation.

Available Commands:

calc Calculate X-ray properties for a single material batch Process multiple materials from CSV file compare Compare X-ray properties between multiple materials convert Convert between energy and wavelength units formula Parse and analyze chemical formulas atomic Look up atomic data for elements bragg Calculate Bragg angles for diffraction list List available data and information install-completion Install shell completion for xraylabtool uninstall-completion Remove shell completion for xraylabtool

The CLI supports various output formats (table, CSV, JSON), field filtering, precision control, and comprehensive shell completion for enhanced usability.

class xraylabtool.interfaces.cli.MemoryMonitor[source]

Bases: object

__init__()[source]
Return type:

None

update()[source]
Return type:

None

print_summary()[source]
Return type:

None

class xraylabtool.interfaces.cli.PerformanceMetrics[source]

Bases: object

__init__()[source]
Return type:

None

time_operation()[source]
Return type:

Any

record_operations(count)[source]
Return type:

None

Parameters:

count (int)

print_summary(verbose=False)[source]
Return type:

None

Parameters:

verbose (bool)

class xraylabtool.interfaces.cli.AdaptiveChunkSizer[source]

Bases: object

__init__()[source]
Return type:

None

calculate_chunk_size(total)[source]
Return type:

int

Parameters:

total (int)

xraylabtool.interfaces.cli.create_batch_progress_tracker(**kwargs)[source]
Return type:

Any

Parameters:

kwargs (Any)

xraylabtool.interfaces.cli.create_parser()[source]

Create the main argument parser with all subcommands.

Return type:

ArgumentParser

xraylabtool.interfaces.cli.add_calc_command(subparsers)[source]

Add the ‘calc’ subcommand for single material calculations.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_batch_command(subparsers)[source]

Add the ‘batch’ subcommand for processing multiple materials.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_convert_command(subparsers)[source]

Add the ‘convert’ subcommand for unit conversions.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_formula_command(subparsers)[source]

Add the ‘formula’ subcommand for formula parsing.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_atomic_command(subparsers)[source]

Add the ‘atomic’ subcommand for atomic data lookup.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_bragg_command(subparsers)[source]

Add the ‘bragg’ subcommand for Bragg angle calculations.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_list_command(subparsers)[source]

Add the ‘list’ subcommand for listing available data.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_install_completion_command(subparsers)[source]

Add the ‘install-completion’ subcommand for shell completion setup.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_completion_command(subparsers)[source]

Add the ‘completion’ subcommand for the new completion system.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_uninstall_completion_command(subparsers)[source]

Add the ‘uninstall-completion’ subcommand for shell completion removal.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.add_compare_command(subparsers)[source]

Add the ‘compare’ subcommand for material comparison.

Return type:

None

Parameters:

subparsers (Any)

xraylabtool.interfaces.cli.parse_energy_string(energy_str)[source]

Parse energy string and return numpy array.

Return type:

ndarray

Parameters:

energy_str (str)

xraylabtool.interfaces.cli.format_xray_result(result, format_type, precision=6, fields=None)[source]

Format XRayResult for output.

Return type:

str

Parameters:
xraylabtool.interfaces.cli.cmd_calc(args)[source]

Handle the ‘calc’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_batch(args)[source]

Handle the ‘batch’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_convert(args)[source]

Handle the ‘convert’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_formula(args)[source]

Handle the ‘formula’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_atomic(args)[source]

Handle the ‘atomic’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_bragg(args)[source]

Handle the ‘bragg’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_list(args)[source]

Handle the ‘list’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_install_completion(args)[source]

Handle the ‘install-completion’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_uninstall_completion(args)[source]

Handle the ‘uninstall-completion’ command.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_completion(args)[source]

Handle the ‘completion’ command for the new completion system.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.cmd_compare(args)[source]

Handle the ‘compare’ command for material comparison.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.cli.main()[source]

Execute the main CLI application.

Return type:

int

CLI Commands Overview

XRayLabTool provides 9 CLI commands:

Command

Description

calc

Calculate X-ray properties for a single material

batch

Process multiple materials from CSV file

convert

Convert between energy and wavelength units

formula

Parse and analyze chemical formulas

atomic

Look up atomic scattering factor data

bragg

Calculate Bragg diffraction angles

list

Display reference information and constants

install-completion

Install shell completion (bash, zsh, fish, PowerShell)

uninstall-completion

Remove shell completion

Command Examples

Single Material Calculation:

# Basic calculation
xraylabtool calc Si --density 2.33 --energy 8000

# Multiple energies
xraylabtool calc SiO2 --density 2.20 --energy 5000,8000,10000

# Energy range
xraylabtool calc Al --density 2.70 --energy 1000-20000:100

# Different output formats
xraylabtool calc Si --density 2.33 --energy 8000 --output csv
xraylabtool calc Si --density 2.33 --energy 8000 --output json

Batch Processing:

# Process CSV file
xraylabtool batch materials.csv --output results.csv

# Specify energy column
xraylabtool batch data.csv --energy-column "Energy (eV)"

# JSON output
xraylabtool batch materials.csv --output results.json --format json

Unit Conversions:

# Energy to wavelength
xraylabtool convert --energy 8000 --to wavelength

# Wavelength to energy
xraylabtool convert --wavelength 1.55 --to energy

# Multiple values
xraylabtool convert --energy 5000,8000,10000 --to wavelength

Formula Analysis:

# Parse chemical formula
xraylabtool formula SiO2

# Complex formula
xraylabtool formula "Ca5(PO4)3F"

# With molecular weight
xraylabtool formula SiO2 --molecular-weight

Atomic Data Lookup:

# Element information
xraylabtool atomic Si

# Scattering factors at specific energy
xraylabtool atomic Si --energy 8000

# Multiple elements
xraylabtool atomic Si,Al,O --energy 8000

Bragg Diffraction:

# Calculate Bragg angle
xraylabtool bragg --d-spacing 3.14 --energy 8000

# Multiple reflections
xraylabtool bragg --d-spacing 3.14,1.92,1.64 --energy 8000

Reference Information:

# List supported elements
xraylabtool list elements

# Physical constants
xraylabtool list constants

# Example formulas
xraylabtool list examples

Output Formats

All commands support multiple output formats:

  • table (default): Human-readable tabular format

  • csv: Comma-separated values for spreadsheet import

  • json: JSON format for programmatic processing

Shell Completion (Legacy Bridge)

Shell completion system for XRayLabTool.

This module provides a backward-compatible interface to the new virtual environment-centric completion system while maintaining the same API that the existing CLI expects.

class xraylabtool.interfaces.completion.CompletionInstaller[source]

Bases: object

Handles virtual environment-centric completion installation.

__init__()[source]
Return type:

None

install(shell=None, target_env=None, force=False)[source]

Install completion in virtual environment.

Parameters:
  • shell (str | None) – Shell type (bash, zsh, fish, powershell). Auto-detected if None.

  • target_env (str | None) – Target environment name. Current environment if None.

  • force (bool) – Force reinstallation if already installed.

Return type:

bool

Returns:

True if installation succeeded, False otherwise.

uninstall(target_env=None, all_envs=False)[source]

Uninstall completion from environment(s).

Parameters:
  • target_env (str | None) – Target environment name. Current environment if None.

  • all_envs (bool) – Remove from all environments if True.

Return type:

bool

Returns:

True if uninstallation succeeded, False otherwise.

list_environments()[source]

List all detected environments with completion status.

Return type:

None

status()[source]

Show completion status for current environment.

Return type:

None

install_bash_completion(**kwargs)[source]

Install bash completion (backward compatibility).

Return type:

bool

uninstall_bash_completion(**kwargs)[source]

Uninstall bash completion (backward compatibility).

Return type:

bool

uninstall_completion(shell_type=None, cleanup_session=True, **kwargs)[source]

Uninstall completion (backward compatibility).

Return type:

bool

test_completion()[source]

Test completion functionality (backward compatibility).

Return type:

bool

get_bash_completion_dir()[source]

Get bash completion directory (backward compatibility).

Return type:

Path

get_user_bash_completion_dir()[source]

Get user bash completion directory (backward compatibility).

Return type:

Path

xraylabtool.interfaces.completion.install_completion_main(args)

Legacy install completion main function with new system backend.

This function maintains backward compatibility with the existing CLI while using the new completion system internally.

Return type:

int

Parameters:

args (Namespace)

xraylabtool.interfaces.completion.uninstall_completion_main(args)

Legacy uninstall completion main function with new system backend.

Return type:

int

Parameters:

args (Any)

Shell Completion v2

The completion_v2 sub-package is the current virtual-environment-centric completion system, replacing the legacy bridge above.

Virtual environment-centric completion installer.

This module handles installation and management of shell completion that activates/deactivates with virtual environment changes.

class xraylabtool.interfaces.completion_v2.installer.CompletionInstaller[source]

Bases: object

Handles virtual environment-centric completion installation.

__init__()[source]
Return type:

None

install(shell=None, target_env=None, force=False)[source]

Install completion in virtual environment.

Parameters:
  • shell (str | None) – Shell type (bash, zsh, fish, powershell). Auto-detected if None.

  • target_env (str | None) – Target environment name. Current environment if None.

  • force (bool) – Force reinstallation if already installed.

Return type:

bool

Returns:

True if installation succeeded, False otherwise.

uninstall(target_env=None, all_envs=False)[source]

Uninstall completion from environment(s).

Parameters:
  • target_env (str | None) – Target environment name. Current environment if None.

  • all_envs (bool) – Remove from all environments if True.

Return type:

bool

Returns:

True if uninstallation succeeded, False otherwise.

list_environments()[source]

List all detected environments with completion status.

Return type:

None

status()[source]

Show completion status for current environment.

Return type:

None

install_bash_completion(**kwargs)[source]

Install bash completion (backward compatibility).

Return type:

bool

uninstall_bash_completion(**kwargs)[source]

Uninstall bash completion (backward compatibility).

Return type:

bool

uninstall_completion(shell_type=None, cleanup_session=True, **kwargs)[source]

Uninstall completion (backward compatibility).

Return type:

bool

test_completion()[source]

Test completion functionality (backward compatibility).

Return type:

bool

get_bash_completion_dir()[source]

Get bash completion directory (backward compatibility).

Return type:

Path

get_user_bash_completion_dir()[source]

Get user bash completion directory (backward compatibility).

Return type:

Path

Shell-specific completion script generators.

This module provides modular completion script generation for different shells, replacing the large hardcoded strings with template-based generation.

class xraylabtool.interfaces.completion_v2.shells.CompletionGenerator(command_name='xraylabtool')[source]

Bases: ABC

Base class for shell completion generators.

Parameters:

command_name (str)

__init__(command_name='xraylabtool')[source]
Parameters:

command_name (str)

abstractmethod generate(commands, global_options)[source]

Generate completion script for this shell.

Return type:

str

Parameters:
abstract property shell_name: str

Name of the shell this generator supports.

abstract property file_extension: str

File extension for completion scripts.

class xraylabtool.interfaces.completion_v2.shells.BashCompletionGenerator(command_name='xraylabtool')[source]

Bases: CompletionGenerator

Generates Bash completion scripts.

Parameters:

command_name (str)

property shell_name: str

Name of the shell this generator supports.

property file_extension: str

File extension for completion scripts.

generate(commands, global_options)[source]

Generate Bash completion script.

Return type:

str

Parameters:
class xraylabtool.interfaces.completion_v2.shells.ZshCompletionGenerator(command_name='xraylabtool')[source]

Bases: CompletionGenerator

Generates native Zsh completion scripts.

Parameters:

command_name (str)

property shell_name: str

Name of the shell this generator supports.

property file_extension: str

File extension for completion scripts.

generate(commands, global_options)[source]

Generate native Zsh completion script.

Return type:

str

Parameters:
class xraylabtool.interfaces.completion_v2.shells.FishCompletionGenerator(command_name='xraylabtool')[source]

Bases: CompletionGenerator

Generates Fish shell completion scripts.

Parameters:

command_name (str)

property shell_name: str

Name of the shell this generator supports.

property file_extension: str

File extension for completion scripts.

generate(commands, global_options)[source]

Generate Fish completion script.

Return type:

str

Parameters:
class xraylabtool.interfaces.completion_v2.shells.PowerShellCompletionGenerator(command_name='xraylabtool')[source]

Bases: CompletionGenerator

Generates PowerShell completion scripts.

Parameters:

command_name (str)

property shell_name: str

Name of the shell this generator supports.

property file_extension: str

File extension for completion scripts.

generate(commands, global_options)[source]

Generate PowerShell completion script.

Return type:

str

Parameters:
class xraylabtool.interfaces.completion_v2.shells.CompletionManager[source]

Bases: object

Manages completion script generation for all supported shells.

__init__()[source]
Return type:

None

get_supported_shells()[source]

Get list of supported shell types.

Return type:

list[str]

generate_completion(shell, commands, global_options)[source]

Generate completion script for specified shell.

Return type:

str

Parameters:
get_filename(shell, command_name='xraylabtool')[source]

Get the appropriate filename for a completion script.

Return type:

str

Parameters:
  • shell (str)

  • command_name (str)

xraylabtool.interfaces.completion_v2.shells.get_xraylabtool_commands()[source]

Get the XRayLabTool command definitions for completion.

Return type:

dict[str, dict[str, Any]]

xraylabtool.interfaces.completion_v2.shells.get_global_options()[source]

Get global options available for all commands.

Return type:

list[str]

Environment detection and management for shell completion.

This module provides robust detection of Python virtual environments and manages completion activation/deactivation based on environment state.

class xraylabtool.interfaces.completion_v2.environment.EnvironmentType[source]

Bases: object

Constants for environment types.

SYSTEM = 'system'
VENV = 'venv'
VIRTUALENV = 'virtualenv'
CONDA = 'conda'
MAMBA = 'mamba'
PIPENV = 'pipenv'
POETRY = 'poetry'
class xraylabtool.interfaces.completion_v2.environment.EnvironmentInfo(env_type, path, name, is_active=False, python_version=None, has_completion=False)[source]

Bases: object

Information about a detected environment.

Parameters:
  • env_type (str)

  • path (Path)

  • name (str)

  • is_active (bool)

  • python_version (str | None)

  • has_completion (bool)

__init__(env_type, path, name, is_active=False, python_version=None, has_completion=False)[source]
Parameters:
  • env_type (str)

  • path (Path)

  • name (str)

  • is_active (bool)

  • python_version (str | None)

  • has_completion (bool)

to_dict()[source]

Convert to dictionary for serialization.

Return type:

dict[str, Any]

classmethod from_dict(data)[source]

Create from dictionary.

Return type:

EnvironmentInfo

Parameters:

data (dict[str, Any])

class xraylabtool.interfaces.completion_v2.environment.EnvironmentDetector[source]

Bases: object

Detects and manages Python virtual environments.

__init__()[source]
Return type:

None

get_current_environment()[source]

Get information about the currently active environment.

Return type:

EnvironmentInfo | None

discover_all_environments(use_cache=True)[source]

Discover all available Python environments.

Return type:

list[EnvironmentInfo]

Parameters:

use_cache (bool)

clear_cache()[source]

Clear the environment cache.

Return type:

None

Performance optimizations and caching for shell completion.

This module provides caching mechanisms and performance optimizations to make completion faster and more responsive.

class xraylabtool.interfaces.completion_v2.cache.CompletionCache(cache_dir=None)[source]

Bases: object

Fast caching system for completion data.

Parameters:

cache_dir (Path | None)

__init__(cache_dir=None)[source]
Parameters:

cache_dir (Path | None)

get_cache_key(data)[source]

Generate cache key from data.

Return type:

str

Parameters:

data (Any)

get(key, timeout=None)[source]

Get cached data by key.

Return type:

Any | None

Parameters:
  • key (str)

  • timeout (int | None)

set(key, data, metadata=None)[source]

Cache data with optional metadata.

Return type:

None

Parameters:
invalidate(key)[source]

Invalidate cached data.

Return type:

None

Parameters:

key (str)

clear()[source]

Clear all cached data.

Return type:

None

get_cache_stats()[source]

Get cache statistics.

Return type:

dict[str, Any]

class xraylabtool.interfaces.completion_v2.cache.CompletionDataManager[source]

Bases: object

Manages and caches completion data for fast access.

__init__()[source]
Return type:

None

get_commands(force_refresh=False)[source]

Get command definitions with caching.

Return type:

dict[str, dict[str, Any]]

Parameters:

force_refresh (bool)

get_global_options(force_refresh=False)[source]

Get global options with caching.

Return type:

list[str]

Parameters:

force_refresh (bool)

get_completion_script(shell, force_refresh=False)[source]

Get cached completion script for shell.

Return type:

str | None

Parameters:
cache_completion_script(shell, script)[source]

Cache completion script for shell.

Return type:

None

Parameters:
invalidate_command_cache()[source]

Invalidate command-related caches.

Return type:

None

class xraylabtool.interfaces.completion_v2.cache.FastCompletionProvider[source]

Bases: object

Optimized completion provider for runtime performance.

__init__()[source]
Return type:

None

get_command_completions(partial_command)[source]

Get command completions for partial input.

Return type:

list[str]

Parameters:

partial_command (str)

get_option_completions(command, partial_option)[source]

Get option completions for a command.

Return type:

list[str]

Parameters:
  • command (str)

  • partial_option (str)

get_file_completions(partial_path)[source]

Get file path completions (optimized).

Return type:

list[str]

Parameters:

partial_path (str)

warm_cache()[source]

Pre-warm caches for better performance.

Return type:

None

class xraylabtool.interfaces.completion_v2.cache.PerformanceMonitor[source]

Bases: object

Monitor completion performance for optimization.

__init__()[source]
Return type:

None

record_completion_time(duration)[source]

Record completion timing.

Return type:

None

Parameters:

duration (float)

record_cache_hit()[source]

Record cache hit.

Return type:

None

record_cache_miss()[source]

Record cache miss.

Return type:

None

get_stats()[source]

Get performance statistics.

Return type:

dict[str, Any]

xraylabtool.interfaces.completion_v2.cache.get_data_manager()[source]

Get global completion data manager instance.

Return type:

CompletionDataManager

xraylabtool.interfaces.completion_v2.cache.get_performance_monitor()[source]

Get global performance monitor instance.

Return type:

PerformanceMonitor

Integration layer for the new completion system.

This module provides backward compatibility and integration with the existing CLI while gradually migrating to the new virtual environment-centric completion system.

xraylabtool.interfaces.completion_v2.integration.legacy_install_completion_main(args)[source]

Legacy install completion main function with new system backend.

This function maintains backward compatibility with the existing CLI while using the new completion system internally.

Return type:

int

Parameters:

args (Namespace)

xraylabtool.interfaces.completion_v2.integration.legacy_uninstall_completion_main(args)[source]

Legacy uninstall completion main function with new system backend.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.completion_v2.integration.test_completion_installation()[source]

Test if completion is working in the current environment.

Return type:

int

xraylabtool.interfaces.completion_v2.integration.handle_new_completion_command(args)[source]

Handle new ‘completion’ subcommand.

Return type:

int

Parameters:

args (list[str])

xraylabtool.interfaces.completion_v2.integration.install_completion_main(args)

Legacy install completion main function with new system backend.

This function maintains backward compatibility with the existing CLI while using the new completion system internally.

Return type:

int

Parameters:

args (Namespace)

xraylabtool.interfaces.completion_v2.integration.uninstall_completion_main(args)

Legacy uninstall completion main function with new system backend.

Return type:

int

Parameters:

args (Any)

Command-line interface for the new completion system.

This module provides CLI commands for managing the virtual environment-centric shell completion system.

xraylabtool.interfaces.completion_v2.cli.create_completion_parser()[source]

Create argument parser for completion commands.

Return type:

ArgumentParser

xraylabtool.interfaces.completion_v2.cli.handle_completion_command(args)[source]

Handle completion subcommands.

Return type:

int

Parameters:

args (Namespace)

xraylabtool.interfaces.completion_v2.cli.show_completion_info()[source]

Show information about the completion system.

Return type:

None

xraylabtool.interfaces.completion_v2.cli.completion_main(args=None)[source]

Main entry point for completion commands.

Return type:

int

Parameters:

args (Any)

xraylabtool.interfaces.completion_v2.cli.install_completion_main(args)[source]

Legacy install completion main function.

Return type:

int

Parameters:

args (Namespace)

xraylabtool.interfaces.completion_v2.cli.uninstall_completion_main(args)[source]

Legacy uninstall completion main function.

Return type:

int

Parameters:

args (Any)

Bash Completion Features

The shell completion system provides:

  • Command completion: All 9 CLI commands

  • Option completion: Command flags and parameters

  • File completion: Input/output file paths

  • Element completion: Chemical element symbols

  • Unit completion: Energy and wavelength units

Installation

# Install completion for current user
xraylabtool install-completion

# Install system-wide (requires sudo)
sudo xraylabtool install-completion --system

# Custom completion script location
xraylabtool install-completion --path /custom/path

Usage

After installation, completion is available by pressing Tab:

xraylabtool [TAB]          # Shows all commands
xraylabtool calc [TAB]     # Shows calc command options
xraylabtool atomic S[TAB]  # Completes to supported elements starting with 'S'

Uninstallation

# Remove completion
xraylabtool uninstall-completion

# Remove system-wide completion
sudo xraylabtool uninstall-completion --system

Platform Support

Shell completion is supported for:

  • Bash: Full support on Linux and macOS (requires bash-completion)

  • Zsh: Full support on Linux and macOS (requires zsh-completions)

  • Fish: Native support with built-in completion system

  • PowerShell: Full support on Windows, macOS, and Linux

Error Handling

The CLI provides error handling with helpful messages:

# Invalid formula
$ xraylabtool calc XYZ --density 1.0 --energy 8000
Error: Unknown element 'XYZ' in formula

# Missing required parameter
$ xraylabtool calc Si --energy 8000
Error: --density is required

# Invalid energy range
$ xraylabtool calc Si --density 2.33 --energy 0
Error: Energy must be positive

Integration Examples

With Python Scripts:

import subprocess
import json

# Call CLI from Python
result = subprocess.run([
    "xraylabtool", "calc", "Si",
    "--density", "2.33",
    "--energy", "8000",
    "--output", "json"
], capture_output=True, text=True)

data = json.loads(result.stdout)
print(f"Critical angle: {data[0]['critical_angle_degrees']}")

With Shell Scripts:

#!/bin/bash

# Process multiple materials
for material in Si Al Cu; do
    echo "Processing $material..."
    xraylabtool calc $material --density 2.33 --energy 8000 --output csv >> results.csv
done