Metadata-Version: 2.4
Name: torchvsw
Version: 0.2.1
Summary: T-matrix extraction workflows for TorchGDM and sampled fields
Author-email: "Peter R. Wiecha" <pwiecha@laas.fr>
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://gitlab.com/wiechapeter/torchtmat
Project-URL: Documentation, https://wiechapeter.gitlab.io/torchtmat
Project-URL: Changelog, https://gitlab.com/wiechapeter/torchtmat/-/blob/main/CHANGELOG.md
Project-URL: Issues, https://gitlab.com/wiechapeter/torchtmat/-/issues
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Physics
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: h5py
Requires-Dist: numpy
Requires-Dist: scipy
Requires-Dist: torch
Requires-Dist: tqdm
Provides-Extra: torchgdm
Requires-Dist: torchgdm; extra == "torchgdm"
Provides-Extra: validation
Requires-Dist: treams; extra == "validation"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Provides-Extra: doc
Requires-Dist: sphinx; extra == "doc"
Requires-Dist: nbsphinx; extra == "doc"
Requires-Dist: myst-parser; extra == "doc"
Dynamic: license-file

# torchvsw

Torch-first toolkit for autodiff-capable T-matrix extraction from sampled
fields and TorchGDM workflows.

**Documentation**: <https://wiechapeter.gitlab.io/torchtmat> — source code:
<https://gitlab.com/wiechapeter/torchtmat>.

A T-matrix is the matrix that maps an incoming light field to the field a
particle scatters back. This package fits that matrix from simulated or
measured fields. It uses torch tensors throughout, so the gradient of a
T-matrix flows back to the material and geometry parameters of your model.
The waves use vector spherical harmonics (VSH), which are the spherical-wave
basis of the field.

## Conventions, and a note on reciprocity

Every mode of degree l is scaled by i/sqrt(l(l+1)), so the VSH basis and the
extracted T-matrices follow the treams / published HDF5 T-matrix format
convention exactly.

Reciprocity of the material does **not** mean that the T-matrix is symmetric
under transposition. For a reciprocal object the T-matrix satisfies
(arXiv:2408.10727, Eq. 21)

    T[(l, m, p), (l', m', p')] = (-1)^(m + m') * T[(l', -m', p'), (l, -m, p)]

with only the sign of m flipped and the polarization kept. A perfectly
reciprocal object generally has a strongly non-symmetric T-matrix (any object
placed off the coordinate origin, or a cluster without special symmetry). Use
`reciprocity_residual` to check an extracted T-matrix against this relation; a
residual of the order of the reported fit `rel_error` is expected, while plain
`T.T` symmetry is not.

## Install

You need Python 3.10 or newer, and PyTorch. The package is on PyPI:

```bash
pip install torchvsw                 # core: pulls numpy, scipy, h5py, tqdm
pip install "torchvsw[torchgdm]"     # + TorchGDM, the solver behind the main workflow
pip install "torchvsw[validation]"   # + treams, for analytic cross-checks
pip install "torchvsw[dev,doc]"      # + pytest and the Sphinx tool chain
```

Or install from source (PyTorch is required):

```bash
pip install -e .
```

## Quick start

One discretized sphere, and its T-matrix:

```python
import torch
import torchgdm as tg
from torchvsw import extract_tmatrix_from_simulation

sphere = tg.struct3d.StructDiscretizedHexagonal3D(
    discretization_config=tg.struct3d.sphere(r=80.0 / 15.0),  # radius / step
    step=15.0,
    materials=tg.materials.MatConstant(torch.tensor(4.0)),
)
sim = tg.Simulation(
    structures=[sphere],
    illumination_fields=[],
    environment=tg.env.EnvHomogeneous3D(1.0),
    wavelengths=torch.as_tensor([600.0]),
)
result = extract_tmatrix_from_simulation(
    simulation=sim,
    r_enclosing_nm=160.0,
    lmax=2,
    run_kwargs={"progress_bar": False, "verbose": 0},
)
print(result.t_matrix.shape)   # (16, 16), the 16 VSH modes up to lmax = 2
```

This takes about one second on a CPU. Example
`examples/01_torchgdm_simulation_to_tmatrix.py` runs the same case with plots
and diagnostics.

## Main API

Main public entry points:

- `extract_tmatrix_from_simulation(...)`
  - Takes a TorchGDM `Simulation`, builds full-basis VSH illuminations, probes fields on an enclosing sphere (`r_enclosing_nm`), and returns the extracted T-matrix.
- `export_tmatrix_hdf5_from_simulation(...)`
  - One-call path: TorchGDM simulation -> extracted T-matrix -> `.tmat.h5`.
  - Optional post-write validator run (`run_validation=True/False`).
- `prepare_full_vsh_illumination_setup(...)`
  - Returns both:
    - the TorchGDM illumination objects and
    - the matching incident fields at custom probe points.
- `extract_tmatrix_from_scattered_fields(...)`
  - Reconstructs the T-matrix from sampled scattered fields (torch-native, autograd-compatible).
- `export_tmatrix_hdf5(...)`
  - Write a T-matrix and metadata into `.tmat.h5` format.

Support helpers:

- `sphere_surface_points(radius_nm, lebedev_order=...)`
- `validate_tmatrix_file(path)`
- `field_matrix_from_modes(...)` and `extract_tmatrix_from_field_samples(...)`, the two low-level
  steps the functions above combine: build the mode matrix, then fit it.

Maintained submodules:

- `torchvsw.workflows`: default torch-first workflows.
- `torchvsw.core`: low-level extraction numerics.
- `torchvsw.tools`: export, sampling, and validator helpers.
- `torchvsw.torch_vsh`: canonical full-basis VSH implementation.


## Typical workflows

1. End-to-end:
   - `Simulation -> extract_tmatrix_from_simulation -> T-matrix`.
2. Split pipeline:
   - (optional) `prepare_full_vsh_illumination_setup` to get clean illuminations + incident fields at points,
   - run any solver to get scattered fields,
   - call `extract_tmatrix_from_scattered_fields`.

## Examples and Docs

- Jupyter-script type examples are in `examples/`
- Documentation is in `doc/` and uses Sphinx + autosummary + sphinx-gallery.
- The website includes an auto-generated example gallery from `examples/`
  (examples `01` to `07`).

Build docs:

```bash
cd doc
pip install -r requirements.txt
make html
```

## Run tests

```bash
pytest tests -q
```

The suite needs TorchGDM and `treams`. Expect `82 passed, 2 failed`. The two
failures are in `test_pymiediff_gpm_workflow.py`, because the installed
pymiediff imports a TorchGDM module that no longer exists. They are not caused
by this package.

## Version, license, authors

- Version: `0.2.1` in `pyproject.toml`, also readable as `torchvsw.__version__`.
  Release notes are in
  [CHANGELOG.md](https://gitlab.com/wiechapeter/torchtmat/-/blob/main/CHANGELOG.md),
  also rendered in the documentation under "Changelog".
- License: GNU General Public License v3.0 or later, see
  [LICENSE](https://gitlab.com/wiechapeter/torchtmat/-/blob/main/LICENSE).
  TorchGDM is GPL-3 too, and the other dependencies are BSD or MIT licensed.
- Author: Peter R. Wiecha (`pwiecha@laas.fr`).
