xraylabtool


Namexraylabtool JSON
Version 0.1.4 PyPI version JSON
download
home_pageNone
SummaryMaterial Property Calculations for X-ray Interactions - A Python package for calculating X-ray optical properties of materials
upload_time2025-08-14 15:38:08
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseMIT
keywords xray crystallography diffraction scattering laboratory synchrotron optics materials cxro nist
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # XRayLabTool

[![PyPI version](https://badge.fury.io/py/xraylabtool.svg)](https://badge.fury.io/py/xraylabtool)
[![Python versions](https://img.shields.io/pypi/pyversions/xraylabtool.svg)](https://pypi.org/project/xraylabtool/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://pepy.tech/badge/xraylabtool)](https://pepy.tech/project/xraylabtool)

**Material Property Calculations for X-ray Interactions**

`XRayLabTool` is a Python package that provides functions to calculate X-ray optical properties of materials based on their chemical formulas and densities. It is particularly useful for synchrotron scientists, materials researchers, and X-ray optics developers.

---

## 📆 Features

- Compute optical constants (δ, β), scattering factors (f1, f2), and other X-ray interaction parameters
- Support for both single and multiple material calculations
- Easy-to-use dataclass-based output
- Based on CXRO/NIST data tables
- Vectorized calculations using NumPy for high performance
- Built-in caching system for atomic scattering factor data
- **NEW**: Enhanced robustness with complex number handling
- **NEW**: Improved type safety and error handling
- **NEW**: Updated pandas compatibility for modern versions
- **NEW**: PCHIP interpolation for accurate scattering factor calculations
- **NEW**: Comprehensive test suite with 100% coverage

---

## 📦 Installation

### From PyPI (Recommended)

```bash
pip install xraylabtool
```

### From Source (Development)

```bash
git clone https://github.com/imewei/pyXRayLabTool.git
cd pyXRayLabTool
pip install -e .
```

### Requirements

- Python ≥ 3.12
- NumPy ≥ 1.20.0
- SciPy ≥ 1.7.0
- Pandas ≥ 1.3.0
- Mendeleev ≥ 0.10.0
- tqdm ≥ 4.60.0
- matplotlib ≥ 3.4.0 (optional, for plotting)

---

## 🚀 Quick Start

### Single Material

```python
import xraylabtool as xlt

# Calculate properties for quartz at multiple X-ray energies
result = xlt.calculate_sub_refraction("SiO2", [8.0, 10.0, 12.0], 2.2)
print(f"Molecular weight: {result.MW:.2f} g/mol")
print(f"Critical angles: {result.Critical_Angle} degrees")
```

### Multiple Materials

```python
import xraylabtool as xlt

# Compare properties of different materials
formulas = ["SiO2", "Al2O3", "Fe2O3"]
densities = [2.2, 3.95, 5.24]
energies = [8.0, 10.0, 12.0]

results = xlt.calculate_refraction(formulas, energies, densities)
for formula, result in results.items():
    print(f"{formula}: MW = {result.MW:.2f} g/mol")
```

### Accessing Results

```python
# Access individual properties
result = xlt.calculate_sub_refraction("SiO2", 10.0, 2.2)
print(f"Formula: {result.Formula}")
print(f"Molecular Weight: {result.MW:.2f} g/mol")
print(f"Electron Density: {result.Electron_Density:.4f} electrons/ų")
print(f"Dispersion coefficient: {result.Dispersion[0]:.2e}")
print(f"Absorption coefficient: {result.Absorption[0]:.2e}")
```

---

## 📥 Input Parameters

| Parameter    | Type                                  | Description                                                    |
| ------------ | ------------------------------------- | -------------------------------------------------------------- |
| `formula(s)` | `str` or `List[str]`                  | Case-sensitive chemical formula(s), e.g., `"CO"` vs `"Co"`     |
| `energy`     | `float`, `List[float]`, or `np.array` | X-ray photon energies in keV (valid range: **0.03–30 keV**)   |
| `density`    | `float` or `List[float]`              | Mass density in g/cm³ (one per formula)                       |

---

## 📤 Output: `XRayResult` Dataclass

The `XRayResult` dataclass contains all computed X-ray optical properties:

- `Formula: str` – Chemical formula
- `MW: float` – Molecular weight (g/mol)
- `Number_Of_Electrons: float` – Total electrons per molecule
- `Density: float` – Mass density (g/cm³)
- `Electron_Density: float` – Electron density (electrons/ų)
- `Energy: np.ndarray` – X-ray energies (keV)
- `Wavelength: np.ndarray` – X-ray wavelengths (Å)
- `Dispersion: np.ndarray` – Dispersion coefficient δ
- `Absorption: np.ndarray` – Absorption coefficient β
- `f1: np.ndarray` – Real part of atomic scattering factor
- `f2: np.ndarray` – Imaginary part of atomic scattering factor
- `Critical_Angle: np.ndarray` – Critical angles (degrees)
- `Attenuation_Length: np.ndarray` – Attenuation lengths (cm)
- `reSLD: np.ndarray` – Real scattering length density (Å⁻²)
- `imSLD: np.ndarray` – Imaginary scattering length density (Å⁻²)

---

## 📘 Detailed Examples

### Basic Usage

```python
import xraylabtool as xlt
import numpy as np

# Single energy calculation
result = xlt.calculate_sub_refraction("SiO2", 10.0, 2.33)
print(f"Formula: {result.Formula}")                    # "SiO2"
print(f"Molecular weight: {result.MW:.2f} g/mol")     # 60.08 g/mol
print(f"Dispersion: {result.Dispersion[0]:.2e}")       # δ value
print(f"Critical angle: {result.Critical_Angle[0]:.3f}°")  # θc
```

### Energy Range Scan

```python
# Energy range with numpy
energies = np.linspace(8.0, 12.0, 21)  # 21 points from 8-12 keV
result = xlt.calculate_sub_refraction("SiO2", energies, 2.33)

print(f"Energy range: {result.Energy[0]:.1f} - {result.Energy[-1]:.1f} keV")
print(f"Number of points: {len(result.Energy)}")
```

### Multiple Materials Analysis

```python
# Common X-ray optics materials
materials = {
    "SiO2": 2.2,      # Fused silica
    "Si": 2.33,       # Silicon
    "Al2O3": 3.95,    # Sapphire
    "C": 3.52,  # Diamond
}

formulas = list(materials.keys())
densities = list(materials.values())
energy = 10.0  # keV (Cu Kα)

results = xlt.calculate_refraction(formulas, energy, densities)

# Compare critical angles
for formula, result in results.items():
    print(f"{formula:8}: θc = {result.Critical_Angle[0]:.3f}°, "
          f"δ = {result.Dispersion[0]:.2e}")
```

### Plotting Results

```python
import matplotlib.pyplot as plt

# Energy-dependent properties
energies = np.logspace(np.log10(1), np.log10(20), 100)
result = xlt.calculate_sub_refraction("Si", energies, 2.33)

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))

# Plot optical constants
ax1.loglog(result.Energy, np.abs(result.Dispersion), label='|δ|')
ax1.loglog(result.Energy, result.Absorption, label='β')
ax1.set_xlabel('Energy (keV)')
ax1.set_ylabel('Optical constants')
ax1.legend()
ax1.grid(True, alpha=0.3)

# Plot critical angle
ax2.loglog(result.Energy, result.Critical_Angle)
ax2.set_xlabel('Energy (keV)')
ax2.set_ylabel('Critical angle (°)')
ax2.grid(True, alpha=0.3)

plt.tight_layout()
plt.show()
```

---

## 🔗 References

- [CXRO - Center for X-ray Optics](http://www.cxro.lbl.gov)
- [NIST - National Institute of Standards and Technology](http://www.nist.gov)

> This Python package is ported from a Julia module, which was translated from a MATLAB script originally developed by **Zhang Jiang** at the **Advanced Photon Source**, Argonne National Laboratory.

---


## 🧪 License

MIT License

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "xraylabtool",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": null,
    "keywords": "xray, crystallography, diffraction, scattering, laboratory, synchrotron, optics, materials, cxro, nist",
    "author": null,
    "author_email": "Wei Chen <wchen@anl.gov>",
    "download_url": "https://files.pythonhosted.org/packages/d8/e5/e8bcfd87ff6998b600c8e6d8c290c4fdfb626b7fe659a727cd91d433d3ab/xraylabtool-0.1.4.tar.gz",
    "platform": null,
    "description": "# XRayLabTool\n\n[![PyPI version](https://badge.fury.io/py/xraylabtool.svg)](https://badge.fury.io/py/xraylabtool)\n[![Python versions](https://img.shields.io/pypi/pyversions/xraylabtool.svg)](https://pypi.org/project/xraylabtool/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Downloads](https://pepy.tech/badge/xraylabtool)](https://pepy.tech/project/xraylabtool)\n\n**Material Property Calculations for X-ray Interactions**\n\n`XRayLabTool` is a Python package that provides functions to calculate X-ray optical properties of materials based on their chemical formulas and densities. It is particularly useful for synchrotron scientists, materials researchers, and X-ray optics developers.\n\n---\n\n## \ud83d\udcc6 Features\n\n- Compute optical constants (\u03b4, \u03b2), scattering factors (f1, f2), and other X-ray interaction parameters\n- Support for both single and multiple material calculations\n- Easy-to-use dataclass-based output\n- Based on CXRO/NIST data tables\n- Vectorized calculations using NumPy for high performance\n- Built-in caching system for atomic scattering factor data\n- **NEW**: Enhanced robustness with complex number handling\n- **NEW**: Improved type safety and error handling\n- **NEW**: Updated pandas compatibility for modern versions\n- **NEW**: PCHIP interpolation for accurate scattering factor calculations\n- **NEW**: Comprehensive test suite with 100% coverage\n\n---\n\n## \ud83d\udce6 Installation\n\n### From PyPI (Recommended)\n\n```bash\npip install xraylabtool\n```\n\n### From Source (Development)\n\n```bash\ngit clone https://github.com/imewei/pyXRayLabTool.git\ncd pyXRayLabTool\npip install -e .\n```\n\n### Requirements\n\n- Python \u2265 3.12\n- NumPy \u2265 1.20.0\n- SciPy \u2265 1.7.0\n- Pandas \u2265 1.3.0\n- Mendeleev \u2265 0.10.0\n- tqdm \u2265 4.60.0\n- matplotlib \u2265 3.4.0 (optional, for plotting)\n\n---\n\n## \ud83d\ude80 Quick Start\n\n### Single Material\n\n```python\nimport xraylabtool as xlt\n\n# Calculate properties for quartz at multiple X-ray energies\nresult = xlt.calculate_sub_refraction(\"SiO2\", [8.0, 10.0, 12.0], 2.2)\nprint(f\"Molecular weight: {result.MW:.2f} g/mol\")\nprint(f\"Critical angles: {result.Critical_Angle} degrees\")\n```\n\n### Multiple Materials\n\n```python\nimport xraylabtool as xlt\n\n# Compare properties of different materials\nformulas = [\"SiO2\", \"Al2O3\", \"Fe2O3\"]\ndensities = [2.2, 3.95, 5.24]\nenergies = [8.0, 10.0, 12.0]\n\nresults = xlt.calculate_refraction(formulas, energies, densities)\nfor formula, result in results.items():\n    print(f\"{formula}: MW = {result.MW:.2f} g/mol\")\n```\n\n### Accessing Results\n\n```python\n# Access individual properties\nresult = xlt.calculate_sub_refraction(\"SiO2\", 10.0, 2.2)\nprint(f\"Formula: {result.Formula}\")\nprint(f\"Molecular Weight: {result.MW:.2f} g/mol\")\nprint(f\"Electron Density: {result.Electron_Density:.4f} electrons/\u00c5\u00b3\")\nprint(f\"Dispersion coefficient: {result.Dispersion[0]:.2e}\")\nprint(f\"Absorption coefficient: {result.Absorption[0]:.2e}\")\n```\n\n---\n\n## \ud83d\udce5 Input Parameters\n\n| Parameter    | Type                                  | Description                                                    |\n| ------------ | ------------------------------------- | -------------------------------------------------------------- |\n| `formula(s)` | `str` or `List[str]`                  | Case-sensitive chemical formula(s), e.g., `\"CO\"` vs `\"Co\"`     |\n| `energy`     | `float`, `List[float]`, or `np.array` | X-ray photon energies in keV (valid range: **0.03\u201330 keV**)   |\n| `density`    | `float` or `List[float]`              | Mass density in g/cm\u00b3 (one per formula)                       |\n\n---\n\n## \ud83d\udce4 Output: `XRayResult` Dataclass\n\nThe `XRayResult` dataclass contains all computed X-ray optical properties:\n\n- `Formula: str` \u2013 Chemical formula\n- `MW: float` \u2013 Molecular weight (g/mol)\n- `Number_Of_Electrons: float` \u2013 Total electrons per molecule\n- `Density: float` \u2013 Mass density (g/cm\u00b3)\n- `Electron_Density: float` \u2013 Electron density (electrons/\u00c5\u00b3)\n- `Energy: np.ndarray` \u2013 X-ray energies (keV)\n- `Wavelength: np.ndarray` \u2013 X-ray wavelengths (\u00c5)\n- `Dispersion: np.ndarray` \u2013 Dispersion coefficient \u03b4\n- `Absorption: np.ndarray` \u2013 Absorption coefficient \u03b2\n- `f1: np.ndarray` \u2013 Real part of atomic scattering factor\n- `f2: np.ndarray` \u2013 Imaginary part of atomic scattering factor\n- `Critical_Angle: np.ndarray` \u2013 Critical angles (degrees)\n- `Attenuation_Length: np.ndarray` \u2013 Attenuation lengths (cm)\n- `reSLD: np.ndarray` \u2013 Real scattering length density (\u00c5\u207b\u00b2)\n- `imSLD: np.ndarray` \u2013 Imaginary scattering length density (\u00c5\u207b\u00b2)\n\n---\n\n## \ud83d\udcd8 Detailed Examples\n\n### Basic Usage\n\n```python\nimport xraylabtool as xlt\nimport numpy as np\n\n# Single energy calculation\nresult = xlt.calculate_sub_refraction(\"SiO2\", 10.0, 2.33)\nprint(f\"Formula: {result.Formula}\")                    # \"SiO2\"\nprint(f\"Molecular weight: {result.MW:.2f} g/mol\")     # 60.08 g/mol\nprint(f\"Dispersion: {result.Dispersion[0]:.2e}\")       # \u03b4 value\nprint(f\"Critical angle: {result.Critical_Angle[0]:.3f}\u00b0\")  # \u03b8c\n```\n\n### Energy Range Scan\n\n```python\n# Energy range with numpy\nenergies = np.linspace(8.0, 12.0, 21)  # 21 points from 8-12 keV\nresult = xlt.calculate_sub_refraction(\"SiO2\", energies, 2.33)\n\nprint(f\"Energy range: {result.Energy[0]:.1f} - {result.Energy[-1]:.1f} keV\")\nprint(f\"Number of points: {len(result.Energy)}\")\n```\n\n### Multiple Materials Analysis\n\n```python\n# Common X-ray optics materials\nmaterials = {\n    \"SiO2\": 2.2,      # Fused silica\n    \"Si\": 2.33,       # Silicon\n    \"Al2O3\": 3.95,    # Sapphire\n    \"C\": 3.52,  # Diamond\n}\n\nformulas = list(materials.keys())\ndensities = list(materials.values())\nenergy = 10.0  # keV (Cu K\u03b1)\n\nresults = xlt.calculate_refraction(formulas, energy, densities)\n\n# Compare critical angles\nfor formula, result in results.items():\n    print(f\"{formula:8}: \u03b8c = {result.Critical_Angle[0]:.3f}\u00b0, \"\n          f\"\u03b4 = {result.Dispersion[0]:.2e}\")\n```\n\n### Plotting Results\n\n```python\nimport matplotlib.pyplot as plt\n\n# Energy-dependent properties\nenergies = np.logspace(np.log10(1), np.log10(20), 100)\nresult = xlt.calculate_sub_refraction(\"Si\", energies, 2.33)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))\n\n# Plot optical constants\nax1.loglog(result.Energy, np.abs(result.Dispersion), label='|\u03b4|')\nax1.loglog(result.Energy, result.Absorption, label='\u03b2')\nax1.set_xlabel('Energy (keV)')\nax1.set_ylabel('Optical constants')\nax1.legend()\nax1.grid(True, alpha=0.3)\n\n# Plot critical angle\nax2.loglog(result.Energy, result.Critical_Angle)\nax2.set_xlabel('Energy (keV)')\nax2.set_ylabel('Critical angle (\u00b0)')\nax2.grid(True, alpha=0.3)\n\nplt.tight_layout()\nplt.show()\n```\n\n---\n\n## \ud83d\udd17 References\n\n- [CXRO - Center for X-ray Optics](http://www.cxro.lbl.gov)\n- [NIST - National Institute of Standards and Technology](http://www.nist.gov)\n\n> This Python package is ported from a Julia module, which was translated from a MATLAB script originally developed by **Zhang Jiang** at the **Advanced Photon Source**, Argonne National Laboratory.\n\n---\n\n\n## \ud83e\uddea License\n\nMIT License\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Material Property Calculations for X-ray Interactions - A Python package for calculating X-ray optical properties of materials",
    "version": "0.1.4",
    "project_urls": {
        "Bug Reports": "https://github.com/imewei/pyXRayLabTool/issues",
        "Changelog": "https://github.com/imewei/pyXRayLabTool/blob/main/docs/source/changelog.rst",
        "Documentation": "https://pyxraylabtool.readthedocs.io",
        "Homepage": "https://github.com/imewei/pyXRayLabTool",
        "Issues": "https://github.com/imewei/pyXRayLabTool/issues",
        "Repository": "https://github.com/imewei/pyXRayLabTool.git"
    },
    "split_keywords": [
        "xray",
        " crystallography",
        " diffraction",
        " scattering",
        " laboratory",
        " synchrotron",
        " optics",
        " materials",
        " cxro",
        " nist"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f3c438e0fb686adf7474f150a347e4a459765c8b2845ccb7616a448a85581325",
                "md5": "6149944fe78c3242069a8765d640d154",
                "sha256": "7fbd4da58e011eab35f3862440e8a75e8a729a0e2e718dca5536b40217a62999"
            },
            "downloads": -1,
            "filename": "xraylabtool-0.1.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6149944fe78c3242069a8765d640d154",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 513593,
            "upload_time": "2025-08-14T15:38:07",
            "upload_time_iso_8601": "2025-08-14T15:38:07.438188Z",
            "url": "https://files.pythonhosted.org/packages/f3/c4/38e0fb686adf7474f150a347e4a459765c8b2845ccb7616a448a85581325/xraylabtool-0.1.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "d8e5e8bcfd87ff6998b600c8e6d8c290c4fdfb626b7fe659a727cd91d433d3ab",
                "md5": "459be8ca0e505ef8011ff89a9e8b0efa",
                "sha256": "e4b2cbb9428690747a9a5131c0f5f5dda326ce8f0a04ae6dcb4f2d538042d32b"
            },
            "downloads": -1,
            "filename": "xraylabtool-0.1.4.tar.gz",
            "has_sig": false,
            "md5_digest": "459be8ca0e505ef8011ff89a9e8b0efa",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 464010,
            "upload_time": "2025-08-14T15:38:08",
            "upload_time_iso_8601": "2025-08-14T15:38:08.914484Z",
            "url": "https://files.pythonhosted.org/packages/d8/e5/e8bcfd87ff6998b600c8e6d8c290c4fdfb626b7fe659a727cd91d433d3ab/xraylabtool-0.1.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-14 15:38:08",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "imewei",
    "github_project": "pyXRayLabTool",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "xraylabtool"
}
        
Elapsed time: 0.87592s