Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
default_language_version:
python: python3.13
ci:
autofix_commit_msg: |
[pre-commit.ci] auto fixes from pre-commit hooks
Expand Down
24 changes: 21 additions & 3 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,25 @@

Tool for extracting signals with specific rotational symmetries from noisy data at scale

* LONGER DESCRIPTION HERE
.. long-description-start

``diffpy.saf`` finds the orientation angles of signals with n-fold
rotational symmetry in 2D data, such as diffraction patterns. It builds
symmetry adapted filters (SAFs), angular filters with the same n-fold
symmetry as the signal, and finds the angle at which each image overlaps
most strongly with the filter.

The package provides two main classes:

* ``SymmetryAdaptedFilter`` builds a SAF and a matching angular mask for
any n-fold symmetry, angular resolution, and image shape.
* ``RatchetModel`` tracks the orientation angles of up to two signals
through a stack of images, such as a rotating sample. Each image is
searched starting from the angles found in the previous image, so the
angles accumulate as the sample rotates instead of wrapping back into
one symmetry period.

.. long-description-end

For more information about the diffpy.saf library, please consult our `online documentation <https://diffpy.github.io/diffpy.saf>`_.

Expand Down Expand Up @@ -82,7 +100,7 @@ and run the following ::

This package also provides command-line utilities. To check the software has been installed correctly, type ::

diffpy.saf --version
diffpy-saf --version

You can also type the following command to verify the installation. ::

Expand All @@ -91,7 +109,7 @@ You can also type the following command to verify the installation. ::

To view the basic usage and available commands, type ::

diffpy.saf -h
diffpy-saf -h

Getting Started
---------------
Expand Down
31 changes: 0 additions & 31 deletions docs/source/api/diffpy.saf.example_package.rst

This file was deleted.

24 changes: 14 additions & 10 deletions docs/source/api/diffpy.saf.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,25 @@
:undoc-members:
:show-inheritance:

Subpackages
-----------

.. toctree::
diffpy.saf.example_package

Submodules
----------

|module|
--------
|filters|
---------

.. |filters| replace:: diffpy.saf.filters module

.. automodule:: diffpy.saf.filters
:members:
:undoc-members:
:show-inheritance:

|ratchet_model|
---------------

.. |module| replace:: diffpy.saf.example_submodule module
.. |ratchet_model| replace:: diffpy.saf.ratchet_model module

.. automodule:: diffpy.saf.example_submodule
.. automodule:: diffpy.saf.ratchet_model
:members:
:undoc-members:
:show-inheritance:
9 changes: 8 additions & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

import sys
import time
import tomllib
from importlib.metadata import version
from pathlib import Path

Expand All @@ -24,6 +25,12 @@
except Exception:
fullversion = "No version found. The correct version will appear in the released version." # noqa: E501

# Read the package description from pyproject.toml, its single source.
pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml"
with pyproject_path.open("rb") as pyproject_file:
description = tomllib.load(pyproject_file)["project"]["description"]
rst_epilog = f".. |description| replace:: {description}"

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use Path().resolve() to make it absolute, like shown here. # noqa: E501
Expand Down Expand Up @@ -300,7 +307,7 @@
"diffpy.saf Documentation",
ab_authors,
"diffpy.saf",
"One line description of project.",
description,
"Miscellaneous",
),
]
Expand Down
6 changes: 5 additions & 1 deletion docs/source/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@

.. |title| replace:: diffpy.saf documentation

``diffpy.saf`` - Tool for extracting signals with specific rotational symmetries from noisy data at scale
``diffpy.saf`` - |description|

.. include:: ../../README.rst
:start-after: .. long-description-start
:end-before: .. long-description-end

| Software version |release|
| Last updated |today|.
Expand Down
24 changes: 24 additions & 0 deletions news/migrate-source.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
**Added:**

* ``SymmetryAdaptedFilter`` class in ``diffpy.saf.filters`` for building n-fold symmetry-adapted filters.
* ``RatchetModel`` class in ``diffpy.saf.ratchet_model`` for extracting orientation angles of symmetric signals in 2D data.

**Changed:**

* <news item>

**Deprecated:**

* <news item>

**Removed:**

* Template ``dot_product`` function and its tests from ``diffpy.saf.functions``.

**Fixed:**

* <news item>

**Security:**

* <news item>
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ exclude = [] # exclude packages matching these glob patterns (empty by default)
namespaces = false # to disable scanning PEP 420 namespaces (true by default)

[project.scripts]
diffpy-saf = "diffpy.saf.app:main"
diffpy-saf = "diffpy.saf.saf_app:main"

[tool.setuptools.dynamic]
dependencies = {file = ["requirements/pip.txt"]}
Expand Down
2 changes: 2 additions & 0 deletions requirements/conda.txt
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
numpy
scipy
tqdm
2 changes: 2 additions & 0 deletions requirements/pip.txt
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
numpy
scipy
tqdm
3 changes: 2 additions & 1 deletion src/diffpy/saf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
# See LICENSE.rst for license information.
#
##############################################################################
"""Tool for extracting signals with specific rotational symmetries from noisy data at scale"""
"""Tool for extracting signals with specific rotational symmetries from
noisy data at scale."""

# package version
from diffpy.saf.version import __version__ # noqa
Expand Down
116 changes: 116 additions & 0 deletions src/diffpy/saf/filters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import numpy as np


class SymmetryAdaptedFilter:
"""Build an angular filter with n-fold rotational symmetry.

The filter has `n_folds` lobes radiating from `center`, centered on
the directions `phi_0 + m * 360 / n_folds` degrees. Angles are measured
from the +column axis toward the +row axis, which appears clockwise
when the image is shown with its origin in the upper left.

Parameters
----------
resolution : float
The angular resolution, in degrees, that sets the width of each
lobe.
n_folds : int
The number of lobes, i.e. the order of the rotational symmetry.
imshape : tuple of int, optional
The shape of the filter as (rows, columns). Default is (128, 128).
phi_0 : float, optional
The rotation angle of the filter in degrees. Default is 0.
center : tuple of int, optional
The position of the filter center as (row, column). Defaults to
`(imshape[0] // 2, imshape[1] // 2)`.
"""

def __init__(
self,
resolution,
n_folds,
imshape=(128, 128),
phi_0=0.0,
center=None,
):
self.k = self._find_k_value(resolution, n_folds)
self.n_folds = n_folds
self.phi_0 = phi_0
self.imshape = imshape
if center is None:
center = (imshape[0] // 2, imshape[1] // 2)
self.center = center

@staticmethod
def _find_k_value(resolution, n_folds):
res_rad = np.deg2rad(resolution)
k = np.log(1 / 2) / (np.log(np.cos((n_folds / 4 * res_rad)) ** 2))
return k

def _get_phi_grid(self):
y_grid, x_grid = np.mgrid[0 : self.imshape[0], 0 : self.imshape[1]]
center_row, center_col = self.center
return np.arctan2(y_grid - center_row, x_grid - center_col)

def generate_filter(self):
"""Generate the symmetry adapted filter (SAF).

Returns
-------
saf : ndarray
The generated SAF of shape `imshape`.
"""
phi_grid = self._get_phi_grid()
phi_0_rad = np.deg2rad(self.phi_0)
saf = (
np.abs(np.cos(0.5 * self.n_folds * (phi_grid - phi_0_rad)))
** self.k
)
return saf

def generate_mask(self, width):
"""Generate a mask that covers each lobe out to an angular
width.

A pixel is in the mask when its direction from `center` lies within
`width` / 2 degrees of a lobe center, and a width of 0 masks
nothing. The SAF falls off steadily
from each lobe center to halfway between lobes, so the mask equals
the SAF thresholded at cos(`n_folds` * `width` / 4) ** `k`, but its
width does not depend on `resolution`.

Parameters
----------
width : float
The full angular width of the mask around each lobe, in
degrees. It must be from 0, which masks nothing, to one period
of 360 / `n_folds` degrees, which covers every direction.

Returns
-------
mask : ndarray of bool
The mask of shape `imshape`, True on and near each lobe.

Raises
------
ValueError
If `width` is not from 0 to 360 / `n_folds`.
"""
period = 360 / self.n_folds
if not 0 <= width <= period:
raise ValueError(
"The mask width must be from 0 to one period of 360 / "
f"n_folds = {period:g} degrees, but {width} was given.\n"
"Please choose a width from 0, for no masking, to "
f"{period:g} degrees."
)
if width == 0:
mask = np.zeros(self.imshape, dtype=bool)
return mask
phi_grid = self._get_phi_grid()
phi_0_rad = np.deg2rad(self.phi_0)
lobe_profile = np.abs(
np.cos(0.5 * self.n_folds * (phi_grid - phi_0_rad))
)
mask = lobe_profile >= np.cos(np.deg2rad(self.n_folds * width / 4))
return mask
31 changes: 0 additions & 31 deletions src/diffpy/saf/functions.py

This file was deleted.

Loading
Loading