Skip to content

Format everything with black. #161

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 30, 2025
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
35 changes: 35 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
repos:
# - repo: https://github.com/charliermarsh/ruff-pre-commit
# # Ruff version.
# rev: 'v0.1.0'
# hooks:
# - id: ruff
# args: ['--fix', '--config', 'pyproject.toml']

- repo: https://github.com/psf/black
rev: 'refs/tags/23.10.0:refs/tags/23.10.0'
hooks:
- id: black
language_version: python3.10
args: ['--config', 'pyproject.toml']
verbose: true

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: end-of-file-fixer
- id: debug-statements # Ensure we don't commit `import pdb; pdb.set_trace()`
exclude: |
(?x)^(
docker/ros/web/static/.*|
)$
- id: trailing-whitespace
exclude: |
(?x)^(
docker/ros/web/static/.*|
(.*/).*\.patch|
)$
# - repo: https://github.com/pre-commit/mirrors-mypy
# rev: v1.6.1
# hooks:
# - id: mypy
10 changes: 5 additions & 5 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys

# sys.path.insert(0, os.path.abspath('.'))
# sys.path.insert(0, os.path.abspath('..'))
Expand Down Expand Up @@ -67,9 +65,11 @@
# choose UTF-8 encoding to allow for Unicode characters, eg. ansitable
# Python session setup, turn off color printing for SE3, set NumPy precision
autorun_languages = {}
autorun_languages['pycon_output_encoding'] = 'UTF-8'
autorun_languages['pycon_input_encoding'] = 'UTF-8'
autorun_languages['pycon_runfirst'] = """
autorun_languages["pycon_output_encoding"] = "UTF-8"
autorun_languages["pycon_input_encoding"] = "UTF-8"
autorun_languages[
"pycon_runfirst"
] = """
from spatialmath import SE3
SE3._color = False
import numpy as np
Expand Down
9 changes: 5 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ keywords = [
"SO(2)", "SE(2)", "SO(3)", "SE(3)",
"twist", "product of exponential", "translation", "orientation",
"angle-axis", "Lie group", "skew symmetric matrix",
"pose", "translation", "rotation matrix",
"pose", "translation", "rotation matrix",
"rigid body transform", "homogeneous transformation",
"Euler angles", "roll-pitch-yaw angles",
"quaternion", "unit-quaternion",
Expand Down Expand Up @@ -63,9 +63,9 @@ dev = [

docs = [
"sphinx",
"sphinx-rtd-theme",
"sphinx-autorun",
"sphinxcontrib-jsmath",
"sphinx-rtd-theme",
"sphinx-autorun",
"sphinxcontrib-jsmath",
"sphinx-favicon",
"sphinx-autodoc-typehints",
]
Expand All @@ -88,6 +88,7 @@ packages = [
]

[tool.black]
required-version = "23.10.0"
line-length = 88
target-version = ['py38']
exclude = "camera_derivatives.py"
1 change: 0 additions & 1 deletion spatialmath/DualQuaternion.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,6 @@ def SE3(self) -> SE3:


if __name__ == "__main__": # pragma: no cover

from spatialmath import SE3, UnitDualQuaternion

print(UnitDualQuaternion(SE3()))
Expand Down
4 changes: 1 addition & 3 deletions spatialmath/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
from spatialmath.DualQuaternion import DualQuaternion, UnitDualQuaternion
from spatialmath.spline import BSplineSE3, InterpSplineSE3, SplineFit

# from spatialmath.Plucker import *
# from spatialmath import base as smb

__all__ = [
# pose
Expand Down Expand Up @@ -46,7 +44,7 @@
"Ellipse",
"BSplineSE3",
"InterpSplineSE3",
"SplineFit"
"SplineFit",
]

try:
Expand Down
19 changes: 10 additions & 9 deletions spatialmath/base/animate.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ def __init__(
if len(dim) == 2:
dim = dim * 3
elif len(dim) != 6:
raise ValueError(f"dim must have 2 or 6 elements, got {dim}. See docstring for details.")
raise ValueError(
f"dim must have 2 or 6 elements, got {dim}. See docstring for details."
)
ax.set_xlim(dim[0:2])
ax.set_ylim(dim[2:4])
ax.set_zlim(dim[4:])
Expand Down Expand Up @@ -223,7 +225,7 @@ def update(frame, animation):
else:
# [unlikely] other types are converted to np array
T = np.array(frame)

if T.shape == (3, 3):
T = smb.r2t(T)

Expand Down Expand Up @@ -606,14 +608,14 @@ def trplot2(
smb.trplot2(self.start, ax=self, block=False, **kwargs)

def run(
self,
self,
movie: Optional[str] = None,
axes: Optional[plt.Axes] = None,
repeat: bool = False,
interval: int = 50,
nframes: int = 100,
wait: bool = False,
**kwargs
wait: bool = False,
**kwargs,
):
"""
Run the animation
Expand Down Expand Up @@ -663,7 +665,6 @@ def update(frame, animation):
animation._draw(T)
self.count += 1 # say we're still running


if movie is not None:
repeat = False

Expand Down Expand Up @@ -698,7 +699,9 @@ def update(frame, animation):
print("overwriting movie", movie)
else:
print("creating movie", movie)
FFwriter = animation.FFMpegWriter(fps=1000 / interval, extra_args=["-vcodec", "libx264"])
FFwriter = animation.FFMpegWriter(
fps=1000 / interval, extra_args=["-vcodec", "libx264"]
)
_ani.save(movie, writer=FFwriter)

if wait:
Expand Down Expand Up @@ -902,8 +905,6 @@ def set_ylabel(self, *args, **kwargs):
# plotvol3(2)
# tranimate(attitude())

from spatialmath import base

# T = smb.rpy2r(0.3, 0.4, 0.5)
# # smb.tranimate(T, wait=True)
# s = smb.tranimate(T, movie=True)
Expand Down
75 changes: 49 additions & 26 deletions spatialmath/base/quaternions.py
Original file line number Diff line number Diff line change
Expand Up @@ -851,57 +851,74 @@ def qslerp(
def _compute_cdf_sin_squared(theta: float):
"""
Computes the CDF for the distribution of angular magnitude for uniformly sampled rotations.

:arg theta: angular magnitude
:rtype: float
:return: cdf of a given angular magnitude
:rtype: float

Helper function for uniform sampling of rotations with constrained angular magnitude.
Helper function for uniform sampling of rotations with constrained angular magnitude.
This function returns the integral of the pdf of angular magnitudes (2/pi * sin^2(theta/2)).
"""
return (theta - np.sin(theta)) / np.pi


@lru_cache(maxsize=1)
def _generate_inv_cdf_sin_squared_interp(num_interpolation_points: int = 256) -> interpolate.interp1d:
def _generate_inv_cdf_sin_squared_interp(
num_interpolation_points: int = 256,
) -> interpolate.interp1d:
"""
Computes an interpolation function for the inverse CDF of the distribution of angular magnitude.

:arg num_interpolation_points: number of points to use in the interpolation function
:rtype: int
:return: interpolation function for the inverse cdf of a given angular magnitude
:rtype: interpolate.interp1d

Helper function for uniform sampling of rotations with constrained angular magnitude.
This function returns interpolation function for the inverse of the integral of the
Helper function for uniform sampling of rotations with constrained angular magnitude.
This function returns interpolation function for the inverse of the integral of the
pdf of angular magnitudes (2/pi * sin^2(theta/2)), which is not analytically defined.
"""
cdf_sin_squared_interp_angles = np.linspace(0, np.pi, num_interpolation_points)
cdf_sin_squared_interp_values = _compute_cdf_sin_squared(cdf_sin_squared_interp_angles)
return interpolate.interp1d(cdf_sin_squared_interp_values, cdf_sin_squared_interp_angles)
cdf_sin_squared_interp_values = _compute_cdf_sin_squared(
cdf_sin_squared_interp_angles
)
return interpolate.interp1d(
cdf_sin_squared_interp_values, cdf_sin_squared_interp_angles
)


def _compute_inv_cdf_sin_squared(x: ArrayLike, num_interpolation_points: int = 256) -> ArrayLike:
def _compute_inv_cdf_sin_squared(
x: ArrayLike, num_interpolation_points: int = 256
) -> ArrayLike:
"""
Computes the inverse CDF of the distribution of angular magnitude.

:arg x: value for cdf of angular magnitudes
:rtype: ArrayLike
:arg num_interpolation_points: number of points to use in the interpolation function
:rtype: int
:return: angular magnitude associate with cdf value
:rtype: ArrayLike

Helper function for uniform sampling of rotations with constrained angular magnitude.
This function returns the angle associated with the cdf value derived form integral of
Helper function for uniform sampling of rotations with constrained angular magnitude.
This function returns the angle associated with the cdf value derived form integral of
the pdf of angular magnitudes (2/pi * sin^2(theta/2)), which is not analytically defined.
"""
inv_cdf_sin_squared_interp = _generate_inv_cdf_sin_squared_interp(num_interpolation_points)
inv_cdf_sin_squared_interp = _generate_inv_cdf_sin_squared_interp(
num_interpolation_points
)
return inv_cdf_sin_squared_interp(x)

def qrand(theta_range:Optional[ArrayLike2] = None, unit: str = "rad", num_interpolation_points: int = 256) -> UnitQuaternionArray:

def qrand(
theta_range: Optional[ArrayLike2] = None,
unit: str = "rad",
num_interpolation_points: int = 256,
) -> UnitQuaternionArray:
"""
Random unit-quaternion

:arg theta_range: angular magnitude range [min,max], defaults to None.
:type xrange: 2-element sequence, optional
:arg unit: angular units: 'rad' [default], or 'deg'
Expand All @@ -913,7 +930,7 @@ def qrand(theta_range:Optional[ArrayLike2] = None, unit: str = "rad", num_interp
:return: random unit-quaternion
:rtype: ndarray(4)

Computes a uniformly distributed random unit-quaternion, with in a maximum
Computes a uniformly distributed random unit-quaternion, with in a maximum
angular magnitude, which can be considered equivalent to a random SO(3) rotation.

.. runblock:: pycon
Expand All @@ -924,24 +941,30 @@ def qrand(theta_range:Optional[ArrayLike2] = None, unit: str = "rad", num_interp
if theta_range is not None:
theta_range = getunit(theta_range, unit)

if(theta_range[0] < 0 or theta_range[1] > np.pi or theta_range[0] > theta_range[1]):
ValueError('Invalid angular range. Must be within the range[0, pi].'
+ f' Recieved {theta_range}.')
if (
theta_range[0] < 0
or theta_range[1] > np.pi
or theta_range[0] > theta_range[1]
):
ValueError(
"Invalid angular range. Must be within the range[0, pi]."
+ f" Recieved {theta_range}."
)

# Sample axis and angle independently, respecting the CDF of the
# angular magnitude under uniform sampling.

# Sample axis and angle independently, respecting the CDF of the
# angular magnitude under uniform sampling.

# Sample angle using inverse transform sampling based on CDF
# Sample angle using inverse transform sampling based on CDF
# of the angular distribution (2/pi * sin^2(theta/2))
theta = _compute_inv_cdf_sin_squared(
np.random.uniform(
low=_compute_cdf_sin_squared(theta_range[0]),
low=_compute_cdf_sin_squared(theta_range[0]),
high=_compute_cdf_sin_squared(theta_range[1]),
),
num_interpolation_points=num_interpolation_points,
)
# Sample axis uniformly using 3D normal distributed
v = np.random.randn(3)
v = np.random.randn(3)
v /= np.linalg.norm(v)

return np.r_[math.cos(theta / 2), (math.sin(theta / 2) * v)]
Expand All @@ -953,7 +976,7 @@ def qrand(theta_range:Optional[ArrayLike2] = None, unit: str = "rad", num_interp
math.sqrt(u[0]) * math.sin(2 * math.pi * u[2]),
math.sqrt(u[0]) * math.cos(2 * math.pi * u[2]),
]


def qmatrix(q: ArrayLike4) -> R4x4:
"""
Expand Down
12 changes: 8 additions & 4 deletions spatialmath/base/transforms2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -746,7 +746,7 @@ def trnorm2(T: SE2Array) -> SE2Array:
b = unitvec(b)
# fmt: off
R = np.array([
[ b[1], b[0]],
[ b[1], b[0]],
[-b[0], b[1]]
])
# fmt: on
Expand Down Expand Up @@ -810,7 +810,7 @@ def tradjoint2(T):
(R, t) = smb.tr2rt(cast(SE3Array, T))
# fmt: off
return np.block([
[R, np.c_[t[1], -t[0]].T],
[R, np.c_[t[1], -t[0]].T],
[0, 0, 1]
]) # type: ignore
# fmt: on
Expand Down Expand Up @@ -853,12 +853,16 @@ def tr2jac2(T: SE2Array) -> R3x3:


@overload
def trinterp2(start: Optional[SO2Array], end: SO2Array, s: float, shortest: bool = True) -> SO2Array:
def trinterp2(
start: Optional[SO2Array], end: SO2Array, s: float, shortest: bool = True
) -> SO2Array:
...


@overload
def trinterp2(start: Optional[SE2Array], end: SE2Array, s: float, shortest: bool = True) -> SE2Array:
def trinterp2(
start: Optional[SE2Array], end: SE2Array, s: float, shortest: bool = True
) -> SE2Array:
...


Expand Down
Loading
Loading