Metadata-Version: 2.4
Name: pyspeckle
Version: 1.0.0
Summary: Routines for creating and analyzing laser speckle
Author-email: Scott Prahl <scott.prahl@oit.edu>
License-Expression: MIT
Project-URL: Homepage, https://github.com/scottprahl/pyspeckle
Project-URL: Documentation, https://pyspeckle2.readthedocs.io
Project-URL: Source, https://github.com/scottprahl/pyspeckle
Project-URL: Tracker, https://github.com/scottprahl/pyspeckle/issues
Project-URL: Changelog, https://github.com/scottprahl/pyspeckle/blob/main/CHANGELOG.rst
Keywords: speckle,objective,subjective,contrast,size,autocorrelation,ACF,PDF,laser
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Requires-Python: >=3.11
Description-Content-Type: text/x-rst
License-File: LICENSE.txt
Requires-Dist: numpy
Requires-Dist: matplotlib
Requires-Dist: scipy
Provides-Extra: docs
Requires-Dist: Sphinx>=8.1.3; extra == "docs"
Requires-Dist: nbsphinx>=0.9.7; extra == "docs"
Requires-Dist: sphinx_automodapi; extra == "docs"
Requires-Dist: sphinx_rtd_theme; extra == "docs"
Requires-Dist: ipython; extra == "docs"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-cov; extra == "dev"
Requires-Dist: imageio; extra == "dev"
Requires-Dist: requests; extra == "dev"
Requires-Dist: ruff; extra == "dev"
Requires-Dist: yamllint; extra == "dev"
Requires-Dist: rstcheck[sphinx,toml]; extra == "dev"
Requires-Dist: pylint; extra == "dev"
Requires-Dist: pyroma; extra == "dev"
Requires-Dist: black[jupyter]; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: check-manifest; extra == "dev"
Requires-Dist: libarchive-c; extra == "dev"
Requires-Dist: pyyaml; extra == "dev"
Requires-Dist: jupyterlab; extra == "dev"
Requires-Dist: nbconvert; extra == "dev"
Requires-Dist: nbformat; extra == "dev"
Provides-Extra: lite
Requires-Dist: jupyterlite-core<0.8,>=0.7; extra == "lite"
Requires-Dist: jupyterlite-pyodide-kernel<0.8,>=0.7; extra == "lite"
Dynamic: license-file

.. |test-badge| image:: https://github.com/scottprahl/pyspeckle/actions/workflows/test.yaml/badge.svg
   :target: https://github.com/scottprahl/pyspeckle/actions/workflows/test.yaml
   :alt: Testing

.. |coverage-badge| image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/scottprahl/pyspeckle/badges/coverage.json
   :target: https://github.com/scottprahl/pyspeckle/actions/workflows/test.yaml
   :alt: Coverage

.. |pypi-badge| image:: https://img.shields.io/pypi/v/pyspeckle?color=4c1
   :target: https://pypi.org/project/pyspeckle/
   :alt: PyPI

.. |pyversions-badge| image:: https://img.shields.io/pypi/pyversions/pyspeckle?color=4c1
   :target: https://pypi.org/project/pyspeckle/
   :alt: Python versions

.. |conda-badge| image:: https://img.shields.io/conda/vn/conda-forge/pyspeckle?label=conda&color=4c1
   :target: https://github.com/conda-forge/pyspeckle-feedstock
   :alt: Conda

.. |downloads-badge| image:: https://img.shields.io/pypi/dm/pyspeckle?color=4c1
   :target: https://pypi.org/project/pyspeckle/
   :alt: Downloads

.. |license-badge| image:: https://img.shields.io/github/license/scottprahl/pyspeckle?color=4c1
   :target: https://github.com/scottprahl/pyspeckle/blob/main/LICENSE.txt
   :alt: License

.. |readthedocs-badge| image:: https://readthedocs.org/projects/pyspeckle2/badge
   :target: https://pyspeckle2.readthedocs.io
   :alt: Docs

.. |doi-badge| image:: https://img.shields.io/badge/DOI-10.5281%2Fzenodo.8311677-4c1
   :target: https://doi.org/10.5281/zenodo.8311677
   :alt: DOI

.. |lite-badge| image:: https://img.shields.io/badge/try-JupyterLite-4c1.svg
   :target: https://scottprahl.github.io/pyspeckle/
   :alt: Try JupyterLite


pyspeckle
=========

=================  =====================================================================
**Testing**        |test-badge| |coverage-badge|
**Package**        |pypi-badge| |conda-badge| |pyversions-badge| |downloads-badge|
**Documentation**  |readthedocs-badge| |doi-badge| |license-badge|
**Explore**        |lite-badge|
=================  =====================================================================

**pyspeckle** is a Python library for generating and analyzing laser speckle fields.
It provides reproducible numerical implementations of physically motivated speckle models used in
optical metrology, coherent imaging, and biomedical photonics.

The methods implemented in this package are derived from Duncan and
Kirkpatrick's *Algorithms for simulation of speckle (laser and otherwise)*
(2008), and the motion of speckle from a deforming target follows Yamaguchi's
*Speckle displacement and decorrelation in the diffraction and image fields
for small object deformation* (1981), both cited below.
The package provides:

- **fully developed speckle** in one, two, or three dimensions, polarized
  (exponential irradiance, contrast 1) or unpolarized (gamma-2, contrast 1/√2)
- **objective and subjective speckle**, which share one construction: the
  aperture is the illuminated spot for objective speckle and the imaging pupil
  for subjective speckle.  Ellipses, rectangles, and annuli are built in, and
  any other pupil can be supplied as an array
- **dynamic speckle**: rigid translation by any fraction of a pixel per frame,
  decorrelation in place to a chosen sequence of correlation coefficients
  (the Gaussian copula of Duncan & Kirkpatrick), and the boiling seen in the
  focal plane as the target moves
- **speckle from a deforming target**: an imaged surface that is translated,
  strained, rotated, tilted, or moved by any displacement field you supply,
  lit by a collimated beam or a point source, and viewed in or out of focus,
  telecentrically or not, at any magnification.  The speckle moves and
  decorrelates as Yamaguchi's theory predicts
- **OCT B-scans** whose contrast and mean irradiance fall with depth
- **correlated Gaussian fields and phase screens** for rough surfaces and
  partially developed speckle
- **analysis**: local contrast, autocorrelation, and plots of first- and
  second-order statistics

Scientific Context
------------------

Coherent imaging systems—including SAR, OCT, ultrasound, ESPI, and laser speckle contrast
imaging—produce granular interference patterns defined by the random phase relationships of scattered waves.
A short example for each field is given under `Examples by field`_ below.

Representative Outputs
----------------------

1D speckle
~~~~~~~~~~

.. image:: https://raw.githubusercontent.com/scottprahl/pyspeckle/main/docs/images/oneD_example.png
   :alt: synthetic 1D speckle intensity profile

2D speckle
~~~~~~~~~~

.. image:: https://raw.githubusercontent.com/scottprahl/pyspeckle/main/docs/images/twoD_speckle.png
   :alt: simulated 2D speckle field

Documentation
-------------

Full documentation and algorithm demonstrations are available at:

https://pyspeckle2.readthedocs.io

Try in JupyterLite (no install required):

https://scottprahl.github.io/pyspeckle/


Installation
------------

``pip``::

   pip install pyspeckle

``conda``::

   conda install -c conda-forge pyspeckle


Quick start
-----------

.. code-block:: python

   import matplotlib.pyplot as plt
   import numpy as np
   import pyspeckle

   # a 256 x 256 pattern with four pixels across the smallest speckle
   speckle = pyspeckle.create_exponential((256, 256), 4, rng=0)

   # contrast over 7 x 7 windows, and of the whole pattern (close to 1)
   local, overall = pyspeckle.local_contrast(speckle, np.ones((7, 7)))

   pyspeckle.statistics_plot(speckle)
   plt.show()


Examples by field
-----------------

The speckle generators return irradiance scaled to a maximum of one (the OCT
B-scan excepted), and all accept ``rng`` as a seed or ``numpy.random.Generator`` for reproducible
output.

Synthetic aperture radar (SAR)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A single-look SAR image of a distributed target is fully developed speckle,
with exponential intensity and contrast 1.  Averaging *L* independent looks
trades resolution for a contrast of 1/√L:

.. code-block:: python

   import numpy as np
   import pyspeckle

   rng = np.random.default_rng(0)
   looks = [pyspeckle.create_exponential((256, 256), 2, rng=rng) for _ in range(4)]
   single, multi = looks[0], np.mean(looks, axis=0)
   print(single.std() / single.mean())  # 1.00
   print(multi.std() / multi.mean())    # 0.50, four looks

Optical coherence tomography (OCT)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A B-scan whose rows are depth.  Multiply scattered light lowers the speckle
contrast from 1 at the surface toward 1/√2, while the mean signal decays as
exp(-μ\ :sub:`eff` z):

.. code-block:: python

   import pyspeckle

   # aorta by default: mua = 2/cm, musp = 30/cm, 1/300 cm per row
   image, depth, contrast = pyspeckle.create_oct_speckle((256, 256), 4, rng=0)
   print(contrast[0], contrast[-1])  # 1.0 at the surface, 0.707 at depth

Medical ultrasound
~~~~~~~~~~~~~~~~~~

B-mode images display the envelope (amplitude) of the echo, which for fully
developed speckle is Rayleigh distributed with a mean-to-standard-deviation
ratio of 1.91.  The resolution cell is finer in depth than laterally, so the
speckle is elongated across the image:

.. code-block:: python

   import numpy as np
   import pyspeckle

   # rows are depth; alpha = 3 makes speckle three times longer laterally
   envelope = np.sqrt(pyspeckle.create_exponential((256, 256), 4, alpha=3, rng=0))
   bmode = 20 * np.log10(envelope / envelope.max())  # log-compressed display, dB
   print(envelope.mean() / envelope.std())           # about 1.9

Speckle metrology (ESPI, speckle photography, digital image correlation)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These methods measure deformation from how the speckle of an imaged surface
moves, and they fail when it decorrelates.  ``create_deformed_speckle`` moves
the surface itself and forms the image again for each frame, so both effects
come out as Yamaguchi derived them: in focus the speckle follows the surface;
out of focus it also drifts with the illumination geometry, by
``defocus * grad[(l_s + z) . a]``, the drift that biases defocused speckle
photography.  Lengths are in object pixels, and the target is padded so that
nothing wraps around:

.. code-block:: python

   import numpy as np
   import pyspeckle

   shape = (256, 256)

   # 0.2% horizontal strain and 1 mrad rotation per frame, in focus
   cube = pyspeckle.create_deformed_speckle(shape, 4, frames=3, strain=0.002, rotation=0.001, rng=0)

   # in-plane and out-of-plane translation lit by a point source 2000 pixels
   # above the target, imaged 500 pixels out of focus
   cube = pyspeckle.create_deformed_speckle(
       shape, 4, frames=2, translation=(0, 2), axial=5, source=(0, 0, 2000), defocus=-500, rng=0
   )

   # any displacement field: a local bulge that also pushes out of plane,
   # lit from 17 degrees off the normal
   def bulge(k, y, x):
       w = k * 2 * np.exp(-(x**2 + y**2) / 50**2)
       return 0 * w, w, 10 * w  # displacement along y, x, and toward the lens

   cube = pyspeckle.create_deformed_speckle(shape, 4, frames=2, displacement=bulge, illumination=0.3, rng=0)

Shear, tilt, magnification, and non-telecentric imaging are keyword arguments
too; the docstring lists them all.

Laser speckle contrast imaging (LSCI)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Moving scatterers such as blood cells make speckle boil.  A camera exposure
averages the changing pattern, and the shorter the decorrelation time compared
with the exposure, the lower the contrast:

.. code-block:: python

   import numpy as np
   import pyspeckle

   # 129 frames take the pattern from fully correlated to fully decorrelated
   cube, correlation, theory = pyspeckle.create_boiling_speckle((128, 128), 4, rng=0)
   for n in (1, 32, 128):
       exposure = cube[..., :n].mean(axis=-1)
       local, overall = pyspeckle.local_contrast(exposure, np.ones((7, 7)))
       print(n, overall)  # 1.01, 0.91, 0.68

``local`` is the contrast map, computed over 7 × 7 windows, that LSCI displays
as a perfusion image.


Dynamic speckle
---------------

These generators return a sequence with frames on the last axis, so
``sequence[:, :, k]`` is frame ``k``. A scalar shift or strain acts along the
horizontal (x) direction.

.. code-block:: python

   import pyspeckle

   shape = (64, 64)

   # Move the same pattern half a pixel to the right per frame.
   translated = pyspeckle.create_translating_speckle(
       shape, 4, shift=0.5, frames=5, rng=0
   )

   # Choose each frame's intensity correlation with the reference frame.
   wanted = [1, 0.75, 0.5, 0.25, 0]
   decorrelated, measured = pyspeckle.create_decorrelating_speckle(
       shape, 4, correlation=wanted, rng=0
   )

   # Add 1% horizontal strain per frame to an imaged target.
   strained = pyspeckle.create_deformed_speckle(
       shape, 4, frames=5, strain=0.01, rng=0
   )

The deformation example above lists what else ``create_deformed_speckle`` can do.

The `2D speckle notebook <https://github.com/scottprahl/pyspeckle/blob/main/docs/2D-Speckle.ipynb>`_
plots each sequence and explains how translation, decorrelation, and deformation
change the pattern.


Citation
--------

If you use ``pyspeckle`` in academic, instructional, or applied technical work,
please cite the software and the original algorithms paper below.

The software DOI shown here is Zenodo's **all-versions DOI**; it resolves to
the latest archived release. To cite the exact code you used, follow that DOI,
select your release in Zenodo's **Versions** list, and use its version-specific
DOI in your citation and BibTeX entry.

Software
~~~~~~~~

Prahl, S. (2026). *pyspeckle: Tools for objective and subjective laser speckle analysis*
(Version 1.0.0) [Computer software]. Zenodo. https://doi.org/10.5281/zenodo.8311677

Original algorithms
~~~~~~~~~~~~~~~~~~~

Duncan, D. D., & Kirkpatrick, S. J. (2008). Algorithms for simulation of
speckle (laser and otherwise). In V. V. Tuchin & L. V. Wang (Eds.),
*Complex Dynamics and Fluctuations in Biomedical Photonics V*, Proceedings of
SPIE **6855**, 685505. https://doi.org/10.1117/12.760518

Speckle from a deforming target
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Yamaguchi, I. (1981). Speckle displacement and decorrelation in the
diffraction and image fields for small object deformation. *Optica Acta*,
**28**\ (10), 1359–1376. https://doi.org/10.1080/713820454


BibTeX
~~~~~~

.. code-block:: bibtex

   @software{pyspeckle_prahl_2026,
     author    = {Scott Prahl},
     title     = {pyspeckle: Tools for objective and subjective laser speckle analysis},
     year      = {2026},
     version   = {1.0.0},
     doi       = {10.5281/zenodo.8311677},
     url       = {https://github.com/scottprahl/pyspeckle},
     publisher = {Zenodo}
   }

   @inproceedings{duncan_kirkpatrick_2008,
     author    = {Donald D. Duncan and Sean J. Kirkpatrick},
     title     = {Algorithms for simulation of speckle (laser and otherwise)},
     booktitle = {Complex Dynamics and Fluctuations in Biomedical Photonics V},
     editor    = {Valery V. Tuchin and Lihong V. Wang},
     volume    = {6855},
     pages     = {685505},
     year      = {2008},
     publisher = {SPIE},
     doi       = {10.1117/12.760518}
   }

   @article{yamaguchi_1981,
     author    = {Ichirou Yamaguchi},
     title     = {Speckle displacement and decorrelation in the diffraction and
                  image fields for small object deformation},
     journal   = {Optica Acta},
     volume    = {28},
     number    = {10},
     pages     = {1359--1376},
     year      = {1981},
     doi       = {10.1080/713820454}
   }

License
-------

``pyspeckle`` is released under the MIT License. Contributions are welcome.
