diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index a4a2a4db..7b0bea80 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -17,6 +17,12 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ startsWith(github.ref, 'refs/pull/') }} jobs: + # The test items tagged `slow` (the AD cross-check harness and the exp/log AD tests) take + # most of the suite's CPU time, so the OS matrix skips them, and the `slow` job below runs + # them once, on Ubuntu with the latest Julia. The other test items tagged `ad`, which + # spend most of their time compiling the AD packages, run only on Ubuntu, because the AD + # code paths do not depend on the operating system. Coverage is uploaded only from the + # Ubuntu job with the latest Julia and the `slow` job, which together run the whole suite. test: name: Julia ${{ matrix.version }} - ${{ matrix.os }} - ${{ github.event_name }} runs-on: ${{ matrix.os }} @@ -36,7 +42,6 @@ jobs: include: - version: 'lts' os: ubuntu-latest - arch: x64 steps: - uses: actions/checkout@v7 - uses: julia-actions/setup-julia@v3 @@ -46,13 +51,61 @@ jobs: - uses: julia-actions/cache@v3 - uses: julia-actions/julia-buildpkg@v1 - uses: julia-actions/julia-runtest@v1 + with: + test_args: ${{ matrix.os == 'ubuntu-latest' && '--exclude slow' || '--exclude slow,ad' }} - uses: julia-actions/julia-processcoverage@v1 + if: matrix.os == 'ubuntu-latest' && matrix.version == '1' - uses: codecov/codecov-action@v7 - if: "matrix.os == 'ubuntu-latest'" + if: matrix.os == 'ubuntu-latest' && matrix.version == '1' with: files: lcov.info + flags: fast token: ${{ secrets.CODECOV_TOKEN }} + slow: + name: Slow tests - Julia 1 - ubuntu-latest - ${{ github.event_name }} + runs-on: ubuntu-latest + if: >- + !contains(github.ref, 'refs/tags/') + && !contains(github.event.head_commit.message, '[skip ci]') + && !contains(github.event.head_commit.message, '[skip tests]') + steps: + - uses: actions/checkout@v7 + - uses: julia-actions/setup-julia@v3 + with: + version: '1' + - uses: julia-actions/cache@v3 + - uses: julia-actions/julia-buildpkg@v1 + - uses: julia-actions/julia-runtest@v1 + with: + test_args: '--tags slow' + - uses: julia-actions/julia-processcoverage@v1 + - uses: codecov/codecov-action@v7 + with: + files: lcov.info + flags: slow + token: ${{ secrets.CODECOV_TOKEN }} + + # The workspace test environment cannot be instantiated before Julia 1.9, so the oldest + # supported Julia runs a few smoke tests in a fresh environment instead. + compat16: + name: Smoke tests - Julia 1.6 - ubuntu-latest - ${{ github.event_name }} + runs-on: ubuntu-latest + if: >- + !contains(github.ref, 'refs/tags/') + && !contains(github.event.head_commit.message, '[skip ci]') + && !contains(github.event.head_commit.message, '[skip tests]') + steps: + - uses: actions/checkout@v7 + - uses: julia-actions/setup-julia@v3 + with: + version: '1.6' + - uses: julia-actions/cache@v3 + - run: julia --project=compat16 -e 'using Pkg; Pkg.develop(path="."); Pkg.add(["ChainRulesCore", "ForwardDiff", "StaticArrays"])' + - run: julia --project=compat16 test/compat16_smoke.jl + + # The docs job does not wait for the tests, so that the docs (and their previews on pull + # requests) can be checked even while some tests fail. docs: name: Documentation runs-on: ubuntu-latest @@ -60,6 +113,7 @@ jobs: !contains(github.event.head_commit.message, '[skip ci]') && !contains(github.event.head_commit.message, '[skip docs]') permissions: + actions: write contents: write statuses: write pull-requests: write @@ -68,19 +122,18 @@ jobs: - uses: julia-actions/setup-julia@v3 with: version: '1' + - uses: julia-actions/cache@v3 - uses: julia-actions/julia-buildpkg@v1 - uses: julia-actions/julia-docdeploy@v1 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} DOCUMENTER_KEY: ${{ secrets.DOCUMENTER_KEY }} - - run: | - julia --project=docs -e ' - using Documenter: DocMeta, doctest - using Quaternionic - DocMeta.setdocmeta!(Quaternionic, :DocTestSetup, :(using Quaternionic); recursive=true) - doctest(Quaternionic)' + # A pull request from a fork has a read-only token, so it can neither comment nor + # deploy a preview. - uses: marocchino/sticky-pull-request-comment@v3 - if: github.event_name == 'pull_request' + if: >- + github.event_name == 'pull_request' + && github.event.pull_request.head.repo.full_name == github.repository with: message: | - [Documentation preview](https://moble.github.io/Quaternionic.jl/previews/PR${{ github.event.pull_request.number }}/) \ No newline at end of file + [Documentation preview](https://moble.github.io/Quaternionic.jl/previews/PR${{ github.event.pull_request.number }}/) diff --git a/.gitignore b/.gitignore index c9b0a86d..d78da56d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,14 @@ # Files generated by invoking Julia with --track-allocation *.jl.mem +*.jl.*.mem + +# HTML coverage reports generated with genhtml (see test/runtests.jl) +/coverage/ + +# Python environments created by CondaPkg, and macOS metadata +.CondaPkg/ +.DS_Store # System-specific files and directories generated by the BinaryProvider and BinDeps packages # They contain absolute paths specific to the host computer, and so should not be committed diff --git a/Project.toml b/Project.toml index adf234b2..3bed6c10 100644 --- a/Project.toml +++ b/Project.toml @@ -8,52 +8,71 @@ projects = ["test", "docs"] [deps] GenericLinearAlgebra = "14197337-ba66-59df-a3e3-ca00e7dcff7a" -LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" PrecompileTools = "aea7be01-6a6a-4083-8856-8a6e6704d82a" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Requires = "ae029012-a4dd-5104-9daa-d747884805df" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" +# ChainRules and Enzyme appear in [weakdeps] and [compat] partly to bound their versions: +# the ChainRules opt-outs were audited against ChainRules 1.73, and Enzyme's floor matches +# the EnzymeRules API used by QuaternionicEnzymeExt. [weakdeps] ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2" ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" +DifferentiationInterface = "a0c0ee7d-e4b9-4e03-894e-1c5f64a51d63" Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" FastDifferentiation = "eb9bf01b-bf85-4b60-bf87-ee5de06c00be" ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6" -StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" +ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f" -ZygoteRules = "700de1a5-db45-46bc-99cf-38207098b444" [extensions] QuaternionicChainRulesCoreExt = "ChainRulesCore" -QuaternionicChainRulesExt = ["ChainRules", "ChainRulesCore"] +QuaternionicDifferentiationInterfaceExt = "DifferentiationInterface" +QuaternionicEnzymeExt = "Enzyme" QuaternionicFastDifferentiationExt = "FastDifferentiation" QuaternionicForwardDiffExt = "ForwardDiff" QuaternionicLatexifyExt = "Latexify" +QuaternionicMooncakeExt = ["Mooncake", "ChainRulesCore"] +QuaternionicReverseDiffExt = "ReverseDiff" QuaternionicSymbolicsExt = "Symbolics" -QuaternionicZygoteExt = ["Zygote", "ZygoteRules", "ChainRulesCore", "StaticArraysCore"] +QuaternionicZygoteExt = ["Zygote", "ChainRulesCore"] + +# Every [weakdeps] entry is repeated here, so that Pkg before Julia 1.9, which does not +# know about [weakdeps], accepts their [compat] entries. +[extras] +ChainRules = "082447d4-558c-5d27-93f4-14fc19e9eca2" +ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" +DifferentiationInterface = "a0c0ee7d-e4b9-4e03-894e-1c5f64a51d63" +Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" +FastDifferentiation = "eb9bf01b-bf85-4b60-bf87-ee5de06c00be" +ForwardDiff = "f6369f11-7733-5829-9624-2563aa707210" +Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316" +Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6" +ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" +Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" +Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f" [compat] ChainRules = "1.72.6" -ChainRulesCore = "1" +ChainRulesCore = "1.15" +DifferentiationInterface = "0.7" Enzyme = "0.13.82" -FastDifferentiation = "0.3.15, 0.4" +FastDifferentiation = "0.4" ForwardDiff = "0.10, 1" GenericLinearAlgebra = "0.3.11, 0.4" -LaTeXStrings = "1" Latexify = "0.15, 0.16" LinearAlgebra = "1, < 0.0.1" Mooncake = "0.4.161, 0.5" PrecompileTools = "1.2" Random = "1, < 0.0.1" Requires = "1" +ReverseDiff = "1.15" StaticArrays = "1.8.1" -StaticArraysCore = "1.4.3" Symbolics = "0.1, 1, 2, 3, 4, 5, 6, 7" Zygote = "0.7.10" -ZygoteRules = "0.2.7" julia = "1.6" diff --git a/README.md b/README.md index 4ab8245b..a2a373bb 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ Pkg.add("Quaternionic") ``` ## Usage -See [the documentation](https://moble.github.io/Quaternionic.jl/dev) for details. +See [the documentation](https://moble.github.io/Quaternionic.jl/stable/) for details. ## Motivation The goal of this project is to build a complete quaternion type in Julia. There are @@ -28,11 +28,10 @@ several features that I consider to be fairly basic to a good quaternion package * Subtypes for rotors and pure-vector quaternions, with corresponding specialized methods * Numerous conversions to and from other representations of things quaternions can represent — especially rotations - * Smooth interpolation, and differentation of the interpolant + * Smooth interpolation, and differentiation of the interpolant * Intelligent handling of distance measures * Construction of random quaternions of the various special types * Enabling efficient integration of angular velocity - * Construction of a minimal rotation * Documentation * Thorough testing diff --git a/docs/make.jl b/docs/make.jl index 3d7b522f..0b9e477a 100644 --- a/docs/make.jl +++ b/docs/make.jl @@ -32,14 +32,26 @@ makedocs(; remotes=notes_remotes, pages=[ "Introduction" => "index.md", - "Basics" => "manual.md", + "Manual" => [ + "Types and construction" => "types.md", + "Algebra and mathematical functions" => "math.md", + "Rotations and conversions" => "conversions.md", + "Distances and alignment" => "distances.md", + "Lorentz transformations" => "lorentz.md", + ], "Functions of time" => "functions_of_time.md", - "Differentiating by quaternions" => "differentiation.md", - "All functions" => "functions.md", - "Geometric Algebra" => "geometric_algebra.md", - "Spacetime Algebra" => "spacetime_algebra.md", + "Differentiating by quaternionic arguments" => "differentiation.md", + "Theory" => [ + "Geometric algebra" => "geometric_algebra.md", + "Spacetime algebra" => "spacetime_algebra.md", + ], + "References" => "references.md", notes_pages..., + "API index" => "api.md", ], + # Every exported or public name must be documented. Internal helpers, such as + # `squad_control_points`, may have docstrings that are deliberately left out. + checkdocs=:public, # doctest = false, doctestfilters = [ # Drop any digit after the 12th digit after a decimal, throughout the docs diff --git a/docs/serve.jl b/docs/serve.jl index 9723d553..e7b04d6a 100644 --- a/docs/serve.jl +++ b/docs/serve.jl @@ -1,7 +1,28 @@ # This simply uses `make.jl` in this directory to build the docs, then serves them locally. # Run `julia --project=docs docs/serve.jl` from the top directory to execute this script. +# +# LiveServer rebuilds the docs whenever a file in `docs/src` or in the package's `src` +# changes. Docstring edits in `src` appear in the rebuilt docs only if Revise is available +# (for example, from the default global environment), because otherwise the package is not +# reloaded between builds. + +# Activate the docs environment even if this script was started with another project (for +# example, `--project=.`), because the doctests need packages such as Symbolics that only +# the docs environment provides. +import Pkg +Pkg.activate(@__DIR__) + +try + using Revise +catch + @warn "Revise is not available, so docstring edits will not appear until the server is restarted." +else + using Quaternionic +end -#using Quaternionic import LiveServer: servedocs -servedocs(; launch_browser=true) +servedocs(; + include_dirs=["src/", realpath(joinpath("docs", "src", "local_notes"))], + launch_browser=true, +) diff --git a/docs/src/api.md b/docs/src/api.md new file mode 100644 index 00000000..d0feb9f6 --- /dev/null +++ b/docs/src/api.md @@ -0,0 +1,26 @@ +# API index + +This page lists every documented function, type, and constant that the package +exports or declares public, with links to their documentation on the other pages. +Internal helper functions are not listed. + +Some of these functions are defined in `Quaternionic`, while others extend functions +from Julia's `Base` and `LinearAlgebra` modules, such as `conj`, `abs`, `exp`, `log`, +`randn`, `normalize`, `⋅` (also known as `dot`), and `×` (also known as `cross`). +Many other functions from `Base` that are not listed here have also been extended to +work with quaternionic types, so that quaternions can generally function as numbers. +These include `+`, `-`, `*`, `/`, `inv`, `==`, `isequal`, `isnan`, `isinf`, `iszero`, +`isone`, `show`, `read`, `write`, `hash`, `promote_rule`, and so on. They are not +separately documented, but should behave analogously to their behavior with `Complex` +numbers. + +A few exported names are documented together with closely related names: `distance2` +with [`distance`](@ref); the type aliases `QuaternionF64`, `QuaternionF32`, and +`QuaternionF16` with [`Quaternion`](@ref), and similarly for [`Rotor`](@ref) and +[`QuatVec`](@ref). Names that are public but not +exported, such as [`Quaternionic.value`](@ref) and [`Quaternionic.KAN`](@ref), must be +qualified with the module name or imported explicitly. + +```@index +Modules = [Quaternionic, Base, LinearAlgebra] +``` diff --git a/docs/src/conversions.md b/docs/src/conversions.md new file mode 100644 index 00000000..847fd863 --- /dev/null +++ b/docs/src/conversions.md @@ -0,0 +1,14 @@ +# Rotations and conversions + +It can sometimes be useful to convert between quaternions and other +representations. Most of these functions are named `to_` and +have a corresponding `from_` function. Furthermore, most +convert to/from representations of rotations. While rotations are not the only +useful application of quaternions, they are probably the most common. The only +conversions that are not specifically related to rotations are +[`to_float_array`](@ref) and [`from_float_array`](@ref). + +```@autodocs +Modules = [Quaternionic] +Pages = ["conversion.jl"] +``` diff --git a/docs/src/differentiation.md b/docs/src/differentiation.md index f8d9adf3..263a6619 100644 --- a/docs/src/differentiation.md +++ b/docs/src/differentiation.md @@ -1,39 +1,115 @@ # Differentiating by quaternionic arguments As with complex arguments, differentiation with respect to -quaternionic arguments treats the components of the quaternionic -argument as independent real arguments. These rules are implemented -for this package in `ChainRulesCore`, which means that they should -work seamlessly with [any package that relies on -`ChainRulesCore`](https://juliadiff.org/ChainRulesCore.jl/stable/#ChainRules-roll-out-status), -such as [`Zygote`](https://github.com/FluxML/Zygote.jl). Derivatives -can also be calculated automatically using -[`ForwardDiff.jl`](https://juliadiff.org/ForwardDiff.jl/) +quaternionic arguments treats the four components of each quaternion +as independent real arguments. That is, a quaternion is regarded as a +vector in ``\mathbb{R}^4``, and derivatives are the usual Jacobians of +the resulting real functions. The precise statement of this +convention, and its consequences for `Rotor` and `QuatVec`, are given +[below](@ref "Tangent conventions"). + +Several automatic-differentiation (AD) packages can differentiate code +that uses this package, but they obtain derivatives in different ways, +return gradients of different types, and have different limitations. +These are described in the following sections. For most purposes, +[`ForwardDiff.jl`](https://juliadiff.org/ForwardDiff.jl/) is the +simplest and most thoroughly tested choice for functions of a few real +variables, while the reverse-mode packages are preferable for +gradients of scalar functions of many variables. As with complex differentiation, there are numerous notions of quaternionic differentiation — including generalizations of the holomorphic and Wirtinger derivatives, as well as left- and right-multiplicative derivatives. The goal here is to provide the -basic differentiation rules upon which these derivatives can be -implemented, but not to implement those derivatives themselves. It is -recommended that you carefully check how the definitions of `frule` -and `rrule` translate into your specific notion of quaternionic -derivatives, since getting this wrong will quietly give you wrong -results. - -!!! warn "Zygote is weird" - Note that Zygote's handling of input and output arguments is just - strange. Specifically, everything goes badly if an input or - output is quaternionic. For example, if we define ``f(t) = tq`` - for some fixed quaternion ``q``, Zygote's derivative of this is - just the first component of the correct answer. - - Fortunately, this does not seem to be a problem when functions - involve quaternions *internally*, so for testing we can just - provide input or accept output in the form of arrays, but convert - them to quaternions inside the function to be tested, and switch - to checking the Jacobian as needed. No other AD package seems to - have this problem. +basic real derivatives from which any of these can be built. + +!!! warning "Check the convention" + If you need one of the specifically quaternionic derivatives + mentioned above, check carefully how the real-component convention + described here translates into your notion of derivative. Getting + this wrong will quietly give unexpected results. + + +## Supported AD packages + +The following table lists the AD packages that are tested with this +package, how each of them obtains derivatives of quaternionic +functions, and the type of the gradient it returns for a scalar +function of a quaternionic argument. All hand-written differentiation +rules live in a single extension that is loaded with +[`ChainRulesCore`](https://juliadiff.org/ChainRulesCore.jl/stable/); +the other packages differentiate the source code of this package +directly. + +| Package | How derivatives are obtained | Gradient with respect to `Quaternion`, `Rotor`, and `QuatVec` arguments | +|:--------|:-----------------------------|:-----------------------------------------------------------------------| +| [ForwardDiff](https://juliadiff.org/ForwardDiff.jl/) | Differentiates the source with dual-number components. An extension makes `ForwardDiff.derivative` return quaternions for quaternion-valued functions, including those with complex components. | Arguments must be real arrays (for example, `components(q)`), so gradients are arrays. `ForwardDiff.derivative` of a quaternion-valued function returns a `Quaternion` (a `QuatVec` for a `QuatVec`-valued function, and a `Quaternion` for a `Rotor`-valued function). | +| [ReverseDiff](https://juliadiff.org/ReverseDiff.jl/) | Differentiates the source with tracked components. It does not use the ChainRules rules. | Arguments must be real arrays, so gradients are arrays. | +| [Zygote](https://fluxml.ai/Zygote.jl/) and other ChainRules consumers | Uses the ChainRules rules directly; a small Zygote extension adds what ChainRules cannot express (Zygote's own rules for `Number`, `inv`, and broadcasting). | `Quaternion` for `Quaternion` and `Rotor` arguments; `QuatVec` for `QuatVec` arguments. | +| [Enzyme](https://enzymead.github.io/Enzyme.jl/stable/) | Differentiates the source natively, in forward and reverse mode, including forward-over-reverse Hessians. An extension supplies `Enzyme.onehot` for quaternion arguments and rules for the one LAPACK call (used by `from_rotation_matrix` and `align`). | Reverse mode returns an object of the argument's own type: a `Rotor` holding the raw gradient (so `abs` reports 1), or a `QuatVec` whose hidden scalar slot may be nonzero. Read these with `components(g)`. `Enzyme.gradient(Forward, f, q)` returns a tuple of the partial derivatives. | +| [Mooncake](https://chalk-lab.github.io/Mooncake.jl/stable/) | Differentiates the source natively, in forward and reverse mode. It imports the ChainRules rules for only two primitives that it cannot trace: Base's complex `sqrt` and the LAPACK eigenvector call. | Mooncake's structural `Tangent` type by default; a `Quaternion` (or a `QuatVec` for a `QuatVec` argument) with `Mooncake.Config(friendly_tangents=true)`. | +| [FastDifferentiation](https://github.com/brianguenter/FastDifferentiation.jl) | Symbolic differentiation of expression graphs built from quaternions with `Node` components. | Arrays of expressions. Functions that branch on component values are not supported; see below. | +| [Symbolics](https://docs.sciml.ai/Symbolics/stable/) | Symbolic differentiation (for example, with `Symbolics.Differential`) of quaternions with `Num` components. | Symbolic expressions. A few functions that branch on component values, such as `sqrt`, are not supported. | + +Every package in this table except FastDifferentiation differentiates `exp` and `log` +correctly, including at the points where their implementations switch to series +expansions or special formulas: the identity, quaternions with tiny or zero vector +part, quaternions near the negative real axis, and pure vectors. (The exceptions for +second derivatives with Mooncake are listed under [Known limitations](@ref).) For +FastDifferentiation, these functions raise an explanatory error. + +The extensions for Zygote, Enzyme, Mooncake, and ReverseDiff are loaded only as package +extensions, so they require Julia 1.9 or later; the compatible versions of Zygote, +Enzyme, and Mooncake require Julia 1.10 or later. The ChainRulesCore, ForwardDiff, +FastDifferentiation, and Symbolics integrations also work on older versions of Julia. + + +## Tangent conventions + +For a `Quaternion` argument, the tangent (and cotangent) is a `Quaternion` whose four +components are the four partial derivatives, as described in detail in the next +section. `Rotor` and `QuatVec` are subsets of the quaternions, and their tangents follow +from that fact: + +| Primal type | Tangent and cotangent type in the ChainRules rules | Notes | +|:------------|:------------------------------------------|:------| +| `Quaternion{T}` | `Quaternion{float(T)}` | | +| `Rotor{T}` | `Quaternion{float(T)}`, never a `Rotor` | The cotangent is the ambient gradient in ``\mathbb{R}^4``; see below. | +| `QuatVec{T}` | `QuatVec{float(T)}` | The scalar part is zero by construction. | +| `AbstractQuaternion{Bool}` (the constants `𝐢`, `𝐣`, and `𝐤`) | `NoTangent()` | As for `Bool` in ChainRulesCore. | +| `AbstractQuaternion{<:Integer}` | `Quaternion{Float64}` or `QuatVec{Float64}` | As for `Integer` in ChainRulesCore. | +| A `Real` or `Complex` scalar receiving a quaternion cotangent | The scalar part of the cotangent | | + +**`Rotor` arguments.** A `Rotor` is a unit quaternion, so the true tangent space at a +rotor ``R`` is the three-dimensional space ``\{R\, v : v \in \mathrm{QuatVec}\}``, which +consists of the quaternions orthogonal to ``R`` in ``\mathbb{R}^4``. The rules in this +package do not restrict cotangents to that space. Instead, a `Rotor` is differentiated +as the four real numbers it stores, and the gradient with respect to a `Rotor` argument +is the ambient gradient in ``\mathbb{R}^4`` of whatever the code computes from those +four numbers. Its component along ``R`` therefore depends on how the function is +written: for example, `abs(R)` is identically 1 for a `Rotor`, but `sqrt(R ⋅ R)` has a +nonzero gradient along ``R``. When only the part tangent to the unit sphere is +meaningful, project the gradient ``g`` onto the tangent space with ``g - (g \cdot R)\, +R``; the projections of the gradients of different implementations of the same function +agree. The gradient is returned as a `Quaternion` (or, with Enzyme, a `Rotor` holding +the raw components), never as a renormalized `Rotor`. Note that `abs` and `abs2` of a +`Rotor`-typed gradient return 1, whatever its components are, so read Enzyme's `Rotor` +gradients with `components(g)`. + +**`QuatVec` arguments and outputs.** A `QuatVec` has zero scalar part, so tangents and +cotangents of `QuatVec`s have zero scalar part, and the scalar component of the input is +treated as a constant. The ChainRules rules return `QuatVec` cotangents for `QuatVec` +arguments. Enzyme and Mooncake differentiate the stored components structurally, so +the scalar slot of their raw gradient may be nonzero when the code reads it; that slot +should be ignored (for example, by using `vec(g)`). + +**Complex components.** Quaternions with complex components (such as the [`Lorentz`](@ref) +transformations) follow ChainRules' convention for complex numbers: a pullback applies +the conjugate transpose of the Jacobian on ``\mathbb{C}^4``. Quaternion multiplication is +bilinear over ``\mathbb{C}``, so the pullback of ``x \mapsto a\, x\, b`` is ``\Delta +\mapsto a^\dagger\, \Delta\, b^\dagger``, where ``a^\dagger`` is the quaternion +conjugate of the componentwise complex conjugate of ``a``. For real components, +``a^\dagger = \bar{a}``, and this reduces to the real convention. ## Simple generalization of complex differentiation @@ -202,7 +278,7 @@ these matrices. For example, our function might be ``\mathbb{R} \to ```math f(w) = s(w) + 𝐢 t(w) + 𝐣 u(w) + 𝐤 v(w). ``` -So the `rrule` would just look like +So the `rrule` would just look like ```math \tfrac{\partial s}{\partial w} \, \Delta s + \tfrac{\partial t}{\partial w} \, \Delta t + \tfrac{\partial u}{\partial w} \, \Delta u + \tfrac{\partial v}{\partial w} \, \Delta v = @@ -221,31 +297,33 @@ So the `rrule` would just look like ``` Or we might have a function ``\mathbb{H} \to \mathbb{R}``: ```math -f(w, x, y, z) = s(w, x, y, z), +f(w + 𝐢 x + 𝐣 y + 𝐤 z) = s(w, x, y, z), ``` -so the `rrule` would look like +so the pullback maps the scalar cotangent ``\Delta s`` to the +quaternion ```math -\tfrac{\partial s}{\partial w} \, \Delta s + \tfrac{\partial t}{\partial w} \, \Delta t + \tfrac{\partial u}{\partial w} \, \Delta u + \tfrac{\partial v}{\partial w} \, \Delta v -= +\tfrac{\partial s}{\partial w} \, \Delta s ++ 𝐢 \, \tfrac{\partial s}{\partial x} \, \Delta s ++ 𝐣 \, \tfrac{\partial s}{\partial y} \, \Delta s ++ 𝐤 \, \tfrac{\partial s}{\partial z} \, \Delta s, +\qquad\text{or, in matrix form,}\qquad \begin{pmatrix} \tfrac{\partial s}{\partial w} -& -\tfrac{\partial t}{\partial w} -& -\tfrac{\partial u}{\partial w} -& -\tfrac{\partial v}{\partial w} +\\ +\tfrac{\partial s}{\partial x} +\\ +\tfrac{\partial s}{\partial y} +\\ +\tfrac{\partial s}{\partial z} \end{pmatrix} -\begin{pmatrix} -\Delta s \\ \Delta t \\ \Delta u \\ \Delta v -\end{pmatrix}. +\Delta s. ``` Similarly, we can extend this with multiple arguments — ``\mathbb{R}``, ``\mathbb{H}``, or other — by appending those -arguments to ``s``, ``t``, ``u``, and ``v``, for example. And -equivalently for the outputs. For example, a function +arguments to the arguments of ``s``, ``t``, ``u``, and ``v``, and +similarly for multiple outputs. For example, a function ``\mathbb{R} \times \mathbb{H} \to \mathbb{H}`` would look like ```math f(\sigma, w, x, y, z) = @@ -291,45 +369,181 @@ output are expanded to arrays, the AD proceeds as usual, and then the resulting arrays are reshaped back into quaternions as needed. -## Applications to `QuatVec` and `Rotor` - -To understand how this works for `QuatVec` and `Rotor` inputs or -outputs, we just consider that these are submanifolds of the -`Quaternion` manifold. The only subtlety is that — while the tangent -space to `Quaternion` and `QuatVec` are naturally identified with -`Quaternion` and `QuatVec` themselves — the tangent space of the -`Rotor` submanifold is naturally identified with `Quaternion`. - -Thus, for a `QuatVec` input, ``w`` must always be 0, which means that -the tangent must always have ``\Delta w = 0``, and we always treat the -output functions ``(s,t,u,v)`` as independent of ``w`` so that -``\partial s / \partial w`` and so on are always 0. Similarly, for -`QuatVec` outputs, ``s`` must always be 0, so that the tangent must -always have ``\Delta s = 0``, and ``\partial s / \partial w`` and so -on are always 0. With these considerations in mind, it's not hard to -simplify the expressions above for `QuatVec` inputs and outputs. - -On the other hand, because the tangent space to the `Rotor` -submanifold is naturally identified with `Quaternion`, while there is -a natural constraint on the norms of the input and output arguments, -there are no structural constraints on the tangent vectors (just that -they must be orthogonal to the arguments themselves, when viewed as -vectors in ``\mathbb{R}^4`` with the Euclidean metric). Thus, the -expressions above for `Quaternion` inputs and outputs will look -formally identical for `Rotor` inputs or outputs. - - -## Older functions - -In this vein, we also have some very explicit functions for computing "primals" -(values) and derivatives of functions of `log` and `exp`. These are older, and -likely to be deprecated at some point in favor of `ChainRulesCore`-based AD. -Also, because of massive simplifications that result when using the right types, -these derivatives are more strict about input types than the main functions -themselves. For example, the derivatives of `exp` are defined only for -`QuatVec` arguments; the derivatives of `log` are defined only for `Rotor` -arguments; etc. +## Quaternions at the boundary of a differentiated function + +Every package in the table above can differentiate functions that use +quaternions *internally*, in whatever combination of operations the +function needs. The questions in this section concern only the +*boundary* of the function being differentiated: the arguments that +the AD package differentiates with respect to, and the final output. +Because `AbstractQuaternion <: Number`, a generic AD interface sees a +quaternion there as a single scalar, and would compute the derivative +of (or with respect to) its scalar part only. This package therefore +adds methods to the AD packages so that each such case either gives +the full derivative or raises an `ArgumentError` explaining what to do +instead; none silently returns a partial result. + +The pattern that works with every package is to write the function so +that its argument is a real number or a real array, from which it +builds any quaternions it needs, and its output is a real number or a +real array, such as `collect(components(q))` or `to_float_array(qs)`. +The tests of this package use that pattern throughout. + +**Quaternion-valued outputs.** For a function ``f`` of a real +variable ``t`` (or of a real vector ``x``) whose output is a +quaternion, or an array of quaternions: + +| Call | Result | +|:-----|:-------| +| `ForwardDiff.derivative(f, t)` | The full derivative: a `Quaternion` (a `QuatVec` if the output is a `QuatVec`), or an array of them | +| `ForwardDiff.jacobian(f, x)` with an array of quaternions as output | A matrix of quaternions, whose entry ``(i, j)`` is the derivative of the ``i``th output with respect to ``x_j`` | +| `Enzyme.autodiff(Forward, …)` and `Enzyme.jacobian(Forward, f, x)` | The full derivatives, with quaternion entries | +| `DifferentiationInterface.derivative` and `pushforward` | The full derivative with `AutoForwardDiff`, `AutoZygote`, and `AutoEnzyme` in either mode, through an extension of this package that seeds reverse-mode pullbacks with each of the four units; see below for the exceptions | +| `DifferentiationInterface.jacobian` of an array of quaternions | A matrix of quaternions in forward mode (`AutoForwardDiff`, `AutoEnzyme(mode=Forward)`); an `ArgumentError` in reverse mode | +| `Zygote.gradient` and `Zygote.jacobian` | An `ArgumentError`, as Zygote raises for complex outputs. An explicit pullback from `Zygote.pullback`, applied to the cotangents ``1``, ``𝐢``, ``𝐣``, and ``𝐤`` in turn, gives the four components of the derivative | +| `ReverseDiff.gradient` and `ReverseDiff.jacobian` | An `ArgumentError` | +| `Enzyme.gradient(Reverse, …)` and `Enzyme.jacobian(Reverse, …)` | An error from Enzyme, which requires real outputs in reverse mode | +| `Mooncake.value_and_gradient!!` | An error from Mooncake, which requires a floating-point output; `Mooncake.value_and_pullback!!` with an explicit Mooncake tangent works | + +The exceptions with `DifferentiationInterface.derivative` are these: +with `AutoMooncakeForward` the derivative is returned as Mooncake's +structural `Tangent` rather than as a `Quaternion`; with reverse-mode +`AutoMooncake` it raises an error, because Mooncake requires the seed +of a struct-valued output to be its own tangent type; and with +reverse-mode `AutoEnzyme` a `QuatVec`-valued function raises an error, +because Enzyme requires a `QuatVec` seed while +DifferentiationInterface seeds with `oneunit(y)`, which is a +`Quaternion`. + +**Quaternion arguments.** For a real-valued function of a quaternion +argument ``q``, or of an array of quaternions: + +* Reverse-mode gradients work: `Zygote.gradient`, + `Enzyme.gradient(Reverse, …)`, and Mooncake (directly or through + `DifferentiationInterface.gradient`) return gradients of the types + listed in the table of [Supported AD packages](@ref). +* `Enzyme.gradient(Forward, f, q)` returns a tuple of the four partial + derivatives for a single quaternion, and raises an `ArgumentError` + for an array of quaternions, because Enzyme's forward-mode seeds for + arrays would perturb only the scalar parts. +* ForwardDiff and ReverseDiff accept only real numbers and real arrays + as arguments. +* `DifferentiationInterface.derivative` with respect to a single + quaternion argument returns the derivative along `oneunit(q)` — that + is, with respect to the scalar component only — just as it does for + a `Complex` argument. This is how DifferentiationInterface defines + the derivative, so it is not changed here, but it is rarely what is + wanted; use a gradient, or pass the components as a real vector. +* Forward-mode `DifferentiationInterface.gradient` and `jacobian` with + respect to an array of quaternions raise an `ArgumentError`, for the + same reason as with Enzyme. + + +## Known limitations + +The following limitations are known. Several of them are bugs in the +AD packages themselves, which have been reported or reproduced +upstream. Each item says whether it applies *anywhere* in the +function being differentiated, or only at its *boundary* (its +arguments and final output, as described in the previous section). + +**Zygote** + * Anywhere: functions that mutate arrays cannot be differentiated: + `squad`, `unflip`, `unflip!`, `slerp` with the `unflip=true` + keyword, and `to_euler_phases!`. + * Anywhere: `to_float_array` and `from_float_array` use + `reinterpret`, for which Zygote has no adjoint. + * Anywhere: products of matrices of quaternions are not supported, + because ChainRules restricts its array rules to commutative number + types. + * Anywhere: `Zygote.hessian` through `from_rotation_matrix` is not + tested. + * Boundary only: `Zygote.jacobian` fails for functions that splat + their vector argument, such as `x -> from_euler_angles(x...)`, + although `Zygote.gradient` works. This is a limitation of Zygote + with any splatted argument, not only with quaternions. + +**Enzyme** + * Anywhere: `align` applied to vectors of `QuatVec`s or `Rotor`s, + and the forward-over-reverse Hessian of `sqrt`, need + `Enzyme.set_runtime_activity` on the mode. + * Anywhere: batched reverse mode (batch width greater than 1, which + DifferentiationInterface uses for Jacobians) crashes the compiler + on `squad` and `unflip`. Gradients of scalar functions (batch + width 1) work. + +**Mooncake** + * Anywhere: forward-over-reverse Hessians are affected by two bugs + in Mooncake. The Hessian of a product with a factor that is + exactly zero is silently wrong, which affects `log` at quaternions + with zero vector part (including the identity). The Hessian of + `atan(y, x)` at `x = 0` throws an error about `bitcast`, which + affects `log` and real powers of pure-vector quaternions. First + derivatives in both modes are correct. + * Boundary only: `Mooncake.TestUtils.test_rule` cannot be used with + `QuatVec` arguments, because its finite differences perturb the + hidden scalar slot. + +**ReverseDiff** + * Anywhere: compiled or replayed tapes freeze value-dependent + branches at the point where the tape was recorded. The functions + in this package switch between formulas (for example, to series + expansions near the identity) at thresholds where the formulas + agree to rounding error, so a tape recorded at a generic point is + accurate everywhere except exactly at the special points: the + identity, quaternions with zero vector part, and the negative real + axis. Uncompiled `ReverseDiff.gradient` re-records the tape on + each call and has no such problem. + +**FastDifferentiation** + * Anywhere: FastDifferentiation cannot follow branches that depend + on the values of variables. Functions that choose an algorithm + that way — `exp`, `log`, `sqrt`, non-integer powers, powers of + `Rotor`s, `to_euler_phases`, and `from_euler_phases` — raise an + error explaining this when called with FastDifferentiation + variables. + * Anywhere: integer powers are also disabled, because + FastDifferentiation itself returns incorrect Jacobians for some of + them. The same upstream problem gives wrong Jacobians for some + expressions in which several products share a common + subexpression, such as the rotation matrix of a normalized rotor, + so results from FastDifferentiation should be checked + independently. + +**Symbolics** + * Anywhere: a few functions, such as `sqrt`, choose an algorithm by + comparing the values of components, and raise an error + ("non-boolean (Num) used in boolean context") for symbolic + components. + + +## For AD and extension authors + +The functions below help code that must work both with ordinary +numbers and with the number types of AD packages, such as +ForwardDiff's `Dual` and ReverseDiff's `TrackedReal`. The extensions +for those packages add methods to `value`, so that thresholds and +special cases in this package are chosen by the values of the +components rather than by their derivative parts. + +```@docs +Quaternionic.value +Quaternionic.iszerovalue +``` + + +## Explicit derivatives of `exp` and `log` + +This package also provides some very explicit functions for computing +values and derivatives of `log` and `exp`. These are older, and may +be deprecated at some point in favor of AD. Because of the +simplifications that result from using the right types, these +derivatives are more strict about input types than the main functions +themselves: the derivatives of `exp` are defined only for `QuatVec` +arguments, and the derivatives of `log` are defined only for `Rotor` +arguments. Analytic derivatives of `slerp` and `squad` are described +in [Functions of time](@ref). ```@autodocs Modules = [Quaternionic] diff --git a/docs/src/distances.md b/docs/src/distances.md new file mode 100644 index 00000000..a3227cd7 --- /dev/null +++ b/docs/src/distances.md @@ -0,0 +1,73 @@ +# Distances and alignment + +There are several ways of measuring the "distance" between two +quaternions: ``d(q_1, q_2)``. Fundamentally, any comparison between +two quaternions ``q_1`` and ``q_2`` must make use of a binary +operation, for which there are two obvious choices: addition or +multiplication. For either choice, we operate on ``q_1`` and the +appropriate inverse (either additive or multiplicative) of ``q_2``. +That is, ``d`` should be a function of either ``q_1 - q_2`` or +``q_1/q_2``.[^1] + +[^1]: For ``q_1/q_2``, we are dealing with the *multiplicative* group + of quaternions, which does not include 0, so we will assume that + no quaternion involved in such a function can be 0. + +Now, we also have a number of criteria we would like any distance +function to satisfy. For any quaternions ``q_1`` and ``q_2`` and any +*unit* quaternion ``q_3``, we require + + * real-valued: ``d(q_1, q_2) \in \mathbb{R}`` + * symmetry: ``d(q_1, q_2) = d(q_2, q_1)`` + * invariance: ``d(q_3\, q_1, q_3\, q_2) = d(q_1, q_2) = d(q_1\, q_3, q_2\, q_3)`` + * identity: ``d(q_1, q_1) = 0`` + * positive-definiteness: ``d(q_1, q_2) > 0`` whenever ``q_1 ≠ q_2`` + +(Of course, it should be noted that these criteria all hold in the +*exact* case; when using floating-point numbers, they will likely be +violated near edge cases.) + +It is not hard to see that these criteria can be satisfied by any of + + * `abs(q₁ - q₂)` + * `abs2(q₁ - q₂)` + * `abs(log(q₁ / q₂))` + * `abs2(log(q₁ / q₂))` + +If ``q_1`` and ``q_2`` are interpreted as rotations, we frequently +don't care about their signs, and just want the *smallest* distance +between them, for any choice of sign. Furthermore, in the +multiplicative case, the `log` functions will involve calculation of +the `log` of the magnitudes of the quaternions, which should be 1. In +this case, we relax the "positive-definiteness" criterion to allow +``d(q_1, q_2)`` to equal zero when ``q_1`` and ``q_2`` are related by +a nonzero scalar multiple. + +For `Rotor` types, the latter two multiplicative options are most +relevant, while for other types the additive options are more +relevant. These are the default behaviors of the `distance` and +`distance2` functions, which are documented together below. + +```@autodocs +Modules = [Quaternionic] +Pages = ["distance.jl"] +``` + + +## Alignment + +There are many ways to optimize alignment with rotations. In +particular, we can seek the optimal rotation that takes one set of +points onto a corresponding set of points, or the optimal quaternion +that takes one set of quaternions onto a corresponding set of +quaternions. In both cases, the "optimal" value depends on the metric +being used. The simplest and most robust results are obtained when +the metric is the standard Euclidean metric (in the case of points), +or the magnitude of the difference (in the case of quaternions). +Here, we assume that `QuatVec`s represent points, and any other type +of quaternion should be treated as rotors. + +```@autodocs +Modules = [Quaternionic] +Pages = ["alignment.jl"] +``` diff --git a/docs/src/functions.md b/docs/src/functions.md deleted file mode 100644 index 2d9a4c0a..00000000 --- a/docs/src/functions.md +++ /dev/null @@ -1,35 +0,0 @@ -# Function list - -Functions that operate on `Quaternion`, `Rotor`, and `QuatVec` types -are defined both in the `Quaternionic` module and in Julia's own -`Base` and `LinearAlgebra` modules. The functions defined in the -`Base` module are generally standard mathematical functions that have -been extended to work with quaternions, while the functions defined in -the `Quaternionic` module are more specialized functions that are -specific to quaternion algebra. - -## External functions - - * [`Base.conj`](@ref) - * [`Base.abs`](@ref) - * [`Base.abs2`](@ref) - * [`Base.angle`](@ref) - * [`Base.exp`](@ref) - * [`Base.log`](@ref) - * [`Base.sqrt`](@ref) - * [`Base.:^`](@ref) - * [`LinearAlgebra.:⋅`](@ref) (a.k.a. `LinearAlgebra.dot`) - -In addition, many other functions from `Base` that are not listed here -have also been extended to work with quaternionic types, so that -quaternions can generally function as numbers. This includes -functions such as `+`, `-`, `*`, `/`, `inv`, `==`, `isequal`, `isnan`, -`isinf`, `iszero`, `isone`, `show`, `read`, `write`, `hash`, -`promote_rule`, and so on. These are not separately documented, but -should behave analogously to their behavior with `Complex` numbers. - -## Functions defined in `Quaternionic` - -```@index -Modules = [Quaternionic] -``` diff --git a/docs/src/functions_of_time.md b/docs/src/functions_of_time.md index 0aaa16c0..174edde9 100644 --- a/docs/src/functions_of_time.md +++ b/docs/src/functions_of_time.md @@ -1,149 +1,164 @@ # Functions of time -When using quaternions to represent rotations and orientations, we frequently -model dynamical systems, which means that the quaternions must be regarded as -functions of time. The preceding functions can all be applied at each instant -of time, but we also need to be deal with the *change* of quaternions over -time, for which there are several important techniques: +When using quaternions to represent rotations and orientations, we +frequently model dynamical systems, which means that the quaternions +must be regarded as functions of time. The preceding functions can +all be applied at each instant of time, but we also need to deal with +the *change* of quaternions over time, for which there are several +important techniques: - * [Interpolation](@ref) — Taking discretely sampled quaternionic time series and - interpolating to different samples, and possibly differentiating. - * [Angular velocity](@ref) — Both differentiation of a quaternionic function of time - to get angular velocity, and integration of angular velocity to get an - orientation as a function of time. - * [Minimal rotation](@ref) — Finding the *least* dynamical motion that can achieve - pointing in a certain direction. - * [Differentiating by quaternionic arguments](@ref) — Thanks to the [chain + * [Interpolation](@ref) — Taking discretely sampled quaternionic + time series and interpolating to different samples, and possibly + differentiating. + * [Angular velocity](@ref) — Both differentiation of a quaternionic + function of time to get angular velocity, and integration of + angular velocity to get an orientation as a function of time. + * [Minimal rotation](@ref) — Background on finding the *least* + dynamical motion that can achieve pointing in a certain direction. + (No function for this is provided by the package.) + * [Differentiating by quaternionic arguments](@ref) — Thanks to the + [chain rule](https://en.wikipedia.org/wiki/Chain_rule#Multivariable_case), - differentiating many nontrivial quaternionic functions of time will also - involve differentiating with respect to components of quaternionic - arguments. + differentiating many nontrivial quaternionic functions of time + will also involve differentiating with respect to components of + quaternionic arguments. ## Interpolation -Component-wise interpolation of quaternions does not generally yield good -results when the quaternions are interpreted as rotations. The basic reason is -that rotations correspond to *unit* quaternions, but component-wise -interpolation does not respect this constraint. There are two specialized -functions for dealing with this problem. The first is [`slerp`](@ref), which -is an abbreviation of "Spherical Linear intERPolation", and is the direct -analog of standard linear interpolation of functions ℝ → ℝ. The second is -[`squad`](@ref), which is an abbreviation of "Spherical QUADrangle -interpolation", and is more analogous to cubic interpolation by Bézier splines. -The first is relatively fast but has discontinuous first derivatives at the -input points, while the second is somewhat slower but has continuous first and -second derivatives. +Component-wise interpolation of quaternions does not generally yield +good results when the quaternions are interpreted as rotations. The +basic reason is that rotations correspond to *unit* quaternions, but +component-wise interpolation does not respect this constraint. There +are two specialized functions for dealing with this problem. The +first is [`slerp`](@ref), which is an abbreviation of "Spherical +Linear intERPolation", and is the direct analog of standard linear +interpolation of functions ℝ → ℝ. The second is [`squad`](@ref), +which is an abbreviation of "Spherical QUADrangle interpolation", and +is more analogous to cubic interpolation by Bézier splines. The first +is relatively fast but has discontinuous first derivatives at the +input points, while the second is somewhat slower but has a continuous +first derivative (and therefore a continuous angular velocity). The +second derivative of `squad` is generally discontinuous at the input +points. -In both cases, it is important for extraneous sign flips to be eliminated -before passing quaternions to the interpolating functions. For this purpose, -there is the [`unflip`](@ref) utility function, which can also be called -automatically by passing the corresponding keywords to `slerp` and `squad`. +In both cases, it is important for extraneous sign flips to be +eliminated before passing quaternions to the interpolating functions. +For this purpose, there is the [`unflip`](@ref) utility function, +which can also be called automatically by passing the corresponding +keywords to `slerp` and `squad`. -It can be very useful to compute the derivative of various functions with -respect to their arguments — for example, when computing angular velocity of a -`squad` interpolant.[^1] See [Differentiating by quaternionic arguments](@ref) for -more details. The value *and derivative* of `slerp` can be simultaneously -evaluated and differentiated analytically with [`slerp∂slerp∂τ`](@ref) (or -automatically with `ForwardDiff`). While, `squad` and its derivative can be -evaluated with [`squad∂squad∂t`](@ref), this is a relatively low-level function; -it is easier to use the relevant keyword arguments to [`squad`](@ref). +It can be very useful to compute the derivative of various functions +with respect to their arguments — for example, when computing angular +velocity of a `squad` interpolant.[^1] See [Differentiating by +quaternionic arguments](@ref) for more details. The value *and +derivative* of `slerp` can be simultaneously evaluated and +differentiated analytically with [`slerp∂slerp∂τ`](@ref) (or +automatically with `ForwardDiff`). While `squad` and its derivative +can be evaluated with [`squad∂squad∂t`](@ref), this is a relatively +low-level function; it is easier to use the relevant keyword arguments +to [`squad`](@ref). -[^1]: - Essentially, we treat each quaternionic argument as a series of four real - arguments. For each input argument, the output is generally a quaternion; - interpreting those outputs as also being a series of four real quantities, these - derivatives could also be thought of as [Jacobian - matrices](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant) of the - relevant functions, though the actual return types are collections of - `Quaternion` objects. +[^1]: Essentially, we treat each quaternionic argument as a series of + four real arguments. For each input argument, the output is + generally a quaternion; interpreting those outputs as also being a + series of four real quantities, these derivatives could also be + thought of as [Jacobian + matrices](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant) + of the relevant functions, though the actual return types are + collections of `Quaternion` objects. ```@autodocs Modules = [Quaternionic] -Pages = ["interpolation.jl"] +Pages = ["src/interpolation.jl", "src/gradients_interpolation.jl"] +Filter = f -> f !== Quaternionic.squad_control_points ``` Note that gradients can also be calculated automatically using -[`ForwardDiff.jl`](https://juliadiff.org/ForwardDiff.jl/).[^2] For example, we -could compute the derivative of `slerp` with respect to the `y` component of -the first input quaternion as +[`ForwardDiff.jl`](https://juliadiff.org/ForwardDiff.jl/).[^2] For +example, we could compute the derivative of `slerp` with respect to +the `y` component of the first input quaternion as ```julia ∂slerp∂q₁y(q₁, q₂, τ) = ForwardDiff.derivative(ϵ->slerp(q₁+ϵ*imy, q₂, τ), 0) ``` This is equal to ```julia -s, ∂s∂t = slerp∂slerp(q₁, q₂, τ) -∂s∂t[3] +s, ∂s∂q₁, ∂s∂q₂, ∂s∂τ = slerp∂slerp(q₁, q₂, τ) +∂s∂q₁[3] ``` though `slerp∂slerp` computes the value and all derivatives of `slerp` -simultaneously, and does at least as fast as most AD systems would. -Nonetheless, it is useful to know that `ForwardDiff` can process functions -*involving* `Quaternionic` methods. +simultaneously, and is at least as fast as most AD systems would be. +Nonetheless, it is useful to know that `ForwardDiff` can process +functions *involving* `Quaternionic` methods. -[^2]: - There is also support for using other AD systems via `ChainRulesCore`. Those - are somewhat more complicated than just using `ForwardDiff`, so there may be - cases where the support is incomplete or incorrect. Please open [an issue](https://github.com/moble/Quaternionic.jl/issues) - (or Pull Request) if you find such cases. +[^2]: Other AD systems are also supported, with some limitations that + are described in [Differentiating by quaternionic + arguments](@ref). Please open [an + issue](https://github.com/moble/Quaternionic.jl/issues) (or pull + request) if you find cases where the support is incomplete or + incorrect. ## Angular velocity -Given a quaternionic function of time ``q(t)``, we can — in principle — -differentiate it to find ``\dot{q}(t)``. This is related to the more familiar -[angular velocity](https://en.wikipedia.org/wiki/Angular_velocity) +Given a quaternionic function of time ``q(t)``, we can — in principle +— differentiate it to find ``\dot{q}(t)``. This is related to the +more familiar [angular +velocity](https://en.wikipedia.org/wiki/Angular_velocity) ``\vec{\omega}`` by the equation ```math \vec{\omega} = 2 \dot{q}\, q^{-1}. ``` -While ``\dot{q}(t)`` can certainly be useful, it "lives" in a four-dimensional -space, which means that it takes a little more work to relate to our -three-dimensional space. On the other hand, the direction of ``\vec{\omega}`` -represents the instantaneous axis of rotation in our three-dimensional space, -and its magnitude describes the rate of rotation about that axis. More -importantly, many results from physics describe rotations in terms of -``\vec{\omega}``, rather than ``\dot{q}(t)``. So generally, we need a way to -go from ``q(t)`` to ``\vec{\omega}(t)`` — and back. +While ``\dot{q}(t)`` can certainly be useful, it "lives" in a +four-dimensional space, which means that it takes a little more work +to relate to our three-dimensional space. On the other hand, the +direction of ``\vec{\omega}`` represents the instantaneous axis of +rotation in our three-dimensional space, and its magnitude describes +the rate of rotation about that axis. More importantly, many results +from physics describe rotations in terms of ``\vec{\omega}``, rather +than ``\dot{q}(t)``. So generally, we need a way to go from ``q(t)`` +to ``\vec{\omega}(t)`` — and back. -The details of this process and some examples are discussed in full in [this -paper](https://arxiv.org/abs/1604.08139). +The details of this process and some examples are discussed in full in +[this paper](https://arxiv.org/abs/1604.08139). -Taking ``q(t)`` and obtaining ``\vec{\omega}(t)`` is fairly straightforward: -one simply needs to obtain ``\dot{q}(t)`` and apply the equation above. If -``q(t)`` is known analytically, it may be possible to compute ``\dot{q}`` -directly (as in the example from Sec. 6.2 of [the -paper](https://arxiv.org/abs/1604.08139)). But ordinarily, this is a difficult -task. For numerical functions automatic differentiation can be used to obtain -a numerical result for ``\dot{q}`` (see [below](#Gradient)). Or, if ``q`` is -discretely sampled, [`squad`](@ref) (with the relevant keyword arguments) can -be used to find the derivative of the interpolant at any instant and/or the -corresponding angular velocity. +Taking ``q(t)`` and obtaining ``\vec{\omega}(t)`` is fairly +straightforward: one simply needs to obtain ``\dot{q}(t)`` and apply +the equation above. If ``q(t)`` is known analytically, it may be +possible to compute ``\dot{q}`` directly (as in the example from Sec. +6.2 of [the paper](https://arxiv.org/abs/1604.08139)). But +ordinarily, this is a difficult task. For numerical functions +automatic differentiation can be used to obtain a numerical result for +``\dot{q}`` (see [Differentiating by quaternionic arguments](@ref)). +Or, if ``q`` is discretely sampled, [`squad`](@ref) (with the relevant +keyword arguments) can be used to find the derivative of the +interpolant at any instant and/or the corresponding angular velocity. -Going the other way, obtaining ``q(t)`` from ``\vec{\omega}(t)``, is more -delicate — though still possible. It requires integrating the ordinary -differential equation +Going the other way, obtaining ``q(t)`` from ``\vec{\omega}(t)``, is +more delicate — though still possible. It requires integrating the +ordinary differential equation ```math \dot{q} = \frac{1}{2} \vec{\omega}\, q, ``` -which is just a rearrangement of the equation above to solve for ``\dot{q}``. -Standard theorems on differential equations tell us that this equation has a -solution for ``q(t)`` as long as we know ``\vec{\omega}`` as a function of time -(and possibly of ``q``, but not ``\dot{q}``), and supply an initial value for -``q`` at some instant of time. Note that [the -paper](https://arxiv.org/abs/1604.08139) noted above found that integrating -this equation without any restriction on the norm of ``q`` is generally the -most accurate and efficient choice. However, with loose integration -tolerances, numerical error may result in the output ``q(t)`` having norm -significantly different from 1. In this case, to use ``q`` as a rotation, -you can normalize the result, or simply apply it by "true" conjugation with the -inverse as in +which is just a rearrangement of the equation above to solve for +``\dot{q}``. Standard theorems on differential equations tell us that +this equation has a solution for ``q(t)`` as long as we know +``\vec{\omega}`` as a function of time (and possibly of ``q``, but not +``\dot{q}``), and supply an initial value for ``q`` at some instant of +time. Note that [the paper](https://arxiv.org/abs/1604.08139) noted +above found that integrating this equation without any restriction on +the norm of ``q`` is generally the most accurate and efficient choice. +However, with loose integration tolerances, numerical error may result +in the output ``q(t)`` having norm significantly different from 1. In +this case, to use ``q`` as a rotation, you can normalize the result, +or simply apply it by "true" conjugation with the inverse as in ```math q\, \vec{v}\, q^{-1}, ``` rather than using ``\bar{q}`` in the last factor. -If `DifferentialEquations.jl` is available, we can solve the ODE with code like -this: +If `DifferentialEquations.jl` is available, we can solve the ODE with +code like this: ```julia using Quaternionic using DifferentialEquations @@ -161,35 +176,37 @@ angular_velocity_problem = ODEProblem(angular_velocity_ode, quaternion(q₀), ts # Now, solve it q = solve(angular_velocity_problem, Vern9(), abstol=1e-12, reltol=0) ``` -Here, we have constructed a very simple `ω⃗` function — which can actually be -integrated analytically — but it could be any callable that returns a `QuatVec` -(or `Quaternion`). Note that the initial condition `q₀` has to be a -`Quaternion` on input to `ODEProblem` because `DifferentialEquations.jl` tries -to construct a zero element of that type, which is impossible for a `Rotor`. -This initial condition is also used for the output type and — as mentioned -above — numerical errors will tend to move the norm away from 1, so a `Rotor` -would not make sense anyway. The choices of `Vern9` and `abstol=1e-12` here -are quite stringent, and may be overkill for many problems. It is recommended -to set `reltol=0` in all cases. +Here, we have constructed a very simple `ω⃗` function — which can +actually be integrated analytically — but it could be any callable +that returns a `QuatVec` (or `Quaternion`). Note that the initial +condition `q₀` has to be a `Quaternion` on input to `ODEProblem` +because `DifferentialEquations.jl` tries to construct a zero element +of that type, which is impossible for a `Rotor`. This initial +condition is also used for the output type and — as mentioned above — +numerical errors will tend to move the norm away from 1, so a `Rotor` +would not make sense anyway. The choices of `Vern9` and +`abstol=1e-12` here are quite stringent, and may be overkill for many +problems. It is recommended to set `reltol=0` in all cases. -The `q` that results from `solve` contains the time steps `q.t` at which the -solution was found along with the solution values `q.u` at each of those time -steps, but can also be used as a function of time to compute the value `q(t)` -at an arbitrary time in `tspan`. In this simple case, we can compute the exact -value of, and compare it to the result of integration: +The `q` that results from `solve` contains the time steps `q.t` at +which the solution was found along with the solution values `q.u` at +each of those time steps, but can also be used as a function of time +to compute the value `q(t)` at an arbitrary time in `tspan`. In this +simple case, we can compute the exact value of, and compare it to the +result of integration: ```julia q_exact = @. exp([Ω⃗] * q.t / 2) * q₀ maximum(distance.(q.u, q_exact)) ``` -Typical numbers for this maximum error are roughly `1e-14`, though they -increase as `tspan` is increased. +Typical numbers for this maximum error are roughly `1e-14`, though +they increase as `tspan` is increased. -Also note that this simple version involves allocations at each time step. If -this is problematic, it should be easy to [define in-place +Also note that this simple version involves allocations at each time +step. If this is problematic, it should be easy to [define in-place updating](https://diffeq.sciml.ai/dev/tutorials/ode_example/#Example-2:-Solving-Systems-of-Equations) -versions of `ω⃗` and `angular_velocity_ode` to eliminate allocations, using -vectors to hold the numbers instead of quaternions, and an expression like this -for the ODE: +versions of `ω⃗` and `angular_velocity_ode` to eliminate allocations, +using vectors to hold the numbers instead of quaternions, and an +expression like this for the ODE: ```julia dqdt[1] = (q[2]*ω⃗t[2] + q[3]*ω⃗t[3] + q[4]*ω⃗t[4]) / -2 dqdt[2] = (q[1]*ω⃗t[2] - q[3]*ω⃗t[4] + q[4]*ω⃗t[3]) / 2 @@ -197,14 +214,15 @@ for the ODE: dqdt[4] = (q[1]*ω⃗t[4] - q[2]*ω⃗t[3] + q[3]*ω⃗t[2]) / 2 ``` -There is a particularly useful complicated but analytic example available here: +There is a particularly useful complicated but analytic example +available here: ```@autodocs Modules = [Quaternionic] Pages = ["examples.jl"] ``` -Because this is an analytic solution, we know that `R(t)` and `ω⃗(t)` output by -this function are consistent with each other to within numerical accuracy. We -can check that our integration scheme agrees: +Because this is an analytic solution, we know that `R(t)` and `ω⃗(t)` +output by this function are consistent with each other to within +numerical accuracy. We can check that our integration scheme agrees: ```julia R, ω⃗, Ṙ = precessing_nutating_example() angular_velocity_ode(q, ω⃗, t) = ω⃗(t) * q / 2 @@ -212,53 +230,64 @@ tspan = (0., 100_000.) angular_velocity_problem = ODEProblem(angular_velocity_ode, quaternion(R(tspan[1])), tspan, ω⃗) q = solve(angular_velocity_problem, Vern9(), abstol=1e-12, reltol=0); ``` -To check the difference between the analytic `R` and the integrated `q.u`, we -evaluate +To check the difference between the analytic `R` and the integrated +`q.u`, we evaluate ```julia julia> maximum(distance.(R.(q.t), RotorF64.(q.u))) 3.655365559565175e-13 ``` -The maximum error is consistent with time-stepping error, so we can have -confidence that other `ω⃗` functions would be correctly integrated also. +The maximum error is consistent with time-stepping error, so we can +have confidence that other `ω⃗` functions would be correctly +integrated also. ## Minimal rotation -One common problem arises when a system must be rotated to align some axis with -some direction, while the rotation of the system *about* that axis is -irrelevant. To be specific, suppose we want to rotate our basis vectors -``\hat{x}, \hat{y}, \hat{z}`` so that ``\hat{z}`` points in a particular -direction. A naive approach may be to determine the direction in terms of -spherical coordinates ``(\theta, \phi)``, and then use the rotation determined -by Euler angles ``(\alpha, \beta, \gamma) = (\phi, \theta, 0)``. However, as -with most applications of Euler angles, this is a terrible idea. The resulting -orientation will be extremely sensitive to the direction whenever it happens to -be near the poles. In such cases, the angular velocity of the system will be -very high — potentially infinite, in principle. +!!! note + This section is background only: the package does not provide a + function that computes the minimal rotation, but the recipe below + can be implemented with the functions it does provide. -A *slightly* better approach would be to use ``(\alpha, \beta, \gamma) = (\phi, -\theta, -\phi)``, which is the most direct rotation from the ``z`` axis to the -point given by ``(\theta, \phi)``, and behaves better in the limit of small -``\theta``. However, this only works for rotations directly from the ``z`` -axis; the result depends on the choice of coordinates, and is not the best -choice for tracking general motion of the target axis. +One common problem arises when a system must be rotated to align some +axis with some direction, while the rotation of the system *about* +that axis is irrelevant. To be specific, suppose we want to rotate +our basis vectors ``\hat{x}, \hat{y}, \hat{z}`` so that ``\hat{z}`` +points in a particular direction. A naive approach may be to +determine the direction in terms of spherical coordinates ``(\theta, +\phi)``, and then use the rotation determined by Euler angles +``(\alpha, \beta, \gamma) = (\phi, \theta, 0)``. However, as with +most applications of Euler angles, this is a terrible idea. The +resulting orientation will be extremely sensitive to the direction +whenever it happens to be near the poles. In such cases, the angular +velocity of the system will be very high — potentially infinite, in +principle. -Fortunately, it is possible to take *any* rotor ``R_\mathrm{axis}(t)`` that -aligns the axis correctly, and compute another rotation that also aligns the -axis, but has the smallest possible angular velocity. This is called the -"minimal rotation". The general problem is discussed (by way of a very -specific physical situation) in detail in Sec. III and Appendix B of [this -paper](https://arxiv.org/abs/1110.2965). Essentially, we solve the equation +A *slightly* better approach would be to use ``(\alpha, \beta, \gamma) += (\phi, \theta, -\phi)``, which is the most direct rotation from the +``z`` axis to the point given by ``(\theta, \phi)``, and behaves +better in the limit of small ``\theta``. However, this only works for +rotations directly from the ``z`` axis; the result depends on the +choice of coordinates, and is not the best choice for tracking general +motion of the target axis. + +Fortunately, it is possible to take *any* rotor ``R_\mathrm{axis}(t)`` +that aligns the axis correctly, and compute another rotation that also +aligns the axis, but has the smallest possible angular velocity. This +is called the "minimal rotation". The general problem is discussed +(by way of a very specific physical situation) in detail in Sec. III +and Appendix B of [this paper](https://arxiv.org/abs/1110.2965). +Essentially, we solve the equation ```math \dot{\gamma} = 2 \left[\dot{R}_\mathrm{axis}\, 𝐤\, \bar{R}_\mathrm{axis} \right]_w ``` -(where the subscript ``w`` just takes the scalar component) for ``\gamma(t)``. -We then construct the rotor +(where the subscript ``w`` just takes the scalar component) for +``\gamma(t)``. We then construct the rotor ```math R(t) = R_\mathrm{axis}(t)\, \exp\left[\gamma(t) 𝐤 / 2 \right] ``` -This rotor also aligns the axis correctly, but otherwise has the smallest -possible angular velocity. Here, ``R_\mathrm{axis}`` may be constructed in any -convenient way, including using spherical coordinates or even Euler angles; the -resulting ``R(t)`` will be independent of such poor life choices. +This rotor also aligns the axis correctly, but otherwise has the +smallest possible angular velocity. Here, ``R_\mathrm{axis}`` may be +constructed in any convenient way, including using spherical +coordinates or even Euler angles; the resulting ``R(t)`` will be +independent of such poor life choices. diff --git a/docs/src/geometric_algebra.md b/docs/src/geometric_algebra.md index 196af2f7..7b281cc5 100644 --- a/docs/src/geometric_algebra.md +++ b/docs/src/geometric_algebra.md @@ -9,7 +9,7 @@ has a clear geometric justification. The treatment here focuses on *real* quaternions. The extension to complex quaternions (needed for Lorentz boosts via the spacetime algebra) is covered -on a separate page. +on the [spacetime algebra page](spacetime_algebra.md). ## The geometric algebra over ``ℝ³`` @@ -52,10 +52,10 @@ The pseudoscalar ``𝐈 = 𝐱𝐲𝐳`` also squares to ``-1``, so its inverse is ``𝐈^{-1} = -𝐈 = 𝐳𝐲𝐱``. ``𝐈`` has a special property in three dimensions: since moving it -past any grade-1 vector costs ``(-1)^{n-1} = (-1)^2 = +1`` sign -changes, it commutes with every element of the algebra. Left- and -right-multiplication by ``𝐈`` are therefore identical, and we can -unambiguously write ``𝐈\,𝐯 = 𝐯\,𝐈``. +past any grade-1 vector takes ``n-1 = 2`` transpositions, it picks up +a factor of ``(-1)^{n-1} = +1``, so it commutes with every element of +the algebra. Left- and right-multiplication by ``𝐈`` are therefore +identical, and we can unambiguously write ``𝐈\,𝐯 = 𝐯\,𝐈``. ### The reverse @@ -119,8 +119,9 @@ For grade-2 bivectors the reverse introduces a sign (e.g., ``` where the first step uses ``a \wedge c = \langle ac \rangle_n`` when the grades of ``a`` and ``c`` sum to ``n``, and the third - uses the fact that right-multiplication by ``𝐈`` shifts grade by - ``n``, so only the scalar part of ``a\widetilde{b}`` contributes. + uses the fact that right-multiplication by ``𝐈`` maps grade ``k`` + to grade ``n-k``, so only the scalar (grade-0) part of + ``a\widetilde{b}`` contributes to grade ``n``. ## Reflections and rotations @@ -178,15 +179,17 @@ R\,𝐱\,\widetilde{R} A right-handed rotation by ``\vartheta`` about ``𝐳`` (curling the right hand from ``𝐱`` toward ``𝐲``, thumb along ``+𝐳``) maps ``𝐱 \to \cos\vartheta\,𝐱 + \sin\vartheta\,𝐲``. The formula above has a -negative ``\sin`` term: ``\exp(\theta\,𝐱𝐲)`` rotates ``𝐱`` toward -``-𝐲``, i.e., *clockwise* in the ``𝐱𝐲``-plane (left-handed about -``𝐳``). Right-handed rotation by ``\vartheta`` about ``+𝐳`` -requires the opposite sign: ``\exp(\frac{\vartheta}{2}\,𝐲𝐱)``. The -same test on the remaining coordinate planes — checking whether -``\exp(\vartheta\,𝐲𝐳)`` maps ``𝐲`` toward ``+𝐳`` or ``-𝐳``, and -whether ``\exp(\vartheta\,𝐳𝐱)`` maps ``𝐳`` toward ``+𝐱`` or -``-𝐱`` — gives in each case the same conclusion: the bivector with -*reversed* index order is the right-handed one. The results are: +negative ``\sin`` term: ``\exp(\frac{\vartheta}{2}\,𝐱𝐲)`` rotates +``𝐱`` toward ``-𝐲``, i.e., *clockwise* in the ``𝐱𝐲``-plane +(left-handed about ``𝐳``). Right-handed rotation by ``\vartheta`` +about ``+𝐳`` requires the opposite sign: +``\exp(\frac{\vartheta}{2}\,𝐲𝐱)``. The same test on the remaining +coordinate planes — checking whether +``\exp(\frac{\vartheta}{2}\,𝐲𝐳)`` maps ``𝐲`` toward ``+𝐳`` or +``-𝐳``, and whether ``\exp(\frac{\vartheta}{2}\,𝐳𝐱)`` maps ``𝐳`` +toward ``+𝐱`` or ``-𝐱`` — gives in each case the same conclusion: +the bivector with *reversed* index order is the right-handed one. The +results are: ```math \begin{array}{ll} \text{right-handed rotation about } 𝐱: & \exp\left(\tfrac{\vartheta}{2}\,𝐳𝐲\right), \\[4pt] diff --git a/docs/src/index.md b/docs/src/index.md index 073b50ea..dbb36ac1 100644 --- a/docs/src/index.md +++ b/docs/src/index.md @@ -9,16 +9,27 @@ rotations — along with thorough testing, documentation, and integration with t rest of Julia. Wherever possible, standard functions that work with `Complex` will also work with `Quaternion`. -In addition to a basic `Quaternion{T}` type, we also have [`Rotor{T}`](@ref) and -[`QuatVec{T}`](@ref) specializations, which can improve the accuracy and -efficiency of certain applications. Each of these can be defined over any -`T<:Number`; in addition to the standard primitive types (`Float64`, etc.), -`BigFloat` and `Symbolics.Num` are tested extensively. +In addition to a basic `Quaternion{T}` type, we also have +[`Rotor{T}`](@ref) and [`QuatVec{T}`](@ref) specializations, which can +improve the accuracy and efficiency of certain applications. Each of +these can be defined over any `T<:Number`; in addition to the standard +primitive types (`Float64`, etc.), `BigFloat`, `Complex` numbers, and +`Symbolics.Num` are tested extensively. Quaternions with complex +components also represent Lorentz transformations, as described in +[Lorentz transformations](@ref). + +This page is a quick tour of the package. The Manual pages describe +each group of functions in more detail, the [Functions of time](@ref) +page describes interpolation and angular velocity, and +[Differentiating by quaternionic arguments](@ref) describes the +support for automatic differentiation. The Theory pages derive the +conventions used throughout the package, and the API index at the end +lists every documented function and type. ## Examples -There are numerous ways to construct a [`Quaternion`](@ref) — the simplest being -to just give the components: +There are numerous ways to construct a [`Quaternion`](@ref) — the +simplest being to just give the components: ```jldoctest example julia> using Quaternionic @@ -28,29 +39,31 @@ julia> q = quaternion(1.0, 2.0, 3.0, 4.0) julia> p = quaternion(4, 3, 2, 1) 4 + 3𝐢 + 2𝐣 + 1𝐤 ``` -For convenience, you can also pass a vector that will be unpacked for you: +For convenience, you can also pass a vector that will be unpacked for +you: ```jldoctest example julia> c = [1.0, 2.0, 3.0, 4.0]; julia> q = quaternion(c) 1.0 + 2.0𝐢 + 3.0𝐣 + 4.0𝐤 ``` -Though, if the vector has the wrong number of elements, a `MethodError` will be -raised. +If the vector has the wrong number of elements, a `DimensionMismatch` +error is raised. -Each quaternion type is parametrized by the types of its components (which are -promoted to be all the same type). Any subtype of `Number` is allowed, and is -detected automatically. For example, above `q` has type `Quaternion{Float64}`, -while `p` has type `Quaternion{Int64}`.[^1] The base type may be given -explicitly if desired, to override the detected type: +Each quaternion type is parametrized by the types of its components +(which are promoted to be all the same type). Any subtype of `Number` +is allowed, and is detected automatically. For example, above `q` has +type `Quaternion{Float64}`, while `p` has type +`Quaternion{Int64}`.[^1] The base type may be given explicitly if +desired, to override the detected type: ```jldoctest example julia> r = Quaternion{Float64}(4, 3, 2, 1) 4.0 + 3.0𝐢 + 2.0𝐣 + 1.0𝐤 ``` -The various `Float` and `Int` types work well, as do `BigFloat`, and the [`Num` -type from -`Symbolics.jl`](https://symbolics.juliasymbolics.org/v0.1/manual/variables/#A-note-about-functions-restricted-to-Numbers-1). -In particular, we can use symbolic expressions as components: +The various `Float` and `Int` types work well, as do `BigFloat` and +the `Num` type from +[`Symbolics.jl`](https://docs.sciml.ai/Symbolics/stable/). In +particular, we can use symbolic expressions as components: ```jldoctest symbolics; setup = :(using Quaternionic, Symbolics) julia> using Quaternionic, Symbolics @@ -59,10 +72,10 @@ julia> @variables a b c d e; julia> quaternion(a-b, b*c, c/d, d+e) a - b + b*c𝐢 + (c / d)𝐣 + (d + e)𝐤 ``` -In analogy with the complex types, the aliases `QuaternionF64`, `QuaternionF32`, -and `QuaternionF16` are provided, as well as the constants `imx`, `imy`, and -`imz`, and (for copy-paste convenience) the aliases 𝐢, 𝐣, and 𝐤 (as Unicode -bold characters): +In analogy with the complex types, the aliases `QuaternionF64`, +`QuaternionF32`, and `QuaternionF16` are provided, as well as the +constants `imx`, `imy`, and `imz`, and (for copy-paste convenience) +the aliases 𝐢, 𝐣, and 𝐤 (as Unicode bold characters): ```jldoctest example julia> QuaternionF64 QuaternionF64 (alias for Quaternion{Float64}) @@ -75,14 +88,15 @@ As with the complex `im`, the result of multiplying `imx`, etc., with any real number will be a quaternion with the type of the other number. -[^1]: - Note that, mathematically speaking, quaternions can only be defined over a - [field](https://en.wikipedia.org/wiki/Field_(mathematics)#Definition), which - necessarily cannot be an integer type (because the multiplicative inverse of - an integer is not generally an integer). Nonetheless, it is possible to - define a `Quaternion{<:Integer}`, which should behave as expected. However, - many functions (such as [`exp`](@ref), [`log`](@ref), etc.) will then - return a `Quaternion` of some different type, just as is the case for +[^1]: Note that, mathematically speaking, quaternions can only be + defined over a + [field](https://en.wikipedia.org/wiki/Field_(mathematics)#Definition), + which necessarily cannot be an integer type (because the + multiplicative inverse of an integer is not generally an integer). + Nonetheless, it is possible to define a `Quaternion{<:Integer}`, + which should behave as expected. However, many functions (such as + [`exp`](@ref), [`log`](@ref), etc.) will then return a + `Quaternion` of some different type, just as is the case for `Complex{<:Integer}`. It is also possible to construct random quaternions using @@ -94,11 +108,14 @@ julia> randn(QuaternionF64) julia> randn(RotorF32) rotor(0.18842402 - 0.30743068𝐢 + 0.92128336𝐣 + 0.14567046𝐤) ``` -Each component of the quaternion is chosen from a normal distribution -with mean 0 and standard deviation 1, which means that the resulting -quaternion will have an equal probability of being in any direction — -the probability distribution is "isotropic". This is, for example, -and good way of choosing a random direction: +For a `Quaternion`, each component is chosen independently from a +normal distribution with mean 0 and variance 1/4 (standard deviation +1/2), so that the expected value of `abs2(q)` is 1. For a `QuatVec`, +each of the three vector components has variance 1/3, and a `Rotor` is +the normalized result. In each case, the resulting quaternion has an +equal probability of pointing in any direction — the probability +distribution is "isotropic". This is, for example, a good way of +choosing a random direction: ```jldoctest example julia> normalize(randn(QuatVecF64)) - 0.3018853063494534𝐢 + 0.4571280910615297𝐣 - 0.8365997670169042𝐤 @@ -145,7 +162,7 @@ julia> imag(q) Alternatively, *and slightly less efficiently*, various parts can be accessed as fields: ```jldoctest example -julia> q[1], q[2], q[3], q[4] +julia> q.w, q.x, q.y, q.z (1.0, 2.0, 3.0, 4.0) julia> q.vec 3-element Vector{Float64}: @@ -163,19 +180,22 @@ julia> q.im Again, however, these field accesses incur a slight overhead, so it's more efficient to treat the quaternion as an array and use indexing. -Functions may also be broadcast to *each component* of a `Quaternion`. For -example, this can be particularly helpful when simplifying `Symbolics` -expressions: +Because quaternions are `Number`s, broadcasting treats each quaternion +as a single scalar; functions are *not* broadcast over the components. +To apply a function to each component, apply it to the components and +construct a new quaternion. For example, this can be particularly +helpful when simplifying `Symbolics` expressions: ```jldoctest symbolics julia> @variables q[1:4]; # Defines q[1] through q[4] as symbolic variables julia> Q = quaternion(q...); -julia> simplify.(Q * imz * conj(Q)) +julia> quaternion(simplify.(components(Q * imz * conj(Q)))...) 0 + (2q[1]*q[3] + 2q[2]*q[4])𝐢 + (-2q[1]*q[2] + 2q[3]*q[4])𝐣 + (q[1]^2 - (q[2]^2) - (q[3]^2) + q[4]^2)𝐤 ``` -(Though, note that you probably want to use `Q(imz)` instead of the last -expression, when using floating-point numbers, for efficiency reasons.) +(Though, note that you probably want to use `Q(imz)` instead of the +last expression, when using floating-point numbers, for efficiency +reasons.) The basic algebraic operations work as you would expect: ```jldoctest example @@ -191,41 +211,86 @@ julia> q / p 0.6666666666666666 + 0.3333333333333333𝐢 + 0.0𝐣 + 0.6666666666666666𝐤 ``` Essential mathematical functions familiar from complex math, such as -[`conj`](@ref), [`abs`](@ref), [`abs2`](@ref), [`log`](@ref), [`exp`](@ref), -etc., are also available. +[`conj`](@ref), [`abs`](@ref), [`abs2`](@ref), [`log`](@ref), +[`exp`](@ref), etc., are also available. -Also note that one of the more useful quaternion operations is group conjugation -or "sandwiching". This is the operation that allows a `Rotor` to actually -rotate a `QuatVec`. For a rotor ``R`` and vector `v`, this is expressed -mathematically as +Also note that one of the more useful quaternion operations is group +conjugation or "sandwiching". This is the operation that allows a +`Rotor` to actually rotate a `QuatVec`. For a rotor ``R`` and vector +``v``, this is expressed mathematically as ```math v′ = R\, v\, R^{-1} = R\, v\, \bar{R}. ``` -Here, the first equality is the usual definition of conjugation of ``v`` by -``R``, while the second equality stems from the fact that for a rotor, ``R^{-1} -= \bar{R}``. This second operation is sometimes referred to as "sandwiching" -or "∗-conjugation" (when working in a ∗-algebra) to distinguish it from the more -usual group conjugation involving the inverse. It is this second version that -is implemented here by using `Quaternion`s or `Rotor`s as functions. For a `Q` -of either type, and a `v<:QuatVec`, we have +Here, the first equality is the usual definition of conjugation of +``v`` by ``R``, while the second equality stems from the fact that for +a rotor, ``R^{-1} = \bar{R}``. This second operation is sometimes +referred to as "sandwiching" or "∗-conjugation" (when working in a +∗-algebra) to distinguish it from the more usual group conjugation +involving the inverse. It is this second version that is implemented +here by using `Quaternion`s or `Rotor`s as functions. For a `Q` of +either type, and a `v<: QuatVec`, we have ```julia Q * v * conj(Q) ≈ Q(v) ``` -In particular, `Q(v)` (the right-hand side) is about twice as efficient as -performing the conjugation and two multiplications explicitly (the left-hand -side). +In particular, `Q(v)` (the right-hand side) is about twice as +efficient as performing the conjugation and two multiplications +explicitly (the left-hand side). Note that, for a general +`Quaternion` `Q`, the result is scaled by `abs2(Q)`. + +## Rotations + +The most common application of quaternions is to represent rotations. +A rotation by angle ``\vartheta`` about the unit axis ``\hat{n}`` is +given by the rotor ``\exp(\vartheta\, \hat{n} / 2)``, where +``\hat{n}`` is a `QuatVec`. For example, a rotation by ``\pi/2`` +about the ``z`` axis takes the ``x`` axis to the ``y`` axis: +```jldoctest example +julia> R = exp(π/4 * imz) +rotor(0.7071067811865476 + 0.0𝐢 + 0.0𝐣 + 0.7071067811865475𝐤) + +julia> R(imx) ≈ imy +true +``` +Rotations can be converted to and from other representations, such as +rotation matrices, Euler angles, and spherical coordinates (see +[Rotations and conversions](@ref)); compared with [`distance`](@ref) +(see [Distances and alignment](@ref)); and interpolated with +[`slerp`](@ref) and [`squad`](@ref) (see [Functions of time](@ref)): +```jldoctest example +julia> to_rotation_matrix(R) ≈ [0 -1 0; 1 0 0; 0 0 1] +true +julia> distance(R, one(R)) ≈ π/4 +true + +julia> slerp(one(R), R, 0.5) ≈ exp(π/8 * imz) +true +``` -## References +## Special relativity + +Quaternions with complex components represent Lorentz transformations +of Minkowski spacetime, through the isomorphism between the complex +quaternions and the even subalgebra of the spacetime algebra. The +[`Lorentz`](@ref) type is a `Rotor` with complex components, and +[`Boost`](@ref) constructs a pure boost. Calling a Lorentz +transformation on a 4-vector ``[t, x, y, z]`` transforms it: +```jldoctest example +julia> B = Boost([0.6, 0.0, 0.0]); # A boost with velocity 0.6 along x + +julia> B([1, 0, 0, 0]) ≈ [1.25, 0.75, 0, 0] # The 4-velocity of a moving particle +true +``` +See [Lorentz transformations](@ref) for more details, and [Quaternions +and the Spacetime Algebra](@ref) for the theory. + + +## Sources Several of the algorithms implemented here are — as far as I know — original to this package, including [`exp`](@ref), [`log`](@ref), and [`sqrt`](@ref). But important contributions came from a number of sources, including the notes by [dantam2014](@citet) and [kahan2014](@citet). More advanced functions of time were developed -in [BoyleOwenPfeiffer2011](@citet) and [Boyle2017](@citet). - -### Bibliography - -```@bibliography -``` +in [BoyleOwenPfeiffer2011](@citet) and [Boyle2017](@citet). The full +bibliography is on the [References](@ref) page. diff --git a/docs/src/lorentz.md b/docs/src/lorentz.md new file mode 100644 index 00000000..6c66bc22 --- /dev/null +++ b/docs/src/lorentz.md @@ -0,0 +1,103 @@ +# Lorentz transformations + +Quaternions with complex components represent proper orthochronous +Lorentz transformations — more precisely, elements of their double +cover ``\mathrm{Spin}^+(3,1)`` — through the isomorphism between the +complex quaternions and the even subalgebra of the spacetime algebra. +The theory, including the sign conventions, is described on the +[Quaternions and the Spacetime Algebra](@ref) page; this page +describes how to use it. + +The [`Lorentz`](@ref) type is simply an alias for `Rotor{Complex{T}}`. +The [`Boost`](@ref) function constructs a pure boost from a rapidity +and a direction, or from a velocity (in units where ``c = 1``), and +`Lorentz(R)` converts a real `Rotor` `R` into the corresponding pure +rotation. Lorentz transformations are composed with `*` and inverted +with `inv`, and calling one on a Minkowski 4-vector ``[t, x, y, z]`` +(with signature ``{-}{+}{+}{+}``) transforms it: +```jldoctest lorentz +julia> using Quaternionic + +julia> B = Boost([0.6, 0.0, 0.0]); # A boost with velocity 0.6 along x + +julia> B([1, 0, 0, 0]) ≈ [1.25, 0.75, 0, 0] +true + +julia> Boost(atanh(0.6), [1, 0, 0]) ≈ B # The same boost, given by its rapidity +true +``` + +The action is *active*: `Λ(v)` is the transformed vector, expressed in +the original frame. Above, `B` maps the 4-velocity of a particle at +rest to the 4-velocity ``\gamma\,(1, \vec{v})`` of a particle moving +with velocity ``\vec{v}``. The components of a fixed vector as seen +by an observer moving with velocity ``\vec{v}`` are given instead by +the passive transformation `inv(Boost(v⃗))`. Composition acts from +right to left: +```jldoctest lorentz +julia> R = Lorentz(exp(π/8 * imz)); # A rotation by π/4 about z + +julia> v = [1.0, 2.0, 3.0, 4.0]; + +julia> (R * B)(v) ≈ R(B(v)) +true + +julia> inv(B)(B(v)) ≈ v +true +``` + +Every Lorentz transformation can be factored into simpler pieces. The +functions [`RB`](@ref Quaternionic.RB) and [`BR`](@ref +Quaternionic.BR) factor it into a rotation and a boost (in either +order), [`Rv`](@ref Quaternionic.Rv) and [`vR`](@ref Quaternionic.vR) +do the same but return the boost's velocity, and [`KAN`](@ref +Quaternionic.KAN) computes the Iwasawa decomposition described in +[Iwasawa's ``KA\,N`` decomposition](@ref iwasawa-kan): +```jldoctest lorentz +julia> K, A, N = Quaternionic.KAN(R * B); + +julia> K * A * N ≈ R * B +true +``` + +The functions [`ℂreal`](@ref Quaternionic.ℂreal), [`ℂimag`](@ref +Quaternionic.ℂimag), [`ℂreim`](@ref Quaternionic.ℂreim), and +[`ℂconj`](@ref Quaternionic.ℂconj) operate on the real and imaginary +parts of the complex components. These functions are public but not +exported, so they must be qualified with the module name, or imported +explicitly. + +Many generic quaternion functions, such as `exp`, `log`, `sqrt`, and +integer powers, also accept complex quaternions, and `abs` and `abs2` +compute the complex spinor norm. Functions that are specific to +rotations in three dimensions, such as `distance`, `to_euler_angles`, +and `from_rotation_matrix`, do not support `Lorentz` input. + +## Reference + +The entry `Lorentz(::AbstractVector)` below documents the action +`Λ(v)` of a Lorentz transformation `Λ` on a 4-vector `v`. + +```@meta +CurrentModule = Quaternionic +``` + +```@docs +Lorentz +Lorentz(::AbstractVector) +Boost +ga_components +RB +BR +Rv +vR +KAN +ℂreal +ℂimag +ℂreim +ℂconj +``` + +```@meta +CurrentModule = nothing +``` diff --git a/docs/src/manual.md b/docs/src/manual.md deleted file mode 100644 index eb4b5f91..00000000 --- a/docs/src/manual.md +++ /dev/null @@ -1,177 +0,0 @@ -# Quaternionic functions - -From `AbstractQuaternion{T}` we define three subtypes: - - * `Quaternion{T}`, which is an element of the general algebra of quaternions - over any `T<:Real`. - * `Rotor{T}`, which is an element of the multiplicative group of unit - quaternions, and is interpreted as mapping to a rotation. The magnitude is - *assumed* to be 1 (though, for efficiency, this is not generally - confirmed), and the sign may be freely changed in certain cases. - * `QuatVec{T}`, which is an element of the additive group of quaternions with - 0 scalar part; a "pure vector" quaternion. - -For simplicity, almost every function in this package is defined for general -`Quaternion`s, so you may not need any other type. However, it can frequently -be more accurate *and* more efficient to use the other subtypes where relevant. - -## Constructors, constants, and conversions - -At the most basic level, `Quaternion{T}` mimics `Complex{T}` as closely as -possible, including the behavior of most functions in `Base`. The `Rotor{T}` -and `QuatVec{T}` subtypes behave very similarly, except that most of their -constructors automatically impose the constraints that the norm is 1 and the -scalar component is 0, respectively. Also note that when a certain operation -is not defined for either of those subtypes, the functions will usually convert -to a general `Quaternion` automatically. - -To create new `Quaternion`s interactively, it is typically most convenient to -use the constants `imx`, `imy`, and `imz` — or equivalently `𝐢`, `𝐣`, and `𝐤` — -multiplied by appropriate factors and added together. For programmatic work, -it is more common to use the [`Quaternion`](@ref) function — which takes all -four components, the three vector components, or just the one scalar component, -and creates a new `Quaternion` of the type implied by the arguments. You can -also *specify* the type, as in `Quaternion{Float64}(...)`. Type conversions -with `promote`, `widen`, `float`, etc., work as expected. - -```@autodocs -Modules = [Quaternionic] -Pages = ["quaternion.jl"] -Order = [:module, :type, :constant, :function, :macro] -``` - -## Number functions from Base - -The standard [`Number` -functions](https://docs.julialang.org/en/v1/base/numbers/#General-Number-Functions-and-Constants) -that work for `Complex`, such as `isfinite`, `iszero`, etc., should work -analogously for `Quaternion`. The `hash`, `read`, and `write` functions are -also implemented. As noted in the [Examples](@ref), broadcasting to each -component is also implemented via `broadcasted`. - -```@autodocs -Modules = [Quaternionic, Base] -Pages = ["base.jl"] -``` - - -## Algebraic and other mathematical functions - -Along with the basic binary operators, the essential mathematical functions -like [`conj`](@ref), [`abs`](@ref), [`abs2`](@ref), [`exp`](@ref), -[`log`](@ref), etc., are implemented. Most of these functions are found in the -`Base` module, and are simply overloaded methods of functions that should also -be familiar from `Complex` types. Note that we use a slightly different -interpretation of [`angle`](@ref) for `Quaternion`, compared to `Complex`. We -also have [`absvec`](@ref) and [`abs2vec`](@ref), which are not useful in a -`Complex` context, but compute the relevant quantities for the "vector" -component of a `Quaternion`. - -```@autodocs -Modules = [Quaternionic] -Pages = ["algebra.jl", "math.jl"] -``` - - -## Random quaternions - -It is frequently convenient to construct random `Quaternion` objects, which can -be done just as with other types by passing the desired output type to the -[`randn`](@ref) function. The `rand` function is not overloaded, because there -would be no geometric significance to such a `Quaternion`; `randn` results are -independent of the orientation of the basis used to define the quaternions. -Note that it is possible to get random *rotors* and *vectors* by passing the -appropriate types to the `randn` function. - -```@autodocs -Modules = [Quaternionic] -Pages = ["random.jl"] -``` - - -## Conversions - -It can sometimes be useful to convert between quaternions and other -representations. Most of these functions are named `to_` and -have a corresponding `from_` function. Furthermore, most -convert to/from representations of rotations. While rotations are not the only -useful application of quaternions, they are probably the most common. The only -conversions that are not specifically related to rotations are -[`to_float_array`](@ref) and [`from_float_array`](@ref). - -```@autodocs -Modules = [Quaternionic] -Pages = ["conversion.jl"] -``` - - -## Distances - -There are several ways of measuring the "distance" between two quaternions: -``d(q_1, q_2)``. Fundamentally, any comparison between two quaternions ``q_1`` -and ``q_2`` must make use of a binary operation, for which there are two -obvious choices: addition or multiplication. For either choice, we operate on -``q_1`` and the appropriate inverse (either additive or multiplicative) of -``q_2``. That is, ``d`` should be a function of either ``q_1 - q_2`` or -``q_1/q_2``.[^1] - -[^1]: - For ``q_1/q_2``, we are dealing with the *multiplicative* group of - quaternions, which does not include 0, so we will assume that no quaternion - involved in such a function can be 0. - -Now, we also have a number of criteria we would like any distance function to -satisfy. For any quaternions ``q_1`` and ``q_2`` and any *unit* quaternion -``q_3``, we require - - * real-valued: ``d(q_1, q_2) \in \mathbb{R}`` - * symmetry: ``d(q_1, q_2) = d(q_2, q_1)`` - * invariance: ``d(q_3\, q_1, q_3\, q_2) = d(q_1, q_2) = d(q_1\, q_3, q_2\, q_3)`` - * identity: ``d(q_1, q_1) = 0`` - * positive-definiteness: ``d(q_1, q_2) > 0`` whenever ``q_1 ≠ q_2`` - -(Of course, it should be noted that these criteria all hold in the *exact* case; -when using floating-point numbers, they will likely be violated near edge -cases.) - -It is not hard to see that these criteria can be satisfied by any of - - * `abs(q₁ - q₂)` - * `abs2(q₁ - q₂)` - * `abs(log(q₁ / q₂))` - * `abs2(log(q₁ / q₂)` - -If ``q_1`` and ``q_2`` are interpreted as rotations, we frequently don't care -about their signs, and just want the *smallest* distance between them, for any -choice of sign. Furthermore, in the multiplicative case, the `log` functions -will involve calculation of the `log` of the magnitudes of the quaternions, -which should be 1. In this case, we relax the "positive-definiteness" criterion -to allow ``d(q_1, q_2)`` to equal zero when ``q_1`` and ``q_2`` are related by a -nonzero scalar multiple. - -For `Rotor` types, the latter two multiplicative options are most relevant, -while for other types the additive options are more relevant. These are the -default behaviors of the `distance` and `distance2` functions. - -```@autodocs -Modules = [Quaternionic] -Pages = ["distance.jl"] -``` - - -## Alignment - -There are many ways to optimize alignment with rotations. In particular, we can -seek the optimal rotation that takes one set of points onto a corresponding set -of points, or the optimal quaternion that takes one set of quaternions onto a -corresponding set of quaternions. In both cases, the "optimal" value depends on -the metric being used. The simplest and most robust results are obtained when -the metric is the standard Euclidean metric (in the case of points), or the -magnitude of the difference (in the case of quaternions). Here, we assume that -`QuatVec`s represent points, and any other type of quaternion should be treated -as rotors. - -```@autodocs -Modules = [Quaternionic] -Pages = ["alignment.jl"] -``` diff --git a/docs/src/math.md b/docs/src/math.md new file mode 100644 index 00000000..09d6b25d --- /dev/null +++ b/docs/src/math.md @@ -0,0 +1,54 @@ +# Algebra and mathematical functions + +Along with the basic binary operators, the essential mathematical +functions like [`conj`](@ref), [`abs`](@ref), [`abs2`](@ref), +[`exp`](@ref), [`log`](@ref), etc., are implemented. Most of these +functions are found in the `Base` module, and are simply overloaded +methods of functions that should also be familiar from `Complex` +types. Note that we use a slightly different interpretation of +[`angle`](@ref) for `Quaternion`, compared to `Complex`. We also have +[`absvec`](@ref) and [`abs2vec`](@ref), which are not useful in a +`Complex` context, but compute the relevant quantities for the +"vector" component of a `Quaternion`. + +Quaternions with complex components, which represent [Lorentz +transformations](@ref), are also supported by most of these functions. +For them, `abs2` and `abs` compute the complex *spinor norm*, ``w^2 + +x^2 + y^2 + z^2``, and its square root, rather than the Euclidean +norm; see [Quaternions and the Spacetime Algebra](@ref) for the +reasons. + +Calling a quaternion `Q` on a `QuatVec` `v`, as in `Q(v)`, computes +the "sandwich" `Q * v * conj(Q)` efficiently. For a `Rotor`, this is +the rotation of `v`; for a general `Quaternion`, the result is also +scaled by `abs2(Q)`. + +```@autodocs +Modules = [Quaternionic] +Pages = ["algebra.jl", "math.jl"] +``` + +## `@fastmath` + +The arithmetic operators `+`, `-`, `*`, and `/`, and the power `^`, +can be used inside `@fastmath` expressions, and they return the same +types as without `@fastmath`. The one exception is a chained +expression such as `@fastmath 1.0 * 2.0 * 3.0 * imz`, in which none of +the first three factors is a quaternion; there, Julia's generic +fallback promotes all of the factors to a common type, so the result +is a `Quaternion` rather than a `QuatVec`. + +## Matrices of quaternions + +Arrays of quaternions work with most generic code, but some generic +linear-algebra and statistics routines assume that multiplication of +scalars commutes, and give silently wrong answers for quaternions. +Products of matrices and vectors, `inv`, solutions of square systems +with `\` and `/`, `lu`, `cholesky`, and operations on `Diagonal`, +`Bidiagonal`, and triangular matrices preserve the order of products, +and are correct. On the other hand, `det` and `logabsdet` return a +quaternion whose phase is arbitrary (only `abs(det(A))` is +meaningful), solving a system with a `Tridiagonal` matrix gives wrong +results, and `Statistics.cov` and `Statistics.cor` are not meaningful +for quaternions. Functions such as `exp`, `log`, `sqrt`, and `eigen` +of a quaternion matrix are not supported. diff --git a/docs/src/references.bib b/docs/src/references.bib index 7600d4ab..c44b637a 100644 --- a/docs/src/references.bib +++ b/docs/src/references.bib @@ -97,4 +97,17 @@ @article{Boyle2017 eprint = {1604.08139}, archivePrefix ={arXiv}, primaryClass = {gr-qc}, -} \ No newline at end of file +} + +@book{MarkleyCrassidis_2014, + address = {New York}, + title = {Fundamentals of Spacecraft Attitude Determination and Control}, + series = {Space Technology Library}, + volume = 33, + isbn = {978-1-4939-0801-1}, + publisher = {Springer}, + author = {Markley, F. Landis and Crassidis, John L.}, + year = 2014, + doi = {10.1007/978-1-4939-0802-8}, + url = {https://doi.org/10.1007/978-1-4939-0802-8}, +} diff --git a/docs/src/references.md b/docs/src/references.md new file mode 100644 index 00000000..95f21777 --- /dev/null +++ b/docs/src/references.md @@ -0,0 +1,6 @@ +# References + +This is the complete bibliography of the works cited in this documentation. + +```@bibliography +``` diff --git a/docs/src/spacetime_algebra.md b/docs/src/spacetime_algebra.md index fd0db8be..c6d4b99e 100644 --- a/docs/src/spacetime_algebra.md +++ b/docs/src/spacetime_algebra.md @@ -27,9 +27,9 @@ this more general algebra. One crucial new feature is the *spinor norm*: for complex quaternions, the GA reverse gives ``𝐐𝐐̃ = w² + x² + y² + z²``, which is a -*complex* scalar, distinct from the Euclidean norm ``|w|² + |x|² + -|y|² + |z|²`` which will always be real. The surprising point is that -the normalization condition ``𝐐𝐐̃ = 1`` is now *two real* +*complex* scalar, distinct from the squared Euclidean norm ``|w|² + +|x|² + |y|² + |z|²``, which is always real. The surprising point is +that the normalization condition ``𝐐𝐐̃ = 1`` is now *two real* conditions, because this says that the "imaginary" part is zero. This reduces the eight real degrees of freedom in a complex quaternion down to six, which is the correct number for a Lorentz transformation in @@ -44,8 +44,9 @@ four-dimensional Minkowski space, and we use the metric signature ```math 𝐭^2 = -1, \qquad 𝐱^2 = 𝐲^2 = 𝐳^2 = +1, ``` -and all other products anticommute. The full algebra has dimension -``2^4 = 16``, with basis elements grouped by grade: +and all other products between distinct basis vectors anticommute. +The full algebra has dimension ``2^4 = 16``, with basis elements +grouped by grade: ```math \begin{array}{lll} @@ -168,19 +169,24 @@ exactly as for real quaternions. Now, we have to be careful to distinguish between two different notions of "norm" for complex quaternions: the *spinor norm* and the -*Euclidean norm*. The spinor norm, +*Euclidean norm*. The (squared) spinor norm, ```math 𝐐\,\widetilde{𝐐} = w^2 + x^2 + y^2 + z^2, ``` is the one that arises from the GA reverse, and it is the physically meaningful notion of "unit" for Lorentz transformations. Notably, the -result is a *complex* number. On the other hand, the Euclidean norm, +result is a *complex* number. On the other hand, the squared +Euclidean norm, which treats the four complex components as a vector +in ``ℂ⁴``, ```math -𝐐\,𝐐^\dagger = |w|^2 + |x|^2 + |y|^2 + |z|^2, -``` -is always a positive real number, and does not have a direct geometric -meaning in this context. The relevant condition that defines a spinor -(in this case, a Lorentz rotor) is that the *spinor* norm equals 1: +|w|^2 + |x|^2 + |y|^2 + |z|^2, +``` +is always a nonnegative real number, and does not have a direct +geometric meaning in this context. (It equals the scalar part of the +product of ``𝐐`` with its reverse after complex conjugation of the +components, but the other parts of that product are generally +nonzero.) The relevant condition that defines a spinor (in this case, +a Lorentz rotor) is that the *spinor* norm equals 1: ```math 𝐐\,\widetilde{𝐐} = 1 + 0i. ``` @@ -195,15 +201,14 @@ is ``` which is not equal to ``1`` in general. Phase factors therefore do *not* belong to the Lorentz rotor group, even though they are unit elements under -the Euclidean norm (``|\exp(i\varphi)| = 1``). +the Euclidean norm (``|\exp(i\alpha)| = 1``). !!! note "Real vs. complex quaternions" - - For real quaternions, ``𝐐\,\widetilde{𝐐} = \sum r_i^2 = \sum |r_i|^2``, - so the spinor and Euclidean norms coincide. This is why the distinction - never arises on the GA page. For complex quaternions they diverge, and - only the spinor norm has the correct geometric meaning for Lorentz - transformations. + For real quaternions, ``𝐐\,\widetilde{𝐐} = \sum r_i^2 = \sum + |r_i|^2``, so the spinor and Euclidean norms coincide. This is + why the distinction never arises on the GA page. For complex + quaternions they diverge, and only the spinor norm has the correct + geometric meaning for Lorentz transformations. ## Rotors in the STA @@ -215,10 +220,10 @@ three-dimensional case: R = \exp\!\left(\frac{\vartheta}{2}\,\hat{B}\right) = \cos\frac{\vartheta}{2} + \sin\frac{\vartheta}{2}\,\hat{B}, ``` -where ``\hat{B} \in \{𝐳𝐲, 𝐱𝐳, 𝐲𝐱\}`` is a unit spatial bivector. -The components are real, and the spinor norm happens to equal the -Euclidean norm: ``R\widetilde{R} = \cos^2(\vartheta/2) + -\sin^2(\vartheta/2) = 1``. +where ``\hat{B}`` is any unit spatial bivector, such as ``𝐳𝐲``, +``𝐱𝐳``, ``𝐲𝐱``, or unit-norm combinations of them. The components +are real, and the spinor norm happens to equal the Euclidean norm: +``R\widetilde{R} = \cos^2(\vartheta/2) + \sin^2(\vartheta/2) = 1``. A boost in the ``𝐯``-direction by rapidity ``\varphi`` uses the boost bivector ``𝐭𝐯``: @@ -235,15 +240,26 @@ B\,\widetilde{B} = \cosh^2\!\frac{\varphi}{2} - \sinh^2\!\frac{\varphi}{2} = 1, ``` -while the Euclidean norm is ``\cosh^2(\varphi/2) + \sinh^2(\varphi/2) -= \cosh\varphi \neq 1`` for ``\varphi \neq 0``. This concretely shows -why the spinor norm is the physically correct notion of "unit" for -Lorentz transformations. +while the squared Euclidean norm is ``\cosh^2(\varphi/2) + +\sinh^2(\varphi/2) = \cosh\varphi \neq 1`` for ``\varphi \neq 0``. +This concretely shows why the spinor norm is the physically correct +notion of "unit" for Lorentz transformations. -[^boost]: The sign can be verified by expanding the Lorentz transformation - ``\Lambda\,𝐯\,\widetilde{\Lambda}`` on the 4-vector ``𝐯 = t\,𝐭 + x\,𝐱`` - and confirming that a positive rapidity boosts ``t \to \cosh\varphi\,t + - \sinh\varphi\,x`` and ``x \to \sinh\varphi\,t + \cosh\varphi\,x``. +The transformations are *active*: ``B\,𝐰\,\widetilde{B}`` is the +boosted vector ``𝐰``, expressed in the original frame. For example, +the boost with velocity ``\vec{v}`` maps the 4-velocity ``𝐭`` of a +particle at rest to the 4-velocity ``\gamma\,(𝐭 + \vec{v})`` of a +particle moving with velocity ``\vec{v}``. The components of a fixed +vector as seen by an observer moving with velocity ``\vec{v}`` are +instead given by the inverse boost. Products act from right to left: +``(Λ_1 Λ_2)\, 𝐰\, \widetilde{(Λ_1 Λ_2)} = Λ_1 \bigl(Λ_2\, 𝐰\, +\widetilde{Λ_2}\bigr) \widetilde{Λ_1}``. + +[^boost]: The sign can be verified by taking ``𝐯 = 𝐱``, expanding + ``B\,𝐰\,\widetilde{B}`` for the 4-vector ``𝐰 = t\,𝐭 + x\,𝐱``, + and confirming that a positive rapidity boosts ``t \to + \cosh\varphi\,t + \sinh\varphi\,x`` and ``x \to \sinh\varphi\,t + + \cosh\varphi\,x``. ## [Iwasawa's ``KA\,N`` decomposition](@id iwasawa-kan) @@ -260,14 +276,14 @@ G = {KA\,N}. Our implementation of this decomposition relies on a choice of basis unit vectors: we specifically use the ``𝐭`` and ``𝐳`` basis vectors, -and assume that we know how to find the plane corresponding to both. -We use those to pick out boosts along that spatial direction, and null -rotations that fix the corresponding null vector. Specifically, we -have the following subgroups: +and the boost plane ``𝐭𝐳`` that they span. We use those to pick out +boosts along that spatial direction, and null rotations that fix the +corresponding null vector. Specifically, we have the following +subgroups: - **``K``** is the maximal compact subgroup, which in the case of the Lorentz group is isomorphic to the rotation group - ``\mathrm{SO}(3)``, and in the case of ``\mathrm{Spin}(3,1)`` is + ``\mathrm{SO}(3)``, and in the case of ``\mathrm{Spin}^+(3,1)`` is isomorphic to ``\mathrm{Spin}(3)``. - **``A``** is the abelian subgroup of boosts in a fixed direction. We take this direction to be the z-axis, so that we have ``A = @@ -337,7 +353,7 @@ and the fact that ``𝐭𝐳u₊ = u₊``, we have ```math \begin{aligned} Rₐ u₊ -&= \left[\cosh\left(\frac{φₐ}{2}\right) + \sinh\left(\frac{φₐ}{2}\right)\right] u₊ +&= \left[\cosh\left(\frac{φₐ}{2}\right) + \sinh\left(\frac{φₐ}{2}\right)\right] u₊ \\ &= e^{φₐ/2} u₊. \end{aligned} ``` @@ -397,27 +413,8 @@ Rₙ = Rₐ^{-1} Rₖ^{-1} Λ. This decomposition is implemented in the [`Quaternionic.KAN`](@ref) function. -## API reference - -```@meta -CurrentModule = Quaternionic -``` - -```@docs -Lorentz -Lorentz(::AbstractVector) -Boost -ga_components -RB -BR -Rv -vR -KAN -ℂreal -ℂimag -ℂreim -ℂconj -``` +The functions that implement these constructions are described on the +[Lorentz transformations](@ref) page. ## Further reading diff --git a/docs/src/types.md b/docs/src/types.md new file mode 100644 index 00000000..cc701b1b --- /dev/null +++ b/docs/src/types.md @@ -0,0 +1,105 @@ +# Types and construction + +From `AbstractQuaternion{T}` we define three subtypes: + + * `Quaternion{T}`, which is an element of the general algebra of + quaternions over any `T<:Number`. Most commonly, `T` is a real + floating-point type, but integers, symbolic types, and complex + numbers are also supported. Complex components are used to + represent [Lorentz transformations](@ref). + * `Rotor{T}`, which is an element of the multiplicative group of + unit quaternions, and is interpreted as mapping to a rotation. + The magnitude is *assumed* to be 1 (though, for efficiency, this + is not generally confirmed), and the sign may be freely changed in + certain cases. + * `QuatVec{T}`, which is an element of the additive group of + quaternions with 0 scalar part; a "pure vector" quaternion. + +For simplicity, almost every function in this package is defined for +general `Quaternion`s, so you may not need any other type. However, +it can frequently be more accurate *and* more efficient to use the +other subtypes where relevant. + +## Constructors, constants, and conversions + +At the most basic level, `Quaternion{T}` mimics `Complex{T}` as +closely as possible, including the behavior of most functions in +`Base`. The `Rotor{T}` and `QuatVec{T}` subtypes behave very +similarly, except that most of their constructors automatically impose +the constraints that the norm is 1 and the scalar component is 0, +respectively. Also note that when a certain operation is not defined +for either of those subtypes, the functions will usually convert to a +general `Quaternion` automatically. + +To create new `Quaternion`s interactively, it is typically most +convenient to use the constants `imx`, `imy`, and `imz` — or +equivalently `𝐢`, `𝐣`, and `𝐤` — multiplied by appropriate factors +and added together. For programmatic work, it is more common to use +the [`quaternion`](@ref) function — which takes all four components, +the three vector components, or just the one scalar component, and +creates a new `Quaternion` of the type implied by the arguments. The +[`rotor`](@ref) and [`quatvec`](@ref) functions do the same for the +other subtypes. You can also *specify* the type, as in +`Quaternion{Float64}(...)`. Type conversions with `promote`, `widen`, +`float`, etc., work as expected. + +```@docs +AbstractQuaternion +Quaternion +Rotor +QuatVec +quaternion +rotor +quatvec +imx +imy +imz +𝐢 +𝐣 +𝐤 +components +basetype +``` + +## Number functions from Base + +The standard [`Number` +functions](https://docs.julialang.org/en/v1/base/numbers/#General-Number-Functions-and-Constants) +that work for `Complex`, such as `isfinite`, `iszero`, etc., should +work analogously for `Quaternion`. The `hash`, `read`, and `write` +functions are also implemented. Because quaternions are `Number`s, +broadcasting treats each quaternion as a single scalar: `abs.(q)` is +the same as `abs(q)`, for example. To apply a function to each +component, apply it to [`components`](@ref)`(q)` and construct a new +quaternion from the result. + +## Random quaternions + +It is frequently convenient to construct random `Quaternion` objects, +which can be done just as with other types by passing the desired +output type to the [`randn`](@ref) function. The `rand` function is +not overloaded, because there would be no geometric significance to +such a `Quaternion`; `randn` results are independent of the +orientation of the basis used to define the quaternions. Note that it +is possible to get random *rotors* and *vectors* by passing the +appropriate types to the `randn` function. + +```@autodocs +Modules = [Quaternionic] +Pages = ["random.jl"] +``` + +## Symbolic components and LaTeX display + +Quaternions with `Num` components from +[`Symbolics.jl`](https://docs.sciml.ai/Symbolics/stable/) support the +basic algebra and most of the mathematical functions. A few +functions, such as `sqrt`, choose an algorithm by comparing the values +of components, and raise an error ("non-boolean (Num) used in boolean +context") for symbolic components. To simplify each component of a +symbolic quaternion, use `quaternion(simplify.(components(q))...)`. + +When [`Latexify.jl`](https://github.com/korsbo/Latexify.jl) is loaded, +`latexify(q)` returns the LaTeX form of a quaternion, and quaternions +are displayed as LaTeX in environments that support the `text/latex` +MIME type, such as Jupyter notebooks. diff --git a/ext/QuaternionicChainRulesCoreExt.jl b/ext/QuaternionicChainRulesCoreExt.jl deleted file mode 100644 index 404750ea..00000000 --- a/ext/QuaternionicChainRulesCoreExt.jl +++ /dev/null @@ -1,517 +0,0 @@ -module QuaternionicChainRulesCoreExt - -using Quaternionic -import Quaternionic: _sincu, _cossu -using StaticArrays -isdefined(Base, :get_extension) ? - (using ChainRulesCore; import ChainRulesCore: rrule, rrule_via_ad, RuleConfig, ProjectTo) : - (using ..ChainRulesCore; import ...ChainRulesCore: rrule, rrule_via_ad, RuleConfig, ProjectTo) - - -function rrule(::typeof(components), q::AbstractQuaternion) - c = components(q) - Π = ProjectTo(q) - function components_pullback(Δ) - Δs, Δt, Δu, Δv = Tuple(unthunk(Δ)) - Δq = typeof(q)(Δs, Δt, Δu, Δv) - return NoTangent(), Π(Δq) - end - return c, components_pullback -end - -function rrule(::typeof(Base.getindex), q::AbstractQuaternion, i::Integer) - s = q[i] - function quaternion_getindex_pullback(Δs) - Δw = Δx = Δy = Δz = zero(s) - @inbounds if i == 1 - Δw = unthunk(Δs) - elseif i == 2 - Δx = unthunk(Δs) - elseif i == 3 - Δy = unthunk(Δs) - elseif i == 4 - Δz = unthunk(Δs) - else - throw(BoundsError(q, i)) - end - return NoTangent(), typeof(q)(Δw, Δx, Δy, Δz), NoTangent() - end - return s, quaternion_getindex_pullback -end - - -################## -## Constructors ## -################## - -# Quaternion -function rrule(::Type{QT}, arg::AbstractVector) where {QT<:AbstractQuaternion} - # AbstractQuaternion_pullback(Δquat) = (NoTangent(), components(unthunk(Δquat))) - # return QT(arg), AbstractQuaternion_pullback - # Return a same-shaped tangent for the vector argument - function AbstractQuaternion_pullback(Δquat) - Δw, Δx, Δy, Δz = components(unthunk(Δquat)) - Δarg = similar(arg) - if length(Δarg) == 4 - Δarg[1] = Δw; Δarg[2] = Δx; Δarg[3] = Δy; Δarg[4] = Δz - else - # Fall back: try to fill linearly - for (i, v) in enumerate((Δw, Δx, Δy, Δz)) - i <= length(Δarg) && (Δarg[i] = v) - end - end - return NoTangent(), Δarg - end - return QT(arg), AbstractQuaternion_pullback -end -function rrule(::Type{QT}, w::AbstractQuaternion) where {QT<:AbstractQuaternion} - Quaternion_pullback(Δquat) = (NoTangent(), unthunk(Δquat)) - return QT(w), Quaternion_pullback -end -function rrule(::Type{QT}, w, x, y, z) where {QT<:AbstractQuaternion} - Quaternion_pullback(Δquat) = (NoTangent(), components(unthunk(Δquat))...) - return QT(SVector{4}(w, x, y, z)), Quaternion_pullback -end -function rrule(::Type{QT}, x, y, z) where {QT<:AbstractQuaternion} - Quaternion_pullback(Δquat) = (NoTangent(), vec(unthunk(Δquat))...) - return QT(SVector{4}(false, x, y, z)), Quaternion_pullback -end -function rrule(::Type{QT}, w::Number) where {QT<:AbstractQuaternion} - Quaternion_pullback(Δquat) = (NoTangent(), real(unthunk(Δquat))) - return QT(SVector{4}(w, false, false, false)), Quaternion_pullback -end - -rrule(::typeof(quaternion), args...) = rrule(Quaternion{promote_type(typeof.(args)...)}, args...) -function rrule(::typeof(quaternion), v::AbstractVector) - if length(v) == 4 - Q, Quaternion_pullback1 = rrule(quaternion, v[begin], v[begin+1], v[begin+2], v[begin+3]) - elseif length(v) == 3 - Q, Quaternion_pullback1 = rrule(quaternion, v[begin], v[begin+1], v[begin+2]) - elseif length(v) == 1 - Q, Quaternion_pullback1 = rrule(quaternion, v[begin]) - else - throw(DimensionMismatch("Input vector must have 1, 3, or 4 inputs")) - end - function Quaternion_pullback2(ΔQ) - _, Q̄... = Quaternion_pullback1(ΔQ) - Q̄′ = similar(v) - copyto!(Q̄′, Q̄) - (NoTangent(), Q̄′) - end - return Q, Quaternion_pullback2 -end -rrule(::typeof(quaternion), w::AbstractQuaternion{T}) where {T} = rrule(Quaternion{T}, w) -rrule(::typeof(quaternion), w::T) where {T<:Number} = rrule(Quaternion{T}, w) - -rrule(::Type{Quaternion}, args...) = rrule(quaternion, args...) -rrule(::Type{Quaternion}, w::AbstractVector) = rrule(quaternion, w) -rrule(::Type{Quaternion}, w::AbstractQuaternion) = rrule(quaternion, w) -rrule(::Type{Quaternion}, w::Number) = rrule(quaternion, w) - -# Rotor -function rrule(::typeof(rotor), w, x, y, z) - n = √(w^2 + x^2 + y^2 + z^2) - function Rotor_pullback(ΔR) - # s = w/n - # t = x/n - # u = y/n - # v = z/n - ∂s∂w = (n+w)*(n-w)/n^3 # 1/n - w^2/n^3 - ∂s∂x = -x*w/n^3 - ∂s∂y = -y*w/n^3 - ∂s∂z = -z*w/n^3 - ∂t∂w = -x*w/n^3 - ∂t∂x = (n+x)*(n-x)/n^3 # 1/n - x^2/n^3 - ∂t∂y = -y*x/n^3 - ∂t∂z = -z*x/n^3 - ∂u∂w = -y*w/n^3 - ∂u∂x = -x*y/n^3 - ∂u∂y = (n+y)*(n-y)/n^3 # 1/n - y^2/n^3 - ∂u∂z = -z*y/n^3 - ∂v∂w = -z*w/n^3 - ∂v∂x = -x*z/n^3 - ∂v∂y = -y*z/n^3 - ∂v∂z = (n+z)*(n-z)/n^3 # 1/n - z^2/n^3 - Δs,Δt,Δu,Δv = components(unthunk(ΔR)) - ( - NoTangent(), - (∂s∂w*Δs + ∂t∂w*Δt + ∂u∂w*Δu + ∂v∂w*Δv), - (∂s∂x*Δs + ∂t∂x*Δt + ∂u∂x*Δu + ∂v∂x*Δv), - (∂s∂y*Δs + ∂t∂y*Δt + ∂u∂y*Δu + ∂v∂y*Δv), - (∂s∂z*Δs + ∂t∂z*Δt + ∂u∂z*Δu + ∂v∂z*Δv) - # (1/n - w^2/n^3) + 𝐢*w*x/n^3 + 𝐣*w*y/n^3 + 𝐤*w*z/n^3, - # - x*w/n^3 + 𝐢*(-1/n + x*x/n^3) + 𝐣*x*y/n^3 + 𝐤*x*z/n^3, - # - y*w/n^3 + 𝐢*y*x/n^3 + 𝐣*(-1/n + y*y/n^3) + 𝐤*y*z/n^3, - # - z*w/n^3 + 𝐢*z*x/n^3 + 𝐣*z*y/n^3 + 𝐤*(-1/n + z*z/n^3), - ) - end - a = SVector{4}(w, x, y, z) - v = a ./ abs(Quaternion{eltype(a)}(a)) - return Rotor{eltype(v)}(v), Rotor_pullback -end - -function rrule(::typeof(rotor), x, y, z) - n = √(x^2 + y^2 + z^2) - function Rotor_pullback(ΔR) - # s = 0 - # t = x/n - # u = y/n - # v = z/n - ∂t∂x = (n+x)*(n-x)/n^3 # 1/n - x^2/n^3 - ∂t∂y = -y*x/n^3 - ∂t∂z = -z*x/n^3 - ∂u∂x = -x*y/n^3 - ∂u∂y = (n+y)*(n-y)/n^3 # 1/n - y^2/n^3 - ∂u∂z = -z*y/n^3 - ∂v∂x = -x*z/n^3 - ∂v∂y = -y*z/n^3 - ∂v∂z = (n+z)*(n-z)/n^3 # 1/n - z^2/n^3 - Δt,Δu,Δv = vec(unthunk(ΔR)) - ( - NoTangent(), - (∂t∂x*Δt + ∂u∂x*Δu + ∂v∂x*Δv), - (∂t∂y*Δt + ∂u∂y*Δu + ∂v∂y*Δv), - (∂t∂z*Δt + ∂u∂z*Δu + ∂v∂z*Δv) - ) - end - a = SVector{4}(false, x, y, z) - v = a ./ abs(Quaternion{eltype(a)}(a)) - return Rotor{eltype(v)}(v), Rotor_pullback -end - -function rrule(::typeof(rotor), v::AbstractVector) - if length(v) == 4 - R, Rotor_pullback1 = rrule(rotor, v[begin], v[begin+1], v[begin+2], v[begin+3]) - elseif length(v) == 3 - R, Rotor_pullback1 = rrule(rotor, v[begin], v[begin+1], v[begin+2]) - elseif length(v) == 1 - R, Rotor_pullback1 = rrule(rotor, v[begin]) - else - throw(DimensionMismatch("Input vector must have 1, 3, or 4 inputs")) - end - function Rotor_pullback2(ΔR) - _, R̄... = Rotor_pullback1(ΔR) - R̄′ = similar(v) - copyto!(R̄′, R̄) - (NoTangent(), R̄′) - end - return R, Rotor_pullback2 -end - -function rrule(::typeof(rotor), q::AbstractQuaternion) - R, Rotor_pullback1 = rrule(rotor, q[1], q[2], q[3], q[4]) - function Rotor_pullback2(ΔR) - nt, R̄w, R̄x, R̄y, R̄z = Rotor_pullback1(ΔR) - (nt, typeof(q)(R̄w, R̄x, R̄y, R̄z)) - end - return R, Rotor_pullback2 -end - -function rrule(::typeof(rotor), w::Number) - n = √(w^2) - function Rotor_pullback(ΔR) - # s = w/n - # t = 0 - # u = 0 - # v = 0 - ∂s∂w = (n+w)*(n-w)/n^3 # 1/n - w^2/n^3 - Δs = real(unthunk(ΔR)) - ( - NoTangent(), - ∂s∂w*Δs - ) - end - v = SVector{4}(copysign(one(w), w), false, false, false) - return Rotor{eltype(v)}(v), Rotor_pullback -end - -rrule(::Type{Rotor}, args...) = rrule(rotor, args...) -rrule(::Type{Rotor}, w::AbstractVector) = rrule(rotor, w) -rrule(::Type{Rotor}, w::AbstractQuaternion) = rrule(rotor, w) -rrule(::Type{Rotor}, w::Number) = rrule(rotor, w) - -# QuatVec -function rrule(::typeof(quatvec), w, x, y, z) - function QuatVec_pullback(ΔV) - (NoTangent(), ZeroTangent(), vec(unthunk(ΔV))...) - end - v = SVector{4}(false, x, y, z) - return QuatVec{eltype(v)}(v), QuatVec_pullback -end - -function rrule(::typeof(quatvec), x, y, z) - function QuatVec_pullback(ΔV) - (NoTangent(), vec(unthunk(ΔV))...) - end - v = SVector{4}(false, x, y, z) - return QuatVec{eltype(v)}(v), QuatVec_pullback -end - -function rrule(::typeof(quatvec), v::AbstractVector) - if length(v) == 4 - V, QuatVec_pullback1 = rrule(quatvec, v[begin], v[begin+1], v[begin+2], v[begin+3]) - elseif length(v) == 3 - V, QuatVec_pullback1 = rrule(quatvec, v[begin], v[begin+1], v[begin+2]) - elseif length(v) == 1 - V, QuatVec_pullback1 = rrule(quatvec, v[begin]) - else - throw(DimensionMismatch("Input vector must have 1, 3, or 4 inputs")) - end - function QuatVec_pullback2(ΔV) - _, Q̄... = QuatVec_pullback1(ΔV) - Q̄′ = similar(v) - copyto!(Q̄′, Q̄) - (NoTangent(), Q̄′) - end - return V, QuatVec_pullback2 -end - -function rrule(::typeof(quatvec), q::AbstractQuaternion) - R, QuatVec_pullback1 = rrule(quatvec, q[1], q[2], q[3], q[4]) - function QuatVec_pullback2(ΔV) - nt, Q̄w, Q̄x, Q̄y, Q̄z = QuatVec_pullback1(ΔV) - (nt, typeof(q)(Q̄w, Q̄x, Q̄y, Q̄z)) - end - return R, QuatVec_pullback2 -end - -function rrule(::typeof(quatvec), w::Number) - function QuatVec_pullback(ΔV) - (NoTangent(), ZeroTangent()) - end - v = SVector{4}(w, false, false, false) - return QuatVec{eltype(v)}(v), QuatVec_pullback -end - -rrule(::Type{QuatVec}, args...) = rrule(quatvec, args...) -rrule(::Type{QuatVec}, w::AbstractQuaternion) = rrule(quatvec, w) -rrule(::Type{QuatVec}, w::AbstractVector) = rrule(quatvec, w) -rrule(::Type{QuatVec}, w::Number) = rrule(quatvec, w) - - - -# rrule(config::RuleConfig{>:HasReverseMode}, ::Type{Rotor}, args...) = rrule_via_ad(config, rotor, args...) -# rrule(config::RuleConfig{>:HasReverseMode}, ::Type{QuatVec}, args...) = rrule_via_ad(config, quatvec, args...) - - - - - - -## Modified from `Complex` entries in ChainRulesCore.jl/src/projection.jl -ProjectTo(::T) where {T<:AbstractQuaternion} = ProjectTo{T}() -ProjectTo(x::AbstractQuaternion{<:Integer}) = ProjectTo(float(x)) -for T in ( - QuaternionF16, QuaternionF32, QuaternionF64, - RotorF16, RotorF32, RotorF64, - QuatVecF16, QuatVecF32, QuatVecF64 -) - @eval ProjectTo(::$T) = ProjectTo{$T}() -end -function (::ProjectTo{QT})(dx::AbstractQuaternion{<:AbstractFloat}) where {T<:AbstractFloat, QT<:AbstractQuaternion{T}} - #@info "ProjectTo{QT}(dx::AbstractQuaternion{<:AbstractFloat})" QT dx typeof(dx) convert(QT, dx) - return convert(QT, dx) -end -# COV_EXCL_START -# function (::ProjectTo{QT})(dx::AbstractFloat) where {T<:AbstractFloat, QT<:AbstractQuaternion{T}} -# return convert(QT, dx) -# end -function (::ProjectTo{QT})(dx::AbstractQuaternion{<:Integer}) where {T<:AbstractFloat, QT<:AbstractQuaternion{T}} - #@info "ProjectTo{QT}(dx::AbstractQuaternion{<:Integer})" - return convert(QT, dx) -end -# function (::ProjectTo{QT})(dx::Integer) where {T<:AbstractFloat, QT<:AbstractQuaternion{T}} -# return convert(QT, dx) -# end -# function (project::ProjectTo{QT})(dx::Real) where {QT<:AbstractQuaternion} -# return project(QT(dx)) -# end -# COV_EXCL_STOP - -# function (project::ProjectTo{<:Number})(dx::Tangent{QT}) where {QT<:AbstractQuaternion} -# project(QT(dx[:components])) -# end - -# # ProjectTo for Number must NOT manufacture a Quaternion from a Tangent{Quaternion}. -# # Instead, take the appropriate scalar (here: the scalar component). -# function (project::ProjectTo{T})(dx::Tangent{QT}) where {QT<:AbstractQuaternion, T<:Number} -# # dx[:components] is a 4-tuple (Δw, Δx, Δy, Δz); a Number primal wants a Number tangent. -# return project(dx[:components][1]) -# end - - -## Copied from `Complex` entries in ChainRulesCore.jl/src/tangent_types/abstract_zero.jl -for pattern ∈ 1:15 - T1 = iszero(pattern & 1) ? Number : AbstractZero - T2 = iszero(pattern & 2) ? Number : AbstractZero - T3 = iszero(pattern & 4) ? Number : AbstractZero - T4 = iszero(pattern & 8) ? Number : AbstractZero - w = iszero(pattern & 1) ? :w : false - x = iszero(pattern & 2) ? :x : false - y = iszero(pattern & 4) ? :y : false - z = iszero(pattern & 8) ? :z : false - @eval (QT::Type{Quaternion})(w::$T1, x::$T2, y::$T3, z::$T4) = QT($w, $x, $y, $z) # COV_EXCL_LINE -end - - -## Copied from `Complex` entries in ChainRulesCore.jl/src/tangent_types/thunks.jl -# COV_EXCL_START -function (::Type{QT})(a::AbstractThunk) where {QT<:AbstractQuaternion} - QT(unthunk(a)) -end -function (::Type{QT})(a::AbstractThunk, b::AbstractThunk, c::AbstractThunk) where {QT<:AbstractQuaternion} - QT(unthunk(a, b, c)) -end -function (::Type{QT})(a::AbstractThunk, b::AbstractThunk, c::AbstractThunk, d::AbstractThunk) where {QT<:AbstractQuaternion} - QT(unthunk(a, b, c, d)) -end -# COV_EXCL_STOP - - -# Following ChainRules , -# we define derivatives of a function of a quaternion in terms of its components: -# -# f(w + 𝐢*x + 𝐣*y + 𝐤*z) = s + 𝐢*t + 𝐣*u + 𝐤*v -# -# The `frule(Δw+𝐢*Δx+𝐣*Δy+𝐤*Δz)` should return -# -# (∂s/∂w Δw + ∂s/∂x Δx + ∂s/∂y Δy + ∂s/∂z Δz) -# + 𝐢 * (∂t/∂w Δw + ∂t/∂x Δx + ∂t/∂y Δy + ∂t/∂z Δz) -# + 𝐣 * (∂u/∂w Δw + ∂u/∂x Δx + ∂u/∂y Δy + ∂u/∂z Δz) -# + 𝐤 * (∂v/∂w Δw + ∂v/∂x Δx + ∂v/∂y Δy + ∂v/∂z Δz) -# -# while the `rrule(Δs+𝐢*Δt+𝐣*Δu+𝐤*Δv)` should return -# -# (∂s/∂w Δs + ∂t/∂w Δt + ∂u/∂w Δu + ∂v/∂w Δv) -# + 𝐢 * (∂s/∂x Δs + ∂t/∂x Δt + ∂u/∂x Δu + ∂v/∂x Δv) -# + 𝐣 * (∂s/∂y Δs + ∂t/∂y Δt + ∂u/∂y Δu + ∂v/∂y Δv) -# + 𝐤 * (∂s/∂z Δs + ∂t/∂z Δt + ∂u/∂z Δu + ∂v/∂z Δv) - -function rrule(::typeof(+), t::Real, q::AbstractQuaternion) - y = t + q - function add_pullback_tq(Δy) - Δw, Δx, Δu, Δv = components(unthunk(Δy)) - return NoTangent(), Δw, typeof(q)(Δw, Δx, Δu, Δv) - end - return y, add_pullback_tq -end -function rrule(::typeof(+), q::AbstractQuaternion, t::Real) - y = q + t - function add_pullback_qt(Δy) - Δw, Δx, Δu, Δv = components(unthunk(Δy)) - return NoTangent(), typeof(q)(Δw, Δx, Δu, Δv), Δw - end - return y, add_pullback_qt -end - -function rrule(::typeof(*), t::Real, q::AbstractQuaternion) - function mul_pullback(Δq) - ∂t = @thunk q ⋅ unthunk(Δq) - ∂q = @thunk t * unthunk(Δq) - return (NoTangent(), ∂t, ∂q) - end - return t * q, mul_pullback -end -function rrule(::typeof(*), q::AbstractQuaternion, t::Real) - function mul_pullback(Δq) - ∂t = @thunk q ⋅ unthunk(Δq) - ∂q = @thunk t * unthunk(Δq) - return (NoTangent(), ∂q, ∂t) - end - return q * t, mul_pullback -end - -function rrule(::typeof(exp), q::Quaternion{T}) where T - w, x, y, z = components(q) - a = absvec(q) - e = exp(w) - sinc = _sincu(a) - coss = _cossu(a) - - s = e * cos(a) - t = e * x * sinc - u = e * y * sinc - v = e * z * sinc - R = quaternion(s, t, u, v) - - ∂sinc∂x = coss * x - ∂sinc∂y = coss * y - ∂sinc∂z = coss * z - ∂s∂w = s - ∂t∂w = t - ∂u∂w = u - ∂v∂w = v - ∂s∂x = -e * x * sinc - ∂s∂y = -e * y * sinc - ∂s∂z = -e * z * sinc - ∂t∂x = e * sinc + e * x * ∂sinc∂x - ∂t∂y = e * x * ∂sinc∂y - ∂t∂z = e * x * ∂sinc∂z - ∂u∂x = e * y * ∂sinc∂x - ∂u∂y = e * sinc + e * y * ∂sinc∂y - ∂u∂z = e * y * ∂sinc∂z - ∂v∂x = e * z * ∂sinc∂x - ∂v∂y = e * z * ∂sinc∂y - ∂v∂z = e * sinc + e * z * ∂sinc∂z - - function exp_pullback(ΔR) - Δs, Δt, Δu, Δv = components(unthunk(ΔR)) - return ( - NoTangent(), - typeof(q)( - (∂s∂w * Δs + ∂t∂w * Δt + ∂u∂w * Δu + ∂v∂w * Δv), - (∂s∂x * Δs + ∂t∂x * Δt + ∂u∂x * Δu + ∂v∂x * Δv), - (∂s∂y * Δs + ∂t∂y * Δt + ∂u∂y * Δu + ∂v∂y * Δv), - (∂s∂z * Δs + ∂t∂z * Δt + ∂u∂z * Δu + ∂v∂z * Δv) - ) - ) - end - - return R, exp_pullback -end - -function rrule(::typeof(exp), v⃗::QuatVec{T}) where T - x, y, z = vec(v⃗) - a = absvec(v⃗) - sinc = _sincu(a) - coss = _cossu(a) - - s = cos(a) - t = x * sinc - u = y * sinc - v = z * sinc - R = rotor(s, t, u, v) - - ∂sinc∂x = coss * x - ∂sinc∂y = coss * y - ∂sinc∂z = coss * z - ∂s∂x = -x * sinc - ∂s∂y = -y * sinc - ∂s∂z = -z * sinc - ∂t∂x = sinc + x * ∂sinc∂x - ∂t∂y = x * ∂sinc∂y - ∂t∂z = x * ∂sinc∂z - ∂u∂x = y * ∂sinc∂x - ∂u∂y = sinc + y * ∂sinc∂y - ∂u∂z = y * ∂sinc∂z - ∂v∂x = z * ∂sinc∂x - ∂v∂y = z * ∂sinc∂y - ∂v∂z = sinc + z * ∂sinc∂z - - function exp_pullback(ΔR) - Δs, Δt, Δu, Δv = components(unthunk(ΔR)) - return ( - NoTangent(), - typeof(v⃗)( - (∂s∂x * Δs + ∂t∂x * Δt + ∂u∂x * Δu + ∂v∂x * Δv), - (∂s∂y * Δs + ∂t∂y * Δt + ∂u∂y * Δu + ∂v∂y * Δv), - (∂s∂z * Δs + ∂t∂z * Δt + ∂u∂z * Δu + ∂v∂z * Δv) - ) - ) - end - - return R, exp_pullback -end - - -end diff --git a/ext/QuaternionicChainRulesCoreExt/QuaternionicChainRulesCoreExt.jl b/ext/QuaternionicChainRulesCoreExt/QuaternionicChainRulesCoreExt.jl new file mode 100644 index 00000000..9887708a --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/QuaternionicChainRulesCoreExt.jl @@ -0,0 +1,30 @@ +# Derivative rules (`rrule`s and `frule`s) and projections for ChainRules consumers, such as +# Zygote. This file is loaded as a package extension on Julia 1.9 and later, and by Requires +# (included from `src/Quaternionic.jl`, so nested inside `Quaternionic`) on earlier versions. +# +# The conventions for tangents and cotangents are documented at the top of `projection.jl`, +# and the helper functions that every rule file uses are listed at the top of `helpers.jl`. +# Rules and opt-outs live in separate files, because an `@opt_out` with exactly the signature +# of a supplied rule silently deletes that rule. +module QuaternionicChainRulesCoreExt + +# Under Requires, this file is included into `Quaternionic` itself, so both `Quaternionic` +# and `ChainRulesCore` (which Requires binds there) are reached as relative imports. +isdefined(Base, :get_extension) ? + (using Quaternionic; import Quaternionic: basetype, value, iszerovalue) : + (using ..Quaternionic; import ..Quaternionic: basetype, value, iszerovalue) +isdefined(Base, :get_extension) ? + (using ChainRulesCore; import ChainRulesCore: rrule, frule, ProjectTo, @opt_out) : + (using ..ChainRulesCore; import ..ChainRulesCore: rrule, frule, ProjectTo, @opt_out) +using StaticArrays: SVector +using LinearAlgebra: LinearAlgebra, dot, norm, normalize + +include("helpers.jl") +include("projection.jl") +include("structural.jl") +include("arithmetic.jl") +include("elementary.jl") +include("geometry.jl") +include("optouts.jl") + +end # module diff --git a/ext/QuaternionicChainRulesCoreExt/arithmetic.jl b/ext/QuaternionicChainRulesCoreExt/arithmetic.jl new file mode 100644 index 00000000..6019d8a9 --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/arithmetic.jl @@ -0,0 +1,395 @@ +# Rules for arithmetic (section 3.2 of the AD specification): the binary operations `+`, `-`, +# `*`, `/`, and `\`, with the `Base.FastMath` versions of the first four; unary `-`, `conj`, +# and `inv`, with `sub_fast` and `inv_fast`; the left folds of `*` and `+` (and of `mul_fast` +# and `add_fast`) with three or more arguments; and `muladd`. +# +# Each rule is the exact derivative of what the source computes from the stored components: +# +# * Quaternion multiplication is bilinear (ℂ-bilinear for complex components), so the +# pullback of `a * b` is `(Δ * qadjoint(b), qadjoint(a) * Δ)`. +# * Division by a `Quaternion` or a `QuatVec` is multiplication by its inverse. Division +# by a `Rotor` divides by `abs2(::Rotor)`, which is identically one, so `a / R` is +# `a * conj(R)`, even for a `Rotor` that does not have unit norm. +# * The product and the quotient of two `Rotor`s with real components are normalized +# (through `rotor`). Those with complex components are normalized only when the sum of +# the squared magnitudes of the raw components is less than 16, as in +# `Quaternionic.complex_rotor_product`. The two-argument rules for complex `Rotor` pairs +# are opted out in `optouts.jl`, so that the AD system traces the source; but the folds +# and `muladd`, which cannot hand a single step back to the AD system, reproduce that test +# in `isrenormalized`. +# * `a \ b` is Base's generic `adjoint(adjoint(b) / adjoint(a))`, so its rule is the +# composition of the rules for those three steps. This gives `inv(a) * b` for a +# `Quaternion` `a`, but `R \ b == conj(R) * b` for a `Rotor` `R`, and `t \ q == q / conj(t)` +# for a complex scalar `t`. +# * `muladd(a, b, c)` promotes its three arguments to a common type and then computes +# `a * b + c`. Promotion converts without normalizing, so it has a unit derivative; but it +# leaves three `Rotor`s as `Rotor`s, whose product is then normalized. +# +# The rules for two arguments forward to `binary_rrule` and `binary_frule`, which dispatch on +# the operation and the argument types through `binary_cotangents` and `binary_pushforward`. + +######################################################################################## +## Normalizing tangents and cotangents +######################################################################################## + +""" + outputcot(Ω, ΔΩ) + +Normalize the cotangent `ΔΩ` of the output `Ω` of an arithmetic operation: `cot(ΔΩ)` for a +quaternion `Ω`, with the scalar part set to zero for a `QuatVec` (whose scalar part is +identically zero, so that its cotangent is meaningless), and `scalarcot(ΔΩ)` for any other +number. +""" +outputcot(::AQ, ΔΩ) = cot(ΔΩ) +function outputcot(::QuatVec, ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return Δ + return quaternion(zero(Δ[1]), Δ[2], Δ[3], Δ[4]) +end +outputcot(::Number, ΔΩ) = scalarcot(ΔΩ) + +""" + iszerotangent(ẋ) + +Return `true` when the tangent `ẋ` is `nothing` or an `AbstractZero`, possibly inside a +thunk. The result depends only on the type of `ẋ`. +""" +iszerotangent(ẋ) = unthunk(ẋ) isa Union{Nothing,AbstractZero} + +""" + inputtangent(x, ẋ) + +Return the tangent `ẋ` of the argument `x` in the form that the pushforwards use: a +`Quaternion` for a quaternion `x` (with zero scalar part for a `QuatVec`), a number for any +other number, and `false` (a strong zero) for a zero tangent. A number that is the tangent +of a quaternion is the quaternion with only that scalar part, so that the tangent of a +number promoted to a quaternion (as in `muladd`) is embedded correctly. +""" +inputtangent(::AQ, ẋ) = zerofill(cot(ẋ)) +function inputtangent(::QuatVec, ẋ) + Δ = cot(ẋ) + Δ isa AbstractZero && return false + return quaternion(zero(Δ[1]), Δ[2], Δ[3], Δ[4]) +end +inputtangent(::Number, ẋ) = zerofill(scalarcot(ẋ)) + +######################################################################################## +## Products and quotients of rotors, which may be normalized +######################################################################################## + +""" + rawproduct(op, a, b) + +Return the raw product (for `op` being `*`) or quotient (for `/`) of the `Rotor`s `a` and +`b` as a `Quaternion`, before the normalization that the source applies to `Rotor` +products. The components are computed by the same expressions as in the source. +""" +rawproduct(::typeof(*), a::Rotor, b::Rotor) = quaternion(a) * b +rawproduct(::typeof(/), a::Rotor, b::Rotor) = quaternion(a) / b + +""" + isrenormalized(P) + +Return `true` when the raw product or quotient `P` of two `Rotor`s, at least one of which +has complex components, is normalized by the source. This is the test of +`Quaternionic.complex_rotor_product`, applied to values, so that dual numbers take the same +branch as the numbers they contain. +""" +isrenormalized(P::AQ) = (value(sum(abs2, components(P))) < 16) === true + +######################################################################################## +## Pullbacks of the binary operations +######################################################################################## + +""" + product_cotangents(a, b, Δ) + +Return the cotangents `(∂a, ∂b)` of the arguments of the raw product `a * b`, given the +`Quaternion` (or, for two numbers, scalar) cotangent `Δ` of the product. A cotangent of a +number that is not a quaternion is a number. +""" +product_cotangents(a::AQ, b::AQ, Δ) = (Δ * qadjoint(b), qadjoint(a) * Δ) +product_cotangents(a::Number, b::AQ, Δ) = (inner(b, Δ), conj(a) * Δ) +product_cotangents(a::AQ, b::Number, Δ) = (Δ * conj(b), inner(a, Δ)) +product_cotangents(a::Number, b::Number, Δ) = (Δ * conj(b), conj(a) * Δ) + +""" + quotient_cotangents(Ω, a, b, Δ) + +Return the cotangents `(∂a, ∂b)` of the arguments of the raw quotient `Ω = a / b`, given +the `Quaternion` cotangent `Δ` of the quotient. For a `Quaternion` or `QuatVec` divisor, +`Ω = a * inv(b)`; for a `Rotor` divisor, the source computes `Ω = a * conj(b)`; and for a +number that is not a quaternion, `Ω` is `a` with each component divided by `b`. +""" +function quotient_cotangents(Ω, a, b::AQ, Δ) + ib = inv(q_(b)) + ∂a = first(product_cotangents(a, ib, Δ)) + ∂b = -(qadjoint(Ω) * Δ * qadjoint(ib)) + return ∂a, ∂b +end +quotient_cotangents(Ω, a, b::Number, Δ) = (Δ / conj(b), -inner(Ω, Δ) / conj(b)) +function quotient_cotangents(Ω, a, b::Rotor, Δ) + ∂a = first(product_cotangents(a, conj(quaternion(b)), Δ)) + ∂b = conj(qadjoint(a) * Δ) + return ∂a, ∂b +end + +""" + binary_cotangents(op, Ω, a, b, Δ) + +Return the cotangents `(∂a, ∂b)` of the arguments of `Ω = op(a, b)`, before projection, +given the cotangent `Δ` of `Ω`, normalized by `outputcot`. +""" +binary_cotangents(::typeof(+), Ω, a, b, Δ) = (Δ, Δ) +binary_cotangents(::typeof(-), Ω, a, b, Δ) = (Δ, -Δ) +binary_cotangents(::typeof(*), Ω, a, b, Δ) = product_cotangents(a, b, Δ) +binary_cotangents(::typeof(/), Ω, a, b, Δ) = quotient_cotangents(Ω, a, b, Δ) +function binary_cotangents(::typeof(\), Ω, a, b, Δ) + # Ω = adjoint(Ω′) with Ω′ = adjoint(b) / adjoint(a). The `adjoint` of a quaternion is + # its quaternion conjugate, and that of a complex number is its complex conjugate; each + # is its own adjoint as a linear map over the reals, so cotangents pass through it as + # tangents do. + ∂b′, ∂a′ = binary_cotangents(/, adjoint(Ω), adjoint(b), adjoint(a), adjoint(Δ)) + return adjoint(∂a′), adjoint(∂b′) +end + +# The normalized products and quotients of two rotors. +for op ∈ (:*, :/) + @eval begin + function binary_cotangents(::typeof($op), Ω, a::Rotor{<:Real}, b::Rotor{<:Real}, Δ) + P = rawproduct($op, a, b) + return binary_cotangents($op, P, quaternion(a), b, normalize_pullback(P, Δ)) + end + function binary_cotangents(::typeof($op), Ω, a::Rotor, b::Rotor, Δ) + P = rawproduct($op, a, b) + ΔP = isrenormalized(P) ? normalize_pullback(P, Δ) : Δ + return binary_cotangents($op, P, quaternion(a), b, ΔP) + end + end +end + +""" + binary_rrule(op, a, b) + +Return the primal `op(a, b)` and its pullback, for `op` being `+`, `-`, `*`, `/`, or `\\`, +and for any combination of quaternions and other numbers. +""" +function binary_rrule(op, a, b) + Ω = op(a, b) + proja, projb = ProjectTo(a), ProjectTo(b) + function binary_pullback(ΔΩ) + Δ = outputcot(Ω, ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, Δ) + ∂a, ∂b = binary_cotangents(op, Ω, a, b, Δ) + return NoTangent(), proja(∂a), projb(∂b) + end + return Ω, binary_pullback +end + +######################################################################################## +## Pushforwards of the binary operations +######################################################################################## + +""" + binary_pushforward(op, Ω, a, b, ȧ, ḃ) + +Return the tangent of `Ω = op(a, b)`, before projection, given the tangents `ȧ` and `ḃ` +of the arguments, normalized by `inputtangent`. +""" +binary_pushforward(::typeof(+), Ω, a, b, ȧ, ḃ) = ȧ + ḃ +binary_pushforward(::typeof(-), Ω, a, b, ȧ, ḃ) = ȧ - ḃ +binary_pushforward(::typeof(*), Ω, a, b, ȧ, ḃ) = ȧ * q_(b) + q_(a) * ḃ +binary_pushforward(::typeof(/), Ω, a, b, ȧ, ḃ) = (ȧ - q_(Ω) * ḃ) * inv(q_(b)) +binary_pushforward(::typeof(/), Ω, a, b::Rotor, ȧ, ḃ) = + ȧ * conj(quaternion(b)) + q_(a) * conj(ḃ) +function binary_pushforward(::typeof(\), Ω, a, b, ȧ, ḃ) + # As in `binary_cotangents`, Ω = adjoint(adjoint(b) / adjoint(a)). + Ω̇′ = binary_pushforward(/, adjoint(Ω), adjoint(b), adjoint(a), adjoint(ḃ), adjoint(ȧ)) + return adjoint(Ω̇′) +end + +# The normalized products and quotients of two rotors. +for op ∈ (:*, :/) + @eval begin + function binary_pushforward(::typeof($op), Ω, a::Rotor{<:Real}, b::Rotor{<:Real}, ȧ, ḃ) + P = rawproduct($op, a, b) + return normalize_pushforward(P, binary_pushforward($op, P, quaternion(a), b, ȧ, ḃ)) + end + function binary_pushforward(::typeof($op), Ω, a::Rotor, b::Rotor, ȧ, ḃ) + P = rawproduct($op, a, b) + Ṗ = binary_pushforward($op, P, quaternion(a), b, ȧ, ḃ) + return isrenormalized(P) ? normalize_pushforward(P, Ṗ) : Ṗ + end + end +end + +""" + binary_frule(op, a, b, ȧ, ḃ) + +Return the primal `op(a, b)` and its tangent, given the tangents `ȧ` and `ḃ` of the +arguments, for `op` being `+`, `-`, `*`, `/`, or `\\`. +""" +function binary_frule(op, a, b, ȧ, ḃ) + Ω = op(a, b) + iszerotangent(ȧ) && iszerotangent(ḃ) && return Ω, ZeroTangent() + Ω̇ = binary_pushforward(op, Ω, a, b, inputtangent(a, ȧ), inputtangent(b, ḃ)) + return Ω, ProjectTo(Ω)(Ω̇) +end + +######################################################################################## +## Rules for the binary operations +######################################################################################## + +for (op, opfast) ∈ ((:+, :add_fast), (:-, :sub_fast), (:*, :mul_fast), (:/, :div_fast), (:\, nothing)) + fs = opfast === nothing ? (op,) : (op, :(Base.FastMath.$opfast)) + for f ∈ fs, (A, B) ∈ ((:AQ, :AQ), (:AQ, :Number), (:Number, :AQ)) + @eval rrule(::typeof($f), a::$A, b::$B) = binary_rrule($op, a, b) + @eval frule((_, ȧ, ḃ)::Tuple, ::typeof($f), a::$A, b::$B) = binary_frule($op, a, b, ȧ, ḃ) + end +end + +# These are covered by the methods for `(AQ, AQ)` above, and are listed separately to make +# explicit that the normalized products of real rotors have rules. The products of complex +# rotors are opted out in `optouts.jl`. +for (op, opfast) ∈ ((:*, :mul_fast), (:/, :div_fast)), f ∈ (op, :(Base.FastMath.$opfast)) + @eval rrule(::typeof($f), a::Rotor{<:Real}, b::Rotor{<:Real}) = binary_rrule($op, a, b) + @eval frule((_, ȧ, ḃ)::Tuple, ::typeof($f), a::Rotor{<:Real}, b::Rotor{<:Real}) = + binary_frule($op, a, b, ȧ, ḃ) +end + +######################################################################################## +## Unary operations +######################################################################################## + +""" + unary_cotangent(op, Ω, q, Δ) + +Return the cotangent of the argument of `Ω = op(q)`, before projection, given the +`Quaternion` cotangent `Δ` of `Ω`, for `op` being `-`, `conj`, or `inv`. The inverse of a +`Rotor` is its conjugate, whatever its norm. +""" +unary_cotangent(::typeof(-), Ω, q, Δ) = -Δ +unary_cotangent(::typeof(conj), Ω, q, Δ) = conj(Δ) +function unary_cotangent(::typeof(inv), Ω, q, Δ) + Ωa = qadjoint(Ω) + return -(Ωa * Δ * Ωa) +end +unary_cotangent(::typeof(inv), Ω, q::Rotor, Δ) = conj(Δ) + +""" + unary_pushforward(op, Ω, q, q̇) + +Return the tangent of `Ω = op(q)`, before projection, given the `Quaternion` tangent `q̇` +of `q`, for `op` being `-`, `conj`, or `inv`. +""" +unary_pushforward(::typeof(-), Ω, q, q̇) = -q̇ +unary_pushforward(::typeof(conj), Ω, q, q̇) = conj(q̇) +function unary_pushforward(::typeof(inv), Ω, q, q̇) + Ωq = quaternion(Ω) + return -(Ωq * q̇ * Ωq) +end +unary_pushforward(::typeof(inv), Ω, q::Rotor, q̇) = conj(q̇) + +""" + unary_rrule(op, q) + +Return the primal `op(q)` and its pullback, for `op` being `-`, `conj`, or `inv`. +""" +function unary_rrule(op, q::AQ) + Ω = op(q) + proj = ProjectTo(q) + function unary_pullback(ΔΩ) + Δ = outputcot(Ω, ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(unary_cotangent(op, Ω, q, Δ)) + end + return Ω, unary_pullback +end + +""" + unary_frule(op, q, q̇) + +Return the primal `op(q)` and its tangent, given the tangent `q̇` of `q`, for `op` being +`-`, `conj`, or `inv`. +""" +function unary_frule(op, q::AQ, q̇) + Ω = op(q) + iszerotangent(q̇) && return Ω, ZeroTangent() + return Ω, ProjectTo(Ω)(unary_pushforward(op, Ω, q, inputtangent(q, q̇))) +end + +# `sub_fast(q)` is `-q`, and `inv_fast(q)` is `inv(q)`. +for (f, op) ∈ ((:-, :-), (:(Base.FastMath.sub_fast), :-), (:conj, :conj), (:inv, :inv), + (:(Base.FastMath.inv_fast), :inv)) + @eval rrule(::typeof($f), q::AQ) = unary_rrule($op, q) + @eval frule((_, q̇)::Tuple, ::typeof($f), q::AQ) = unary_frule($op, q, q̇) +end + +######################################################################################## +## Products and sums of three or more arguments, and `muladd` +######################################################################################## + +""" + fold_rrule(op, a, b, xs...) + +Return the primal and the pullback of the left fold `op(op(op(a, b), xs[1]), ...)`, which +is how Base evaluates `*` and `+` (and the source evaluates `mul_fast` and `add_fast`) with +three or more arguments. Each step uses `binary_rrule`. + +These are rules rather than opt-outs, because ChainRules' own rule for `*` with four or more +arguments calls `rrule(*, Ω3, more...)` on the product `Ω3` of the first three arguments and +the rest; that call reaches these rules when the first quaternion is the fifth argument or +later, and an opt-out there would return `nothing`. +""" +fold_rrule(op, a, b) = binary_rrule(op, a, b) +function fold_rrule(op, a, b, c, xs...) + ab, ab_pullback = binary_rrule(op, a, b) + Ω, rest_pullback = fold_rrule(op, ab, c, xs...) + function fold_pullback(ΔΩ) + Δrest = rest_pullback(ΔΩ) + _, ∂a, ∂b = ab_pullback(Δrest[2]) + return (NoTangent(), ∂a, ∂b, Base.tail(Base.tail(Δrest))...) + end + return Ω, fold_pullback +end + +""" + muladd_rrule(a, b, c) + +Return the primal `muladd(a, b, c)` and its pullback. Base promotes the three arguments to +a common type and computes `a * b + c`; promotion converts without normalizing, so the +cotangent of each promoted argument is simply projected onto the original argument. +""" +function muladd_rrule(a, b, c) + pa, pb, pc = promote(a, b, c) + ab, product_pullback = binary_rrule(*, pa, pb) + Ω, sum_pullback = binary_rrule(+, ab, pc) + function muladd_pullback(ΔΩ) + _, ∂ab, ∂c = sum_pullback(ΔΩ) + _, ∂a, ∂b = product_pullback(∂ab) + return (NoTangent(), projectargs((a, b, c), (∂a, ∂b, ∂c))...) + end + return Ω, muladd_pullback +end + +""" + muladd_frule(a, b, c, ȧ, ḃ, ċ) + +Return the primal `muladd(a, b, c)` and its tangent, given the tangents of the arguments. +""" +function muladd_frule(a, b, c, ȧ, ḃ, ċ) + pa, pb, pc = promote(a, b, c) + ab, ab_dot = binary_frule(*, pa, pb, ȧ, ḃ) + return binary_frule(+, ab, pc, ab_dot, ċ) +end + +for (A, B, C) ∈ Iterators.product(ntuple(i -> (:AQ, :Number), 3)...) + :AQ ∈ (A, B, C) || continue + for (f, op) ∈ ((:*, :*), (:+, :+), (:(Base.FastMath.mul_fast), :*), (:(Base.FastMath.add_fast), :+)) + @eval rrule(::typeof($f), a::$A, b::$B, c::$C, xs::Vararg{Number}) = + fold_rrule($op, a, b, c, xs...) + end + @eval rrule(::typeof(muladd), a::$A, b::$B, c::$C) = muladd_rrule(a, b, c) + @eval frule((_, ȧ, ḃ, ċ)::Tuple, ::typeof(muladd), a::$A, b::$B, c::$C) = + muladd_frule(a, b, c, ȧ, ḃ, ċ) +end diff --git a/ext/QuaternionicChainRulesCoreExt/elementary.jl b/ext/QuaternionicChainRulesCoreExt/elementary.jl new file mode 100644 index 00000000..68fe0a13 --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/elementary.jl @@ -0,0 +1,1000 @@ +# Rules for `exp`, `log`, `sqrt`, powers, and `csqrt` (sections 3.3, 3.4, and 3.7 of the AD +# specification). +# +# Each rule is the exact derivative of what the source in `src/math.jl` computes from the +# stored components, including off the unit sphere for a `Rotor`, whose `log`, `sqrt`, and +# powers assume unit norm in ways that the rules reproduce. The primal is always computed +# by calling the function itself. The pullbacks and pushforwards are generic in the element +# type, so that nested AD (such as `Zygote.hessian`, which runs ForwardDiff through them) +# works, and every branch inside them tests values, through `value` and `iszerovalue`. +# +# Near the identity, the functions of the vector part are evaluated as power series, so that +# all of their derivatives stay accurate there. The number of terms depends on the +# precision of the element type, so that the series are as accurate for `BigFloat` as for +# `Float64`. The pullbacks of `log` and `sqrt` are evaluated in forms that cannot overflow +# or underflow where the primal does not. +# +# Only real components have rules for `log`, `sqrt`, non-integer powers, and integer powers +# of a `Rotor`; with complex components these are opted out in `optouts.jl`, so that the AD +# system differentiates the source. `exp` and integer powers of a `Quaternion` or `QuatVec` +# have rules for any components. + +######################################################################################## +## Small helpers +######################################################################################## + +""" + seriestype(x) + +Return the real floating-point type of the value of `x`, whose precision decides how many +terms of a power series are needed. +""" +seriestype(x) = real(float(typeof(value(x)))) + +""" + bilinearvec(a, b) + +Return the bilinear product `Σᵢ aᵢ bᵢ` of the vector components (2 to 4) of the quaternions +`a` and `b`, without complex conjugation. +""" +bilinearvec(a, b) = a[2] * b[2] + a[3] * b[3] + a[4] * b[4] + +""" + vecpart(q) + +Return the `Quaternion` with the vector part of `q` and a zero scalar part. +""" +vecpart(q) = quaternion(zero(q[2]), q[2], q[3], q[4]) + +""" + pushtangent(x, ẋ) + +Return the tangent `ẋ` of the argument `x` of a pushforward, normalized and projected onto +`x`. This is a `Quaternion` for a quaternion `x` and a number for a number `x`, and it is a +zero of that type when `ẋ` is `nothing` or an `AbstractZero`, or when `x` is not +differentiable. +""" +function pushtangent(x::AbstractQuaternion, ẋ) + z = zero(float(quaternion(x))) + Δ = cot(ẋ) + Δ isa AbstractZero && return z + t = ProjectTo(x)(Δ) + t isa AbstractZero && return z + return quaternion(t) +end +function pushtangent(x::Number, ẋ) + z = zero(float(x)) + Δ = scalarcot(ẋ) + Δ isa AbstractZero && return z + t = ProjectTo(x)(Δ) + t isa AbstractZero && return z + return t +end + +######################################################################################## +## Power series +######################################################################################## + +""" + expseriesterms(T) + +Return the number of terms of the series in `cosroot`, `sincroot`, and `sincrootslope` that +makes their truncation error smaller than the precision of `T` for every `|x| < 1`. This is +the smallest `n` with `(2n)! ≥ 2^(precision(T)+3)`, which is 10 for `Float64`. For types +without a precision, it is 10. +""" +function expseriesterms(::Type{T}) where {T<:AbstractFloat} + bits = precision(T) + 3 + n, l = 1, 1.0 # l = log2((2n)!) + while l < bits + n += 1 + l += log2((2n - 1) * (2n)) + end + return n +end +expseriesterms(::Type) = 10 +# The values for the IEEE types, which the method above also returns, are given explicitly, +# so that they cost nothing at run time. +expseriesterms(::Type{Float64}) = 10 +expseriesterms(::Type{Float32}) = 6 +expseriesterms(::Type{Float16}) = 4 + +""" + logseriesterms(T) + +Return the number of terms of the series in `atanroot` and `atanrootslope` that makes their +truncation error smaller than the precision of `T` for every `0 ≤ x ≤ 1/16`. This is 14 for +`Float64`. For types without a precision, it is 24. +""" +logseriesterms(::Type{T}) where {T<:AbstractFloat} = cld(precision(T) + 3, 4) +logseriesterms(::Type) = 24 + +""" + rootclosedforms(x) + +Return `(cos(√x), sin(√x)/√x)` in closed form. Both are even functions of √x, so the branch +of the square root does not matter. When the real part of `x` is negative, they are +evaluated as `cosh(√(-x))` and `sinh(√(-x))/√(-x)`, so that the square root is never taken +on or near its branch cut. (On the cut, ForwardDiff's derivative of the complex square +root of a number whose imaginary part is a negative zero belongs to the opposite branch from +its value, which spoils nested derivatives.) +""" +function rootclosedforms(x) + if real(value(x)) < 0 + b = sqrt(-x) + return cosh(b), sinh(b) / b + end + a = sqrt(x) + return cos(a), sin(a) / a +end + +""" + cosroot(x) + +Return cos(√x) = Σₖ (-x)ᵏ/(2k)!, evaluated as a power series when `abs(value(x)) < 1`. +""" +function cosroot(x) + abs(value(x)) < 1 || return first(rootclosedforms(x)) + r = one(x) + for k ∈ expseriesterms(seriestype(x))-1:-1:1 + r = 1 - x / ((2k - 1) * (2k)) * r + end + return r +end + +""" + sincroot(x) + +Return sin(√x)/√x = Σₖ (-x)ᵏ/(2k+1)!, evaluated as a power series when `abs(value(x)) < 1`. +""" +function sincroot(x) + abs(value(x)) < 1 || return last(rootclosedforms(x)) + r = one(x) + for k ∈ expseriesterms(seriestype(x))-1:-1:1 + r = 1 - x / ((2k) * (2k + 1)) * r + end + return r +end + +""" + sincrootslope(x) + +Return (cos(√x) - sin(√x)/√x)/x, which is twice the derivative of `sincroot(x)`, evaluated +as the power series Σₖ (-1)ᵏ⁺¹ 2(k+1) xᵏ/(2k+3)! when `abs(value(x)) < 1`. +""" +function sincrootslope(x) + if abs(value(x)) ≥ 1 + C, S = rootclosedforms(x) + return (C - S) / x + end + # The ratio of consecutive terms is -x/(2k(2k+3)), and the first term is -1/3. + r = one(x) + for k ∈ expseriesterms(seriestype(x))-1:-1:1 + r = 1 - x / ((2k) * (2k + 3)) * r + end + return -r / 3 +end + +""" + atanroot(x) + +Return atan(√x)/√x = Σₖ (-x)ᵏ/(2k+1) as a power series, accurate for `0 ≤ x ≤ 1/16`. +""" +function atanroot(x) + # The ratio of consecutive terms is -(2k-1)x/(2k+1), and the first term is 1. + r = one(x) + for k ∈ logseriesterms(seriestype(x))-1:-1:1 + r = 1 - x * (2k - 1) / (2k + 1) * r + end + return r +end + +""" + atanrootslope(x) + +Return (1/(1+x) - atanroot(x))/x = Σₖ₌₁ (-1)ᵏ 2k/(2k+1) xᵏ⁻¹ as a power series, accurate for +`0 ≤ x ≤ 1/16`. +""" +function atanrootslope(x) + # The ratio of consecutive terms is -x(k+1)(2k+1)/(k(2k+3)), and the first term is -2/3. + r = one(x) + for k ∈ logseriesterms(seriestype(x))-1:-1:1 + r = 1 - x * ((k + 1) * (2k + 1)) / (k * (2k + 3)) * r + end + return -2r / 3 +end + +######################################################################################## +## exp +######################################################################################## + +# exp(w + v⃗) = E (C + S v⃗), with E = exp(w), x = Σᵢ vᵢ² (bilinear for complex components), +# C = cos√x, and S = sin√x/√x. With D = (C - S)/x = 2 dS/dx, the pushforward is +# Ω̇ = ẇ Ω + E (-S ⟨v⃗, v⃗̇⟩ + S v⃗̇ + D ⟨v⃗, v⃗̇⟩ v⃗), +# with the bilinear ⟨⋅, ⋅⟩. The pullback applies the conjugate transpose, which evaluates +# the same coefficients at the componentwise conjugate of `q`. The factor Ω in the first +# term is recomputed from C and S, rather than taken from the primal, so that the rule does +# not depend on how well an AD system differentiates the source's own evaluation of `exp` +# when nested AD runs through the rule. (With complex components, the source's `absvec` +# takes a complex square root that may lie on its branch cut.) + +""" + expfactors(q) + +Return `(E, C, S, D)` for the quaternion `q = w + v⃗`: E = exp(w), and with x = Σᵢ vᵢ², +C = cos√x, S = sin√x/√x, and D = (C - S)/x. +""" +function expfactors(q) + x = q[2] * q[2] + q[3] * q[3] + q[4] * q[4] + return exp(q[1]), cosroot(x), sincroot(x), sincrootslope(x) +end + +""" + exp_pushforward(q, q̇) + +Return the pushforward of `exp` at the `Quaternion` `q`, applied to the `Quaternion` tangent +`q̇`. +""" +function exp_pushforward(q, q̇) + E, C, S, D = expfactors(q) + vv̇ = bilinearvec(q, q̇) + a = E * S + b = E * D * vv̇ + a * q̇[1] + return quaternion( + E * C * q̇[1] - a * vv̇, + a * q̇[2] + b * q[2], a * q̇[3] + b * q[3], a * q̇[4] + b * q[4] + ) +end + +""" + exp_pullback(q, Δ) + +Return the pullback of `exp` at the `Quaternion` `q`, applied to the `Quaternion` cotangent +`Δ`. +""" +function exp_pullback(q, Δ) + p = conjcomponents(q) + E, C, S, D = expfactors(p) + vΔ = bilinearvec(p, Δ) + a = E * S + b = E * D * vΔ - a * Δ[1] + return quaternion( + E * C * Δ[1] + a * vΔ, a * Δ[2] + b * p[2], a * Δ[3] + b * p[3], a * Δ[4] + b * p[4] + ) +end + +# `exp(::QuatVec)` is the case w = 0, with an unnormalized `Rotor` result, and +# `exp(::Rotor)` is `exp(quaternion(q))`, so one rule serves every quaternion type. +for f ∈ (:exp, :(Base.FastMath.exp_fast)) + @eval begin + function rrule(::typeof($f), q::AQ) + Ω = $f(q) + p = float(quaternion(q)) + proj = ProjectTo(q) + function exp_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(exp_pullback(p, Δ)) + end + return Ω, exp_back + end + function frule((_, q̇)::Tuple, ::typeof($f), q::AQ) + Ω = $f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + ṗ = pushtangent(q, Δ) + return Ω, ProjectTo(Ω)(exp_pushforward(float(quaternion(q)), ṗ)) + end + end +end + +######################################################################################## +## log (real components) +######################################################################################## + +# log(q) = log n + f v⃗ for q = w + v⃗, with n = |q|, a = |v⃗|, and f = atan(a, w)/a. With +# g = (w/n² - f)/a², the pushforward is +# Ω̇ = ⟨q, q̇⟩/n² + f v⃗̇ + v⃗ (g ⟨v⃗, v⃗̇⟩ - ẇ/n²), +# and the pullback is +# ∂w = (w Δ₁ - ⟨v⃗, Δ⃗⟩)/n², ∂v⃗ = (Δ₁/n² + g ⟨v⃗, Δ⃗⟩) v⃗ + f Δ⃗. +# Since log(λq) = log λ + log q for λ > 0, both are evaluated at the unit quaternion p = q/n +# (where n = 1) and divided by n, which cannot overflow or underflow. Near the positive +# real axis (w > 0 and a² ≤ w²/16), with x = a²/w², f = A(x)/w and g = B(x)/w³, where A is +# `atanroot` and B is `atanrootslope`. Elsewhere, g ⟨v⃗, ⋅⟩ v⃗ is evaluated as +# (w - f) ⟨û, ⋅⟩ û with the unit vector û = v⃗/a, so that a² is never formed. Exactly on +# the negative real axis, the source returns the constant vector part π𝐤, so f = g = 0 +# there. + +""" + logfactors(p) + +Return `(f, h, isseries)` for the unit `Quaternion` `p` with real components, with `f` as in +the comment above. When `isseries` is true, `h` is `g`, which multiplies ⟨v⃗, ⋅⟩ v⃗. +Otherwise, `h` is `w - f`, which multiplies ⟨û, ⋅⟩ û, because g = (w - f)/a² when n = 1. +""" +function logfactors(p) + w = p[1] + if value(w) > 0 + x = (p[2] / w)^2 + (p[3] / w)^2 + (p[4] / w)^2 + if value(x) ≤ 1//16 + return atanroot(x) / w, atanrootslope(x) / w^3, true + end + end + if iszerovalue(vec(p)) # On the negative real axis + return zero(w), zero(w), true + end + a = absvec(p) + f = atan(a, w) / a + return f, w - f, false +end + +""" + log_pullback(q, Δ) + +Return the pullback of `log` at the `Quaternion` `q` with real components, applied to the +`Quaternion` cotangent `Δ`. At `q = 0`, where the source returns a constant, the result is +zero. +""" +function log_pullback(q, Δ) + n = abs(q) + if iszerovalue(q) + z = zero(Δ[1] / n) + return quaternion(z, z, z, z) + end + p = q / n + f, h, isseries = logfactors(p) + vΔ = bilinearvec(p, Δ) + α = if isseries + Δ[1] + h * vΔ + else + a = absvec(p) + Δ[1] + (h * (vΔ / a)) / a + end + ∂ = quaternion( + p[1] * Δ[1] - vΔ, α * p[2] + f * Δ[2], α * p[3] + f * Δ[3], α * p[4] + f * Δ[4] + ) + return ∂ / n +end + +""" + log_pushforward(q, q̇) + +Return the pushforward of `log` at the `Quaternion` `q` with real components, applied to the +`Quaternion` tangent `q̇`. At `q = 0`, where the source returns a constant, the result is +zero. +""" +function log_pushforward(q, q̇) + n = abs(q) + if iszerovalue(q) + z = zero(q̇[1] / n) + return quaternion(z, z, z, z) + end + p = q / n + ṗ = q̇ / n + f, h, isseries = logfactors(p) + vv̇ = bilinearvec(p, ṗ) + β = if isseries + h * vv̇ - ṗ[1] + else + a = absvec(p) + (h * (vv̇ / a)) / a - ṗ[1] + end + return quaternion( + p[1] * ṗ[1] + vv̇, f * ṗ[2] + β * p[2], f * ṗ[3] + β * p[3], f * ṗ[4] + β * p[4] + ) +end + +# The source computes log(R) of a real `Rotor` as |R| V for R[1] ≥ 0 (it evaluates θ/sin θ +# with sin θ = a/|R|) and as V for R[1] < 0, where V = vec(log(quaternion(R))) is +# homogeneous of degree 0; exactly on the negative real axis, it returns the constant π𝐤. +# The result is a `QuatVec`, so only the vector part of a cotangent matters. + +""" + rotorlog_pullback(q, L, Δ) + +Return the pullback of `log` at the real `Rotor` with components `q` (a `Quaternion`), +where `L` is `log(q)`, applied to the `Quaternion` cotangent `Δ`. +""" +function rotorlog_pullback(q, L, Δ) + Δv = vecpart(Δ) + ∂V = log_pullback(q, Δv) + if value(q[1]) ≥ 0 + r = abs(q) + return r * ∂V + (bilinearvec(L, Δv) / r) * q + elseif iszerovalue(vec(q)) + return zero(∂V) + else + return ∂V + end +end + +""" + rotorlog_pushforward(q, q̇) + +Return the pushforward of `log` at the real `Rotor` with components `q` (a `Quaternion`), +applied to the `Quaternion` tangent `q̇`, as a `Quaternion` with zero scalar part. +""" +function rotorlog_pushforward(q, q̇) + V̇ = vecpart(log_pushforward(q, q̇)) + if value(q[1]) ≥ 0 + r = abs(q) + return r * V̇ + (inner(q, q̇) / r) * vecpart(log(q)) + elseif iszerovalue(vec(q)) + return zero(V̇) + else + return V̇ + end +end + +for f ∈ (:log, :(Base.FastMath.log_fast)) + @eval begin + function rrule(::typeof($f), q::Quaternion{<:Real}) + Ω = $f(q) + p = float(q) + proj = ProjectTo(q) + function log_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(log_pullback(p, Δ)) + end + return Ω, log_back + end + function frule((_, q̇)::Tuple, ::typeof($f), q::Quaternion{<:Real}) + Ω = $f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, ProjectTo(Ω)(log_pushforward(float(q), pushtangent(q, Δ))) + end + function rrule(::typeof($f), R::Rotor{<:Real}) + Ω = $f(R) + p = float(quaternion(R)) + L = log(p) + proj = ProjectTo(R) + function rotorlog_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(rotorlog_pullback(p, L, Δ)) + end + return Ω, rotorlog_back + end + function frule((_, Ṙ)::Tuple, ::typeof($f), R::Rotor{<:Real}) + Ω = $f(R) + Δ = cot(Ṙ) + Δ isa AbstractZero && return Ω, Δ + Ω̇ = rotorlog_pushforward(float(quaternion(R)), pushtangent(R, Δ)) + return Ω, ProjectTo(Ω)(Ω̇) + end + end +end + +######################################################################################## +## sqrt (real components) +######################################################################################## + +# For a `Quaternion` (and a `QuatVec`, through `quaternion`), s = √q = σ + u⃗ satisfies +# s² = q in every branch of the source, including its rescaling branches, which are exact. +# With r = |s|² = |q|, differentiating s² = q gives +# σ̇ = (σ ẇ + ⟨u⃗, v⃗̇⟩)/(2r), u⃗̇ = (v⃗̇ - 2σ̇ u⃗)/(2σ), +# and the pullback is +# ∂w = (σ Δ₁ - ⟨u⃗, Δ⃗⟩)/(2r), ∂v⃗ = (Δ⃗ + 2 ∂w u⃗)/(2σ). +# The factor 1/r is applied as two divisions by |s|, so that it can neither overflow nor +# underflow. +# On the non-positive real axis, the source returns √(-w) 𝐤, whose only derivative is +# ∂Ω₄/∂w = -1/(2√(-w)). + +""" + sqrt_pullback(q, s, Δ) + +Return the pullback of `sqrt` at the `Quaternion` `q` with real components, where `s` is +`sqrt(q)` as a `Quaternion`, applied to the `Quaternion` cotangent `Δ`. +""" +function sqrt_pullback(q, s, Δ) + if value(q[1]) ≤ 0 && iszerovalue(vec(q)) + ∂w = -Δ[4] / (2s[4]) + z = zero(∂w) + return quaternion(∂w, z, z, z) + end + σ = s[1] + m = abs(s) + ∂w = ((σ / m) * Δ[1] - bilinearvec(s, Δ) / m) / (2m) + c = 2∂w + d = 2σ + return quaternion( + ∂w, (Δ[2] + c * s[2]) / d, (Δ[3] + c * s[3]) / d, (Δ[4] + c * s[4]) / d + ) +end + +""" + sqrt_pushforward(q, s, q̇) + +Return the pushforward of `sqrt` at the `Quaternion` `q` with real components, where `s` is +`sqrt(q)` as a `Quaternion`, applied to the `Quaternion` tangent `q̇`. +""" +function sqrt_pushforward(q, s, q̇) + if value(q[1]) ≤ 0 && iszerovalue(vec(q)) + ṡ₄ = -q̇[1] / (2s[4]) + z = zero(ṡ₄) + return quaternion(z, z, z, ṡ₄) + end + σ = s[1] + m = abs(s) + σ̇ = ((σ / m) * q̇[1] + bilinearvec(s, q̇) / m) / (2m) + c = 2σ̇ + d = 2σ + return quaternion( + σ̇, (q̇[2] - c * s[2]) / d, (q̇[3] - c * s[3]) / d, (q̇[4] - c * s[4]) / d + ) +end + +# The source computes sqrt(R) of a real `Rotor` with abs(R) ≡ 1, so it is not √ off the unit +# sphere. For w ≥ 0, with c = √(2(1+w)), Ω = (c/2, v⃗/c). For w < 0, with s = |v⃗|, +# u⃗ = v⃗/s, and d = √(2(1-w)), Ω = (s/d, u⃗ d/2). On the non-positive real axis, +# Ω = √(-w) 𝐤. + +""" + rotorsqrt_pullback(q, Δ) + +Return the pullback of `sqrt` at the real `Rotor` with components `q` (a `Quaternion`), +applied to the `Quaternion` cotangent `Δ`. +""" +function rotorsqrt_pullback(q, Δ) + w = q[1] + if value(w) ≤ 0 && iszerovalue(vec(q)) + ∂w = -Δ[4] / (2sqrt(-w)) + z = zero(∂w) + return quaternion(∂w, z, z, z) + elseif value(w) ≥ 0 + c = sqrt(2(1 + w)) + return quaternion( + Δ[1] / (2c) - bilinearvec(q, Δ) / c^3, Δ[2] / c, Δ[3] / c, Δ[4] / c + ) + else + s = absvec(q) + d = sqrt(2(1 - w)) + h = d / 2 + uΔ = bilinearvec(q, Δ) / s + ∂s = Δ[1] / d + ∂d = -Δ[1] * s / d^2 + uΔ / 2 + # With u⃗ = v⃗/s and s = |v⃗|, ∂v⃗ = (h Δ⃗ - h ⟨u⃗, Δ⃗⟩ u⃗)/s + ∂s u⃗, + # and ∂w = -∂d/d. + a = h / s + b = (∂s - a * uΔ) / s + return quaternion( + -∂d / d, a * Δ[2] + b * q[2], a * Δ[3] + b * q[3], a * Δ[4] + b * q[4] + ) + end +end + +""" + rotorsqrt_pushforward(q, q̇) + +Return the pushforward of `sqrt` at the real `Rotor` with components `q` (a `Quaternion`), +applied to the `Quaternion` tangent `q̇`. +""" +function rotorsqrt_pushforward(q, q̇) + w = q[1] + if value(w) ≤ 0 && iszerovalue(vec(q)) + ṡ₄ = -q̇[1] / (2sqrt(-w)) + z = zero(ṡ₄) + return quaternion(z, z, z, ṡ₄) + elseif value(w) ≥ 0 + c = sqrt(2(1 + w)) + b = q̇[1] / c^3 + return quaternion( + q̇[1] / (2c), q̇[2] / c - b * q[2], q̇[3] / c - b * q[3], q̇[4] / c - b * q[4] + ) + else + s = absvec(q) + d = sqrt(2(1 - w)) + h = d / 2 + ṡ = bilinearvec(q, q̇) / s + ḋ = -q̇[1] / d + # Ω⃗ = u⃗ h, with u⃗̇ = (v⃗̇ - u⃗ ṡ)/s and ḣ = ḋ/2 + a = h / s + b = (ḋ / 2 - a * ṡ) / s + return quaternion( + ṡ / d - s * ḋ / d^2, + a * q̇[2] + b * q[2], a * q̇[3] + b * q[3], a * q̇[4] + b * q[4] + ) + end +end + +# A `QuatVec` has the same rule as a `Quaternion`, through `quaternion`. +const RealQV = Union{Quaternion{<:Real},QuatVec{<:Real}} +for f ∈ (:sqrt, :(Base.FastMath.sqrt_fast)) + @eval begin + function rrule(::typeof($f), q::RealQV) + Ω = $f(q) + p = float(quaternion(q)) + proj = ProjectTo(q) + function sqrt_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(sqrt_pullback(p, Ω, Δ)) + end + return Ω, sqrt_back + end + function frule((_, q̇)::Tuple, ::typeof($f), q::RealQV) + Ω = $f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + ṗ = pushtangent(q, Δ) + return Ω, ProjectTo(Ω)(sqrt_pushforward(float(quaternion(q)), Ω, ṗ)) + end + function rrule(::typeof($f), R::Rotor{<:Real}) + Ω = $f(R) + p = float(quaternion(R)) + proj = ProjectTo(R) + function rotorsqrt_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(rotorsqrt_pullback(p, Δ)) + end + return Ω, rotorsqrt_back + end + function frule((_, Ṙ)::Tuple, ::typeof($f), R::Rotor{<:Real}) + Ω = $f(R) + Δ = cot(Ṙ) + Δ isa AbstractZero && return Ω, Δ + ṗ = pushtangent(R, Δ) + return Ω, ProjectTo(Ω)(rotorsqrt_pushforward(float(quaternion(R)), ṗ)) + end + end +end + +######################################################################################## +## Integer powers +######################################################################################## + +# With Ω = qⁿ for n ≥ 1, Ω̇ = Σₖ qᵏ⁻¹ q̇ qⁿ⁻ᵏ, which is exact everywhere. The pullback is +# accumulated by the recurrence S₁ = Δ, Sₘ₊₁ = q† Sₘ + Δ (q†)ᵐ, and the pushforward by the +# same recurrence with q in place of q†; neither mutates anything, so that nested AD works. +# A negative power is the inverse of the positive power, as in the source, and the pullback +# of Ω = inv(P) is -Ω† Δ Ω†. + +""" + intpow_pullback(p, n, Ω, Δ) + +Return the pullback of `p ↦ pⁿ` at the `Quaternion` `p` (with floating-point components), +where `Ω = pⁿ` as a `Quaternion`, applied to the `Quaternion` cotangent `Δ`. +""" +function intpow_pullback(p, n::Integer, Ω, Δ) + n == 0 && return zero(p * Δ) + if n < 0 + Ωa = qadjoint(Ω) + return intpow_pullback(p, -n, Ω, -(Ωa * Δ * Ωa)) + end + a = qadjoint(p) + S = Δ * one(a) + P = a + for _ ∈ 2:n + S = a * S + Δ * P + P = P * a + end + return S +end + +""" + intpow_pushforward(p, n, Ω, ṗ) + +Return the pushforward of `p ↦ pⁿ` at the `Quaternion` `p` (with floating-point components), +where `Ω = pⁿ` as a `Quaternion`, applied to the `Quaternion` tangent `ṗ`. +""" +function intpow_pushforward(p, n::Integer, Ω, ṗ) + n == 0 && return zero(p * ṗ) + if n < 0 + return -(Ω * intpow_pushforward(p, -n, Ω, ṗ) * Ω) + end + S = ṗ * one(p) + P = p + for _ ∈ 2:n + S = p * S + ṗ * P + P = P * p + end + return S +end + +""" + intpow_rule(q, n) + +Return the primal and the pullback of `q^n` for an integer `n` and a quaternion `q` that is +not a `Rotor`. A `QuatVec` is raised to the power as `quaternion(q)`. +""" +function intpow_rule(q::AQ, n::Integer) + Ω = q^n + p = float(quaternion(q)) + Ωq = quaternion(Ω) + proj = ProjectTo(q) + function intpow_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, NoTangent()) + return NoTangent(), proj(intpow_pullback(p, n, Ωq, Δ)), NoTangent() + end + return Ω, intpow_back +end + +""" + intpow_frule(q̇, q, n) + +Return the primal and the tangent of `q^n` for an integer `n` and a quaternion `q` that is +not a `Rotor`. +""" +function intpow_frule(q̇, q::AQ, n::Integer) + Ω = q^n + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + ṗ = pushtangent(q, Δ) + return Ω, ProjectTo(Ω)(intpow_pushforward(float(quaternion(q)), n, quaternion(Ω), ṗ)) +end + +# The source raises a real `Rotor` to an integer power by repeated normalized products, +# except that R⁰ = 1, R¹ = R, and R⁻¹ = conj(R) are not normalized. Because |ab| = |a||b|, +# the result for |n| ≥ 2 is normalize(R^|n|), conjugated when n < 0. + +""" + rotorintpow_rule(R, n) + +Return the primal and the pullback of `R^n` for a real `Rotor` `R` and an integer `n`. +""" +function rotorintpow_rule(R::Rotor{<:Real}, n::Integer) + Ω = R^n + p = float(quaternion(R)) + m = abs(n) + P = p^m + proj = ProjectTo(R) + function rotorintpow_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, NoTangent()) + Δ′ = n < 0 ? conj(Δ) : Δ + ∂ = if m == 0 + zero(p * Δ) + elseif m == 1 + Δ′ * one(p) + else + intpow_pullback(p, m, P, normalize_pullback(P, Δ′)) + end + return NoTangent(), proj(∂), NoTangent() + end + return Ω, rotorintpow_back +end + +""" + rotorintpow_frule(Ṙ, R, n) + +Return the primal and the tangent of `R^n` for a real `Rotor` `R` and an integer `n`. +""" +function rotorintpow_frule(Ṙ, R::Rotor{<:Real}, n::Integer) + Ω = R^n + Δ = cot(Ṙ) + Δ isa AbstractZero && return Ω, Δ + p = float(quaternion(R)) + ṗ = pushtangent(R, Δ) + m = abs(n) + Ω̇ = if m == 0 + zero(p * ṗ) + elseif m == 1 + ṗ * one(p) + else + P = p^m + normalize_pushforward(P, intpow_pushforward(p, m, P, ṗ)) + end + return Ω, ProjectTo(Ω)(n < 0 ? conj(Ω̇) : Ω̇) +end + +######################################################################################## +## Real and quaternionic exponents +######################################################################################## + +# For a base with real components that is not a `Rotor` raised to a real power, the source +# computes q^s = exp(s L) with L = log(p) and p = quaternion(q), multiplying s L in that +# order when s is a quaternion. A real base x is promoted to quaternion(x). The pullback +# runs through the pullbacks of exp at s L, of the product s L, and of log at p. + +""" + pow_pullback(p, s, L, Δ) + +Return the cotangents `(∂p, ∂s)` of the base `p` (a `Quaternion` with real components) and +the exponent `s` (a real number or a quaternion) of `p^s = exp(s L)`, where `L = log(p)`, +given the `Quaternion` cotangent `Δ`. +""" +function pow_pullback(p, s, L, Δ) + ∂sL = exp_pullback(q_(s * L), Δ) + ∂s = s isa AQ ? ∂sL * qadjoint(L) : inner(L, ∂sL) + ∂L = qadjoint(q_(s)) * ∂sL + return log_pullback(p, ∂L), ∂s +end + +""" + pow_pushforward(p, s, L, ṗ, ṡ) + +Return the tangent of `p^s = exp(s L)`, where `L = log(p)`, given the `Quaternion` tangent +`ṗ` of the base and the tangent `ṡ` of the exponent. +""" +function pow_pushforward(p, s, L, ṗ, ṡ) + L̇ = log_pushforward(p, ṗ) + return exp_pushforward(q_(s * L), ṡ * L + s * L̇) +end + +""" + realpow_rule(q, s) + +Return the primal and the pullback of `q^s` for a quaternion base `q` with real components +and a real or quaternionic exponent `s`, or for a real base `q` and a quaternionic `s`. +""" +function realpow_rule(q::Union{Real,RealQ}, s::Union{Real,RealQ}) + Ω = q^s + p = quaternion(float(q)) + L = log(p) + pq, ps = ProjectTo(q), ProjectTo(s) + function pow_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, Δ) + ∂p, ∂s = pow_pullback(p, s, L, Δ) + return NoTangent(), pq(∂p), ps(∂s) + end + return Ω, pow_back +end + +""" + realpow_frule(q̇, ṡ, q, s) + +Return the primal and the tangent of `q^s` for the arguments of `realpow_rule`. +""" +function realpow_frule(q̇, ṡ, q::Union{Real,RealQ}, s::Union{Real,RealQ}) + Ω = q^s + p = quaternion(float(q)) + ṗ = quaternion(pushtangent(q, q̇)) + ṡ′ = pushtangent(s, ṡ) + return Ω, ProjectTo(Ω)(pow_pushforward(p, s, log(p), ṗ, ṡ′)) +end + +# The source computes R^s for a real `Rotor` R and a real s as exp(s V), where V is the +# vector part of log(quaternion(R)), which is homogeneous of degree 0: both its series +# branch near the identity and its general branch agree with this. Exactly on the negative +# real axis (a zero vector part with R[1] ≤ 0), it returns cos(πs) + sin(πs) 𝐤, which does +# not depend on R and whose derivative with respect to s is π𝐤 Ω. + +""" + rotorpowlog(p) + +Return `(V, onaxis)` for the real `Rotor` with components `p` (a `Quaternion`), where `V` is +the vector part of `log(p)` as a `Quaternion`, or π𝐤 when `onaxis` is true, that is, when +`p` lies on the non-positive real axis. +""" +function rotorpowlog(p) + if !(value(p[1]) > 0) && iszerovalue(vec(p)) + z = zero(p[1]) + return quaternion(z, z, z, π * one(z)), true + end + return vecpart(log(p)), false +end + +""" + rotorpow_rule(R, s) + +Return the primal and the pullback of `R^s` for a real `Rotor` `R` and a real number `s`. +""" +function rotorpow_rule(R::Rotor{<:Real}, s::Real) + Ω = R^s + p = float(quaternion(R)) + V, onaxis = rotorpowlog(p) + pR, ps = ProjectTo(R), ProjectTo(s) + function rotorpow_back(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, Δ) + if onaxis + ∂s = inner(V * Ω, Δ) + return NoTangent(), pR(zero(p * ∂s)), ps(∂s) + end + ∂sV = vecpart(exp_pullback(s * V, Δ)) + ∂s = bilinearvec(V, ∂sV) + return NoTangent(), pR(log_pullback(p, s * ∂sV)), ps(∂s) + end + return Ω, rotorpow_back +end + +""" + rotorpow_frule(Ṙ, ṡ, R, s) + +Return the primal and the tangent of `R^s` for a real `Rotor` `R` and a real number `s`. +""" +function rotorpow_frule(Ṙ, ṡ, R::Rotor{<:Real}, s::Real) + Ω = R^s + p = float(quaternion(R)) + V, onaxis = rotorpowlog(p) + ṡ′ = pushtangent(s, ṡ) + Ω̇ = if onaxis + ṡ′ * (V * quaternion(Ω)) + else + V̇ = vecpart(log_pushforward(p, pushtangent(R, Ṙ))) + exp_pushforward(s * V, ṡ′ * V + s * V̇) + end + return Ω, ProjectTo(Ω)(Ω̇) +end + +######################################################################################## +## Method table for `^` and `pow_fast` +######################################################################################## + +# The signatures are chosen so that no two of them, and none of them and the opt-outs in +# `optouts.jl` (`(AQ, Number)`, `(Number, AQ)`, `(AQ, AQ)`, and +# `(Rotor{<:Complex}, Integer)`), are ambiguous, and so that none of them coincides with an +# opt-out, which would delete it. +for f ∈ (:^, :(Base.FastMath.pow_fast)) + @eval begin + rrule(::typeof($f), q::AQ, n::Integer) = intpow_rule(q, n) + rrule(::typeof($f), q::RealQ, n::Integer) = intpow_rule(q, n) + rrule(::typeof($f), R::Rotor{<:Real}, n::Integer) = rotorintpow_rule(R, n) + rrule(::typeof($f), q::RealQ, s::Union{Real,RealQ}) = realpow_rule(q, s) + rrule(::typeof($f), q::RealQ, s::RealQ) = realpow_rule(q, s) + rrule(::typeof($f), R::Rotor{<:Real}, s::Real) = rotorpow_rule(R, s) + rrule(::typeof($f), x::Real, s::RealQ) = realpow_rule(x, s) + + frule((_, q̇, _)::Tuple, ::typeof($f), q::AQ, n::Integer) = intpow_frule(q̇, q, n) + frule((_, q̇, _)::Tuple, ::typeof($f), q::RealQ, n::Integer) = + intpow_frule(q̇, q, n) + frule((_, Ṙ, _)::Tuple, ::typeof($f), R::Rotor{<:Real}, n::Integer) = + rotorintpow_frule(Ṙ, R, n) + frule((_, q̇, ṡ)::Tuple, ::typeof($f), q::RealQ, s::Union{Real,RealQ}) = + realpow_frule(q̇, ṡ, q, s) + frule((_, q̇, ṡ)::Tuple, ::typeof($f), q::RealQ, s::RealQ) = + realpow_frule(q̇, ṡ, q, s) + frule((_, Ṙ, ṡ)::Tuple, ::typeof($f), R::Rotor{<:Real}, s::Real) = + rotorpow_frule(Ṙ, ṡ, R, s) + frule((_, ẋ, ṡ)::Tuple, ::typeof($f), x::Real, s::RealQ) = realpow_frule(ẋ, ṡ, x, s) + end +end + +# `literal_pow(^, q, Val(n))` computes `q^n`, so its rules forward to those of `^`. For a +# complex `Rotor`, the rules of `^` are opted out and return `nothing`, which is then passed +# on. A consumer that treats a returned `nothing` as the absence of a rule then +# differentiates the source. Zygote does not do so by itself, because no `no_rrule` +# matches this signature, so it relies on the `rrule(::ZygoteRuleConfig, literal_pow, ...)` +# method in QuaternionicZygoteExt, which, given a `nothing`, differentiates `q^n` through +# `rrule_via_ad`. + +""" + literalpow_rule(rule) + +Return the primal and pullback of `literal_pow(^, q, Val(n))`, given the result `rule` of +`rrule(^, q, n)`, or `nothing` if `rule` is `nothing`. +""" +literalpow_rule(::Nothing) = nothing +function literalpow_rule((Ω, back)::Tuple) + literalpow_back(ΔΩ) = (NoTangent(), NoTangent(), back(ΔΩ)[2], NoTangent()) + return Ω, literalpow_back +end + +function rrule(::typeof(Base.literal_pow), ::typeof(^), q::AQ, ::Val{n}) where {n} + return literalpow_rule(rrule(^, q, n)) +end +function frule( + (_, _, q̇, _)::Tuple, ::typeof(Base.literal_pow), ::typeof(^), q::AQ, ::Val{n} +) where {n} + return frule((NoTangent(), q̇, NoTangent()), ^, q, n) +end + +######################################################################################## +## csqrt +######################################################################################## + +# `Quaternionic.csqrt(z)` is `sqrt(z)`, through which every complex square root in the +# source passes. Its rule exists for Mooncake, which imports it, because Base's +# `sqrt(::Complex)` reinterprets bits in a way that Mooncake cannot trace. For real +# arguments the AD systems use their own rules for `sqrt`. +function rrule(::typeof(Quaternionic.csqrt), z::Complex) + Ω = Quaternionic.csqrt(z) + proj = ProjectTo(z) + function csqrt_back(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(Δ / conj(2Ω)) + end + return Ω, csqrt_back +end +function frule((_, ż)::Tuple, ::typeof(Quaternionic.csqrt), z::Complex) + Ω = Quaternionic.csqrt(z) + Δ = scalarcot(ż) + Δ isa AbstractZero && return Ω, Δ + return Ω, Δ / (2Ω) +end diff --git a/ext/QuaternionicChainRulesCoreExt/geometry.jl b/ext/QuaternionicChainRulesCoreExt/geometry.jl new file mode 100644 index 00000000..4e1a6e03 --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/geometry.jl @@ -0,0 +1,414 @@ +# Rules for the norms (`abs`, `abs2`, `absvec`, `abs2vec`, and `norm`), for the geometric +# functions (`R(v)`, `angle`, `distance2`, `distance`, and `dot`), and for the LAPACK +# eigenvector computation behind `from_rotation_matrix` and `align`. +# +# Each rule is the exact derivative of what the source computes from the stored components, +# including off the unit sphere for `Rotor`s. In particular, `abs`, `abs2`, and (for real +# components) `norm` of a `Rotor` return the constant 1 without reading the components, so +# their derivatives are zero, whereas `absvec` and `abs2vec` of a `Rotor` read the stored +# vector part. Every branch inside a rule tests values, as the source does, so that dual +# numbers (as in `Zygote.hessian`) take the same branch as the floats they wrap. Each rule +# computes a single gradient quaternion that serves both the pullback and the pushforward, +# so that each formula exists once. +# +# `slerp` needs no rule of its own: it is `(q₂/q₁)^τ q₁`, and the composition of the rules +# for the `Rotor` quotient, for `Rotor^s`, and for the `Rotor` product is exact, including +# at `q₁ == q₂`. + +######################################################################################## +## Norms +######################################################################################## + +# `abs2` is the sum of the squares of the components (the holomorphic spinor norm `Σᵢ zᵢ²` +# for complex components), so its gradient is `2 conjcomponents(q)` in the conventions of +# `projection.jl`. For a `QuatVec`, the scalar slot is zero by construction, and the +# projection discards it anyway. +function rrule(::typeof(abs2), q::AQ) + proj = ProjectTo(q) + function abs2_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(2 * conjcomponents(q) * Δ) + end + return abs2(q), abs2_pullback +end +function frule((_, q̇)::Tuple, ::typeof(abs2), q::AQ) + Ω = abs2(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + Δq = ProjectTo(q)(Δ) + Δq isa AbstractZero && return Ω, Δq + return Ω, 2 * bilinear(q, Δq) +end + +function rrule(::typeof(abs2vec), q::AQ) + proj = ProjectTo(q) + function abs2vec_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(2 * conjcomponents(quatvec(q)) * Δ) + end + return abs2vec(q), abs2vec_pullback +end +function frule((_, q̇)::Tuple, ::typeof(abs2vec), q::AQ) + Ω = abs2vec(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + Δq = ProjectTo(q)(Δ) + Δq isa AbstractZero && return Ω, Δq + return Ω, 2 * bilinear(quatvec(q), Δq) +end + +""" + hypotfactor(Δ, Ω) + +Return `Δ / conj(Ω)`, the factor by which the conjugated components are multiplied in the +pullback of a norm `Ω` computed by `hypot`, or zero when `Ω` is zero by value. At that +point the norm has a cone-shaped kink, and the zero is a subgradient, as for `hypot`. +""" +function hypotfactor(Δ, Ω) + s = Δ / conj(Ω) + return iszerovalue(Ω) ? zero(s) : s +end + +# `abs` and `absvec` are computed by `hypot` (or by its complex analogue, the principal +# square root of the spinor norm), so their gradients are the conjugated components divided +# by the conjugated norm, with a zero cotangent where the norm vanishes. The real `norm` of +# a quaternion with real components is `abs`. +for (f, part) ∈ ((:abs, :identity), (:absvec, :quatvec), (:norm, :identity)) + @eval begin + function rrule(::typeof($f), q::AQ) + Ω = $f(q) + proj = ProjectTo(q) + function norm_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(conjcomponents($part(q)) * hypotfactor(Δ, Ω)) + end + return Ω, norm_pullback + end + function frule((_, q̇)::Tuple, ::typeof($f), q::AQ) + Ω = $f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + Δq = ProjectTo(q)(Δ) + Δq isa AbstractZero && return Ω, Δq + s = bilinear($part(q), Δq) / Ω + return Ω, iszerovalue(Ω) ? zero(s) : s + end + end +end + +# For complex components, `norm` is instead the real Euclidean norm of the eight real +# numbers that make up the components. It is a real function of complex variables, whose +# ChainRules gradient is `q / Ω` (not conjugated), applied to the real part of the +# cotangent, as for the `norm` of a complex array. This method also covers a complex +# `Rotor`, whose `norm` reads the stored components. +function rrule(::typeof(norm), q::AbstractQuaternion{<:Complex}) + Ω = norm(q) + proj = ProjectTo(q) + function complexnorm_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(quaternion(q) * hypotfactor(real(Δ), Ω)) + end + return Ω, complexnorm_pullback +end +function frule((_, q̇)::Tuple, ::typeof(norm), q::AbstractQuaternion{<:Complex}) + Ω = norm(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + Δq = ProjectTo(q)(Δ) + Δq isa AbstractZero && return Ω, Δq + s = real(inner(q, Δq)) / Ω + return Ω, iszerovalue(Ω) ? zero(s) : s +end + +# `abs` and `abs2` of any `Rotor`, and `norm` of a `Rotor` with real components, return the +# constant 1 without reading the stored components, so their derivatives are zero. +for (f, RT) ∈ ((:abs, :Rotor), (:abs2, :Rotor), (:norm, :(Rotor{<:Real}))) + @eval begin + function rrule(::typeof($f), q::$RT) + rotornorm_pullback(ΔΩ) = (NoTangent(), ZeroTangent()) + return $f(q), rotornorm_pullback + end + frule(::Tuple, ::typeof($f), q::$RT) = $f(q), ZeroTangent() + end +end + +######################################################################################## +## The action of a rotor on a vector +######################################################################################## + +# `R(v)` evaluates the vector part of the sandwich product `R v R̄` by a homogeneous +# quadratic formula, valid for any stored `R`, whatever its norm, and returns it as a +# `QuatVec`. With `Δ⃗` the vector part of the cotangent, the adjoint of `x ↦ a x b` is +# `x ↦ a† x b†`, and quaternion conjugation has a real Jacobian, so +# `∂R = Δ⃗ (v R̄)† + conj((R v)† Δ⃗)` and `∂v = R† Δ⃗ (R̄)†`, where `(R̄)† = conjcomponents(R)`. +function rrule(R::Rotor, v::QuatVec) + Ω = R(v) + projR = ProjectTo(R) + projv = ProjectTo(v) + Rq = quaternion(R) + vq = quaternion(v) + function action_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (Δ, Δ) + Δv = quaternion(false, Δ[2], Δ[3], Δ[4]) + ∂R = Δv * qadjoint(vq * conj(Rq)) + conj(qadjoint(Rq * vq) * Δv) + ∂v = qadjoint(Rq) * Δv * conjcomponents(Rq) + return projR(∂R), projv(∂v) + end + return Ω, action_pullback +end +function frule((Ṙ, v̇)::Tuple, R::Rotor, v::QuatVec) + Ω = R(v) + ΔR = cot(Ṙ) + Δv = cot(v̇) + ΔR isa AbstractZero && Δv isa AbstractZero && return Ω, ZeroTangent() + Rq = quaternion(R) + vq = quaternion(v) + ΔRq = ΔR isa AbstractZero ? zero(Rq) : ProjectTo(R)(ΔR) + Δvq = Δv isa AbstractZero ? zero(vq) : quaternion(false, Δv[2], Δv[3], Δv[4]) + Ω̇ = ΔRq * vq * conj(Rq) + Rq * Δvq * conj(Rq) + Rq * vq * conj(ΔRq) + return Ω, ProjectTo(Ω)(Ω̇) +end + +######################################################################################## +## Angle +######################################################################################## + +""" + angle_gradient(q) + +Return the gradient, as a `Quaternion`, of `angle(q) = 2atan(a, w)` with respect to the +components of the real quaternion `q`, where `w = q[1]` and `a = absvec(q)`. This is +`(2/n²) (-a, (w/a) v⃗)`, with `n = abs(quaternion(q))` and `v⃗` the vector part of `q`. +Where the vector part vanishes (by value), the source returns a constant, so the gradient +is zero there. +""" +function angle_gradient(q::AbstractQuaternion{<:Real}) + w = q[1] + zerovec = iszerovalue(vec(q)) + a₀ = absvec(q) + a = zerovec ? one(a₀) : a₀ + n = abs(quaternion(q)) + c = 2 / n + wa = (w / n) * c / a + g = quaternion(-(a / n) * c, wa * q[2], wa * q[3], wa * q[4]) + return zerovec ? zero(g) : g +end + +for f ∈ (:angle, :(Base.FastMath.angle_fast)) + @eval begin + function rrule(::typeof($f), q::Union{Quaternion{<:Real},Rotor{<:Real}}) + proj = ProjectTo(q) + function angle_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(angle_gradient(q) * Δ) + end + return $f(q), angle_pullback + end + function frule((_, q̇)::Tuple, ::typeof($f), q::Union{Quaternion{<:Real},Rotor{<:Real}}) + Ω = $f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + Δq = ProjectTo(q)(Δ) + Δq isa AbstractZero && return Ω, Δq + return Ω, bilinear(angle_gradient(q), Δq) + end + end +end + +######################################################################################## +## Distances between rotors +######################################################################################## + +# The source computes `distance2(R₁, R₂)` from the normalized quotient `Q = R₁ / R₂`, which +# is `R₁ R̄₂ / abs(R₁ R̄₂)`, since the source divides by `abs2(::Rotor) ≡ 1`. The function of +# `Q` that it evaluates is homogeneous of degree zero, as is its choice of branch (up to +# rounding), so it is the same function of the raw product `P = R₁ R̄₂`, and the rules +# differentiate it there, without the normalization. + +""" + distance2_gradient(P) + +Return the gradient, as a `Quaternion`, of the function that `distance2(R₁, R₂)` evaluates +on the quotient `R₁ / R₂`, evaluated at the real quaternion `P`, which may be any positive +multiple of that quotient. The source evaluates `atan(a, abs(w))^2`, with `w = P[1]` and +`a = absvec(P)`, except where `a²` is small compared with `w²` (by value), where it +evaluates the series `x * evalpoly(x, (1, -2//3, 23//45, -44//105))` in `x = a²/w²`. This +function differentiates whichever of the two the source evaluates. The series branch +includes the point `a = 0`, where the gradient is zero and the function is smooth. +""" +function distance2_gradient(P::Quaternion{<:Real}) + w = P[1] + v² = abs2vec(P) + w² = w^2 + # These are the threshold and the comparison of the source, applied to the values. + w₀ = value(w) + T = w₀ isa AbstractFloat ? typeof(w₀) : Float64 + small = value(v²) ≤ (sqrt(sqrt(eps(T))) / 2) * value(w²) + if small === true + x = v² / w² + # The derivative of the series with respect to `x`, and the chain rule through + # `x = a²/w²`, for which `∂x/∂w = -2x/w` and `∂x/∂v⃗ = 2v⃗/w²`. + dfdx = evalpoly(x, (1, -4//3, 23//15, -176//105)) + c = 2dfdx / w² + return quaternion(-2dfdx * x / w, c * P[2], c * P[3], c * P[4]) + else + a = absvec(P) + aw = abs(w) + n = abs(P) + θ = atan(a, aw) + c = 2θ / n + ca = (aw / n) * c / a + return quaternion(-sign(w) * (a / n) * c, ca * P[2], ca * P[3], ca * P[4]) + end +end + +""" + rotorquotient_pullback(R₁, R₂, ∂P) + +Return the cotangents of the quaternions `R₁` and `R₂` in the raw product +`P = R₁ * conj(R₂)` of their stored components, given the cotangent `∂P` of `P`, for real +components. +""" +function rotorquotient_pullback(R₁::AbstractQuaternion, R₂::AbstractQuaternion, ∂P) + return ∂P * quaternion(R₂), conj(∂P) * quaternion(R₁) +end + +""" + rotorquotient_pushforward(R₁, R₂, Ṙ₁, Ṙ₂) + +Return the tangent of the raw product `P = R₁ * conj(R₂)` of the stored components of the +rotors `R₁` and `R₂`, given their tangents `Ṙ₁` and `Ṙ₂`, either of which may be an +`AbstractZero`, or `ZeroTangent()` if both are. +""" +function rotorquotient_pushforward(R₁::Rotor, R₂::Rotor, Ṙ₁, Ṙ₂) + Δ₁ = cot(Ṙ₁) + Δ₂ = cot(Ṙ₂) + Δ₁ isa AbstractZero && Δ₂ isa AbstractZero && return ZeroTangent() + q₁ = quaternion(R₁) + q₂ = quaternion(R₂) + Δ₁q = Δ₁ isa AbstractZero ? zero(q₁) : ProjectTo(R₁)(Δ₁) + Δ₂q = Δ₂ isa AbstractZero ? zero(q₂) : ProjectTo(R₂)(Δ₂) + return Δ₁q * conj(q₂) + q₁ * conj(Δ₂q) +end + +function rrule(::typeof(distance2), R₁::Rotor{<:Real}, R₂::Rotor{<:Real}) + Ω = distance2(R₁, R₂) + p₁, p₂ = ProjectTo(R₁), ProjectTo(R₂) + function distance2_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, Δ) + P = quaternion(R₁) * conj(quaternion(R₂)) + ∂₁, ∂₂ = rotorquotient_pullback(R₁, R₂, distance2_gradient(P) * real(Δ)) + return NoTangent(), p₁(∂₁), p₂(∂₂) + end + return Ω, distance2_pullback +end +function frule((_, Ṙ₁, Ṙ₂)::Tuple, ::typeof(distance2), R₁::Rotor{<:Real}, R₂::Rotor{<:Real}) + Ω = distance2(R₁, R₂) + Ṗ = rotorquotient_pushforward(R₁, R₂, Ṙ₁, Ṙ₂) + Ṗ isa AbstractZero && return Ω, Ṗ + P = quaternion(R₁) * conj(quaternion(R₂)) + return Ω, distance2_gradient(P) ⋅ Ṗ +end + +# `distance(R₁, R₂)` is `√distance2(R₁, R₂)`. Where it vanishes (by value), as at +# `R₁ == R₂`, it has a cone-shaped kink, and the cotangent is zero, rather than the `0 · ∞` +# that the chain rule through `√` would give. +function rrule(::typeof(distance), R₁::Rotor{<:Real}, R₂::Rotor{<:Real}) + Ω = distance(R₁, R₂) + p₁, p₂ = ProjectTo(R₁), ProjectTo(R₂) + function distance_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, Δ) + P = quaternion(R₁) * conj(quaternion(R₂)) + ∂₁, ∂₂ = rotorquotient_pullback(R₁, R₂, distance2_gradient(P) * hypotfactor(real(Δ), 2Ω)) + return NoTangent(), p₁(∂₁), p₂(∂₂) + end + return Ω, distance_pullback +end +function frule((_, Ṙ₁, Ṙ₂)::Tuple, ::typeof(distance), R₁::Rotor{<:Real}, R₂::Rotor{<:Real}) + Ω = distance(R₁, R₂) + Ṗ = rotorquotient_pushforward(R₁, R₂, Ṙ₁, Ṙ₂) + Ṗ isa AbstractZero && return Ω, Ṗ + P = quaternion(R₁) * conj(quaternion(R₂)) + return Ω, hypotfactor(distance2_gradient(P) ⋅ Ṗ, 2Ω) +end + +######################################################################################## +## The componentwise dot product +######################################################################################## + +# `p ⋅ q` is the bilinear sum `Σᵢ pᵢ qᵢ` of the components (without complex conjugation), so +# its partial derivatives are `qᵢ` and `pᵢ`, and the pullback multiplies the conjugated +# components by the cotangent. +function rrule(::typeof(dot), p::AQ, q::AQ) + projp, projq = ProjectTo(p), ProjectTo(q) + function dot_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, Δ) + return NoTangent(), projp(conjcomponents(q) * Δ), projq(conjcomponents(p) * Δ) + end + return dot(p, q), dot_pullback +end +function frule((_, ṗ, q̇)::Tuple, ::typeof(dot), p::AQ, q::AQ) + Ω = dot(p, q) + Δp = cot(ṗ) + Δq = cot(q̇) + Δp isa AbstractZero && Δq isa AbstractZero && return Ω, ZeroTangent() + Δpq = Δp isa AbstractZero ? zero(quaternion(p)) : ProjectTo(p)(Δp) + Δqq = Δq isa AbstractZero ? zero(quaternion(q)) : ProjectTo(q)(Δq) + return Ω, bilinear(Δpq, q) + bilinear(p, Δqq) +end + +######################################################################################## +## The dominant eigenvector of a symmetric matrix, computed by LAPACK +######################################################################################## + +# `Quaternionic.dominant_eigenvector_lapack(A, uplo)` is the only place where +# `from_rotation_matrix` and `align` call LAPACK, and backends cannot differentiate LAPACK. +# The derivative formulas are plain functions in `src/conversion.jl`, shared with the +# Enzyme extension, and they read only the triangle of `A` (or of its tangent) named by +# `uplo`. The pullback returns a dense matrix that is zero in the other triangle. +function rrule( + ::typeof(Quaternionic.dominant_eigenvector_lapack), A::Matrix{<:Union{Float32,Float64}}, + uplo::Char +) + v = Quaternionic.dominant_eigenvector_lapack(A, uplo) + proj = ProjectTo(A) + function dominant_eigenvector_pullback(Δv) + v̄ = unthunk(Δv) + v̄ isa Union{Nothing,AbstractZero} && return (NoTangent(), ZeroTangent(), NoTangent()) + Ā = Quaternionic.dominant_eigenvector_pullback(A, uplo, v, collect(v̄)) + return NoTangent(), proj(Ā), NoTangent() + end + return v, dominant_eigenvector_pullback +end +function frule( + (_, ΔA, _)::Tuple, ::typeof(Quaternionic.dominant_eigenvector_lapack), + A::Matrix{<:Union{Float32,Float64}}, uplo::Char +) + v = Quaternionic.dominant_eigenvector_lapack(A, uplo) + Ȧ = unthunk(ΔA) + Ȧ isa Union{Nothing,AbstractZero} && return v, ZeroTangent() + return v, Quaternionic.dominant_eigenvector_pushforward(A, uplo, v, collect(Ȧ)) +end + +# `Quaternionic.value` strips the derivative parts of a (possibly nested) dual number, and +# the source uses its result only in branch decisions, in thresholds, and as the starting +# point of the Newton refinement in `refined_dominant_eigenvector`, whose derivatives the +# Newton steps supply. Declaring it non-differentiable keeps Zygote from differentiating +# the fields of a dual number, which it cannot do, so that `Zygote.hessian` (ForwardDiff +# over Zygote) works through `from_rotation_matrix` and `align`. The rules are written out, +# rather than generated by `@non_differentiable`, because the `frule` generated by +# ChainRulesCore 1.15 is ambiguous with its own `frule(::RuleConfig, args...)`. +function rrule(::typeof(Quaternionic.value), x) + value_pullback(ΔΩ) = (NoTangent(), NoTangent()) + return Quaternionic.value(x), value_pullback +end +frule(::Tuple, ::typeof(Quaternionic.value), x) = Quaternionic.value(x), NoTangent() diff --git a/ext/QuaternionicChainRulesCoreExt/helpers.jl b/ext/QuaternionicChainRulesCoreExt/helpers.jl new file mode 100644 index 00000000..9eb95b6e --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/helpers.jl @@ -0,0 +1,211 @@ +# Helpers shared by every rule file of `QuaternionicChainRulesCoreExt`. +# +# This is the fixed helper API of the AD specification (section 8). The rule files +# (`arithmetic.jl`, `optouts.jl`, `elementary.jl`, and `geometry.jl`) may rely on exactly +# these names: +# +# AQ, RealQ aliases for `AbstractQuaternion` and `AbstractQuaternion{<:Real}` +# cot(Δ) normalize a cotangent (or tangent) of a quaternion-valued +# output to a `Quaternion`, or to `ZeroTangent()` +# scalarcot(Δ) the same for a scalar-valued output +# q_(x) `quaternion(x)` for a quaternion, the identity for a number +# conjcomponents(q) the `Quaternion` with every component complex-conjugated +# qadjoint(q) `conj(conjcomponents(q))`, the adjoint of multiplication by `q` +# inner(a, b) the Hermitian inner product `Σᵢ conj(aᵢ) bᵢ` of the components +# bilinear(a, b) the bilinear product `Σᵢ aᵢ bᵢ` of the components (an addition +# to the fixed API, for pushforwards with complex components) +# zerofill(x) `false` for `nothing` or an `AbstractZero`, otherwise `x` +# componentcot(i, Δ) the quaternion whose only nonzero component is `Δ`, at index `i` +# normalize_pullback(a, Δ) the pullback of `a ↦ a / abs(a)` at `a` +# normalize_pushforward(a, ȧ) the pushforward of `a ↦ a / abs(a)` at `a` +# projectargs(args, Δs) project each cotangent in `Δs` onto its argument in `args` +# +# The name `q_` is kept as the specification gives it; it has no leading underscore. Other +# internal functions of Quaternionic should be referred to by qualified name, as in +# `Quaternionic.csqrt`, rather than added to the imports of the module file. The module file +# also makes available `LinearAlgebra`, `dot`, `norm`, `normalize`, `SVector`, `basetype`, +# `value`, and `iszerovalue`, together with everything that ChainRulesCore exports. + +const AQ = AbstractQuaternion +const RealQ = AbstractQuaternion{<:Real} + +""" + cot(Δ) + +Normalize a cotangent (or a tangent) that a backend may pass for a quaternion-valued output +into a `Quaternion`, or into `ZeroTangent()` when it is zero. + +Thunks are unthunked; `nothing` and every `AbstractZero` become `ZeroTangent()`; a quaternion +of any type (including a stray `Rotor` or `QuatVec`) is converted to a `Quaternion` without +being renormalized; a real or complex number becomes the quaternion with only that scalar +part; a `Tangent`, a `NamedTuple` with the single field `components` or `data`, a `Tuple`, or +an `AbstractVector` of length 4 is unpacked recursively, with `nothing` and `AbstractZero` +entries treated as zeros. +""" +cot(Δ::AbstractThunk) = cot(unthunk(Δ)) +cot(::Union{Nothing,AbstractZero}) = ZeroTangent() +cot(Δ::AbstractQuaternion) = quaternion(Δ) +cot(Δ::Union{Real,Complex}) = quaternion(Δ) +cot(Δ::Tangent) = cot(ChainRulesCore.backing(Δ)) +cot(Δ::NamedTuple{(:components,)}) = cot(Δ.components) +cot(Δ::NamedTuple{(:data,)}) = cot(Δ.data) +function cot(Δ::Tuple) + length(Δ) == 4 || + throw(DimensionMismatch("A quaternion cotangent must have 4 components, not $(length(Δ))")) + return cotcomponents(Δ[1], Δ[2], Δ[3], Δ[4]) +end +function cot(Δ::AbstractVector) + length(Δ) == 4 || + throw(DimensionMismatch("A quaternion cotangent must have 4 components, not $(length(Δ))")) + return cotcomponents(Δ[begin], Δ[begin+1], Δ[begin+2], Δ[begin+3]) +end + +""" + cotcomponents(a, b, c, d) + +Return the `Quaternion` with components `a`, `b`, `c`, and `d`, each of which may be a +thunk, `nothing`, or an `AbstractZero`, or `ZeroTangent()` when all four are zero. This is +the worker of `cot` for tuples and vectors. +""" +function cotcomponents(a, b, c, d) + a, b, c, d = unthunk(a), unthunk(b), unthunk(c), unthunk(d) + if all(x -> x isa Union{Nothing,AbstractZero}, (a, b, c, d)) + return ZeroTangent() + end + return quaternion(zerofill(a), zerofill(b), zerofill(c), zerofill(d)) +end + +""" + scalarcot(Δ) + +Normalize a cotangent that a backend may pass for a scalar-valued output: thunks are +unthunked, `nothing` becomes `ZeroTangent()`, and a `Tangent` of a `Complex` becomes the +`Complex` number. +""" +scalarcot(Δ) = Δ +scalarcot(Δ::AbstractThunk) = scalarcot(unthunk(Δ)) +scalarcot(::Union{Nothing,AbstractZero}) = ZeroTangent() +scalarcot(Δ::Tangent{<:Complex}) = Complex(zerofill(Δ.re), zerofill(Δ.im)) + +""" + q_(x) + +Return `quaternion(x)` for a quaternion `x` of any type, and `x` itself for any other number. +""" +q_(x::AbstractQuaternion) = quaternion(x) +q_(x::Number) = x + +""" + conjcomponents(q) + +Return `q` as a `Quaternion` with each component complex-conjugated. This is merely +`quaternion(q)` for real components. For a number `x`, return `conj(x)`. +""" +conjcomponents(q::AbstractQuaternion{<:Real}) = quaternion(q) +conjcomponents(q::AbstractQuaternion) = quaternion(conj(q[1]), conj(q[2]), conj(q[3]), conj(q[4])) +conjcomponents(x::Number) = conj(x) + +""" + qadjoint(q) + +Return the quaternion `a` such that multiplication on the left by `a` is the adjoint +(conjugate transpose, as a map on ℝ⁴ or ℂ⁴) of multiplication on the left by `q`; the same +holds for multiplication on the right. This is `conj(conjcomponents(q))`, which is just +`conj(q)` for real components. For a number `x`, return `conj(x)`. +""" +qadjoint(q::AbstractQuaternion) = conj(conjcomponents(q)) +qadjoint(x::Number) = conj(x) + +""" + inner(a, b) + +Return the Hermitian inner product `Σᵢ conj(aᵢ) bᵢ` of the components of `a` and `b`. A +number that is not a quaternion is treated as a quaternion with only a scalar part. For +real components, this is the same as `a ⋅ b`. +""" +inner(a::AbstractQuaternion, b::AbstractQuaternion) = + conj(a[1]) * b[1] + conj(a[2]) * b[2] + conj(a[3]) * b[3] + conj(a[4]) * b[4] +inner(a::AbstractQuaternion, b::Number) = conj(a[1]) * b +inner(a::Number, b::AbstractQuaternion) = conj(a) * b[1] +inner(a::Number, b::Number) = conj(a) * b + +""" + bilinear(a, b) + +Return the bilinear product `Σᵢ aᵢ bᵢ` of the components of `a` and `b`, without complex +conjugation. A number that is not a quaternion is treated as a quaternion with only a +scalar part. For real components, this is the same as `inner(a, b)` and `a ⋅ b`. +""" +bilinear(a::AbstractQuaternion, b::AbstractQuaternion) = + a[1] * b[1] + a[2] * b[2] + a[3] * b[3] + a[4] * b[4] +bilinear(a::AbstractQuaternion, b::Number) = a[1] * b +bilinear(a::Number, b::AbstractQuaternion) = a * b[1] +bilinear(a::Number, b::Number) = a * b + +""" + zerofill(x) + +Return `false` (a strong zero) when `x` is `nothing` or an `AbstractZero`, the unthunked +value when `x` is a thunk, and `x` itself otherwise. +""" +zerofill(x) = x +zerofill(::Union{Nothing,AbstractZero}) = false +zerofill(x::AbstractThunk) = zerofill(unthunk(x)) + +""" + componentcot(i, Δ) + +Return the `Quaternion` whose `i`th component is `Δ` and whose other components are zero. +An `AbstractZero` is returned unchanged. +""" +function componentcot(i::Integer, Δ) + z = zero(Δ) + return quaternion( + ifelse(i == 1, Δ, z), ifelse(i == 2, Δ, z), ifelse(i == 3, Δ, z), ifelse(i == 4, Δ, z) + ) +end +componentcot(::Integer, Δ::AbstractZero) = Δ + +""" + normalize_pullback(a, Δ) + +Return the pullback of the normalization `a ↦ a / abs(a)` at the quaternion `a`, applied to +the cotangent `Δ`, as a `Quaternion`. With `n = abs(quaternion(a))` (computed by `hypot`, so +that it neither overflows nor underflows where the primal does not) and `â = a / n`, this is +`(Δ - conjcomponents(â) * inner(â, Δ)) / conj(n)`. For complex components, `n` is the +holomorphic square root of the spinor norm, as in the source, so this is the conjugate +transpose of the complex Jacobian. An `AbstractZero` cotangent is returned unchanged. +""" +function normalize_pullback(a::AbstractQuaternion, Δ) + Δq = cot(Δ) + Δq isa AbstractZero && return Δq + aq = quaternion(a) + n = abs(aq) + â = aq / n + return (Δq - conjcomponents(â) * inner(â, Δq)) / conj(n) +end + +""" + normalize_pushforward(a, ȧ) + +Return the pushforward of the normalization `a ↦ a / abs(a)` at the quaternion `a`, applied +to the tangent `ȧ`, as a `Quaternion`. With `n` and `â` as in `normalize_pullback`, +this is `(ȧ - â * bilinear(â, ȧ)) / n`. An `AbstractZero` tangent is returned unchanged. +""" +function normalize_pushforward(a::AbstractQuaternion, ȧ) + ȧq = cot(ȧ) + ȧq isa AbstractZero && return ȧq + aq = quaternion(a) + n = abs(aq) + â = aq / n + return (ȧq - â * bilinear(â, ȧq)) / n +end + +""" + projectargs(args, Δs) + +Project each cotangent in the tuple `Δs` with `ProjectTo` of the corresponding argument in +the tuple `args`, leaving every `AbstractZero` unchanged. +""" +projectargs(args::Tuple, Δs::Tuple) = + map((a, d) -> d isa AbstractZero ? d : ProjectTo(a)(d), args, Δs) diff --git a/ext/QuaternionicChainRulesCoreExt/optouts.jl b/ext/QuaternionicChainRulesCoreExt/optouts.jl new file mode 100644 index 00000000..06f11a2f --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/optouts.jl @@ -0,0 +1,87 @@ +# Opt-outs of ChainRules' generic `Number` rules (section 2 of the AD specification). +# +# `AbstractQuaternion <: Number`, so the scalar rules of ChainRules (and the rules that +# ChainRulesCore's `@scalar_rule` generates) apply to quaternion arguments, and they assume +# that multiplication commutes. Where this extension supplies no rule of its own, the +# opt-outs below make the AD system differentiate the package's source instead. +# +# These opt-outs live in a file of their own because `@opt_out rrule(sig)` defines both +# `no_rrule(sig)` and `rrule(sig) = nothing`. An opt-out with exactly the signature of a +# rule supplied in another file would therefore silently delete that rule, so each signature +# here must differ from every supplied one. An opt-out that is broader than a supplied rule +# (such as `log(::AbstractQuaternion)` here and `log(::Quaternion{<:Real})` in +# `elementary.jl`) coexists with it: dispatch selects the narrower rule, and the AD system +# skips a rule only when the selected `rrule` and `no_rrule` methods have the same signature. +# +# The `frule` opt-outs take `::Tuple` tangents, like the supplied `frule`s; with `::Any`, +# they would be ambiguous with them. + +# The real-component rules for `log` and `sqrt` are in `elementary.jl`. These catch +# complex components (where the generic rule has a relative error of 2.3 for `log`) and any +# other element type. +for f ∈ (:log, :sqrt, :(Base.FastMath.log_fast), :(Base.FastMath.sqrt_fast)) + @eval @opt_out rrule(::typeof($f), ::AQ) + @eval @opt_out frule(::Tuple, ::typeof($f), ::AQ) +end + +# The rules for real powers (and integer powers of most quaternions) are in `elementary.jl`; +# these catch complex components and complex rotors. +for f ∈ (:^, :(Base.FastMath.pow_fast)) + for (A, B) ∈ ((:AQ, :Number), (:Number, :AQ), (:AQ, :AQ), (:(Rotor{<:Complex}), :Integer)) + @eval @opt_out rrule(::typeof($f), ::$A, ::$B) + @eval @opt_out frule(::Tuple, ::typeof($f), ::$A, ::$B) + end +end + +# The source renormalizes the product or quotient of two rotors, at least one of which has +# complex components, only when the sum of the squared magnitudes of the raw components is +# less than 16 (`Quaternionic.complex_rotor_product`). Tracing the source follows that test +# exactly. Base computes `a \ b` as `adjoint(adjoint(b) / adjoint(a))`, which is such a +# quotient for two rotors, and the `Base.FastMath` versions call the ordinary operators. +for f ∈ (:*, :/, :\, :(Base.FastMath.mul_fast), :(Base.FastMath.div_fast)) + for (A, B) ∈ ((:(Rotor{<:Complex}), :Rotor), (:Rotor, :(Rotor{<:Complex})), + (:(Rotor{<:Complex}), :(Rotor{<:Complex}))) + @eval @opt_out rrule(::typeof($f), ::$A, ::$B) + @eval @opt_out frule(::Tuple, ::typeof($f), ::$A, ::$B) + end +end + +# Base's `sign(x) = x / abs(x)` runs for quaternions, whereas the generic rule uses `im`. +for f ∈ (:sign, :(Base.FastMath.sign_fast)) + @eval @opt_out rrule(::typeof($f), ::AQ) + @eval @opt_out frule(::Tuple, ::typeof($f), ::AQ) +end + +# The angle of a quaternion with complex components is `2absvec(log(q))`; the rules for real +# components are in `geometry.jl`. +for f ∈ (:angle, :(Base.FastMath.angle_fast)) + @eval @opt_out rrule(::typeof($f), ::Union{Quaternion{<:Complex},Rotor{<:Complex}}) + @eval @opt_out frule(::Tuple, ::typeof($f), ::Union{Quaternion{<:Complex},Rotor{<:Complex}}) +end + +# `norm(q, p)` and `LinearAlgebra.norm2(q)` reach Base's `Number` methods, which are not the +# quaternion norm for complex components. The rules for `norm(q)` are in `geometry.jl`. +@opt_out rrule(::typeof(norm), ::AQ, ::Real) +@opt_out frule(::Tuple, ::typeof(norm), ::AQ, ::Real) +@opt_out frule(::Tuple, ::typeof(LinearAlgebra.norm2), ::AQ) + +# Base's `Number` methods of `det`, `logdet`, and `pinv` run for quaternions, but the generic +# rules assume commutativity. +for f ∈ (:(LinearAlgebra.det), :(LinearAlgebra.logdet), :(LinearAlgebra.pinv)) + @eval @opt_out rrule(::typeof($f), ::AQ) + @eval @opt_out frule(::Tuple, ::typeof($f), ::AQ) +end + +# Every pattern of three arguments, each a quaternion or another number, with at least one +# quaternion. `fma` has a `@scalar_rule`, which assumes commutativity. The `frule`s of +# ChainRules for `*` and `+` with three or more arguments project nothing, and the one for `*` +# with three arguments ignores the normalization of rotor products, so these are opted out +# too; their `rrule`s are the folds in `arithmetic.jl`. +for (A, B, C) ∈ Iterators.product(ntuple(i -> (:AQ, :Number), 3)...) + :AQ ∈ (A, B, C) || continue + @eval @opt_out rrule(::typeof(fma), ::$A, ::$B, ::$C) + @eval @opt_out frule(::Tuple, ::typeof(fma), ::$A, ::$B, ::$C) + for f ∈ (:*, :+, :(Base.FastMath.mul_fast), :(Base.FastMath.add_fast)) + @eval @opt_out frule(::Tuple, ::typeof($f), ::$A, ::$B, ::$C, ::Vararg{Number}) + end +end diff --git a/ext/QuaternionicChainRulesCoreExt/projection.jl b/ext/QuaternionicChainRulesCoreExt/projection.jl new file mode 100644 index 00000000..fac1b049 --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/projection.jl @@ -0,0 +1,68 @@ +# Projection of tangents and cotangents onto quaternion arguments. +# +# Conventions: +# +# * The tangent and cotangent of a `Quaternion{T}` or `Rotor{T}` primal is a +# `Quaternion{float(T)}`. A `Rotor`-typed cotangent would be renormalized by `Rotor` +# arithmetic, so it is never produced. +# * The tangent and cotangent of a `QuatVec{T}` primal is a `QuatVec{float(T)}`, whose +# scalar part is zero by construction. +# * A primal with `Bool` components, such as `𝐢`, `𝐣`, and `𝐤`, is not differentiable, and +# its cotangent is `NoTangent()`, as for `ProjectTo(::Bool)`. +# * A primal with integer components has a `Float64` (or other floating-point) cotangent, +# as for `ProjectTo(::Integer)`. +# * A quaternion cotangent that reaches a real or complex primal is reduced to its scalar +# part, projected onto that primal. +# * For complex components, a pullback applies the conjugate transpose of the Jacobian on +# ℂ⁴, as ChainRules prescribes; see `qadjoint`, `inner`, and `conjcomponents` in +# `helpers.jl`. +# +# The methods of `ProjectTo{Quaternion}` and `ProjectTo{QuatVec}` that take a `Tangent` +# exist partly to resolve ambiguities with ChainRulesCore's own methods for `Tangent{<:T}` +# and `Tangent{<:Number}`. + +function ProjectTo(q::AbstractQuaternion) + element = ProjectTo(zero(basetype(q))) + element isa ProjectTo{NoTangent} && return element + if q isa QuatVec + return ProjectTo{QuatVec}(; element=element) + else + return ProjectTo{Quaternion}(; element=element) + end +end + +function (p::ProjectTo{Quaternion})(dx::AbstractQuaternion) + return quaternion(p.element(dx[1]), p.element(dx[2]), p.element(dx[3]), p.element(dx[4])) +end +function (p::ProjectTo{QuatVec})(dx::AbstractQuaternion) + return quatvec(p.element(dx[2]), p.element(dx[3]), p.element(dx[4])) +end + +for P ∈ (:Quaternion, :QuatVec) + @eval begin + (p::ProjectTo{$P})(dx::Number) = p(cot(dx)) + (p::ProjectTo{$P})(dx::Tangent{<:Complex}) = + p(Complex(zerofill(dx.re), zerofill(dx.im))) + function (p::ProjectTo{$P})(dx::Union{Tangent,Tuple,NamedTuple,AbstractVector}) + Δ = cot(dx) + return Δ isa AbstractZero ? Δ : p(Δ) + end + function (p::ProjectTo{$P})(dx::Tangent{<:$P}) + Δ = cot(dx) + return Δ isa AbstractZero ? Δ : p(Δ) + end + function (p::ProjectTo{$P})(dx::Tangent{<:Number}) + Δ = cot(dx) + return Δ isa AbstractZero ? Δ : p(Δ) + end + end +end + +# A quaternion cotangent that reaches a real or complex primal keeps only its scalar part. +# This is not type piracy, because the argument type is ours. The `Complex` method is needed +# by the complex `log`, whose source mixes complex scalars with quaternions. +(p::ProjectTo{<:Union{Real,Complex}})(dx::AbstractQuaternion) = p(dx[1]) +function (p::ProjectTo{<:Union{Real,Complex}})(dx::Tangent{<:AbstractQuaternion}) + Δ = cot(dx) + return Δ isa AbstractZero ? Δ : p(Δ[1]) +end diff --git a/ext/QuaternionicChainRulesCoreExt/structural.jl b/ext/QuaternionicChainRulesCoreExt/structural.jl new file mode 100644 index 00000000..cc417a1c --- /dev/null +++ b/ext/QuaternionicChainRulesCoreExt/structural.jl @@ -0,0 +1,416 @@ +# Rules for structural access (`components`, `getindex`, `real`, `imag`, and `vec`), for the +# constructors, and for the normalizing functions `rotor` and `normalize`. +# +# Each constructor rule is the exact derivative of what the constructor stores. The type +# constructors with an explicit parameter, such as `Rotor{T}(w, x, y, z)`, store their +# arguments without normalizing them; `QuatVec` constructors discard any scalar part, so a +# scalar argument receives a zero cotangent; and `rotor`, `Rotor` without a parameter, and +# `normalize` divide by the norm computed with `hypot`. The structural `q.components` (through +# `getfield`) needs no rule, because its cotangent arrives as a `Tangent` or a `NamedTuple`, +# which `cot` and `ProjectTo` accept. Properties such as `q.w` and `q.im` reach `getindex`. + +######################################################################################## +## Structural access +######################################################################################## + +function rrule(::typeof(components), q::AQ) + proj = ProjectTo(q) + function components_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(Δ) + end + return components(q), components_pullback +end +function frule((_, q̇)::Tuple, ::typeof(components), q::AQ) + Ω = components(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + Δp = ProjectTo(q)(Δ) + Δp isa AbstractZero && return Ω, Δp + return Ω, components(Δp) +end + +function rrule(::typeof(getindex), q::AQ, i::Integer) + proj = ProjectTo(q) + function getindex_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ, NoTangent()) + return NoTangent(), proj(componentcot(i, Δ)), NoTangent() + end + return q[i], getindex_pullback +end +function frule((_, q̇, _)::Tuple, ::typeof(getindex), q::AQ, i::Integer) + Ω = q[i] + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, Δ[i] +end + +# The cotangent of `real(q)` is placed in the scalar component as it is. Taking `real` of +# it would be wrong for complex components, whose scalar part is itself complex. +function rrule(::typeof(real), q::AQ) + proj = ProjectTo(q) + function real_pullback(ΔΩ) + Δ = scalarcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(componentcot(1, Δ)) + end + return real(q), real_pullback +end +function frule((_, q̇)::Tuple, ::typeof(real), q::AQ) + Ω = real(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, Δ[1] +end + +""" + vectorpartcot(Δ) + +Normalize a cotangent that a backend may pass for the three-component view returned by +`imag(q)` or `vec(q)` into the `Quaternion` with zero scalar part and that vector part, or +into `ZeroTangent()`. It accepts a `Tuple` or an `AbstractVector` of length 3, and the +structural `Tangent` (or `NamedTuple`) of a `SubArray`, whose `parent` field holds the +cotangent of all four components. +""" +vectorpartcot(Δ::AbstractThunk) = vectorpartcot(unthunk(Δ)) +vectorpartcot(::Union{Nothing,AbstractZero}) = ZeroTangent() +vectorpartcot(Δ::Tangent) = vectorpartcot(ChainRulesCore.backing(Δ)) +function vectorpartcot(Δ::NamedTuple) + haskey(Δ, :parent) || + throw(ArgumentError("Cannot interpret $(typeof(Δ)) as the cotangent of a vector part")) + P = cot(Δ.parent) + P isa AbstractZero && return P + return quaternion(false, P[2], P[3], P[4]) +end +function vectorpartcot(Δ::Tuple) + length(Δ) == 3 || + throw(DimensionMismatch("A vector-part cotangent must have 3 components, not $(length(Δ))")) + return cotcomponents(nothing, Δ[1], Δ[2], Δ[3]) +end +function vectorpartcot(Δ::AbstractVector) + length(Δ) == 3 || + throw(DimensionMismatch("A vector-part cotangent must have 3 components, not $(length(Δ))")) + return cotcomponents(nothing, Δ[begin], Δ[begin+1], Δ[begin+2]) +end + +for f ∈ (:imag, :vec) + @eval begin + function rrule(::typeof($f), q::AQ) + proj = ProjectTo(q) + function vectorpart_pullback(ΔΩ) + Δ = vectorpartcot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(Δ) + end + return $f(q), vectorpart_pullback + end + function frule((_, q̇)::Tuple, ::typeof($f), q::AQ) + Ω = $f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, vec(Δ) + end + end +end + +######################################################################################## +## Splitting and assembling the components of constructor arguments +######################################################################################## + +""" + splitcot(QT, Δ, Val(N)) + +Split the `Quaternion` cotangent `Δ` of a quaternion of type `QT`, constructed from `N` +numbers, into a tuple of the cotangents of those numbers. Four numbers are the components +`(w, x, y, z)`, three are `(x, y, z)`, and one is `w`. A `QuatVec` discards its scalar +argument, which therefore receives `ZeroTangent()`. +""" +splitcot(::Type, Δ, ::Val{4}) = (Δ[1], Δ[2], Δ[3], Δ[4]) +splitcot(::Type, Δ, ::Val{3}) = (Δ[2], Δ[3], Δ[4]) +splitcot(::Type, Δ, ::Val{1}) = (Δ[1],) +splitcot(::Type{<:QuatVec}, Δ, ::Val{4}) = (ZeroTangent(), Δ[2], Δ[3], Δ[4]) +splitcot(::Type{<:QuatVec}, Δ, ::Val{1}) = (ZeroTangent(),) + +""" + vectorcot(QT, v, Δ) + +Return the cotangent of the vector `v` from which a quaternion of type `QT` was constructed, +given the `Quaternion` cotangent `Δ` of that quaternion, as an array projected onto `v`. A +vector of length 4 holds the components `(w, x, y, z)`, one of length 3 holds `(x, y, z)`, +and one of length 1 holds `w`. The scalar entry of a vector from which a `QuatVec` was +constructed receives a zero. +""" +function vectorcot(::Type{QT}, v::AbstractVector, Δ) where {QT} + Δ isa AbstractZero && return Δ + n = length(v) + z = zero(Δ[1]) + dropscalar = QT <: QuatVec + d = if n == 4 + [dropscalar ? z : Δ[1], Δ[2], Δ[3], Δ[4]] + elseif n == 3 + [Δ[2], Δ[3], Δ[4]] + else + [dropscalar ? z : Δ[1]] + end + # `ProjectTo` of a `StaticArray` does not convert the element type, so the elements are + # projected first. + T = eltype(v) + d′ = isconcretetype(T) && T <: Number ? map(ProjectTo(zero(T)), d) : d + return ProjectTo(v)(d′) +end + +""" + assembletangent(ȧs) + +Return the `Quaternion` tangent of a quaternion constructed from numbers whose tangents are +the entries of the tuple `ȧs`, interpreted as in `splitcot`, or `ZeroTangent()` if every +entry is zero. A tangent may also be an `AbstractVector` of length 1, 3, or 4, for a +quaternion constructed from a vector. +""" +function assembletangent(ȧs::Tuple) + all(x -> unthunk(x) isa Union{Nothing,AbstractZero}, ȧs) && return ZeroTangent() + return assemblecomponents(map(zerofill, ȧs)...) +end +function assembletangent(v̇::AbstractVector) + n = length(v̇) + n ∈ (1, 3, 4) || + throw(DimensionMismatch("A quaternion tangent must have 1, 3, or 4 components, not $n")) + if n == 4 + return assembletangent((v̇[begin], v̇[begin+1], v̇[begin+2], v̇[begin+3])) + elseif n == 3 + return assembletangent((v̇[begin], v̇[begin+1], v̇[begin+2])) + else + return assembletangent((v̇[begin],)) + end +end +assembletangent(v̇::AbstractThunk) = assembletangent(unthunk(v̇)) +assembletangent(::Union{Nothing,AbstractZero}) = ZeroTangent() + +""" + assemblecomponents(w, x, y, z) + assemblecomponents(x, y, z) + assemblecomponents(w) + +Return the `Quaternion` with the given components, missing components being zero, as +`quaternion` does for numbers. +""" +assemblecomponents(w, x, y, z) = quaternion(w, x, y, z) +assemblecomponents(x, y, z) = quaternion(false, x, y, z) +assemblecomponents(w) = quaternion(w, false, false, false) + +######################################################################################## +## Constructors that store their arguments +######################################################################################## + +""" + storing_rule(QT, Ω, args) + +Return the primal `Ω` and the pullback of a constructor of the quaternion type `QT` that +stores the numbers `args` as components (subject only to the `QuatVec` discarding its scalar +part), as the type constructors and `quaternion` and `quatvec` do. +""" +function storing_rule(::Type{QT}, Ω, args::Tuple{Vararg{Number,N}}) where {QT,N} + proj = ProjectTo(Ω) + function constructor_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), map(a -> ZeroTangent(), args)...) + Δp = proj(Δ) + Δp isa AbstractZero && return (NoTangent(), map(a -> Δp, args)...) + return (NoTangent(), projectargs(args, splitcot(QT, Δp, Val(N)))...) + end + return Ω, constructor_pullback +end + +""" + storing_vector_rule(QT, Ω, v) + +Return the primal `Ω` and the pullback of a constructor of the quaternion type `QT` from the +vector `v`, of length 1, 3, or 4, which stores the entries of `v` as components (subject only +to the `QuatVec` discarding its scalar part). +""" +function storing_vector_rule(::Type{QT}, Ω, v::AbstractVector) where {QT} + proj = ProjectTo(Ω) + function constructor_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + Δp = proj(Δ) + Δp isa AbstractZero && return (NoTangent(), Δp) + return NoTangent(), vectorcot(QT, v, Δp) + end + return Ω, constructor_pullback +end + +""" + converting_rule(Ω, q) + +Return the primal `Ω` and the pullback of a constructor that converts the quaternion `q` to +the type of `Ω`, without normalizing it. +""" +function converting_rule(Ω, q::AQ) + projΩ = ProjectTo(Ω) + projq = ProjectTo(q) + function constructor_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + Δp = projΩ(Δ) + Δp isa AbstractZero && return (NoTangent(), Δp) + return NoTangent(), projq(Δp) + end + return Ω, constructor_pullback +end + +for QT ∈ (:Quaternion, :Rotor, :QuatVec) + @eval begin + rrule(::Type{$QT{T}}, args::Vararg{Number,N}) where {T,N} = + storing_rule($QT, $QT{T}(args...), args) + rrule(::Type{$QT{T}}, v::AbstractVector) where {T} = + storing_vector_rule($QT, $QT{T}(v), v) + rrule(::Type{$QT{T}}, q::AQ) where {T} = converting_rule($QT{T}(q), q) + + function frule((_, ȧs...)::Tuple, ::Type{$QT{T}}, args::Vararg{Number,N}) where {T,N} + Ω = $QT{T}(args...) + Δ = assembletangent(ȧs) + Δ isa AbstractZero && return Ω, Δ + return Ω, ProjectTo(Ω)(Δ) + end + function frule((_, v̇)::Tuple, ::Type{$QT{T}}, v::AbstractVector) where {T} + Ω = $QT{T}(v) + Δ = assembletangent(v̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, ProjectTo(Ω)(Δ) + end + function frule((_, q̇)::Tuple, ::Type{$QT{T}}, q::AQ) where {T} + Ω = $QT{T}(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, ProjectTo(Ω)(ProjectTo(q)(Δ)) + end + end +end + +# The lower-case constructors, and the type constructors without a parameter, promote their +# arguments to a common element type and then store them. +for (f, QT) ∈ ((:quaternion, :Quaternion), (:quatvec, :QuatVec)) + @eval begin + rrule(::Union{typeof($f),Type{$QT}}, args::Vararg{Number,N}) where {N} = + storing_rule($QT, $f(args...), args) + rrule(::Union{typeof($f),Type{$QT}}, v::AbstractVector) = storing_vector_rule($QT, $f(v), v) + rrule(::Union{typeof($f),Type{$QT}}, q::AQ) = converting_rule($f(q), q) + + function frule((_, ȧs...)::Tuple, ::Union{typeof($f),Type{$QT}}, args::Vararg{Number,N}) where {N} + Ω = $f(args...) + Δ = assembletangent(ȧs) + Δ isa AbstractZero && return Ω, Δ + return Ω, ProjectTo(Ω)(Δ) + end + function frule((_, v̇)::Tuple, ::Union{typeof($f),Type{$QT}}, v::AbstractVector) + Ω = $f(v) + Δ = assembletangent(v̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, ProjectTo(Ω)(Δ) + end + function frule((_, q̇)::Tuple, ::Union{typeof($f),Type{$QT}}, q::AQ) + Ω = $f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + return Ω, ProjectTo(Ω)(ProjectTo(q)(Δ)) + end + end +end + +######################################################################################## +## Normalizing constructors and `normalize` +######################################################################################## + +# `rotor(w, x, y, z)`, `rotor(x, y, z)`, `rotor(v)`, and `rotor(q)` divide the components by +# `abs` of the quaternion they form; `Rotor(...)` without a type parameter is `rotor(...)`. +# The result of `rotor(w)` with a single number is ±1 (for real `w`), so its derivative is +# zero. + +""" + normalizing_rule(Ω, a, args) + +Return the primal `Ω` and the pullback of a function that normalizes the quaternion `a`, +whose components are formed from the numbers `args` as by `quaternion(args...)`. +""" +function normalizing_rule(Ω, a::AQ, args::Tuple{Vararg{Number,N}}) where {N} + function rotor_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), map(x -> ZeroTangent(), args)...) + return (NoTangent(), projectargs(args, splitcot(Quaternion, normalize_pullback(a, Δ), Val(N)))...) + end + return Ω, rotor_pullback +end + +const RotorConstructor = Union{typeof(rotor),Type{Rotor}} + +function rrule(::RotorConstructor, w::Number, x::Number, y::Number, z::Number) + return normalizing_rule(rotor(w, x, y, z), quaternion(w, x, y, z), (w, x, y, z)) +end +function rrule(::RotorConstructor, x::Number, y::Number, z::Number) + return normalizing_rule(rotor(x, y, z), quaternion(false, x, y, z), (x, y, z)) +end +function rrule(::RotorConstructor, w::Number) + rotor_constant_pullback(ΔΩ) = (NoTangent(), ZeroTangent()) + return rotor(w), rotor_constant_pullback +end +function rrule(::RotorConstructor, v::AbstractVector) + Ω = rotor(v) + a = quaternion(v) + n = length(v) + function rotor_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + # A vector of length 1 gives ±1, as `rotor(w)` does, so its cotangent is zero. + ∂a = n == 1 ? zero(normalize_pullback(a, Δ)) : normalize_pullback(a, Δ) + return NoTangent(), vectorcot(Quaternion, v, ∂a) + end + return Ω, rotor_pullback +end + +# `rotor(q)`, `Rotor(q)`, and `normalize(q)` (which is `q / abs(q)`, or `rotor(q)` for a +# `Rotor`) share the normalization pullback. +for F ∈ (:RotorConstructor, :(typeof(normalize))) + @eval function rrule(f::$F, q::AQ) + Ω = f(q) + proj = ProjectTo(q) + function normalize_q_pullback(ΔΩ) + Δ = cot(ΔΩ) + Δ isa AbstractZero && return (NoTangent(), Δ) + return NoTangent(), proj(normalize_pullback(q, Δ)) + end + return Ω, normalize_q_pullback + end + @eval function frule((_, q̇)::Tuple, f::$F, q::AQ) + Ω = f(q) + Δ = cot(q̇) + Δ isa AbstractZero && return Ω, Δ + Δq = ProjectTo(q)(Δ) + Δq isa AbstractZero && return Ω, Δq + return Ω, ProjectTo(Ω)(normalize_pushforward(q, Δq)) + end +end + +function frule((_, ẇ, ẋ, ẏ, ż)::Tuple, ::RotorConstructor, w::Number, x::Number, y::Number, z::Number) + Ω = rotor(w, x, y, z) + ȧ = assembletangent(map(zerofill, projectargs((w, x, y, z), (ẇ, ẋ, ẏ, ż)))) + ȧ isa AbstractZero && return Ω, ȧ + return Ω, ProjectTo(Ω)(normalize_pushforward(quaternion(w, x, y, z), ȧ)) +end +function frule((_, ẋ, ẏ, ż)::Tuple, ::RotorConstructor, x::Number, y::Number, z::Number) + Ω = rotor(x, y, z) + ȧ = assembletangent(map(zerofill, projectargs((x, y, z), (ẋ, ẏ, ż)))) + ȧ isa AbstractZero && return Ω, ȧ + return Ω, ProjectTo(Ω)(normalize_pushforward(quaternion(false, x, y, z), ȧ)) +end +frule(::Tuple, ::RotorConstructor, w::Number) = rotor(w), ZeroTangent() +function frule((_, v̇)::Tuple, ::RotorConstructor, v::AbstractVector) + Ω = rotor(v) + ȧ = assembletangent(v̇) + ȧ isa AbstractZero && return Ω, ȧ + Ω̇ = ProjectTo(Ω)(normalize_pushforward(quaternion(v), ȧ)) + # A vector of length 1 gives ±1, as `rotor(w)` does, so its tangent is zero. + return Ω, length(v) == 1 ? zero(Ω̇) : Ω̇ +end diff --git a/ext/QuaternionicChainRulesExt.jl b/ext/QuaternionicChainRulesExt.jl deleted file mode 100644 index 51993d45..00000000 --- a/ext/QuaternionicChainRulesExt.jl +++ /dev/null @@ -1,10 +0,0 @@ -module QuaternionicChainRulesExt - -# using Quaternionic -# import Quaternionic: _sincu, _cossu -# using StaticArrays -# isdefined(Base, :get_extension) ? -# (using ChainRules; import ChainRulesCore: ChainRulesCore, frule, rrule, NoTangent) : -# (using ..ChainRules; import ...ChainRulesCore: ChainRulesCore, frule, rrule, NoTangent) - -end diff --git a/ext/QuaternionicDifferentiationInterfaceExt.jl b/ext/QuaternionicDifferentiationInterfaceExt.jl new file mode 100644 index 00000000..039e22f7 --- /dev/null +++ b/ext/QuaternionicDifferentiationInterfaceExt.jl @@ -0,0 +1,78 @@ +# DifferentiationInterface treats every `Number` as a real or complex scalar. For +# quaternions, that would silently give wrong results in two places, which this extension +# corrects. Both concern only the input and output of the function being differentiated; +# quaternions inside the function are unaffected. +# +# 1. A reverse-mode backend computes `derivative` (or `pushforward`) of a function with a +# scalar output by a single pullback, seeded with `oneunit(y)`. For a quaternion output, +# that gives only the derivative of its scalar part. DifferentiationInterface handles +# `Complex` outputs with a second pullback, seeded with `im`; the method below does the +# same for quaternions, with one pullback for each of the four units (and four more, +# seeded with `im` times the units, for complex components). +# +# 2. DifferentiationInterface builds seeds for arrays (for reverse-mode Jacobians of array +# outputs, and for forward-mode derivatives with respect to array inputs) from `basis(a, +# i)`, which puts `oneunit` of the element type at index `i`. For an array of +# quaternions, those seeds cover only the scalar parts, and the results would silently +# omit the derivatives of (or with respect to) the vector parts. The method below raises +# an error instead. +# +# Both methods extend internal functions of DifferentiationInterface, and the tests check +# that they are still reached. `Test.detect_ambiguities` reports the first method as +# ambiguous with the in-place methods of `_value_and_pushforward_via_pullback`, exactly as +# it does for DifferentiationInterface's own `Number` and `Complex` methods; no call can +# reach those ambiguities, because their first argument would have to be a quaternion and a +# function at once. This extension is loaded only as a package extension; the compatible +# versions of DifferentiationInterface require Julia 1.10 or later. +module QuaternionicDifferentiationInterfaceExt + +import Quaternionic: AbstractQuaternion, Quaternion, QuatVec, basetype +import DifferentiationInterface as DI +import LinearAlgebra: dot + +# The four units `c`, `c𝐢`, `c𝐣`, and `c𝐤`, as quaternions of type `S`. The seeds of the +# pullbacks must have the type of `oneunit(y)`, the seed with which DifferentiationInterface +# prepared them; for a `Rotor` output, that is a `Rotor` (built here without normalization). +function units(::Type{S}, c) where {S<:AbstractQuaternion} + z = zero(c) + (S(c, z, z, z), S(z, c, z, z), S(z, z, c, z), S(z, z, z, c)) +end + +function DI._value_and_pushforward_via_pullback( + y_ex::AbstractQuaternion, + f::F, + pullback_prep::DI.PullbackPrep, + backend::DI.ADTypes.AbstractADType, + x, + tx::NTuple{B}, + contexts::Vararg{DI.Context,C}, +) where {F,B,C} + S = typeof(oneunit(y_ex)) + T = basetype(S) + pullbackof(dy) = only(DI.pullback(f, pullback_prep, backend, x, (dy,), contexts...)) + y = f(x, map(DI.unwrap, contexts)...) + # As with ForwardDiff, the derivative of a `QuatVec` is a `QuatVec`, and the derivative of + # any other quaternion is a `Quaternion`. + D = y_ex isa QuatVec ? QuatVec : Quaternion + a = map(pullbackof, units(S, one(T))) + ty = if T <: Complex + b = map(pullbackof, units(S, im * one(T))) + map(tx) do dx + D(ntuple(k -> complex(real(dot(a[k], dx)), real(dot(b[k], dx))), 4)...) + end + else + map(dx -> D(ntuple(k -> dot(a[k], dx), 4)...), tx) + end + return y, ty +end + +function DI.basis(::AbstractArray{<:AbstractQuaternion}, _) + throw(ArgumentError( + "DifferentiationInterface treats each element of an array as a real or complex " * + "number, so it cannot compute derivatives of (or with respect to) the vector parts " * + "of an array of quaternions. Return (or pass) their components as a real array " * + "instead, for example with `to_float_array` (or `from_float_array`)." + )) +end + +end # module diff --git a/ext/QuaternionicEnzymeExt.jl b/ext/QuaternionicEnzymeExt.jl new file mode 100644 index 00000000..48eb738c --- /dev/null +++ b/ext/QuaternionicEnzymeExt.jl @@ -0,0 +1,313 @@ +# Support for Enzyme. Enzyme differentiates the package's source natively, in forward and +# reverse mode and at higher order: quaternions are immutable `isbits` structs, so they are +# `Active` arguments in reverse mode, and the shadow of a quaternion has the primal's own +# type. (The shadow of a `Rotor` is a `Rotor` holding the raw gradient components, so its +# `abs` reports 1; read such shadows with `components` or `vec`.) So this extension +# imports no ChainRules rules, and it provides only +# +# * `Enzyme.onehot` for quaternion arguments, so that `Enzyme.gradient(Forward, f, q)` +# works when `q` is a quaternion; +# * native rules for `Quaternionic.dominant_eigenvector_lapack`, because Enzyme cannot +# differentiate the LAPACK call inside it, which `from_rotation_matrix` and `align` +# reach (these rules are first-order only, so Enzyme cannot compute second +# derivatives through those two functions); +# * rules that work around a bug in Enzyme's own reverse rule for `hypot` with three or +# more arguments, on `Quaternionic.hypotenuse`, through which `abs` and `absvec` of +# real quaternions call `hypot`. +# +# This file is loaded only as a package extension (Julia 1.9 and later); Requires never +# loads it. +module QuaternionicEnzymeExt + +import Enzyme +import Enzyme: EnzymeRules +using Enzyme: Annotation, Active, Const, Duplicated, BatchDuplicated +using Quaternionic: Quaternionic, AbstractQuaternion, QuatVec +import StaticArrays + + +############################################################################################ +# `Enzyme.onehot` +# +# `Enzyme.gradient(Forward, f, x)` pushes forward one tangent per degree of freedom of `x`, +# and it gets those tangents from `Enzyme.onehot(x)` (or from `Enzyme.chunkedonehot` when a +# `chunk` size is given). A quaternion is a `Number` with no such methods of its own, so +# they are defined here. Each tangent is a quaternion of the same type as the argument +# (Enzyme requires a shadow of the primal's own type), with one component equal to 1 and the +# others 0. A `QuatVec` has only three degrees of freedom, because its scalar part is +# always zero, so it gets three tangents, one for each vector component. The gradient with +# respect to a quaternion argument is then a tuple of four derivatives (three for a +# `QuatVec`), in the order of `components` (or of `vec`). + +# The number of degrees of freedom of `q`, which is the number of tangents `onehot` returns. +ntangents(::AbstractQuaternion) = 4 +ntangents(::QuatVec) = 3 + +# The `i`th tangent that `onehot` returns for `q`: the quaternion of the same type as `q` +# whose `i`th component (`i`th vector component for a `QuatVec`) is 1, and whose others are +# 0. The type's own constructor stores the components as given, so the tangent of a `Rotor` +# is not normalized. +unittangent(q::AbstractQuaternion{T}, i::Int) where {T} = + typeof(q)(ntuple(j -> T(j == i), Val(4))...) +unittangent(q::QuatVec{T}, i::Int) where {T} = + typeof(q)(ntuple(j -> T(j == i + 1), Val(4))...) + +Enzyme.onehot(q::AbstractQuaternion) = ntuple(i -> unittangent(q, i), Val(4)) +Enzyme.onehot(q::QuatVec) = ntuple(i -> unittangent(q, i), Val(3)) +Enzyme.onehot(q::AbstractQuaternion, start::Int, endl::Int) = + ntuple(i -> unittangent(q, start + i - 1), endl - start + 1) + +# Enzyme's generic method counts the degrees of freedom with `length`, which is 1 for any +# `Number`, so the chunks are formed here from `ntangents` instead. +function Enzyme.chunkedonehot(q::AbstractQuaternion, ::Val{chunk}) where {chunk} + n = ntangents(q) + ntuple(k -> Enzyme.onehot(q, (k - 1) * chunk + 1, min(k * chunk, n)), cld(n, chunk)) +end + +# For an array of quaternions, Enzyme's own `onehot` puts `one` of the element type at each +# index, which perturbs only the scalar parts. So `Enzyme.gradient(Forward, f, x)` and +# `Enzyme.jacobian(Forward, f, x)` (and DifferentiationInterface's forward-mode `gradient`) +# would silently omit the derivatives with respect to the vector parts. These methods raise +# an error instead. Reverse mode, and arrays of quaternions inside the function, are +# unaffected. The `Array` and `SArray` methods resolve ambiguities with Enzyme's methods. +for A ∈ (:AbstractArray, :Array, :(StaticArrays.SArray{S,<:AbstractQuaternion} where {S})) + E = A isa Symbol ? :($A{<:AbstractQuaternion}) : A + @eval Enzyme.onehot(::$E) = throw(onehot_array_error()) + @eval Enzyme.onehot(::$E, ::Int, ::Int) = throw(onehot_array_error()) +end +function onehot_array_error() + ArgumentError( + "Forward-mode gradients and Jacobians with respect to an array of quaternions would " * + "perturb only their scalar parts. Pass the components as a real array instead, for " * + "example with `to_float_array` and `from_float_array`, or use reverse mode." + ) +end + + +############################################################################################ +# Rules for `dominant_eigenvector_lapack` +# +# `Quaternionic.dominant_eigenvector_lapack(A, uplo)` is the only place where +# `from_rotation_matrix` and `align` call LAPACK, and Enzyme cannot differentiate LAPACK. +# The derivative formulas are plain functions in `src/conversion.jl`, shared with the +# ChainRulesCore extension; they read only the triangle of `A` (or of its tangent) named by +# `uplo`, and the pullback returns a dense matrix that is zero in the other triangle. The +# rules handle any batch width. +# +# A matrix that is inactive gets a zero tangent and no cotangent. It may arrive as a +# `Const`, but with runtime activity enabled, Enzyme passes a matrix that turns out to be +# inactive at run time as a `Duplicated` (or `BatchDuplicated`) whose shadow is the primal +# matrix itself. Accumulating a cotangent into that shadow would overwrite the caller's +# matrix, so such a shadow is recognized by identity, as in Enzyme's own rules for +# `LinearAlgebra`, and skipped. +# +# These rules are first-order only. Their bodies call LAPACK (through `eigen` and the +# dense solve in `bordered_solve`), which Enzyme cannot differentiate, so Enzyme cannot +# compute second derivatives through `from_rotation_matrix` or `align`; it throws an error +# there. ForwardDiff can, through the value-refined eigenvector in `src`. + +const LAPACKFloat = Union{Float32,Float64} + +# The `k`th of the `N` shadows of the argument `A`. +shadowof(A::Annotation, k, N) = N == 1 ? A.dval : A.dval[k] + +# Whether the `k`th of the `N` shadows of the matrix argument `A` stands for an inactive +# matrix: `A` is a `Const`, or runtime activity is enabled and the shadow is `A` itself. +isinactive(config, ::Const, k, N) = true +isinactive(config, A::Annotation, k, N) = + EnzymeRules.runtime_activity(config) && shadowof(A, k, N) === A.val + +# The tangent of `v` along the `k`th of the `N` shadows of the matrix argument `A`. +function eigenvectortangent(config, A::Annotation, uplo, v, k, N) + isinactive(config, A, k, N) && return zero(v) + Quaternionic.dominant_eigenvector_pushforward(A.val, uplo, v, shadowof(A, k, N)) +end + +function EnzymeRules.forward( + config::EnzymeRules.FwdConfig, + func::Const{typeof(Quaternionic.dominant_eigenvector_lapack)}, + ::Type{RT}, + A::Annotation{Matrix{T}}, + uplo::Const{Char} +) where {RT,T<:LAPACKFloat} + v = func.val(A.val, uplo.val) + N = EnzymeRules.width(config) + if EnzymeRules.needs_shadow(config) + dv = if N == 1 + eigenvectortangent(config, A, uplo.val, v, 1, N) + else + ntuple(k -> eigenvectortangent(config, A, uplo.val, v, k, N), Val(N)) + end + if EnzymeRules.needs_primal(config) + return N == 1 ? Duplicated(v, dv) : BatchDuplicated(v, dv) + else + return dv + end + elseif EnzymeRules.needs_primal(config) + return v + else + return nothing + end +end + +# The forward pass stores copies of `A` and of `v` on the tape, in case the caller +# overwrites either one before the reverse pass, along with the shadow of `v`, into which +# the caller accumulates the cotangent of `v`. +function EnzymeRules.augmented_primal( + config::EnzymeRules.RevConfig, + func::Const{typeof(Quaternionic.dominant_eigenvector_lapack)}, + ::Type{RT}, + A::Annotation{Matrix{T}}, + uplo::Const{Char} +) where {RT,T<:LAPACKFloat} + v = func.val(A.val, uplo.val) + N = EnzymeRules.width(config) + dv = N == 1 ? zero(v) : ntuple(_ -> zero(v), Val(N)) + primal = EnzymeRules.needs_primal(config) ? v : nothing + shadow = EnzymeRules.needs_shadow(config) ? dv : nothing + return EnzymeRules.AugmentedReturn(primal, shadow, (copy(A.val), copy(v), dv)) +end + +# Accumulate the cotangent of `A` into its `k`th shadow, given the `k`th cotangent `v̄` of +# `v`, unless that shadow stands for an inactive matrix, and zero `v̄`, which the forward +# pass allocated. +function accumulate_eigenvector_cotangent!(config, A, k, N, A0, uplo, v, v̄) + if !isinactive(config, A, k, N) + shadowof(A, k, N) .+= Quaternionic.dominant_eigenvector_pullback(A0, uplo, v, v̄) + end + fill!(v̄, 0) + nothing +end + +function EnzymeRules.reverse( + config::EnzymeRules.RevConfig, + func::Const{typeof(Quaternionic.dominant_eigenvector_lapack)}, + ::Type{RT}, + tape, + A::Annotation{Matrix{T}}, + uplo::Const{Char} +) where {RT,T<:LAPACKFloat} + A0, v, dv = tape + N = EnzymeRules.width(config) + for k in 1:N + accumulate_eigenvector_cotangent!(config, A, k, N, A0, uplo.val, v, N == 1 ? dv : dv[k]) + end + return (nothing, nothing) +end + + +############################################################################################ +# Rules for `hypotenuse` +# +# WORKAROUND for two Enzyme bugs, one of which crashes the process +# (EnzymeAD/Enzyme.jl#3775). These rules, and the function `hypotenuse` in +# `src/math.jl`, exist only to avoid those bugs, and should be removed once both are fixed. +# +# For real components, `abs(q)` is `hypotenuse(components(q)...)` and `absvec(q)` is +# `hypotenuse(vec(q)...)`, where `Quaternionic.hypotenuse` is `hypot` of three or four +# numbers, and `rotor` normalizes with `abs`. Enzyme's own reverse rule for `hypot` with +# three or more arguments (`_hypotreverse` in Enzyme's `src/internal_rules/math.jl`, as of +# Enzyme 0.13.211) reads the cotangent as `dret.val[i]` when the batch width is greater than +# 1, but Enzyme passes a tuple of `Active` values there, so it throws `FieldError: type +# Tuple has no field val`. Batched reverse mode, which DifferentiationInterface uses for +# Jacobians, therefore failed for nearly every function that builds a `Rotor`. These rules +# compute the same derivatives as Enzyme's rules for `hypot`: the derivative with respect to +# each argument `x` is `x / h`, with `h` the result, or zero where `h` is zero, and they +# handle any batch width. Forward mode has no such bug, but a function with reverse rules +# needs a forward rule as well, because Enzyme calls it when it differentiates the reverse +# pass in forward mode (forward-over-reverse Hessians). These rules can be removed once +# Enzyme's reverse rule is fixed. +# +# The rules are defined on `hypotenuse`, whose arguments are numbers, rather than on `abs` +# and `absvec`, whose argument is a quaternion. Enzyme (as of 0.13.211) adds the cotangent +# that a reverse rule returns for an `Active` struct argument into the shadow of that +# argument with a vector load and store that claim the alignment of a vector of all the +# components (32 bytes for four `Float64`s), but the shadow is aligned only to 8 bytes. On +# x86_64 processors with AVX, that store crashes the process (with a segmentation fault or +# an access violation) whenever the shadow happens not to be 32-byte aligned. A number is +# passed by value, so its cotangent needs no such store. +# +# The workaround helps only with recent releases of Enzyme (it was verified with 0.13.205 +# and 0.13.209). Older releases of Enzyme 0.13 (at least up to 0.13.85) refuse every custom +# reverse rule with an active result at a batch width greater than 1 ("Not yet supported: +# Enzyme custom rule of batch size ..."), which includes these rules as well as Enzyme's own +# rule for `hypot`, so batched reverse mode through `abs` fails there either way. + +const HypotFloat = Base.IEEEFloat + +# The divisor in the derivatives of `h = hypot(xs...)`, which is `h` itself, or 1 where `h` +# is zero, as in Enzyme's rules for `hypot`. +hypotdivisor(h) = iszero(h) ? one(h) : h + +# The `k`th of the `N` tangents of the argument `x`, which is zero for a constant. +argumenttangent(x::Const, k, N) = zero(x.val) +argumenttangent(x::Annotation, k, N) = N == 1 ? x.dval : x.dval[k] + +# The tangent of `h = hypotenuse(xs...)` along the `k`th of the `N` tangents of the +# arguments `xs`. +hypottangent(xs, h, k, N) = + +(map(x -> x.val * argumenttangent(x, k, N), xs)...) / hypotdivisor(h) + +# The cotangent of the result in reverse mode: a single `Active` value, or a tuple of them +# for a batch width greater than 1, or the type of an inactive result, whose cotangent is +# zero. +resultcotangent(dret::Active, h, k) = dret.val +resultcotangent(dret::Tuple, h, k) = dret[k].val +resultcotangent(::Type, h, k) = zero(h) + +# The cotangent of the argument `x` of `h = hypotenuse(xs...)`, given the cotangent `d` of +# `h` (a tuple of them for a batch width greater than 1): nothing for a constant argument. +argumentcotangent(::Const, h, d) = nothing +argumentcotangent(x::Active, h, d::Number) = x.val * d / hypotdivisor(h) +argumentcotangent(x::Active, h, d::Tuple) = map(dₖ -> argumentcotangent(x, h, dₖ), d) + +# The first argument `x` of each rule is separate from the others, `xs`, only so that the +# type parameter `T` is bound. +function EnzymeRules.forward( + config::EnzymeRules.FwdConfig, func::Const{typeof(Quaternionic.hypotenuse)}, + ::Type{RT}, x::Annotation{T}, xs::Annotation{T}... +) where {RT,T<:HypotFloat} + args = (x, xs...) + h = func.val(map(a -> a.val, args)...) + N = EnzymeRules.width(config) + if EnzymeRules.needs_shadow(config) + dh = if N == 1 + hypottangent(args, h, 1, N) + else + ntuple(k -> hypottangent(args, h, k, N), Val(N)) + end + if EnzymeRules.needs_primal(config) + return N == 1 ? Duplicated(h, dh) : BatchDuplicated(h, dh) + else + return dh + end + elseif EnzymeRules.needs_primal(config) + return h + else + return nothing + end +end + +function EnzymeRules.augmented_primal( + config::EnzymeRules.RevConfig, func::Const{typeof(Quaternionic.hypotenuse)}, + ::Type{RT}, x::Union{Const{T},Active{T}}, xs::Union{Const{T},Active{T}}... +) where {RT,T<:HypotFloat} + h = func.val(x.val, map(a -> a.val, xs)...) + primal = EnzymeRules.needs_primal(config) ? h : nothing + return EnzymeRules.AugmentedReturn(primal, nothing, h) +end + +function EnzymeRules.reverse( + config::EnzymeRules.RevConfig, func::Const{typeof(Quaternionic.hypotenuse)}, dret, h, + x::Union{Const{T},Active{T}}, xs::Union{Const{T},Active{T}}... +) where {T<:HypotFloat} + N = EnzymeRules.width(config) + d = if N == 1 + resultcotangent(dret, h, 1) + else + ntuple(k -> resultcotangent(dret, h, k), Val(N)) + end + return map(a -> argumentcotangent(a, h, d), (x, xs...)) +end + +end # module diff --git a/ext/QuaternionicFastDifferentiationExt.jl b/ext/QuaternionicFastDifferentiationExt.jl index d174ab7b..4fd66cf1 100644 --- a/ext/QuaternionicFastDifferentiationExt.jl +++ b/ext/QuaternionicFastDifferentiationExt.jl @@ -18,9 +18,23 @@ absvec(q::AbstractQuaternion{Node}) = √sum(x->x^2, vec(q)) ### Functions that used to appear in quaternion.jl -quaternion(w::Node) = quaternion(SVector{4}(w, false, false, false)) -rotor(w::Node) = rotor(SVector{4}(one(w), false, false, false)) -quatvec(w::Node) = quatvec(SVector{4,typeof(w)}(false, false, false, false)) +# The other components are filled with `zero(w)` rather than `false`, because `Node(false)` +# prints as `false`. +quaternion(w::Node) = quaternion(SVector{4}(w, zero(w), zero(w), zero(w))) +function rotor(w::Node) + # When `w` is a constant, the components are those of src's `rotor(v)` for that + # constant, so that the result is `±1` for a finite nonzero constant and a NaN rotor for a + # zero, NaN, or infinite constant. The sign of a variable or any other expression is + # unknown, so the identity rotor is returned without symbolic normalization. + v = FastDifferentiation.is_constant(w) ? FastDifferentiation.value(w) : nothing + c = if v isa Real + SVector{4,Node}(components(rotor(v))) + else + SVector{4,Node}(one(w), zero(w), zero(w), zero(w)) + end + Rotor{Node}(c) +end +quatvec(w::Node) = quatvec(SVector{4}(zero(w), zero(w), zero(w), zero(w))) for QT1 ∈ (AbstractQuaternion, Quaternion, QuatVec, Rotor) @eval begin wrapper(::Type{<:$QT1}, ::Val{OP}, ::Type{<:Node}) where {OP} = quaternion @@ -47,22 +61,20 @@ let NT = Node end let T = Node for OP ∈ (Val{+}, Val{-}, Val{*}, Val{/}) - @eval wrapper(::Type{<:Quaternion}, ::$OP, ::Type{<:$T}) = quaternion - if T !== Quaternion - @eval wrapper(::Type{<:$T}, ::$OP, ::Type{<:Quaternion}) = quaternion + @eval begin + wrapper(::Type{<:Quaternion}, ::$OP, ::Type{<:$T}) = quaternion + wrapper(::Type{<:$T}, ::$OP, ::Type{<:Quaternion}) = quaternion end end end Base.promote_rule(::Type{Q}, ::Type{S}) where {Q<:AbstractQuaternion,S<:Node} = wrapper(Q){promote_type(basetype(Q), S)} - - -# # Broadcast-like operations from FastDifferentiation -# # (d::FastDifferentiation.Operator)(q::QT) where {QT<:AbstractQuaternion} = QT(d(q[1]), d(q[2]), d(q[3]), d(q[4])) -# # (d::FastDifferentiation.Operator)(q::QuatVec) = quatvec(d(q[2]), d(q[3]), d(q[4])) -# (d::FastDifferentiation.Differential)(q::Quaternion) = quaternion(d(q[1]), d(q[2]), d(q[3]), d(q[4])) -# (d::FastDifferentiation.Differential)(q::Rotor) = quaternion(d(q[1]), d(q[2]), d(q[3]), d(q[4])) -# (d::FastDifferentiation.Differential)(q::QuatVec) = quatvec(d(q[2]), d(q[3]), d(q[4])) +# As in src/quaternion.jl, a `QuatVec` or a `Rotor` promoted with a scalar becomes a +# `Quaternion`. These methods also resolve ambiguities with the rules in src. +for QT ∈ (QuatVec, Rotor) + @eval Base.promote_rule(::Type{$QT{T}}, ::Type{S}) where {T<:Number,S<:Node} = + Quaternion{promote_type(T, S)} +end ### Functions that used to appear in algebra.jl @@ -88,35 +100,59 @@ let S = Node end end -# Here, we disable FastDifferentiation support for functions that rely on conditionals; -# otherwise, they will fail with errors like +# Here, we disable FastDifferentiation support for functions that cannot yet be used with FD +# variables, so that they raise an explanatory error. There are two obstacles. First, most +# of these functions choose an algorithm with Julia `if` statements that depend on the +# values of the components, which fail for FD variables with errors like # # TypeError: non-boolean (Node) used in boolean context # -# This could be removed once FastDifferentiation supports conditionals, and these functions -# are tested. -for method ∈ ( - :(Quaternionic.to_euler_phases(::AbstractQuaternion{Node})), - :(Quaternionic.from_euler_phases(::Complex{Node}, ::Complex{Node}, ::Complex{Node})), - :(Base.log(::Quaternion{Node})), - :(Base.log(::Rotor{Node})), - :(Base.exp(::Quaternion{Node})), - :(Base.exp(::QuatVec{Node})), - :(Base.sqrt(::Quaternion{Node})), - :(Base.sqrt(::QuatVec{Node})), - :(Base.sqrt(::Rotor{Node})), - :(Base.:^(::Rotor{Node}, ::Number)), - :(Base.:^(::Quaternion{Node}, ::Integer)), - :(Base.:^(::QuatVec{Node}, ::Integer)), - :(Base.:^(::Rotor{Node}, ::Integer)), -) - func = first(split(string(method), '(')) - @eval begin - $(method) = error( - """FastDifferentiation does not yet support conditionals involving FD variables, - which are needed to implement its derivative of `$(func)` involving quaternions. - """ - ) +# FastDifferentiation provides `if_else` for such conditionals, but these functions would +# have to be rewritten to use it. Second, the integer powers do not branch on the +# components, but FastDifferentiation itself returns incorrect Jacobians for some of them +# (such as `q^3`), and throws a `KeyError` for others (such as `rotor(q)^2`). The same +# upstream problem also affects explicit products like `q*q*q`, and expressions involving +# the normalization of a `Rotor`, which are not disabled here. Non-integer powers of a +# `Quaternion` are not listed, because they call `log`, which raises its own error. These +# stubs can be removed once both problems are solved, and these functions are tested. +let conditionals = "it chooses an algorithm with conditionals on the values of the " * + "components, which FastDifferentiation does not support", + upstream = "FastDifferentiation computes incorrect derivatives for some integer powers" + stubs = [ + (:(Quaternionic.to_euler_phases(::AbstractQuaternion{Node})), conditionals), + (:(Base.log(::Quaternion{Node})), conditionals), + (:(Base.log(::Rotor{Node})), conditionals), + (:(Base.exp(::Quaternion{Node})), conditionals), + (:(Base.exp(::QuatVec{Node})), conditionals), + (:(Base.sqrt(::Quaternion{Node})), conditionals), + (:(Base.sqrt(::QuatVec{Node})), conditionals), + (:(Base.sqrt(::Rotor{Node})), conditionals), + # The exponent types are listed separately, rather than as `Number`, to avoid + # ambiguities with Base's `^(::Number, ::Rational)` and with methods in src that + # take a quaternion exponent. + (:(Base.:^(::Rotor{Node}, ::Real)), conditionals), + (:(Base.:^(::Rotor{Node}, ::Rational)), conditionals), + (:(Base.:^(::Rotor{Node}, ::Complex)), conditionals), + (:(Base.:^(::Quaternion{Node}, ::Integer)), upstream), + (:(Base.:^(::QuatVec{Node}, ::Integer)), upstream), + (:(Base.:^(::Rotor{Node}, ::Integer)), upstream), + ] + # `Complex{Node}` is a valid type only when `Node <: Real`, which is true in + # FastDifferentiation 0.4 but not in 0.3. + if Node <: Real + push!(stubs, ( + :(Quaternionic.from_euler_phases(::Complex{Node}, ::Complex{Node}, ::Complex{Node})), + conditionals + )) + end + for (method, reason) ∈ stubs + # The message is built here, outside the quoted expression, so that it is complete + # when the stub is defined. Interpolating `func` inside the string in the quoted + # expression would instead look up a global `func` when the stub is called. + func = first(split(string(method), '(')) + msg = "`$(func)` cannot yet be used with FastDifferentiation variables, because " * + "$(reason)." + @eval $(method) = error($msg) end end @@ -141,11 +177,13 @@ end # this package or not (on Julia 1.8 and higher) r(v) 𝓇(𝓋) - for a ∈ [s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆] + # Tuples, unlike vectors, keep the type of each element, so that mixed operations + # are compiled too. + for a ∈ (s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆) conj(a) - for b ∈ [s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆] + for b ∈ (s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆) a * b - # a / b # TODO: Uncomment when https://github.com/brianguenter/FastDifferentiation.jl/issues/98 is fixed + a / b a + b a - b end diff --git a/ext/QuaternionicForwardDiffExt.jl b/ext/QuaternionicForwardDiffExt.jl index 1c923946..c3933bab 100644 --- a/ext/QuaternionicForwardDiffExt.jl +++ b/ext/QuaternionicForwardDiffExt.jl @@ -1,6 +1,11 @@ module QuaternionicForwardDiffExt using Quaternionic +import Quaternionic: AbstractQuaternion, Quaternion, QuatVec, quaternion, quatvec, components, + wrapper, basetype +# Under Requires (Julia < 1.9), ForwardDiff must be reached relative to the parent module; +# an absolute `using ForwardDiff` works there but warns that Quaternionic does not depend +# on ForwardDiff. isdefined(Base, :get_extension) ? (using ForwardDiff) : (using ..ForwardDiff) # Recurse so that nested duals, as in higher-order derivatives, are stripped to the @@ -12,33 +17,66 @@ Quaternionic.value(x::ForwardDiff.Dual) = Quaternionic.value(ForwardDiff.value(x # Quaternionic.iszerovalue(x::ForwardDiff.Dual) = iszero(Quaternionic.value(x)) ############################################### -# Let ForwardDiff act naturally on quaternions. - -# These next three definitions are cribbed from similar expressions -# enabling differentiation of complex-valued functions in -# https://github.com/JuliaDiff/ForwardDiff.jl/blob/78c73afd9a21593daf54f61c7d0db67130cf29e1/src/derivative.jl#L83-L88 - -@inline ForwardDiff.extract_derivative(::Type{T}, y::AbstractQuaternion) where {T} = zero(y) - -# Both Quaternion and Rotor, when differentiated, result in a Quaternion... -@inline function ForwardDiff.extract_derivative(::Type{T}, y::AbstractQuaternion{TD}) where {T, TD <: ForwardDiff.Dual} - quaternion( - ForwardDiff.partials(T, y[1], 1), - ForwardDiff.partials(T, y[2], 1), - ForwardDiff.partials(T, y[3], 1), - ForwardDiff.partials(T, y[4], 1) - ) +# Extract values and derivatives from quaternion-valued results. +# +# `ForwardDiff.derivative` calls `extract_derivative(T, y)` on the result `y`, and +# DifferentiationInterface calls `value(T, y)` and `partials(T, y, i)` on it, where `T` is +# the tag of the differentiation in progress. For a `Number` that is not a `Dual`, +# ForwardDiff's fallbacks return `zero(y)`, `y`, and `zero(y)`, respectively, which would +# silently discard the derivatives stored in the components of a quaternion. So we apply +# ForwardDiff's own methods to each component, which handle a `Dual` of any tag and a +# constant. Complex components, as in `Lorentz` rotors, are split into their real and +# imaginary parts, because only recent versions of ForwardDiff provide `extract_derivative` +# for `Complex{<:Dual}`, and none provides `value` or `partials` for it. Passing the tag +# `T` through keeps nested differentiation free of perturbation confusion. +# +# The derivative of a `QuatVec` is a `QuatVec`, and the derivative of a `Quaternion` or a +# `Rotor` is a `Quaternion`; derivatives of rotors are not rotors. The value, on the other +# hand, keeps the type of the result: a `Rotor` stays a `Rotor`, and its components are +# stored as they are, without normalization. +# +# `ForwardDiff.can_dual` is deliberately not extended to quaternions: inputs to ForwardDiff +# must be real numbers or arrays of them. + +# Apply the ForwardDiff extraction function `f` to the component `c`. +componentwise(f, ::Type{T}, c, args...) where {T} = f(T, c, args...) +function componentwise(f, ::Type{T}, c::Complex, args...) where {T} + complex(f(T, real(c), args...), f(T, imag(c), args...)) +end + +# Apply `f` to each component of `y`, and return the results as a `Quaternion`, or as a +# `QuatVec` if `y` is a `QuatVec`. +function componentwise(f, ::Type{T}, y::AbstractQuaternion, args...) where {T} + rewrap(y, map(c -> componentwise(f, T, c, args...), Tuple(components(y)))) +end +rewrap(::AbstractQuaternion, c) = quaternion(c...) +rewrap(::QuatVec, c) = quatvec(c...) + +function ForwardDiff.extract_derivative(::Type{T}, y::AbstractQuaternion) where {T} + componentwise(ForwardDiff.extract_derivative, T, y) +end + +function ForwardDiff.value(::Type{T}, y::AbstractQuaternion) where {T} + c = map(cᵢ -> componentwise(ForwardDiff.value, T, cᵢ), Tuple(components(y))) + wrapper(y){promote_type(map(typeof, c)...)}(c...) +end + +function ForwardDiff.partials(::Type{T}, y::AbstractQuaternion, i) where {T} + componentwise(ForwardDiff.partials, T, y, i) end -# ...but QuatVec results in a QuatVec -# COV_EXCL_START -@inline function ForwardDiff.extract_derivative(::Type{T}, y::QuatVec{TD}) where {T, TD <: ForwardDiff.Dual} - quatvec( - ForwardDiff.partials(T, y[2], 1), - ForwardDiff.partials(T, y[3], 1), - ForwardDiff.partials(T, y[4], 1) - ) +# `ForwardDiff.jacobian` of a function that returns an array of quaternions allocates its +# result with the element type `valtype(T, eltype(y))`, and fills it with `partials` above. +# For a quaternion of duals, ForwardDiff's fallback would return the quaternion type itself, +# so the Jacobian would silently hold dual numbers instead of derivatives. This method gives +# the type that `partials` returns, so that each entry of the Jacobian is the derivative of +# one quaternion of the output with respect to one real input. +function ForwardDiff.valtype(::Type{T}, ::Type{Q}) where {T,Q<:AbstractQuaternion} + derivativewrapper(Q){partialstype(T, basetype(Q))} end -# COV_EXCL_STOP +partialstype(::Type{T}, ::Type{C}) where {T,C} = ForwardDiff.valtype(T, C) +partialstype(::Type{T}, ::Type{Complex{C}}) where {T,C} = Complex{ForwardDiff.valtype(T, C)} +derivativewrapper(::Type{<:AbstractQuaternion}) = Quaternion +derivativewrapper(::Type{<:QuatVec}) = QuatVec end # module diff --git a/ext/QuaternionicLatexifyExt.jl b/ext/QuaternionicLatexifyExt.jl index 615de565..337273ad 100644 --- a/ext/QuaternionicLatexifyExt.jl +++ b/ext/QuaternionicLatexifyExt.jl @@ -3,9 +3,19 @@ module QuaternionicLatexifyExt import Quaternionic: AbstractQuaternion, QuatVec isdefined(Base, :get_extension) ? (using Latexify) : (using ..Latexify) +function latexraw_component(x::Number) + # Utility function to print one component of a quaternion in raw LaTeX. Latexify + # writes NaN as plain text, which would be set in math italics. + if x isa AbstractFloat && isnan(x) + "\\mathrm{NaN}" + else + Latexify.latexify(x, env=:raw, bracket=true) + end +end + function _pm_latex(x::Number) # Utility function to print a component of a quaternion in LaTeX - s = Latexify.latexify(x, env=:raw, bracket=true) + s = latexraw_component(x) if s[1] ∉ "+-" s = "+" * s end @@ -21,14 +31,27 @@ function _pm_latex(x::Number) s end -function Base.show(io::IO, ::MIME"text/latex", q::AbstractQuaternion) - s = Latexify.LaTeXStrings.latexstring( - q isa QuatVec ? "" : Latexify.latexify(q[1], env=:raw, bracket=true), +function latexraw_quaternion(q::AbstractQuaternion) + # Build the LaTeX form of `q`, without math delimiters. As in the plain-text form, the + # scalar part of a `QuatVec` is omitted. + string( + q isa QuatVec ? "" : latexraw_component(q[1]), _pm_latex(q[2]), "\\,\\mathbf{i}", _pm_latex(q[3]), "\\,\\mathbf{j}", _pm_latex(q[4]), "\\,\\mathbf{k}" ) - print(io, s) +end + +# This recipe makes `latexify(q)` agree with the `text/latex` form below, and lets +# Latexify's own methods for arrays and tables display arrays of quaternions. Without the +# `env` setting, Latexify would return the `LaTeXString` without math delimiters. +Latexify.@latexrecipe function f(q::AbstractQuaternion) + env --> :inline + return Latexify.LaTeXStrings.LaTeXString(latexraw_quaternion(q)) +end + +function Base.show(io::IO, ::MIME"text/latex", q::AbstractQuaternion) + print(io, Latexify.LaTeXStrings.latexstring(latexraw_quaternion(q))) end end # module diff --git a/ext/QuaternionicMooncakeExt.jl b/ext/QuaternionicMooncakeExt.jl new file mode 100644 index 00000000..8625e5be --- /dev/null +++ b/ext/QuaternionicMooncakeExt.jl @@ -0,0 +1,87 @@ +# Support for Mooncake. Mooncake differentiates the package's source natively, so this +# extension provides rules only for the two internal functions whose implementations +# Mooncake cannot trace: +# +# * `Quaternionic.csqrt(z)`, the complex square root, because Base's `sqrt(::Complex)` +# reinterprets the bits of floating-point numbers, which Mooncake refuses to +# differentiate. Every complex square root in the package goes through `csqrt`, which +# covers complex quaternions and `Lorentz` rotors. +# * `Quaternionic.dominant_eigenvector_lapack(A, uplo)`, because it calls LAPACK. It is +# used by `from_rotation_matrix` and `align`. +# +# It also replaces, for Mooncake only, the implementations of `abs` and `absvec` of +# quaternions with real floating-point components (see the overlays below). +# +# The rules themselves are the ChainRules `frule`s and `rrule`s of the ChainRulesCore +# extension, imported with `@from_chainrules`, which provides both forward and reverse +# mode. That is why this extension is triggered by ChainRulesCore as well as by Mooncake; +# Mooncake depends on ChainRulesCore, so the second trigger is always present. Real +# arguments of `csqrt` are left to Mooncake's own rule for `sqrt`. +# +# This extension is loaded only as a package extension (Julia 1.9 and later), never by +# Requires. +module QuaternionicMooncakeExt + +import Mooncake +import ChainRulesCore +using Quaternionic: Quaternionic, AbstractQuaternion, Quaternion, QuatVec, quaternion, quatvec, + components, absvec + +for T ∈ (Float32, Float64) + @eval Mooncake.@from_chainrules Mooncake.DefaultCtx Tuple{ + typeof(Quaternionic.csqrt), Complex{$T} + } + @eval Mooncake.@from_chainrules Mooncake.DefaultCtx Tuple{ + typeof(Quaternionic.dominant_eigenvector_lapack), Matrix{$T}, Char + } +end + +# For real components, `abs` and `absvec` call `hypot` with three or four arguments. +# Mooncake's reverse rule for `hypot` with more than two arguments calls Base's `_hypot`, +# which reinterprets the bits of floating-point numbers, so that forward mode over reverse +# mode (as in `DifferentiationInterface.hessian` with `SecondOrder(AutoMooncakeForward(), +# AutoMooncake())`) throws an `ArgumentError` for every function that calls them, which +# includes `log`, `exp`, and powers. These overlays compute the same norms with the +# package's `_hypot`, which scales the components by the largest of their absolute values +# and takes a square root, so that every mode of Mooncake differentiates them natively. +# The overlays are used only while Mooncake differentiates, and their values agree with +# those of `hypot` to within roundoff. A zero vector gets the norm zero as a constant, with +# a zero derivative. +const IEEE = Base.IEEEFloat +scalednorm(c) = iszero(maximum(abs, c)) ? zero(eltype(c)) : Quaternionic._hypot(c) +Mooncake.@mooncake_overlay Base.abs(q::Quaternion{T}) where {T<:IEEE} = scalednorm(components(q)) +Mooncake.@mooncake_overlay Base.abs(q::QuatVec{T}) where {T<:IEEE} = scalednorm(vec(q)) +Mooncake.@mooncake_overlay Quaternionic.absvec(q::AbstractQuaternion{T}) where {T<:IEEE} = scalednorm(vec(q)) + +# Friendly tangents. By default, Mooncake reports the gradient with respect to a +# quaternion argument in its structural form, `Tangent{(components=Tangent{(data=…)},)}`. +# With `Mooncake.Config(friendly_tangents=true)`, the methods below report it as a +# `Quaternion` instead (or as a `QuatVec` for a `QuatVec` argument), which is also the +# tangent type that the ChainRules rules use. The gradient with respect to a `Rotor` is +# therefore a `Quaternion`, not a `Rotor`. These hooks were introduced in Mooncake 0.5, so +# they are defined only when Mooncake provides them. +@static if isdefined(Mooncake, :AsCustomised) && isdefined(Mooncake, :FriendlyTangentCache) + const MooncakeScalar = Union{Base.IEEEFloat,Complex{<:Base.IEEEFloat}} + + function Mooncake.friendly_tangent_cache(::AbstractQuaternion{<:MooncakeScalar}) + return Mooncake.FriendlyTangentCache{Mooncake.AsCustomised}(nothing) + end + + # `componenttangents(t)` returns the four components of the structural tangent `t` of a + # quaternion. + componenttangents(t::Mooncake.Tangent) = t.fields.components.fields.data + + function Mooncake.tangent_to_friendly_internal!!( + ::Nothing, ::AbstractQuaternion{<:MooncakeScalar}, t::Mooncake.Tangent + ) + return quaternion(componenttangents(t)...) + end + function Mooncake.tangent_to_friendly_internal!!( + ::Nothing, ::QuatVec{<:MooncakeScalar}, t::Mooncake.Tangent + ) + c = componenttangents(t) + return quatvec(c[2], c[3], c[4]) + end +end + +end # module diff --git a/ext/QuaternionicReverseDiffExt.jl b/ext/QuaternionicReverseDiffExt.jl new file mode 100644 index 00000000..50fbac72 --- /dev/null +++ b/ext/QuaternionicReverseDiffExt.jl @@ -0,0 +1,147 @@ +module QuaternionicReverseDiffExt + +# ReverseDiff differentiates quaternions whose components are `TrackedReal`s natively, by +# recording the scalar operations on their components, so this extension provides no +# derivative rules. It only makes the source take the same branches as it does for plain +# numbers, fixes broadcasting of a `TrackedReal` with an array of quaternions, and keeps +# replayed tapes of `from_rotation_matrix` and `align` correct. It is loaded only as a +# package extension (Julia 1.9 and later), never through Requires. + +import Quaternionic +import Quaternionic: AbstractQuaternion +import ReverseDiff +import ReverseDiff: TrackedReal, TrackedArray, SpecialInstruction +using Base.Broadcast: Broadcasted +import LinearAlgebra +using LinearAlgebra: Symmetric, ⋅ +using StaticArrays: SMatrix, SVector + +# Strip the tracking, so that `iszerovalue` and the value-based series thresholds take the +# same branches as they do for the underlying numbers, and so that `dominant_eigenvector` +# treats a tracked element type as a wrapped one and uses its value-refined eigenvector. +# The recursion also strips nested tracking, as in `ReverseDiff.hessian`, and dual numbers +# inside `TrackedReal`s. +Quaternionic.value(x::TrackedReal) = Quaternionic.value(ReverseDiff.value(x)) + +# ReverseDiff requires the function it differentiates to return a real number (for +# `gradient`) or an array of real numbers (for `jacobian`). It treats any other `Number` +# that is not a `TrackedReal` as a constant, so a quaternion output, or an array of them, +# would silently give a gradient or Jacobian of zeros. These methods raise an error +# instead. Quaternions inside the function are unaffected; only the final output matters. +function ReverseDiff.seeded_reverse_pass!(_, ::AbstractQuaternion, _, _) + throw(ArgumentError( + "ReverseDiff.gradient requires a function that returns a real number, but this " * + "function returns a quaternion. Return a real number computed from it, or " * + "differentiate `x -> collect(components(f(x)))` with `ReverseDiff.jacobian`." + )) +end +function ReverseDiff.seeded_reverse_pass!( + ::AbstractArray, ::AbstractArray{<:AbstractQuaternion}, ::TrackedArray, _ +) + throw(ArgumentError( + "ReverseDiff.jacobian requires a function that returns an array of real numbers, " * + "but this function returns an array of quaternions. Return their components " * + "instead, for example with `to_float_array`." + )) +end + +# ReverseDiff specializes `materialize` for `f.(x, A)` and `f.(A, x)`, where `x` is a +# `TrackedReal`, `A` is an array of numbers, and `f` is any binary function with a DiffRules +# rule. Those methods call `broadcast(f, x, A)`, assuming that `A` holds plain reals, but +# for an array of quaternions that call builds the same `Broadcasted` object and reaches the +# same method again, until the stack overflows. For the binary functions that quaternions +# support, the methods below broadcast elementwise instead, so that each element records its +# own scalar operations. The array types are the six that ReverseDiff specializes, so that +# each of its methods is overridden by one of these, which is strictly more specific. + +const RDBroadcasted{F,T} = Broadcasted{<:Any,<:Any,F,T} + +# Compute the broadcast `bc` elementwise. This is what Base's `materialize` does, and it +# keeps the style of the broadcast, so that static arrays give static results. +elementwise(bc::Broadcasted) = copy(Base.Broadcast.instantiate(bc)) + +for f ∈ (:+, :-, :*, :/, :^) + for A ∈ (:AbstractArray, :AbstractVector, :AbstractMatrix, :Array, :Vector, :Matrix) + @eval begin + function Base.Broadcast.materialize( + bc::RDBroadcasted{typeof($f),<:Tuple{$A{<:AbstractQuaternion},TrackedReal}} + ) + elementwise(bc) + end + function Base.Broadcast.materialize( + bc::RDBroadcasted{typeof($f),<:Tuple{TrackedReal,$A{<:AbstractQuaternion}}} + ) + elementwise(bc) + end + end + end +end + +# `from_rotation_matrix` and `align` find the dominant eigenvector of a symmetric 4×4 +# matrix. For wrapped element types, `refined_dominant_eigenvector` in src/conversion.jl +# starts from the eigenvector of the matrix of values, which LAPACK computes, and refines it +# by two Newton steps, through which the derivatives are propagated. ReverseDiff would +# record that starting vector as a constant, so a tape replayed at another input (as by +# `ReverseDiff.gradient!` or `ReverseDiff.hessian!` with a recorded or compiled tape) would +# start from the eigenvector of the recording point, and its results would be wrong unless +# the two points were very close. The method below is the same computation, except that +# the starting vector is recorded as an instruction of its own, whose forward pass +# recomputes it from the current values and whose reverse pass propagates nothing, because +# the starting vector is a constant at every input. Each Newton step must stay identical +# to that of the source method. +function Quaternionic.refined_dominant_eigenvector(M::Symmetric{T}) where {T<:TrackedReal} + A = SMatrix{4,4,T}(M) + v = SVector{4,T}(starting_vector(A)) + λ = v ⋅ (A * v) + for _ ∈ 1:2 + r = A * v - λ * v + δ = Quaternionic.bordered_matrix(A - λ * LinearAlgebra.I, v) \ + SVector{5,T}(-r[1], -r[2], -r[3], -r[4], (1 - v ⋅ v) / 2) + v += SVector{4,T}(δ[1], δ[2], δ[3], δ[4]) + λ -= δ[5] + end + v +end + +# The starting vector of `refined_dominant_eigenvector` for the matrix `A` of `TrackedReal`s: +# the dominant unit eigenvector of the matrix of values, as a tuple of `TrackedReal`s on the +# tape of `A`. The instruction stores the vector of plain numbers computed when it was +# recorded. On a replay, the recomputed vector is given the sign closer to that one, so +# that the sign chosen downstream at the recording point (in `positive_hemisphere`, whose +# test a tape freezes) stays consistent. When the values of `A` are themselves tracked, as +# under `ReverseDiff.hessian`, the vector of values is found by the same function one level +# down, so that it is also recomputed when the outer tape (such as a `HessianTape`) is +# replayed. +function starting_vector(A::SMatrix{4,4,<:TrackedReal}) + a = first(A) + V, D = ReverseDiff.valtype(a), ReverseDiff.derivtype(a) + v = if V <: TrackedReal + starting_vector(map(ReverseDiff.value, A)) + else + Tuple(Quaternionic.dominant_eigenvector(Symmetric(map(Quaternionic.value, A)))) + end + tp = ReverseDiff.tape(A) + output = ntuple(k -> TrackedReal{V,D,Nothing}(convert(V, v[k]), zero(D), tp), 4) + ReverseDiff.record!( + tp, SpecialInstruction, starting_vector, A, output, map(Quaternionic.value, v) + ) + output +end + +function ReverseDiff.special_forward_exec!(instruction::SpecialInstruction{typeof(starting_vector)}) + A, output, v₀ = instruction.input, instruction.output, instruction.cache + ReverseDiff.pull_value!(A) + v = Quaternionic.dominant_eigenvector(Symmetric(map(Quaternionic.value, A))) + s = sum(v[k] * v₀[k] for k ∈ 1:4) < 0 ? -1 : 1 + for k ∈ 1:4 + ReverseDiff.value!(output[k], convert(ReverseDiff.valtype(output[k]), s * v[k])) + end + nothing +end + +function ReverseDiff.special_reverse_exec!(instruction::SpecialInstruction{typeof(starting_vector)}) + ReverseDiff.unseed!(instruction.output) + nothing +end + +end # module diff --git a/ext/QuaternionicSymbolicsExt.jl b/ext/QuaternionicSymbolicsExt.jl index b21413ef..d4036769 100644 --- a/ext/QuaternionicSymbolicsExt.jl +++ b/ext/QuaternionicSymbolicsExt.jl @@ -14,11 +14,44 @@ Base.abs(q::AbstractQuaternion{Symbolics.Num}) = √sum(x->x^2, components(q)) Base.abs(q::QuatVec{Symbolics.Num}) = √sum(x->x^2, vec(q)) absvec(q::AbstractQuaternion{Symbolics.Num}) = √sum(x->x^2, vec(q)) +# The source of `log` and of non-integer powers of a `Rotor` chooses among branches by +# comparing the values of the components, which symbolic components do not have. Instead, +# these methods return the general formula, log(q) = log|q| + atan(|v⃗|, w) v⃗/|v⃗|, which is +# valid everywhere except on the real axis, where it has a removable singularity (or, on +# the negative real axis, a branch cut). As with `exp`, it should not be evaluated there +# by direct substitution. The formula for a `Rotor` assumes unit norm. +function Base.log(q::Quaternion{Symbolics.Num}) + a = absvec(q) + log(abs(q)) + atan(a, q[1]) * (quatvec(q) / a) +end +function Base.log(q::Rotor{Symbolics.Num}) + a = absvec(q) + atan(a, q[1]) * (quatvec(q) / a) +end +# Integer powers of a `Rotor` have no branches, so only the other exponents are listed. +Base.:^(q::Rotor{Symbolics.Num}, s::AbstractFloat) = exp(s * log(q)) +Base.:^(q::Rotor{Symbolics.Num}, s::Rational) = exp(s * log(q)) +Base.:^(q::Rotor{Symbolics.Num}, s::Symbolics.Num) = exp(s * log(q)) + ### Functions that used to appear in quaternion.jl -quaternion(w::Symbolics.Num) = quaternion(SVector{4}(w, false, false, false)) -rotor(w::Symbolics.Num) = rotor(SVector{4}(one(w), false, false, false)) -quatvec(w::Symbolics.Num) = quatvec(SVector{4,typeof(w)}(false, false, false, false)) +# The other components are filled with `zero(w)` rather than `false`, because `Num(false)` +# prints as `false`. +quaternion(w::Symbolics.Num) = quaternion(SVector{4}(w, zero(w), zero(w), zero(w))) +function rotor(w::Symbolics.Num) + # When `w` wraps a numerical constant, the components are those of src's `rotor(v)` for + # that constant, so that the result is `±1` for a finite nonzero constant and a NaN rotor + # for a zero, NaN, or infinite constant. The sign of any other expression is unknown, so + # the identity rotor is returned without symbolic normalization. + v = Symbolics.value(w) + c = if v isa Real + SVector{4,Symbolics.Num}(components(rotor(v))) + else + SVector{4,Symbolics.Num}(one(w), zero(w), zero(w), zero(w)) + end + Rotor{Symbolics.Num}(c) +end +quatvec(w::Symbolics.Num) = quatvec(SVector{4}(zero(w), zero(w), zero(w), zero(w))) for QT1 ∈ (AbstractQuaternion, Quaternion, QuatVec, Rotor) @eval begin wrapper(::Type{<:$QT1}, ::Val{OP}, ::Type{<:Symbolics.Num}) where {OP} = quaternion @@ -45,140 +78,75 @@ let NT = Symbolics.Num end let T = Symbolics.Num for OP ∈ (Val{+}, Val{-}, Val{*}, Val{/}) - @eval wrapper(::Type{<:Quaternion}, ::$OP, ::Type{<:$T}) = quaternion - if T !== Quaternion - @eval wrapper(::Type{<:$T}, ::$OP, ::Type{<:Quaternion}) = quaternion + @eval begin + wrapper(::Type{<:Quaternion}, ::$OP, ::Type{<:$T}) = quaternion + wrapper(::Type{<:$T}, ::$OP, ::Type{<:Quaternion}) = quaternion end end end -Base.promote_rule(::Type{Q}, ::Type{S}) where {Q<:AbstractQuaternion,S<:Symbolics.Num} = - wrapper(Q){promote_type(basetype(Q), S)} +# This method resolves an ambiguity with Symbolics' rule +# `promote_rule(::Type{<:Number}, ::Type{Num})`. Base.promote_rule(::Type{Q}, ::Type{Symbolics.Num}) where {Q<:AbstractQuaternion} = wrapper(Q){promote_type(basetype(Q), Symbolics.Num)} +# As in src/quaternion.jl, a `QuatVec` or a `Rotor` promoted with a scalar becomes a +# `Quaternion`. These methods also resolve ambiguities with the rules in src. +for QT ∈ (QuatVec, Rotor) + @eval Base.promote_rule(::Type{$QT{T}}, ::Type{Symbolics.Num}) where {T<:Number} = + Quaternion{promote_type(T, Symbolics.Num)} +end ### Functions that used to appear in base.jl -function Base.:(==)(q1::AbstractQuaternion{Symbolics.Num}, q2::AbstractQuaternion{Symbolics.Num}) - ( - iszero(Symbolics.simplify(q1[1]-q2[1]; expand=true)) && - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::AbstractQuaternion{Symbolics.Num}, q2::AbstractQuaternion) - ( - iszero(Symbolics.simplify(q1[1]-q2[1]; expand=true)) && - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::AbstractQuaternion{Symbolics.Num}, q2::Number) - ( - iszero(Symbolics.simplify(q1[1]-q2; expand=true)) && - iszero(Symbolics.simplify(q1[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]; expand=true)) - ) -end -function Base.:(==)(q1::Number, q2::AbstractQuaternion{Symbolics.Num}) - ( - iszero(Symbolics.simplify(q1-q2[1]; expand=true)) && - iszero(Symbolics.simplify(q2[2]; expand=true)) && - iszero(Symbolics.simplify(q2[3]; expand=true)) && - iszero(Symbolics.simplify(q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::AbstractQuaternion{Symbolics.Num}, q2::Symbolics.Num) - ( - iszero(Symbolics.simplify(q1[1]-q2; expand=true)) && - iszero(Symbolics.simplify(q1[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]; expand=true)) - ) -end -function Base.:(==)(q1::Symbolics.Num, q2::AbstractQuaternion{Symbolics.Num}) - ( - iszero(Symbolics.simplify(q1-q2[1]; expand=true)) && - iszero(Symbolics.simplify(q2[2]; expand=true)) && - iszero(Symbolics.simplify(q2[3]; expand=true)) && - iszero(Symbolics.simplify(q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::QuatVec{Symbolics.Num}, q2::AbstractQuaternion{Symbolics.Num}) - ( - iszero(Symbolics.simplify(q2[1]; expand=true)) && - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::AbstractQuaternion{Symbolics.Num}, q2::QuatVec{Symbolics.Num}) - ( - iszero(Symbolics.simplify(q1[1]; expand=true)) && - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::QuatVec{Symbolics.Num}, q2::QuatVec{Symbolics.Num}) - ( - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::QuatVec{Symbolics.Num}, q2::AbstractQuaternion) - ( - iszero(q2[1]) && - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q2::AbstractQuaternion, q1::QuatVec{Symbolics.Num}) - ( - iszero(q2[1]) && - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::AbstractQuaternion{Symbolics.Num}, q2::QuatVec) - ( - iszero(Symbolics.simplify(q1[1]; expand=true)) && - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) - ) -end -function Base.:(==)(q1::QuatVec{Symbolics.Num}, q2::QuatVec) + +# A symbolic expression is treated as zero when it simplifies to zero. Other numbers are +# tested directly. +simplifies_to_zero(x::Symbolics.Num) = iszero(Symbolics.simplify(x; expand=true)) +simplifies_to_zero(z::Complex) = simplifies_to_zero(real(z)) && simplifies_to_zero(imag(z)) +simplifies_to_zero(x::Number) = iszero(x) + +# A `QuatVec` always stores a zero scalar part, so comparing all four components gives the +# right answer for every combination of quaternion types, and a `QuatVec` equals a scalar +# exactly when both are zero. +function symbolic_equal(q1::AbstractQuaternion, q2::AbstractQuaternion) ( - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) + simplifies_to_zero(q1[1]-q2[1]) && + simplifies_to_zero(q1[2]-q2[2]) && + simplifies_to_zero(q1[3]-q2[3]) && + simplifies_to_zero(q1[4]-q2[4]) ) end -function Base.:(==)(q2::QuatVec, q1::QuatVec{Symbolics.Num}) +function symbolic_equal(q::AbstractQuaternion, x::Number) ( - iszero(Symbolics.simplify(q1[2]-q2[2]; expand=true)) && - iszero(Symbolics.simplify(q1[3]-q2[3]; expand=true)) && - iszero(Symbolics.simplify(q1[4]-q2[4]; expand=true)) + simplifies_to_zero(q[1]-x) && + simplifies_to_zero(q[2]) && + simplifies_to_zero(q[3]) && + simplifies_to_zero(q[4]) ) end -function Base.:(==)(q1::QuatVec{Symbolics.Num}, q2::Number) - false -end -function Base.:(==)(q1::Number, q2::QuatVec{Symbolics.Num}) - false -end -function Base.:(==)(q1::QuatVec{Symbolics.Num}, q2::Symbolics.Num) - false -end -function Base.:(==)(q1::Symbolics.Num, q2::QuatVec{Symbolics.Num}) - false + +# Each of these combinations of argument types is needed to avoid method ambiguities with +# the methods in src/base.jl and in Symbolics. +let NT = Symbolics.Num + QTs = (AbstractQuaternion, QuatVec, AbstractQuaternion{NT}, QuatVec{NT}) + for QT1 ∈ QTs, QT2 ∈ QTs + if QT1 <: AbstractQuaternion{NT} || QT2 <: AbstractQuaternion{NT} + @eval Base.:(==)(q1::$QT1, q2::$QT2) = symbolic_equal(q1, q2) + end + end + for QT ∈ QTs + @eval begin + Base.:(==)(q::$QT, x::$NT) = symbolic_equal(q, x) + Base.:(==)(x::$NT, q::$QT) = symbolic_equal(q, x) + end + end + for QT ∈ (AbstractQuaternion{NT}, QuatVec{NT}) + @eval begin + Base.:(==)(q::$QT, x::Number) = symbolic_equal(q, x) + Base.:(==)(x::Number, q::$QT) = symbolic_equal(q, x) + end + end end + function _pm_ascii(x::Symbolics.Num) # Utility function to print a component of a quaternion s = "$x" @@ -199,8 +167,6 @@ end # Broadcast-like operations from Symbolics -# (d::Symbolics.Operator)(q::QT) where {QT<:AbstractQuaternion} = QT(d(q[1]), d(q[2]), d(q[3]), d(q[4])) -# (d::Symbolics.Operator)(q::QuatVec) = quatvec(d(q[2]), d(q[3]), d(q[4])) (d::Symbolics.Differential)(q::Quaternion) = quaternion(d(q[1]), d(q[2]), d(q[3]), d(q[4])) (d::Symbolics.Differential)(q::Rotor) = quaternion(d(q[1]), d(q[2]), d(q[3]), d(q[4])) (d::Symbolics.Differential)(q::QuatVec) = quatvec(d(q[2]), d(q[3]), d(q[4])) @@ -257,9 +223,11 @@ end # this package or not (on Julia 1.8 and higher) r(v) Symbolics.simplify.(𝓇(𝓋)) - for a ∈ [s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆] + # Tuples, unlike vectors, keep the type of each element, so that mixed operations + # are compiled too. + for a ∈ (s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆) conj(a) - for b ∈ [s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆] + for b ∈ (s, v, r, q, 𝓈, 𝓋, 𝓇, 𝓆) a * b a / b a + b diff --git a/ext/QuaternionicZygoteExt.jl b/ext/QuaternionicZygoteExt.jl index f0c7d41b..10cb5d39 100644 --- a/ext/QuaternionicZygoteExt.jl +++ b/ext/QuaternionicZygoteExt.jl @@ -1,64 +1,177 @@ +# Zygote-specific glue for quaternions. Every derivative rule lives in +# `QuaternionicChainRulesCoreExt`, and Zygote uses those rules directly. This module adds only +# what ChainRules cannot express. Zygote prefers its own rules for `ZygoteRuleConfig` and its +# own `@adjoint`s over config-free ChainRules rules, and several of those assume commutative +# multiplication or complex-number semantics, because `AbstractQuaternion <: Number`. They +# are overridden here for quaternion arguments. +# +# This extension is loaded only as a package extension, when both Zygote and ChainRulesCore +# are loaded; Requires never loads it. (The compatible versions of Zygote require Julia 1.10 +# or later.) module QuaternionicZygoteExt -import Quaternionic: Quaternionic, components, AbstractQuaternion -isdefined(Base, :get_extension) ? - (import Zygote; import ZygoteRules) : - (import ...Zygote; import ...ZygoteRules) +import Quaternionic: Quaternionic, AbstractQuaternion +import Zygote +import Zygote: ZygoteRuleConfig, @adjoint +import ChainRulesCore: rrule, rrule_via_ad, ProjectTo, NoTangent, unthunk -import StaticArraysCore: SVector -import ChainRulesCore: unthunk +const AQ = AbstractQuaternion +const QArr = AbstractArray{<:AbstractQuaternion} +const NArr = AbstractArray{<:Number} -# Lift any Δq form into a tuple cotangent -function Δtuple(Δq) - Δ = unthunk(Δq) - if Δ isa AbstractQuaternion - return components(Δ) - elseif Δ isa SVector{4} - return Tuple(Δ) - elseif Δ isa Tuple && length(Δ) == 4 - return Δ - elseif Δ isa Real - return (Δ, zero(Δ), zero(Δ), zero(Δ)) - else - error("Unsupported cotangent type: $(typeof(Δ))") - end +# Zygote defines rules for these functions on `(::ZygoteRuleConfig, ::Number)`, which outrank +# the config-free quaternion rules. Their pullbacks treat the argument as a complex number: +# `imag`'s pullback returns `real(Δ) * im`, for example, which turns the cotangent of a +# `QuatVec` into a complex vector. These methods are more specific, and they forward to the +# config-free rules. (Defining the quaternion rules on `RuleConfig` instead would be +# ambiguous with Zygote's.) +for f ∈ (:real, :imag, :conj, :abs2, :abs) + @eval rrule(::ZygoteRuleConfig, ::typeof($f), q::AQ) = rrule($f, q) end -Zygote.@adjoint function Base.:+(t::Real, q::AbstractQuaternion) - q′ = t + q - function pullback(Δq′) - Δw, Δx, Δy, Δz = Δtuple(Δq′) - return (Δw, typeof(q)(Δw, Δx, Δy, Δz)) - end - return q′, pullback +# Zygote's rule for `literal_pow` (which `q^2` with a literal exponent calls) differentiates +# `x^p` as if multiplication commuted. This method forwards to the quaternion rule. Where +# there is none, because the power is opted out (as for complex `Rotor`s), it differentiates +# `q^p` instead, which reaches the rules or the source of `^`. +function rrule( + config::ZygoteRuleConfig, ::typeof(Base.literal_pow), ::typeof(^), q::AQ, v::Val{p} +) where {p} + result = rrule(Base.literal_pow, ^, q, v) + result === nothing || return result + Ω, power_pullback = rrule_via_ad(config, ^, q, p) + literal_pow_pullback(ΔΩ) = (NoTangent(), NoTangent(), power_pullback(ΔΩ)[2], NoTangent()) + return Ω, literal_pow_pullback end -Zygote.@adjoint function Base.:+(q::AbstractQuaternion, t::Real) - q′ = q + t - function pullback(Δq′) - Δw, Δx, Δy, Δz = Δtuple(Δq′) - return (typeof(q)(Δw, Δx, Δy, Δz), Δw) +# Zygote's rule for `+(xs::Number...)` passes the cotangent of the sum to every argument +# without projecting it, which gives a real argument a quaternion gradient. This function +# returns the sum and a pullback that first projects the cotangent onto the sum (which +# normalizes the forms that Zygote may pass, such as a `NamedTuple`) and then onto each +# argument. A real argument thus receives the scalar part of the cotangent. +function projected_plus(args...) + Ω = +(args...) + project_sum = ProjectTo(Ω) + projections = map(ProjectTo, args) + function plus_pullback(ΔΩ) + Δ = project_sum(unthunk(ΔΩ)) + return (NoTangent(), map(p -> p(Δ), projections)...) end - return q′, pullback + return Ω, plus_pullback end -Zygote.@adjoint function Base.:-(t::Real, q::AbstractQuaternion) - q′ = t - q - function pullback(Δq′) - Δw, Δx, Δy, Δz = Δtuple(Δq′) - return (Δw, typeof(q)(-Δw, -Δx, -Δy, -Δz)) +# These methods cover sums of one or two arguments, at least one of which is a quaternion. +rrule(::ZygoteRuleConfig, ::typeof(+), a::AQ) = projected_plus(a) +for (A, B) ∈ ((:AQ, :AQ), (:AQ, :Number), (:Number, :AQ)) + @eval rrule(::ZygoteRuleConfig, ::typeof(+), a::$A, b::$B) = projected_plus(a, b) +end + +# Sums of three or more arguments with a quaternion among the first three. The seven +# patterns of quaternions and numbers in those positions cover each other's intersections, so +# that no two of these methods are ambiguous. +for (A, B, C) ∈ Iterators.product((:AQ, :Number), (:AQ, :Number), (:AQ, :Number)) + :AQ ∈ (A, B, C) || continue + @eval rrule(::ZygoteRuleConfig, ::typeof(+), a::$A, b::$B, c::$C, xs::Number...) = + projected_plus(a, b, c, xs...) +end + +# Sums whose first quaternion is in position 4 through 8, after real or complex numbers. A +# first quaternion further along still gets Zygote's unprojected rule, which gives the other +# arguments quaternion gradients with the correct scalar parts. These methods cannot be +# ambiguous with those above, because a quaternion is not a `Union{Real,Complex}`. +for k ∈ 4:8 + reals = [Symbol(:r, i) for i ∈ 1:k-1] + signature = [:($(r)::Union{Real,Complex}) for r ∈ reals] + @eval rrule(::ZygoteRuleConfig, ::typeof(+), $(signature...), q::AQ, xs::Number...) = + projected_plus($(reals...), q, xs...) +end + +# Zygote's `@adjoint inv(::Union{Number,AbstractMatrix})` bypasses ChainRules, and its formula +# is wrong for quaternions with complex components. This adjoint calls the quaternion rule. +@adjoint function Base.inv(q::AQ) + Ω, back = rrule(inv, q) + function inv_pullback(Δ) + return (Zygote.wrap_chainrules_output(back(Zygote.wrap_chainrules_input(Δ))[2]),) end - return q′, pullback + return Ω, inv_pullback end -Zygote.@adjoint function Base.:-(q::AbstractQuaternion, t::Real) - q′ = q - t - function pullback(Δq′) - Δw, Δx, Δy, Δz = Δtuple(Δq′) - return (typeof(q)(Δw, Δx, Δy, Δz), -Δw) +# Zygote's broadcast adjoints for `.*`, `./`, `.^p`, `abs2.`, and `imag.` assume commutative +# multiplication or complex arguments, and scalar times quaternion array overflows the stack. +# When any operand is a quaternion or an array of quaternions, these adjoints use Zygote's +# generic broadcast instead, which applies the scalar rules elementwise. The pullback of +# `Zygote._broadcast_generic` returns a leading cotangent for the broadcast style, which is +# dropped here. The signatures with `Bool` resolve ambiguities with Zygote's adjoints for +# `Bool` operands. The broadcast adjoints for `.+`, `.-`, `real.`, and `conj.` are already +# correct for quaternions. +const BinarySignatures = ( + (:AQ, :QArr), (:QArr, :AQ), (:QArr, :QArr), (:Number, :QArr), (:QArr, :Number), + (:Bool, :QArr), (:QArr, :Bool), (:AQ, :NArr), (:NArr, :AQ), (:QArr, :NArr), (:NArr, :QArr), +) +for op ∈ (:*, :/), (A, B) ∈ BinarySignatures + @eval @adjoint function Base.Broadcast.broadcasted(::typeof($op), x::$A, y::$B) + Ω, back = Zygote._broadcast_generic(__context__, $op, x, y) + return Ω, Base.tail ∘ back end - return q′, pullback +end +@adjoint function Base.Broadcast.broadcasted( + ::typeof(Base.literal_pow), ::typeof(^), x::QArr, p::Val +) + Ω, back = Zygote._broadcast_generic(__context__, y -> Base.literal_pow(^, y, p), x) + return Ω, Δ -> (nothing, nothing, back(Δ)[3], nothing) +end +for f ∈ (:abs2, :imag) + @eval @adjoint function Base.Broadcast.broadcasted(::typeof($f), x::QArr) + Ω, back = Zygote._broadcast_generic(__context__, $f, x) + return Ω, Base.tail ∘ back + end +end + +# A broadcast whose operands are all scalars computes the same thing as the scalar call, but +# Zygote's adjoints for scalar operands of `.*`, `./`, `.^p`, `abs2.`, and `imag.` share the +# commutative and complex assumptions of the array adjoints. Zygote's generic broadcast does +# not handle these zero-dimensional broadcasts, so when a quaternion is among the operands, +# these adjoints differentiate the scalar call instead, which reaches the quaternion rules. +# A broadcast of `*` over three or more scalar operands, as in `broadcast(*, a, b, c)`, is +# handled in the same way when a quaternion is among the first three operands; the seven +# patterns are those of the sums above. (Chained operators, as in `a .* b .* c`, are nested +# broadcasts of two operands.) +for op ∈ (:*, :/), (A, B) ∈ ((:AQ, :AQ), (:AQ, :Number), (:Number, :AQ)) + @eval @adjoint Base.Broadcast.broadcasted(::typeof($op), x::$A, y::$B) = + Zygote._pullback(__context__, $op, x, y) +end +for (A, B, C) ∈ Iterators.product((:AQ, :Number), (:AQ, :Number), (:AQ, :Number)) + :AQ ∈ (A, B, C) || continue + @eval @adjoint Base.Broadcast.broadcasted( + ::typeof(*), x::$A, y::$B, z::$C, zs::Number... + ) = Zygote._pullback(__context__, *, x, y, z, zs...) +end +@adjoint Base.Broadcast.broadcasted(::typeof(Base.literal_pow), ::typeof(^), x::AQ, p::Val) = + Zygote._pullback(__context__, Base.literal_pow, ^, x, p) +for f ∈ (:abs2, :imag) + @eval @adjoint Base.Broadcast.broadcasted(::typeof($f), x::AQ) = + Zygote._pullback(__context__, $f, x) end +# `Zygote.gradient` seeds the output of the function with `sensitivity(y)`, which is +# `one(y)` for a `Number`, and `Zygote.jacobian` treats a `Number` output, or each element of +# an array output, as a single scalar. For quaternion outputs, both would silently return +# the derivatives of the scalar parts only. Zygote raises errors for complex outputs in the +# same places, and these methods do the same for quaternions. Quaternions inside the +# function are unaffected; only the final output matters. +function Zygote.sensitivity(::AQ) + throw(ArgumentError( + "Output is a quaternion, so the gradient is not defined. Differentiate a real " * + "number computed from it, call the pullback from `Zygote.pullback` with an explicit " * + "quaternion cotangent, or use `Zygote.jacobian` on `x -> collect(components(f(x)))`." + )) +end +Zygote._jvec(::AQ) = throw(quaternion_jacobian_error()) +Zygote._jvec(::QArr) = throw(quaternion_jacobian_error()) +function quaternion_jacobian_error() + ArgumentError( + "jacobian does not accept quaternion output. Return the components as a real " * + "array instead, for example with `collect(components(q))` or `to_float_array`." + ) +end end # module diff --git a/scripts/docs.jl b/scripts/docs.jl index 7ad03628..88f2fe4d 100644 --- a/scripts/docs.jl +++ b/scripts/docs.jl @@ -12,7 +12,9 @@ println("Building docs starting at ", Dates.format(Dates.now(), "HH:MM:SS"), "." using Pkg cd((@__DIR__) * "/..") Pkg.activate("docs") -Pkg.update() +# The docs share the workspace's root Manifest.toml with the tests, so this only +# instantiates it; updating it would also change the packages that the tests use. +Pkg.instantiate() using LiveServer servedocs(launch_browser=true) diff --git a/scripts/test.jl b/scripts/test.jl index 4f56c494..798f478b 100644 --- a/scripts/test.jl +++ b/scripts/test.jl @@ -5,16 +5,26 @@ using Pkg cd((@__DIR__) * "/..") Pkg.activate(".") +# Coverage is written even when the tests fail, but the failure is reported and the script +# then exits with a nonzero status. +testerror = nothing try Δt = @elapsed Pkg.test("Quaternionic"; coverage=true, test_args=ARGS) println("Running tests took $Δt seconds.") catch e - println("Tests failed; proceeding to coverage") + e isa InterruptException && rethrow() + global testerror = e + showerror(stderr, e) + println(stderr, "\nTests failed; proceeding to coverage") end -Pkg.activate() # Activate Julia's base (home) directory +Pkg.activate("test") # Coverage is a dependency of the test environment. using Coverage cd((@__DIR__) * "/..") coverage = vcat(Coverage.process_folder("src"), Coverage.process_folder("ext")) Coverage.writefile("lcov.info", coverage) -Coverage.clean_folder(".") +# Pkg.test writes .cov files only next to the package's own sources. Cleaning just these +# directories avoids following symbolic links out of the repository. +foreach(Coverage.clean_folder, ("src", "ext", "test")) + +isnothing(testerror) || exit(1) diff --git a/src/Lorentz.jl b/src/Lorentz.jl index c20c360c..5e92d018 100644 --- a/src/Lorentz.jl +++ b/src/Lorentz.jl @@ -8,7 +8,7 @@ We work in the spacetime algebra ``Cl(3,1)`` with metric signature ``{−}{+}{+} basis vectors `𝐭, 𝐱, 𝐲, 𝐳` satisfying `𝐭² = −1`, `𝐱² = 𝐲² = 𝐳² = +1`, all mutually anticommuting. The pseudoscalar ``𝐈 = 𝐭𝐱𝐲𝐳`` satisfies ``𝐈² = −𝟏``. -Elements of ``𝐑 ∈ \mathrm{Spin}⁺(3,1)`` live in the even subalgebra (grades 0, 2, 4) and +Elements ``𝐑 ∈ \mathrm{Spin}⁺(3,1)`` live in the even subalgebra (grades 0, 2, 4) and satisfy ``𝐑 𝐑̃ = 𝟏``, where ``𝐑̃`` is the GA reverse. In particular, note that that product *could* include a term proportional to the pseudoscalar; it is zero: ``𝐑 𝐑̃ = 𝟏 + 0 𝐈``. This subalgebra splits into two parts: @@ -32,19 +32,67 @@ usual, you can get the plain (complex) coefficients with [`components`](@ref). ## Operations -Compose with `*`, invert with `inv`, obtain the identity with `one`. -Apply to a Minkowski 4-vector `v = [vᵗ, vˣ, vʸ, vᶻ]` by calling `Λ(v)`. -Access the GA components via [`ga_components`](@ref). +Compose with `*`, invert with `inv`, and obtain the identity with `one`. Apply `Λ` to a +Minkowski 4-vector `v = [vᵗ, vˣ, vʸ, vᶻ]` by calling `Λ(v)`, and access the GA components +via [`ga_components`](@ref). + +The action is *active*: `Λ(v)` is the transformed vector, expressed in the original frame. +For example, `Boost(v⃗)([1, 0, 0, 0])` is `γ .* [1; v⃗]`, the 4-velocity of a particle moving +with velocity `v⃗`. The components of a fixed vector as seen by an observer moving with +velocity `v⃗` are given by the passive transformation `inv(Boost(v⃗))`. Composition acts +from right to left, so that `(Λ₁ * Λ₂)(v) ≈ Λ₁(Λ₂(v))`. + +Calling `Λ` on a 4-vector given as an `AbstractVector` is different from calling it on a +`QuatVec`. `Λ(v::QuatVec)` is the generic rotor sandwich `Λ * v * conj(Λ)`, which, in this +encoding, transforms a spatial *bivector* (such as an electromagnetic field) rather than a +spatial vector, and it returns a complex `QuatVec` even for real input. + +Many generic quaternion functions, such as `exp`, `log`, `sqrt`, and integer powers, also +accept complex quaternions. Functions that are specific to rotations in three dimensions, +such as `distance`, `to_euler_angles`, and `from_rotation_matrix`, do not support `Lorentz` +input. ## Constructors -Use the named constructor [`Boost`](@ref). For a pure rotation, use `Lorentz(R)`. +Use the named constructor [`Boost`](@ref) for a pure boost, and `Lorentz(R)` for the pure +rotation given by a real `Rotor` `R`. More generally, the forms + + Lorentz(q::AbstractQuaternion) + Lorentz(w, x, y, z) + Lorentz(v::AbstractVector) + Lorentz(w::Number) + +convert the given (possibly complex) components to complex numbers and normalize the result +by the complex spinor norm `√(w² + x² + y² + z²)`, so that `w² + x² + y² + z² = 1` in +complex arithmetic. The vector form accepts 1, 3, or 4 components, like [`rotor`](@ref). +Note that this normalization is not the same as normalization by the Euclidean norm. For +example, `Lorentz(QuatVec(0, im, 0, 0))` (the bivector `𝐭𝐱`, whose spinor norm is `im`) +returns the rotation `𝐢`. For a boost with large rapidity, the spinor norm is computed as +a difference of large numbers, so the normalization itself loses accuracy. The type +constructors `Lorentz{T}(w, x, y, z)` and `Lorentz{T}(q::AbstractQuaternion)` do not +normalize, and are the better choice when the input is already known to have unit spinor +norm. Finally, `Lorentz(T)` returns the type `Lorentz{T}` for a real number type `T`. """ const Lorentz{T<:Real} = Rotor{Complex{T}} -Lorentz(q::AbstractQuaternion) = Rotor(complex.(components(q))...) -Lorentz(w) = Rotor(complex(w)) -Lorentz(w, x, y, z) = Rotor(complex(w), complex(x), complex(y), complex(z)) +# The components are converted one at a time, rather than by broadcasting `complex` over +# `components(q)` and splatting the result, because Zygote cannot differentiate that splat. +Lorentz(q::AbstractQuaternion) = + Rotor(complex(q[1]), complex(q[2]), complex(q[3]), complex(q[4])) +function Lorentz(v::AbstractVector) + if length(v) == 4 + Lorentz(v[begin], v[begin+1], v[begin+2], v[begin+3]) + elseif length(v) == 3 + Lorentz(false, v[begin], v[begin+1], v[begin+2]) + elseif length(v) == 1 + Lorentz(v[begin]) + else + throw(DimensionMismatch("Lorentz rotor must have 1, 3, or 4 inputs")) + end +end +Lorentz(w::Number) = Lorentz(w, false, false, false) +Lorentz(w::Number, x::Number, y::Number, z::Number) = + Rotor(complex(w), complex(x), complex(y), complex(z)) @doc raw""" ga_components(Λ::Lorentz{T}) → SVector{8, T} @@ -53,7 +101,7 @@ Return the eight real geometric-algebra components of `Λ` in Cl(3,1), ordered as in the even-subalgebra expansion of a Spin⁺(3,1) rotor: ```math -𝐑 = R^1 + R^𝐢\,𝐢 + R^𝐣\,𝐣 + R^𝐤\,𝐤 + R^{𝐭𝐱}\,𝐭𝐱 + R^{𝐭𝐲}\,𝐭𝐲 + R^{𝐭𝐳}\,𝐭𝐳 + R^𝐈\,𝐈 +𝐑 = R^1 + R^{𝐳𝐲}\,𝐳𝐲 + R^{𝐱𝐳}\,𝐱𝐳 + R^{𝐲𝐱}\,𝐲𝐱 + R^{𝐭𝐱}\,𝐭𝐱 + R^{𝐭𝐲}\,𝐭𝐲 + R^{𝐭𝐳}\,𝐭𝐳 + R^{𝐭𝐱𝐲𝐳}\,𝐈 ``` where ``𝐈 = 𝐭𝐱𝐲𝐳`` is the pseudoscalar of ``\mathrm{Cl}(3,1)``. @@ -103,27 +151,41 @@ R¹ Rᵗˣʸᶻ + Rᶻʸ Rᵗˣ + Rˣᶻ Rᵗʸ + Rʸˣ Rᵗᶻ = 0. ``` """ function ga_components(Λ::Lorentz{T}) where {T<:Real} - w, x, y, z = getfield(Λ, :components) - @SVector [real(w), real(x), real(y), real(z), imag(x), imag(y), imag(z), imag(w)] + w, x, y, z = components(Λ) + # The varargs constructor is used rather than `@SVector [...]`, which builds the + # SVector from a tuple, because Zygote cannot differentiate that tuple form. + SVector(real(w), real(x), real(y), real(z), imag(x), imag(y), imag(z), imag(w)) end # --------------------------------------------------------------------------- # Named constructors # --------------------------------------------------------------------------- """ - Boost(η::T, n̂::AbstractVector) → Lorentz{T} - Boost(η::T, n̂::QuatVec) → Lorentz{T} - Boost(v⃗::QuatVec) → Lorentz{T} - Boost(v⃗::AbstractVector) → Lorentz{T} + Boost(η, n̂::AbstractVector) → Lorentz{S} + Boost(η, n̂::QuatVec) → Lorentz{S} + Boost(v⃗::QuatVec) → Lorentz{S} + Boost(v⃗::AbstractVector) → Lorentz{S} Construct the pure boost with rapidity `η` along the unit direction `n̂`, or equivalently from a velocity vector `v⃗` whose magnitude `β = norm(v⃗)` encodes the boost speed (in units where c = 1) and whose direction gives `n̂`. -The first two forms take an explicit rapidity and unit direction. The last two forms -accept a velocity vector `v⃗` and compute `η = atanh(β)` and `n̂ = v⃗ / β` internally. -The direction `n̂` may be either a 3-element `AbstractVector` `[nˣ, nʸ, nᶻ]` or a -`QuatVec` (whose `x`, `y`, `z` components are used as the direction). +The first two forms take an explicit rapidity and unit direction. The last two forms accept +a velocity vector `v⃗`, which must satisfy `β < 1`, and are equivalent to `Boost(atanh(β), +v⃗ / β)`. The direction `n̂` may be either a 3-element `AbstractVector` `[nˣ, nʸ, nᶻ]` or a +`QuatVec` (whose `x`, `y`, `z` components are used as the direction), and the velocity `v⃗` +may likewise be a 3-element `AbstractVector` or a `QuatVec`. + +The element type `S` of the result is the floating-point type obtained by promoting the +types of all the inputs, so that, for example, an integer rapidity, a `Float32` rapidity +with a `Float64` direction, and automatic differentiation with respect to the direction all +work as expected. + +The direction `n̂` is neither checked nor normalized; if it is not a unit vector, the result +does not have unit spinor norm, and is not a Lorentz transformation. The velocity forms +throw a `DomainError` if `β ≥ 1`. Note that the velocity parametrization cannot represent +large rapidities accurately, because `β = tanh(η)` rounds to 1 for `η ≳ 19` in `Float64`; +the rapidity forms have no such limitation. In the even subalgebra of Cl(3,1) the rotor is @@ -131,108 +193,139 @@ In the even subalgebra of Cl(3,1) the rotor is 𝐑 = \\cosh(η/2)·𝟏 + \\sinh(η/2)·(nˣ\\,𝐭𝐱 + nʸ\\,𝐭𝐲 + nᶻ\\,𝐭𝐳). ``` +This is an active transformation: `Boost(v⃗)` maps the 4-velocity `[1, 0, 0, 0]` of a +particle at rest to `γ .* [1; v⃗]`, the 4-velocity of a particle moving with velocity `v⃗`. + See [`ga_components(::Lorentz)`](@ref) for the correspondence between this GA form and the quaternion storage. """ -function Boost(η::T, n̂::AbstractVector) where {T<:Real} +function Boost(η::Real, n̂::AbstractVector) length(n̂) == 3 || throw(DimensionMismatch( "boost direction must be a 3-vector; got length $(length(n̂))" )) Base.require_one_based_indexing(n̂) - ch, sh = cosh(η / 2), sinh(η / 2) - return Rotor{Complex{T}}( + S = float(promote_type(typeof(η), eltype(n̂))) + # Converting η first makes the result as precise as its element type claims. + ηS = convert(S, η) + ch, sh = cosh(ηS / 2), sinh(ηS / 2) + return Rotor{Complex{S}}( complex(ch), - complex(zero(T), sh * n̂[1]), - complex(zero(T), sh * n̂[2]), - complex(zero(T), sh * n̂[3]), + complex(zero(S), sh * n̂[1]), + complex(zero(S), sh * n̂[2]), + complex(zero(S), sh * n̂[3]), ) end -function Boost(η::T, n̂::QuatVec) where {T<:Real} - ch, sh = cosh(η / 2), sinh(η / 2) +function Boost(η::Real, n̂::QuatVec) + S = float(promote_type(typeof(η), basetype(n̂))) + # Converting η first makes the result as precise as its element type claims. + ηS = convert(S, η) + ch, sh = cosh(ηS / 2), sinh(ηS / 2) _, nx, ny, nz = components(n̂) - return Rotor{Complex{T}}( + return Rotor{Complex{S}}( complex(ch), - complex(zero(T), sh * nx), - complex(zero(T), sh * ny), - complex(zero(T), sh * nz), + complex(zero(S), sh * nx), + complex(zero(S), sh * ny), + complex(zero(S), sh * nz), ) end function Boost(v⃗::QuatVec{T}) where {T<:Real} + S = float(T) β² = abs2vec(v⃗) - ch, shc = if iszerovalue(v⃗) - # Taylor series for cosh(atanh(β)/2) and sinh(atanh(β)/2)/β in β², - # correct through 4th order so that AD derivatives at β=0 are accurate. - 1 + β²*(1 + 11β²/16)/8, - (1 + β²*(3 + 31β²/16)/8) / 2 - else - β = sqrt(β²) - η = atanh(β) - cosh(η/2), sinh(η/2) / β - end + # The check throws only for a definite `false`, so that symbolic input, for which the + # comparison returns an expression rather than a `Bool`, is accepted. + (value(β²) < 1) === false && + throw(DomainError(v⃗, "a boost velocity must have norm less than 1")) + # With s = √(1-β²) = 1/γ, the half-angle formulas give cosh(η/2) = √((1+s)/(2s)) and + # sinh(η/2)/β = 1/√(2s(1+s)). Unlike `atanh` and division by β, these expressions are + # smooth in β² near zero and involve no cancellation, so no special case is needed + # there, even for derivatives of any order. + s = sqrt(1 - β²) + shc = inv(sqrt(2s * (1 + s))) # sinh(η/2) / β + ch = (1 + s) * shc # cosh(η/2) vˣ, vʸ, vᶻ = vec(v⃗) - return Rotor{Complex{T}}( + return Rotor{Complex{S}}( complex(ch), - complex(zero(T), shc * vˣ), - complex(zero(T), shc * vʸ), - complex(zero(T), shc * vᶻ), + complex(zero(S), shc * vˣ), + complex(zero(S), shc * vʸ), + complex(zero(S), shc * vᶻ), ) end -Boost(v⃗::AbstractVector{T}) where {T<:Real} = Boost(QuatVec(v⃗)) +function Boost(v⃗::AbstractVector{T}) where {T<:Real} + length(v⃗) == 3 || throw(DimensionMismatch( + "boost velocity must be a 3-vector; got length $(length(v⃗))" + )) + return Boost(QuatVec(v⃗)) +end # --------------------------------------------------------------------------- # Action on Minkowski 4-vectors # --------------------------------------------------------------------------- """ - (Λ::Lorentz)(v::AbstractVector) → similar(v) + (Λ::Lorentz{T})(v::AbstractVector) → AbstractVector{S} Apply `Λ` to the Minkowski 4-vector `v = [vᵗ, vˣ, vʸ, vᶻ]` (signature −+++) -and return the transformed vector in a fresh container of the same type with -element type `T`. - -The action is the Spin⁺(3,1) sandwich `V′ = R·V·R̃` in Cl(3,1), where `R̃` is -the GA reverse. The eight real GA components `(R¹, Rᶻʸ, …, Rᵗˣʸᶻ)` are -extracted via [`ga_components(::Lorentz)`](@ref), and the bilinear -expansion of the grade-1 projection of `R·V·R̃` is applied directly. +and return the transformed vector. + +The element type `S` of the result is obtained by promoting `T` and `eltype(v)` through the +arithmetic, so that `Lorentz{Float64}` acting on a vector of `Int` or `Float32` returns +`Float64` elements, and dual numbers from automatic differentiation propagate. An +`SVector{4}` input returns an `SVector{4, S}`; any other input returns a new container +`similar(v, S)`, which, for example, is a `Vector{S}` for a `Vector` or a view. + +The action is the Spin⁺(3,1) sandwich `V′ = R·V·R̃` in Cl(3,1), where `R̃` is the GA +reverse. This is an active transformation, and `(Λ₁ * Λ₂)(v) ≈ Λ₁(Λ₂(v))`. The eight real +GA components `(R¹, Rᶻʸ, …, Rᵗˣʸᶻ)` are extracted via [`ga_components(::Lorentz)`](@ref), +and the bilinear expansion of the grade-1 projection of `R·V·R̃` is applied directly. """ function (Λ::Lorentz)(v::AbstractVector) - return typeof(v)(Λ(SVector{4}(v))) + length(v) == 4 || throw(DimensionMismatch( + "a Minkowski 4-vector must have length 4; got length $(length(v))" + )) + v′ = Λ(SVector{4}(v[begin], v[begin+1], v[begin+2], v[begin+3])) + # For the common containers, whose `similar` is a `Vector`, the result is built without + # mutation, so that reverse-mode AD such as Zygote can differentiate through it. + if v isa Union{Array, AbstractRange, SubArray{<:Any, 1, <:Array}} + return Vector(v′) + else + return copyto!(similar(v, eltype(v′)), v′) + end end function (Λ::Lorentz{T1})(v::SVector{4, T2}) where {T1<:Real, T2<:Real} R¹, Rᶻʸ, Rˣᶻ, Rʸˣ, Rᵗˣ, Rᵗʸ, Rᵗᶻ, Rᵗˣʸᶻ = ga_components(Λ) - v′ᵗ = v ⋅ @SVector [ + v′ᵗ = v ⋅ SVector( R¹^2 + Rᵗˣ^2 + Rᵗˣʸᶻ^2 + Rᵗʸ^2 + Rᵗᶻ^2 + Rʸˣ^2 + Rˣᶻ^2 + Rᶻʸ^2, 2R¹ * Rᵗˣ - 2Rᵗˣʸᶻ * Rᶻʸ + 2Rᵗʸ * Rʸˣ - 2Rᵗᶻ * Rˣᶻ, 2R¹ * Rᵗʸ - 2Rᵗˣ * Rʸˣ - 2Rᵗˣʸᶻ * Rˣᶻ + 2Rᵗᶻ * Rᶻʸ, 2R¹ * Rᵗᶻ + 2Rᵗˣ * Rˣᶻ - 2Rᵗˣʸᶻ * Rʸˣ - 2Rᵗʸ * Rᶻʸ - ] + ) - v′ˣ = v ⋅ @SVector [ + v′ˣ = v ⋅ SVector( 2R¹ * Rᵗˣ - 2Rᵗˣʸᶻ * Rᶻʸ - 2Rᵗʸ * Rʸˣ + 2Rᵗᶻ * Rˣᶻ, R¹^2 + Rᵗˣ^2 + Rᵗˣʸᶻ^2 - Rᵗʸ^2 - Rᵗᶻ^2 - Rʸˣ^2 - Rˣᶻ^2 + Rᶻʸ^2, -2R¹ * Rʸˣ + 2Rᵗˣ * Rᵗʸ - 2Rᵗˣʸᶻ * Rᵗᶻ + 2Rˣᶻ * Rᶻʸ, 2R¹ * Rˣᶻ + 2Rᵗˣ * Rᵗᶻ + 2Rᵗˣʸᶻ * Rᵗʸ + 2Rʸˣ * Rᶻʸ - ] + ) - v′ʸ = v ⋅ @SVector [ + v′ʸ = v ⋅ SVector( 2R¹ * Rᵗʸ + 2Rᵗˣ * Rʸˣ - 2Rᵗˣʸᶻ * Rˣᶻ - 2Rᵗᶻ * Rᶻʸ, 2R¹ * Rʸˣ + 2Rᵗˣ * Rᵗʸ + 2Rᵗˣʸᶻ * Rᵗᶻ + 2Rˣᶻ * Rᶻʸ, R¹^2 - Rᵗˣ^2 + Rᵗˣʸᶻ^2 + Rᵗʸ^2 - Rᵗᶻ^2 - Rʸˣ^2 + Rˣᶻ^2 - Rᶻʸ^2, -2R¹ * Rᶻʸ - 2Rᵗˣ * Rᵗˣʸᶻ + 2Rᵗʸ * Rᵗᶻ + 2Rʸˣ * Rˣᶻ - ] + ) - v′ᶻ = v ⋅ @SVector [ + v′ᶻ = v ⋅ SVector( 2R¹ * Rᵗᶻ - 2Rᵗˣ * Rˣᶻ - 2Rᵗˣʸᶻ * Rʸˣ + 2Rᵗʸ * Rᶻʸ, -2R¹ * Rˣᶻ + 2Rᵗˣ * Rᵗᶻ - 2Rᵗˣʸᶻ * Rᵗʸ + 2Rʸˣ * Rᶻʸ, 2R¹ * Rᶻʸ + 2Rᵗˣ * Rᵗˣʸᶻ + 2Rᵗʸ * Rᵗᶻ + 2Rʸˣ * Rˣᶻ, R¹^2 - Rᵗˣ^2 + Rᵗˣʸᶻ^2 - Rᵗʸ^2 + Rᵗᶻ^2 + Rʸˣ^2 - Rˣᶻ^2 - Rᶻʸ^2 - ] - - v′ = @SVector [v′ᵗ, v′ˣ, v′ʸ, v′ᶻ] + ) + + v′ = SVector(v′ᵗ, v′ˣ, v′ʸ, v′ᶻ) return v′ end @@ -244,20 +337,22 @@ end """ ℂconj(Λ::Lorentz{T}) → Lorentz{T} + ℂconj(q::AbstractQuaternion{Complex{T}}) → typeof(q) Component-wise complex conjugate of `Λ`: conjugate each complex coefficient `(w, x, y, z) → -(w̄, x̄, ȳ, z̄)`. +(w̄, x̄, ȳ, z̄)`. The result has the same type as the input, and is not renormalized. This is distinct from the GA reverse, which is `conj(Λ)` and just negates the quaternion "vector" part. For `Λ = R*B` with `R` a pure rotation and `B` a pure boost, `ℂconj(Λ) = R * B⁻¹`, since `ℂconj(B) = B⁻¹` for pure boosts and `ℂconj(R) = R` for real rotors. """ -ℂconj(Λ::Lorentz{T}) where {T<:Real} = Rotor{Complex{T}}( +ℂconj(Λ::AbstractQuaternion{Complex{T}}) where {T<:Real} = typeof(Λ)( conj(Λ[1]), conj(Λ[2]), conj(Λ[3]), conj(Λ[4]) ) """ ℂreal(Λ::Lorentz{T}) → Quaternion{T} + ℂreal(q::AbstractQuaternion{Complex{T}}) → Quaternion{T} Complex-real part of `Λ`: `Quaternion(real(Λ[1]), real(Λ[2]), real(Λ[3]), real(Λ[4]))`. @@ -274,8 +369,9 @@ may be complex; this function returns a full quaternion, with all components rea """ ℂimag(Λ::Lorentz{T}) → Quaternion{T} + ℂimag(q::AbstractQuaternion{Complex{T}}) → Quaternion{T} -Imaginary-part of `Λ`: `Quaternion(imag(Λ[1]), imag(Λ[2]), imag(Λ[3]), imag(Λ[4]))`. +Complex-imaginary part of `Λ`: `Quaternion(imag(Λ[1]), imag(Λ[2]), imag(Λ[3]), imag(Λ[4]))`. For `Λ = R*B` where `R` is a pure rotation and `B` is a pure boost with rapidity `η` in direction `n̂`, this equals `sinh(η/2)*R*n̂`. @@ -291,10 +387,11 @@ components real. """ ℂreim(Λ::Lorentz{T}) → (Quaternion{T}, Quaternion{T}) + ℂreim(q::AbstractQuaternion{Complex{T}}) → (Quaternion{T}, Quaternion{T}) Return `(ℂreal(Λ), ℂimag(Λ))` as a single call. """ -ℂreim(Λ::Lorentz{T}) where {T<:Real} = (ℂreal(Λ), ℂimag(Λ)) +ℂreim(Λ::AbstractQuaternion{Complex{T}}) where {T<:Real} = (ℂreal(Λ), ℂimag(Λ)) # --------------------------------------------------------------------------- # Polar decomposition @@ -303,7 +400,9 @@ Return `(ℂreal(Λ), ℂimag(Λ))` as a single call. """ RB(Λ::Lorentz{T}) → (R::Rotor{T}, B::Lorentz{T}) -Polar decomposition `Λ = R * B`: pure rotation `R` followed by pure boost `B`. +Polar decomposition `Λ = R * B` into a pure rotation `R` and a pure boost `B`. When `Λ` +acts on a vector, the boost `B` is applied first, and then the rotation `R`, so that `Λ(v) ≈ +Lorentz(R)(B(v))`. !!! note "Double cover" Since `Spin⁺(3,1)` is a double cover of `SO⁺(3,1)`, both `(R, B)` and `(-R, -B)` @@ -321,7 +420,9 @@ Since `cosh(η/2)` is 1 for no boost, and grows smoothly with `η`, we can find simply by normalizing the complex-real part of `Λ`. And since the norm of `R` is 1, we can find `cosh(η/2)` as the magnitude of the complex-real part of `Λ`. Then, we find `sinh(η/2)*n̂` simply by multiplying the complex-imaginary part of `Λ` by `inv(R)`, and -reconstruct `B` simply by adding the result to `cosh(η/2)`. +reconstruct `B` simply by adding the result to `cosh(η/2)`. The boost `B` is constructed +directly from these components, without renormalization by the spinor norm, which would +introduce relative errors of order `eps(T) * cosh(η)` at large rapidity. See also [`BR`](@ref), [`vR`](@ref), and [`Rv`](@ref) for similar forms, and [`KAN`](@ref) for the Iwasawa decomposition. @@ -329,14 +430,16 @@ for the Iwasawa decomposition. function RB(Λ::Lorentz{T}) where {T<:Real} ℜΛ, ℑΛ = ℂreim(Λ) R = rotor(ℜΛ) - B = Lorentz(abs(ℜΛ) + im * (conj(R) * ℑΛ)) + B = Lorentz{T}(abs(ℜΛ) + im * (conj(R) * ℑΛ)) return R, B end """ BR(Λ::Lorentz{T}) → (B::Lorentz{T}, R::Rotor{T}) -Polar decomposition `Λ = B * R`: pure boost `B` followed by pure rotation `R`. +Polar decomposition `Λ = B * R` into a pure boost `B` and a pure rotation `R`. When `Λ` +acts on a vector, the rotation `R` is applied first, and then the boost `B`, so that `Λ(v) ≈ +B(Lorentz(R)(v))`. The algorithm here is the same as for [`RB`](@ref), but with the order of multiplication by `inv(R)` reversed. @@ -347,7 +450,7 @@ decomposition. function BR(Λ::Lorentz{T}) where {T<:Real} ℜΛ, ℑΛ = ℂreim(Λ) R = rotor(ℜΛ) - B = Lorentz(abs(ℜΛ) + im * (ℑΛ * conj(R))) + B = Lorentz{T}(abs(ℜΛ) + im * (ℑΛ * conj(R))) return B, R end @@ -356,7 +459,7 @@ end Return the pure rotation `R` and (vectorial) boost velocity `v⃗` such that `Λ = R * Boost(η, v̂)` where `η = atanh(β)` is the associated rapidity with `β = norm(v⃗)` as the boost -parameter. +parameter. When `Λ` acts on a vector, the boost is applied first, and then the rotation. The boost spinor is `B = cosh(η/2) + im*v̂*sinh(η/2)` in the quaternionic encoding. Note that `v̂` is the unit vector in the direction of `v⃗`. We can immediately obtain the values @@ -371,16 +474,23 @@ use half-angle formulas to show that = \frac{2 \cosh(η/2)}{2\cosh^2(η/2) - 1}, ``` where the last equality uses the double-angle identity ``\cosh(η) = 2\cosh^2(η/2) - 1``. -The last form is made up of entirely of the scalar component of `B`, does not involve any +The last form is made up entirely of the scalar component of `B`, does not involve any cancellation or division by small numbers, and avoids computing the norm of the vector part. +!!! note "Large rapidities" + The velocity cannot represent large rapidities accurately, because `β = tanh(η)` + approaches 1 exponentially quickly. The rapidity reconstructed from `v⃗` loses relative + accuracy roughly like `eps(T) * exp(2η)`, and in `Float64`, `β` rounds to `1` for `η ≳ + 19`, so that `Boost(v⃗)` is inaccurate or throws. For large boosts, use [`RB`](@ref) or + [`BR`](@ref), which return the boost as a `Lorentz` rotor. + See also [`vR`](@ref), [`RB`](@ref), and [`BR`](@ref) for similar forms, and [`KAN`](@ref) for the Iwasawa decomposition. """ function Rv(Λ::Lorentz{T}) where {T<:Real} R, B = RB(Λ) v̂sinhη╱2 = QuatVec(ℂimag(B)) # equal to v̂ * sinh(η/2) - coshη╱2 = real(real(B)) # inner `real`` gets scalar part, outer takes ℂreal + coshη╱2 = real(real(B)) # inner `real` gets scalar part, outer takes ℂreal v⃗ = v̂sinhη╱2 * (2coshη╱2 / (2coshη╱2^2 - 1)) return R, v⃗ end @@ -388,8 +498,9 @@ end """ vR(Λ::Lorentz{T}) → (v⃗::QuatVec{T}, R::Rotor{T}) -Return the boost velocity `v⃗` and pure rotation `R` such that `Λ = Boost(η, v̂) * R`. See -[`Rv`](@ref) for more details. +Return the boost velocity `v⃗` and pure rotation `R` such that `Λ = Boost(η, v̂) * R`. When +`Λ` acts on a vector, the rotation is applied first, and then the boost. See [`Rv`](@ref) +for more details, including the loss of accuracy at large rapidities. See also [`BR`](@ref) and [`RB`](@ref) for similar forms, and [`KAN`](@ref) for the Iwasawa decomposition. @@ -397,7 +508,7 @@ decomposition. function vR(Λ::Lorentz{T}) where {T<:Real} B, R = BR(Λ) v̂sinhη╱2 = QuatVec(ℂimag(B)) # equal to v̂ * sinh(η/2) - coshη╱2 = real(real(B)) # inner `real`` gets scalar part, outer takes ℂreal + coshη╱2 = real(real(B)) # inner `real` gets scalar part, outer takes ℂreal v⃗ = v̂sinhη╱2 * (2coshη╱2 / (2coshη╱2^2 - 1)) return v⃗, R end @@ -407,7 +518,7 @@ end # --------------------------------------------------------------------------- @doc raw""" - KAN(Λ::Lorentz{T}) → (Rₖ, Rₐ, Rₙ) + KAN(Λ::Lorentz{T}) → (Rₖ::Rotor{T}, Rₐ::Lorentz{T}, Rₙ::Lorentz{T}) Compute the Iwasawa ``KAN`` decomposition of the Lorentz transformation `Λ`, returning the three factors such that `Λ = Rₖ * Rₐ * Rₙ`, where @@ -416,6 +527,20 @@ three factors such that `Λ = Rₖ * Rₐ * Rₙ`, where - `Rₐ ∈ A` is a boost along the ``𝐳`` axis, `Rₐ = cosh(φₐ/2) + sinh(φₐ/2) 𝐭𝐳`, and - `Rₙ ∈ N` is a null rotation fixing the null vector ``ℓ = (𝐭+𝐳)/√2``. +As with [`RB`](@ref) and [`BR`](@ref), the rotation `Rₖ` is returned as a real `Rotor{T}`, +and can be converted with `Lorentz(Rₖ)`, while `Rₐ` and `Rₙ` are returned as `Lorentz{T}` +rotors. When `Λ` acts on a vector, `Rₙ` is applied first, then `Rₐ`, and then `Rₖ`. + +!!! note "Conditioning" + The decomposition is intrinsically ill-conditioned when the rapidity ``φₐ`` of the ``A`` + factor is large and negative (a large boost toward ``-𝐳``). In that case, the errors + in `Rₖ` grow roughly like `eps(T) * exp(|φₐ|)`, and those in `Rₙ` like `eps(T) * + exp(2|φₐ|)`. This sensitivity is a property of the decomposition itself, rather than of + the algorithm used here. More generally, when the total rapidity `η` of `Λ` is large, + rounding its components to `T` leaves a spinor norm that differs from 1 by about `eps(T) + * exp(η)`. No exact factorization of such a `Λ` exists, so the product `Rₖ * Rₐ * Rₙ` + can differ from `Λ` by a relative error of that order. + See the [`KAN` decomposition section](@ref iwasawa-kan) of the spacetime-algebra documentation for a full discussion and derivation of the method used in this function. @@ -430,14 +555,16 @@ function KAN(Λ::Lorentz{T}) where {T<:Real} ℂℜΛu₊ = ℂreal(Λ * u₊) Rₖ = rotor(ℂℜΛu₊) # We avoid transcendental functions `ln`, `sinh`, and `cosh` by using the structure of - # the following product to read off just the relevant components. - RₐRₙ = conj(Rₖ) * Λ + # the following product to read off just the relevant components. The products are + # formed in plain `Quaternion` arithmetic, so that they are not renormalized, which + # would lose accuracy at large rapidity. + RₐRₙ = Quaternion(conj(Rₖ)) * Quaternion(Λ) coshφ╱2, sinhφ╱2 = real(RₐRₙ.w), imag(RₐRₙ.z) - Rₐ = coshφ╱2 + sinhφ╱2 * 𝐭𝐳 + Rₐ = Lorentz{T}(coshφ╱2, 0, 0, im * sinhφ╱2) # Rather than returning the raw `Rₐ⁻¹ * RₐRₙ`, which may have accumulated roundoff # errors, we project that result onto the null-rotation sector by averaging 𝐢 and 𝐣 # components, and setting 𝟏 and 𝐤 components to their exact values. - Rₙraw = conj(Rₐ) * RₐRₙ + Rₙraw = Quaternion(conj(Rₐ)) * RₐRₙ ξˣ╱2sqrt2 = (imag(Rₙraw.x) - real(Rₙraw.y)) / 2 ξʸ╱2sqrt2 = (imag(Rₙraw.y) + real(Rₙraw.x)) / 2 Rₙ = Lorentz{T}(1, ξʸ╱2sqrt2 + im * ξˣ╱2sqrt2, -ξˣ╱2sqrt2 + im * ξʸ╱2sqrt2, 0) diff --git a/src/Quaternionic.jl b/src/Quaternionic.jl index 8fd0f747..fc4bc839 100644 --- a/src/Quaternionic.jl +++ b/src/Quaternionic.jl @@ -1,10 +1,9 @@ module Quaternionic -import LinearAlgebra: LinearAlgebra, Symmetric, eigen, norm, normalize, (⋅) +import LinearAlgebra: LinearAlgebra, Symmetric, eigen, norm, normalize, (⋅), (×) import GenericLinearAlgebra import PrecompileTools: PrecompileTools, @compile_workload, @setup_workload import StaticArrays: StaticArrays, @SMatrix, @SVector, SA, SMatrix, SVector -import LaTeXStrings import Random: AbstractRNG, default_rng # The `public` keyword is a syntax error before Julia 1.11, so we wrap it in a macro that @@ -26,6 +25,7 @@ export Rotor, rotor, RotorF64, RotorF32, RotorF16 export QuatVec, quatvec, QuatVecF64, QuatVecF32, QuatVecF16 export components, basetype @public value, iszerovalue +@public dominant_eigenvector @public ℂconj, ℂreal, ℂimag, ℂreim @public RB, BR, Rv, vR, KAN export (⋅), (×), (×̂), normalize, norm @@ -38,7 +38,7 @@ export from_float_array, to_float_array, export distance, distance2 export align export Lorentz, Boost, ga_components -export unflip, unflip!, slerp, squad +export unflip, unflip!, slerp, squad, squad! export ∂log, log∂log, ∂exp, exp∂exp, slerp∂slerp, slerp∂slerp∂τ, squad∂squad∂t export precessing_nutating_example @@ -70,14 +70,16 @@ end @static if !isdefined(Base, :get_extension) # COV_EXCL_START + # Julia 1.6 through 1.8 do not support package extensions, so Requires loads them. + # Zygote 0.7, Enzyme 0.13, and Mooncake need Julia 1.10 or later, so their extensions + # are not listed here, and neither is the ReverseDiff extension, which is written to be + # loaded only as a package extension. function __init__() - @require ChainRules="082447d4-558c-5d27-93f4-14fc19e9eca2" include("../ext/QuaternionicChainRulesExt.jl") - @require ChainRulesCore="d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" include("../ext/QuaternionicChainRulesCoreExt.jl") + @require ChainRulesCore="d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4" include("../ext/QuaternionicChainRulesCoreExt/QuaternionicChainRulesCoreExt.jl") @require FastDifferentiation="eb9bf01b-bf85-4b60-bf87-ee5de06c00be" include("../ext/QuaternionicFastDifferentiationExt.jl") @require ForwardDiff="f6369f11-7733-5829-9624-2563aa707210" include("../ext/QuaternionicForwardDiffExt.jl") @require Symbolics="0c5d862f-8b57-4792-8d23-62f2024744c7" include("../ext/QuaternionicSymbolicsExt.jl") @require Latexify="23fbe1c1-3f47-55db-b15f-69d7ec21a316" include("../ext/QuaternionicLatexifyExt.jl") - @require Zygote="e88e6eb3-aa80-5325-afca-941959d7151f" include("../ext/QuaternionicZygoteExt.jl") end # COV_EXCL_STOP diff --git a/src/algebra.jl b/src/algebra.jl index 7e8d5193..fdd6f504 100644 --- a/src/algebra.jl +++ b/src/algebra.jl @@ -54,16 +54,47 @@ function Base.:*(q::Q1, p::Q2) where {Q1<:AbstractQuaternion, Q2<:AbstractQuater end +# There is deliberately no shortcut returning `one` when `p == q`. Such a branch would +# return a constant, so AD backends whose `==` compares only primal values (Enzyme, +# Mooncake, ReverseDiff, and ForwardDiff 0.10) would lose the derivative there. It would +# also make the return type depend on the values, and it would fail for symbolic types +# whose `==` does not return a `Bool`. Instead, each vector component is written as a sum +# of two differences, `(a*b - c*d) + (e*f - g*h)`, in which the terms of each difference +# are identical products when `p == q`. Both differences then vanish exactly in +# floating-point arithmetic. The scalar part sums the products in the same order as +# `abs2`, so `q / q` is exactly one for real floating-point components. (For complex +# components, the final complex division may still round, by about one ulp.) +# +# For real floating-point components, `abs2(p)` overflows when `abs(p)` exceeds about +# `sqrt(floatmax)`, and it underflows to a subnormal number or zero when `abs(p)` falls below +# about `sqrt(floatmin)`. In that case both `q` and `p` are multiplied by a power of two that +# brings the largest component of `p` near 1. This scaling is exact, so it changes neither +# the quotient nor the exactness of `q / q`. The power is clamped to the range of normal +# numbers, so that it stays finite when the components of `p` are subnormal; the recursive +# call then scales again if one step was not enough. The test is applied to `value(den)`, +# so that dual numbers are rescaled in the same way as the floats they contain. It begins +# with type checks that the compiler resolves, so it is skipped entirely for `Rotor`s, whose +# `abs2` is identically one, and for other element types, such as complex and symbolic +# types. The `maximum` is evaluated, using values only, when the scaling is needed. function Base.:/(q::Q1, p::Q2) where {Q1<:AbstractQuaternion, Q2<:AbstractQuaternion} - if p == q - return one(promote_type(Q1, float(Q2))) - end den = abs2(p) + if p isa Union{Quaternion, QuatVec} && value(den) isa AbstractFloat + d = value(den) + T = typeof(d) + if !(floatmin(T) ≤ d < T(Inf)) + m = maximum(x -> abs(value(x)), components(p)) + if !iszero(m) && isfinite(m) + k = clamp(-exponent(m), exponent(floatmin(T)), exponent(floatmax(T))) + σ = ldexp(one(T), k) + return wrapper(Q1, Val(/), Q2)(components((σ * q) / (σ * p))) + end + end + end wrapper(Q1, Val(/), Q2)( - (+q[1]*p[1] + q[2]*p[2] + q[3]*p[3] + q[4]*p[4]) / den, - (-q[1]*p[2] + q[2]*p[1] - q[3]*p[4] + q[4]*p[3]) / den, - (-q[1]*p[3] + q[2]*p[4] + q[3]*p[1] - q[4]*p[2]) / den, - (-q[1]*p[4] - q[2]*p[3] + q[3]*p[2] + q[4]*p[1]) / den + (q[1]*p[1] + q[2]*p[2] + q[3]*p[3] + q[4]*p[4]) / den, + ((q[2]*p[1] - q[1]*p[2]) + (q[4]*p[3] - q[3]*p[4])) / den, + ((q[3]*p[1] - q[1]*p[3]) + (q[2]*p[4] - q[4]*p[2])) / den, + ((q[4]*p[1] - q[1]*p[4]) + (q[3]*p[2] - q[2]*p[3])) / den ) end @@ -74,7 +105,22 @@ let S = Number Base.:*(s::$S, p::Q) where {Q<:AbstractQuaternion} = wrapper($S, Val(*), Q)(s*components(p)) Base.:/(p::Q, s::$S) where {Q<:AbstractQuaternion} = wrapper(Q, Val(/), $S)(components(p)/s) function Base.:/(s::$S, p::Q) where {Q<:AbstractQuaternion} - f = s / abs2(p) + den = abs2(p) + # As in quaternion division above, `s` and `p` are rescaled by a power of two + # when `abs2(p)` overflows or underflows. + if p isa Union{Quaternion, QuatVec} && value(den) isa AbstractFloat + d = value(den) + T = typeof(d) + if !(floatmin(T) ≤ d < T(Inf)) + m = maximum(x -> abs(value(x)), components(p)) + if !iszero(m) && isfinite(m) + k = clamp(-exponent(m), exponent(floatmin(T)), exponent(floatmax(T))) + σ = ldexp(one(T), k) + return wrapper($S, Val(/), Q)(components((σ * s) / (σ * p))) + end + end + end + f = s / den wrapper($S, Val(/), Q)(p[1] * f, -p[2] * f, -p[3] * f, -p[4] * f) end end @@ -119,6 +165,14 @@ Note that this function is not very commonly used, except as a quick way to determine whether the two quaternions are more anti-parallel than parallel, for functions like [`unflip`](@ref). +This method extends `LinearAlgebra.dot`, of which `⋅` is an alias, and returns only the +componentwise sum `p[1]*q[1] + p[2]*q[2] + p[3]*q[3] + p[4]*q[4]`, which is the Euclidean +inner product for real components. Generic linear-algebra code written for +`Complex` numbers usually assumes instead that the `dot` of two scalars is the full product +`conj(p) * q`. Consequently, functions that rely on that assumption, such as `x' * y` for +vectors, `qr`, `svd`, and least-squares solutions with `\`, do not give the quaternionic +results for arrays of quaternions. + This can be typed as `\cdot` in a Julia-aware editor. """ @inline function LinearAlgebra.:⋅(p::AbstractQuaternion, q::AbstractQuaternion) @@ -127,13 +181,17 @@ end @doc raw""" a × b + cross(a, b) Return the cross product of two pure-vector quaternions. Equal to ½ of the commutator product `a*b-b*a`. +This extends `LinearAlgebra.cross`, of which `×` is an alias, so the same function is +used whether `×` comes from `Quaternionic` or from `LinearAlgebra`. + This can be typed as `\times` in a Julia-aware editor. """ -@inline function ×(a::QuatVec, b::QuatVec) +@inline function LinearAlgebra.:×(a::QuatVec, b::QuatVec) quatvec( a[3] * b[4] - a[4] * b[3], a[4] * b[2] - a[2] * b[4], @@ -145,8 +203,13 @@ end a ×̂ b Return the *direction* of the cross product between `a` and `b`; the normalized vector along -[`a×b`](@ref Quaternionic.:×) — unless the magnitude is zero, in which case the zero vector -is returned. +[`a×b`](@ref LinearAlgebra.:×) — unless the magnitude is zero, in which case the zero vector +is returned. Both cases give the same element type, which is a floating-point type for +integer or rational inputs. + +For complex components, the magnitude is the spinor norm computed by [`absvec`](@ref), which +can vanish for a nonzero null vector. Such a vector cannot be normalized, so it is returned +unchanged. This can be typed as `\times\hat` in a Julia-aware editor. """ @@ -154,7 +217,9 @@ This can be typed as `\times\hat` in a Julia-aware editor. axb = a × b av = absvec(axb) if iszerovalue(av) - return axb + # Dividing by one gives this branch the same element type as the other branch, + # which matters when `a` and `b` have integer or rational components. + return axb / one(av) else return axb / av end @@ -174,6 +239,13 @@ This extends `LinearAlgebra.normalize` for quaternion types. @inline LinearAlgebra.normalize(q::AbstractQuaternion) = q / abs(q) @inline LinearAlgebra.normalize(q::Rotor) = rotor(q) +# The function-call syntax `R(v)` computes the sandwich product `R * v * conj(R)`. Both +# methods below use the same homogeneous formula for the vector part, which is valid for +# any `R`, whatever its norm. The product equals the rotation `R * v * inv(R)` only when +# `abs(R) == 1`; otherwise it is that rotation scaled by `abs2(R)`. The `Rotor` method +# accepts only a `QuatVec`, and returns a `QuatVec`. The `Quaternion` method sets the +# scalar part to `abs2(R) * v[1]`, and wraps the result in the wrapper type of `v`, which +# renormalizes the result when `v` is a `Rotor`. function (R::Rotor)(v::QuatVec) quatvec(SA[ false, diff --git a/src/alignment.jl b/src/alignment.jl index fa9afc10..45b4893f 100644 --- a/src/alignment.jl +++ b/src/alignment.jl @@ -1,35 +1,35 @@ @doc raw""" - align(a⃗, b⃗, [w]) + align(a⃗::AbstractArray{<:QuatVec}, b⃗::AbstractArray{<:QuatVec}, [w]) -Solve [Wahba's problem](https://en.wikipedia.org/wiki/Wahba%27s_problem), -finding a rotation that aligns the set of points `a⃗` to a corresponding set of -points `b⃗` by minimizing the distance between the first set and the rotated -second set. +Solve [Wahba's problem](https://en.wikipedia.org/wiki/Wahba%27s_problem), finding the rotor +`R` that best rotates the set of points `b⃗` onto a corresponding set of points `a⃗`, so +that `R * b⃗[i] * R⁻¹ ≈ a⃗[i]`. -Here, `a⃗` and `b⃗` must be equally sized arrays of `QuatVec`s. If present, `w` -must be an equally sized array of real numbers; if not, it is taken to be 1. +Here, `a⃗` and `b⃗` must be equally sized arrays of `QuatVec`s with real components. If +present, `w` must be an equally sized array of real numbers; if not, it is taken to be 1. We define the loss function ```math L(ℛ) ≔ Σᵢ wᵢ ‖a⃗ᵢ - ℛ b⃗ᵢ‖² ``` -where ``ℛ`` is a rotation operator, and return the quaternion corresponding to -the optimal ``ℛ`` that minimizes this function. +where ``ℛ`` is a rotation operator, and return the `Rotor` corresponding to the optimal +``ℛ`` that minimizes this function. -Note that it is possible that the points do not uniquely determine a rotation — -as when one or both sets of points is rotationally symmetric. In that case, the -loss function ``L(ℛ)`` will still be minimized and the points will still be -optimally aligned by the output quaternion, but that quaternion will not be -unique. +Since `R` and `-R` represent the same rotation, the sign of the result is fixed by +convention: its scalar part is positive, or, if the scalar part is zero, its first nonzero +component is positive. + +Note that it is possible that the points do not uniquely determine a rotation — as when one +or both sets of points is rotationally symmetric. In that case, the loss function ``L(ℛ)`` +will still be minimized and the points will still be optimally aligned by the output rotor, +but that rotor will not be unique. # Notes -In their book [_Fundamentals of Spacecraft Attitude Determination and Control_ -(2014)](https://doi.org/10.1007/978-1-4939-0802-8), Markley and Crassidis say -that "Davenport’s method remains the best method for solving Wahba’s problem". -This method provides the optimal quaternion as the dominant eigenvector (the one -with the largest eigenvalue) of a certain matrix. We start by defining the -supplementary matrix +[MarkleyCrassidis_2014](@citet) say that "Davenport’s method remains the best method for +solving Wahba’s problem". This method provides the optimal quaternion as the dominant +eigenvector (the one with the largest eigenvalue) of a certain matrix. We start by defining +the supplementary matrix ```math S ≔ Σᵢ wᵢ a⃗ᵢ b⃗ᵢᵀ ``` @@ -44,75 +44,90 @@ S₁₂-S₂₁ Then the key matrix is ```math M ≔ \begin{bmatrix} -S + Sᵀ - (\mathrm{tr}S)\, I₃ & s⃗ \\ -s⃗ᵀ & \mathrm{tr}S -\end{bmatrix} +\mathrm{tr}S & -s⃗ᵀ \\ +-s⃗ & S + Sᵀ - (\mathrm{tr}S)\, I₃ +\end{bmatrix}. ``` -It is possible for this matrix to have degenerate eigenvalues, corresponding to -cases where the points do not uniquely determine the rotation, as described -above. +If ``(w, x, y, z)`` is the dominant eigenvector of this matrix, the result is the rotor ``w ++ x𝐢 + y𝐣 + z𝐤``. (Markley and Crassidis order the components with the scalar last and +use the opposite sign for ``s⃗``, because their convention for quaternion multiplication +differs from the one used here.) It is possible for this matrix to have degenerate +eigenvalues, corresponding to cases where the points do not uniquely determine the rotation, +as described above. + +This method works with any real float type, and the result has the same element type as the +input. It computes the eigen-decomposition of `M`, which LAPACK provides only for +`Float16`, `Float32`, and `Float64`; for anything else we rely on `GenericLinearAlgebra`, as +[`from_rotation_matrix`](@ref) does, and which `Quaternionic` depends on directly so that +you do not have to load it yourself. -This method works with any float type. It computes the -eigen-decomposition of `M`, which LAPACK provides only for `Float16`, -`Float32`, and `Float64`; for anything else we rely on -`GenericLinearAlgebra`, as [`from_rotation_matrix`](@ref) does, and -which `Quaternionic` depends on directly so that you do not have to -load it yourself. +# References + +* [MarkleyCrassidis_2014](@cite) F. L. Markley and J. L. Crassidis, _Fundamentals of + Spacecraft Attitude Determination and Control_ (Springer, New York, 2014) """ function align(a⃗::AbstractArray{<:QuatVec}, b⃗::AbstractArray{<:QuatVec}, w::AbstractArray{<:Real}) - # This is Eq. (5.11) from Markley and Crassidis - S = sum(w[i] * vec(a⃗[i]) * vec(b⃗[i])' for i in eachindex(a⃗, b⃗, w)) + # This is Eq. (5.11) from Markley and Crassidis. Each term of the sum is built from + # static three-vectors, so that it stays on the stack. The parentheses prevent the + # product from being parsed as a three-argument `*`, which would allocate. + S = sum( + (w[i] * SVector(a⃗[i][2], a⃗[i][3], a⃗[i][4])) * + transpose(SVector(b⃗[i][2], b⃗[i][3], b⃗[i][4])) + for i in eachindex(a⃗, b⃗, w) + ) return _align_Wahba(S) end function align(a⃗::AbstractArray{<:QuatVec}, b⃗::AbstractArray{<:QuatVec}) # This is Eq. (5.11) from Markley and Crassidis - S = sum(vec(a⃗[i]) * vec(b⃗[i])' for i in eachindex(a⃗, b⃗)) + S = sum( + SVector(a⃗[i][2], a⃗[i][3], a⃗[i][4]) * + transpose(SVector(b⃗[i][2], b⃗[i][3], b⃗[i][4])) + for i in eachindex(a⃗, b⃗) + ) return _align_Wahba(S) end function _align_Wahba(S) - # This is Eq. (5.17) from Markley and Crassidis, modified to suit our - # conventions by flipping the sign of ``z``, and moving the final dimension - # to the first dimension. - M = Symmetric([ - S[1,1]+S[2,2]+S[3,3] S[3,2]-S[2,3] S[1,3]-S[3,1] S[2,1]-S[1,2] - S[3,2]-S[2,3] S[1,1]-S[2,2]-S[3,3] S[1,2]+S[2,1] S[1,3]+S[3,1] - S[1,3]-S[3,1] S[1,2]+S[2,1] -S[1,1]+S[2,2]-S[3,3] S[2,3]+S[3,2] - S[2,1]-S[1,2] S[1,3]+S[3,1] S[2,3]+S[3,2] -S[1,1]-S[2,2]+S[3,3] - ]) - # This extracts the dominant eigenvector, and interprets it as a Rotor. - # Note that `dominant_eigenvector` selects by eigen*value* rather than by - # position, because `eigen` guarantees no particular ordering across the - # various backends and the generic ones disagree. Routing through that - # helper is also what lets this work for element types LAPACK cannot - # handle: it avoids the LAPACK-only `eigen(M, n:n)` range form for those. - # `M` is deliberately a dense `Matrix` rather than an `SMatrix` — the - # generic `eigen` has no method for `Symmetric{Double64,<:SMatrix}`. - return rotor(dominant_eigenvector(M)...) + # This is Eq. (5.17) from Markley and Crassidis, modified to suit our conventions by + # flipping the sign of their vector `z` (the `s⃗` of the docstring), and moving the + # final dimension to the first dimension. The elements are given in column-major + # order. + M = Symmetric(SMatrix{4,4}( + S[1,1]+S[2,2]+S[3,3], S[3,2]-S[2,3], S[1,3]-S[3,1], S[2,1]-S[1,2], + S[3,2]-S[2,3], S[1,1]-S[2,2]-S[3,3], S[1,2]+S[2,1], S[1,3]+S[3,1], + S[1,3]-S[3,1], S[1,2]+S[2,1], -S[1,1]+S[2,2]-S[3,3], S[2,3]+S[3,2], + S[2,1]-S[1,2], S[1,3]+S[3,1], S[2,3]+S[3,2], -S[1,1]-S[2,2]+S[3,3] + )) + # This extracts the dominant eigenvector, and interprets it as a Rotor. Note that + # `dominant_eigenvector` selects by eigen*value* rather than by position, because + # `eigen` guarantees no particular ordering across the various backends, and it also + # handles element types that LAPACK cannot. + return positive_hemisphere(rotor(dominant_eigenvector(M)...)) end @doc raw""" - align(A, B, [w]) + align(A::AbstractArray{<:Rotor}, B::AbstractArray{<:Rotor}, [w]) -Find a `Rotor` that aligns the set of rotors `A` to a corresponding set `B` by -minimizing the distance between the first set and the rotated second set. +Find the `Rotor` `R` that best rotates the set of rotors `B` onto a +corresponding set `A`, so that `R * B[i] ≈ A[i]`, by minimizing the distance +between the first set and the rotated second set. -Here, `A` and `B` must be equally sized arrays of `AbstractQuaternion`s. If -present, `w` must be an equally sized array of real numbers; if not, it is -taken to be 1. We define the loss function +Here, `A` and `B` must be equally sized arrays of `Rotor`s. If present, `w` +must be an equally sized array of real numbers; if not, it is taken to be 1. We +define the loss function ```math L(R) ≔ Σᵢ wᵢ |Aᵢ - R Bᵢ|² ``` -where ``R`` is a `Rotor`, and return the quaternion corresponding to the optimal -``R`` that minimizes this function. +where ``R`` is a `Rotor`, and return the optimal ``R`` that minimizes this +function. Note that it is possible that the input data do not uniquely determine a rotor, -which will happen when sum below is zero. When this happens, the result will -contain `NaN`s, but no error will be raised. When the sum is very close to — -but not exactly — zero, the accuracy of the result will be limited. However, +which will happen when the sum below is zero. When this happens, the result +will contain `NaN`s, but no error will be raised. When the sum is very close to +— but not exactly — zero, the accuracy of the result will be limited. However, the loss function will not depend strongly on the result in that case. Be aware that this function _is_ sensitive to the signs of the input @@ -127,13 +142,13 @@ exponential, differentiating with respect to the argument of the exponential, and setting that argument to 0. This derivative should be 0 at the minimum. We have ```math -∂ⱼ Σᵢ wᵢ |Aᵢ - \exp[vⱼ] R Bᵢ|² → 2 ⟨ eⱼ R Σᵢ wᵢ Bᵢ Āᵢ ⟩₀ +∂ⱼ Σᵢ wᵢ |Aᵢ - \exp[vⱼ] R Bᵢ|² → -2 ⟨ eⱼ R Σᵢ wᵢ Bᵢ Āᵢ ⟩₀ ``` where → denotes taking ``vⱼ→0``, the symbol ``⟨⟩₀`` denotes taking the scalar part, and ``eⱼ`` is the unit quaternionic vector in the ``j`` direction. The only way for this quantity to be zero for each choice of ``j`` is if ```math -R Σᵢ wᵢ Bᵢ Āᵢ +R Σᵢ wᵢ Bᵢ Āᵢ ``` is itself a pure scalar. This, in turn, can only happen if either (1) the sum is 0 or (2) if ``R`` is proportional to the _conjugate_ of the sum: @@ -141,7 +156,8 @@ is 0 or (2) if ``R`` is proportional to the _conjugate_ of the sum: R ∝ Σᵢ wᵢ Aᵢ B̄ᵢ ``` Now, since we want ``R`` to be a rotor, we simply define it to be the normalized -sum. +sum. The positive normalization makes the scalar in question positive, which +gives the minimum of the loss function rather than the maximum. """ function align(A::AbstractArray{<:Rotor}, B::AbstractArray{<:Rotor}, w::AbstractArray{<:Real}) diff --git a/src/base.jl b/src/base.jl index a9c3cb74..7e438bc0 100644 --- a/src/base.jl +++ b/src/base.jl @@ -10,19 +10,56 @@ function Base.rtoldefault(x::Union{T,Type{T}}, y::Union{S,Type{S}}, atol::Real) Base.rtoldefault(x, basetype(y), atol) end +# For complex components, `abs` returns the complex spinor norm, which cannot be compared +# with a tolerance, so Base's `isapprox(::Number, ::Number)` would throw. Instead, these +# methods compare the components as vectors, using the real Euclidean norm of the +# difference, just as `isapprox` does for vectors of complex numbers. +for (T1, T2) ∈ ( + (AbstractQuaternion{<:Complex}, AbstractQuaternion), + (AbstractQuaternion, AbstractQuaternion{<:Complex}), + (AbstractQuaternion{<:Complex}, AbstractQuaternion{<:Complex}), + (AbstractQuaternion{<:Complex}, Number), + (Number, AbstractQuaternion{<:Complex}), +) + @eval function Base.isapprox(q1::$T1, q2::$T2; kwargs...) + isapprox(components(quaternion(q1)), components(quaternion(q2)); kwargs...) + end +end + Base.:(==)(q1::AbstractQuaternion{<:Number}, q2::AbstractQuaternion{<:Number}) = (q1[1]==q2[1]) && (q1[2]==q2[2]) && (q1[3]==q2[3]) && (q1[4]==q2[4]) Base.:(==)(q::AbstractQuaternion{<:Number}, x::Number) = isreal(q) && real(q) == x Base.:(==)(x::Number, q::AbstractQuaternion) = isreal(q) && real(q) == x Base.isequal(q1::AbstractQuaternion, q2::AbstractQuaternion) = isequal(q1[1],q2[1]) && isequal(q1[2],q2[2]) && isequal(q1[3],q2[3]) && isequal(q1[4],q2[4]) -Base.:(==)(q1::QuatVec{<:Number}, q2::AbstractQuaternion{<:Number}) = (q1[2]==q2[2]) && (q1[3]==q2[3]) && (q1[4]==q2[4]) -Base.:(==)(q1::AbstractQuaternion{<:Number}, q2::QuatVec{<:Number}) = (q1[2]==q2[2]) && (q1[3]==q2[3]) && (q1[4]==q2[4]) +# A `QuatVec` has zero scalar part, so it equals another quaternion only if that quaternion +# also has zero scalar part, and it equals a number only if both are zero. The scalar part +# that a `QuatVec` stores is always zero, but these methods treat it as zero regardless. +Base.:(==)(q1::QuatVec{<:Number}, q2::AbstractQuaternion{<:Number}) = iszero(q2[1]) && (q1[2]==q2[2]) && (q1[3]==q2[3]) && (q1[4]==q2[4]) +Base.:(==)(q1::AbstractQuaternion{<:Number}, q2::QuatVec{<:Number}) = iszero(q1[1]) && (q1[2]==q2[2]) && (q1[3]==q2[3]) && (q1[4]==q2[4]) Base.:(==)(q1::QuatVec{<:Number}, q2::QuatVec{<:Number}) = (q1[2]==q2[2]) && (q1[3]==q2[3]) && (q1[4]==q2[4]) -Base.:(==)(q::QuatVec{<:Number}, x::Number) = false -Base.:(==)(x::Number, q::QuatVec) = false -Base.isequal(q1::AbstractQuaternion, q2::QuatVec) = isequal(q1[2],q2[2]) && isequal(q1[3],q2[3]) && isequal(q1[4],q2[4]) -Base.isequal(q1::QuatVec, q2::AbstractQuaternion) = isequal(q1[2],q2[2]) && isequal(q1[3],q2[3]) && isequal(q1[4],q2[4]) +Base.:(==)(q::QuatVec{<:Number}, x::Number) = iszero(q[2]) && iszero(q[3]) && iszero(q[4]) && iszero(x) +Base.:(==)(x::Number, q::QuatVec) = iszero(q[2]) && iszero(q[3]) && iszero(q[4]) && iszero(x) + +# `isequal` must agree with `hash`, which hashes all four components and hashes a quaternion +# with zero vector part like its scalar part. So, as for `Complex`, signed zeros are +# distinguished, NaN equals NaN, and a quaternion is `isequal` to a number only if its +# vector components are positive zeros and its scalar part is `isequal` to the number. The +# scalar part of a `QuatVec` is a positive zero. The methods comparing with a number are +# restricted to the standard number types, because packages such as Symbolics define +# `isequal` between their own types and any `Number`, which would otherwise be ambiguous. +const StandardNumber = Union{AbstractFloat,Integer,Rational,AbstractIrrational,Complex} +Base.isequal(q1::AbstractQuaternion, q2::QuatVec) = isequal(q1[1],zero(q1[1])) && isequal(q1[2],q2[2]) && isequal(q1[3],q2[3]) && isequal(q1[4],q2[4]) +Base.isequal(q1::QuatVec, q2::AbstractQuaternion) = isequal(zero(q2[1]),q2[1]) && isequal(q1[2],q2[2]) && isequal(q1[3],q2[3]) && isequal(q1[4],q2[4]) Base.isequal(q1::QuatVec, q2::QuatVec) = isequal(q1[2],q2[2]) && isequal(q1[3],q2[3]) && isequal(q1[4],q2[4]) +Base.isequal(q::AbstractQuaternion, x::StandardNumber) = isequal(q[1],x) && isequal(q[2],zero(q[2])) && isequal(q[3],zero(q[3])) && isequal(q[4],zero(q[4])) +Base.isequal(x::StandardNumber, q::AbstractQuaternion) = isequal(q, x) +Base.isequal(q::QuatVec, x::StandardNumber) = isequal(zero(x),x) && isequal(q[2],zero(q[2])) && isequal(q[3],zero(q[3])) && isequal(q[4],zero(q[4])) + +# Note that, for a quaternion with complex components, `isreal` checks only that the vector +# part is zero; the scalar part may be complex. This matches `real(q)`, which returns the +# scalar part `q[1]`, and `q == x` for a number `x`, which compares `x` with that scalar +# part. In the spacetime-algebra reading of complex quaternions, such an element is the sum +# of a scalar and a pseudoscalar. Base.isreal(q::AbstractQuaternion{T}) where {T<:Number} = iszero(q[2]) && iszero(q[3]) && iszero(q[4]) Base.isinteger(q::AbstractQuaternion{T}) where {T<:Number} = isreal(q) && isinteger(real(q)) @@ -42,6 +79,7 @@ derivative. For nested types, such as the nested dual numbers used to compute h derivatives, this should strip every level of nesting. """ value(x) = x +value(z::Complex) = complex(value(real(z)), value(imag(z))) """ iszerovalue(x) @@ -67,6 +105,14 @@ iszerovalue(q::AbstractQuaternion) = iszerovalue(components(q)) iszerovalue(q::QuatVec) = iszerovalue(vec(q)) Base.round(q::QT, r::RoundingMode=RoundNearest; kwargs...) where {QT<:AbstractQuaternion} = QT(round.(components(q), r; kwargs...)) +# Rounding the components of a `Rotor` generally gives a quaternion whose norm is not 1, so +# the result is a `Quaternion`. +Base.round(q::Rotor{T}, r::RoundingMode=RoundNearest; kwargs...) where {T} = Quaternion(round.(components(q), r; kwargs...)) +# Rounding to an integer type, as for real numbers. This throws an `InexactError` unless +# the quaternion is real. (Julia 1.11 and later would reach the same result through a +# generic method in `Base`, but Julia 1.10 and earlier have none for `Number`s.) +Base.round(::Type{T}, q::AbstractQuaternion, r::RoundingMode=RoundNearest) where {T<:Integer} = + T(round(q, r)) Base.in(q::AbstractQuaternion, r::AbstractRange{<:Number}) = isreal(q) && real(q) in r @@ -87,33 +133,60 @@ const hash_0_imagx = hash(0, h_imagx) const hash_0_imagy = hash(0, h_imagy) const hash_0_imagz = hash(0, h_imagz) +# A quaternion with zero vector part hashes like its scalar part, as `isequal` requires. function Base.hash(q::AbstractQuaternion, h::UInt) # TODO: with default argument specialization, this would be better: # hash(q[1], h ⊻ hash(q[2], h ⊻ h_imagx) ⊻ hash(0, h ⊻ h_imagx) ⊻ hash(q[3], h ⊻ h_imagy) ⊻ hash(0, h ⊻ h_imagy) ⊻ hash(q[4], h ⊻ h_imagz) ⊻ hash(0, h ⊻ h_imagz)) hash(q[1], h ⊻ hash(q[2], h_imagx) ⊻ hash_0_imagx ⊻ hash(q[3], h_imagy) ⊻ hash_0_imagy ⊻ hash(q[4], h_imagz) ⊻ hash_0_imagz) end +# The scalar part of a `QuatVec` is hashed as a positive zero, matching `isequal`. +function Base.hash(q::QuatVec, h::UInt) + hash(zero(q[2]), h ⊻ hash(q[2], h_imagx) ⊻ hash_0_imagx ⊻ hash(q[3], h_imagy) ⊻ hash_0_imagy ⊻ hash(q[4], h_imagz) ⊻ hash_0_imagz) +end -function _pm_ascii(x) - # Utility function to print a component of a quaternion - s = "$x" +# These utility functions print a component `x` of a quaternion as a signed term, such as `" +# + 2.0"` or `" - 3.0"`, to which `show` appends the basis element. A component whose +# printed form contains an operator is wrapped in parentheses. In general, the sign must +# then stay inside the parentheses: moving the minus sign of the `Complex` number `-1 + 2im` +# outside would print `- (1 + 2im)`, which is `-1 - 2im`. Only for a single signed real +# number, as printed by the standard real types, may the sign be moved outside, as in `- +# (3.0e-9)`. Non-finite and `Bool` components are followed by `*`, as in `show` for +# `Complex`, so that `NaN*𝐢` and `true*𝐣` can be parsed back. The methods taking `io` +# print the component with the properties of `io`, such as `:compact`. Other types, such as +# symbolic types, are printed through the method taking only `x`, which extensions may +# specialize. +function _pm_ascii(s::AbstractString) if s[1] ∉ "+-" s = "+" * s end if occursin(r"[+^/-]", s[2:end]) - s = " " * s[1] * " " * "(" * s[2:end] * ")" + s = s[1] == '+' ? " + (" * s[2:end] * ")" : " + (" * s * ")" else s = " " * s[1] * " " * s[2:end] end s end +_pm_ascii(x) = _pm_ascii(string(x)) +_pm_ascii(io::IO, x) = _pm_ascii(x) +_pm_ascii(io::IO, x::Complex) = _pm_ascii(sprint(print, x; context=io)) +function _pm_ascii(io::IO, x::Union{AbstractFloat,Integer,Rational}) + s = sprint(print, x; context=io) + sign, s = s[1] == '-' ? ('-', s[2:end]) : ('+', s) + if occursin(r"[+^/-]", s) + s = "(" * s * ")" + elseif x isa Bool || !isfinite(x) + s = s * "*" + end + " " * sign * " " * s +end function Base.show(io::IO, q::AbstractQuaternion) print( io, q isa QuatVec ? "" : q[1], - _pm_ascii(q[2]), "𝐢", - _pm_ascii(q[3]), "𝐣", - _pm_ascii(q[4]), "𝐤" + _pm_ascii(io, q[2]), "𝐢", + _pm_ascii(io, q[3]), "𝐣", + _pm_ascii(io, q[4]), "𝐤" ) end @@ -123,8 +196,6 @@ function Base.show(io::IO, q::Rotor) print(io, ")") end -_pm_latex(x) = _pm_ascii(x) - function Base.read(s::IO, QT::Type{Q}) where {T<:Number, Q<:AbstractQuaternion{T}} w = read(s,T) diff --git a/src/conversion.jl b/src/conversion.jl index d5818a6c..592d3737 100644 --- a/src/conversion.jl +++ b/src/conversion.jl @@ -33,16 +33,20 @@ end """ to_float_array(A) + to_float_array(q) View a quaternion array as an array of numbers -The output array will have an extra initial dimension whose size is 4, because -successive indices in that dimension correspond to successive components of the -quaternion. +The output array will have an extra initial dimension whose size is 4, because successive +indices in that dimension correspond to successive components of the quaternion. The +element type of the output is the base type of the input quaternions; it is not converted to +a float type. -Note that this returns a view of the original data only if the base type of the -input array `isbitstype`; otherwise, a new array of that type must be created, -and the memory copied. +Note that this returns a view of the original data only if the base type of the input array +`isbitstype`; otherwise, a new array of that type must be created, and the memory copied. + +When the argument is a single quaternion `q`, the result is a new `Vector` of +its four components, converted to a float type as by `float(q)`. See also [`from_float_array`](@ref). """ @@ -59,7 +63,11 @@ function to_float_array(::Val{false}, A::AbstractArray{<:AbstractQuaternion{T}}) end F end -to_float_array(q::AbstractQuaternion) = collect(float(q).components) +# WORKAROUND for an Enzyme bug (EnzymeAD/Enzyme.jl#3776). The components are copied +# with `Vector` rather than `collect`, because Enzyme (as of 0.13.211, on Julia 1.10) +# crashes in reverse mode on `collect` of an `SVector` inside a closure called by another +# closure. The result is the same. Once that bug is fixed, this can be `collect` again. +to_float_array(q::AbstractQuaternion) = Vector(components(float(q))) @doc raw""" @@ -107,8 +115,18 @@ NOTE: Before opening an issue reporting something "wrong" with this function, be read all of [this page](https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible), *especially* the very last section about opening issues or pull requests. +!!! warning "Derivatives at the Euler singularities" + The Euler angles are not differentiable functions of the quaternion components at the + Euler singularities (β=0 or β=π), where only α+γ or α-γ, respectively, is defined. + Automatic differentiation of this function at exactly those points returns `NaN` for + some of the derivatives, and those `NaN`s propagate into the derivatives of anything + computed from the angles, even when that result is itself smooth. + +Quaternions with complex components (`Lorentz` rotors) are not supported, and raise an +`ArgumentError`. + # Returns -- `αβγ::StaticVector{T}` +- `αβγ::SVector{3,T}` # Raises - `AllHell` if you try to actually use Euler angles, when you could have been using @@ -124,31 +142,44 @@ function to_euler_angles(q::AbstractQuaternion) a0 = 2atan(hypot(q[2], q[3]), hypot(q[1], q[4])) a1 = atan(q[4], q[1]) a2 = atan(-q[2], q[3]) - @SVector [a1+a2, a0, a1-a2] + SVector(a1+a2, a0, a1-a2) +end +function to_euler_angles(q::AbstractQuaternion{<:Complex}) + throw(ArgumentError(complex_conversion_message(to_euler_angles))) +end + +# The message for conversions that are defined only for real rotations. +function complex_conversion_message(f) + "`$f` is not defined for quaternions with complex components (such as `Lorentz` " * + "rotors), because they do not represent rotations of real three-dimensional space. " * + "Note that `to_rotation_matrix` of a `Lorentz` rotor returns its complex-orthogonal " * + "action on bivectors." end """ from_euler_angles(α, β, γ) + from_euler_angles(αβγ) Come over from the dark side. +Return the `Rotor` corresponding to the Euler angles `α`, `β`, and `γ`, which may also be +given as a single collection `αβγ` of three angles. + Assumes the Euler angles correspond to the quaternion `R` via R = exp(α𝐤/2) * exp(β𝐣/2) * exp(γ𝐤/2) -where 𝐣 and 𝐤 rotate about the fixed ``y`` and ``z`` axes, respectively, so -this reprents an initial rotation (in the positive sense) through an angle -``γ`` about the axis ``z``, followed by a rotation through ``β`` about the axis -``y``, and a final rotation through ``α`` about the axis ``z``. This is -equivalent to performing an initial rotation through ``α`` about the axis -``z``, followed by a rotation through ``β`` about the *rotated* axis ``y'``, -followed by a rotation through ``γ`` about the *twice-rotated* axis ``z''``. +where 𝐣 and 𝐤 rotate about the fixed ``y`` and ``z`` axes, respectively, so this +represents an initial rotation (in the positive sense) through an angle ``γ`` about the axis +``z``, followed by a rotation through ``β`` about the axis ``y``, and a final rotation +through ``α`` about the axis ``z``. This is equivalent to performing an initial rotation +through ``α`` about the axis ``z``, followed by a rotation through ``β`` about the *rotated* +axis ``y'``, followed by a rotation through ``γ`` about the *twice-rotated* axis ``z''``. The angles are naturally assumed to be in radians. -NOTE: Before opening an issue reporting something "wrong" with this function, -be sure to read all of [this -page](https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible), +NOTE: Before opening an issue reporting something "wrong" with this function, be sure to +read all of [this page](https://github.com/moble/quaternion/wiki/Euler-angles-are-horrible), *especially* the very last section about opening issues or pull requests. # See Also @@ -172,33 +203,34 @@ from_euler_angles(αβγ) = from_euler_angles(αβγ...) Convert input quaternion to complex phases of Euler angles -Interpreting the input quaternion as a rotation (though its normalization -scales out), we can define the complex Euler phases from the Euler angles (α, -β, γ) as +Interpreting the input quaternion as a rotation (though its normalization scales out), we +can define the complex Euler phases from the Euler angles (α, β, γ) as zₐ ≔ exp(i*α) zᵦ ≔ exp(i*β) zᵧ ≔ exp(i*γ) -These are more useful geometric quantities than the angles themselves — being -involved in computing spherical harmonics and Wigner's 𝔇 matrices — and can be -computed from the components of the corresponding quaternion algebraically -(without the use of transcendental functions). +These are more useful geometric quantities than the angles themselves — being involved in +computing spherical harmonics and Wigner's 𝔇 matrices — and can be computed from the +components of the corresponding quaternion algebraically (without the use of transcendental +functions). -Note that `to_euler_phases!(z, q)` is supported for backwards compatibility, -but because this function returns an `SVector`, there is probably no advantage -to the in-place approach. +Note that `to_euler_phases!(z, q)` is supported for backwards compatibility, but because +this function returns an `SVector`, there is probably no advantage to the in-place approach. -!!! warning "Incorrect derivatives near singularities" +Integer quaternions are converted to a float type first. The normalization of the input +scales out, as long as the squares of its components neither overflow nor underflow. +Quaternions with complex components (`Lorentz` rotors) are not supported, and raise an +`ArgumentError`. - Note that the derivatives of these phases with respect to the quaternion - components are ill-defined at the Euler singularities (specifically, when - β=0 or β=π). The problematic cases will just return 1 for the phase - factor, which will autodiff to zero. Fortunately, this should not pollute - downstream results if they are grounded in geometric quantities. - Specifically, Wigner's 𝔇 matrices can be computed from these phases without - any issues, because the ``d`` factors should be zero anyway, and the product - rule will save us. +!!! warning "Incorrect derivatives near singularities" + Note that the derivatives of these phases with respect to the quaternion components are + ill-defined at the Euler singularities (specifically, when β=0 or β=π). The problematic + cases will just return 1 for the phase factor, which will autodiff to zero. + Fortunately, this should not pollute downstream results if they are grounded in + geometric quantities. Specifically, Wigner's 𝔇 matrices can be computed from these + phases without any issues, because the ``d`` factors should be zero anyway, and the + product rule will save us. # Returns - `z::SVector{Complex{T}}`: complex phases (zₐ, zᵦ, zᵧ) in that order. @@ -210,6 +242,8 @@ to the in-place approach. """ function to_euler_phases(R::AbstractQuaternion{T}) where {T} + # These are not computed with `hypot`, whose derivative is NaN at zero; the derivative + # of `√` at zero gives the finite results described in the docstring. a = R[1]^2 + R[4]^2 b = R[2]^2 + R[3]^2 sqrta = √a @@ -224,14 +258,26 @@ function to_euler_phases(R::AbstractQuaternion{T}) where {T} else zm = Complex{T}(R[3], -R[2]) / sqrtb # exp[i(α-γ)/2] end - @SVector [ + SVector( zp * zm, # exp[iα] Complex{T}((a - b), 2 * sqrta * sqrtb) / (a + b), # exp[iβ] zp * conj(zm), # exp[iγ] - ] + ) +end +to_euler_phases(R::AbstractQuaternion{<:Integer}) = to_euler_phases(float(R)) +function to_euler_phases(R::AbstractQuaternion{<:Complex}) + throw(ArgumentError(complex_conversion_message(to_euler_phases))) end +""" + to_euler_phases!(z, R) + +Store the Euler phases of the quaternion `R` in the vector `z`, and return `z`. + +This is equivalent to `z[:] = to_euler_phases(R)`, and is provided for backwards +compatibility. See [`to_euler_phases`](@ref) for details. +""" function to_euler_phases!(z::Array{Complex{T}}, R::AbstractQuaternion{T}) where {T} z[:] = to_euler_phases(R) z @@ -242,28 +288,26 @@ end from_euler_phases(zₐ, zᵦ, zᵧ) from_euler_phases(z) -Return the quaternion corresponding to these Euler phases. +Return the `Rotor` corresponding to these Euler phases. -Interpreting the input quaternion as a rotation (though its normalization -scales out), we can define the complex Euler phases from the Euler angles (α, -β, γ) as +The complex Euler phases are defined in terms of the Euler angles (α, β, γ) as zₐ ≔ exp(i*α) zᵦ ≔ exp(i*β) zᵧ ≔ exp(i*γ) -These are more useful geometric quantites than the angles themselves — being -involved in computing spherical harmonics and Wigner's 𝔇 matrices — and can be -computed from the components of the corresponding quaternion algebraically -(without the use of transcendental functions). +These are more useful geometric quantities than the angles themselves — being involved in +computing spherical harmonics and Wigner's 𝔇 matrices — and can be computed from the +components of the corresponding quaternion algebraically (without the use of transcendental +functions). # Parameters -- `z::Vector{Complex{T}}`: complex vector of length 3, representing the complex - phases (zₐ, zᵦ, zᵧ) in that order. +- `z`: a collection (such as a `Vector` or `SVector`) of three complex numbers, representing + the complex phases (zₐ, zᵦ, zᵧ) in that order. # Returns -- `R::Quaternion{T}` +- `R::Rotor{T}` # See Also - [`to_euler_phases`](@ref): Convert quaternion to Euler phases @@ -272,11 +316,13 @@ computed from the components of the corresponding quaternion algebraically """ function from_euler_phases(zₐ, zᵦ, zᵧ) - zb = √(zᵦ) # exp[iβ/2] - zp = √(zₐ * zᵧ) # exp[i(α+γ)/2] - zm = √(zₐ * conj(zᵧ)) # exp[i(α-γ)/2] - if abs(zₐ - zp * zm) > abs(zₐ + zp * zm) - zp *= -1 + zb = csqrt(zᵦ) # exp[iβ/2] + zp = csqrt(zₐ * zᵧ) # exp[i(α+γ)/2] + zm = csqrt(zₐ * conj(zᵧ)) # exp[i(α-γ)/2] + # This comparison is equivalent to one of `abs`, but `abs2` has no singular derivative + # at zero, which reverse-mode automatic differentiation would otherwise record. + if abs2(zₐ - zp * zm) > abs2(zₐ + zp * zm) + zp = -zp end rotor(real(zb) * real(zp), -imag(zb) * imag(zm), imag(zb) * real(zm), real(zb) * imag(zp)) end @@ -288,81 +334,130 @@ from_euler_phases(z) = from_euler_phases(z...) Return the spherical coordinates corresponding to this quaternion. -We can treat the quaternion as a transformation taking the ``z`` axis to some -direction ``n̂``. This direction can be described in terms of spherical -coordinates (θ, ϕ). Here, we use the standard commonly used in physics: θ -represents the "polar angle" between the ``z`` axis and the direction ``n̂``, -while ϕ represents the "azimuthal angle" between the ``x`` axis and the -projection of ``n̂`` into the ``x``-``y`` plane. Both angles are given in -radians. +We can treat the quaternion as a transformation taking the ``z`` axis to some direction +``n̂``. This direction can be described in terms of spherical coordinates (θ, ϕ). Here, we +use the convention commonly used in physics: θ represents the "polar angle" between the +``z`` axis and the direction ``n̂``, while ϕ represents the "azimuthal angle" between the +``x`` axis and the projection of ``n̂`` into the ``x``-``y`` plane. Both angles are given +in radians, and the result is an `SVector` of (θ, ϕ). + +The outputs are in these ranges: + + - θ ∈ [0, π] + - ϕ ∈ (-2π, 2π] + +As for [`to_euler_angles`](@ref), ϕ is not reduced to a range of length 2π, so `q` and `-q` +may give values of ϕ that differ by 2π. Quaternions with complex components (`Lorentz` +rotors) are not supported, and raise an `ArgumentError`. + +!!! warning "Derivatives at the poles" + The spherical coordinates are not differentiable functions of the quaternion components + at the poles (θ=0 or θ=π). Automatic differentiation of this function at exactly those + points returns zero for the derivatives of θ, and `NaN` for some of the derivatives of + ϕ. """ function to_spherical_coordinates(q::Q) where {Q<:AbstractQuaternion} q = float(q) - a0 = 2acos(√((q[1]^2+q[4]^2)/abs2(q))) + # This is the same expression as in `to_euler_angles`, which is accurate near the poles + # and independent of the normalization of `q`. At exactly the poles, the sum of squares + # replaces `hypot`; it has the same value (zero) there, but a zero derivative rather + # than a NaN. + v = iszerovalue(q[2]) && iszerovalue(q[3]) ? q[2]^2 + q[3]^2 : hypot(q[2], q[3]) + s = iszerovalue(q[1]) && iszerovalue(q[4]) ? q[1]^2 + q[4]^2 : hypot(q[1], q[4]) + a0 = 2atan(v, s) a1 = atan(q[4], q[1]) a2 = atan(-q[2], q[3]) - @SVector [a0, a1+a2] + SVector(a0, a1+a2) +end +function to_spherical_coordinates(q::AbstractQuaternion{<:Complex}) + throw(ArgumentError(complex_conversion_message(to_spherical_coordinates))) end """ from_spherical_coordinates(θ, ϕ) + from_spherical_coordinates(θϕ) -Return a rotor corresponding to these spherical coordinates. +Return a rotor corresponding to these spherical coordinates, which may also be given as a +single collection `θϕ` of two angles. -Considering (θ, ϕ) as a point ``n̂`` on the sphere, we can also construct a -quaternion that rotates the ``z`` axis onto that point. Here, we use the -standard commonly used in physics: θ represents the "polar angle" between the -``z`` axis and the direction ``n̂``, while ϕ represents the "azimuthal angle" -between the ``x`` axis and the projection of ``n̂`` into the ``x``-``y`` plane. -Both angles must be given in radians. +Considering (θ, ϕ) as a point ``n̂`` on the sphere, we can also construct a quaternion that +rotates the ``z`` axis onto that point. Here, we use the convention commonly used in +physics: θ represents the "polar angle" between the ``z`` axis and the direction ``n̂``, +while ϕ represents the "azimuthal angle" between the ``x`` axis and the projection of ``n̂`` +into the ``x``-``y`` plane. Both angles must be given in radians. """ function from_spherical_coordinates(θ, ϕ) - sϕ, cϕ = sincos(ϕ/2) - sθ, cθ = sincos(θ/2) + # `sin` and `cos` are called separately, rather than through `sincos`, because Enzyme + # cannot take second derivatives of `sincos`. + sϕ, cϕ = sin(ϕ/2), cos(ϕ/2) + sθ, cθ = sin(θ/2), cos(θ/2) rotor(cθ*cϕ, -sθ*sϕ, sθ*cϕ, cθ*sϕ) end from_spherical_coordinates(θϕ) = from_spherical_coordinates(θϕ...) +# Implementation notes for `dominant_eigenvector`, which `from_rotation_matrix` and `align` +# call on 4×4 matrices with static storage. The methods are split on whether LAPACK can +# handle the element type: +# +# * For `Float16`, `Float32`, and `Float64`, `eigen(M, n:n)` asks LAPACK for the largest +# eigenpair alone, which is both cheaper and unambiguous. That range form has no method +# for other element types. LAPACK computes `Float16` in `Float32`, so the result is +# converted back to the input's element type. For `Float32` and `Float64`, the LAPACK +# call is isolated in `dominant_eigenvector_lapack`, which takes a plain `Matrix` and +# the `uplo` character of the `Symmetric` wrapper. Automatic differentiation packages +# cannot trace LAPACK, so the extensions give that function derivative rules, which use +# the formulas in `dominant_eigenvector_pushforward` and `dominant_eigenvector_pullback` +# below. +# +# * Otherwise we take the full decomposition and select by `argmax` of the eigenvalues +# rather than by position. Selecting `vectors[:, end]` would be wrong: the *only* +# guarantee `eigen` makes about ordering is what the underlying implementation chooses +# to provide, and the generic implementations disagree. `GenericLinearAlgebra` sorts +# ascending, but `GenericSchur` — which takes precedence for `Symmetric` once it is +# loaded, and which arrives indirectly with packages such as `DoubleFloats` — does not. +# Since the eigenvalues of the Bar-Itzhack matrix are `(-1, -1, -1, 3)`, picking the +# wrong column does not merely lose accuracy; it returns a rotor a full `π/2` away. +# Selecting by value makes the result independent of which packages happen to be loaded, +# and scanning four eigenvalues costs nothing beside the decomposition itself. +# +# The generic method converts static storage to a dense `Matrix` first with `_dense`, +# because the generic backends have no `eigen` method for static storage, and on Julia 1.6 +# through 1.8 neither does LAPACK's range form. +# +# Element types that wrap a float, such as the dual numbers of ForwardDiff, are handled by +# `refined_dominant_eigenvector` instead. The generic `eigen` would propagate derivatives +# through every eigenpair, and for an exact rotation matrix the Bar-Itzhack matrix has the +# triply degenerate eigenvalue -1, so first derivatives of the dominant eigenvector were +# correct but second derivatives (nested duals) were not, and were NaN at the identity. """ - dominant_eigenvector(M) + dominant_eigenvector(M::Symmetric) -The eigenvector of the symmetric matrix `M` belonging to its largest +Return the unit eigenvector of the real symmetric matrix `M` that belongs to its largest eigenvalue. -Used by both [`from_rotation_matrix`](@ref), on a static 4×4, and -[`align`](@ref), on a dense 4×4. - -This function has two method groups, split on whether LAPACK can -handle the element type: - - * For `Float16`, `Float32`, and `Float64`, `eigen(M, n:n)` asks - LAPACK for the largest eigenpair alone, which is both cheaper and - unambiguous. That range form has no method for other element - types, which is precisely what used to limit `align` to those - three. - - * Otherwise we take the full decomposition and select by `argmax` of - the eigenvalues rather than by position. Selecting `vectors[:, - end]` would be wrong: the *only* guarantee `eigen` makes about - ordering is what the underlying implementation chooses to provide, - and the generic implementations disagree. `GenericLinearAlgebra` - sorts ascending, but `GenericSchur` — which takes precedence for - `Symmetric` once it is loaded, and which arrives indirectly with - packages such as `DoubleFloats` — does not. Since the eigenvalues - of the Bar-Itzhack matrix are `(-1, -1, -1, 3)`, picking the wrong - column does not merely lose accuracy; it returns a rotor a full - `π/2` away. Selecting by value makes the result independent of - which packages happen to be loaded. - -Scanning four eigenvalues costs nothing beside the eigendecomposition -itself, so the generic method pays no meaningful price for the -robustness. +This is the computation at the heart of [`from_rotation_matrix`](@ref) and [`align`](@ref), +each of which builds a symmetric 4×4 matrix whose dominant eigenvector is the optimal rotor. +The sign of the result is arbitrary, as for any eigenvector; those functions choose it +afterward. + +The result is a vector with the element type of `M`. `Float16`, `Float32`, and `Float64` +matrices are handled by LAPACK, and other real element types (such as `BigFloat`) by a +generic eigendecomposition, which needs a package such as `GenericLinearAlgebra` (loaded by +this package). The function can be differentiated by the AD packages that this package +supports. For 4×4 matrices whose elements are the number types of AD packages (such as +ForwardDiff's dual numbers), the eigenvector of the values is refined by Newton steps, so +that higher derivatives are also correct; they have been checked through fourth order. +Derivatives assume that the largest eigenvalue is simple. Complex matrices are not +supported. """ function dominant_eigenvector(M::Symmetric{T}) where {T} + if size(M) == (4, 4) && typeof(value(first(M))) !== T + return refined_dominant_eigenvector(M) + end λ, V = try eigen(_dense(M)) catch err @@ -370,9 +465,114 @@ function dominant_eigenvector(M::Symmetric{T}) where {T} end V[:, argmax(λ)] end -function dominant_eigenvector(M::Symmetric{<:Union{Float16,Float32,Float64}}) +function dominant_eigenvector(M::Symmetric{T}) where {T<:Union{Float32,Float64}} + dominant_eigenvector_lapack(Matrix(parent(M)), M.uplo) +end +function dominant_eigenvector(M::Symmetric{Float16}) n = size(M, 1) - eigen(M, n:n).vectors[:, 1] + v = eigen(_dense(M), n:n).vectors[:, 1] + eltype(v) === Float16 ? v : Float16.(v) +end +function dominant_eigenvector(M::Symmetric{<:Complex}) + throw(ArgumentError( + "`from_rotation_matrix` and `align` need matrices or vectors with real " + * "elements; complex (and `Lorentz`) input is not supported." + )) +end + +# The unit eigenvector of `Symmetric(A, Symbol(uplo))` belonging to its largest eigenvalue, +# computed by LAPACK. This is the only place where `from_rotation_matrix` and `align` call +# LAPACK for `Float32` and `Float64`, and its arguments are plain arrays, so that a single +# derivative rule for each automatic-differentiation package covers both functions. +function dominant_eigenvector_lapack( + A::Matrix{T}, uplo::Char +) where {T<:Union{Float32,Float64}} + n = size(A, 1) + eigen(Symmetric(A, Symbol(uplo)), n:n).vectors[:, 1] +end + +# The first `n = length(v)` entries of the solution `x` of the bordered system +# +# [S - λI v] [x] [b] +# [ vᵀ 0] [μ] = [0], +# +# which is nonsingular when `λ` is a simple eigenvalue of the symmetric matrix `S` with unit +# eigenvector `v`. Then `x` is the solution of `(S - λI) x = b` orthogonal to `v`, for any +# `b` orthogonal to `v`. +function bordered_solve(S, λ, v, b) + n = length(v) + K = [S - λ * LinearAlgebra.I v; transpose(v) zero(λ)] + (K \ [b; zero(λ)])[1:n] +end + +# The derivative of `v = dominant_eigenvector_lapack(A, uplo)` along the tangent `Ȧ` of `A`, +# given `v` itself. Differentiating `S v = λ v` and `vᵀv = 1`, where `S` is the symmetric +# matrix and `λ = vᵀ S v`, gives `(S - λI) v̇ = λ̇ v - Ṡ v` with `vᵀ v̇ = 0`, so `v̇` is +# minus the bordered solve with `b = Ṡ v`. The component of `b` along `v` changes only +# `λ̇`, and is removed first. Only the triangle of `Ȧ` named by `uplo` is used, as for `A`. +function dominant_eigenvector_pushforward(A, uplo::Char, v, Ȧ) + S = Matrix(Symmetric(A, Symbol(uplo))) + λ = v ⋅ (S * v) + b = Matrix(Symmetric(Ȧ, Symbol(uplo))) * v + -bordered_solve(S, λ, v, b - (v ⋅ b) * v) +end + +# The cotangent of `A` in `v = dominant_eigenvector_lapack(A, uplo)`, given `v` and its +# cotangent `v̄`. The bordered matrix is symmetric, so the pullback applies the same solve +# as the pushforward, sign included, to `v̄`, giving `w`. The cotangent of the full +# symmetric matrix is `G = w vᵀ`. Each off-diagonal entry of the triangle named by `uplo` +# stands for two entries of the symmetric matrix, and each diagonal entry for one, so the +# cotangent of `A` is `triu(G + Gᵀ) - Diagonal(G)` for `'U'`, or the `tril` analogue for +# `'L'`, and zero in the other triangle. +function dominant_eigenvector_pullback(A, uplo::Char, v, v̄) + S = Matrix(Symmetric(A, Symbol(uplo))) + λ = v ⋅ (S * v) + w = -bordered_solve(S, λ, v, v̄ - (v ⋅ v̄) * v) + G = w * transpose(v) + H = G + transpose(G) + triangle = uplo == 'U' ? LinearAlgebra.triu(H) : LinearAlgebra.tril(H) + triangle - LinearAlgebra.Diagonal(G) +end + +# The 5×5 matrix `[B v; vᵀ 0]` for a 4×4 matrix `B` and a 4-vector `v`, built element by +# element in column-major order. Concatenation would be simpler to read, but it hits an +# ambiguous `vcat` method for some element types, such as those of ReverseDiff. +function bordered_matrix(B::SMatrix{4,4,T}, v::SVector{4,T}) where {T} + SMatrix{5,5,T}( + B[1,1], B[2,1], B[3,1], B[4,1], v[1], + B[1,2], B[2,2], B[3,2], B[4,2], v[2], + B[1,3], B[2,3], B[3,3], B[4,3], v[3], + B[1,4], B[2,4], B[3,4], B[4,4], v[4], + v[1], v[2], v[3], v[4], zero(T) + ) +end + +# The dominant eigenvector of a 4×4 symmetric matrix `M` whose element type `T` wraps a +# float, such as a (possibly nested) dual number. The eigenvector `v₀` of the matrix of +# values, `map(value, M)`, is computed by the float methods above; it is exact for the +# values but carries no derivatives. Then two Newton steps on `F(v, λ) = (M v - λ v, (vᵀv - +# 1)/2)` in the element type `T` fill in the derivatives. As a power series in the +# perturbation that the derivatives describe, the error of `v₀` begins at first order, and +# each Newton step doubles the order at which the error begins. So one step gives exact +# first derivatives, and two steps give exact derivatives through third order. The Jacobian +# of `F` is `[M-λI -v; vᵀ 0]`, which is nonsingular when the dominant eigenvalue is simple, +# as it is for any (nearly) orthogonal input to `from_rotation_matrix`. This avoids +# differentiating the degenerate eigenvectors that the generic `eigen` would otherwise +# differentiate. +function refined_dominant_eigenvector(M::Symmetric{T}) where {T} + A = SMatrix{4,4,T}(M) + v = SVector{4,T}(dominant_eigenvector(Symmetric(map(value, A)))) + λ = v ⋅ (A * v) + for _ ∈ 1:2 + r = A * v - λ * v + # The Newton step `(δv, δλ)` solves `[A-λI -v; vᵀ 0] (δv, δλ) = -F`, which is + # the symmetric system below for `(δv, -δλ)`. + δ = bordered_matrix(A - λ * LinearAlgebra.I, v) \ + SVector{5,T}(-r[1], -r[2], -r[3], -r[4], (1 - v ⋅ v) / 2) + v += SVector{4,T}(δ[1], δ[2], δ[3], δ[4]) + λ -= δ[5] + end + v end # Give a usable error for element types that cannot support an @@ -407,18 +607,16 @@ end The underlying failure was `$summary`.""")) end -# Materialize static storage for the generic `eigen` backends. This -# is a separate helper rather than another `dominant_eigenvector` -# method so that `Symmetric{Float64,<:SMatrix}` — which would match -# both an element-type method and a storage-type method — cannot -# become an ambiguity. +# Materialize static storage for `eigen`. This is a separate helper rather than another +# `dominant_eigenvector` method so that `Symmetric{Float64,<:SMatrix}` — which would match +# both an element-type method and a storage-type method — cannot become an ambiguity. # # The generic backends implement `eigen` only against dense storage: -# `eigen(::Symmetric{Double64,<:SMatrix})` raises a `MethodError`, -# even though the same matrix decomposes fine once it is dense. A 4×4 -# copy is negligible beside a generic eigendecomposition, and it is -# what lets `from_rotation_matrix` — which builds an `SMatrix` — -# accept the full range of float types. +# `eigen(::Symmetric{Double64,<:SMatrix})` raises a `MethodError`, even though the same +# matrix decomposes fine once it is dense. On Julia 1.6 through 1.8, the LAPACK range form +# `eigen(::Symmetric{Float64,<:SMatrix}, n:n)` fails in the same way. A 4×4 copy is +# negligible beside an eigendecomposition, and it is what lets `from_rotation_matrix` and +# `align` — which build an `SMatrix` — accept the full range of float types. _dense(M::Symmetric) = M _dense(M::Symmetric{<:Any,<:SMatrix}) = Symmetric(Matrix(M)) @@ -440,11 +638,18 @@ This function returns that quaternion, using Bar-Itzhack's algorithm (version 3) for non-orthogonal matrices. [J. Guidance, Vol. 23, No. 6, p. 1085](http://dx.doi.org/10.2514/2.4654) -This works for any float element type. Note that this function computes the -eigen-decomposition of `ℛ`, which LAPACK provides only for `Float16`, `Float32`, and -`Float64`; for anything else we rely on `GenericLinearAlgebra`, which `Quaternionic` now -depends on directly. (It used to be your job to install and import that package, and a -`MethodError` was your only warning.) +Since `R` and `-R` represent the same rotation, the sign of the result is fixed by +convention: its scalar part is positive, or, if the scalar part is zero, its first nonzero +component is positive. The result is therefore discontinuous at rotations through an angle +of π, where the scalar part changes sign. See [`unflip`](@ref) for making a sequence of +rotors continuous. + +This works for any real element type, and for float input the result has the same element +type as the input. It computes the eigen-decomposition of a 4×4 symmetric matrix built from +`ℛ`, which LAPACK provides only for `Float16`, `Float32`, and `Float64`; for anything else +we rely on `GenericLinearAlgebra`, which `Quaternionic` depends on directly. The +eigen-decomposition makes this function far more expensive than +[`to_rotation_matrix`](@ref). Matrices with complex elements are not supported. """ function from_rotation_matrix(ℛ::AbstractMatrix) @@ -452,13 +657,15 @@ function from_rotation_matrix(ℛ::AbstractMatrix) @inbounds begin # Compute 3K₃ according to Eq. (2) of Bar-Itzhack. We will just be looking for the # eigenvector with the largest eigenvalue, so scaling by a strictly positive number - # (3, in this case) won't change that. - K₃3 = Symmetric(@SMatrix[ - ℛ[1,1]-ℛ[2,2]-ℛ[3,3] ℛ[2,1]+ℛ[1,2] ℛ[3,1]+ℛ[1,3] ℛ[2,3]-ℛ[3,2]; - 0 ℛ[2,2]-ℛ[1,1]-ℛ[3,3] ℛ[3,2]+ℛ[2,3] ℛ[3,1]-ℛ[1,3]; - 0 0 ℛ[3,3]-ℛ[1,1]-ℛ[2,2] ℛ[1,2]-ℛ[2,1]; - 0 0 0 ℛ[1,1]+ℛ[2,2]+ℛ[3,3] - ]) + # (3, in this case) won't change that. Only the upper triangle is used, and the + # elements are given in column-major order. + z = zero(ℛ[1,1]) + K₃3 = Symmetric(SMatrix{4,4}( + ℛ[1,1]-ℛ[2,2]-ℛ[3,3], z, z, z, + ℛ[2,1]+ℛ[1,2], ℛ[2,2]-ℛ[1,1]-ℛ[3,3], z, z, + ℛ[3,1]+ℛ[1,3], ℛ[3,2]+ℛ[2,3], ℛ[3,3]-ℛ[1,1]-ℛ[2,2], z, + ℛ[2,3]-ℛ[3,2], ℛ[3,1]-ℛ[1,3], ℛ[1,2]-ℛ[2,1], ℛ[1,1]+ℛ[2,2]+ℛ[3,3] + )) # Compute the *dominant* eigenvector (the one with the largest eigenvalue) de = dominant_eigenvector(K₃3) @@ -466,6 +673,19 @@ function from_rotation_matrix(ℛ::AbstractMatrix) # Convert it into a quaternion R = rotor(de[4], -de[1], -de[2], -de[3]) end + positive_hemisphere(R) +end + +# Choose the sign of the rotor `R`, which represents the same rotation as `-R`, so that its +# first nonzero component is positive. The comparisons use only the values of the +# components, so that dual numbers make the same choice as the floats they wrap. +function positive_hemisphere(R::Rotor) + for c ∈ components(R) + v = value(c) + if !iszero(v) + return v < 0 ? -R : R + end + end R end @@ -483,14 +703,25 @@ we can also express this rotation in terms of a 3x3 matrix `ℛ` such that v' = ℛ * v. -This function returns that matrix. +This function returns that matrix, as an `SMatrix{3,3}`. The normalization of `q` scales +out, as long as `abs2(q)` neither overflows nor underflows. + +For a `Lorentz` rotor (a quaternion with complex components), the result is the +complex-orthogonal matrix in SO(3,ℂ) that represents the action of the rotor on bivectors. """ function to_rotation_matrix(q::Q) where {Q<:AbstractQuaternion} n = inv(abs2(q)) - @SMatrix [ - 1 - 2*(q[3]^2 + q[4]^2) * n 2*(q[2]*q[3] - q[4]*q[1]) * n 2*(q[2]*q[4] + q[3]*q[1]) * n ; - 2*(q[2]*q[3] + q[4]*q[1]) * n 1 - 2*(q[2]^2 + q[4]^2) * n 2*(q[3]*q[4] - q[2]*q[1]) * n ; - 2*(q[2]*q[4] - q[3]*q[1]) * n 2*(q[3]*q[4] + q[2]*q[1]) * n 1 - 2*(q[2]^2 + q[3]^2) * n - ] + # The elements are given in column-major order. + SMatrix{3,3}( + 1 - 2*(q[3]^2 + q[4]^2) * n, + 2*(q[2]*q[3] + q[4]*q[1]) * n, + 2*(q[2]*q[4] - q[3]*q[1]) * n, + 2*(q[2]*q[3] - q[4]*q[1]) * n, + 1 - 2*(q[2]^2 + q[4]^2) * n, + 2*(q[3]*q[4] + q[2]*q[1]) * n, + 2*(q[2]*q[4] + q[3]*q[1]) * n, + 2*(q[3]*q[4] - q[2]*q[1]) * n, + 1 - 2*(q[2]^2 + q[3]^2) * n + ) end diff --git a/src/distance.jl b/src/distance.jl index 3eb83ccd..d2e3ecf0 100644 --- a/src/distance.jl +++ b/src/distance.jl @@ -2,22 +2,31 @@ distance(q₁, q₂) distance2(q₁, q₂) -Measure the "distance" between two quaternions, or the squared distance with -`distance2`. +Measure the "distance" between two quaternions, or the squared distance with `distance2`. -By default, this function just returns the natural measure in the *additive* -group of quaternions: +By default, these functions use the natural measure in the *additive* group of quaternions, +so that `distance2` returns ```julia abs2(q₁ - q₂) ``` -If both arguments are `Rotor`s, the function returns the natural measure in the -*rotation* group, which is roughly +and `distance` returns its square root. For quaternions with complex components, `abs2` is +the spinor norm, so these values may be complex, and they may be zero for distinct +quaternions. + +If both arguments are `Rotor`s, the functions use the natural measure in the *rotation* +group instead, so that `distance2` returns ```julia -abs2(log(q₁ / q₂)) +min(abs2(log(q₁ / q₂)), abs2(log(-q₁ / q₂))) ``` -Note that for `Rotor`s, this method is (efficiently) independent of the -scaling of `q₁` and `q₂`, including up to factors of -1, as is appropriate for -the rotation group. +and `distance` returns its square root. This is half the angle (in radians) of the rotation +that takes `q₂` to `q₁`, and it lies in the range ``[0, π/2]``. For example, `rotor(imx)` +and `rotor(imy)` represent rotations through ``π`` about the ``x`` and ``y`` axes. The +rotation that takes one to the other is a rotation through ``π`` about the ``z`` axis, so +their distance is ``π/2``. These methods are (efficiently) independent of the scaling of +`q₁` and `q₂`, including factors of -1, as is appropriate for the rotation group. The +`Rotor` methods do not support complex components (`Lorentz` rotors), because the Lorentz +group has no positive-definite bi-invariant metric; they throw an `ArgumentError` for such +input. # Examples ```jldoctest example @@ -36,16 +45,38 @@ distance2(q₁::AbstractQuaternion, q₂::AbstractQuaternion) = abs2(q₁ - q₂ distance(q₁::Rotor, q₂::Rotor) = √distance2(q₁, q₂) distance2(q₁::Rotor, q₂::Rotor) = _abs2_small_vec_log(q₁ / q₂) -@inline function _abs2_small_vec_log(q::Rotor{T}) where {T} - # Like `min(abs2(log(q)), abs2(log(-q)))`, but assumes the norm of `q` is 1 - x = abs2vec(q) / q[1]^2 - if x ≤ ∜(eps(typeof(x))) / 2 +# Like `min(abs2(log(q)), abs2(log(-q)))`, but assumes that the norm of `q` is 1. The +# threshold that selects the series is chosen by the type of the value of the scalar part, +# so that dual numbers take the same branches as the floats they wrap. +_abs2_small_vec_log(q::Rotor) = _abs2_small_vec_log(value(q[1]), q) + +@inline function _abs2_small_vec_log(w, q::Rotor) + v² = abs2vec(q) + w² = q[1]^2 + # This compares `x = v²/w²` with the threshold, but only on the values, and without + # dividing, so that nothing singular is evaluated when `q[1]` is zero. For element + # types whose values are not floats, such as `ReverseDiff.TrackedReal`, the threshold + # for `Float64` is used. For symbolic types, the comparison does not evaluate to a + # `Bool`, so the closed form is used. + T = w isa AbstractFloat ? typeof(w) : Float64 + small = value(v²) ≤ (sqrt(sqrt(eps(T))) / 2) * value(w²) + if small === true # Near the identity, `absvec` is the square root of a tiny number, whose derivatives # are huge and lose all accuracy when they cancel, or are NaN when it is exactly 0. # This series for `atan(√x)^2` in `x` is smooth instead; its relative truncation # error is about `x⁴/3`, which is below `eps` for this range of `x`. + x = v² / w² x * evalpoly(x, (1, -2//3, 23//45, -44//105)) else atan(absvec(q), abs(q[1]))^2 end end + +function _abs2_small_vec_log(::Complex, q::Rotor) + throw(ArgumentError( + "`distance` and `distance2` are not defined for `Rotor`s with complex components " + * "(`Lorentz` rotors), because the Lorentz group has no positive-definite " + * "bi-invariant metric. Use `distance(quaternion(q₁), quaternion(q₂))` for the " + * "additive measure, which is complex in general." + )) +end diff --git a/src/gradients_exp_log.jl b/src/gradients_exp_log.jl index 1b6ff823..1cb3269e 100644 --- a/src/gradients_exp_log.jl +++ b/src/gradients_exp_log.jl @@ -3,10 +3,14 @@ Return the gradient of `log(Z)` with respect to the components of `Z`. -The result includes "off-shell" components of the gradient, meaning that even -though change of `Z` in a direction that changes its norm would not be allowed -for a `Rotor`, we measure the gradient in that direction anyway. That is, the -elements of the returned vector of quaternions is +The result includes "off-shell" components of the gradient, meaning that even though change +of `Z` in a direction that changes its norm would not be allowed for a `Rotor`, we measure +the gradient in that direction anyway. Specifically, the gradient is that of the extension +of the logarithm to general quaternions, +```math +\log(Z) = \log|Z| + \frac{\mathrm{atan}(|\vec{Z}|, Z_w)}{|\vec{Z}|}\, \vec{Z}, +``` +so that the elements of the returned vector of quaternions are ```math \begin{aligned} \left[ @@ -18,36 +22,19 @@ elements of the returned vector of quaternions is \end{aligned} ``` -Note that, even though `log(::Rotor)` is a `QuatVec`, the derivative (and -therefore each element of the result) is a general `Quaternion`. +Note that, even though `log(::Rotor)` is a `QuatVec`, the derivative (and therefore each +element of the result) is a general `Quaternion`. -See also [`∂exp`](@ref) for a similar function, as well as [`log∂log`](@ref) -for a function to compute the value along with the gradient. +See also [`∂exp`](@ref) for a similar function, as well as [`log∂log`](@ref) for a function +to compute the value along with the gradient. # Examples ```julia -julia> ∂log∂w, ∂log∂x, ∂log∂y, ∂log∂z = ∂log(randn(QuatVecF64)); +julia> ∂log∂w, ∂log∂x, ∂log∂y, ∂log∂z = ∂log(randn(RotorF64)); ``` """ -function ∂log(Z::Rotor) - # log(Z::Rotor) = log(abs2) / 2 + f(Z) * vec(Z) - # f(Z) = atan(absvec / Z[1]) / absvec = acos(Z[1]) / absvec - a2 = abs2vec(Z) - a = sqrt(a2) - if a < 2eps(typeof(a)) - return Quaternion.([quaternion(one(a)), zero(a)*imx, zero(a)*imy, one(a)*imz]) - end - f = acos(Z[1]) / a - fprime = (Z[1] - f) / a2 - V = 1 + fprime * quatvec(Z) - [ - quaternion(conj(Z)), - Z[2] * V + f * imx, - Z[3] * V + f * imy, - Z[4] * V + f * imz, - ] -end +∂log(Z::Rotor) = log∂log(Z)[2] """ @@ -64,26 +51,64 @@ julia> l, ∂l = log∂log(randn(RotorF64)); ``` """ function log∂log(Z::Rotor) - # log(Z::Rotor) = log(abs2) / 2 + f(Z) * vec(Z) - # f(Z) = atan(absvec / Z[1]) / absvec = acos(Z[1]) / absvec - a2 = abs2vec(Z) - a = sqrt(a2) - if a < 2eps(typeof(a)) - return ( - quatvec(zero(a)), - Quaternion.([quaternion(one(a)), zero(a)*imx, zero(a)*imy, one(a)*imz]) - ) + # With w = Z[1] and a = absvec(Z), the logarithm is extended off shell as + # + # log(Z) = log(|Z|) + f vec(Z), where f = atan(a, w) / a. + # + # Its derivatives are + # + # ∂log(Z)/∂w = conj(Z) / |Z|², + # ∂log(Z)/∂Zᵢ = Zᵢ (1/|Z|² + f′ vec(Z)) + f 𝐞ᵢ, where f′ = (w/|Z|² - f) / a². + # + # Near the identity, the difference in f′ cancels catastrophically, and the square root + # in `a` has an infinite derivative at a = 0. There, both f and f′ are instead + # computed from series in x = a²/w², which carry the derivatives of every input + # component through AD. The series are f = A(x)/w and f′ = S(x)/w³, where + # + # A(x) = Σₖ (-1)ᵏ xᵏ / (2k+1), and S(x) = Σₖ (-1)ᵏ⁺¹ 2(k+1) xᵏ / (2k+3). + # + # Below the threshold x ≤ eps^(1/5), the six terms used here truncate each series at + # well below `eps`. + # + # The term Zᵢ f′ vec(Z) is computed as uᵢ k u. In the series branch, u = vec(Z) and + # k = f′. Otherwise, u = vec(Z)/a and k = f′a², because f′ alone overflows near the + # antipode, where it grows like 1/a³. + Z = float(Z) + w = Z[1] + a² = abs2vec(Z) + n² = w*w + a² + if value(w) > 0 && value(a²) ≤ value(w*w) * eps(typeof(value(a²)))^(1//5) + x = a² / (w*w) + f = evalpoly(x, (1, -1//3, 1//5, -1//7, 1//9, -1//11)) / w + k = evalpoly(x, (-2//3, 4//5, -6//7, 8//9, -10//11, 12//13)) / (w*w*w) + u = quatvec(Z) + l = f * quatvec(Z) + elseif iszerovalue(quatvec(Z)) + # Z is a negative real number, where the logarithm is singular, and its derivatives + # with respect to the vector components are infinite. As `log` does, we return π𝐤 + # as the value. The gradient keeps only the finite derivatives of log(|Z|), which + # is also what AD of `log(::Quaternion)` gives at this point. The components are + # tested, rather than `a²`, because `a²` underflows to zero for tiny nonzero vector + # parts, which belong in the general branch below. + f = zero(n²) + k = zero(n²) + u = quatvec(Z) + l = QuatVec{typeof(n²)}(false, false, false, π) + else + a = absvec(Z) + f = atan(a, w) / a + k = w / n² - f + u = quatvec(Z) / a + # Multiplying the angle by `u` avoids overflow in `f` for a tiny `a`. + l = atan(a, w) * u end - f = acos(Z[1]) / a - fprime = (Z[1] - f) / a2 - V = 1 + fprime * quatvec(Z) - ∂log = [ - quaternion(conj(Z)), - Z[2] * V + f * imx, - Z[3] * V + f * imy, - Z[4] * V + f * imz, + ∂l = [ + quaternion(conj(Z)) / n², + Z[2] / n² + u[2] * k * u + f * imx, + Z[3] / n² + u[3] * k * u + f * imy, + Z[4] / n² + u[4] * k * u + f * imz, ] - (f * quatvec(Z), ∂log) + (l, ∂l) end @@ -92,21 +117,20 @@ end Return the gradient of `exp(Z)` with respect to the components of `Z`. -The result includes "off-shell" components of the gradient, meaning that even -though a scalar component of `Z` would not be allowed for a `QuatVec`, we -measure the gradient in that direction anyway. That is, the first element -of the returned vector of quaternions is +The result includes "off-shell" components of the gradient, meaning that even though a +scalar component of `Z` would not be allowed for a `QuatVec`, we measure the gradient in +that direction anyway. That is, the first element of the returned vector of quaternions is ```math \begin{aligned} \left.\frac{\partial} {\partial Z_w} \exp(Z) \right|_{Z_w=0}. \end{aligned} ``` -Note that, even though `exp(::QuatVec)` is a `Rotor`, the derivative (and -therefore each element of the result) is a general `Quaternion`. +Note that, even though `exp(::QuatVec)` is a `Rotor`, the derivative (and therefore each +element of the result) is a general `Quaternion`. -See also [`∂log`](@ref) for a similar function, as well as [`exp∂exp`](@ref) -for a function to compute the value along with the gradient. +See also [`∂log`](@ref) for a similar function, as well as [`exp∂exp`](@ref) for a function +to compute the value along with the gradient. # Examples ```julia @@ -114,26 +138,7 @@ julia> ∂exp∂w, ∂exp∂x, ∂exp∂y, ∂exp∂z = ∂exp(randn(QuatVecF64) ``` """ -function ∂exp(Z::QuatVec) - # exp(Z::Quaternion) = exp(Z[1]) * cos(absvec) + g(Z) * vec(Z) - # g(Z) = exp(Z[1]) * sin(absvec) / absvec - a2 = abs2vec(Z) - a = sqrt(a2) - if a < 2eps(typeof(a)) - return Quaternion.([quaternion(one(a)), one(a)*imx, one(a)*imy, one(a)*imz]) - end - s, c = sincos(a) - sinca = s / a - g = sinca - gprime = (c - g) / a2 - V = -sinca + gprime * Z - [ - c + sinca * Z, - Z[2] * V + g * imx, - Z[3] * V + g * imy, - Z[4] * V + g * imz, - ] -end +∂exp(Z::QuatVec) = exp∂exp(Z)[2] """ @@ -141,7 +146,9 @@ end Return the value and gradient of `exp(Z)` with respect to the components of `Z`. -See [`∂exp`](@ref) for more explanation of the components of the gradient. +The value is a `Rotor`, as returned by `exp(Z)`, while the elements of the gradient are +general `Quaternion`s. See [`∂exp`](@ref) for more explanation of the components of the +gradient. # Examples ```julia @@ -150,26 +157,40 @@ julia> e, ∂e = exp∂exp(randn(QuatVecF64)); ``` """ function exp∂exp(Z::QuatVec) - # exp(Z::Quaternion) = exp(Z[1]) * cos(absvec) + g(Z) * vec(Z) - # g(Z) = exp(Z[1]) * sin(absvec) / absvec - a2 = abs2vec(Z) - a = sqrt(a2) - if a < 2eps(typeof(a)) - return ( - quaternion(one(a)), - Quaternion.([quaternion(one(a)), one(a)*imx, one(a)*imy, one(a)*imz]) - ) + # With a = absvec(Z), the exponential is extended off shell as + # + # exp(Z) = exp(Z_w) (c + g vec(Z)), where c = cos(a) and g = sin(a) / a. + # + # Its derivatives at Z_w = 0 are + # + # ∂exp(Z)/∂Z_w = exp(Z), + # ∂exp(Z)/∂Zᵢ = Zᵢ (-g + g′ vec(Z)) + g 𝐞ᵢ, where g′ = (c - g) / a². + # + # Near a = 0, the difference in g′ cancels catastrophically, and the square root in `a` + # has an infinite derivative at a = 0. There, c, g, and g′ are instead computed from + # their Taylor series in a², which carry the derivatives of every input component + # through AD. The terms of g′ are (-1)ᵏ⁺¹ 2(k+1) a²ᵏ / (2k+3)!. + Z = float(Z) + a² = abs2vec(Z) + if value(a²) ≤ eps(typeof(value(a²)))^(1//5) + c = evalpoly(a², (1, -1//2, 1//24, -1//720, 1//40320, -1//3628800)) + g = evalpoly(a², (1, -1//6, 1//120, -1//5040, 1//362880, -1//39916800)) + g′ = evalpoly(a², (-1//3, 1//30, -1//840, 1//45360, -1//3991680, 1//518918400)) + else + a = sqrt(a²) + # Separate `sin` and `cos` calls (rather than `sincos`) keep second-order Enzyme + # working. + c = cos(a) + g = sin(a) / a + g′ = (c - g) / a² end - s, c = sincos(a) - sinca = s / a - g = sinca - gprime = (c - g) / a2 - V = -sinca + gprime * Z - ∂exp = [ - c + sinca * Z, + e = Rotor{typeof(c)}(c, g*Z[2], g*Z[3], g*Z[4]) + V = -g + g′ * Z + ∂e = [ + quaternion(e), Z[2] * V + g * imx, Z[3] * V + g * imy, Z[4] * V + g * imz, ] - (c+g*Z, ∂exp) + (e, ∂e) end diff --git a/src/gradients_interpolation.jl b/src/gradients_interpolation.jl index d814a187..d6a49010 100644 --- a/src/gradients_interpolation.jl +++ b/src/gradients_interpolation.jl @@ -3,69 +3,62 @@ Return the value and gradient of `slerp`. -The gradient is with respect to each of the input arguments in turn, with each -quaternion regarded as a series of four arguments. That is, a total of 10 -quaternions will be returned: +The gradient is with respect to each of the input arguments in turn, with each quaternion +regarded as a series of four arguments. That is, a total of 10 quaternions will be +returned: ```math \begin{aligned} - &\big[\\ - &\quad \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₁.w} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₁.x} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₁.y} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₁.z} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₂.w} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₂.x} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₂.y} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial q₂.z} \mathrm{slerp}(q₁, q₂, τ), \\ - &\quad \frac{\partial}{\partial \tau} \mathrm{slerp}(q₁, q₂, τ), \\ - &\big] + \big[ + &\mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₁.w} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₁.x} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₁.y} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₁.z} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₂.w} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₂.x} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₂.y} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial q₂.z} \mathrm{slerp}(q₁, q₂, τ), \\ + &\frac{\partial}{\partial \tau} \mathrm{slerp}(q₁, q₂, τ) + \big] \end{aligned} ``` -For convenience, this will be a 4-tuple with the `slerp` as the first element, -the first four components of the derivative, followed by the next four -components of the derivative, followed by the last component of the derivative. +For convenience, this will be a 4-tuple with the `slerp` as the first element, the first +four components of the derivative, followed by the next four components of the derivative, +followed by the last component of the derivative. The first element is a `Rotor`, and each +derivative is a general `Quaternion`. As with [`∂log`](@ref), the derivatives with respect +to the components of `q₁` and `q₂` include "off-shell" directions that would change their +norms. -See also [`slerp`](@ref) for just the value, and [`slerp∂slerp∂τ`](@ref) for -just the value and the derivative with respect to `τ`. +See also [`slerp`](@ref) for just the value, and [`slerp∂slerp∂τ`](@ref) for just the value +and the derivative with respect to `τ`. # Examples ```julia -julia> (q1, q2), τ = randn(RotorF64, 2), rand(); +julia> (q₁, q₂), τ = randn(RotorF64, 2), rand(); julia> s, ∂s∂q₁, ∂s∂q₂, ∂s∂τ = slerp∂slerp(q₁, q₂, τ); ``` """ function slerp∂slerp(q₁::Rotor, q₂::Rotor, τ::Real) + # slerp(q₁, q₂, τ) = exp(τ log(r)) q₁, where r = q₂ / q₁. r = q₂ / q₁ - basis = typeof(r)[1, imx, imy, imz] l, ∂l = log∂log(r) e, ∂e = exp∂exp(τ*l) s = e * q₁ + # ∂e∂r[c] is the derivative of e with respect to r[c]. + ∂e∂r = [τ * sum(∂e[b] * ∂l[c][b] for b in 1:4) for c in 1:4] + # The derivative of s along a change δr of r is (Σ_c ∂e∂r[c] δr[c]) q₁. + ∂s∂r(δr) = sum(∂e∂r[c] * δr[c] for c in 1:4) * q₁ + T = basetype(r) + basis = ( + Quaternion{T}(1, 0, 0, 0), Quaternion{T}(0, 1, 0, 0), + Quaternion{T}(0, 0, 1, 0), Quaternion{T}(0, 0, 0, 1) + ) ( s, - [ - sum( - ∂e[b] * τ * ∂l[c][b] * ( - q₂ * conj(basis[a]) #/ abs2(q₁) - - 2q₁[a] * (q₂/q₁) #/ abs2(q₁) - )[c] * q₁ - for b in 1:4 - for c in 1:4 - ) + e * basis[a] - for a in 1:4 - ], - [ - sum( - ∂e[b] * τ * ∂l[c][b] * ( - basis[a] / q₁ - )[c] * q₁ - for b in 1:4 - for c in 1:4 - ) - for a in 1:4 - ], + [∂s∂r(q₂ * conj(basis[a]) - 2q₁[a] * r) + e * basis[a] for a in 1:4], + [∂s∂r(basis[a] / q₁) for a in 1:4], l * s ) end @@ -74,10 +67,10 @@ end """ slerp∂slerp∂τ(q₁, q₂, τ) -Return the value and time-derivative of `slerp`. +Return the value of `slerp` and its derivative with respect to `τ`. -See also [`slerp∂slerp`](@ref), which returns the value and *all* of the -derivatives of `slerp`. +See also [`slerp∂slerp`](@ref), which returns the value and *all* of the derivatives of +`slerp`. """ function slerp∂slerp∂τ(q₁::Rotor, q₂::Rotor, τ::Real) @@ -94,35 +87,40 @@ end Compute the value and time-derivative of [`squad`](@ref). -This is primarily an internal helper function, taking various parameters -computed within the `squad` function. This will be used to compute the -derivative of `squad` when the angular velocity is also requested. To actually -obtain the derivative, simply pass the relevant keyword to the `squad` -function. +This is primarily an internal helper function, taking various parameters computed within the +`squad` function. This will be used to compute the derivative of `squad` when the angular +velocity is also requested. To actually obtain the derivative, simply pass the relevant +keyword to the `squad` function. """ function squad∂squad∂t(qᵢ, A, B, qᵢ₊₁, ta, tb, t) - # squad = slerp(slerp(qᵢ, qᵢ₊₁, τ), slerp(A, B, τ), 2τ*(1-τ)) - # τ = (t - ta) / (tb - ta) - # ∂τ∂t = 1 / (tb - ta) - # ∂(2τ*(1-τ))/∂t = ∂τ/∂t * (2 - 4τ) + # squad = slerp(X, Y, σ), with + # X = slerp(qᵢ, qᵢ₊₁, τ), Y = slerp(A, B, τ), σ = 2τ(1-τ), τ = (t - ta) / (tb - ta). + # Writing slerp(X, Y, σ) = exp(σ log(r)) X with r = Y / X, the derivative along τ is + # ∂s/∂τ = (∂e/∂τ) X + e ∂X/∂τ, where e = exp(σ log(r)), + # and ∂e/∂τ follows from the chain rule through `exp∂exp` and `log∂log`, using + # ∂r/∂τ = (∂Y/∂τ - r ∂X/∂τ) / X. + # This directional derivative avoids building the full Jacobians of `slerp∂slerp`. τ = (t - ta) / (tb - ta) ∂τ∂t = 1 / (tb - ta) X, ∂X∂τ = slerp∂slerp∂τ(qᵢ, qᵢ₊₁, τ) - ∂X∂t = ∂τ∂t * ∂X∂τ - Y, ∂Y∂τ = slerp∂slerp∂τ(A, B, τ) - ∂Y∂t = ∂τ∂t * ∂Y∂τ - s, ∂s∂X, ∂s∂Y, ∂s∂τparabola = slerp∂slerp(X, Y, 2τ*(1-τ)) - ∂s∂t = ∂τ∂t * (2 - 4τ) * ∂s∂τparabola + σ = 2τ*(1-τ) + ∂σ∂τ = 2 - 4τ - ( - s, - sum(∂X∂t[b] * ∂s∂X[b] for b in 1:4) - + sum(∂Y∂t[b] * ∂s∂Y[b] for b in 1:4) - + ∂s∂t - ) + r = Y / X + ∂r∂τ = (∂Y∂τ - r * ∂X∂τ) / X + l, ∂l = log∂log(r) + ∂l∂τ = sum(∂l[c] * ∂r∂τ[c] for c in 1:4) + e, ∂e = exp∂exp(σ*l) + ∂σl∂τ = ∂σ∂τ * l + σ * ∂l∂τ + ∂e∂τ = sum(∂e[b] * ∂σl∂τ[b] for b in 1:4) + + s = e * X + ∂s∂τ = ∂e∂τ * X + e * ∂X∂τ + + (s, ∂τ∂t * ∂s∂τ) end diff --git a/src/interpolation.jl b/src/interpolation.jl index a78d738e..3ab382cd 100644 --- a/src/interpolation.jl +++ b/src/interpolation.jl @@ -7,29 +7,42 @@ const Rotator = Union{Quaternion, Rotor} -function _unflip!(q, Rpre, R, Rpost) +# The sign test uses the real part of the inner product, so that complex quaternions are +# also supported. For a Lorentz rotor, the real part of the scalar part of the relative +# transformation is cos(θ/2) cosh(η/2), which selects the hemisphere just as in the real +# case. + +# In-place worker: `I` is the axis along the dimension being unflipped, and `Rpre` and +# `Rpost` are the Cartesian indices before and after that dimension. +function unflip!(q::AbstractArray, Rpre::CartesianIndices, I::AbstractUnitRange, Rpost::CartesianIndices) @inbounds for Ipost in Rpost - for i in R + for i in first(I)+1:last(I) for Ipre in Rpre - if q[Ipre, i-1, Ipost] ⋅ q[Ipre, i, Ipost] < 0 - q[Ipre, i, Ipost] *= -1 + if real(q[Ipre, i-1, Ipost] ⋅ q[Ipre, i, Ipost]) < 0 + # Unary minus is exact and keeps the element type; multiplying a + # `Rotor` by -1 would give a `Quaternion`, which is renormalized when + # it is stored back. + q[Ipre, i, Ipost] = -q[Ipre, i, Ipost] end end end end + q end -function _unflip!(q, p, Rpre, R, Rpost) +# Copying worker: the unflipped values of `q` are written into `p`, which has the same axes. +function unflip!(p::AbstractArray, q::AbstractArray, Rpre::CartesianIndices, I::AbstractUnitRange, Rpost::CartesianIndices) + isempty(I) && return p @inbounds for Ipost in Rpost - let i = 1 + let i = first(I) for Ipre in Rpre p[Ipre, i, Ipost] = q[Ipre, i, Ipost] end end - for i in R + for i in first(I)+1:last(I) for Ipre in Rpre - if p[Ipre, i-1, Ipost] ⋅ q[Ipre, i, Ipost] < 0 + if real(p[Ipre, i-1, Ipost] ⋅ q[Ipre, i, Ipost]) < 0 p[Ipre, i, Ipost] = -q[Ipre, i, Ipost] else p[Ipre, i, Ipost] = q[Ipre, i, Ipost] @@ -37,28 +50,25 @@ function _unflip!(q, p, Rpre, R, Rpost) end end end -end - - -function unflip!(q::AbstractArray{<:AbstractQuaternion}; dim::Integer=1) - Rpre = CartesianIndices(size(q)[1:dim-1]) - R = 2:size(q, dim) - Rpost = CartesianIndices(size(q)[dim+1:end]) - _unflip!(q, Rpre, R, Rpost) + p end """ - unflip(q, [dim=1]) - unflip!(q, [dim=1]) + unflip(q; dim=1) + unflip!(q; dim=1) + +Flip the signs of successive quaternions along dimension `dim` so that they are as +continuous as possible. -Flip the signs of successive quaternions along dimension `dim` so that they are -as continuous as possible. +If `q` represents a series of rotations, the sign of each element is arbitrary. However, +for certain purposes — such as interpolation and differentiation — the continuity of the +quaternions matters, and so we want the *quaternions* to be as continuous as possible +without changing the *rotations* that they represent. -If `q` represents a series of rotations, the sign of each element is arbitrary. -However, for certain purposes — such as interpolation and differentiation — the -continuity of the quaternions matters, and so we want the *quaternions* to be -as continuous as possible without changing the *rotations* that they represent. +The first element along `dim` is never changed. Each subsequent element is negated if the +real part of its inner product with the (possibly negated) preceding element is negative. +`unflip` returns a new array, while `unflip!` modifies `q` in place and returns it. # Examples ```jldoctest @@ -73,12 +83,24 @@ julia> unflip(q) ``` """ function unflip(q::AbstractArray{<:AbstractQuaternion}; dim::Integer=1) - p = similar(q) - Rpre = CartesianIndices(size(q)[1:dim-1]) - R = 2:size(q, dim) - Rpost = CartesianIndices(size(q)[dim+1:end]) - _unflip!(q, p, Rpre, R, Rpost) - p + Rpre = CartesianIndices(axes(q)[1:dim-1]) + I = axes(q, dim) + Rpost = CartesianIndices(axes(q)[dim+1:end]) + unflip!(similar(q), q, Rpre, I, Rpost) +end + + +""" + unflip!(q; dim=1) + +Flip the signs of successive quaternions along dimension `dim` of `q` in place, and return +`q`. See [`unflip`](@ref) for details. +""" +function unflip!(q::AbstractArray{<:AbstractQuaternion}; dim::Integer=1) + Rpre = CartesianIndices(axes(q)[1:dim-1]) + I = axes(q, dim) + Rpost = CartesianIndices(axes(q)[dim+1:end]) + unflip!(q, Rpre, I, Rpost) end @@ -109,7 +131,7 @@ function and its derivative with respect to each parameter of the input. """ function slerp(q₁::R1, q₂::R2, τ::Real; unflip::Bool=false) where {R1<:Rotator, R2<:Rotator} - if unflip && q₁⋅q₂ < 0 + if unflip && real(q₁⋅q₂) < 0 return (-q₂ / q₁)^τ * q₁ end (q₂ / q₁)^τ * q₁ @@ -117,10 +139,11 @@ end @doc raw""" - squad_control_points(R::AbstractVector{Rotor}, t::AbstractVector{<:AbstractFloat}, i::Int) + squad_control_points(R::AbstractVector{<:Rotor}, t::AbstractVector{<:Real}, i::Int) -This is a helper function for the `squad` routines, returning the control -points between one pair of input rotors. +This is a helper function for the `squad` routines, returning the control points between one +pair of input rotors. Both control points are returned as `Rotor`s of the same type, which +is promoted from the types of `R` and `t`. The expressions for ``A`` and ``B`` (assuming all indices are valid) are ```math @@ -156,11 +179,15 @@ B_{\mathrm{end}} &= R_{\mathrm{end}}\, \bar{R}_{\mathrm{end-1}}\, R_{\mathrm{end \end{aligned} ``` """ -function squad_control_points(R::AbstractVector{<:Rotor}, t::AbstractVector{<:AbstractFloat}, i::Int) +function squad_control_points(R::AbstractVector{<:Rotor}, t::AbstractVector{<:Real}, i::Int) + # Both control points are converted to one type, so that the return type does not depend + # on `i`. + RT = Rotor{promote_type(basetype(eltype(R)), typeof(float(one(eltype(t)))))} + n = length(R) if i==1 A = R[1] - elseif i==length(R) - A = R[end] # COV_EXCL_LINE + elseif i==n + A = R[n] # COV_EXCL_LINE else A = R[i] * exp( ( @@ -169,19 +196,19 @@ function squad_control_points(R::AbstractVector{<:Rotor}, t::AbstractVector{<:Ab ) / 4 ) end - if i 0 + minimum(diff(tin)) > 0 || + throw(ArgumentError("`tin` must be strictly increasing")) if length(tout) > 1 - @assert minimum(diff(tout)) > 0 - tout_begin, tout_end = extrema(tout) - @assert t_begin ≤ tout_begin - @assert tout_end ≤ t_end - elseif length(tout) == 1 - @assert t_begin ≤ tout[1] ≤ t_end + minimum(diff(tout)) > 0 || + throw(ArgumentError("`tout` must be strictly increasing")) end + tout_begin, tout_end = extrema(tout) + t_begin ≤ tout_begin && tout_end ≤ t_end || + throw(ArgumentError("`tout` must lie within [$t_begin, $t_end]")) end if unflip Rin = unflip_func(Rin) end + n = length(tin) j = 1 - toutj = tout[j] - if toutj == tin[1] - if evaluate_Ω⃗ || evaluate_Ṙ + while j ≤ length(Rout) + # The segment is located by value. AD types such as `ForwardDiff.Dual` may also + # compare their partials when their values are equal, which would push a time equal + # to a knot into a neighboring segment, or out of range at either end. + toutj = value(tout[j]) + i = searchsortedfirst(tin, toutj; by=value) - 1 + if i == 0 && toutj == value(tin[1]) i = 1 - A, B = squad_control_points(Rin, tin, i) - ta, tb = tin[i], tin[i+1] - qᵢ, qᵢ₊₁ = Rin[i], Rin[i+1] - s, ∂s∂t = squad∂squad∂t(qᵢ, A, B, qᵢ₊₁, ta, tb, tout[j]) - if evaluate_Ω⃗ - Ω⃗out[j] = 2 * eltype(Ω⃗out)(∂s∂t / s) - end - if evaluate_Ṙ - Ṙout[j] = ∂s∂t - end end - Rout[1] = Rin[1] - j += 1 - end - while j ≤ length(Rout) - toutj = tout[j] - i = searchsortedfirst(tin, toutj) - 1 - if i == length(tin) - error("Searching for $toutj went out of range [$t_begin, $t_end]") # COV_EXCL_LINE + if i < 1 || i ≥ n + error("Searching for $(tout[j]) went out of range [$t_begin, $t_end]") end A, B = squad_control_points(Rin, tin, i) ta, tb = tin[i], tin[i+1] qᵢ, qᵢ₊₁ = Rin[i], Rin[i+1] - while j ≤ length(Rout) && tb ≥ tout[j] + # Both ends of the segment are checked, so that an out-of-order time goes back to + # the segment search instead of being extrapolated from the current segment. + while j ≤ length(Rout) && value(ta) ≤ value(tout[j]) ≤ value(tb) if evaluate_Ω⃗ || evaluate_Ṙ s, ∂s∂t = squad∂squad∂t(qᵢ, A, B, qᵢ₊₁, ta, tb, tout[j]) Rout[j] = s @@ -276,7 +304,8 @@ function squad!( Ṙout[j] = ∂s∂t end else - τ = (tout[j] - ta) / (tb - ta) + # `float` keeps rational times away from `^(::Rotor, ::Rational)`. + τ = float((tout[j] - ta) / (tb - ta)) Rout[j] = slerp( slerp(qᵢ, qᵢ₊₁, τ), slerp(A, B, τ), @@ -288,76 +317,87 @@ function squad!( end end +function squad!( + Rout::AbstractVector{<:Rotor}, Rin::AbstractVector{<:Rotor}, tin::AbstractVector{<:Real}, + tout::AbstractVector{<:Real}; unflip=false, validate=false +) + squad!(Rout, nothing, nothing, Rin, tin, tout; unflip=unflip, validate=validate) +end """ squad(Rin, tin, tout; [kwargs...]) -"Spherical QUADrangle interpolation" of the input `Rotor`s `Rin` with -corresponding times `tin`, to the output times `tout`. +"Spherical QUADrangle interpolation" of the input `Rotor`s `Rin` with corresponding times +`tin`, to the output times `tout`. This is a slightly generalized version of [Shoemake's "spherical Bézier -curves"](https://doi.org/10.1145/325165.325242), to allow for time steps of -varying sizes. +curves"](https://doi.org/10.1145/325165.325242), to allow for time steps of varying sizes. -The input `Rin` and `tin` must be vectors of the same length. The output -`tout` may be either a single real number or a vector of real numbers. Both -`tin` and `tout` are assumed to be sorted, and `tout` is assumed to be -contained entirely within `tin`; no extrapolation will be done. +The input `Rin` and `tin` must be vectors of the same length. The output `tout` may be +either a single real number or a vector of real numbers. The times `tin` are assumed to be +strictly increasing, and `tout` must be contained entirely within the range of `tin`; no +extrapolation will be done. Sorted `tout` is evaluated most efficiently, but the result is +correct for any order. See also [`squad!`](@ref) for in-place versions of this function. # Keyword arguments -If `unflip=true` is passed as a keyword, the [`unflip`](@ref) function will be -applied to `Rin`. +If `unflip=true` is passed as a keyword, the [`unflip`](@ref) function will be applied to +`Rin`. -If `validate=true` is passed as a keyword, the time ordering of the input `tin` -and `tout` will be tested to ensure that no extrapolation will be done. +If `validate=true` is passed as a keyword, the time ordering of the input `tin` and `tout` +will be tested to ensure that no extrapolation will be done, and an `ArgumentError` will be +thrown otherwise. Even without validation, an error is thrown when an element of `tout` +falls outside the range of `tin`. -If `compute_angular_velocity=true` is passed as a keyword, the return value -will be a tuple. The first element of the tuple will be a vector of `Rotor`s -as before, but the second element will be a vector of `QuatVec`s representing -the angular velocity. +If `compute_angular_velocity=true` is passed as a keyword, the return value will be a tuple. +The first element of the tuple will be a vector of `Rotor`s as before, but the second +element will be a vector of `QuatVec`s representing the angular velocity. -If `compute_derivative=true` is passed as a keyword, the return value will be -a tuple. The first element of the tuple will be a vector of `Rotor`s as -before, but the last element will be a vector of `Quaternion`s representing the -time-derivative of the rotors. Note that if `compute_angular_velocity=true`, -this tuple will have three elements. +If `compute_derivative=true` is passed as a keyword, the return value will be a tuple. The +first element of the tuple will be a vector of `Rotor`s as before, but the last element will +be a vector of `Quaternion`s representing the time-derivative of the rotors. Note that if +`compute_angular_velocity=true`, this tuple will have three elements. """ -function squad( - Rin::AbstractVector{Rotor{T}}, tin::AbstractVector{<:Real}, tout::AbstractVector{<:Real}; +@inline function squad( + Rin::AbstractVector{Rotor{T}}, tin::AbstractVector{<:Real}, tout::Union{Real, AbstractVector{<:Real}}; unflip=false, validate=false, compute_angular_velocity=false, compute_derivative=false ) where {T} + # The flags are lifted into the type domain, so that the return type can be inferred + # whenever they are constants, as they are with the default values. Inlining this + # method lets the compiler see those constants. + squad( + Rin, tin, tout, Val(compute_angular_velocity), Val(compute_derivative); + unflip=unflip, validate=validate + ) +end + +function squad( + Rin::AbstractVector{Rotor{T}}, tin::AbstractVector{<:Real}, tout::AbstractVector{<:Real}, + ::Val{Ω⃗}, ::Val{Ṙ}; unflip=false, validate=false +) where {T, Ω⃗, Ṙ} Rout_eltype = promote_type(eltype(tin), eltype(tout), T) Rout = similar(Rin, Rotor{Rout_eltype}, length(tout)) - Ω⃗out = compute_angular_velocity ? similar(Rin, QuatVec{Rout_eltype}, length(tout)) : nothing - Ṙout = compute_derivative ? similar(Rin, Quaternion{Rout_eltype}, length(tout)) : nothing + Ω⃗out = Ω⃗ ? similar(Rin, QuatVec{Rout_eltype}, length(tout)) : nothing + Ṙout = Ṙ ? similar(Rin, Quaternion{Rout_eltype}, length(tout)) : nothing squad!(Rout, Ω⃗out, Ṙout, Rin, tin, tout; unflip=unflip, validate=validate) - if compute_angular_velocity && compute_derivative + if Ω⃗ && Ṙ return (Rout, Ω⃗out, Ṙout) - elseif compute_angular_velocity + elseif Ω⃗ return (Rout, Ω⃗out) - elseif compute_derivative + elseif Ṙ return (Rout, Ṙout) end return Rout end - function squad( - Rin::AbstractVector{Rotor{T}}, tin::AbstractVector{<:Real}, tout::Real; - unflip=false, validate=false, compute_angular_velocity=false, compute_derivative=false + Rin::AbstractVector{Rotor{T}}, tin::AbstractVector{<:Real}, tout::Real, + Ω⃗::Val, Ṙ::Val; unflip=false, validate=false ) where {T} - result = squad(Rin, tin, [tout]; unflip, validate, compute_angular_velocity, compute_derivative) - if compute_angular_velocity && compute_derivative - return (result[1][1], result[2][1], result[3][1]) - elseif compute_angular_velocity - return (result[1][1], result[2][1]) - elseif compute_derivative - return (result[1][1], result[2][1]) - end - return result[1] + result = squad(Rin, tin, [tout], Ω⃗, Ṙ; unflip=unflip, validate=validate) + result isa Tuple ? map(first, result) : result[1] end diff --git a/src/math.jl b/src/math.jl index eecd0ba1..cdf6e06d 100644 --- a/src/math.jl +++ b/src/math.jl @@ -7,6 +7,11 @@ Sum of the squares of all four components of the quaternion. Note that the result for a `Rotor` is identically 1, even if that is not true numerically. +For complex components, as used to represent elements of the spacetime algebra (see +[`Lorentz`](@ref)), this is the complex "spinor norm" ``\\sum_i z_i^2``, which is a complex +number that may even vanish for a nonzero quaternion; it is *not* the Euclidean sum +``\\sum_i |z_i|^2``. Use `norm` to obtain the Euclidean norm. + # Examples ```jldoctest julia> abs2(quaternion(1,2,4,10)) @@ -15,31 +20,51 @@ julia> abs2(quaternion(1,2,4,10)) """ Base.abs2(q::AbstractQuaternion) = sum(abs2, components(q)) Base.abs2(q::AbstractQuaternion{T}) where {T<:Real} = sum(x->x^2, components(q)) -Base.abs2(q::AbstractQuaternion{Complex{T}}) where {T<:Real} = sum(z->z^2, components(q)) +Base.abs2(q::AbstractQuaternion{Complex{T}}) where {T<:Real} = sum(z->z*z, components(q)) Base.abs2(q::QuatVec) = sum(abs2, vec(q)) Base.abs2(q::QuatVec{T}) where {T<:Real} = sum(x->x^2, vec(q)) -Base.abs2(q::QuatVec{Complex{T}}) where {T<:Real} = sum(z->z^2, vec(q)) +# For complex components, the sum is written out rather than taken over the view that `vec` +# returns; see the comment on `absvec` below. +Base.abs2(q::QuatVec{Complex{T}}) where {T<:Real} = q[2]*q[2] + q[3]*q[3] + q[4]*q[4] Base.abs2(::Rotor{T}) where {T<:Number} = one(real(T)) +# WORKAROUND for Enzyme bugs (EnzymeAD/Enzyme.jl#3775). `hypotenuse` is just `hypot` +# of three or four numbers. Except for complex components, `abs` and `absvec` call this +# function rather than `hypot` itself, only so that `QuaternionicEnzymeExt` can give it +# rules whose arguments are the components, which are numbers. Rules on `abs` and `absvec` +# themselves would take a quaternion argument, and Enzyme's handling of such rules crashes +# on x86_64 processors with AVX; see the extension. Once that bug and the bug in Enzyme's +# own rule for `hypot` (also described in the extension) are fixed, `abs` and `absvec` +# should call `hypot` directly again, and this function and its rules should be removed. +hypotenuse(x, y, z) = hypot(x, y, z) +hypotenuse(w, x, y, z) = hypot(w, x, y, z) + """ abs(q) Square root of the sum of the squares of all four components of the quaternion. -This function uses Julia's built-in `hypot` function to avoid overflow and underflow. +For real components, this function uses Julia's built-in `hypot` function to avoid overflow +and underflow. Note that the result for a `Rotor` is identically 1, even if that is not true numerically. +For complex components, this is the principal square root of the complex spinor norm +[`abs2`](@ref), computed with a rescaling that likewise avoids overflow and underflow. It +is a complex number in general, and may vanish for a nonzero quaternion. Use `norm` to +obtain the real Euclidean norm. + # Examples ```jldoctest julia> abs(quaternion(1,2,4,10)) 11.0 ``` """ -Base.abs(q::AbstractQuaternion) = hypot(components(q)...) +Base.abs(q::AbstractQuaternion) = hypotenuse(components(q)...) Base.abs(q::AbstractQuaternion{Complex{T}}) where {T<:Real} = _hypot(components(q)) -Base.abs(q::QuatVec) = hypot(vec(q)...) -Base.abs(q::QuatVec{Complex{T}}) where {T<:Real} = _hypot(vec(q)) +Base.abs(q::QuatVec) = hypotenuse(vec(q)...) +# See the comment on `absvec` below. +Base.abs(q::QuatVec{Complex{T}}) where {T<:Real} = _hypot(SVector{3}(q[2], q[3], q[4])) Base.abs(::Rotor{T}) where {T<:Number} = one(real(T)) """ @@ -47,6 +72,9 @@ Base.abs(::Rotor{T}) where {T<:Number} = one(real(T)) Sum of the squares of the three "vector" components of the quaternion. +For complex components, this is the complex sum ``\\sum_i z_i^2`` over the vector +components, as with [`abs2`](@ref). + # Examples ```jldoctest julia> abs2vec(quaternion(1,2,3,6)) @@ -55,14 +83,18 @@ julia> abs2vec(quaternion(1,2,3,6)) """ abs2vec(q::AbstractQuaternion) = sum(abs2, vec(q)) abs2vec(q::AbstractQuaternion{T}) where {T<:Real} = sum(x->x^2, vec(q)) -abs2vec(q::AbstractQuaternion{Complex{T}}) where {T<:Real} = sum(z->z^2, vec(q)) +# For complex components, the sum is written out rather than taken over the view that `vec` +# returns; see the comment on `absvec` below. +abs2vec(q::AbstractQuaternion{Complex{T}}) where {T<:Real} = q[2]*q[2] + q[3]*q[3] + q[4]*q[4] """ absvec(q) Square root of the sum of the squares of the three "vector" components of the quaternion. -This function uses Julia's built-in `hypot` function to avoid overflow and underflow. +For real components, this function uses Julia's built-in `hypot` function to avoid +overflow and underflow. For complex components, this is the principal square root of the +complex sum [`abs2vec`](@ref), as with [`abs`](@ref). # Examples ```jldoctest @@ -70,15 +102,128 @@ julia> absvec(quaternion(1,2,3,6)) 7.0 ``` """ -absvec(q::AbstractQuaternion) = hypot(vec(q)...) -absvec(q::AbstractQuaternion{Complex{T}}) where {T<:Real} = _hypot(vec(q)) +absvec(q::AbstractQuaternion) = hypotenuse(vec(q)...) +# For complex components, the vector part is passed to `_hypot` as an `SVector` rather than +# as the view that `vec` returns, because Enzyme 0.13.209 aborts in reverse mode on +# reductions over that view of complex numbers (an upstream bug). The value is the same. +absvec(q::AbstractQuaternion{Complex{T}}) where {T<:Real} = _hypot(SVector{3}(q[2], q[3], q[4])) + +""" + norm(q) + +Euclidean norm of the quaternion `q`. + +For real components, this equals [`abs(q)`](@ref abs); in particular, it is identically 1 +for a `Rotor`. For complex components, it is instead the real, nonnegative Euclidean norm +``\\sqrt{\\sum_i |z_i|^2}`` of the eight real numbers making up the four components, whereas +`abs` and `abs2` return the complex spinor norm. This is the norm with which `≈` +(`isapprox`) compares quaternions with complex components. + +# Examples +```jldoctest +julia> norm(quaternion(1,2,4,10)) +11.0 +julia> norm(Quaternion{ComplexF64}(1, 1im, 0, 0)) +1.4142135623730951 +``` +""" LinearAlgebra.norm(q::AbstractQuaternion) = abs(q) +LinearAlgebra.norm(q::AbstractQuaternion{<:Complex}) = norm(components(q)) Base.inv(q::AbstractQuaternion) = conj(q) / abs2(q) +function Base.inv(q::Union{Quaternion{T},QuatVec{T}}) where {T<:AbstractFloat} + a² = abs2(q) + if floatmin(T) ≤ a² < T(Inf) + return conj(q) / a² + end + m = maximum(abs, components(q)) + if iszero(m) || !isfinite(m) + return conj(q) / a² # Inf or NaN, as appropriate + end + # `abs2` overflowed or underflowed, so rescale `q` by 2⁻ᵉ, which is exact, to bring its + # largest component near 1. Then inv(q) = 2⁻ᵉ inv(2⁻ᵉ q). The factor 2⁻ᵉ itself may + # not be representable, so `ldexp` is applied to each component instead. + e = exponent(m) + p = typeof(q)(ldexp.(components(q), -e)) + r = conj(p) / abs2(p) + return typeof(r)(ldexp.(components(r), -e)) +end Base.inv(q::Rotor) = conj(q) # Specialize to ensure output is also a Rotor +# The following functions implement the Taylor series used by `exp`, `log`, and `^` near the +# identity, along with the test for whether the series applies. The coefficients are +# written as ratios of small integers, applied by nested multiplication and division, so +# that they are exact and cheap for every element type, including `Float16`, `BigFloat`, and +# `Double64`, and so that they do not lose accuracy when converted. + +# The threshold ε^(1/8) below which the series are used, where `ε` is the machine epsilon. +# The truncation error of `atanseries` and `logseries` is then about x⁸/17 ≤ ε, while the +# general branches are kept away from the region where their derivatives lose accuracy. +seriestolerance(::Type{T}) where {T<:AbstractFloat} = sqrt(sqrt(sqrt(eps(T)))) + +# The threshold for `cosseries` and `sincseries`, whose truncation error is about y⁶/12!. +# For `Float64`, `Float32`, and `Float16`, ε^(1/8) is small enough that this error is below +# ε, but for types with more than about 114 bits of precision, such as `BigFloat`, it is +# not, so the threshold is reduced to 27ε^(1/6) ≤ (12! ε)^(1/6) for them. The sixth root is +# computed with `exp` and `log`, because `cbrt(::Double64)` returns a tuple. +function trigseriestolerance(::Type{T}) where {T<:AbstractFloat} + min(seriestolerance(T), 27 * exp(log(eps(T)) / 6)) +end + +# Return `true` if `|x|` is at most `tolerance(T)`, where `T` is the floating-point type of +# the value of `x`. The test is applied to `value(x)`, so that dual numbers take the same +# branch as their values, whatever their partials are. For types whose values are not +# floating-point numbers, such as symbolic types, the size of `x` cannot be tested, so this +# returns `iszerovalue(x)`. +issmallvalue(x, tolerance=seriestolerance) = issmallvalue(value(x), x, tolerance) +function issmallvalue(v::Union{T,Complex{T}}, _, tolerance) where {T<:AbstractFloat} + abs(v) ≤ tolerance(T) +end +issmallvalue(_, x, _) = iszerovalue(x) + +# Return `true` if the vector part of `q` is small compared to its scalar part, in the sense +# that `|abs2vec(q)| ≤ ε^(1/8) |q[1]|²`. As with `issmallvalue`, the test is applied to the +# values of the components, and reduces to `iszerovalue(vec(q))` for other types. The +# components are rescaled first, so that the squares cannot underflow. +isnearscalar(q::AbstractQuaternion) = isnearscalar(value.(components(q)), q) +function isnearscalar(c::SVector{4,<:Union{T,Complex{T}}}, _) where {T<:AbstractFloat} + m = maximum(abs, c) + iszero(m) && return true + c = c / m + abs(c[2]*c[2] + c[3]*c[3] + c[4]*c[4]) ≤ seriestolerance(T) * abs(c[1]*c[1]) +end +isnearscalar(_, q) = iszerovalue(vec(q)) + +# cos(√y), accurate when `issmallvalue(y, trigseriestolerance)` +cosseries(y) = 1 - y/2 * (1 - y/12 * (1 - y/30 * (1 - y/56 * (1 - y/90)))) + +# sin(√y)/√y, accurate when `issmallvalue(y, trigseriestolerance)` +sincseries(y) = 1 - y/6 * (1 - y/20 * (1 - y/42 * (1 - y/72 * (1 - y/110)))) + +# atan(√x)/√x, accurate when `issmallvalue(x)` +function atanseries(x) + 1 - x/3 * (1 - 3x/5 * (1 - 5x/7 * (1 - 7x/9 * (1 - 9x/11 * (1 - 11x/13 * (1 - 13x/15)))))) +end + +# √(1+x) atan(√x)/√x, accurate when `issmallvalue(x)`. This is v/sin(v) for the angle v +# with tan(v) = √x. For a complex `Rotor`, `x` is complex, so its square root goes +# through `csqrt`. +logseries(x) = atanseries(x) * csqrt(1 + x) + +# log(abs(q)) for a `Quaternion` with `a = abs(q)`. When `a` is close to 1, `log(a)` loses +# relative accuracy because `a` itself is rounded, so we evaluate log1p(|q|² - 1)/2, with +# |q|² - 1 computed in a form that is accurate near |q| = 1. +function logabs(q, a) + if abs2(a - 1) < 0.25 + log1p((q[1] - 1) * (q[1] + 1) + abs2vec(q)) / 2 + else + log(a) + end +end + + @doc raw""" log(q) @@ -119,17 +264,16 @@ julia> log(quaternion(-exp(7))) # Notes -This function uses an accurate algorithm for finding the logarithm, although automatic -differentiation may become inaccurate near the negative real axis because the analytic -derivatives blow up there. - The `log` function is very analogous to the [`sqrt`](@ref) function [which is essentially `exp(log(q)/2)`], in that both functions have discontinuous behavior along the negative real axis, and derivatives that blow up as you approach that axis. Therefore, the same caveats -about computing derivatives using automatic differentiation apply here as well. -Specifically, those derivatives will be numerically unstable near the negative real axis, -and will be incorrect *on* the negative real axis itself; rather than being undefined, the -derivatives will typically be returned as zero because of our fixed choice of result there. +about computing derivatives using automatic differentiation apply to both functions. + +Integer and rational components are converted to floating-point numbers first. Because the +algorithm chooses its branch by comparing component values, symbolic component types such as +`Symbolics.Num` instead get the general formula ``\log|q| + \arctan(|\vec{v}|, w)\, +\vec{v}/|\vec{v}|`` (from the Symbolics extension), which should not be evaluated on the +real axis by direct substitution. If we decompose the result of this function as ``\log(q) = s + \vec{v}``, where ``s`` is the scalar part and ``\vec{v}`` is the pure-vector part, then clearly ``s`` and ``\vec{v}`` @@ -139,9 +283,10 @@ q = \exp\left(\log(q)\right) = \exp\left(s\right) \exp\left(\vec{v}\right). ``` Note that the exponential of a pure-vector quaternion is a unit quaternion, so we have decomposed ``q`` into a product of a positive real number and a unit quaternion. We already -know how to take the logarithm of a positive real number. Therefore, in the following we -assume that ``q`` is a unit quaternion, so that ``s=0`` and we only need to find -``\vec{v}``. +know how to take the logarithm of a positive real number; when ``|q|`` is close to 1, we +compute it as `log1p(abs2(q) - 1)/2`, with `abs2(q) - 1` evaluated without cancellation, for +accuracy. Therefore, in the following we assume that ``q`` is a unit quaternion, so that +``s=0`` and we only need to find ``\vec{v}``. We now write ``\log(q)`` as ``v\hat{v}``, where ``v`` is just the scalar norm. Note that, because of the periodicity of the `exp` function, we can assume that ``v \in [0, \pi]`` and, @@ -154,139 +299,164 @@ into ``v`` and ``\hat{v}``. But we can find ``\cos(v)`` as the scalar part of t and ``\sin(v)`` as the `absvec` (since we know that ``\sin(v) \geq 0``). Then, we can compute ``v = \mathrm{atan}(\sin(v), \cos(v))``. And finally, we simply multiply the vector part of the input by ``v / \sin(v)`` to obtain the logarithm. This factor is given -accurately by `invsinc(v)` whenever ``|v| \leq \pi/2``. - -When that condition is not satisfied (which also implies ``\cos(v)<0``, we can rewrite the +accurately by `invsinc(v)` whenever ``|v| \leq \pi/2``. Near the identity, where the vector +part is small compared to the scalar part, ``\sin(v)`` is the square root of a small number, +whose derivatives lose accuracy; there, we instead evaluate ``v/\sin(v)`` as a Taylor series +in ``x = |\vec{q}|^2 / q[1]^2 = \tan^2(v)``, so that automatic differentiation remains +accurate. + +When ``|v| > \pi/2`` (which also implies ``\cos(v)<0``), we instead define ``v' = \pi - +v``, so that ``\cos(v') = -\cos(v)`` and ``\sin(v') = \sin(v)``, and we can rewrite the problem as ```math -\exp\left(v \hat{v}\right) = \cos(v) + \hat{v} \sin(v) = -\cos(v-\pi) - \hat{v} \sin(v-\pi) -= -\cos(v') - \hat{v} \sin(v'). +\exp\left(v \hat{v}\right) = \cos(v) + \hat{v} \sin(v) = -\cos(v') + \hat{v} \sin(v'). ``` -Here, we want to multiply the vector component by ``-v / \sin(v') = -(v'+\pi) / \sin(v')``. -Note that we can easily compute ``v' = \mathrm{atan}(\sin(v), -\cos(v))``. This algorithm -is surprisingly accurate, even when ``v`` is extremely close to ``\pi``, which implies that -the vector part of the input is extremely small. +We can compute ``v' = \mathrm{atan}(\sin(v), -\cos(v))`` accurately, and then we need to +multiply the unit vector ``\hat{v}`` by ``v = \pi - v'``. This algorithm is surprisingly +accurate, even when ``v`` is extremely close to ``\pi``, which implies that the vector part +of the input is extremely small. The only special case remaining to handle is when ``\cos(v) < 0`` but ``\sin(v)`` is *identically* zero. In this case, we could throw an error, but this is not usually helpful. Instead, we arbitrarily choose to return ``\pi 𝐤``. +For complex components, the same formulas are used with the complex spinor norm +[`abs`](@ref) in place of the Euclidean norm. The branch is then chosen by the sign of the +real part of ``\cos(v) = q[1]/|q|``. When it is nonnegative, the angle is computed as ``v = +-i \log\left(\cos(v) + i \sin(v)\right)``, where ``i`` is the imaginary unit of the complex +components and the logarithm is the principal complex logarithm; this is smooth even where +``q[1] = 0``. Otherwise, ``v'`` is computed with the principal complex branch of `atan`. + If `q` is a `Rotor`, we return a `QuatVec`; if `q` is a general `Quaternion`, we return a -general `Quaternion` — though if `q` happens to have norm exactly 1, the result will have a -scalar part of exactly 0. Note that, because there is no geometric reason to take the -logarithm of a `QuatVec`, that case is not implemented; if you really need to compute it, -you can convert the `QuatVec` to a `Quaternion` first. +general `Quaternion` — though if `q` has unit norm, the scalar part of the result will be +zero up to roundoff. Note that, because there is no geometric reason to take the logarithm +of a `QuatVec`, that case is not implemented; if you really need to compute it, you can +convert the `QuatVec` to a `Quaternion` first. """ -function Base.log(q::Quaternion{T}) where {T} +function Base.log(q::Quaternion) + q = float(q) + T = basetype(q) if iszerovalue(q) # q == 0 return Quaternion{T}(-Inf, false, false, false) end + # When the largest component is beyond about 1e154 or below about 1e-146 (for Float64), + # the values are still right, but the derivatives of `x / y` and `atan(y, x)` that AD + # tools use contain `y²` and `x² + y²`, which overflow or underflow. In that case `q` + # is multiplied by a power of two σ = 2ᵏ that brings its largest component near 1, and + # log(q) = log(σq) - k log(2) is returned. This scaling is exact, and the vector part + # of the logarithm does not depend on |q|. As in division, the test uses only the + # values of the components, so that dual numbers are rescaled in the same way as the + # floats they contain, and the power is clamped to the range of normal numbers, so that + # the recursive call scales again if one step was not enough. + if value(q[1]) isa AbstractFloat + R = typeof(value(q[1])) + m = maximum(x -> abs(value(x)), components(q)) + if isfinite(m) && !(sqrt(floatmin(R) / eps(R)) ≤ m ≤ sqrt(floatmax(R)) / 4) + k = clamp(-exponent(m), exponent(floatmin(R)), exponent(floatmax(R))) + return log(ldexp(one(R), k) * q) - k * log(R(2)) + end + end a = abs(q) cosv = q[1] if cosv ≥ 0 # q[1] ≥ 0 - f = if iszerovalue(vec(q)) - # When the vector part vanishes, `absvec` reduces to - # `sqrt(0)`, whose infinite derivative poisons the - # derivative of the whole expression; use a series in - # `sinv²` instead. As of 2026-08-19 ForwardDiff still - # requires this branch. - sinv² = abs2vec(q) - x = sinv² / cosv^2 - (1 + x * (1//6 + x * (-11//120 + x * (103//1680)))) / a + f = if isnearscalar(q) + # Near the identity, `absvec` is the square root of a tiny number, whose + # derivatives are huge and lose all accuracy when they cancel, or are infinite + # when it is exactly 0; use a series in tan²(v) instead. + logseries(abs2vec(quatvec(q) / cosv)) else - sinv = absvec(q) - v = atan(sinv, cosv) - invsinc(v) / a + invsinc(atan(absvec(q), cosv)) end - return log(a) + f * quatvec(q) + return logabs(q, a) + f * (quatvec(q) / a) elseif iszerovalue(vec(q)) # q is a negative real number # Note that we check this branch only after ruling out cosv≥0 because this could # otherwise correspond to *positive* real numbers, which are treated correctly by # the preceding branch, but only the preceding branch will behave correctly for AD. - return Quaternion{T}(log(a), false, false, π) + return Quaternion{T}(logabs(q, a), false, false, π) else # q[1] < 0 but q⃗ ≠ 0 sinv = absvec(q) v′ = atan(sinv, -cosv) - f = -invsinc(v′) * (v′-π) / v′ / a - return log(a) + f * quatvec(q) + # Dividing the vector part by `sinv` first avoids overflow when `sinv` is tiny. + return logabs(q, a) + (π - v′) * (quatvec(q) / sinv) end end -function Base.log(q::Rotor{T}) where {T} +function Base.log(q::Rotor) + q = float(q) cosv = q[1] if cosv ≥ 0 # q[1] ≥ 0 - f = if iszerovalue(vec(q)) - # When the vector part vanishes, `absvec` reduces to - # `sqrt(0)`, whose infinite derivative poisons the - # derivative of the whole expression; use a series in - # `sinv²` instead. As of 2026-08-19 ForwardDiff still - # requires this branch. - sinv² = abs2vec(q) - x = sinv² / cosv^2 - 1 + x * (1//6 + x * (-11//120 + x * (103//1680))) + f = if isnearscalar(q) + # Series branch required for AD; see `log(::Quaternion)` above + logseries(abs2vec(quatvec(q) / cosv)) else - sinv = absvec(q) - v = atan(sinv, cosv) - invsinc(v) + invsinc(atan(absvec(q), cosv)) end return f * quatvec(q) elseif iszerovalue(vec(q)) # q is a negative real number # Note that we check this branch only after ruling out cosv≥0 because this could # otherwise correspond to *positive* real numbers, which are treated correctly by # the preceding branch, but only the preceding branch will behave correctly for AD. - return QuatVec{T}(false, false, false, π) + return QuatVec{basetype(q)}(false, false, false, π) else # q[1] < 0 but q⃗ ≠ 0 sinv = absvec(q) v′ = atan(sinv, -cosv) - f = -invsinc(v′) * (v′-π) / v′ - return f * quatvec(q) + return (π - v′) * (quatvec(q) / sinv) end end -function Base.log(q::Quaternion{Complex{T}}) where {T<:Real} +function Base.log(q::Quaternion{<:Complex}) + q = float(q) + T = basetype(q) if iszerovalue(q) - return Quaternion{Complex{T}}(Complex{T}(-Inf), false, false, false) + return Quaternion{T}(T(-Inf), false, false, false) end a = abs(q) cosv = q[1] - if real(cosv) ≥ 0 - f = if iszerovalue(vec(q)) + # The first branch below returns the angle v with -π/2 ≤ real(v) ≤ π/2, whose cosine has + # a nonnegative real part, so the branch must be chosen by cos(v) = q[1]/a, not by q[1] + # alone. + if real(cosv / a) ≥ 0 + f = if isnearscalar(q) # Series branch required for AD; see `log(::Quaternion)` above - sinv² = abs2vec(q) - x = sinv² / cosv^2 - (1 + x * (1//6 + x * (-11//120 + x * (103//1680)))) / a + logseries(abs2vec(quatvec(q) / cosv)) else + # The angle v satisfies cos(v) = cosv/a and sin(v) = sinv/a, so that exp(iv) = + # (cosv + i sinv)/a, where `i` is the imaginary unit of the components. The + # principal logarithm gives the v with -π/2 ≤ real(v) ≤ π/2 in this branch. + # Unlike atan(sinv/cosv), this is smooth where cosv = 0, so its derivatives are + # correct there too. sinv = absvec(q) - v = atan(sinv / cosv) - invsinc(v) / a + v = -im * log((cosv + im * sinv) / a) + v * a / sinv end - return log(a) + f * quatvec(q) + return logabs(q, a) + f * (quatvec(q) / a) elseif iszerovalue(vec(q)) - return Quaternion{Complex{T}}(log(a), false, false, Complex{T}(π)) + return Quaternion{T}(logabs(q, a), false, false, T(π)) else sinv = absvec(q) v′ = atan(-sinv / cosv) - f = -invsinc(v′) * (v′ - π) / v′ / a - return log(a) + f * quatvec(q) + f = -invsinc(v′) * (v′ - π) / v′ + return logabs(q, a) + f * (quatvec(q) / a) end end -function Base.log(q::Rotor{Complex{T}}) where {T<:Real} +function Base.log(q::Rotor{<:Complex}) + q = float(q) + T = basetype(q) cosv = q[1] if real(cosv) ≥ 0 - f = if iszerovalue(vec(q)) + f = if isnearscalar(q) # Series branch required for AD; see `log(::Quaternion)` above - sinv² = abs2vec(q) - x = sinv² / cosv^2 - 1 + x * (1//6 + x * (-11//120 + x * (103//1680))) + logseries(abs2vec(quatvec(q) / cosv)) else + # As in `log(::Quaternion{<:Complex})` above, with a = 1 sinv = absvec(q) - v = atan(sinv / cosv) - invsinc(v) + v = -im * log(cosv + im * sinv) + v / sinv end return f * quatvec(q) elseif iszerovalue(vec(q)) - return QuatVec{Complex{T}}(false, false, Complex{T}(π)) + return QuatVec{T}(false, false, T(π)) else sinv = absvec(q) v′ = atan(-sinv / cosv) @@ -306,11 +476,16 @@ all finite quaternions: \exp(q) = \sum_{k=0}^\infty \frac{q^k}{k!}. ``` -!!! note "Derivatives at 0" +The exponential of a `QuatVec` is a `Rotor`. The exponential of a `Quaternion` or of a +`Rotor` is a `Quaternion`. + +!!! note "Derivatives near 0" - Note that automatic differentiation of this function *at exactly* `q=0` will only be - accurate through fifth order. Using sixth-order derivatives or higher is so unusual - that this will likely not be a problem in practice. + When the vector part of `q` is small, its contribution is evaluated as a Taylor series + so that automatic differentiation is accurate there. Derivatives with respect to the + vector components *at exactly* zero vector part are therefore accurate only through + eleventh order. Using twelfth-order derivatives or higher is so unusual that this will + likely not be a problem in practice. # Examples ```jldoctest @@ -343,41 +518,52 @@ The only special case is when ``v=0``, in which case there is no unique choice o ``\hat{v}``, but then `exp(q) = exp(s)`. Unfortunately, this means that we need to use a separate branch for this isolated case, which means that automatic differentiation with respect to the vector components will incorrectly produce a derivative of zero at that point -if we do nothing but return the value. Therefore, we actually use a Taylor expansion to -compute the result through fifth order in the magnitude of the vector part. This will -produce correct derivatives up to fifth order. +if we do nothing but return the value. Moreover, when ``v`` is small but nonzero, ``v`` is +the square root of a small number, and higher derivatives computed through that square root +and through ``\sin(v)/v`` lose accuracy to cancellation. Therefore, whenever ``v^2`` is +small, we evaluate ``\cos(v)`` and ``\sin(v)/v`` as Taylor series in ``v^2``, which are +accurate to machine precision there, and give accurate derivatives. + +With symbolic component types such as `Symbolics.Num`, the vector part cannot be tested for +being small, so the general formula is returned. That expression has a removable +singularity where the vector part vanishes, so it should not be evaluated there by direct +substitution. """ -function Base.exp(q::Quaternion{T}) where {T} - e = exp(q[1]) - if iszerovalue(vec(q)) - # Take this a little seriously, to obtain accurate AD - a² = abs2vec(q) - ec = e*(1 - a²*(1 - a²/12)/2) - es = e*(1 - a²*(1 - a²/20)/6) - return Quaternion{typeof(ec)}(ec, es*q[2], es*q[3], es*q[4]) +function Base.exp(q::Quaternion) + q = float(q) + e = cexp(q[1]) + a² = abs2vec(q) + c, s = if issmallvalue(a², trigseriestolerance) + cosseries(a²), sincseries(a²) else a = absvec(q) - esinc = e * _sincu(a) - Quaternion{typeof(esinc)}(e*cos(a), esinc*q[2], esinc*q[3], esinc*q[4]) + ccos(a), _sincu(a) end + ec, es = e*c, e*s + Quaternion{typeof(ec)}(ec, es*q[2], es*q[3], es*q[4]) end -function Base.exp(v⃗::QuatVec{T}) where {T} - c, s = if iszerovalue(vec(v⃗)) - # Take this a little seriously, to obtain accurate AD - a² = abs2vec(v⃗) - 1 - a²*(1 - a²/12)/2, 1 - a²*(1 - a²/20)/6 +function Base.exp(v⃗::QuatVec) + v⃗ = float(v⃗) + a² = abs2vec(v⃗) + c, s = if issmallvalue(a², trigseriestolerance) + cosseries(a²), sincseries(a²) else a = absvec(v⃗) - cos(a), _sincu(a) + ccos(a), _sincu(a) end Rotor{typeof(c)}(c, s*v⃗[2], s*v⃗[3], s*v⃗[4]) end +Base.exp(q::Rotor) = exp(quaternion(q)) @doc raw""" sqrt(q) Square root of a quaternion. +The square root of a `Rotor` is a `Rotor`, and the square root of a `Quaternion` or of a +`QuatVec` is a `Quaternion`. (The square root of a pure vector is not a pure vector.) +Integer and rational components are converted to floating-point numbers first. + !!! note "Branch-cut behavior" As with the logarithm, the quaternionic square-root has a branch cut along the @@ -386,6 +572,10 @@ Square root of a quaternion. the complex case, the choice of `𝐤` is arbitrary; the vector component of the returned quaternion could be any unit vector. + For complex components, when the vector components are precisely zero and the real + part of the scalar component is not positive, the result is instead the scalar + `sqrt(q[1])`, computed as a complex number, with zero vector part. + !!! warning "Automatic differentiation caveats" Values of `q` that are very close to (but not on) the negative real axis will produce @@ -430,9 +620,18 @@ so that the denominator may be subject to cancellation — we can use the fact t to evaluate the expression in a more stable form: ```math -\sqrt{q} = \left(|q| + q\right)\sqrt{\frac{|q| − q[1]} {2|q⃗|^2}}. +\sqrt{q} = \frac{|q⃗|}{\sqrt{2(|q| − q[1])}} + \frac{q⃗}{|q⃗|} \sqrt{\frac{|q| − q[1]}{2}}. ``` +For real floating-point components, a quaternion whose norm is so large or so small that +these expressions would overflow or underflow is first rescaled by a power of 4, and the +result is rescaled by the corresponding power of 2. In the second expression, the unit +vector ``q⃗/|q⃗|`` is computed from the unscaled vector part, after dividing it by its +largest component, so that it keeps its precision even when the vector part is tiny compared +to the scalar part. For complex components, the first expression is used whenever the real +part of `q[1]` is nonnegative, and the second with ``|q⃗|^2`` evaluated as the complex sum +`abs2vec(q)` otherwise. + Note that whenever the vector part is zero and the scalar part is negative, the solution is not unique (and the denominator above is zero), because it necessarily involves the square root of -1, of which there are infinitely many in the space of quaternions. In this case, @@ -450,45 +649,107 @@ Ultimately, the reason for this is geometrical, so it should be avoided by the u case. Therefore, for the sake of efficiency and accuracy when the problem is geometrically well conditioned, we do not attempt to special-case the derivative at these points. +Because the algorithm chooses its branch by comparing component values, it does not work +with symbolic component types such as `Symbolics.Num`. """ -function Base.sqrt(q::T) where {T<:AbstractQuaternion} - if q[1] <= 0 && iszerovalue(vec(q)) - return T(false, false, false, √(-q[1])) +function Base.sqrt(q::Union{Quaternion{T},Rotor{T}}) where {T<:Real} + q = float(q) + Q = typeof(q) + w = q[1] + if w ≤ 0 && iszerovalue(vec(q)) + return Q(false, false, false, √(-w)) end - # `ifelse` (below) would evaluate both arms, and the unused arm is - # 0/0 whenever `q` is a positive real; the resulting NaN - # contaminates the derivative. Branch instead, so that arm is - # never evaluated. As of 2026-08-19 Mooncake and ReverseDiff both - # still require this. - ## c₁ = ifelse(q[1] ≥ 0, (abs(q) + q[1]), (abs2vec(q) / (abs(q) - q[1]))) - c₁ = if q[1] ≥ 0 - (abs(q) + q[1]) + k = sqrtscale(q) + if !iszero(k) + return rescaledsqrt(q, k) + end + # `ifelse` would evaluate both arms, and the unused arm is 0/0 whenever `q` is a + # positive real; the resulting NaN contaminates the derivative. Branch instead, so + # that arm is never evaluated. As of 2026-08-19 Mooncake and ReverseDiff both still + # require this. + a = abs(q) + if w ≥ 0 + c = √(2(a + w)) + return Q(c/2, q[2]/c, q[3]/c, q[4]/c) else - (abs2vec(q) / (abs(q) - q[1])) + # Here the vector part is nonzero. Its direction q⃗/|q⃗| is computed after dividing + # q⃗ by its largest component `m`, so that |q⃗|/m = `s` neither overflows nor loses + # precision to underflow, even when the vector part is tiny or subnormal. The norm + # `s` is computed as `abs` of a `QuatVec`, which is `hypotenuse` of the components, + # so that Enzyme uses the rule for `hypotenuse` in QuaternionicEnzymeExt: Enzyme's + # own reverse rule for `hypot` with three arguments fails at batch widths above 1. + m = maximum(abs, vec(q)) + u = vec(q) / m + s = abs(quatvec(u...)) + d = √(2(a - w)) + h = d/2 + return Q((m/d)*s, (u[1]/s)*h, (u[2]/s)*h, (u[3]/s)*h) end - c₂ = √inv(2c₁) - return T(c₁*c₂, q[2]*c₂, q[3]*c₂, q[4]*c₂) end -function Base.sqrt(q::AbstractQuaternion{Float16}) +function Base.sqrt(q::Union{Quaternion{Float16},Rotor{Float16}}) T = wrapper(typeof(q)) T{Float16}(sqrt(T{Float32}(q))) end - -function Base.sqrt(q::QT) where {T<:Real, QT<:AbstractQuaternion{Complex{T}}} +function Base.sqrt(q::Union{Quaternion{Complex{T}},Rotor{Complex{T}}}) where {T<:Real} + q = float(q) + Q = typeof(q) # As in the real case, only a vanishing vector part with `real(q[1]) ≤ 0` needs a # special branch, because the general formula below would divide by zero. Elsewhere, # the general formula is correct, and taking this branch would lose the derivative with # respect to the vector part. if real(q[1]) ≤ 0 && iszerovalue(vec(q)) - return QT(sqrt(q[1]), false, false, false) + return Q(csqrt(q[1]), false, false, false) end c₁ = if real(q[1]) ≥ 0 (abs(q) + q[1]) else (abs2vec(q) / (abs(q) - q[1])) end - c₂ = √inv(2c₁) - return QT(c₁*c₂, q[2]*c₂, q[3]*c₂, q[4]*c₂) + c₂ = csqrt(inv(2c₁)) + return Q(c₁*c₂, q[2]*c₂, q[3]*c₂, q[4]*c₂) +end +Base.sqrt(q::QuatVec) = sqrt(quaternion(q)) + +# The power `k` such that `sqrt` should rescale `q` by 4⁻ᵏ to avoid overflow and underflow, +# or 0 if no rescaling is needed. The test uses the largest component, which is finite even +# when `abs(q)` overflows. A `Rotor` and types other than floating-point numbers (such as +# dual numbers) are not rescaled. +function sqrtscale(q::Quaternion{T}) where {T<:AbstractFloat} + m = maximum(abs, components(q)) + if isfinite(m) && !iszero(m) && !(floatmin(T)/eps(T) ≤ m ≤ floatmax(T)/8) + exponent(m) ÷ 2 + else + 0 + end +end +sqrtscale(_) = 0 + +# The square root of a floating-point `Quaternion` that `sqrt` rescales by 4⁻ᵏ, which is +# exact, so that |q| is near 1, and then unscales by 2ᵏ. The factor 4⁻ᵏ itself may not be +# representable, so `q` is multiplied twice by 2⁻ᵏ. The scale factors are constants made +# with `ldexp`, and the components are only multiplied by them, because applying `ldexp` to +# the components themselves breaks Enzyme's forward mode for every call to `sqrt`. The +# magnitudes `c` and `d` below are computed from the rescaled quaternion `p`, but the vector +# part of `p` may underflow when it is much smaller than the scalar part, so the vector part +# of the result is computed from that of `q` instead. +function rescaledsqrt(q::Quaternion{T}, k) where {T<:AbstractFloat} + t = ldexp(one(T), -k) # 2⁻ᵏ + t⁻¹ = ldexp(one(T), k) # 2ᵏ + p = (q * t) * t + if q[1] ≥ 0 + c = √(2(abs(p) + p[1])) # 2⁻ᵏ times the `c` in `sqrt` + return Quaternion{T}(t⁻¹ * (c/2), (t*q[2])/c, (t*q[3])/c, (t*q[4])/c) + else + # See the comments on the unscaled case in `sqrt`. + d = √(2(abs(p) - p[1])) # 2⁻ᵏ times the `d` in `sqrt` + m = maximum(abs, vec(q)) + u = vec(q) / m + s = abs(quatvec(u...)) + h = d/2 + return Quaternion{T}( + ((t*m) / d) * s, t⁻¹ * ((u[1]/s)*h), t⁻¹ * ((u[2]/s)*h), t⁻¹ * ((u[3]/s)*h) + ) + end end @@ -514,6 +775,18 @@ rather than the range `[0, π]` used for complex numbers. If you only care abou on vectors, and want to map the result of this function to the range `[0, π]`, you can use `θ -> min(θ, 2π-θ)`. +For real components, this is computed as `2atan(absvec(q), q[1])`, which is equivalent to +`2absvec(log(q))` but is accurate, along with its derivatives, even near `-1`. The angle +has cone-shaped kinks where the vector part vanishes, at which derivatives are returned as +zero. + +For complex components, as for a [`Lorentz`](@ref) transformation, the result is the complex +number `2absvec(log(q))`. When the rotation and the boost share an axis, this is ``θ ± +iη``, where ``θ`` is the rotation angle, ``η`` is the rapidity of the boost, and the sign is +positive when the boost is parallel to the rotation axis. In general, the result does not +separate so simply into a rotation angle and a rapidity, and the imaginary part may be +negative. + # Examples ```jldoctest julia> θ=1.2; @@ -528,8 +801,14 @@ julia> angle(exp(6.2 * imz / 2)) # Note that this is greater than π ``` """ -Base.angle(q::Quaternion{T}) where T = 2 * absvec(log(q)) -Base.angle(q::Rotor{T}) where T = 2 * absvec(log(q)) +function Base.angle(q::Union{Quaternion{<:Real},Rotor{<:Real}}) + if iszerovalue(vec(q)) + # `absvec` is not differentiable here; return the same value with zero derivative. + return 2atan(zero(q[1]), q[1]) + end + 2atan(absvec(q), q[1]) +end +Base.angle(q::Union{Quaternion{<:Complex},Rotor{<:Complex}}) = 2 * absvec(log(q)) @doc raw""" @@ -544,55 +823,122 @@ Specifically, when `q` is a `Rotor`, this provides a geodesic on the unit 3-sphe between those two points. For more general interpolations, see the [`slerp`](@ref) function. +The type of the result depends on the types of the arguments: + + * A `Rotor` raised to a real or complex power is a `Rotor`. The norm of the input is + assumed to be 1, so the result always has unit norm. This includes `Lorentz` rotors, + with complex components. + * A `Quaternion` or `QuatVec` raised to a non-integer power is a `Quaternion`. + * When `s` is itself a quaternion, the result is the `Quaternion` ``\exp(s \log(q))``, + with the product taken in that order. + * When `s` is an `Integer`, the power is computed by repeated multiplication. Then a + `Rotor` gives a `Rotor`, and a `Quaternion` or `QuatVec` gives a `Quaternion`. With + integer components, a nonnegative power keeps integer components, and a negative power + gives floating-point components. + +The branch cut is the same as for [`log`](@ref): a quaternion whose vector part is exactly +zero and whose scalar part is negative is treated as ``|q| \exp(π𝐤)``. Just as for `log`, +derivatives are not defined there for non-integer `s`, and will be returned as zero with +respect to `q`. + +Non-integer powers choose their branch by comparing component values, so with symbolic +component types such as `Symbolics.Num` they are evaluated as `exp(s * log(q))`, with the +general formula for `log`. Integer powers work with them directly. """ function Base.:^(q::Quaternion, s::Number) exp(s * log(q)) end function Base.:^(q::Rotor, s::Number) q = float(q) - x = abs2vec(q) / q[1]^2 - if q[1] > 0 && x ≤ eps(typeof(x))^(1//5) + w = q[1] + if real(w) > 0 && isnearscalar(q) # Near the identity, `absvec(q)` is the square root of a tiny number, whose # derivatives are huge and lose all accuracy when they cancel, or are NaN when it is - # exactly 0. Instead, we write log(q) = A 𝐯/q[1], where A = atan(√x)/√x, and q^s = - # exp(f 𝐯) with f = s A/q[1], using series in `x` and in y = |f 𝐯|² that are - # smooth at the identity. Five terms suffice for a truncation error below `eps`. - A = evalpoly(x, (1, -1//3, 1//5, -1//7, 1//9)) - f = s * A / q[1] - y = f^2 * abs2vec(q) - c, sincu = if y ≤ eps(typeof(y))^(1//5) - evalpoly(y, (1, -1//2, 1//24, -1//720, 1//40320)), - evalpoly(y, (1, -1//6, 1//120, -1//5040, 1//362880)) + # exactly 0. Instead, we write log(q) = A 𝐯/q[1], where A = atan(√x)/√x and x = + # |𝐯|²/q[1]², and q^s = exp(f 𝐯) with f = s A/q[1], using series in `x` and in y = + # |f 𝐯|² that are smooth at the identity. Note that `x` is computed only here, so + # that no division by a vanishing q[1] is ever recorded by reverse-mode AD. + v² = abs2vec(q) + A = atanseries((v² / w) / w) + f = s * A / w + y = f * f * v² + c, sincu = if issmallvalue(y, trigseriestolerance) + cosseries(y), sincseries(y) else - # Only reached for large `s`, so that √y is not small - a = √y - cos(a), sin(a) / a + # Reached when |s| is large enough that √y is not small, or, for types with + # high precision, when the series in `y` would not be accurate enough. For a + # complex `Rotor`, `y` is complex, so its square root goes through `csqrt`. + a = csqrt(y) + ccos(a), csin(a) / a end - return Rotor{typeof(c)}([c, sincu*f*q[2], sincu*f*q[3], sincu*f*q[4]]) + return Rotor{typeof(c)}(c, sincu*f*q[2], sincu*f*q[3], sincu*f*q[4]) end - absolutevec = absvec(q) - if absolutevec ≤ eps(typeof(absolutevec)) - # log(q) ≈ π𝐤, because q ≈ -1 - sin_πs, cos_πs = sincospi(oftype(absolutevec, s)) - return Rotor{basetype(q)}([cos_πs, 0, 0, sin_πs]) + power(q, s) +end +Base.:^(q::Rotor, s::AbstractQuaternion) = quaternion(q)^s + +# Rational exponents would otherwise be ambiguous with Base's `^(::Number, ::Rational)`. We +# forward the exponent unchanged, rather than converting it to a float, so that the +# precision of types like `BigFloat` is kept. +Base.:^(q::Quaternion, s::Rational) = exp(s * log(q)) +Base.:^(q::Rotor, s::Rational) = invoke(^, Tuple{Rotor,Number}, q, s) +Base.:^(q::QuatVec, s::Rational) = quaternion(q)^s + +# The power of a real `Rotor` away from the identity +function power(q::Rotor{<:Real}, s) + if iszerovalue(vec(q)) + # q is -1, so log(q) = π𝐤. We promote `s` (as in the general case below) rather than + # converting it, so that the result has the same type as in the other branches, and + # so that dual numbers work. + sπ = s * one(basetype(q)) + sin_πs, cos_πs = sinpi(sπ), cospi(sπ) + return Rotor{typeof(cos_πs)}(cos_πs, false, false, sin_πs) end + absolutevec = absvec(q) f1 = s * atan(absolutevec, q[1]) - sin_f1, cos_f1 = sincos(f1) - f2 = sin_f1 / absolutevec - Rotor{typeof(cos_f1)}([cos_f1, f2*q[2], f2*q[3], f2*q[4]]) + # `sin` and `cos` are called separately, rather than through `sincos`, because Enzyme + # cannot take second derivatives of `sincos`. + sin_f1, cos_f1 = sin(f1), cos(f1) + # Dividing each component by `absolutevec` before multiplying avoids overflow when + # `absolutevec` is tiny. + Rotor{typeof(cos_f1)}( + cos_f1, sin_f1*(q[2]/absolutevec), sin_f1*(q[3]/absolutevec), sin_f1*(q[4]/absolutevec) + ) end +# The power of a complex `Rotor` (such as a `Lorentz` rotor) away from the identity +power(q::Rotor{<:Complex}, s) = exp(s * log(q)) + # We need to be more specific about the quaternion types here because we had # to be specific about the quaternion type above, and Integer<:Number -for QT ∈ [AbstractQuaternion, Quaternion, QuatVec, Rotor] +for QT ∈ (AbstractQuaternion, Quaternion, Rotor) @eval function Base.:^(q::$QT, s::Integer) - if s ≥ 0 - Base.power_by_squaring(q, s) - else - inv(Base.power_by_squaring(q, -s)) + s < 0 && return inv(q ^ -s) + # This is the square-and-multiply algorithm of `Base.power_by_squaring`, written out + # here, with the same order of operations and therefore the same results and types. + # As of 2026-10-01, Enzyme's reverse mode aborts the Julia process when + # differentiating `Base.power_by_squaring` with the exponents 1 and 2. As in Base's + # `to_power_type`, the input is first converted to the type of a product, so that + # the type of the result does not depend on `s`. For example, that type has + # floating-point components for a `Rotor`, because the product of two rotors is + # normalized, and integer components for `Bool` components, as in `imx`. + x = convert(Base.promote_op(*, typeof(q), typeof(q)), q) + s == 0 && return one(x) + while iseven(s) + x *= x + s >>= 1 + end + p = x + while (s >>= 1) > 0 + x *= x + if isodd(s) + p *= x + end end + p end end +Base.:^(q::QuatVec, s::Integer) = quaternion(q)^s # As with the arithmetic operators in `algebra.jl`, `@fastmath q ^ s` would otherwise # promote `s` to a quaternion, which changes the result for a `Quaternion` and throws an diff --git a/src/precompilation.jl b/src/precompilation.jl index dc8fca99..4bdf3425 100644 --- a/src/precompilation.jl +++ b/src/precompilation.jl @@ -4,7 +4,10 @@ s = randn(Float64) v = randn(QuatVecF64) r = randn(RotorF64) + r2 = randn(RotorF64) q = randn(QuaternionF64) + Rs = [r, r2, r * r2, r2 * r] + ts = [0.0, 1.0, 2.0, 3.0] @compile_workload begin # all calls in this block will be precompiled, regardless of whether they belong to @@ -20,5 +23,24 @@ end end + # The first call of each of these would otherwise take tens of milliseconds (or, for + # `squad`, about a second) to compile. + exp(v) + exp(q) + log(q) + log(r) + sqrt(q) + sqrt(r) + q^2 + r^2 + q^0.3 + r^0.3 + slerp(r, r2, 0.3) + distance(r, r2) + distance2(r, r2) + distance(q, q) + to_rotation_matrix(r) + from_rotation_matrix(to_rotation_matrix(r)) + squad(Rs, ts, [0.5, 1.5, 2.5]) end end diff --git a/src/quaternion.jl b/src/quaternion.jl index f316c679..9e3836f7 100644 --- a/src/quaternion.jl +++ b/src/quaternion.jl @@ -8,25 +8,61 @@ are the vector parts. """ components(q::AbstractQuaternion) = getfield(q, :components) +# The square root of a complex number `z`, which is just `sqrt(z)`. It is a separate +# function owned by this package, so that a derivative rule can be attached to it without +# type piracy. Base's `sqrt(::Complex)` uses bit-level operations that Mooncake cannot +# differentiate, so the Mooncake extension imports the ChainRules rule for this function. +# Every complex square root in the package goes through it. +csqrt(z) = sqrt(z) + +# The exponential, cosine, and sine of a complex number, computed from real functions. +# Base's methods for complex arguments take special branches when the real or imaginary part +# is exactly zero, and tracing AD backends (Mooncake, Enzyme, and ReverseDiff) differentiate +# those branches incorrectly. For finite arguments, these formulas are the ones Base uses +# away from those branches. The sine and cosine of each real number are computed separately +# rather than with `sincos`, because Enzyme cannot take second derivatives through `sincos`. +# For a real argument, each function is Base's own. +cexp(z) = exp(z) +function cexp(z::Complex) + e = exp(real(z)) + Complex(e * cos(imag(z)), e * sin(imag(z))) +end +ccos(z) = cos(z) +ccos(z::Complex) = Complex(cos(real(z)) * cosh(imag(z)), -sin(real(z)) * sinh(imag(z))) +csin(z) = sin(z) +csin(z::Complex) = Complex(sin(real(z)) * cosh(imag(z)), cos(real(z)) * sinh(imag(z))) + # This helper function is mostly copied from Base.math, except that we restrict to Complex # elements, and we omit `abs2` in the final sum. This is crucial because it is the # appropriate norm for complex quaternions, which are supposed to represent rotors in the # spacetime algebra. function _hypot(x) - maxabs = maximum(abs, x) + maxabs = maximum(y -> abs(value(y)), x) result_type = promote_type(eltype(x), typeof(maxabs)) if isnan(maxabs) && any(isinf, x) return convert(result_type, Inf) elseif (iszero(maxabs) || isinf(maxabs)) return convert(result_type, maxabs) else - return maxabs * sqrt(sum(y -> (y / maxabs)^2, x)) + # The square is written as a product, because `^` of a `Complex` goes through + # Base's `_cpow`, which reverse-mode AD packages such as ReverseDiff cannot handle. + return maxabs * csqrt(sum(y -> (y / maxabs) * (y / maxabs), x)) end end """ - Quaternion{T<:Number} <: Number + AbstractQuaternion{T<:Number} <: Number + +Abstract supertype of the quaternion types [`Quaternion`](@ref), [`Rotor`](@ref), and +[`QuatVec`](@ref), with elements of type `T`, which may be retrieved with +[`basetype`](@ref). Every subtype stores its four components `(w, x, y, z)` as an +`SVector{4, T}`, which may be retrieved with [`components`](@ref). +""" +AbstractQuaternion + +""" + Quaternion{T<:Number} <: AbstractQuaternion{T} Quaternionic number type with elements of type `T`. @@ -74,6 +110,18 @@ struct Quaternion{T<:Number} <: AbstractQuaternion{T} Quaternion{T}(w::Number) where {T<:Number} = new{T}(SVector{4,T}(w, false, false, false)) end +""" + quaternion(w, x, y, z) + quaternion(x, y, z) + quaternion(w) + quaternion(v) + quaternion(q) + +Create a [`Quaternion`](@ref) with the given components, whose element type is inferred from +the arguments. Any missing components are set to zero. Here, `v` is a vector of length 1, +3, or 4, which is interpreted as the corresponding list of arguments, and `q` is any +quaternion, whose components are copied. +""" quaternion(a::SVector{4,T}) where {T<:Number} = Quaternion{T}(a) #quaternion(a::AbstractVector) = Quaternion{T}(SVector{4,T}(a)) # See below quaternion(a::AbstractQuaternion) = Quaternion{basetype(a)}(components(a)) @@ -90,7 +138,7 @@ Quaternion(w::T) where {T<:Number} = quaternion(w) @doc raw""" - Rotor{T<:Number} <: Number + Rotor{T<:Number} <: AbstractQuaternion{T} Quaternion of unit magnitude with elements of type `T`. These objects can be significantly faster *and* more accurate in certain operations representing rotations. @@ -119,27 +167,55 @@ sign when the corresponding rotations are not so different (cf. [`unflip`](@ref) The functions rotor(w, x, y, z) + rotor(x, y, z) rotor(w) + rotor(v) + rotor(q) create a new rotor with the given components (where the components are as described in -[`Quaternion`](@ref)), automatically normalizing them on input. Note that this -normalization step is the key difference between the `Rotor` and `rotor` functions; if you -would like to bypass normalization, you can call +[`Quaternion`](@ref)), automatically normalizing them on input. Here, `v` is a vector of +length 1, 3, or 4, and `q` is any quaternion. The element type of the result is a +floating-point type, even for integer input. The type constructors `Rotor(...)`, without a +type parameter, are identical to `rotor(...)` and also normalize. So does +`convert(Rotor{T}, x)` when `x` is a number or a quaternion other than a `Rotor`, and +therefore so do the implicit conversions made by `push!`, `setindex!`, and typed array +literals. Converting a `Rotor` to a `Rotor{T}` with a different element type `T` only +converts the components, without normalizing them again. + +If you would like to bypass normalization, you can call the type constructor with an +explicit type parameter: Rotor{T}(w, x, y, z) + Rotor{T}(x, y, z) Rotor{T}(w) - -in the same way as `rotor`, and `w, x, y, z` will be converted to type `T`. Alternatively, -you can call - Rotor{T}(v) + Rotor{T}(q) -where `v<:AbstractArray` can be converted to an `SVector{4, T}`. If you want to handle the -normalization step, you can use `LinearAlgebra.normalize`. +These simply convert the given components to type `T` and store them; here, `v` is any +`AbstractVector` that can be converted to an `SVector{4, T}`. If you want to handle the +normalization step yourself, you can use `LinearAlgebra.normalize`. However, once a `Rotor` is created, its norm will often be *assumed* to be precisely 1. So if its true norm is significantly different, you will likely see weird results — including -vectors with very different lengths after "rotation" by a non-unit `Rotor`. +vectors with very different lengths after "rotation" by a non-unit `Rotor`. For the same +reason, `abs` and `abs2` of a `Rotor` return exactly 1, and mixing a `Rotor` with any number +or quaternion that is not a `Rotor`, in arithmetic or in `promote`, gives a `Quaternion`. +The functions `zero(Rotor{T})` also returns a `Quaternion`, and `round` of a `Rotor` returns +a `Quaternion`, because neither result is a unit quaternion. However, `zeros(Rotor{T}, +dims...)` returns an array with element type `Rotor{T}`, filled with zero rotors that are +not normalized, so that it can be used to preallocate an array of rotors. + +The product or quotient of two `Rotor`s is a `Rotor`. For real element types, that result +is renormalized to remove the accumulated rounding error. For complex element types (as for +[`Lorentz`](@ref) transformations), it is renormalized only when the sum of the squared +magnitudes of its components is less than 16. The complex spinor norm of a boost with +rapidity ``η`` is computed as ``\cosh^2(η/2) - \sinh^2(η/2)``, which cancels +catastrophically for large ``η``, so renormalizing such a product would add error rather +than remove it. + +For complex element types, normalization divides by the principal square root of the spinor +norm ``w^2 + x^2 + y^2 + z^2``, which is itself complex. The overall sign of the normalized +result therefore changes discontinuously as the spinor norm crosses the negative real axis. Note that simply creating a `Quaternion` that happens to have norm 1 does not make it a `Rotor`. However, you can pass such a `Quaternion` to the `rotor` function and get the @@ -170,19 +246,53 @@ struct Rotor{T<:Number} <: AbstractQuaternion{T} Rotor{T}(w::Number) where {T<:Number} = new{T}(SVector{4,T}(w, false, false, false)) end +# The division is written out component by component, rather than as a broadcast `a ./ n`, +# because ReverseDiff's tapes cannot replay a broadcast into an immutable `SVector`. +""" + rotor(w, x, y, z) + rotor(x, y, z) + rotor(w) + rotor(v) + rotor(q) + +Create a [`Rotor`](@ref) from the given components, normalizing them so that the result has +norm 1. Missing components are set to zero, `v` is a vector of length 1, 3, or 4, which is +interpreted as the corresponding list of arguments, and `q` is any quaternion. The element +type of the result is a floating-point type, even for integer input. To store components +without normalizing them, use the type constructor `Rotor{T}(...)` with an explicit type +parameter. +""" function rotor(a::SVector{4,T}) where {T<:Number} - â = a ./ abs(Quaternion{T}(a)) - Rotor{eltype(â)}(â) + n = abs(Quaternion{T}(a)) + normalized = SVector{4}(a[1] / n, a[2] / n, a[3] / n, a[4] / n) + Rotor{eltype(normalized)}(normalized) end #rotor(a::AbstractVector) = Rotor{T}(SVector{4,T}(a)) # See below rotor(a::AbstractQuaternion) = rotor(components(a)) -function rotor(w, x, y, z) - a = SVector{4}(w, x, y, z) - v = a ./ abs(Quaternion{eltype(a)}(a)) - Rotor{eltype(v)}(v) -end +rotor(w, x, y, z) = rotor(SVector{4}(w, x, y, z)) rotor(x,y,z) = rotor(false, x,y,z) -rotor(w::T) where {T<:Number} = Rotor{T}(SVector{4,T}(copysign(one(w), w), false, false, false)) +# Every arity shares the same normalization, so that `rotor(0)` is NaN like `rotor(0, 0, 0, +# 0)`, and the element type does not depend on the number of arguments. +rotor(w::Number) = rotor(w, false, false, false) + +# This builds the `Rotor` that results from a product or quotient of rotors, at least one of +# which is complex, as for `Lorentz` transformations; see `wrapper` below. Renormalizing +# divides by the complex spinor norm, which is computed with an absolute error of roughly +# eps·S, where S is the sum of the squared magnitudes of the components (cosh η for a boost +# of rapidity η). Below the bound S < 16, that error is at most several ulps, and +# renormalizing removes the drift that accumulates over long chains of products. Above it, +# the error of renormalizing grows in proportion to S and exceeds the error of the product +# itself, so the components are stored as they are. The test is made on `value(S)`, so that +# dual numbers take the same branch as their values. A comparison that does not return a +# `Bool`, as for symbolic types, skips renormalization. +function complex_rotor_product(a::SVector{4}) + if (value(sum(abs2, a)) < 16) === true + rotor(a) + else + Rotor{eltype(a)}(a) + end +end +complex_rotor_product(w, x, y, z) = complex_rotor_product(SVector{4}(w, x, y, z)) Rotor(w::SVector{4,T}) where {T} = rotor(w) Rotor(w::AbstractVector) = rotor(w) @@ -192,7 +302,7 @@ Rotor(x,y,z) = rotor(x,y,z) Rotor(w::T) where {T<:Number} = rotor(w) """ - QuatVec{T<:Number} <: Number + QuatVec{T<:Number} <: AbstractQuaternion{T} Pure-vector quaternion with elements of type `T`. These objects can be significantly faster *and* more accurate in certain operations than general `Quaternion`s. @@ -208,7 +318,20 @@ The functions quatvec(w) create a new `QuatVec` with the given components (where the components are as described in -[`Quaternion`](@ref)), except that the scalar argument `w` is always set to 0. +[`Quaternion`](@ref)), except that the scalar argument `w` is always set to 0. The same is +true of the type constructors `QuatVec(...)` and `QuatVec{T}(...)`, and therefore also of +`convert`, `push!`, and other implicit conversions: any scalar part given to them is +discarded, so that a `QuatVec` never stores a nonzero scalar part. For example, +`QuatVec{T}(w, x, y, z)` and `convert(QuatVec{T}, q)` ignore `w` and the scalar part of `q`, +respectively, and `QuatVec{T}(w)` is the zero vector. + +A `QuatVec` is equal (by `==` and `isequal`) to another quaternion only if the other +quaternion has zero scalar part and the same vector part, and it is equal to a number only +if both are zero. Because the multiplicative identity is not a pure vector, +`one(QuatVec{T})` and `oneunit(QuatVec{T})` return `Quaternion` values. On the other hand, +`ones(QuatVec{T}, dims...)` returns an array with element type `QuatVec{T}`, as requested, +so the scalar part of each `one(QuatVec{T})` is discarded when it is stored, and every +element is the zero vector. # Examples @@ -225,14 +348,29 @@ julia> quatvec(1) """ struct QuatVec{T<:Number} <: AbstractQuaternion{T} components::SVector{4,T} - QuatVec{T}(a::SVector{4,T}) where {T<:Number} = new{T}(a) - QuatVec{T}(a::AbstractVector) where {T<:Number} = new{T}(SVector{4,T}(a)) - QuatVec{T}(a::AbstractQuaternion) where {T<:Number} = new{T}(SVector{4,T}(components(a))) - QuatVec{T}(w,x,y,z) where {T<:Number} = new{T}(SVector{4,T}(w,x,y,z)) + # Every constructor discards the scalar part, so that a `QuatVec` never stores a + # nonzero scalar component. This includes the implicit conversions made by + # `convert`, `push!`, `setindex!`, and typed array literals. + QuatVec{T}(a::SVector{4,T}) where {T<:Number} = new{T}(SVector{4,T}(false, a[2], a[3], a[4])) + QuatVec{T}(a::AbstractVector) where {T<:Number} = QuatVec{T}(SVector{4,T}(a)) + QuatVec{T}(a::AbstractQuaternion) where {T<:Number} = QuatVec{T}(SVector{4,T}(components(a))) + QuatVec{T}(_,x,y,z) where {T<:Number} = new{T}(SVector{4,T}(false,x,y,z)) QuatVec{T}(x,y,z) where {T<:Number} = new{T}(SVector{4,T}(false,x,y,z)) - QuatVec{T}(w::Number) where {T<:Number} = new{T}(SVector{4,T}(w, false, false, false)) + QuatVec{T}(::Number) where {T<:Number} = new{T}(SVector{4,T}(false, false, false, false)) end +""" + quatvec(w, x, y, z) + quatvec(x, y, z) + quatvec(w) + quatvec(v) + quatvec(q) + +Create a [`QuatVec`](@ref) with the given vector components, whose element type is inferred +from the arguments. The scalar argument `w`, or the scalar part of the quaternion `q`, is +discarded, so `quatvec(w)` is the zero vector. Here, `v` is a vector of length 1, 3, or 4, +which is interpreted as the corresponding list of arguments. +""" function quatvec(v::SVector{4,T}) where {T<:Number} v′ = SVector{4,T}(false, v[2], v[3], v[4]) QuatVec{T}(v′) @@ -313,6 +451,11 @@ julia> 1.2 + 3.4𝐢 ``` """ const imx = QuatVec{Bool}(false, true, false, false) +""" + 𝐢 + +Alias for [`imx`](@ref), the quaternionic unit `QuatVec{Bool}` along the `x` axis. +""" const 𝐢 = imx """ @@ -342,6 +485,11 @@ julia> 1.2 + 3.4𝐣 ``` """ const imy = QuatVec{Bool}(false, false, true, false) +""" + 𝐣 + +Alias for [`imy`](@ref), the quaternionic unit `QuatVec{Bool}` along the `y` axis. +""" const 𝐣 = imy """ @@ -371,6 +519,11 @@ julia> 1.2 + 3.4𝐤 ``` """ const imz = QuatVec{Bool}(false, false, false, true) +""" + 𝐤 + +Alias for [`imz`](@ref), the quaternionic unit `QuatVec{Bool}` along the `z` axis. +""" const 𝐤 = imz # Essential constructors @@ -382,6 +535,27 @@ Base.one(::Type{QT}) where {T<:Number,QT<:AbstractQuaternion{T}} = QT(true, fals Base.one(::QT) where {T<:Number,QT<:AbstractQuaternion{T}} = Base.one(QT) Base.one(::Type{QuatVec{T}}) where {T} = one(Quaternion{T}) +# Base's fallbacks for the `UnionAll` types `Rotor` and `QuatVec` go through `convert`, +# which would give the wrong identity element. These methods follow the convention of the +# concrete types above: a quantity that cannot be stored in the original type is returned as +# a `Quaternion`. +Base.zero(::Type{Rotor}) = zero(Quaternion) +Base.one(::Type{QuatVec}) = one(Quaternion) +Base.oneunit(::Type{QuatVec{T}}) where {T} = one(Quaternion{T}) +Base.oneunit(::Type{QuatVec}) = one(Quaternion) +Base.oneunit(q::QuatVec) = oneunit(typeof(q)) + +# Base's `zeros` fills an array of the requested element type with `zero(T)`. For `Rotor`, +# that value is a `Quaternion`, which would then be converted back to a `Rotor`, and that +# conversion normalizes, which would give NaN. Instead, as in earlier versions, the array +# keeps the element type `Rotor{T}` and is filled with the zero rotor, constructed without +# normalization, so that it can be used for preallocation. Every other method of `zeros` +# with a type argument reaches one of these two. +Base.zeros(::Type{Rotor{T}}, dims::NTuple{N,Integer}) where {T,N} = + fill(Rotor{T}(false, false, false, false), dims) +Base.zeros(::Type{Rotor{T}}, dims::Tuple{}) where {T} = + fill(Rotor{T}(false, false, false, false), dims) + # Getting pieces of quaternions @inline function Base.getindex(q::AbstractQuaternion, i::Integer) @boundscheck checkbounds(components(q), i) @@ -409,6 +583,12 @@ end end end Base.@propagate_inbounds Base.getindex(q::AbstractQuaternion, I) = [q[i] for i in I] +Base.getindex(q::AbstractQuaternion, ::Colon) = [q[i] for i in 1:4] +Base.getindex(q::AbstractQuaternion, ::CartesianIndex{0}) = q +# Indexing with `begin` and `end` refers to the four components, as for `q[i]`, rather than +# treating the quaternion as a single scalar, as Base's methods for `Number` do. +Base.firstindex(::AbstractQuaternion) = 1 +Base.lastindex(::AbstractQuaternion) = 4 Base.real(::Type{T}) where {T<:AbstractQuaternion} = basetype(T) Base.real(q::AbstractQuaternion{T}) where {T<:Number} = q[1] Base.imag(q::AbstractQuaternion{T}) where {T<:Number} = @view components(q)[2:4] @@ -437,6 +617,20 @@ end wrapper(::Type{<:Rotor}, ::Val{*}, ::Type{<:Rotor}) = Rotor wrapper(::Type{<:Rotor}, ::Val{/}, ::Type{<:Rotor}) = Rotor +# The product or quotient of two unit rotors is a unit rotor up to rounding error, so for +# real elements it is merely renormalized (through `Rotor(w, x, y, z)`) to remove drift. +# For complex elements, as for `Lorentz` transformations, renormalization divides by the +# complex spinor norm. For a boost of rapidity η, the spinor norm is computed as cosh²(η/2) +# - sinh²(η/2), which cancels catastrophically: the relative error is about eps·cosh(η), and +# the result is NaN for η ≳ 38 in `Float64`. So complex products are renormalized only when +# that error is small; see `complex_rotor_product` above. +for OP ∈ (Val{*}, Val{/}) + @eval begin + wrapper(::Type{<:Rotor{<:Complex}}, ::$OP, ::Type{<:Rotor}) = complex_rotor_product + wrapper(::Type{<:Rotor}, ::$OP, ::Type{<:Rotor{<:Complex}}) = complex_rotor_product + wrapper(::Type{<:Rotor{<:Complex}}, ::$OP, ::Type{<:Rotor{<:Complex}}) = complex_rotor_product + end +end wrapper(::Type{<:Rotor}, ::Val{+}, ::Type{<:Rotor}) = Quaternion wrapper(::Type{<:Rotor}, ::Val{-}, ::Type{<:Rotor}) = Quaternion for QT ∈ (AbstractQuaternion, QuatVec) # Quaternion is handled below @@ -476,6 +670,17 @@ let NT = Number end end end +# These resolve ambiguities between the generic methods for `AbstractQuaternion` and the +# methods for `Number` above, which would otherwise make `*` and `/` between a `Rotor` or a +# `QuatVec` and a user-defined subtype of `AbstractQuaternion` throw. +for QT ∈ (Rotor, QuatVec) + for OP ∈ (Val{*}, Val{/}) + @eval begin + wrapper(::Type{<:AbstractQuaternion}, ::$OP, ::Type{<:$QT}) = Quaternion + wrapper(::Type{<:$QT}, ::$OP, ::Type{<:AbstractQuaternion}) = Quaternion + end + end +end for T ∈ (AbstractQuaternion, Quaternion, QuatVec, Rotor, Number) for OP ∈ (Val{+}, Val{-}, Val{*}, Val{/}) @eval wrapper(::Type{<:Quaternion}, ::$OP, ::Type{<:$T}) = Quaternion @@ -486,6 +691,15 @@ for T ∈ (AbstractQuaternion, Quaternion, QuatVec, Rotor, Number) end +""" + basetype(q) + basetype(QT) + +Return the element type `T` of the quaternion `q`, or of the quaternion type `QT`, where `q +isa AbstractQuaternion{T}` or `QT <: AbstractQuaternion{T}`. This is the type of each +component, as `eltype` is for an array. For example, `basetype(QuaternionF64)` is +`Float64`. +""" basetype(::AbstractQuaternion{T}) where {T} = T basetype(::Type{<:AbstractQuaternion{T}}) where {T} = T Base.widen(::Type{Q}) where {Q<:AbstractQuaternion} = wrapper(Q){widen(basetype(Q))} @@ -503,5 +717,30 @@ Base.promote_rule(::Type{QuatVec{T}}, ::Type{S}) where {T<:Number,S<:Number} = Quaternion{promote_type(T, S)} Base.promote_rule(::Type{QuatVec{T}}, ::Type{S}) where {T<:Number,S<:AbstractQuaternion} = wrapper(wrapper(QuatVec), wrapper(S)){promote_type(T, basetype(S))} +# A `Rotor` mixed with any other number (including `Complex`) is promoted to `Quaternion`, +# because the other number need not have unit norm. +Base.promote_rule(::Type{Rotor{T}}, ::Type{S}) where {T<:Number,S<:Number} = + Quaternion{promote_type(T, S)} +Base.promote_rule(::Type{Rotor{T}}, ::Type{S}) where {T<:Number,S<:AbstractQuaternion} = + wrapper(wrapper(Rotor), wrapper(S)){promote_type(T, basetype(S))} Base.promote_rule(::Type{Q1}, ::Type{Q2}) where {Q1<:AbstractQuaternion,Q2<:AbstractQuaternion} = wrapper(wrapper(Q1), wrapper(Q2)){promote_type(basetype(Q1), basetype(Q2))} + +# Conversion to `Rotor{T}` normalizes, as `convert(Rotor, x)` and `rotor(x)` do, so that the +# implicit conversions made by `push!`, `setindex!`, `fill!`, and typed array literals never +# create a non-unit `Rotor`. The components are converted to `T` before normalizing, so +# that the norm is 1 to the precision of `T`. A `Rotor` is already normalized, so only its +# element type is converted. The raw constructor `Rotor{T}(...)` remains the way to store +# components without normalizing them. +Base.convert(::Type{Rotor{T}}, x::Number) where {T<:Number} = Rotor{T}(rotor(Quaternion{T}(x))) +Base.convert(::Type{Rotor{T}}, q::AbstractQuaternion) where {T<:Number} = + Rotor{T}(rotor(Quaternion{T}(q))) +Base.convert(::Type{Rotor{T}}, q::Rotor) where {T<:Number} = Rotor{T}(q) +Base.convert(::Type{Rotor{T}}, q::Rotor{T}) where {T<:Number} = q + +# Like a `Complex`, a quaternion can be converted to a real type only when it is real. This +# is restricted to the standard real types, because packages such as ForwardDiff and +# Symbolics define constructors of their own real types from any argument, which would +# otherwise be ambiguous. +(::Type{T})(q::AbstractQuaternion) where {T<:Union{AbstractFloat,Integer,Rational}} = + isreal(q) ? T(real(q))::T : throw(InexactError(nameof(T), T, q)) diff --git a/src/random.jl b/src/random.jl index 2dbdfb5e..045b967a 100644 --- a/src/random.jl +++ b/src/random.jl @@ -1,24 +1,26 @@ """ - randn([rng=default_rng()], T=Quaternion{Float64}, [dims...]) + randn([rng=default_rng()], QT, [dims...]) -Generate a normally distributed random quaternion of type `T` with mean 0 and standard -deviation of norm 1. Optionally generate an *array* of such quaternions. This module -currently provides an implementation for the types `QuaternionF16`, `QuaternionF32`, and -`QuaternionF64` (the default). The values are drawn from the spherically symmetric -quaternionic normal distribution of variance 1 (corresponding to each component having -independent normal distribution with mean zero and variance 1/4). +Generate a normally distributed random quaternion of type `QT`, or an *array* of such +quaternions with dimensions `dims`. The type `QT` must specify the element type, which can +be any `AbstractFloat`, as in `QuaternionF64`, `Rotor{Float32}`, or `QuatVec{BigFloat}`. +(There is no default type; `randn()` with no type argument still returns a `Float64`.) -Note that this function works with `Quaternion{BigFloat}`, even though `Base.randn` does -not work with `BigFloat` on Julia <1.9; for earlier versions, we just use the [Box-Muller -transform](https://en.wikipedia.org/wiki/Box–Muller_transform) to obtain the desired -result. +If `QT` is a `Quaternion` type, the values are drawn from the spherically symmetric +quaternionic normal distribution with mean 0 and variance 1, so that the expected value of +`abs2(q)` is 1. This corresponds to each of the four components having an independent +normal distribution with mean 0 and variance 1/4. -If the quaternion type passed in is `Rotor`, the result will be normalized correctly. -Because the distribution is spherically symmetric, the result is a truly random -rotation. +If `QT` is a `Rotor` type, the result is normalized. Because the distribution is +spherically symmetric, the result is a uniformly distributed random rotation. -If the quaternion type is `QuatVec`, the result will have a 0 scalar component, and the -vector will have mean 0 standard deviation of norm 1. +If `QT` is a `QuatVec` type, the result has zero scalar part, and its vector part has mean 0 +and variance 1, corresponding to each of the three vector components having an independent +normal distribution with mean 0 and variance 1/3. + +Note that this function works with `BigFloat` elements, even though `Base.randn` does not +work with `BigFloat` on Julia versions before 1.9; for those versions, the [Box–Muller +transform](https://en.wikipedia.org/wiki/Box–Muller_transform) is used instead. # Examples ```julia diff --git a/src/utilities.jl b/src/utilities.jl index f0950b55..9c56c34f 100644 --- a/src/utilities.jl +++ b/src/utilities.jl @@ -1,6 +1,59 @@ # Un-normalized sinc function # sincu(x::Number) = _sincu(float(x)) -_sincu(x::Number) = iszerovalue(x) ? 1 - x^2/6 * (1 - x^2/20) : isinf(x) ? zero(x) : sin(x)/x +# +# The generic method is used by types such as `ForwardDiff.Dual`, whose derivatives of +# `sin(x)/x` lose accuracy to cancellation for small `x`: the error of the `k`th derivative +# is roughly `eps/x^k`. So the series is used whenever the *value* of `x` is below the +# threshold given by `sincu_tol`, rather than only at zero. The series runs through `x^30`, +# so that, for `Float64` and `Float32`, it can be used up to the threshold 3, beyond which +# the closed form is accurate. Measured against a high-precision reference, with the error +# of the `k`th derivative taken relative to the larger of its magnitude and `1/(k+1)`, the +# value and its first four derivatives are then accurate to a few ulps for every value of +# `x` below 4, including both sides of the threshold, and the fifth and sixth derivatives to +# about 10 and 70 ulps near the threshold, where their errors are largest. Types whose +# value is not a floating-point number, such as symbolic types, take the series only when +# the value is exactly zero. +_sincu(x::Number) = _sincu(x, value(x)) +_sincu(x, v) = iszerovalue(x) ? 1 - x^2/6 * (1 - x^2/20) : isinf(x) ? zero(x) : sin(x)/x +function _sincu(x, v::Union{R,Complex{R}}) where {R<:AbstractFloat} + if abs(v) < sincu_tol(R) + sincu_series(x, R) + else + isinf(x) ? zero(x) : csin(x)/x + end +end +# The Taylor series of `sin(x)/x` through `x^30`, whose coefficients are `(-1)^n/(2n+1)!` +# for `n = 0, …, 15`. For `Float64` and `Float32`, the coefficients are stored. For other +# floating-point types, the series is evaluated in nested form, dividing by the exact +# integers `(2n)(2n+1)`, so that no coefficients need to be computed in that type. +sincu_series(x, ::Type{Float64}) = evalpoly(x * x, sincu_coefficients(Float64)) +sincu_series(x, ::Type{Float32}) = evalpoly(x * x, sincu_coefficients(Float32)) +function sincu_series(x, ::Type{R}) where {R<:AbstractFloat} + x² = x * x + s = one(x²) + for n ∈ 15:-1:1 + s = 1 - x² * s / ((2n) * (2n + 1)) + end + s +end +sincu_coefficients(::Type{Float64}) = ( + 1.0, -0.16666666666666666, 0.008333333333333333, -0.0001984126984126984, + 2.7557319223985893e-6, -2.505210838544172e-8, 1.6059043836821613e-10, + -7.647163731819816e-13, 2.8114572543455206e-15, -8.22063524662433e-18, + 1.9572941063391263e-20, -3.868170170630684e-23, 6.446950284384474e-26, + -9.183689863795546e-29, 1.1309962886447716e-31, -1.216125041553518e-34 +) +sincu_coefficients(::Type{Float32}) = map(Float32, sincu_coefficients(Float64)) +# For a general floating-point type, this threshold makes the first omitted term of the +# series, `x^32/33!`, about `2^-32 * eps(R)`. It is capped at 3, where the closed form is +# accurate, as described above. The constant is `log(factorial(33))`. The threshold is +# computed in `Float64`, which is precise enough and avoids the cost of evaluating `exp` and +# `log` in, for example, `BigFloat` on every call; `eps(R)` is bounded below by `floatmin`, +# so that the threshold stays positive even for precisions beyond the range of `Float64`. +sincu_tol(::Type{R}) where {R<:AbstractFloat} = + min(3.0, exp((log(max(Float64(eps(R)), floatmin(Float64))) + 85.05446701758152) / 32) / 2) +sincu_tol(::Type{Float64}) = 3.0 +sincu_tol(::Type{Float32}) = 3.0f0 # _sincu(x::Number) = ifelse( # iszerovalue(x), # one(x), @@ -12,10 +65,10 @@ _sincu(x::Number) = iszerovalue(x) ? 1 - x^2/6 * (1 - x^2/20) : isinf(x) ? zero( # ) @inline _sincu(x::Union{Float64,ComplexF64}) = abs(x) < 0.0031 ? evalpoly(x^2, (1.0, -0.16666666666666666, 0.008333333333333333)) : - isinf(x) ? zero(x) : sin(x)/x + isinf(x) ? zero(x) : csin(x)/x @inline _sincu(x::Union{Float32,ComplexF32}) = abs(x) < 0.1571f0 ? evalpoly(x^2, (1.0f0, -0.16666667f0, 0.008333334f0)) : - isinf(x) ? zero(x) : sin(x)/x + isinf(x) ? zero(x) : csin(x)/x _sincu(x::Float16) = Float16(_sincu(Float32(x))) # _sincu(x::ComplexF16) = ComplexF16(_sincu(ComplexF32(x))) @@ -27,8 +80,8 @@ _sincu(x::Float16) = Float16(_sincu(Float32(x))) # `x == 0`. # Note that this is only implemented accurately for ``|x| \\lesssim 1``. When ``|x|`` -# approaches ``n\\pi``, the function value blows up. This could be avoided as something like -# ``invsinc(mod(x, π)) * x / mod(x, π)``, but in the interest of efficiency this is not +# approaches ``n\\pi``, the function value blows up. This could be avoided as something +# like ``invsinc(mod(x, π)) * x / mod(x, π)``, but in the interest of efficiency this is not # implemented. # This function is defined to be continuous at `x == 0`, and is implemented using a Taylor @@ -103,12 +156,22 @@ function _cossu(x::Number) end end # hard-code Float64/Float32 Taylor series, with coefficients -# Float64.([(-1)^n/((2n+1)*factorial(2n-1)) for n = 1:6]) +# Float64.([(-1)^n/((2n+1)*factorial(big(2n-1))) for n = 1:10]) The cutoffs are chosen to +# balance the truncation error of the series against the cancellation in the closed form, so +# that the relative error stays below about 2 ulps. _cossu(x::Union{Float64,ComplexF64}) = - abs(x) < 0.44 ? evalpoly(x^2, (-0.3333333333333333, 0.03333333333333333, -0.0011904761904761906, 2.2045855379188714e-5, -2.505210838544172e-7, 1.9270852604185937e-9)) : + abs(x) < 1.2 ? evalpoly(x^2, ( + -0.3333333333333333, 0.03333333333333333, -0.0011904761904761906, + 2.2045855379188714e-5, -2.505210838544172e-7, 1.9270852604185937e-9, + -1.0706029224547743e-11, 4.498331606952833e-14, -1.4797143443923793e-16, + 3.9145882126782523e-19 + )) : isinf(x) ? zero(x) : ((s,c)=sincos(x); (x*c-s)/(x^3)) _cossu(x::Union{Float32,ComplexF32}) = - abs(x) < 0.817f0 ? evalpoly(x^2, (-0.333333335f0, 0.033333335f0, -0.0011904762f0, 2.2045855f-5)) : + abs(x) < 1.2f0 ? evalpoly(x^2, ( + -0.33333334f0, 0.033333335f0, -0.0011904762f0, 2.2045855f-5, -2.5052108f-7, + 1.9270852f-9 + )) : isinf(x) ? zero(x) : ((s,c)=sincos(x); (x*c-s)/(x^3)) _cossu(x::Float16) = Float16(_cossu(Float32(x))) # _cossu(x::ComplexF16) = ComplexF16(_cossu(ComplexF32(x))) diff --git a/test/Project.toml b/test/Project.toml index 281a2bcb..041713ce 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -21,14 +21,12 @@ Quaternionic = "0756cd96-85bf-4b6f-a009-b5012ea7a443" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" StaticArrays = "90137ffa-7385-5640-81b9-e52037218182" -StaticArraysCore = "1e83bf80-4336-4d27-bf5d-d5a4f845583c" Supposition = "5a0628fe-1738-4658-9b6d-0b7605a9755b" Symbolics = "0c5d862f-8b57-4792-8d23-62f2024744c7" Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" TestItemRunner = "f8b46487-2199-4994-9208-9a1283c18c0a" TestItems = "1c621080-faea-4a02-84b6-bbd5e436b8fe" Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f" -ZygoteRules = "700de1a5-db45-46bc-99cf-38207098b444" [sources] Quaternionic = {path = ".."} @@ -52,7 +50,6 @@ Latexify = "0.16.11" Mooncake = "0.5.39" ReverseDiff = "1.16.1" StaticArrays = "1.9.18" -StaticArraysCore = "1.4.4" Supposition = "0.3.3" Symbolics = "7.32.1" TestItemRunner = "1" diff --git a/test/ad_boundaries.jl b/test/ad_boundaries.jl new file mode 100644 index 00000000..f62fd738 --- /dev/null +++ b/test/ad_boundaries.jl @@ -0,0 +1,98 @@ +# Tests of how the AD packages handle quaternions at the boundary of the function being +# differentiated: a quaternion-valued final output, or an array of quaternions. Each case +# must either give the correct derivative or raise an `ArgumentError`; none may silently +# return derivatives of the scalar parts only, or zeros. Quaternions inside the function +# are tested elsewhere; here they appear only to check that they are unaffected. The +# reference derivatives come from `ForwardDiff.derivative`, which returns the full +# quaternion derivative of a quaternion-valued function of a real variable. + +@testmodule BoundaryCases begin + using Quaternionic + const q₀ = quaternion(0.3, -0.5, 0.7, 0.2) + scalarmultiple(t) = t * q₀ + rotorpath(t) = rotor(1.0, t, 2t, -t) + quatvecpath(t) = quatvec(t, t^2, -t) + exppath(t) = exp(t * quatvec(0.3, -0.4, 0.5)) * q₀ + lorentzpath(t) = Lorentz(quaternion(complex(1.0), complex(0.0, t), 0.0, 0.0)) + pair(x) = [x[1] * q₀, x[2] * conj(q₀)] + # Fifteen inputs, more than ForwardDiff's default chunk size, so that `jacobian` works + # in chunks + many(x) = [sum(x) * q₀, x[1] * exp(quatvec(x[2], x[3], x[4]))] +end + +@testitem "AD boundaries: ForwardDiff Jacobians of quaternion arrays" tags=[:ad, :forwarddiff] setup=[BoundaryCases] begin + using ForwardDiff + using .BoundaryCases: pair, many, q₀ + J = ForwardDiff.jacobian(pair, [1.5, 2.0]) + @test J isa Matrix{QuaternionF64} + @test J == [q₀ zero(q₀); zero(q₀) conj(q₀)] + x = collect(range(0.1, 1.5; length=15)) + J = ForwardDiff.jacobian(many, x) + @test J isa Matrix{QuaternionF64} + @test size(J) == (2, 15) + for i ∈ 1:2, j ∈ 1:15 + d = ForwardDiff.derivative(t -> many([k == j ? t : x[k] for k ∈ 1:15])[i], x[j]) + @test J[i, j] ≈ d atol=4eps() + end + # A `Rotor` output has `Quaternion` derivatives, and a `QuatVec` output has `QuatVec` + # derivatives. + @test ForwardDiff.jacobian(x -> [rotor(x[1], x[2], 0, 0)], [1.0, 2.0]) isa Matrix{QuaternionF64} + @test ForwardDiff.jacobian(x -> [quatvec(x[1], x[2], 0)], [1.0, 2.0]) isa Matrix{QuatVecF64} +end + +@testitem "AD boundaries: ReverseDiff quaternion outputs" tags=[:ad, :reversediff] setup=[BoundaryCases] begin + using ReverseDiff + using .BoundaryCases: q₀, pair + @test_throws ArgumentError ReverseDiff.gradient(x -> x[1] * q₀, [1.5]) + @test_throws ArgumentError ReverseDiff.jacobian(pair, [1.5, 2.0]) + # Quaternions inside the function are unaffected. + g = ReverseDiff.gradient(x -> abs2(exp(x[1] * q₀)), [0.4]) + @test g[1] ≈ 2 * abs2(exp(0.4q₀)) * real(q₀) +end + +@testitem "AD boundaries: Zygote quaternion outputs" tags=[:ad, :zygote] setup=[BoundaryCases] begin + using Zygote + using .BoundaryCases: q₀, scalarmultiple, pair + @test_throws ArgumentError Zygote.gradient(scalarmultiple, 1.5) + @test_throws ArgumentError Zygote.jacobian(scalarmultiple, 1.5) + @test_throws ArgumentError Zygote.jacobian(pair, [1.5, 2.0]) + # Quaternions inside the function, and quaternion arguments, are unaffected. + @test Zygote.gradient(t -> abs2(exp(t * q₀)), 0.4)[1] ≈ 2 * abs2(exp(0.4q₀)) * real(q₀) + @test Zygote.gradient(abs2, q₀)[1] ≈ 2q₀ + # An explicit pullback gives each component of the derivative. + _, back = Zygote.pullback(scalarmultiple, 1.5) + @test [back(e)[1] for e ∈ (quaternion(1.0), 𝐢 + 0.0, 𝐣 + 0.0, 𝐤 + 0.0)] ≈ collect(components(q₀)) +end + +@testitem "AD boundaries: DifferentiationInterface" tags=[:ad] setup=[BoundaryCases] begin + import DifferentiationInterface as DI + using ForwardDiff, Zygote, ReverseDiff + import Enzyme + using .BoundaryCases: q₀, scalarmultiple, rotorpath, quatvecpath, exppath, lorentzpath, pair + paths = (scalarmultiple, rotorpath, quatvecpath, exppath, lorentzpath) + # Reverse-mode `derivative` of a quaternion-valued function uses one pullback per unit + # quaternion, so it gives every component. + for f ∈ paths, backend ∈ (DI.AutoZygote(), DI.AutoEnzyme(mode=Enzyme.Reverse)) + # Enzyme requires the seed of a `QuatVec` output to be a `QuatVec`, but + # DifferentiationInterface seeds with `oneunit(y)`, which is a `Quaternion`. + if f === quatvecpath && backend isa DI.AutoEnzyme + @test_throws Exception DI.derivative(f, backend, 0.3) + continue + end + d = DI.derivative(f, backend, 0.3) + d₀ = ForwardDiff.derivative(f, 0.3) + @test typeof(d) == typeof(d₀) + @test d ≈ d₀ atol=8eps() + end + @test DI.derivative(scalarmultiple, DI.AutoForwardDiff(), 0.3) == q₀ + prep = DI.prepare_derivative(rotorpath, DI.AutoZygote(), 0.3) + @test DI.derivative(rotorpath, prep, DI.AutoZygote(), 0.4) ≈ + ForwardDiff.derivative(rotorpath, 0.4) atol=8eps() + @test DI.pushforward(scalarmultiple, DI.AutoZygote(), 1.5, (1.0, 2.0)) == (q₀, 2q₀) + # Forward-mode Jacobians of arrays of quaternions have quaternion entries. + @test DI.jacobian(pair, DI.AutoForwardDiff(), [1.5, 2.0]) == [q₀ zero(q₀); zero(q₀) conj(q₀)] + # Reverse-mode Jacobians of arrays of quaternions raise errors. + for backend ∈ (DI.AutoZygote(), DI.AutoEnzyme(mode=Enzyme.Reverse), DI.AutoReverseDiff()) + @test_throws ArgumentError DI.jacobian(pair, backend, [1.5, 2.0]) + end +end diff --git a/test/ad_crosscheck.jl b/test/ad_crosscheck.jl new file mode 100644 index 00000000..8ce8b1a3 --- /dev/null +++ b/test/ad_crosscheck.jl @@ -0,0 +1,890 @@ +# Cross-backend derivative harness +# +# Every case below is a function from a real vector to a real vector, built from the public +# API of Quaternionic. Because both the inputs and the outputs are plain real vectors, the +# harness does not depend on how any backend represents tangents of quaternions. For each +# case and each of its points, the Jacobian computed by an AD backend (through +# DifferentiationInterface) is compared with a reference computed by central finite +# differences of the same function, evaluated in 256-bit `BigFloat` arithmetic with a tiny +# step. The truncation and rounding errors of that reference are both far below Float64 +# roundoff, and it uses no AD backend at all. +# +# The points include generic random points and the special points at which the +# implementations branch or have removable singularities: the identity, vector parts of +# size 1e-4, 1e-8, and 1e-12, an exactly zero vector part, a pure-vector rotor, points near +# -1, equal and antipodal arguments, the ends of interpolation intervals, and the knots of +# `squad`. Only points at which the function is actually differentiable are included. +# +# Each backend runs in its own test item, so that a crash or a failure in one backend does +# not hide the results of the others. + +@testmodule ADCrossCheck begin + using Test + using Random + using LinearAlgebra: LinearAlgebra, norm, normalize, dot + using Quaternionic + import Quaternionic: RB, BR, Rv, vR, KAN, ℂreal, ℂimag, ℂconj + import DifferentiationInterface as DI + + # ── Building blocks ────────────────────────────────────────────────────────────────── + + # Each argument type is built from consecutive entries of the input vector. A `Rotor` + # is built with `rotor`, which normalizes its input, so its derivative includes the + # projection onto the unit sphere. A `Lorentz` transformation is built as a rotor + # times a boost with velocity given by three further entries. + nargs(::Val{:Q}) = 4 + nargs(::Val{:R}) = 4 + nargs(::Val{:V}) = 3 + nargs(::Val{:L}) = 7 + nargs(T::Symbol) = nargs(Val(T)) + + Qarg(x, i) = quaternion(x[i], x[i+1], x[i+2], x[i+3]) + Rarg(x, i) = rotor(x[i], x[i+1], x[i+2], x[i+3]) + Varg(x, i) = quatvec(x[i], x[i+1], x[i+2]) + Larg(x, i) = rotor(x[i], x[i+1], x[i+2], x[i+3]) * Boost(quatvec(x[i+4], x[i+5], x[i+6])) + + # Where the argument type is a variable, `make(Val(T), x, i)` selects the constructor. + # Closures must capture `Val(T)` rather than the symbol `T` itself, and must not pass + # even a literal symbol to `make`, so that the type of their result can be inferred. + # Enzyme's reverse mode, in particular, fails on functions whose results are boxed. + make(::Val{:Q}, x, i) = Qarg(x, i) + make(::Val{:R}, x, i) = Rarg(x, i) + make(::Val{:V}, x, i) = Varg(x, i) + make(::Val{:L}, x, i) = Larg(x, i) + + # The input entries that produce a given (four-component, real) quaternion value. + embed(::Val{:V}, g) = g[2:4] + embed(::Val, g) = g + embed(T::Symbol, g) = embed(Val(T), collect(Float64, g)) + + # Flatten any output into a real vector. + flat(x::Real) = [x] + flat(z::Complex) = [real(z), imag(z)] + flat(q::AbstractQuaternion{<:Real}) = collect(components(q)) + flat(q::AbstractQuaternion{<:Complex}) = + vcat(collect(real.(components(q))), collect(imag.(components(q)))) + flat(a::AbstractArray{<:Real}) = collect(vec(a)) + # Zygote cannot differentiate `vec` of an `SMatrix` (it returns a 3×3 gradient for the + # 9-vector), which is not the subject of these tests, so matrices are copied first. + flat(a::AbstractMatrix{<:Real}) = vec(Matrix(a)) + flat(a::AbstractArray{<:Complex}) = vcat(collect(real.(vec(a))), collect(imag.(vec(a)))) + flat(a::AbstractArray) = reduce(vcat, map(flat, vec(a))) + flat(t::Tuple) = reduce(vcat, map(flat, t)) + + # An output that is defined only up to an overall sign (an eigenvector, for example) is + # replaced by the products of all pairs of its components, which do not depend on that + # sign and determine the original up to that sign. + signfree(q::AbstractQuaternion) = (c = flat(q); vec(c * c')) + + # ── Points ─────────────────────────────────────────────────────────────────────────── + + const rng = Random.MersenneTwister(20261002) + const n̂ = normalize([0.36, -0.48, 0.8]) + const m̂ = normalize([-0.6, 0.0, 0.8]) + randq() = randn(rng, 4) + randv() = randn(rng, 3) + + # Quaternion values (as four-component vectors) with interesting vector parts + small(s, ε) = [s; ε .* n̂] + const unitpurevector = [0.0; n̂] + + # Points for a function of one argument of type `T`, as `label => x` pairs, selected by + # the kind of singularity the function has. For a `QuatVec`, the kinds are `:smooth` + # (including the zero vector), `:nonzero`, and `:large` (only points of order 1). + function points(T::Symbol, kind::Symbol) + s = T === :Q ? 1.3 : 1.0 # Quaternion points are deliberately not unit-norm + if T === :V + generic = ["generic" => randv(), "generic 2" => randv()] + tiny = ["vec 1e-4" => 1e-4 .* n̂, "vec 1e-8" => 1e-8 .* n̂, "vec 1e-12" => 1e-12 .* n̂] + zero = ["vec 0" => [0.0, 0.0, 0.0]] + kind === :generic && return generic[1:1] + kind === :smooth && return [generic; tiny; zero] + kind === :nonzero && return [generic; tiny] + kind === :large && return generic + error("Unknown kind $kind for $T") + end + generic = ["generic" => randq(), "generic 2" => randq()] + tiny = ["vec 1e-4" => small(s, 1e-4), "vec 1e-8" => small(s, 1e-8), + "vec 1e-12" => small(s, 1e-12)] + zero = [(T === :R ? "identity" : "vec 0") => small(s, 0.0)] + pure = ["pure vector" => [0.0; 1.1 .* n̂]] + nearm1 = ["near -1 (1e-4)" => small(-s, 1e-4)] + minus1 = [(T === :R ? "-identity" : "negative real") => small(-s, 0.0)] + if kind === :generic + return generic[1:1] + elseif kind === :smooth # Differentiable everywhere except, perhaps, at zero + return [generic; tiny; zero; pure; nearm1; minus1] + elseif kind === :log # Not differentiable on the negative real axis + return [generic; tiny; zero; pure; nearm1] + elseif kind === :absvec # Not differentiable where the vector part vanishes + return [generic; tiny; pure; nearm1] + end + error("Unknown kind $kind for $T") + end + + # ── Cases ──────────────────────────────────────────────────────────────────────────── + + # A case is a named function together with the points at which to differentiate it. + # Second derivatives are not checked at the labels listed in `nohessian`, where the + # function is only once differentiable. + const CASES = NamedTuple{(:name, :f, :points, :nohessian), + Tuple{String, Function, Vector{Pair{String,Vector{Float64}}}, Vector{String}}}[] + + function addcase!(name, f, pts; nohessian=String[]) + pts = Pair{String,Vector{Float64}}[p.first => collect(Float64, p.second) for p in pts] + push!(CASES, (name=name, f=f, points=pts, nohessian=collect(String, nohessian))) + nothing + end + + # Unary functions of one argument + function unary!(name, T::Symbol, F, kind::Symbol) + addcase!("$name($T)", let VT=Val(T); x -> flat(F(make(VT, x, 1))) end, points(T, kind)) + end + + # Concatenate points for several arguments, pairing the i-th points of each list + function pairup(pts...) + n = minimum(length, pts) + [join((p[i].first for p in pts), " | ") => reduce(vcat, (p[i].second for p in pts)) + for i in 1:n] + end + + # Points for a function of two quaternionic arguments of types `T1` and `T2` + function binarypoints(T1, T2; equal=true, antipodal=true) + pts = Pair{String,Vector{Float64}}[] + g1 = T1 === :V ? randv() : randq() + g2 = T2 === :V ? randv() : randq() + push!(pts, "generic" => [g1; g2]) + # A unit pure vector is a valid value for every argument type, so equal and + # antipodal values can be built for any pair of types. + if equal + push!(pts, "equal" => [embed(T1, unitpurevector); embed(T2, unitpurevector)]) + if T1 !== :V && T2 !== :V + u = normalize(randq()) + push!(pts, "equal 2" => [embed(T1, u); embed(T2, u)]) + end + end + if antipodal + push!(pts, "antipodal" => [embed(T1, unitpurevector); embed(T2, -unitpurevector)]) + end + pts + end + + # Constructors and accessors + # + # The linear constructors are grouped into a few cases, to save compilation time. + addcase!( + "quaternion, quatvec (4 reals)", + x -> flat(( + quaternion(x[1], x[2], x[3], x[4]), quaternion(x), + quatvec(x[1], x[2], x[3], x[4]), quatvec(x), quatvec(quaternion(x)) + )), + points(:Q, :generic) + ) + addcase!( + "quaternion, quatvec (3 reals)", + x -> flat((quaternion(x[1], x[2], x[3]), quatvec(x[1], x[2], x[3]), quatvec(x))), + points(:V, :smooth) + ) + addcase!("rotor(w,x,y,z)", x -> flat(rotor(x[1], x[2], x[3], x[4])), points(:R, :smooth)) + addcase!("rotor(x,y,z)", x -> flat(rotor(x[1], x[2], x[3])), points(:V, :large)) + addcase!("rotor(::Vector)", x -> flat(rotor(x)), points(:R, :generic)) + addcase!("rotor(::Quaternion), quaternion(::Rotor)", + x -> flat(quaternion(rotor(Qarg(x, 1)))), points(:Q, :smooth)) + addcase!( + "real, imag, vec, getindex, getproperty", + x -> (q = Qarg(x, 1); flat((real(q), imag(q), vec(q), q[2], q.z))), + points(:Q, :generic) + ) + + # Algebra of two quaternionic arguments + const TYPES = (:Q, :R, :V) + # + # Multiplication and division are checked for every pair of types, but addition and + # subtraction, which are simpler, only for some. + const SUMTYPES = ((:Q, :Q), (:R, :R), (:V, :V), (:Q, :R), (:V, :R)) + for T1 ∈ TYPES, T2 ∈ TYPES, (opname, op) ∈ (("+", +), ("-", -), ("*", *), ("/", /)) + opname ∈ ("+", "-") && (T1, T2) ∉ SUMTYPES && continue + n1 = nargs(T1) + addcase!( + "$T1 $opname $T2", + let op=op, V1=Val(T1), V2=Val(T2), n1=n1 + x -> flat(op(make(V1, x, 1), make(V2, x, n1 + 1))) + end, + binarypoints(T1, T2) + ) + end + + # Algebra mixing a real scalar `t` (the first input) with a quaternionic argument + for T ∈ TYPES, (opname, op) ∈ (("+", +), ("-", -), ("*", *), ("/", /)) + pts = Pair{String,Vector{Float64}}[ + "generic" => [0.7; T === :V ? randv() : randq()], + # The quaternion equals the scalar, where shortcuts based on equality would bite + "equal" => [1.0; embed(T, [1.0, 0, 0, 0])], + ] + T === :V && pop!(pts) # A QuatVec cannot equal a nonzero scalar + addcase!("t $opname $T", let op=op, VT=Val(T) + x -> flat(op(x[1], make(VT, x, 2))) + end, pts) + addcase!("$T $opname t", let op=op, VT=Val(T) + x -> flat(op(make(VT, x, 2), x[1])) + end, pts) + end + + # Unary algebra + for T ∈ TYPES + unary!("-, conj", T, q -> (-q, conj(q)), :smooth) + unary!("inv", T, inv, T === :V ? :nonzero : :smooth) + unary!("abs", T, abs, T === :V ? :nonzero : :smooth) + unary!("abs2", T, abs2, :smooth) + unary!("normalize", T, normalize, T === :V ? :nonzero : :smooth) + end + for T ∈ (:Q, :R) + unary!("absvec", T, absvec, :absvec) + unary!("abs2vec", T, abs2vec, :smooth) + end + + # Transcendental functions + unary!("exp", :Q, exp, :smooth) + unary!("exp", :V, exp, :smooth) + unary!("log", :Q, log, :log) + unary!("log", :R, log, :log) + unary!("sqrt", :Q, sqrt, :log) + unary!("sqrt", :R, sqrt, :log) + unary!("sqrt", :V, sqrt, :nonzero) + unary!("angle", :Q, angle, :absvec) + unary!("angle", :R, angle, :absvec) + + # Powers with integer exponents + const EXPONENTS = Dict(:Q => (-2, -1, 0, 1, 2, 3), :R => (-1, 2), :V => (-1, 2, 3)) + for T ∈ TYPES, n ∈ EXPONENTS[T] + unary!("^$n", T, let n=n; q -> q^n end, T === :V ? (n > 0 ? :smooth : :nonzero) : :smooth) + end + # Powers with real exponents, both fixed and as the last input + for T ∈ TYPES + kind = T === :V ? :nonzero : :log + unary!("^0.37", T, q -> q^0.37, kind) + pts = [p.first => [p.second; 0.37] for p in points(T, kind)] + addcase!("$T^s", let VT=Val(T); x -> flat(make(VT, x, 1)^x[end]) end, pts) + end + addcase!("R^s (large s)", x -> flat(Rarg(x, 1)^x[end]), + [p.first => [p.second; 7.3] for p in points(:R, :log)]) + addcase!("t^Q", x -> flat(x[1]^Qarg(x, 2)), ["generic" => [1.7; randq()]]) + addcase!("Q^Q", x -> flat(Qarg(x, 1)^Qarg(x, 5)), + ["generic" => [randq(); randq()], "vec 1e-8 | generic" => [small(1.3, 1e-8); randq()]]) + + # Products of vectors + addcase!("Q ⋅ Q", x -> flat(Qarg(x, 1) ⋅ Qarg(x, 5)), binarypoints(:Q, :Q)) + addcase!("R ⋅ R", x -> flat(Rarg(x, 1) ⋅ Rarg(x, 5)), binarypoints(:R, :R)) + addcase!("V ⋅ V", x -> flat(Varg(x, 1) ⋅ Varg(x, 4)), binarypoints(:V, :V)) + addcase!("Q ⋅ V", x -> flat(Qarg(x, 1) ⋅ Varg(x, 5)), binarypoints(:Q, :V)) + addcase!("V × V", x -> flat(Varg(x, 1) × Varg(x, 4)), binarypoints(:V, :V)) + # The normalized cross product is not differentiable for parallel arguments + addcase!("V ×̂ V", x -> flat(Varg(x, 1) ×̂ Varg(x, 4)), + binarypoints(:V, :V; equal=false, antipodal=false)) + + # Distances. `distance` is the square root of `distance2`, so it is not differentiable + # where `distance2` vanishes: for equal arguments and, for two rotors, for antipodal + # ones. For two rotors, `distance2` has a kink where the rotors are orthogonal in ℝ⁴, + # which no point here approaches. + for (T1, T2) ∈ ((:Q, :Q), (:R, :R), (:V, :V), (:Q, :R), (:R, :V), (:V, :Q)) + n1 = nargs(T1) + bothrotors = T1 === :R && T2 === :R + addcase!("distance2($T1, $T2)", let V1=Val(T1), V2=Val(T2), n1=n1 + x -> flat(distance2(make(V1, x, 1), make(V2, x, n1 + 1))) + end, binarypoints(T1, T2)) + addcase!("distance($T1, $T2)", let V1=Val(T1), V2=Val(T2), n1=n1 + x -> flat(distance(make(V1, x, 1), make(V2, x, n1 + 1))) + end, binarypoints(T1, T2; equal=false, antipodal=!bothrotors)) + end + # Rotor distances near equal and near antipodal arguments, where the series branch is + # taken + let + u = normalize(randq()) + near(ε) = normalize(u .+ ε .* [0.0; n̂]) + pts = ["near equal ($ε)" => [u; near(ε)] for ε ∈ (1e-4, 1e-8, 1e-12)] + apts = ["near antipodal ($ε)" => [u; -near(ε)] for ε ∈ (1e-4, 1e-8, 1e-12)] + addcase!("distance2(R, R) near", x -> flat(distance2(Rarg(x, 1), Rarg(x, 5))), [pts; apts]) + addcase!("distance(R, R) near", x -> flat(distance(Rarg(x, 1), Rarg(x, 5))), [pts; apts]) + end + + # Interpolation + let + u1, u2 = normalize(randq()), normalize(randq()) + near(u, ε) = normalize(u .+ ε .* [0.0; n̂]) + pts = [ + "generic" => [u1; u2; 0.37], + "τ = 0" => [u1; u2; 0.0], + "τ = 1" => [u1; u2; 1.0], + "q₁ == q₂" => [u1; u1; 0.37], + "q₁ == q₂, τ = 0" => [u1; u1; 0.0], + "nearly equal (1e-4)" => [u1; near(u1, 1e-4); 0.37], + "nearly equal (1e-8)" => [u1; near(u1, 1e-8); 0.37], + "nearly antipodal (1e-4)" => [u1; -near(u1, 1e-4); 0.37], + "generic, τ = 1.6" => [u1; u2; 1.6], + "unnormalized" => [2.1 .* u1; 0.4 .* u2; 0.37], + ] + addcase!("slerp", x -> flat(slerp(Rarg(x, 1), Rarg(x, 5), x[9])), pts) + apts = [ + "generic" => [u1; u2; 0.37], + "antipodal" => [u1; -u1; 0.37], + "nearly antipodal (1e-8)" => [u1; -near(u1, 1e-8); 0.37], + ] + addcase!("slerp(unflip=true)", + x -> flat(slerp(Rarg(x, 1), Rarg(x, 5), x[9]; unflip=true)), apts) + end + let + # Four rotors at the times `tin`; the output time is the last input. The function + # is continuously differentiable across the knots, but not twice differentiable. + tin = [0.0, 0.7, 1.5, 2.6] + ω⃗ = quatvec(0.3, -0.8, 0.5) + Rs = [components(exp(t * ω⃗) * rotor(1.0, 0.1, -0.2, 0.05)) for t ∈ tin] + Rs[3] = Rs[3] .+ 0.01 .* randq() # Make it a little irregular + x0 = reduce(vcat, collect.(Rs)) + pts = [ + "interior interval" => [x0; 1.1], + "first interval" => [x0; 0.3], + "last interval" => [x0; 2.2], + "knot t₂" => [x0; 0.7], + "knot t₃" => [x0; 1.5], + ] + addcase!("squad", + x -> flat(squad([Rarg(x, 1), Rarg(x, 5), Rarg(x, 9), Rarg(x, 13)], + tin, x[17])), + pts; nohessian=["knot t₂", "knot t₃"]) + # The angular velocity and the time derivative are continuous across the knots, but + # their derivatives with respect to time are not. + addcase!("squad(compute_angular_velocity=true, compute_derivative=true)", + x -> flat(squad([Rarg(x, 1), Rarg(x, 5), Rarg(x, 9), Rarg(x, 13)], + tin, x[17]; compute_angular_velocity=true, compute_derivative=true)), + pts[1:3]) + end + let + # A sequence of quaternions in which some signs need flipping + u = [normalize(randq()) for _ ∈ 1:4] + for i ∈ 2:4 + if dot(u[i], u[i-1]) * (iseven(i) ? 1 : -1) < 0 + u[i] = -u[i] + end + end + pts = ["generic" => reduce(vcat, u)] + addcase!("unflip(::Vector{Quaternion})", + x -> flat(unflip([Qarg(x, 1), Qarg(x, 5), Qarg(x, 9), Qarg(x, 13)])), pts) + addcase!("unflip(::Vector{Rotor})", + x -> flat(unflip([Rarg(x, 1), Rarg(x, 5), Rarg(x, 9), Rarg(x, 13)])), pts) + end + + # Action of a rotor or a quaternion on a vector + addcase!("R(v)", x -> flat(Rarg(x, 1)(Varg(x, 5))), + pairup(points(:R, :smooth), [points(:V, :smooth); points(:V, :smooth)])) + addcase!("Q(v)", x -> flat(Qarg(x, 1)(Varg(x, 5))), + pairup(points(:Q, :generic), points(:V, :generic))) + + # Conversions + let + # A generic rotor whose Euler angle β is far from 0 and π + u = [0.6, -0.3, 0.5, 0.4] + addcase!("to_euler_angles(R)", x -> flat(to_euler_angles(Rarg(x, 1))), + ["generic" => u, "β = 1e-4" => collect(components(from_euler_angles(0.3, 1e-4, -2.1)))]) + addcase!("to_euler_angles(Q)", x -> flat(to_euler_angles(Qarg(x, 1))), ["generic" => 1.7u]) + addcase!("from_euler_angles", x -> flat(from_euler_angles(x[1], x[2], x[3])), + ["generic" => [0.3, 1.1, -2.1], "β = 0" => [0.3, 0.0, -2.1], "β = π" => [0.3, π, -2.1]]) + addcase!("from_euler_angles(::Vector)", x -> flat(from_euler_angles(x)), ["generic" => [0.3, 1.1, -2.1]]) + addcase!("to_euler_phases", x -> flat(to_euler_phases(Rarg(x, 1))), ["generic" => u]) + addcase!("to_euler_phases!", + x -> (R = Rarg(x, 1); flat(to_euler_phases!(Vector{Complex{basetype(R)}}(undef, 3), R))), + ["generic" => u]) + z = to_euler_phases(rotor(u...)) + zx = reduce(vcat, [[real(zi), imag(zi)] for zi ∈ z]) + addcase!("from_euler_phases", + x -> flat(from_euler_phases(complex(x[1], x[2]), complex(x[3], x[4]), complex(x[5], x[6]))), + ["generic" => zx, "off the unit circle" => 1.1 .* zx]) + # The polar angle θ is not differentiable where it vanishes, but it is for small θ. + sph(θ) = collect(components(from_spherical_coordinates(θ, 0.7))) + addcase!("to_spherical_coordinates", x -> flat(to_spherical_coordinates(Rarg(x, 1))), + ["generic" => u, "θ = 1e-4" => sph(1e-4), "θ = 1e-8" => sph(1e-8)]) + addcase!("from_spherical_coordinates", x -> flat(from_spherical_coordinates(x[1], x[2])), + ["generic" => [1.1, -2.1], "θ = 0" => [0.0, -2.1]]) + addcase!("to_rotation_matrix(R)", x -> flat(to_rotation_matrix(Rarg(x, 1))), points(:R, :smooth)) + addcase!("to_rotation_matrix(Q)", x -> flat(to_rotation_matrix(Qarg(x, 1))), points(:Q, :generic)) + # The sign of the result of `from_rotation_matrix` is arbitrary, so only quantities + # independent of that sign are compared. + M = vec(to_rotation_matrix(rotor(u...))) + addcase!("from_rotation_matrix", x -> signfree(from_rotation_matrix(reshape(x, 3, 3))), + ["generic" => M, "identity" => vec(Matrix{Float64}(LinearAlgebra.I, 3, 3)), + "perturbed" => M .+ 0.01 .* randn(rng, 9)]) + addcase!("to_float_array(::Vector)", x -> flat(to_float_array([Qarg(x, 1), Qarg(x, 5)])), + ["generic" => [randq(); randq()]]) + addcase!("to_float_array(q)", x -> flat(to_float_array(Qarg(x, 1))), points(:Q, :generic)) + addcase!("from_float_array", x -> flat(from_float_array(reshape(x, 4, 2))), + ["generic" => [randq(); randq()]]) + end + + # Alignment + let + R0 = rotor(0.6, -0.3, 0.5, 0.4) + b = [randv() for _ ∈ 1:3] + a = [collect(vec(R0(quatvec(bi...)))) .+ 0.05 .* randv() for bi ∈ b] + w = [0.5, 1.3, 0.9] + x0 = [reduce(vcat, a); reduce(vcat, b); w] + V3(x, i) = [Varg(x, i), Varg(x, i + 3), Varg(x, i + 6)] + # The sign of the dominant eigenvector is arbitrary + addcase!("align(::Vector{QuatVec}, ::Vector{QuatVec}, w)", + x -> signfree(align(V3(x, 1), V3(x, 10), x[19:21])), ["generic" => x0]) + addcase!("align(::Vector{QuatVec}, ::Vector{QuatVec})", + x -> signfree(align(V3(x, 1), V3(x, 10))), ["generic" => x0[1:18]]) + B = [normalize(randq()) for _ ∈ 1:3] + A = [collect(components(R0 * rotor(Bi...))) .+ 0.05 .* randq() for Bi ∈ B] + y0 = [reduce(vcat, A); reduce(vcat, B); w] + R3(x, i) = [Rarg(x, i), Rarg(x, i + 4), Rarg(x, i + 8)] + addcase!("align(::Vector{Rotor}, ::Vector{Rotor}, w)", + x -> flat(align(R3(x, 1), R3(x, 13), x[25:27])), ["generic" => y0]) + addcase!("align(::Vector{Rotor}, ::Vector{Rotor})", + x -> flat(align(R3(x, 1), R3(x, 13))), ["generic" => y0[1:24]]) + end + + # Lorentz transformations + let + vpts = ["generic" => [0.3, -0.2, 0.5], "zero velocity" => [0.0, 0.0, 0.0], + "velocity 1e-4" => 1e-4 .* n̂, "velocity 1e-8" => 1e-8 .* n̂] + addcase!("Boost(η, ::Vector)", x -> flat(Boost(x[1], x[2:4])), + ["generic" => [0.8; n̂], "η = 0" => [0.0; n̂], "unnormalized" => [0.8; 1.3 .* m̂]]) + addcase!("Boost(constant η, ::Vector)", x -> flat(Boost(0.8, x)), ["generic" => n̂]) + addcase!("Boost(η, ::QuatVec)", x -> flat(Boost(x[1], Varg(x, 2))), + ["generic" => [0.8; n̂], "η = 0" => [0.0; n̂]]) + addcase!("Boost(::QuatVec)", x -> flat(Boost(Varg(x, 1))), vpts) + addcase!("Boost(::Vector)", x -> flat(Boost(x[1:3])), vpts) + lpts = [p.first => [normalize(randq()); p.second] for p in vpts] + addcase!("ga_components(Λ)", x -> flat(ga_components(Larg(x, 1))), lpts) + addcase!("Λ * Λ", x -> flat(Larg(x, 1) * Larg(x, 8)), pairup(lpts, reverse(lpts))) + addcase!("inv(Λ)", x -> flat(inv(Larg(x, 1))), lpts) + addcase!("conj(Λ)", x -> flat(conj(Larg(x, 1))), lpts) + addcase!("Λ * R", x -> flat(Larg(x, 1) * Rarg(x, 8)), [p.first => [p.second; randq()] for p in lpts]) + addcase!("Λ(v)", x -> flat(Larg(x, 1)(x[8:11])), [p.first => [p.second; randq()] for p in lpts]) + addcase!("ℂconj, ℂreal, ℂimag", x -> (Λ = Larg(x, 1); flat((ℂconj(Λ), ℂreal(Λ), ℂimag(Λ)))), lpts) + addcase!("RB", x -> flat(RB(Larg(x, 1))), lpts) + addcase!("BR", x -> flat(BR(Larg(x, 1))), lpts) + addcase!("Rv", x -> flat(Rv(Larg(x, 1))), lpts) + addcase!("vR", x -> flat(vR(Larg(x, 1))), lpts) + addcase!("KAN", x -> flat(KAN(Larg(x, 1))), lpts) + end + + # ── References ─────────────────────────────────────────────────────────────────────── + + const PRECISION = 256 + + # Central differences in 256-bit arithmetic. With h = 1e-30, the truncation error is + # of order h² f‴ ≈ 1e-60 f‴, and the rounding error is of order 2⁻²⁵⁶/h ≈ 1e-47. + function reference_jacobian(f, x::Vector{BigFloat}) + h = BigFloat(10)^-30 + columns = map(eachindex(x)) do j + e = zeros(BigFloat, length(x)) + e[j] = h + (f(x .+ e) .- f(x .- e)) ./ (2h) + end + reduce(hcat, columns) + end + + # The Hessian of `s` by central second differences in 256-bit arithmetic. With + # h = 1e-25, the truncation error is of order h² s⁗ ≈ 1e-50 s⁗, and the rounding error + # is of order 2⁻²⁵⁶/h² ≈ 1e-27. + function reference_hessian(s, x::Vector{BigFloat}) + h = BigFloat(10)^-25 + n = length(x) + e(i) = (v = zeros(BigFloat, n); v[i] = h; v) + H = zeros(BigFloat, n, n) + for i ∈ 1:n, j ∈ i:n + H[i, j] = H[j, i] = ( + s(x .+ e(i) .+ e(j)) - s(x .+ e(i) .- e(j)) + - s(x .- e(i) .+ e(j)) + s(x .- e(i) .- e(j)) + ) / (4h^2) + end + H + end + + # Even an implementation that is backward stable — one that returns the exact result + # for inputs perturbed by a few ulps — cannot have derivatives more accurate than the + # change in the exact derivative under such a perturbation. Where the derivative is + # ill-conditioned, for example in the direction of a difference of two nearly equal + # rotors, that change can be far larger than a few hundred ulps of the derivative + # itself. So, alongside each reference, we compute the change in the reference when + # every input is perturbed by at most one ulp in relative terms, and the tolerance + # allows `CONDITIONING` times that change. + const CONDITIONING = 30 + + function reference(derivative, f, x::Vector{Float64}, seed) + setprecision(BigFloat, PRECISION) do + xb = BigFloat.(x) + r = 2 .* rand(Random.MersenneTwister(seed), length(x)) .- 1 + x̃ = xb .* (1 .+ eps(Float64) .* BigFloat.(r)) + D = derivative(f, xb) + D̃ = derivative(f, x̃) + Float64.(D), Float64(norm(D̃ .- D)) + end + end + + # The references depend only on the case and the point, so they are computed once per + # process and shared by all backends. + const JACOBIANS = Dict{Tuple{String,String},Tuple{Matrix{Float64},Float64}}() + const HESSIANS = Dict{Tuple{String,String},Tuple{Matrix{Float64},Float64}}() + reference_jacobian(c, p::Pair) = get!(JACOBIANS, (c.name, p.first)) do + reference(reference_jacobian, c.f, p.second, hash((c.name, p.first))) + end + reference_hessian(c, p::Pair) = get!(HESSIANS, (c.name, p.first)) do + reference(reference_hessian, scalarize(c), p.second, hash((c.name, p.first))) + end + + # A scalar function for the second-derivative checks: a fixed random linear combination + # of the outputs of the case + const WEIGHTS = Dict{String,Vector{Float64}}() + function scalarize(c) + m = length(c.f(c.points[1].second)) + w = get!(() -> 0.5 .+ rand(Random.MersenneTwister(hash(c.name)), m), WEIGHTS, c.name) + x -> dot(w, c.f(x)) + end + + # Errors are measured relative to the size of the reference, but never relative to a + # size smaller than 1, so that a vanishing reference does not demand an exact zero. + scale(Dref) = max(norm(Dref), 1) + relerr(D, Dref) = norm(D .- Dref) / scale(Dref) + + # ── Running the checks ─────────────────────────────────────────────────────────────── + + # Every outcome is also recorded here, so that a script can tabulate the results. If + # the environment variable `QUATERNIONIC_AD_CROSSCHECK_RESULTS` names a file, each + # outcome is also appended to that file as a line of tab-separated values: the backend, + # the case, the point, the status, and the details. + const RESULTS = NamedTuple{(:backend, :case, :point, :status, :detail), + Tuple{String,String,String,Symbol,String}}[] + + function record!(backend, c, p, status, detail) + push!(RESULTS, (backend=backend, case=c.name, point=p.first, status=status, detail=detail)) + file = get(ENV, "QUATERNIONIC_AD_CROSSCHECK_RESULTS", "") + if !isempty(file) + open(file, "a") do io + fields = (backend, c.name, p.first, string(status), detail) + println(io, join((replace(f, '\t' => ' ', '\n' => ' ') for f ∈ fields), '\t')) + end + end + nothing + end + + firstline(e) = first(split(sprint(showerror, e), '\n')) + + # Cases that a backend cannot differentiate, because of a bug or a limitation of the + # backend itself rather than of Quaternionic, with the reason. Their checks are + # `@test_broken`, so that a fix in the backend shows up as an unexpected pass, which + # should then be removed from this list. Each reason names a reproduction that does + # not need this harness; the reproductions are kept with the notes of the 4.4.5 patch, + # in `scratchpad/upstream/`. + const BROKEN = Dict{Tuple{String,String},String}() + for case ∈ ("squad", "squad(compute_angular_velocity=true, compute_derivative=true)", + "unflip(::Vector{Quaternion})", "unflip(::Vector{Rotor})", "to_euler_phases!") + BROKEN[("Zygote", case)] = + "Zygote does not support mutating arrays, which this function does " * + "(reproduction: upstream/zygote_mutation.jl)" + end + BROKEN[("Zygote", "from_euler_angles(::Vector)")] = + "Zygote's `jacobian` fails for a function that splats its vector argument " * + "(reproduction: upstream/zygote_jacobian_splat.jl)" + for case ∈ ("to_float_array(::Vector)", "from_float_array") + BROKEN[("Zygote", case)] = + "Zygote has no adjoint for the constructor of a `ReinterpretArray` " * + "(reproduction: upstream/zygote_reinterpret.jl)" + end + for case ∈ ("squad", "squad(compute_angular_velocity=true, compute_derivative=true)", + "unflip(::Vector{Quaternion})", "unflip(::Vector{Rotor})") + BROKEN[("Enzyme reverse", case)] = + "Enzyme's batched reverse mode crashes the compiler on this function " * + "(reproductions: upstream/enzyme_3.jl and upstream/enzyme_4.jl)" + end + isbroken(label, c) = haskey(BROKEN, (label, c.name)) + + # An optional hook, called before each evaluation, so that a script can find out which + # case was running when a backend crashed the process + const BEFORE = Ref{Any}(nothing) + + function check(label, derivative, reference, rtol, c, p) + BEFORE[] === nothing || BEFORE[](label, c, p) + if isbroken(label, c) + ok = try + D = derivative(c, p) + Dref, κ = reference(c, p) + err, tol = relerr(D, Dref), rtol + CONDITIONING * κ / scale(Dref) + record!(label, c, p, err ≤ tol ? :pass : :broken, "relerr=$(err) tol=$(tol)") + err ≤ tol + catch e + record!(label, c, p, :broken, firstline(e)) + false + end + @test_broken ok + return + end + D = try + derivative(c, p) + catch e + record!(label, c, p, :error, firstline(e)) + rethrow() + end + err, tol = try + Dref, κ = reference(c, p) + relerr(D, Dref), rtol + CONDITIONING * κ / scale(Dref) + catch e + record!(label, c, p, :error, "comparison failed: " * firstline(e)) + rethrow() + end + record!(label, c, p, err ≤ tol ? :pass : :fail, "relerr=$(err) tol=$(tol)") + @test err ≤ tol + end + + """ + crosscheck(label, backend; rtol=300eps(), cases=CASES) + + Compare the Jacobian of every case in `cases` at every point, computed by `backend`, + with the reference. The error relative to the size of the reference may be at most + `rtol`, plus `CONDITIONING` times the change in the reference under a one-ulp + perturbation of the input, also relative to the size of the reference. The outcome of + each comparison is also recorded in `RESULTS`. + """ + function crosscheck(label, backend; rtol=300eps(), cases=CASES) + derivative(c, p) = DI.jacobian(c.f, backend, p.second) + @testset "$label" begin + for c ∈ cases + @testset "$(c.name)" begin + for p ∈ c.points + @testset "$(p.first)" begin + check(label, derivative, reference_jacobian, rtol, c, p) + end + end + end + end + end + end + + # Second derivatives are checked for every case with a scalar output, and for the cases + # with vector outputs whose second derivatives are at particular risk: those with + # series expansions near removable singularities, and those that go through an + # eigendecomposition. Checking every case would take much longer. + const HESSIAN_NAMES = [ + "rotor(w,x,y,z)", "Q * Q", "R * R", "Q / Q", "R / R", "V / V", "inv(Q)", "normalize(V)", + "exp(Q)", "exp(V)", "log(Q)", "log(R)", "sqrt(Q)", "sqrt(R)", + "^-1(Q)", "^2(Q)", "^0.37(Q)", "Q^s", "R^s", "V^s", "Q^Q", + "slerp", "squad", "R(v)", "to_euler_angles(R)", "from_euler_phases", + "to_spherical_coordinates", "from_rotation_matrix", + "align(::Vector{QuatVec}, ::Vector{QuatVec}, w)", "align(::Vector{Rotor}, ::Vector{Rotor}, w)", + "Boost(::QuatVec)", "Λ * Λ", "Λ(v)", "RB", "Rv", "KAN", + ] + hessian_cases() = + filter(c -> c.name ∈ HESSIAN_NAMES || length(c.f(c.points[1].second)) == 1, CASES) + + """ + crosscheck_hessian(label, backend; rtol=1e4eps(), cases=hessian_cases()) + + Compare the Hessian of a fixed random linear combination of the outputs of each case at + every point at which it is twice differentiable, computed by `backend`, with the + reference. The tolerance is formed as in `crosscheck`. + """ + function crosscheck_hessian(label, backend; rtol=1e4eps(), cases=hessian_cases()) + derivative(c, p) = DI.hessian(scalarize(c), backend, p.second) + @testset "$label" begin + for c ∈ cases + @testset "$(c.name)" begin + for p ∈ c.points + p.first ∈ c.nohessian && continue + @testset "$(p.first)" begin + check(label, derivative, reference_hessian, rtol, c, p) + end + end + end + end + end + end + + # ── Running in a separate process ──────────────────────────────────────────────────── + + # Some backends can crash the whole Julia process (with a segmentation fault inside the + # Enzyme compiler, for example) rather than throw an error. When the test items all run + # in one process, as under `runtests.jl`, such a crash would end the whole test run. So + # these backends run in a child process, which is restarted without the case that was + # running when it crashed. The crash is then reported as an error for that case. + + # A test set that records nothing, for use in the child process, which reports its + # outcomes through a file instead + struct QuietTestSet <: Test.AbstractTestSet end + QuietTestSet(description; kwargs...) = QuietTestSet() + Test.record(::QuietTestSet, result) = nothing + Test.finish(::QuietTestSet) = nothing + + # The body of the child process: run the cases not listed in `skipfile`, appending each + # outcome to `resultsfile` and the name of each case and point to `progressfile` just + # before it is evaluated. + function child(label, backend, skipfile, progressfile, resultsfile; rtol) + skip = Set(filter(!isempty, readlines(skipfile))) + written = Ref(0) + function flushresults() + open(resultsfile, "a") do io + for r ∈ RESULTS[written[]+1:end] + detail = replace(r.detail, '\t' => ' ', '\n' => ' ') + println(io, join((r.case, r.point, r.status, detail), '\t')) + end + end + written[] = length(RESULTS) + end + BEFORE[] = (label, c, p) -> begin + flushresults() + write(progressfile, string(c.name, '\t', p.first)) + end + Test.@testset QuietTestSet "child" begin + crosscheck(label, backend; rtol=rtol, cases=filter(c -> c.name ∉ skip, CASES)) + end + flushresults() + write(progressfile, "DONE") + nothing + end + + """ + crosscheck_isolated(label, imports, backend; rtol=300eps(), cases=CASES, maxrestarts=20) + + Run `crosscheck` in a child process, and report its outcomes as tests in this process. + Here, `imports` is code that loads the backend in the child, and `backend` is code that + constructs the backend there. If the child crashes, the case that was running is + reported as an error, and a new child continues with the remaining cases. + """ + function crosscheck_isolated(label, imports, backend; rtol=300eps(), cases=CASES, maxrestarts=20) + self = joinpath(pkgdir(Quaternionic), "test", "ad_crosscheck.jl") + dir = mktempdir() + skipfile, progressfile, resultsfile, logfile = + joinpath.(dir, ("skip", "progress", "results", "log")) + script = """ + using Test + import DifferentiationInterface as DI + $imports + let ex = Meta.parseall(read($(repr(self)), String); filename=$(repr(self))) + m = only(a for a ∈ ex.args + if a isa Expr && a.head === :macrocall && a.args[1] === Symbol("@testmodule")) + Core.eval(Main, Expr(:module, true, m.args[3], m.args[4])) + end + Main.ADCrossCheck.child($(repr(label)), $backend, $(repr(skipfile)), + $(repr(progressfile)), $(repr(resultsfile)); rtol=$rtol) + """ + # The child reports its outcomes to this process, which records them. + env = delete!(copy(ENV), "QUATERNIONIC_AD_CROSSCHECK_RESULTS") + cmd = setenv( + `$(Base.julia_cmd()) --startup-file=no --project=$(Base.active_project()) -e $script`, + env + ) + crashes = Dict{Tuple{String,String},String}() + skip = Set{String}(c.name for c ∈ CASES if c ∉ cases) + for _ ∈ 1:maxrestarts + write(skipfile, join(skip, '\n')) + rm(progressfile; force=true) + process = run(pipeline(ignorestatus(cmd); stdout=logfile, stderr=logfile)) + progress = isfile(progressfile) ? read(progressfile, String) : "" + progress == "DONE" && break + log = read(logfile, String) + if isempty(progress) + # The child failed before reaching any case, so restarting would not help. + error("The child process for $label failed before running any case:\n" * + join(last(split(log, '\n'), 30), '\n')) + end + case, point = split(progress, '\t') + signal = match(r"signal \(?\d+\)?[^\n]*|LLVM ERROR[^\n]*|Assertion[^\n]*", log) + how = process.termsignal == 0 ? "exit code $(process.exitcode)" : "signal $(process.termsignal)" + crashes[(case, point)] = "The process crashed ($how)" * + (signal === nothing ? "" : ": $(signal.match)") + push!(skip, case) + # Cases already completed are not run again. + isfile(resultsfile) && + foreach(l -> push!(skip, first(split(l, '\t'))), readlines(resultsfile)) + end + outcomes = Dict{Tuple{String,String},Tuple{String,String}}() + if isfile(resultsfile) + for l ∈ readlines(resultsfile) + case, point, status, detail = split(l, '\t'; limit=4) + outcomes[(case, point)] = (status, detail) + end + end + @testset "$label" begin + for c ∈ cases + @testset "$(c.name)" begin + for p ∈ c.points + @testset "$(p.first)" begin + key = (c.name, p.first) + if isbroken(label, c) + status, detail = get(outcomes, key, ("broken", + get(crashes, key, "Not reached by the child process"))) + record!(label, c, p, Symbol(status), detail) + @test_broken status == "pass" + elseif haskey(crashes, key) + record!(label, c, p, :crash, crashes[key]) + error(crashes[key]) + elseif !haskey(outcomes, key) + message = any(k -> k[1] == c.name, keys(crashes)) ? + "Not reached, because another point of this case crashed the process" : + "Not reached by the child process" + record!(label, c, p, :error, message) + error(message) + else + status, detail = outcomes[key] + record!(label, c, p, Symbol(status), detail) + status == "error" && error(detail) + @test status == "pass" + end + end + end + end + end + end + end +end + + +@testitem "AD cross-check: ForwardDiff" setup=[ADCrossCheck] tags=[:slow, :validation] begin + import DifferentiationInterface as DI + import ForwardDiff + ADCrossCheck.crosscheck("ForwardDiff", DI.AutoForwardDiff()) +end + +@testitem "AD cross-check: ForwardDiff second derivatives" setup=[ADCrossCheck] tags=[:slow, :validation] begin + import DifferentiationInterface as DI + import ForwardDiff + # With the default chunk size, nested dual numbers with as many as 12 partials at each + # level make compilation take a minute or more for some cases. A chunk size of 1 computes the same + # Hessian in a fraction of a second. + ADCrossCheck.crosscheck_hessian("ForwardDiff (Hessian)", DI.AutoForwardDiff(chunksize=1)) +end + +@testitem "AD cross-check: Zygote" setup=[ADCrossCheck] tags=[:slow, :validation] begin + import DifferentiationInterface as DI + import Zygote + ADCrossCheck.crosscheck("Zygote", DI.AutoZygote()) +end + +@testitem "AD cross-check: ReverseDiff" setup=[ADCrossCheck] tags=[:slow, :validation] begin + import DifferentiationInterface as DI + import ReverseDiff + ADCrossCheck.crosscheck("ReverseDiff", DI.AutoReverseDiff()) +end + +@testitem "AD cross-check: Mooncake" setup=[ADCrossCheck] tags=[:slow, :validation] begin + import DifferentiationInterface as DI + import Mooncake + ADCrossCheck.crosscheck("Mooncake", DI.AutoMooncake(config=nothing)) +end + +@testitem "AD cross-check: Enzyme forward" setup=[ADCrossCheck] tags=[:slow, :validation] begin + # Enzyme can crash the process, so the cases run in a child process. + ADCrossCheck.crosscheck_isolated( + "Enzyme forward", + "import Enzyme", + "DI.AutoEnzyme(mode=Enzyme.Forward, function_annotation=Enzyme.Const)" + ) +end + +@testitem "AD cross-check: Enzyme reverse" setup=[ADCrossCheck] tags=[:slow, :validation] begin + # Enzyme can crash the process, so the cases run in a child process. + ADCrossCheck.crosscheck_isolated( + "Enzyme reverse", + "import Enzyme", + "DI.AutoEnzyme(mode=Enzyme.Reverse, function_annotation=Enzyme.Const)" + ) +end diff --git a/test/ad_enzyme.jl b/test/ad_enzyme.jl new file mode 100644 index 00000000..990e31fa --- /dev/null +++ b/test/ad_enzyme.jl @@ -0,0 +1,596 @@ +# Tests of Enzyme, which differentiates the package's source natively, and of +# `QuaternionicEnzymeExt`, which adds `Enzyme.onehot` for quaternion arguments, rules for +# the LAPACK call behind `from_rotation_matrix` and `align`, and rules for `abs` and +# `absvec` that work around a bug in Enzyme's reverse rule for `hypot`. The references are +# central finite differences in 256-bit `BigFloat` arithmetic (`bigfd` from `ADTestUtils`), +# except for the Hessians, which are compared with ForwardDiff's. +# +# Enzyme's reverse mode is tested at batch width 1 (the gradient of a scalar loss) except in +# the items on batched reverse mode and on `dominant_eigenvector_lapack`. At batch widths +# greater than 1, which DifferentiationInterface uses for Jacobians, Enzyme 0.13.205 crashes +# the compiler on `squad` and `unflip` (an upstream bug), so those functions are tested only +# at batch width 1. Enzyme's reverse rule for `hypot` with three or more arguments also +# fails at those batch widths (another upstream bug). The extension's rules for `abs` and +# `absvec` avoid it, and `sqrt` of a quaternion with a negative scalar part computes the +# norm of its vector part with `abs` for that reason. Forward mode pushes every tangent +# of a vector argument at once (batch width 4 or more), which works. + +@testmodule EnzymeHelpers begin + using Quaternionic + import Enzyme + + export enzyme_gradients, enzyme_hessian + + """ + enzyme_gradients(g, x) + + Return the gradients of the real function `g` at the vector `x` computed by Enzyme in + reverse mode (batch width 1) and in forward mode, as two `Vector`s. + """ + function enzyme_gradients(g, x) + reverse = Enzyme.gradient(Enzyme.Reverse, g, x)[1] + forward = Enzyme.gradient(Enzyme.Forward, g, x)[1] + collect(reverse), collect(forward) + end + + """ + enzyme_hessian(g, x; runtime_activity=false) + + Return the Hessian of the real function `g` at `x`, computed by Enzyme in forward mode + over reverse mode. + """ + function enzyme_hessian(g, x; runtime_activity=false) + fwd = runtime_activity ? Enzyme.set_runtime_activity(Enzyme.Forward) : Enzyme.Forward + rev = runtime_activity ? Enzyme.set_runtime_activity(Enzyme.Reverse) : Enzyme.Reverse + Enzyme.jacobian(fwd, y -> Enzyme.gradient(rev, g, y)[1], x)[1] + end +end + + +@testitem "Enzyme: onehot and quaternion arguments" tags=[:ad, :enzyme] setup=[ADTestUtils] begin + import Enzyme + using .ADTestUtils + + # A loss that involves every component, the product with a constant, and `absvec`, which + # has a rule in the extension. + f(q) = sc(q * P0) + absvec(q) + x = point(:generic) + for (name, make) in (("Quaternion", Q), ("Rotor", Ru), ("QuatVec", V)) + q = make(x) + ref = bigfd(y -> f(make(y)), x) + # `V` ignores `x[1]`, and the tangents of a `QuatVec` are its three vector components. + expected = q isa QuatVec ? ref[2:4] : ref + n = length(expected) + + # The tangents are unit quaternions of the argument's own type. + tangents = Enzyme.onehot(q) + @test length(tangents) == n + @test all(t -> typeof(t) === typeof(q), tangents) + @test [collect(q isa QuatVec ? vec(t) : components(t)) for t in tangents] == + [Float64.(1:n .== i) for i in 1:n] + + # Forward mode, unchunked and in chunks of 1 and 3. + for chunk in (nothing, Val(1), Val(3)) + g = Enzyme.gradient(Enzyme.Forward, f, q; chunk=chunk)[1] + @test g isa Tuple + @test length(g) == n + @test relerr(collect(g), expected) < 1e-14 + end + + # Reverse mode returns a shadow of the argument's own type, holding the raw gradient + # components; for a `Rotor` it is not normalized. + gr = Enzyme.gradient(Enzyme.Reverse, f, q)[1] + @test typeof(gr) === typeof(q) + @test relerr(collect(q isa QuatVec ? vec(gr) : components(gr)), expected) < 1e-14 + end +end + + +@testitem "Enzyme: quaternion algebra" tags=[:ad, :enzyme] setup=[ADTestUtils, EnzymeHelpers] begin + using .ADTestUtils, .EnzymeHelpers + t = 2.5 + cases = [ + ("Q * P0", x -> Q(x) * P0, :all), + ("P0 * Q", x -> P0 * Q(x), :all), + ("Q / P0", x -> Q(x) / P0, :all), + ("P0 / Q", x -> P0 / Q(x), :all), + ("Q \\ P0", x -> Q(x) \ P0, :all), + ("inv(Q)", x -> inv(Q(x)), :all), + ("conj(Q)", x -> conj(Q(x)), :all), + ("-Q", x -> -Q(x), :all), + ("Q + P0", x -> Q(x) + P0, :all), + ("P0 - Q", x -> P0 - Q(x), :all), + ("t * Q", x -> t * Q(x), :all), + ("Q / t", x -> Q(x) / t, :all), + ("x[1] * Q", x -> x[1] * Q(x), :all), + ("t / Q", x -> t / Q(x), :all), + ("abs(Q)", x -> abs(Q(x)), :all), + ("abs2(Q)", x -> abs2(Q(x)), :all), + ("absvec(Q)", x -> absvec(Q(x)), :nonreal), + ("abs2vec(Q)", x -> abs2vec(Q(x)), :all), + ("normalize(Q)", x -> normalize(Q(x)), :all), + ("Q ⋅ P0", x -> Q(x) ⋅ P0, :all), + ("V * V0", x -> V(x) * V0, :nonreal), + ("V × V0", x -> V(x) × V0, :nonreal), + ("abs(V)", x -> abs(V(x)), :nonreal), + ("V^2", x -> V(x)^2, :all), + ] + for (name, f, kind) in cases, (pointname, x) in points(kind) + g = y -> sc(f(y)) + ref = bigfd(g, x) + reverse, forward = enzyme_gradients(g, x) + @testset "$name at $pointname" begin + @test relerr(reverse, ref) < 1e-13 + @test relerr(forward, ref) < 1e-13 + end + end + + # At a zero result, the rules for `abs` and `absvec` give a zero gradient, as Enzyme's + # own rules for `hypot` do (the derivative does not exist there). + for (name, g, x) in (("abs(Q) at zero", x -> abs(Q(x)), zeros(4)), + ("absvec(Q) at the identity", x -> absvec(Q(x)), [1.0, 0.0, 0.0, 0.0]), + ("abs(V) at zero", x -> abs(V(x)), [0.7, 0.0, 0.0, 0.0])) + reverse, forward = enzyme_gradients(g, x) + @testset "$name" begin + @test reverse == zeros(4) + @test forward == zeros(4) + end + end +end + + +@testitem "Enzyme: n-ary operations, constants, structure, and broadcasting" tags=[:ad, :enzyme] setup=[ADTestUtils, EnzymeHelpers] begin + using .ADTestUtils, .EnzymeHelpers + cases = [ + ("muladd", x -> muladd(Q(x), P0, x[2]), :all), + ("t*t*t*t*q", x -> x[1] * x[2] * x[3] * x[4] * P0, :all), + ("t*t*t*q*p", x -> x[1] * x[2] * x[3] * Q(x) * P0, :all), + ("q*p*q*p", x -> Q(x) * P0 * Q(x) * P0, :all), + ("t+2t+3t+q", x -> x[1] + 2x[2] + 3x[3] + Q(x), :all), + ("t+q+p+t", x -> (x[1] + Q(x) + P0 + x[4]) * P0, :all), + ("fastmath", x -> @fastmath(x[1] * Q(x) + x[2]), :all), + ("fastmath division", x -> @fastmath(Q(x) / P0 - x[2] / Q(x)), :all), + ("exp(θ𝐣)", x -> exp(x[1] * 𝐣 + x[2] * 𝐤), :all), + ("θ+𝐣", x -> (x[1] + 𝐣) * Q(x), :all), + ("θ-2𝐤", x -> x[1] - 2𝐤, :all), + ("q*𝐢", x -> Q(x) * 𝐢 + 𝐤 * Q(x), :all), + ("imag", x -> imag(Q(x) * P0), :all), + ("vec", x -> vec(Q(x) * P0), :all), + ("components", x -> components(R(x) * P0), :all), + ("getindex", x -> (Q(x) * P0)[2] - 3 * (Q(x) * P0)[4], :all), + ("to_float_array(q)", x -> to_float_array(Q(x) * P0), :all), + ("to_float_array(qs)", x -> to_float_array([Q(x), P0 * Q(x)]), :all), + ("quaternion(vector)", x -> quaternion(x) * P0, :all), + ("rotor(vector)", x -> rotor(x) * P0, :all), + ("qs .* ts", x -> [Q(x), P0] .* [x[2], 2.0], :all), + ("t .* qs", x -> x[1] .* [Q(x), P0], :all), + ("t * qs", x -> x[1] * [Q(x), P0], :all), + ("qs / t", x -> [Q(x), P0] / x[1], :nonzeroscalar), + ("qs ./ q", x -> [P0, Q(x)] ./ Q(x), :all), + ("qs .^ 2", x -> [Q(x), P0] .^ 2, :all), + ("qs .^ -1", x -> [Q(x), P0] .^ -1, :all), + ("abs2.(qs)", x -> sum(abs2.([Q(x), P0])), :all), + ("conj.(qs)", x -> conj.([Q(x), P0 * Q(x)]), :all), + ("sum", x -> sum([Q(x), P0 * Q(x)]), :all), + ("prod", x -> prod([Q(x), P0, Q(x)]), :all), + ("map", x -> map(q -> q * P0, [Q(x), R(x)]), :all), + ] + for (name, f, kind) in cases + pts = kind === :nonzeroscalar ? points(exclude=(:purevector,)) : points(kind) + for (pointname, x) in pts + g = y -> sc(f(y)) + ref = bigfd(g, x) + reverse, forward = enzyme_gradients(g, x) + @testset "$name at $pointname" begin + @test relerr(reverse, ref) < 1e-13 + @test relerr(forward, ref) < 1e-13 + end + end + end +end + + +@testitem "Enzyme: elementary functions and powers" tags=[:ad, :enzyme] setup=[ADTestUtils, EnzymeHelpers] begin + using .ADTestUtils, .EnzymeHelpers + cases = [ + ("exp(Q)", x -> exp(Q(x)), :all), + ("log(Q)", x -> log(Q(x)), :nocut), + ("sqrt(Q)", x -> sqrt(Q(x)), :nocut), + ("Q^0.3", x -> Q(x)^0.3, :nocut), + ("Q^P0", x -> Q(x)^P0, :nocut), + ("Q^t", x -> Q(x)^(x[2] + 0.5), :nocut), + ("2^Q", x -> 2.0^Q(x), :all), + ("R0^Q", x -> R0^Q(x), :all), + ("exp(V)", x -> exp(V(x)), :all), + ("sqrt(V)", x -> sqrt(V(x)), :nonreal), + [("Q^$n", x -> Q(x)^n, :all) for n in -3:3]..., + ] + for (name, f, kind) in cases, (pointname, x) in points(kind) + g = y -> sc(f(y)) + ref = bigfd(g, x) + reverse, forward = enzyme_gradients(g, x) + # Near -1, the derivatives of `log`, `sqrt`, and non-integer powers are large, and + # the error grows with them. + tol = pointname === :nearminus1 ? 1e-9 : 1e-13 + @testset "$name at $pointname" begin + @test relerr(reverse, ref) < tol + @test relerr(forward, ref) < tol + end + end +end + + +@testitem "Enzyme: rotors" tags=[:ad, :enzyme] setup=[ADTestUtils, EnzymeHelpers] begin + using .ADTestUtils, .EnzymeHelpers + cases = [ + ("R", x -> R(x), :all), + ("R * R0", x -> R(x) * R0, :all), + ("R0 / R", x -> R0 / R(x), :all), + ("R / R0", x -> R(x) / R0, :all), + ("conj(R)", x -> conj(R(x)), :all), + ("R(V0)", x -> R(x)(V0), :all), + ("log(R)", x -> log(R(x)), :nocut), + ("sqrt(R)", x -> sqrt(R(x)), :nocut), + ("R^0.3", x -> R(x)^0.3, :nocut), + ("R^-2", x -> R(x)^-2, :all), + ("angle(R)", x -> angle(R(x)), :nonreal), + ("distance2(R, R0)", x -> distance2(R(x), R0), :all), + ("distance(R, R0)", x -> distance(R(x), R0), :all), + ("slerp(R0, R, 0.3)", x -> slerp(R0, R(x), 0.3), :nocut), + ("slerp(R, R0, 0.3)", x -> slerp(R(x), R0, 0.3), :nocut), + ("slerp(R0, R, τ)", x -> slerp(R0, R(x), x[1]), :nocut), + ("slerp(R, R, 0.3)", x -> slerp(R(x), R(x), 0.3), :all), + ("R^3", x -> R(x)^3, :all), + ("distance2(Q, P0)", x -> distance2(Q(x), P0), :all), + ("R0(V)", x -> R0(V(x)), :all), + ("R * V0 * conj(R)", x -> R(x) * V0 * conj(R(x)), :all), + ("to_rotation_matrix(R)", x -> to_rotation_matrix(R(x)), :all), + # Rotors off the unit sphere, whose components are stored without normalization + ("Ru * R0", x -> Ru(x) * R0, :offsphere), + ("Ru / R0", x -> Ru(x) / R0, :offsphere), + ("log(Ru)", x -> log(Ru(x)), :offsphere), + ("Ru^0.3", x -> Ru(x)^0.3, :offsphere), + ("sqrt(Ru)", x -> sqrt(Ru(x)), :offsphere), + ("Ru^2", x -> Ru(x)^2, :offsphere), + ("Ru^-1", x -> Ru(x)^-1, :offsphere), + ("Ru * Ru", x -> Ru(x) * Ru(x), :offsphere), + ("V0 / Ru", x -> V0 / Ru(x), :offsphere), + ("absvec(Ru)", x -> absvec(Ru(x)), :offsphere), + ] + for (name, f, kind) in cases, (pointname, x) in points(kind) + g = y -> sc(f(y)) + ref = bigfd(g, x) + reverse, forward = enzyme_gradients(g, x) + tol = pointname === :nearminus1 ? 1e-9 : 1e-13 + @testset "$name at $pointname" begin + @test relerr(reverse, ref) < tol + @test relerr(forward, ref) < tol + end + end +end + + +@testitem "Enzyme: Lorentz rotors and complex components" tags=[:ad, :enzyme] setup=[ADTestUtils, EnzymeHelpers] begin + using .ADTestUtils, .EnzymeHelpers + L0 = L([0.4, 0.2, -0.3, 0.5]) + B = Boost(0.2, NHAT) + # `C(x)` is a quaternion with complex components built from the four entries of a point. + C(x) = QC(vcat(x, [x[2] / 3, -x[3] / 2, x[4] / 5 + 0.2, x[1] / 4 - 0.1])) + # At `:minus1`, both `L(x)` and `C(x)` have negative real eigenvalues (as complex 2×2 + # matrices), so they lie on the branch cut of `log` and `sqrt`. + nocut = (:minus1,) + cases = [ + ("L * L0", x -> L(x) * L0, ()), + ("L0 * L", x -> L0 * L(x), ()), + ("L * R0", x -> L(x) * R0, ()), + ("L / B", x -> L(x) / B, ()), + ("L * L", x -> L(x) * L(x), ()), + ("L^2 + L^-1 + L^3", x -> L(x)^2 + L(x)^-1 + L(x)^3, ()), + ("conj(L)", x -> conj(L(x)), ()), + ("inv(L)", x -> inv(L(x)), ()), + ("L(V0)", x -> L(x)(V0), ()), + ("L(vector)", x -> sum(L(x)([1.0, 0.2, -0.3, 0.5])), ()), + ("log(L)", x -> log(L(x)), nocut), + ("sqrt(L)", x -> sqrt(L(x)), nocut), + ("abs(quaternion(L))", x -> abs(quaternion(L(x))), ()), + ("C * P0 + P0 * C", x -> C(x) * P0 + P0 * C(x), ()), + ("C / P0 + P0 / C", x -> C(x) / P0 + P0 / C(x), ()), + ("exp(C)", x -> exp(C(x)), ()), + ("log(C)", x -> log(C(x)), nocut), + ("sqrt(C)", x -> sqrt(C(x)), nocut), + ("C^2", x -> C(x)^2, ()), + ("abs2(C)", x -> abs2(C(x)), ()), + ("(t + 0.5im) * C", x -> (x[2] + 0.5im) * C(x), ()), + ] + for (name, f, exclude) in cases, (pointname, x) in points(:all; exclude=exclude) + g = y -> sc(f(y)) + ref = bigfd(g, x) + reverse, forward = enzyme_gradients(g, x) + tol = pointname === :nearminus1 ? 1e-9 : 1e-13 + @testset "$name at $pointname" begin + @test relerr(reverse, ref) < tol + @test relerr(forward, ref) < tol + end + end + # At `:identity` and `:minus1`, the vector part of `C(x)` above is imaginary, so `exp` + # computes `cos` and `sin` of an imaginary number. Base's `sin`, `cos`, and `exp` of a + # `Complex` take shortcuts when the real or imaginary part is exactly zero, and Enzyme + # differentiates those shortcuts, giving wrong derivatives (scratchpad reproduction + # `upstream/enzyme_5.jl`). The package therefore computes them from real functions + # (`Quaternionic.cexp`, `ccos`, and `csin`), and these cases are regression tests for + # that. `x8` gives a real scalar part, `x8v` a vector part with a negative real square, + # and `x8g` the generator of a boost; `Bp(x)` is a pure boost of rapidity `x[1]`, whose + # non-integer powers reach the same functions. + x8 = [0.7, 0.3, -0.2, 0.4, 0.0, 0.1, 0.05, -0.2] + x8v = [0.7, 0.0, 0.0, 0.0, 0.2, 0.3, -0.2, 0.4] + x8g = vcat(zeros(5), 0.6 .* NHAT) + VC(x) = quatvec(complex(x[2], x[6]), complex(x[3], x[7]), complex(x[4], x[8])) + Bp(x) = Boost(x[1], NHAT) + zerobranches = [ + ("exp(QC), real scalar part", x -> sc(exp(QC(x))), x8), + ("exp(QC), imaginary absvec", x -> sc(exp(QC(x))), x8v), + ("exp of a boost generator", x -> sc(exp(QC(x))), x8g), + ("exp of a boost generator as a QuatVec", x -> sc(exp(VC(x))), x8g), + ("power of a boost", x -> sc(Bp(x)^x[2]), [1.0, 0.3]), + ("large power of a small boost", x -> sc(Bp(x)^x[2]), [0.1, 30.0]), + ("L^s, pure boost", x -> sc(L(x)^0.3) + sc(L(x)^2.7), point(:identity)), + ] + @testset "$name" for (name, g, x) in zerobranches + ref = bigfd(g, x) + reverse, forward = enzyme_gradients(g, x) + @test relerr(reverse, ref) < 1e-13 + @test relerr(forward, ref) < 1e-13 + end +end + + +@testitem "Enzyme: batched reverse mode" tags=[:ad, :enzyme] setup=[ADTestUtils] begin + # Jacobians in reverse mode pull back several cotangents at once. Enzyme's own reverse + # rule for `hypot` with three or more arguments fails at batch widths greater than 1, so + # without the extension's rules for `abs` and `absvec`, every function that builds a + # `Rotor` failed here. + import Enzyme + import DifferentiationInterface as DI + using .ADTestUtils + backend = DI.AutoEnzyme(mode=Enzyme.Reverse, function_annotation=Enzyme.Const) + cases = [ + ("R", x -> R(x), :all), + ("R * R0", x -> R(x) * R0, :all), + ("normalize(Q)", x -> normalize(Q(x)), :all), + ("abs(Q)", x -> abs(Q(x)), :all), + ("abs(Q), absvec(Q)", x -> (abs(Q(x)), absvec(Q(x))), :nonreal), + ("abs(V)", x -> abs(V(x)), :nonreal), + ("absvec(Ru)", x -> absvec(Ru(x)), :offsphere), + ("log(R)", x -> log(R(x)), :nocut), + ("sqrt(Q)", x -> sqrt(Q(x)), :nocut), + ("sqrt(R)", x -> sqrt(R(x)), :nocut), + ("R^0.3", x -> R(x)^0.3, :nocut), + ("slerp(R0, R, 0.3)", x -> slerp(R0, R(x), 0.3), :nocut), + ("L * R0", x -> L(x) * R0, :all), + ] + for (name, f, kind) in cases, (pointname, x) in points(kind) + h = y -> realcoords(f(y)) + ref = bigfd(h, x) + tol = pointname === :nearminus1 ? 1e-9 : 1e-13 + @testset "$name at $pointname" begin + @test relerr(DI.jacobian(h, backend, x), ref) < tol + end + end + + # The same rule, called directly with two cotangents of a scalar result + x = point(:generic) + dx = (zero(x), zero(x)) + Enzyme.autodiff(Enzyme.Reverse, y -> abs(Q(y)), Enzyme.Active, Enzyme.BatchDuplicated(x, dx)) + @test relerr(dx[1], x / abs(Q(x))) < 1e-15 + @test relerr(dx[2], x / abs(Q(x))) < 1e-15 + + # At a zero result, the gradients are zero, as at batch width 1. + for (g, x) in ((y -> abs(Q(y)), zeros(4)), (y -> absvec(Q(y)), [1.0, 0.0, 0.0, 0.0])) + shadows = (zeros(4), zeros(4)) + Enzyme.autodiff(Enzyme.Reverse, g, Enzyme.Active, Enzyme.BatchDuplicated(x, shadows)) + @test shadows[1] == zeros(4) + @test shadows[2] == zeros(4) + @test DI.jacobian(y -> [g(y)], backend, x) == zeros(1, 4) + end +end + + +@testitem "Enzyme: from_rotation_matrix and align" tags=[:ad, :enzyme] setup=[ADTestUtils] begin + import Enzyme + import DifferentiationInterface as DI + using LinearAlgebra: I + using .ADTestUtils + + # Rotation matrices of rotors, at a generic point, at the identity, where the + # Bar-Itzhack matrix has a triply degenerate eigenvalue, and at a pure-vector rotor. + # There, `from_rotation_matrix` chooses the sign of its result by a rule that changes + # under perturbation, so the loss is multiplied by the sign that makes the result agree + # with the input rotor; the derivative of that sign is zero. + function g1(x) + Rx = R(x) + Rf = from_rotation_matrix(to_rotation_matrix(Rx)) + sc(Rf) * sign(Rf ⋅ Rx) + end + # Non-orthogonal matrices + g2(x) = sc(from_rotation_matrix(reshape(x[1:9], 3, 3) + I)) + # `align` of rotated vectors, which needs runtime activity in Enzyme, because its closures + # mix active and constant arrays + vs = [quatvec(1.0, 0.2, -0.3), quatvec(-0.4, 0.9, 0.1), quatvec(0.3, 0.3, 1.0)] + g3(x) = sc(align([R(x)(v) for v in vs], vs)) + g4(x) = sc(align([R(x)(v) for v in vs], vs, [1.0, 0.5, 2.0])) + for (name, g, x, runtime_activity) in ( + ("from_rotation_matrix at generic", g1, point(:generic), false), + ("from_rotation_matrix at identity", g1, point(:identity), false), + ("from_rotation_matrix at purevector", g1, point(:purevector), false), + ("from_rotation_matrix of a non-orthogonal matrix", g2, + 0.1 .* collect(1.0:9.0) .- 0.4, false), + ("align(::Vector{QuatVec})", g3, point(:generic), true), + ("align(::Vector{QuatVec}, w)", g4, point(:generic), true), + ) + ref = bigfd(g, x) + rev = runtime_activity ? Enzyme.set_runtime_activity(Enzyme.Reverse) : Enzyme.Reverse + fwd = runtime_activity ? Enzyme.set_runtime_activity(Enzyme.Forward) : Enzyme.Forward + @testset "$name" begin + @test relerr(Enzyme.gradient(rev, g, x)[1], ref) < 1e-13 + @test relerr(collect(Enzyme.gradient(fwd, g, x)[1]), ref) < 1e-13 + end + end + + # Single precision, through the `Float32` methods of the eigenvector rules + x32 = Float32.(point(:generic)) + ref32 = bigfd(g1, Float64.(x32)) + g32 = Enzyme.gradient(Enzyme.Reverse, g1, x32)[1] + @test eltype(g32) === Float32 + @test relerr(g32, ref32) < 1e-5 + @test relerr(collect(Enzyme.gradient(Enzyme.Forward, g1, x32)[1]), ref32) < 1e-5 + + # Jacobians, which push forward or pull back several tangents at once + h(x) = realcoords(from_rotation_matrix(to_rotation_matrix(R(x)))) + x = point(:generic) + ref = bigfd(h, x) + for mode in (Enzyme.Forward, Enzyme.Reverse) + backend = DI.AutoEnzyme(mode=mode, function_annotation=Enzyme.Const) + @test relerr(DI.jacobian(h, backend, x), ref) < 1e-13 + end +end + + +@testitem "Enzyme: rules for dominant_eigenvector_lapack" tags=[:ad, :enzyme] setup=[ADTestUtils] begin + import Enzyme + using LinearAlgebra: Symmetric, eigen, dot, triu, tril + using .ADTestUtils: relerr + + # The loss of the test with runtime activity below, whose matrix argument is active only + # for `t < 0` + function h(t, B, D, w, uplo) + C = t[1] > 0 ? B : B + t[1] * D + dot(w, Quaternionic.dominant_eigenvector_lapack(C, uplo)) * t[1] + end + + # A symmetric matrix with a simple dominant eigenvalue, stored in both triangles, with + # different (ignored) entries in the other triangle + S = [4.0 0.3 -0.2 0.1; 0.3 1.0 0.5 -0.4; -0.2 0.5 0.7 0.2; 0.1 -0.4 0.2 -1.0] + w = [0.3, -1.1, 0.7, 0.45] + for uplo in ('U', 'L') + A = uplo == 'U' ? triu(S) + tril(fill(9.0, 4, 4), -1) : + tril(S) + triu(fill(9.0, 4, 4), 1) + v₀ = Quaternionic.dominant_eigenvector_lapack(A, uplo) + f = B -> dot(w, Quaternionic.dominant_eigenvector_lapack(B, uplo)) + + # The reference uses the generic eigensolver in `BigFloat`, with the eigenvector's + # sign chosen to agree with `vref` (by default `v₀`). + fbig = (a, vref=v₀) -> begin + E = eigen(Symmetric(reshape(a, 4, 4), Symbol(uplo))) + v = E.vectors[:, argmax(E.values)] + dot(w, dot(v, vref) < 0 ? -v : v) + end + ref = reshape(ADTestUtils.bigfd(fbig, vec(A)), 4, 4) + other = uplo == 'U' ? tril(trues(4, 4), -1) : triu(trues(4, 4), 1) + @test all(iszero, ref[other]) + + Ā = zero(A) + Enzyme.autodiff(Enzyme.Reverse, f, Enzyme.Active, Enzyme.Duplicated(A, Ā)) + @test relerr(Ā, ref) < 1e-13 + @test all(iszero, Ā[other]) + + # Forward mode along one tangent, and along two at once + Ȧ = reshape(collect(1.0:16.0), 4, 4) ./ 10 + ḟ = Enzyme.autodiff(Enzyme.Forward, f, Enzyme.Duplicated(A, Ȧ))[1] + @test ḟ ≈ dot(ref, Ȧ) rtol=1e-13 + ḟs = Enzyme.autodiff(Enzyme.Forward, f, Enzyme.BatchDuplicated(A, (Ȧ, 2Ȧ)))[1] + @test ḟs[1] ≈ dot(ref, Ȧ) rtol=1e-13 + @test ḟs[2] ≈ 2dot(ref, Ȧ) rtol=1e-13 + + # Reverse mode with two cotangents at once + Ās = (zero(A), zero(A)) + Enzyme.autodiff(Enzyme.Reverse, f, Enzyme.Active, Enzyme.BatchDuplicated(A, Ās)) + @test relerr(Ās[1], ref) < 1e-13 + @test relerr(Ās[2], ref) < 1e-13 + + # With runtime activity, Enzyme passes a matrix that is inactive at run time as a + # `Duplicated` whose shadow is the matrix itself. The rules must treat it as + # constant, and in particular must not accumulate a cotangent into it. Here the + # matrix is inactive for `t > 0` and active (through `B + t * D`) for `t < 0`. + D = [0.0 0.2 0.1 -0.3; 0.2 0.5 -0.1 0.0; 0.1 -0.1 0.0 0.4; -0.3 0.0 0.4 -0.2] + A₀ = copy(A) + for t in (0.5, -0.5) + # The sign of the eigenvector is that which LAPACK chooses at `t`. + vt = Quaternionic.dominant_eigenvector_lapack(t > 0 ? A : A + t * D, uplo) + href = ADTestUtils.bigfd(s -> (s > 0 ? fbig(vec(big.(A)), vt) : fbig(vec(A + s * D), vt)) * s, t) + dt = zeros(1) + Enzyme.autodiff(Enzyme.set_runtime_activity(Enzyme.Reverse), h, Enzyme.Active, + Enzyme.Duplicated([t], dt), Enzyme.Const(A), Enzyme.Const(D), + Enzyme.Const(w), Enzyme.Const(uplo)) + @test dt[1] ≈ href rtol=1e-13 + @test A == A₀ + dts = (zeros(1), zeros(1)) + Enzyme.autodiff(Enzyme.set_runtime_activity(Enzyme.Reverse), h, Enzyme.Active, + Enzyme.BatchDuplicated([t], dts), Enzyme.Const(A), Enzyme.Const(D), + Enzyme.Const(w), Enzyme.Const(uplo)) + @test dts[1][1] ≈ href rtol=1e-13 + @test dts[2][1] ≈ href rtol=1e-13 + @test A == A₀ + ḣ = Enzyme.autodiff(Enzyme.set_runtime_activity(Enzyme.Forward), h, + Enzyme.Duplicated([t], [1.0]), Enzyme.Const(A), Enzyme.Const(D), + Enzyme.Const(w), Enzyme.Const(uplo))[1] + @test ḣ ≈ href rtol=1e-13 + @test A == A₀ + end + end +end + + +@testitem "Enzyme: forward-over-reverse Hessians" tags=[:ad, :enzyme] setup=[ADTestUtils, EnzymeHelpers] begin + import ForwardDiff + using .ADTestUtils, .EnzymeHelpers + cases = [ + ("slerp(R0, R, 0.3)", x -> sc(slerp(R0, R(x), 0.3)), :nocut), + ("slerp(R, R, 0.3)", x -> sc(slerp(R(x), R(x), 0.3)), :all), + ("R^0.3", x -> sc(R(x)^0.3), :nocut), + ("exp(Q)", x -> sc(exp(Q(x))), :all), + ("log(Q)", x -> sc(log(Q(x))), :nocut), + ("distance2(R, R0)", x -> distance2(R(x), R0), :all), + ("distance2(R, R * R1)", x -> distance2(R(x), R(x) * rotor(1.0, 1e-3, 0.0, 0.0)), :all), + ("abs(Q)", x -> abs(Q(x)), :all), + ("absvec(Q)", x -> absvec(Q(x)), :nonreal), + ] + for (name, g, kind) in cases, (pointname, x) in points(kind; exclude=(:nearminus1,)) + ref = ForwardDiff.hessian(g, x) + @testset "$name at $pointname" begin + @test relerr(enzyme_hessian(g, x), ref) < 1e-12 + end + end + + # The Hessian of `sqrt` needs runtime activity. + g(x) = sc(sqrt(Q(x))) + for (pointname, x) in points(:nocut; exclude=(:nearminus1,)) + @testset "sqrt(Q) at $pointname" begin + H = enzyme_hessian(g, x; runtime_activity=true) + @test relerr(H, ForwardDiff.hessian(g, x)) < 1e-12 + end + end +end + + +@testitem "Enzyme: squad and unflip at batch width 1" tags=[:ad, :enzyme] setup=[ADTestUtils] begin + # Enzyme's batched reverse mode crashes the compiler on these functions (an upstream + # bug), so reverse mode is tested only through the gradient of a scalar loss. + import Enzyme + using .ADTestUtils + tin = [0.0, 0.7, 1.5, 2.6] + x0 = [1.0, 0.1, -0.2, 0.05, 0.9, 0.3, -0.4, 0.1, 0.6, 0.5, -0.5, 0.2, 0.2, 0.7, -0.6, 0.3] + cases = [ + ("squad", x -> sc(squad([R(x, 1), R(x, 5), R(x, 9), R(x, 13)], tin, x[17])), [x0; 1.1]), + ("unflip(::Vector{Quaternion})", + x -> sc(unflip([Q(x, 1), -Q(x, 5), Q(x, 9), -Q(x, 13)])), x0), + ("unflip(::Vector{Rotor})", + x -> sc(unflip([R(x, 1), -R(x, 5), R(x, 9), -R(x, 13)])), x0), + ] + for (name, g, x) in cases + ref = bigfd(g, x) + @testset "$name" begin + @test relerr(Enzyme.gradient(Enzyme.Reverse, g, x)[1], ref) < 1e-13 + @test relerr(collect(Enzyme.gradient(Enzyme.Forward, g, x)[1]), ref) < 1e-13 + end + end +end diff --git a/test/ad_explog.jl b/test/ad_explog.jl new file mode 100644 index 00000000..568a9583 --- /dev/null +++ b/test/ad_explog.jl @@ -0,0 +1,315 @@ +# Tests of the derivatives of `exp` and `log`, and of powers of a `Rotor`, by every AD +# backend that the package supports, in every mode that the backend has. +# +# Each function is differentiated at a set of points chosen to exercise every branch of the +# source: a generic point, the identity, vector parts of 1e-4, 1e-8, 1e-12, and exactly 0, +# norms of 1e-3 and 1e3, a point near the negative real axis (w < 0 with a vector part of +# 1e-8), and pure vectors. The full Jacobian of the real coordinates of the output, the +# gradient of the scalar loss `sc`, and (where the backend has second derivatives) the +# Hessian of that loss are compared with central finite differences in 256-bit `BigFloat` +# arithmetic (`bigfd` and `bigfdH` from `ADTestUtils`). The errors are measured relative to +# the norm of the reference, with no floor, so that the small derivatives at the point of +# norm 1e3 are checked to their full relative accuracy. + +@testsnippet ExpLogCases begin + using Quaternionic + using Test + using .ADTestUtils: bigfd, bigfdH, sc, realcoords, relerr, Q, R, V + + # Every point has five entries. The first four are the components of the quaternion, + # from which `Q`, `R`, and `V` build their values (`V` ignores the first), and the fifth + # is the exponent of the power of a rotor, which the other functions ignore. + const n̂ = [0.6, -0.48, 0.64] + const EXPLOG_POINTS = [ + "generic" => [1.2, -0.7, 0.5, 0.3, 0.37], + "identity" => [1.0, 0.0, 0.0, 0.0, 0.37], + "vector part 1e-4" => [0.9; 1e-4 * n̂; 0.37], + "vector part 1e-8" => [0.9; 1e-8 * n̂; 0.37], + "vector part 1e-12" => [0.9; 1e-12 * n̂; 0.37], + "vector part 0" => [0.9, 0.0, 0.0, 0.0, 0.37], + "norm 1e-3" => [6e-4, 5e-4, -4e-4, 4.8e-4, 0.37], + "norm 1e3" => [60.0, 600.0, -400.0, 690.0, 0.37], + "near the negative real axis" => [-0.8; 1e-8 * n̂; 0.37], + "pure unit vector" => [0.0; n̂; 0.37], + "pure vector of norm 2" => [0.0; 2n̂; -1.3], + ] + + # The rotor functions take the normalized `R(x)`, because `log` and powers of a `Rotor` + # assume unit norm. + const EXPLOG_CASES = [ + "exp(::Quaternion)" => x -> exp(Q(x)), + "exp(::QuatVec)" => x -> exp(V(x)), + "log(::Quaternion)" => x -> log(Q(x)), + "log(::Rotor)" => x -> log(R(x)), + "Rotor^s" => x -> R(x)^x[5], + ] + + """ + checkexplog(modes; T=Float64, rtol, cases=EXPLOG_CASES, points=EXPLOG_POINTS, broken) + + Check each mode of a backend for each case at each point, with components of type `T`. + Each mode is `label => (kind, d)`, where `kind` is `:jacobian`, `:gradient`, or + `:hessian`, and `d(F, x)` returns the Jacobian of the vector function `F`, the gradient + of the real function `F`, or its Hessian, at `x`. The Jacobian is that of the real + coordinates of the output, and the gradient and Hessian are those of the loss `sc`. The + tolerance `rtol` is a function of `kind` and `T`. The references are computed once for + each case and point, and only for the kinds that are checked. The check of a mode is a + `@test_broken` where `broken(case, point, mode)` is `true`, for the names of the case, + the point, and the mode. + """ + function checkexplog(modes; T=Float64, rtol=defaulttol, cases=EXPLOG_CASES, points=EXPLOG_POINTS, + broken=(c, p, m) -> false) + kinds = unique(first(last(m)) for m in modes) + for (cname, f) in cases + F = x -> realcoords(f(x)) + g = x -> sc(f(x)) + @testset "$cname at $pname" for (pname, x64) in points + x = T.(x64) + refs = Dict( + k => (k === :jacobian ? bigfd(f, x) : k === :gradient ? bigfd(g, x) : bigfdH(g, x)) + for k in kinds + ) + for (label, (kind, d)) in modes + @testset "$label" begin + if broken(cname, pname, label) + @test_broken relerr(d(kind === :jacobian ? F : g, x), refs[kind], 0) < rtol(kind, T) + else + @test relerr(d(kind === :jacobian ? F : g, x), refs[kind], 0) < rtol(kind, T) + end + end + end + end + end + end + + # The tolerances relative to the norm of the reference. Near the negative real axis, + # the derivatives of `log` and the power are of order 1e8 (and the second derivatives + # of order 1e16), and the roundoff in the vector part grows with them. + defaulttol(kind, ::Type{Float64}) = kind === :hessian ? 1e-10 : 1e-12 + defaulttol(kind, ::Type{Float32}) = kind === :hessian ? 1e-3 : 1e-4 +end + + +@testitem "exp and log: ForwardDiff" tags=[:slow, :ad, :forwarddiff] setup=[ADTestUtils, ExpLogCases] begin + import ForwardDiff + modes = [ + "jacobian" => (:jacobian, ForwardDiff.jacobian), + "gradient" => (:gradient, ForwardDiff.gradient), + "hessian" => (:hessian, ForwardDiff.hessian), + "jacobian of gradient" => (:hessian, (g, x) -> ForwardDiff.jacobian(y -> ForwardDiff.gradient(g, y), x)), + ] + checkexplog(modes) + checkexplog(modes[1:2]; T=Float32) +end + + +@testitem "exp and log: ReverseDiff" tags=[:slow, :ad, :reversediff] setup=[ADTestUtils, ExpLogCases] begin + import ReverseDiff + # A tape records the branches taken at the point where it is recorded, so each tape is + # recorded at the point where it is evaluated. + compiledgradient(g, x) = ReverseDiff.gradient!(similar(x), ReverseDiff.compile(ReverseDiff.GradientTape(g, x)), x) + compiledjacobian(F, x) = ReverseDiff.jacobian!(ReverseDiff.compile(ReverseDiff.JacobianTape(F, x)), x) + compiledhessian(g, x) = ReverseDiff.hessian!(ReverseDiff.compile(ReverseDiff.HessianTape(g, x)), x) + modes = [ + "jacobian" => (:jacobian, ReverseDiff.jacobian), + "gradient" => (:gradient, ReverseDiff.gradient), + "hessian" => (:hessian, ReverseDiff.hessian), + "compiled jacobian tape" => (:jacobian, compiledjacobian), + "compiled gradient tape" => (:gradient, compiledgradient), + "compiled hessian tape" => (:hessian, compiledhessian), + ] + checkexplog(modes) + checkexplog(modes[1:2]; T=Float32) +end + + +@testitem "exp and log: Zygote" tags=[:slow, :ad, :zygote] setup=[ADTestUtils, ExpLogCases] begin + import Zygote + modes = [ + "jacobian" => (:jacobian, (F, x) -> Zygote.jacobian(F, x)[1]), + "gradient" => (:gradient, (g, x) -> Zygote.gradient(g, x)[1]), + "hessian (forward over reverse)" => (:hessian, Zygote.hessian), + ] + checkexplog(modes) + checkexplog(modes[1:2]; T=Float32) +end + + +@testitem "exp and log: ChainRules rules" tags=[:slow, :ad, :chainrules] setup=[ADTestUtils, ExpLogCases] begin + using ChainRulesCore: frule, rrule, NoTangent, unthunk + using ChainRulesTestUtils: test_frule, test_rrule + using LinearAlgebra: I + import Random + + # The functions with rules, applied to their primal arguments, which are built from a + # point by `args`. A `Rotor` argument is normalized, and its tangents are `Quaternion`s. + rules = [ + ("exp(::Quaternion)", exp, x -> (Q(x),)), + ("exp(::QuatVec)", exp, x -> (V(x),)), + ("log(::Quaternion)", log, x -> (Q(x),)), + ("log(::Rotor)", log, x -> (R(x),)), + ("Rotor^s", ^, x -> (R(x), x[5])), + ] + + # The coordinates of an argument, from which the references rebuild it, and the basis + # of its tangents + coordsof(a::QuatVec) = collect(vec(a)) + coordsof(a::AbstractQuaternion) = collect(components(a)) + coordsof(a::Real) = [a] + basis(a::QuatVec) = [quatvec((1:3 .== k)...) for k in 1:3] + basis(a::AbstractQuaternion) = [quaternion((1:4 .== k)...) for k in 1:4] + basis(a::Real) = [one(a)] + zerotangent(a::QuatVec) = zero(a) + zerotangent(a::AbstractQuaternion) = zero(quaternion(a)) + zerotangent(a::Real) = zero(a) + # Rebuild an argument of the type of `a` from coordinates. A `Rotor` is rebuilt with + # `rotor`, which normalizes, so that the reference is the derivative along the unit + # sphere. The pushforward of a rotor tangent is compared after projection onto the + # sphere, as `projector` below gives it. + rebuild(a::QuatVec, c) = quatvec(c...) + rebuild(a::Rotor, c) = rotor(c...) + rebuild(a::Quaternion, c) = quaternion(c...) + rebuild(a::Real, c) = c[1] + projector(a::Rotor) = I - collect(components(a)) * collect(components(a))' + projector(a) = I + + @testset "$name at $pname" for (name, f, args) in rules, (pname, x) in EXPLOG_POINTS + a = args(x) + y = f(a...) + # The reference Jacobian with respect to each argument, and its projection + Js = map(eachindex(a)) do i + c = coordsof(a[i]) + J = bigfd(cᵢ -> f(Base.setindex(a, rebuild(a[i], cᵢ), i)...), c) + J = J isa AbstractVector ? reshape(J, :, 1) : J + J * projector(a[i]) + end + # The pushforwards of the basis tangents of each argument + for i in eachindex(a) + columns = map(basis(a[i])) do ȧ + ȧs = ntuple(j -> j == i ? ȧ : zerotangent(a[j]), length(a)) + Ω, Ω̇ = frule((NoTangent(), ȧs...), f, a...) + @test Ω == y + Ω̇ = unthunk(Ω̇) + realcoords(y isa QuatVec ? quatvec(Ω̇) : quaternion(Ω̇)) + end + @test relerr(reduce(hcat, columns) * projector(a[i]), Js[i], 0) < 1e-12 + end + # The pullbacks of the basis cotangents of the output + Ω, pullback = rrule(f, a...) + @test Ω == y + ȳs = y isa QuatVec ? basis(y) : basis(quaternion(y)) + for i in eachindex(a) + rows = map(ȳs) do ȳ + ∂ = unthunk(pullback(ȳ)[i+1]) + c = a[i] isa QuatVec ? collect(vec(∂)) : a[i] isa Real ? [∂] : collect(components(∂)) + permutedims(c) + end + @test relerr(reduce(vcat, rows) * projector(a[i]), Js[i], 0) < 1e-12 + end + end + + # ChainRulesTestUtils, except where its Float64 finite differences are not accurate + # enough: near the negative real axis, where they straddle the branch cut; at the norm + # 1e-3, where the derivatives of `log` are of order 1e4 and the errors of the finite + # differences exceed the tolerance; and at w = 0 for a `Rotor`, where they straddle the + # branches of `log` and powers of an unnormalized `Rotor`. + @testset "ChainRulesTestUtils for $name at $pname" for (name, f, args) in rules, (pname, x) in EXPLOG_POINTS + pname ∈ ("near the negative real axis", "norm 1e-3") && continue + a = args(x) + a[1] isa Rotor && iszero(a[1][1]) && continue + # ChainRulesTestUtils draws its random tangents from the global generator, which is + # reseeded so that each check is reproducible on its own. + Random.seed!(20261002) + test_frule(f, a...; rtol=1e-8, atol=1e-8) + test_rrule(f, a...; rtol=1e-8, atol=1e-8) + end +end + + +@testitem "exp and log: Enzyme" tags=[:slow, :ad, :enzyme] setup=[ADTestUtils, ExpLogCases, EnzymeHelpers] begin + import Enzyme + modes = [ + "forward jacobian" => (:jacobian, (F, x) -> Enzyme.jacobian(Enzyme.Forward, F, x)[1]), + "reverse jacobian" => (:jacobian, (F, x) -> Enzyme.jacobian(Enzyme.Reverse, F, x)[1]), + "forward gradient" => (:gradient, (g, x) -> collect(Enzyme.gradient(Enzyme.Forward, g, x)[1])), + "reverse gradient" => (:gradient, (g, x) -> Enzyme.gradient(Enzyme.Reverse, g, x)[1]), + "forward over reverse hessian" => (:hessian, (g, x) -> enzyme_hessian(g, x)), + ] + checkexplog(modes) + checkexplog(modes[3:4]; T=Float32) +end + + +@testitem "exp and log: Mooncake" tags=[:slow, :ad, :mooncake] setup=[ADTestUtils, ExpLogCases] begin + import Mooncake + import DifferentiationInterface as DI + reverse, forward = DI.AutoMooncake(config=nothing), DI.AutoMooncakeForward(config=nothing) + fwdoverrev = DI.SecondOrder(forward, reverse) + # Mooncake builds its rules for the types of the arguments, not their values, so one + # preparation for each function, operator, backend, and element type serves every point. + preps = IdDict() + function prepared(op, prepare, backend) + (f, x) -> op(f, get!(() -> prepare(f, backend, x), preps, (f, op, backend, eltype(x))), backend, x) + end + modes = [ + "reverse jacobian" => (:jacobian, prepared(DI.jacobian, DI.prepare_jacobian, reverse)), + "forward jacobian" => (:jacobian, prepared(DI.jacobian, DI.prepare_jacobian, forward)), + "reverse gradient" => (:gradient, prepared(DI.gradient, DI.prepare_gradient, reverse)), + "forward gradient" => (:gradient, prepared(DI.gradient, DI.prepare_gradient, forward)), + "forward over reverse hessian" => (:hessian, prepared(DI.hessian, DI.prepare_hessian, fwdoverrev)), + ] + # Mooncake 0.5.60 has two bugs in forward mode over reverse mode, both reproduced in + # `mooncake_fwd_over_rev_zero.jl` in the upstream reports. First, the Hessian of a + # product with a factor that is exactly zero, such as x[2] * exp(x[1]) at x[2] = 0, is + # wrong, which affects `log` at a zero vector part. Second, the Hessian of + # `atan(y, x)` at x = 0 throws an `ArgumentError` about `bitcast`, which affects `log` and + # powers of pure vectors. + zerovector = ("identity", "vector part 0") + purevector = ("pure unit vector", "pure vector of norm 2") + function broken(case, point, mode) + mode == "forward over reverse hessian" || return false + startswith(case, "log") && point ∈ (zerovector..., purevector...) || + case == "Rotor^s" && point ∈ purevector + end + # Every Mooncake rule is compiled for each function and mode, which dominates the time + # of this item, so the gradients (which the Jacobians already check) are computed only + # with `Float32` components. + checkexplog(modes[[1, 2, 5]]; broken=broken) + checkexplog(modes[3:4]; T=Float32) +end + + +@testitem "exp and log: Symbolics and FastDifferentiation" tags=[:slow, :ad] setup=[ADTestUtils, ExpLogCases] begin + import Symbolics + import FastDifferentiation + + # Symbolic components cannot be compared with thresholds, so `exp`, `log`, and powers of + # a `Rotor` return their general formulas, which have removable singularities at a zero + # vector part. Their derivatives are evaluated at points whose vector parts are not + # small. The symbolic normalization of `R(x)` makes the expressions for the power so + # large that their Jacobian takes a minute to compute, so the power is taken of the + # unnormalized `Ru(x)`, at points normalized beforehand. (The general formula for the + # power, like the source away from the identity, does not depend on the norm.) + using .ADTestUtils: Ru + using LinearAlgebra: normalize + Symbolics.@variables w x y z s + vars = [w, x, y, z, s] + numeric = ["generic", "norm 1e3", "pure unit vector", "pure vector of norm 2"] + cases = [EXPLOG_CASES[1:4]; "Rotor^s" => (x -> Ru(x)^x[5])] + for (cname, f) in cases + J = Symbolics.jacobian(realcoords(f(vars)), vars) + Jf = Symbolics.build_function(J, vars; expression=Val(false))[1] + @testset "Symbolics: $cname at $pname" for (pname, p) in EXPLOG_POINTS + pname ∈ numeric || continue + p = cname == "Rotor^s" ? [normalize(p[1:4]); p[5]] : p + @test relerr(Jf(p), bigfd(f, p), 0) < 1e-12 + end + end + + # FastDifferentiation cannot follow the branches of `exp`, `log`, and powers, so they + # raise explanatory errors. + u = FastDifferentiation.make_variables(:u, 5) + for (cname, f) in EXPLOG_CASES + @test_throws ErrorException f(u) + end +end diff --git a/test/ad_forwarddiff.jl b/test/ad_forwarddiff.jl new file mode 100644 index 00000000..f75a93d0 --- /dev/null +++ b/test/ad_forwarddiff.jl @@ -0,0 +1,455 @@ +# Tests of `QuaternionicForwardDiffExt`, which extracts values and derivatives from +# quaternion-valued results of ForwardDiff and of DifferentiationInterface's +# `AutoForwardDiff`, and of the derivatives that ForwardDiff computes natively through the +# package's source. Every reference value is a central finite difference evaluated with +# 256-bit `BigFloat`s, or a function whose derivatives are known to be correct. + +@testmodule ForwardDiffTestUtils begin + using Quaternionic + using ForwardDiff + + """ + flat(y) + + Return the real numbers stored in `y` as a vector, with complex numbers split into their + real and imaginary parts. `y` may be a real or complex number, a quaternion, or an + array of these. + """ + flat(y::Real) = [float(y)] + flat(y::Complex) = [float(real(y)), float(imag(y))] + flat(y::AbstractQuaternion) = reduce(vcat, map(flat, Tuple(components(y)))) + flat(y::AbstractArray) = reduce(vcat, map(flat, y)) + + const weights = (1.0, -0.7, 0.4, 1.3, 0.9, -1.1, 0.6, -0.3) + + """ + sc(y) + + Return a fixed weighted sum of the real numbers in `flat(y)`, which turns a quaternion + result (with real or complex components) into a scalar loss whose derivatives involve + every component. + """ + function sc(y) + c = flat(y) + sum(weights[i] * c[i] for i ∈ eachindex(c)) + end + + """ + bigfd(f, x, n=1) + + Return the `n`th derivative of `f` at the real number `x`, for `n` from 1 to 3, as a + vector of `BigFloat`s that is laid out as `flat(f(x))`. It is computed by a central + finite difference with 256-bit precision, whose truncation and rounding errors are both + far below the precision of `Float64`. + """ + function bigfd(f, x::Real, n::Integer=1) + setprecision(BigFloat, 256) do + X = BigFloat(x) + F(t) = flat(f(t)) + if n == 1 + h = big"1e-25" + (F(X + h) - F(X - h)) / 2h + elseif n == 2 + h = big"1e-18" + (F(X + h) - 2F(X) + F(X - h)) / h^2 + elseif n == 3 + h = big"1e-14" + (F(X + 2h) - 2F(X + h) + 2F(X - h) - F(X - 2h)) / (2h^3) + else + throw(ArgumentError("Only derivatives of orders 1 through 3 are implemented")) + end + end + end + + """ + bigfdH(f, x) + + Return the Hessian of the scalar function `f` at the real vector `x`, computed by + central finite differences with 256-bit precision. + """ + function bigfdH(f, x::AbstractVector) + setprecision(BigFloat, 256) do + X = BigFloat.(x) + h = big"1e-18" + n = length(X) + e(i) = [j == i ? h : zero(h) for j ∈ 1:n] + [ + (f(X + e(i) + e(j)) - f(X + e(i) - e(j)) + - f(X - e(i) + e(j)) + f(X - e(i) - e(j))) / 4h^2 + for i ∈ 1:n, j ∈ 1:n + ] + end + end + + """ + relerr(a, b) + + Return the largest absolute difference between the entries of `a` and `b`, relative to + the largest entry of `b` or to 1, whichever is larger, as a `Float64`. + """ + relerr(a, b) = Float64(maximum(abs, flat(a) - flat(b)) / max(1, maximum(abs, flat(b)))) + + """ + nth_derivative(f, n, t) + + Return the `n`th derivative of `f` at `t`, computed by nesting `n` calls to + `ForwardDiff.derivative`. + """ + function nth_derivative(f, n, t) + n == 0 ? f(t) : ForwardDiff.derivative(τ -> nth_derivative(f, n - 1, τ), t) + end + + """ + hemisphere_sign(R) + + Return the sign, ±1, of the first nonzero component of `R`, which is the sign by which + `from_rotation_matrix(to_rotation_matrix(R))` differs from `R` itself. + """ + function hemisphere_sign(R) + c = first(filter(!iszero, collect(components(R)))) + c < 0 ? -1 : 1 + end +end + +@testitem "ForwardDiff: derivatives of quaternion outputs" tags=[:ad, :forwarddiff] setup=[ForwardDiffTestUtils] begin + using ForwardDiff + using .ForwardDiffTestUtils: bigfd, relerr + + n̂ = normalize(quatvec(1.0, -2.0, 3.0)) + R₀ = Rotor{Float64}(0.9, 0.3, -0.4, 0.2) # This rotor is deliberately not normalized. + + # Each case is a function of a real number, the type of its derivative, and the point. + cases = [ + (t -> Quaternion(sin(t), t^2, exp(t), 1/t), QuaternionF64, 0.7), + (t -> exp(Quaternion(0.3t, t^2, -t, 0.5)), QuaternionF64, 0.4), + # A `Rotor` output has a `Quaternion` derivative. The non-normalizing constructor + # keeps this one off the unit sphere. + (t -> Rotor{typeof(t)}(t*R₀[1], R₀[2]*t^2, R₀[3], R₀[4]+t), QuaternionF64, 0.5), + (t -> exp(t * n̂ / 2), QuaternionF64, 0.3), + (t -> rotor(1.0, t, -t^2, 0.5), QuaternionF64, 0.6), + # A `QuatVec` output has a `QuatVec` derivative. + (t -> t * quatvec(1.0, 2.0, 3.0), QuatVecF64, 0.3), + (t -> log(exp(t * n̂ / 2)), QuatVecF64, 0.8), + (t -> quatvec(sin(t), cos(t), t^3), QuatVecF64, 1.1), + # Complex components, as in `Lorentz` rotors, have complex derivatives. + (t -> Boost(t, n̂), Quaternion{ComplexF64}, 0.3), + (t -> Boost(t, n̂), Quaternion{ComplexF64}, 0.0), + (t -> Boost(t * n̂), Quaternion{ComplexF64}, 0.4), + (t -> Boost(t, n̂) * exp(t * imz / 3), Quaternion{ComplexF64}, 0.25), + (t -> Quaternion(complex(t, t^2), 1, im*t, 0), Quaternion{ComplexF64}, 0.5), + ] + for (f, D, t) ∈ cases + d = ForwardDiff.derivative(f, t) + @test d isa D + @test relerr(d, bigfd(f, t)) < 1e-14 + # None of these derivatives is zero; before version 4.4.5, those of results with + # complex components were. + @test !iszero(d) + end + + # Constant outputs have zero derivatives, whose types follow the same rules. + for (y, D) ∈ ( + (Quaternion(1.0, 2.0, 3.0, 4.0), QuaternionF64), + (rotor(1.0, 2.0, 3.0, 4.0), QuaternionF64), + (quatvec(2.0, 3.0, 4.0), QuatVecF64), + (Boost(0.4, n̂), Quaternion{ComplexF64}), + ) + d = ForwardDiff.derivative(t -> y, 0.3) + @test d isa D + @test iszero(d) + end + @test iszero(ForwardDiff.derivative(t -> imx, 0.3)) + + # This complex result is built directly from complex arithmetic. + f = t -> Lorentz{typeof(t)}(exp(im * t), 0, 0, im * sin(t)) + @test ForwardDiff.derivative(f, 0.2) isa Quaternion{ComplexF64} + @test components(ForwardDiff.derivative(f, 0.2)) ≈ [im * exp(0.2im), 0, 0, im * cos(0.2)] + + # Quaternion arguments are not differentiable by ForwardDiff; inputs must be real. + @test !ForwardDiff.can_dual(QuaternionF64) + @test !ForwardDiff.can_dual(RotorF64) +end + +@testitem "ForwardDiff: nested derivatives of quaternion outputs" tags=[:ad, :forwarddiff] setup=[ForwardDiffTestUtils] begin + using ForwardDiff + using .ForwardDiffTestUtils: bigfd, relerr, nth_derivative + + n̂ = normalize(quatvec(1.0, -2.0, 3.0)) + R₀ = rotor(0.4, -0.2, 0.7, 0.5) + cases = [ + (t -> exp(Quaternion(0.3t, t^2, -t, 0.5)), QuaternionF64, 0.4), + (t -> Rotor{typeof(t)}(t^3, sin(t), 1, t), QuaternionF64, 0.5), + (t -> slerp(R₀, exp(t * n̂ / 2) * R₀, 0.3), QuaternionF64, 0.2), + (t -> exp(t * n̂ / 2)^2.5, QuaternionF64, 0.7), + (t -> log(exp(t * n̂ / 2)), QuatVecF64, 0.8), + (t -> quatvec(sin(t), cos(t), t^3), QuatVecF64, 1.1), + (t -> Boost(t, n̂), Quaternion{ComplexF64}, 0.3), + (t -> Boost(t * n̂), Quaternion{ComplexF64}, 0.4), + ] + for (f, D, t) ∈ cases, n ∈ 2:3 + d = nth_derivative(f, n, t) + @test d isa D + @test relerr(d, bigfd(f, t, n)) < 1e-12 + end + + # The inner derivative of a nested call has dual components of the outer tag, and the + # outer derivative must extract them without confusing the two tags. Here, the inner + # derivative is (1, x, 0, 0), so the outer function is x ↦ x * (1, x, 0, 0). + g = x -> x * ForwardDiff.derivative(y -> Quaternion(x + y, x * y, 0, 0), 1.0) + @test ForwardDiff.derivative(g, 1.5) isa QuaternionF64 + @test components(ForwardDiff.derivative(g, 1.5)) == [1.0, 3.0, 0.0, 0.0] + # An inner function that does not depend on its own argument has zero inner derivative, + # even though its components are duals of the outer tag. + h = x -> ForwardDiff.derivative(y -> Quaternion(x, x^2, 0, 0), 1.0) + @test iszero(h(2.0)) + @test iszero(ForwardDiff.derivative(h, 2.0)) + # The same holds with complex components. + b = x -> x * ForwardDiff.derivative(y -> Boost(x * y, n̂), 0.0) + @test relerr(ForwardDiff.derivative(b, 0.7), bigfd(b, 0.7)) < 1e-14 +end + +@testitem "ForwardDiff: value and partials with a tag" tags=[:ad, :forwarddiff] begin + using ForwardDiff + using ForwardDiff: Dual, Tag + + # ForwardDiff orders tags by the time of their creation, so `TI` is the newer one, and + # it may be the tag of the outer layer of a nested dual whose inner layer has tag `TO`. + outerfunction = x -> x + innerfunction = x -> 2x + TO = typeof(Tag(outerfunction, Float64)) + TI = typeof(Tag(innerfunction, Float64)) + d(v, ps...) = Dual{TO}(v, ps...) + + # A `Rotor` keeps its type, and its components are not normalized. + R = Rotor{Dual{TO,Float64,2}}(d(2.0, 1.0, 0.0), d(0.0, 0.0, 1.0), d(1.0, 2.0, 3.0), d(0.5, 4.0, 5.0)) + @test ForwardDiff.value(TO, R) isa RotorF64 + @test components(ForwardDiff.value(TO, R)) == [2.0, 0.0, 1.0, 0.5] + @test ForwardDiff.partials(TO, R, 1) isa QuaternionF64 + @test components(ForwardDiff.partials(TO, R, 1)) == [1.0, 0.0, 2.0, 4.0] + @test components(ForwardDiff.partials(TO, R, 2)) == [0.0, 1.0, 3.0, 5.0] + + Q = Quaternion(d(1.0, 1.0, 2.0), d(2.0, 3.0, 4.0), d(3.0, 5.0, 6.0), d(4.0, 7.0, 8.0)) + @test ForwardDiff.value(TO, Q) === Quaternion(1.0, 2.0, 3.0, 4.0) + @test ForwardDiff.partials(TO, Q, 2) === Quaternion(2.0, 4.0, 6.0, 8.0) + + V = quatvec(d(2.0, 3.0, 4.0), d(3.0, 5.0, 6.0), d(4.0, 7.0, 8.0)) + @test ForwardDiff.value(TO, V) === quatvec(2.0, 3.0, 4.0) + @test ForwardDiff.partials(TO, V, 1) === quatvec(3.0, 5.0, 7.0) + + # Complex components are split into real and imaginary parts. + CD = Complex{Dual{TO,Float64,2}} + L = Rotor{CD}(complex(d(1.0, 1.0, 0.0), d(0.0, 2.0, 0.0)), complex(d(0.0, 0.0, 1.0), d(0.5, 0.0, 3.0)), + zero(CD), zero(CD)) + @test ForwardDiff.value(TO, L) isa Lorentz{Float64} + @test components(ForwardDiff.value(TO, L)) == [1.0 + 0.0im, 0.0 + 0.5im, 0.0im, 0.0im] + @test ForwardDiff.partials(TO, L, 1) isa Quaternion{ComplexF64} + @test ForwardDiff.partials(TO, L, 1) == Quaternion( + [complex(ForwardDiff.partials(real(c), 1), ForwardDiff.partials(imag(c), 1)) for c ∈ components(L)] + ) + + # Constants have their own values and zero partials. + @test ForwardDiff.value(TO, Quaternion(1.0, 2.0, 3.0, 4.0)) === Quaternion(1.0, 2.0, 3.0, 4.0) + @test iszero(ForwardDiff.partials(TO, Quaternion(1.0, 2.0, 3.0, 4.0), 1)) + @test ForwardDiff.value(TO, imx) === imx + + # For nested duals, the outer layer is extracted first. + x = Dual{TI}(d(1.0, 2.0), d(3.0, 4.0)) + y = Dual{TI}(d(5.0, 6.0), d(7.0, 8.0)) + N = quaternion(x, y, zero(x), zero(x)) + @test ForwardDiff.value(TI, N) === quaternion(d(1.0, 2.0), d(5.0, 6.0), d(0.0, 0.0), d(0.0, 0.0)) + @test ForwardDiff.partials(TI, N, 1) === quaternion(d(3.0, 4.0), d(7.0, 8.0), d(0.0, 0.0), d(0.0, 0.0)) + # Asking for the value or partials of the newer tag from duals of the older tag returns + # the duals themselves or zero, as ForwardDiff does for scalars. + @test ForwardDiff.value(TI, Q) === Q + @test iszero(ForwardDiff.partials(TI, Q, 1)) +end + +@testitem "ForwardDiff: DifferentiationInterface" tags=[:ad, :forwarddiff] setup=[ForwardDiffTestUtils] begin + import DifferentiationInterface as DI + using .ForwardDiffTestUtils: bigfd, relerr + + backend = DI.AutoForwardDiff() + n̂ = normalize(quatvec(1.0, -2.0, 3.0)) + R₀ = Rotor{Float64}(0.9, 0.3, -0.4, 0.2) + + # Each case is a function of a real number, the types of its value and derivative, and + # the point. + cases = [ + (t -> exp(Quaternion(0.3t, t^2, -t, 0.5)), QuaternionF64, QuaternionF64, 0.4), + (t -> Rotor{typeof(t)}(t*R₀[1], R₀[2]*t^2, R₀[3], R₀[4]+t), RotorF64, QuaternionF64, 0.5), + (t -> exp(t * n̂ / 2), RotorF64, QuaternionF64, 0.3), + (t -> quatvec(sin(t), cos(t), t^3), QuatVecF64, QuatVecF64, 1.1), + (t -> Boost(t, n̂), Lorentz{Float64}, Quaternion{ComplexF64}, 0.3), + (t -> Boost(t * n̂), Lorentz{Float64}, Quaternion{ComplexF64}, 0.4), + ] + for (f, Y, D, t) ∈ cases + y, d = DI.value_and_derivative(f, backend, t) + @test y isa Y + @test components(y) == components(f(t)) + @test d isa D + @test relerr(d, bigfd(f, t)) < 1e-14 + @test DI.derivative(f, backend, t) == d + + # ForwardDiff propagates several tangents at once, in one batch. + tangents = (1.0, 2.0, -3.0) + ty = DI.pushforward(f, backend, t, tangents) + @test length(ty) == 3 + @test all(tyᵢ isa D for tyᵢ ∈ ty) + @test all(relerr(tyᵢ, tᵢ * d) < 1e-14 for (tyᵢ, tᵢ) ∈ zip(ty, tangents)) + y2, ty2 = DI.value_and_pushforward(f, backend, t, tangents) + @test y2 isa Y && components(y2) == components(y) + @test all(ty2 .== ty) + + # Second derivatives nest two tags. + d2 = DI.second_derivative(f, backend, t) + @test d2 isa D + @test relerr(d2, bigfd(f, t, 2)) < 1e-12 + y3, d3, d23 = DI.value_derivative_and_second_derivative(f, backend, t) + @test y3 isa Y && components(y3) == components(y) + @test d3 isa D && relerr(d3, d) < 1e-15 + @test d23 isa D && relerr(d23, d2) < 1e-15 + end + + # Functions of a vector are pushed forward along several tangents. + vcases = [ + (x -> exp(quatvec(x[1], x[2]*x[3], x[1])), RotorF64, QuaternionF64), + (x -> Quaternion(x[1], x[2], x[3], x[1]*x[2]) * Quaternion(x[3], 1, x[2], 0), QuaternionF64, QuaternionF64), + (x -> log(rotor(1.0, x...)), QuatVecF64, QuatVecF64), + (x -> Boost(x[1], normalize(quatvec(x[2], 1.0, x[3]))), Lorentz{Float64}, Quaternion{ComplexF64}), + ] + x = [0.3, 0.2, 0.1] + tangents = ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.3, -0.5, 0.7]) + for (f, Y, D) ∈ vcases + y, ty = DI.value_and_pushforward(f, backend, x, tangents) + @test y isa Y + @test components(y) == components(f(x)) + for (tyᵢ, dx) ∈ zip(ty, tangents) + @test tyᵢ isa D + @test relerr(tyᵢ, bigfd(s -> f(x + s * dx), 0.0)) < 1e-14 + end + end +end + +@testitem "ForwardDiff: Hessians on both sides of series thresholds" tags=[:ad, :forwarddiff] setup=[ForwardDiffTestUtils] begin + using ForwardDiff + import Quaternionic: seriestolerance, trigseriestolerance, isnearscalar, issmallvalue + using .ForwardDiffTestUtils: sc, bigfdH, relerr + + # Each point is placed 1 percent inside or outside the threshold at which the source + # switches between a Taylor series and the closed form, and the ForwardDiff Hessian is + # compared with a `BigFloat` Hessian. `BigFloat` has much smaller thresholds, so the + # reference is always computed from the closed form. + tol = seriestolerance(Float64) + trigtol = trigseriestolerance(Float64) + n = vec(normalize(quatvec(1.0, -2.0, 3.0))) + R₂ = rotor(0.4, -0.2, 0.7, 0.5) + w = 1.3 + hessian_error(f, x) = relerr(ForwardDiff.hessian(f, x), bigfdH(f, x)) + + for (δ, inside) ∈ ((-1e-2, true), (1e-2, false)) + # `exp` switches on `abs2vec(q) ≤ trigtol`. + x = [0.3; sqrt(trigtol * (1 + δ)) * n] + @test issmallvalue(abs2vec(Quaternion(x...)), trigseriestolerance) == inside + @test hessian_error(x -> sc(exp(Quaternion(x...))), x) < 1e-12 + @test hessian_error(x -> sc(exp(quatvec(x[2], x[3], x[4]))), x) < 1e-12 + + # `log` and `Rotor ^ s` switch on `abs2vec(q) ≤ tol q[1]²`, through `isnearscalar`. + x = [w; w * sqrt(tol * (1 + δ)) * n] + @test isnearscalar(Quaternion(x...)) == inside + @test hessian_error(x -> sc(log(Quaternion(x...))), x) < 1e-12 + @test hessian_error(x -> sc(log(rotor(x...))), x) < 1e-12 + for s ∈ (0.3, -0.7, 2.5) + @test hessian_error(x -> sc(rotor(x...)^s), x) < 1e-12 + end + + # Inside the `isnearscalar` branch, `Rotor ^ s` switches again, on y ≤ trigtol, where + # y = s² atan(√x)² and x = abs2vec(q) / q[1]². For |s| > 1, this happens at a + # smaller x than the first threshold. + for s ∈ (2.5, -3.0) + xₛ = tan(sqrt(trigtol * (1 + δ)) / abs(s))^2 + x = [w; w * sqrt(xₛ) * n] + @test isnearscalar(Quaternion(x...)) + @test hessian_error(x -> sc(rotor(x...)^s), x) < 1e-12 + end + + # `distance2` switches on x ≤ ε^(1/4)/2, with x = abs2vec(q) / q[1]² for q = R₁ / R₂. + dtol = sqrt(sqrt(eps(Float64))) / 2 + θ = atan(sqrt(dtol * (1 + δ))) + R₁ = Rotor(cos(θ), sin(θ) * n...) * R₂ + q = R₁ / R₂ + @test (abs2vec(q) ≤ dtol * q[1]^2) == inside + @test hessian_error(x -> distance2(rotor(x...), R₂), collect(components(R₁))) < 1e-12 + @test hessian_error(x -> distance2(R₂, rotor(x...)), collect(components(R₁))) < 1e-12 + + # `slerp(R₂, R₁, τ)` takes the power of `R₁ / R₂`, which switches at `tol`. + θ = atan(sqrt(tol * (1 + δ))) + R₁ = Rotor(cos(θ), sin(θ) * n...) * R₂ + @test isnearscalar(R₁ / R₂) == inside + for τ ∈ (0.3, 0.8) + @test hessian_error(x -> sc(slerp(R₂, rotor(x...), τ)), collect(components(R₁))) < 1e-12 + end + end +end + +@testitem "ForwardDiff: Hessians of from_rotation_matrix" tags=[:ad, :forwarddiff] setup=[ForwardDiffTestUtils] begin + using ForwardDiff + using Random + using .ForwardDiffTestUtils: sc, bigfdH, relerr, hemisphere_sign + + # `from_rotation_matrix(to_rotation_matrix(rotor(x)))` is `±rotor(x)`, with the sign + # chosen by the value of `rotor(x)`, so its Hessian is that of `±sc(rotor(x))`. At an + # exact rotation, the Bar-Itzhack matrix has a triply degenerate eigenvalue, which made + # the derivatives of the generic eigendecomposition wrong at second order, and NaN at the + # identity, before version 4.4.5. + rng = Random.MersenneTwister(1234) + points = [ + [0.6, -0.3, 0.5, 0.2], # generic + [1.0, 0.0, 0.0, 0.0], # identity + [1.0, 1e-9, -2e-9, 0.5e-9], # near the identity + [0.0, 0.3, -0.5, 0.8], # pure vector + [-1.0, 1e-3, 2e-3, -1e-3], # near -1 + [-1.0, 0.0, 0.0, 0.0], # exactly -1 + [2.0, -0.6, 1.0, 0.4], # not normalized + [randn(rng, 4) for _ ∈ 1:3]..., + ] + for x ∈ points + s = hemisphere_sign(rotor(x...)) + f = x -> sc(from_rotation_matrix(to_rotation_matrix(rotor(x...)))) + g = x -> s * sc(rotor(x...)) + H = ForwardDiff.hessian(f, x) + G = ForwardDiff.hessian(g, x) + @test all(isfinite, H) + @test relerr(H, G) < 1e-12 + @test relerr(G, bigfdH(g, x)) < 1e-12 + end +end + +@testitem "ForwardDiff: third derivatives of from_rotation_matrix" tags=[:ad, :forwarddiff] setup=[ForwardDiffTestUtils] begin + using ForwardDiff + using .ForwardDiffTestUtils: bigfd, relerr, nth_derivative, hemisphere_sign + + # Derivatives are compared along a path through each point, through third order. The + # eigenvector is refined by Newton steps from the eigenvector of the values; one step + # would give the correct first and second derivatives, but a third derivative that is + # wrong by order 1. + direction = [0.3, -0.5, 0.7, 0.2] + points = [ + [0.6, -0.3, 0.5, 0.2], + [1.0, 0.0, 0.0, 0.0], + [1.0, 1e-9, -2e-9, 0.5e-9], + [0.0, 0.3, -0.5, 0.8], + [-1.0, 1e-3, 2e-3, -1e-3], + [2.0, -0.6, 1.0, 0.4], + ] + for x ∈ points + s = hemisphere_sign(rotor(x...)) + f = t -> from_rotation_matrix(to_rotation_matrix(rotor((x + t * direction)...))) + g = t -> s * rotor((x + t * direction)...) + for n ∈ 1:3 + fₙ = nth_derivative(f, n, 0.0) + @test fₙ isa QuaternionF64 + @test relerr(fₙ, nth_derivative(g, n, 0.0)) < 1e-12 + @test relerr(fₙ, bigfd(g, 0.0, n)) < 1e-12 + end + end +end diff --git a/test/ad_mooncake.jl b/test/ad_mooncake.jl new file mode 100644 index 00000000..3629523a --- /dev/null +++ b/test/ad_mooncake.jl @@ -0,0 +1,419 @@ +# Tests of Mooncake, which differentiates the package's source natively, and of +# `QuaternionicMooncakeExt`, which imports the ChainRules rules for the two internal +# functions that Mooncake cannot trace: `Quaternionic.csqrt` (complex square roots, used by +# complex quaternions and `Lorentz` rotors) and `Quaternionic.dominant_eigenvector_lapack` +# (used by `from_rotation_matrix` and `align`). Every gradient is computed in both reverse +# and forward mode, through DifferentiationInterface, and compared with a central finite +# difference evaluated in 256-bit `BigFloat` arithmetic (`bigfd` from `ADTestUtils`). + +@testsnippet MooncakeSweep begin + using Quaternionic + using Test + import Mooncake + import DifferentiationInterface as DI + using .ADTestUtils: bigfd, relerr + + const MOONCAKE_BACKENDS = ( + "reverse" => DI.AutoMooncake(config=nothing), + "forward" => DI.AutoMooncakeForward(config=nothing), + ) + + """ + sweep(name, f, pts; tol=1e-10, broken=false) + + Check the gradients of the real function `f` computed by Mooncake in reverse and in + forward mode at each point `x` of the `name => x` pairs in `pts` against `bigfd`, to the + relative error `tol`. Each point and mode is a separate test set, so that an error at + one does not hide the results at the others. With `broken=true`, each check is a + `@test_broken`, which passes when Mooncake either throws or returns a wrong gradient, + and reports an unexpected pass once the gradient is correct. + """ + function sweep(name, f, pts; tol=1e-10, broken=false) + @testset "$name" begin + for (pname, x) ∈ pts + ref = bigfd(f, x) + for (mode, backend) ∈ MOONCAKE_BACKENDS + @testset "$name at $pname ($mode)" begin + if broken + @test_broken relerr(DI.gradient(f, backend, x), ref) < tol + else + g = DI.gradient(f, backend, x) + @test g isa AbstractVector{<:Real} + @test relerr(g, ref) < tol + end + end + end + end + end + end + + """ + sweep(cases; kwargs...) + + Run `sweep(name, f, pts; kwargs...)` for each `(name, f, pts)` in `cases`. + """ + function sweep(cases; kwargs...) + for (name, f, pts) ∈ cases + sweep(name, f, pts; kwargs...) + end + end +end + + +@testitem "Mooncake: arithmetic and Rotor algebra" tags=[:ad, :mooncake] setup=[ADTestUtils, MooncakeSweep] begin + using .ADTestUtils + pts = points() + sweep([ + ("q*p", x -> sc(Q(x) * P0), pts), + ("p/q", x -> sc(P0 / Q(x)), pts), + ("q\\p", x -> sc(Q(x) \ P0), pts), + ("inv q", x -> sc(inv(Q(x))), pts), + ("q-t", x -> sc(Q(x) - x[2]) * sc(x[3] - Q(x)), pts), + ("t*t*t*q*p", x -> sc(x[1] * x[2] * x[3] * Q(x) * P0), pts), + ("t+q+p+t", x -> sc((x[1] + Q(x) + P0 + x[4]) * P0), pts), + ("fastmath", x -> sc(@fastmath x[1] * Q(x) + x[2] / Q(x)), pts), + ("θ+𝐣", x -> sc((x[1] + 𝐣) * Q(x) + 𝐤 * Q(x)), pts), + ("R*R0", x -> sc(R(x) * R0), pts), + ("R0/R", x -> sc(R0 / R(x)), pts), + ("R*R", x -> sc(R(x) * R(x)), pts), + ("conj R", x -> sc(conj(R(x)) * P0), pts), + # Off the unit sphere, a `Rotor` stores its components without normalizing them, and + # the derivative is that of what the source computes from them. + ("Ru*Ru", x -> sc(Ru(x) * Ru(x)), pts), + ("P0/Ru", x -> sc(P0 / Ru(x)), pts), + ("V0/Ru", x -> sc(V0 / Ru(x)), pts), + ("inv Ru", x -> sc(inv(Ru(x))), pts), + ]) +end + + +@testitem "Mooncake: exp, log, sqrt, and powers" tags=[:ad, :mooncake] setup=[ADTestUtils, MooncakeSweep] begin + using .ADTestUtils + pts, nocut = points(), points(:nocut) + # `log` and `sqrt` of a `Rotor` are discontinuous at w = 0 off the unit sphere, where + # finite differences do not apply, so the pure vector is excluded for `Ru`. + nocutu = points(:nocut; exclude=(:purevector,)) + sweep([ + ("exp q", x -> sc(exp(Q(x))), pts), + ("exp v", x -> sc(exp(V(x))), pts), + ("log q", x -> sc(log(Q(x))), nocut), + ("log R", x -> sc(log(R(x))), nocut), + ("log Ru", x -> sc(log(Ru(x))), nocutu), + ("sqrt q", x -> sc(sqrt(Q(x))), nocut), + ("sqrt R", x -> sc(sqrt(R(x))), nocut), + ("sqrt v", x -> sc(sqrt(V(x))), points(:nonreal)), + ("q^n", x -> sc(Q(x)^(-3) + Q(x)^0 + Q(x)^1 + Q(x)^4), pts), + ("v^2", x -> sc(V(x)^2), pts), + ("q^0.3", x -> sc(Q(x)^0.3), nocut), + ("q^t", x -> sc(Q(x)^(x[2] + 0.5)), nocut), + ("R^0.3", x -> sc(R(x)^0.3), nocut), + ("Ru^0.3", x -> sc(Ru(x)^0.3), nocutu), + ("R^-2", x -> sc(R(x)^-2), pts), + ]) +end + + +@testitem "Mooncake: norms, slerp, distance2, and rotations" tags=[:ad, :mooncake] setup=[ADTestUtils, MooncakeSweep] begin + using .ADTestUtils + using LinearAlgebra: normalize + pts, nonreal = points(), points(:nonreal) + sweep([ + ("abs", x -> abs(Q(x)), pts), + ("abs2", x -> abs2(Q(x)), pts), + ("absvec", x -> absvec(Q(x)), nonreal), + ("normalize", x -> sc(normalize(Q(x))), pts), + ("angle R", x -> angle(R(x)), nonreal), + ("q⋅p", x -> Q(x) ⋅ P0 + Q(x) ⋅ Q(x), pts), + ("abs2 R", x -> abs2(R(x)) + abs(Ru(x)), pts), + ("slerp(R0,R)", x -> sc(slerp(R0, R(x), 0.3)), pts), + ("slerp(R,R)", x -> sc(slerp(R(x), R(x), 0.3)), pts), + ("slerp τ", x -> sc(slerp(R0, R(x), x[1])), pts), + ("distance2", x -> distance2(R(x), R0), pts), + ("distance2 same", x -> distance2(R(x), R(x) * rotor(1.0, 1e-3, 0, 0)), pts), + ("distance", x -> distance(R(x), R0), pts), + ("R(v)", x -> sc(R(x)(V0)), pts), + ("R(V(x))", x -> sc(R0(V(x))), pts), + ]) +end + + +@testitem "Mooncake: structure, conversion, and arrays" tags=[:ad, :mooncake] setup=[ADTestUtils, MooncakeSweep] begin + using .ADTestUtils + pts = points() + W = [3, -11, 7, 5] ./ 10 + sweep([ + ("imag and w", x -> imag(Q(x))[1] * Q(x).w, pts), + ("components", x -> sum(components(R(x) * P0) .* W), pts), + ("fields", x -> (Q(x) * P0).x + 2 * (V(x) * P0).w, pts), + ("to_float_array", x -> sum(to_float_array(Q(x) * P0) .* W), pts), + ("quaternion(vector)", x -> sc(quaternion(x) * P0), pts), + ("rotor(vector)", x -> sc(rotor(x) * P0), pts), + ("to_euler_phases", x -> sc(to_euler_phases(R(x))), points(:nonreal)), + ("bcast .*", x -> sc([Q(x), P0] .* [P0, Q(x)]), pts), + ("t .* qs", x -> sc(x[1] .* [Q(x), P0]), pts), + ("abs2.(qs)", x -> sum(abs2.([Q(x), P0])), pts), + ("map", x -> sc(map(q -> q * P0, [Q(x), R(x)])), pts), + ("prod", x -> sc(prod([Q(x), P0, Q(x)])), pts), + ]) +end + + +@testitem "Mooncake: complex components and Lorentz rotors" tags=[:ad, :mooncake] setup=[ADTestUtils, MooncakeSweep] begin + using .ADTestUtils + # Most cases here take a complex square root (products of `Lorentz` rotors renormalize, + # for example), which goes through `Quaternionic.csqrt`. Without the imported rule, + # Mooncake refuses to differentiate Base's `sqrt(::Complex)`, because it reinterprets + # the bits of floating-point numbers. + pts = points() + # `C(x)` is a quaternion with complex components built from the four entries of a point. + C(x) = QC(vcat(x, [x[2] / 3, -x[3] / 2, x[4] / 5 + 0.2, x[1] / 4 - 0.1])) + B = Boost(0.2, NHAT) + # At `:minus1`, both `L(x)` and `C(x)` have negative real eigenvalues (as complex 2×2 + # matrices), so they lie on the branch cut of `log`, `sqrt`, and non-integer powers. + nocut = points(exclude=(:minus1,)) + # `Bv(x)` is a boost given by a velocity, and `phases(x)` perturbs the Euler phases `z` + # of a generic rotor. + Bv(x) = Boost(quatvec(x[2] / 3, x[3] / 4, x[4] / 5)) + z = to_euler_phases(rotor(0.6, -0.3, 0.5, 0.4)) + phases(x) = (z[1] * (1 + x[1] / 10), z[2] * complex(1, x[2] / 10), z[3] * complex(1 + x[3] / 10, x[4] / 10)) + # Base's `exp`, `cos`, and `sin` of a complex number take special branches when the real + # or the imaginary part of the argument is exactly zero, and Mooncake does not + # differentiate those branches correctly: some of them throw, and others silently give + # wrong gradients. The package therefore computes these functions from real functions + # (`Quaternionic.cexp`, `ccos`, and `csin`). `exp` of a quaternion with complex + # components would reach the first branch through its scalar part, and the other two + # through `absvec`, which is purely imaginary when the vector part has a negative real + # square, as for the generator of a boost. Non-integer powers of a pure boost would + # reach them too: through `exp`, or, for a boost close to the identity raised to a large + # power, through the closed form that `^` for a `Rotor` uses there. The cases below + # that reach these points are regression tests for that change. + # + # `C(x)` has a real scalar part and a purely imaginary `absvec` at `:identity` and + # `:minus1`, and `L(x)` is a pure boost at `:identity`. + imaginaryabsvec = (:identity, :minus1) + nopureboost = points(exclude=(:identity, :minus1)) + # `x8` gives a real scalar part and a generic vector part, `x8v` a scalar part with a + # nonzero imaginary part and a vector part with a negative real square, and `x8g` the + # generator of a boost; `x8c` is generic. + x8 = [0.7, 0.3, -0.2, 0.4, 0.0, 0.1, 0.05, -0.2] + x8v = [0.7, 0.0, 0.0, 0.0, 0.2, 0.3, -0.2, 0.4] + x8g = vcat(zeros(5), 0.6 .* NHAT) + x8c = [0.7, 0.3, -0.2, 0.4, 0.13, 0.1, 0.05, -0.2] + # `VC(x)` is a `QuatVec` with complex components, whose real parts are `x[2:4]` and + # whose imaginary parts are `x[6:8]`. + VC(x) = quatvec(complex(x[2], x[6]), complex(x[3], x[7]), complex(x[4], x[8])) + # `Bp(x)` is a pure boost of rapidity `x[1]`. For a small power of it, `exp` evaluates + # `cos` and `sin(a)/a` as series, which are polynomials; larger values of `|s η|` reach + # the closed forms. + Bp(x) = Boost(x[1], NHAT) + sweep([ + ("Lorentz prod", x -> sc(L(x) * B), pts), + ("Lorentz L*L", x -> sc(L(x) * L(x)), pts), + ("velocity boost", x -> sc(Bv(x) * R(x)), pts), + ("complex log", x -> sc(log(L(x))), nocut), + ("complex sqrt", x -> sc(sqrt(L(x))), nocut), + ("Lorentz L^s", x -> sc(L(x)^0.3) + sc(L(x)^2.7), nopureboost), + ("Lorentz L^t", x -> sc(L(x)^(x[2] + 0.5)), nopureboost), + ("Lorentz small power of a boost", x -> sc(Bp(x)^0.05), ["η=0.6" => [0.6], "η=-1.0" => [-1.0]]), + ("complex abs", x -> sc(abs(quaternion(L(x)))), pts), + ("complex inv", x -> sc(inv(L(x))), pts), + ("conj and ℂconj", x -> sc(conj(L(x))) + sc(Quaternionic.ℂconj(L(x))), pts), + ("Lorentz action", x -> sum(L(x)([1.0, 0.2, -0.3, 0.5])), pts), + ("ga_components", x -> sum(ga_components(L(x)) .* (1:8) ./ 8), pts), + ("RB", x -> sc(Quaternionic.RB(L(x))), pts), + ("Rv", x -> sc(Quaternionic.Rv(L(x))), pts), + ("KAN", x -> sc(Quaternionic.KAN(L(x))), pts), + ("complex q*p", x -> sc(C(x) * P0 + P0 * C(x)), pts), + ("complex exp", x -> sc(exp(C(x))), points(exclude=imaginaryabsvec)), + ("complex exp, 8 coordinates", x -> sc(exp(QC(x))), ["x8c" => x8c]), + ("complex exp of a QuatVec", x -> sc(exp(VC(x))), ["x8c" => x8c]), + ("complex log q", x -> sc(log(C(x))), nocut), + ("complex sqrt q", x -> sc(sqrt(C(x))), nocut), + ("complex abs2", x -> sc(abs2(C(x))), pts), + ("from_euler_phases", x -> sc(from_euler_phases(phases(x)...)), pts), + ]) + sweep([ + ("complex exp", x -> sc(exp(C(x))), [p => point(p) for p ∈ imaginaryabsvec]), + ("complex exp, real scalar part", x -> sc(exp(QC(x))), ["x8" => x8]), + ("complex exp, imaginary absvec", x -> sc(exp(QC(x))), ["x8v" => x8v]), + ("exp of a boost generator", x -> sc(exp(QC(x))), ["x8g" => x8g]), + ("exp of a boost generator as a QuatVec", x -> sc(exp(VC(x))), ["x8g" => x8g]), + ("Lorentz L^s, pure boost", x -> sc(L(x)^0.3) + sc(L(x)^2.7), [:identity => point(:identity)]), + ("power of a boost", x -> sc(Bp(x)^x[2]), ["η=1.0, s=0.3" => [1.0, 0.3], "η=-0.8, s=2.7" => [-0.8, 2.7]]), + ("large power of a small boost", x -> sc(Bp(x)^x[2]), ["η=0.1, s=30" => [0.1, 30.0]]), + # Near and at the identity, `log` of a `Lorentz` rotor uses the series `logseries`, + # whose complex square root must go through `csqrt`. The derivatives are + # 1.0000009999946 and 1. + ("log of a Lorentz rotor near the identity", + x -> (l = log(Lorentz(1.0, x[1] * im, 2e-3, 0)); imag(l[2]) + real(l[3])), ["x=1e-3" => [1e-3]]), + ("log of a Lorentz rotor at the identity", + x -> (l = log(Lorentz(1.0, x[1] * im, 0, 0)); imag(l[2]) + real(l[3])), ["x=0" => [0.0]]), + ]) +end + + +@testitem "Mooncake: from_rotation_matrix and align" tags=[:ad, :mooncake] setup=[ADTestUtils, MooncakeSweep] begin + using .ADTestUtils + # The sign of the result of `from_rotation_matrix` and `align` is arbitrary. Multiplying + # by the sign that matches the result to `R(x)` gives a smooth loss; the derivative of + # `sign` is zero. + signed(Ra, Rb) = sign(components(Ra) ⋅ components(Rb)) + function frm(x) + Rf = from_rotation_matrix(to_rotation_matrix(R(x))) + return signed(Rf, R(x)) * sc(Rf) + end + a⃗ = [V0, quatvec(0.2, 0.9, -0.4), quatvec(-1.1, 0.1, 0.5)] + function aligned(x) + b⃗ = [R(x)(a) for a ∈ a⃗] + Ra = align(a⃗, b⃗) + return signed(Ra, R(x)) * sc(Ra) + end + # `frm9(y)` differentiates through a matrix that is not exactly orthogonal, built from + # all 9 entries of `y`. + M0 = to_rotation_matrix(R0) + frm9(y) = (Rf = from_rotation_matrix(reshape(y, 3, 3)); signed(Rf, R0) * sc(Rf)) + sweep([ + ("from_rotation_matrix", frm, points()), + ("align", aligned, points()), + ("from_rotation_matrix, non-orthogonal", frm9, + ["perturbed" => vec(collect(M0)) .+ [0.01, -0.02, 0.005, 0.0, 0.015, -0.01, 0.02, 0.0, -0.005]]), + ]; tol=1e-9) +end + + +@testitem "Mooncake: Float32" tags=[:ad, :mooncake] setup=[ADTestUtils, MooncakeSweep] begin + using .ADTestUtils + # The imported rules are defined for `Float32` as well as `Float64`. Mooncake's + # gradients in `Float32` are compared with the `Float64` reference. + signed(Ra, Rb) = sign(components(Ra) ⋅ components(Rb)) + frm(x) = (Rf = from_rotation_matrix(to_rotation_matrix(R(x))); signed(Rf, R(x)) * sc(Rf)) + # `L` uses the `Float64` direction `NHAT`, which would promote everything to `Float64`. + T(x) = eltype(x) + L32(x) = Boost(x[1], T(x).(NHAT)) * Lorentz(rotor(one(T(x)), x[2], x[3], x[4])) + cases = [ + ("Lorentz L*L", x -> sc(L32(x) * L32(x))), + ("complex sqrt", x -> sc(sqrt(L32(x)))), + ("from_rotation_matrix", frm), + ] + for (name, f) ∈ cases, (pname, x) ∈ points(:nocut; exclude=(:nearminus1,)) + ref = bigfd(f, x) + for (mode, backend) ∈ MOONCAKE_BACKENDS + @testset "$name at $pname ($mode)" begin + g = DI.gradient(f, backend, Float32.(x)) + @test g isa Vector{Float32} + @test relerr(g, ref) < 1e-4 + end + end + end +end + + +@testitem "Mooncake: imported rules" tags=[:ad, :mooncake] begin + using Quaternionic + using Random: Xoshiro + using LinearAlgebra: Symmetric, I + import Mooncake + using Mooncake.TestUtils: test_rule + rng = Xoshiro(20261002) + # `A` is a generic symmetric matrix with a simple largest eigenvalue, as the + # Bar-Itzhack matrix of a rotation is (its eigenvalues are 3, -1, -1, and -1). + B = randn(Xoshiro(1), 4, 4) + A = B + B' + 6I + for T ∈ (Float32, Float64), mode ∈ (Mooncake.ReverseMode, Mooncake.ForwardMode) + @testset "csqrt($z) ($T, $mode)" for z ∈ Complex{T}[0.3 + 0.4im, -2 + 1e-3im, 1e-6 - 3im] + test_rule(rng, Quaternionic.csqrt, z; is_primitive=true, mode=mode) + end + @testset "dominant_eigenvector_lapack ($T, $uplo, $mode)" for uplo ∈ ('U', 'L') + test_rule( + rng, Quaternionic.dominant_eigenvector_lapack, Matrix{T}(A), uplo; + is_primitive=true, mode=mode + ) + end + end +end + + +@testitem "Mooncake: test_rule through the source" tags=[:ad, :mooncake] begin + using Quaternionic + using Random: Xoshiro + using LinearAlgebra: normalize + import Mooncake + using Mooncake.TestUtils: test_rule + rng = Xoshiro(20261002) + # Functions with `Quaternion` and `Rotor` arguments, which Mooncake differentiates by + # tracing the source. `QuatVec` arguments cannot be tested this way, because the + # finite differences of `test_rule` perturb the scalar slot of a `QuatVec`, which every + # constructor discards. + q = quaternion(1.2, -0.7, 0.5, 0.3) + p = quaternion(0.3, 0.5, -0.4, 0.8) + Ru = Rotor{Float64}(0.5, 0.3, -0.2, 0.4) # This `Rotor` is off the unit sphere. + R2 = Rotor{Float64}(normalize([0.2, -0.6, 0.3, 0.7])) + qc = Quaternion{ComplexF64}(1 + 2im, 0.3, -0.5im, 0.2 + 0.1im) + cases = [ + ("exp", (exp, q)), ("log", (log, q)), ("sqrt", (sqrt, q)), ("q*p", (*, q, p)), + ("q/p", (/, q, p)), ("Ru*R", (*, Ru, R2)), ("R^s", (^, R2, 0.3)), + ("slerp", (slerp, rotor(q), R2, 0.3)), ("distance2", (distance2, rotor(q), R2)), + ("abs2", (abs2, q)), ("complex product", (*, qc, qc)), ("complex log", (log, qc)), + ("Lorentz", (t -> Boost(quatvec(t, 0.2, -0.1)) * Lorentz(R2), 0.3)), + ("from_rotation_matrix", (from_rotation_matrix, to_rotation_matrix(R2))), + ] + for (name, args) ∈ cases, mode ∈ (Mooncake.ReverseMode, Mooncake.ForwardMode) + @testset "$name ($mode)" begin + test_rule(rng, args...; is_primitive=false, mode=mode) + end + end +end + + +@testitem "Mooncake: friendly tangents" tags=[:ad, :mooncake] setup=[ADTestUtils] begin + using .ADTestUtils: bigfd, relerr, Q + using Quaternionic + import Mooncake + # With `friendly_tangents=true`, the gradient with respect to a quaternion argument is a + # `Quaternion` (also for a `Rotor`), or a `QuatVec` for a `QuatVec`. The hooks exist + # only in Mooncake 0.5 and later. + if isdefined(Mooncake, :AsCustomised) + q = quaternion(1.2, -0.7, 0.5, 0.3) + Ru = Rotor{Float64}(0.5, 0.3, -0.2, 0.4) + v = quatvec(0.3, -0.2, 0.5) + qc = Quaternion{ComplexF64}(1 + 2im, 0.3, -0.5im, 0.2 + 0.1im) + g(q, r, v) = sum(components(q * r * v * conj(q))) + abs2(q) + gc(q) = real(sum(components(q * q))) + garray(qs) = sum(abs2, qs) + sum(components(qs[1] * qs[2])) + function gradients(f, args...; friendly) + config = Mooncake.Config(friendly_tangents=friendly) + cache = Mooncake.prepare_gradient_cache(f, args...; config=config) + return Mooncake.value_and_gradient!!(cache, f, args...)[2][2:end] + end + structural(t::Mooncake.Tangent) = collect(t.fields.components.fields.data) + + ∂q, ∂R, ∂v = gradients(g, q, Ru, v; friendly=true) + @test ∂q isa QuaternionF64 + @test ∂R isa QuaternionF64 + @test ∂v isa QuatVecF64 + sq, sR, sv = gradients(g, q, Ru, v; friendly=false) + @test collect(components(∂q)) == structural(sq) + @test collect(components(∂R)) == structural(sR) + # The scalar slot of the structural tangent of a `QuatVec` may be nonzero, but it is + # not a coordinate of the `QuatVec`, so the friendly tangent drops it. + @test collect(components(∂v))[2:4] == structural(sv)[2:4] + @test ∂v[1] == 0 + @test relerr(collect(components(∂q)), bigfd(x -> g(Q(x), Ru, v), collect(components(q)))) < 1e-12 + + (∂qc,) = gradients(gc, qc; friendly=true) + @test ∂qc isa Quaternion{ComplexF64} + @test collect(components(∂qc)) == structural(gradients(gc, qc; friendly=false)[1]) + + qs = [q, quaternion(0.1, 0.2, 0.3, 0.4)] + (∂qs,) = gradients(garray, qs; friendly=true) + @test ∂qs isa Vector{QuaternionF64} + @test [collect(components(t)) for t ∈ ∂qs] == + [structural(t) for t ∈ gradients(garray, qs; friendly=false)[1]] + + # Integer components have no tangent, and are left to Mooncake's default. + (∂qi,) = gradients(q -> 2.0 * abs2(q), quaternion(1, 2, 3, 4); friendly=true) + @test !(∂qi isa AbstractQuaternion) + else + @info "Mooncake $(pkgversion(Mooncake)) has no friendly-tangent hooks; skipping" + end +end diff --git a/test/ad_optouts.jl b/test/ad_optouts.jl new file mode 100644 index 00000000..7df779c6 --- /dev/null +++ b/test/ad_optouts.jl @@ -0,0 +1,323 @@ +# Tests that ChainRules' generic `Number` rules do not capture quaternion arguments. +# +# `AbstractQuaternion <: Number`, so the scalar rules of ChainRules, ChainRulesCore, and +# Zygote apply to quaternion arguments unless `QuaternionicChainRulesCoreExt` supplies a +# rule of its own or opts out. Those generic rules assume that multiplication commutes, so +# a new generic rule in a later release of any of these packages would silently give wrong +# derivatives. The capture audit below finds every such rule that a call with quaternion +# arguments can reach, and fails for any that is neither displaced nor on an explicit list +# of rules that are correct for quaternions. +# +# An `@opt_out rrule(sig)` also defines `rrule(sig) = nothing`, so an opt-out with exactly +# the signature of a supplied rule would silently delete that rule. The second item checks +# that every supplied rule still returns a rule, and that every opt-out still opts out. + +@testitem "ChainRules: capture audit" tags=[:ad, :chainrules, :slow] begin + using ChainRulesCore + import ChainRulesCore: rrule, frule, no_rrule, no_frule, RuleConfig + import ChainRules, Zygote + using LinearAlgebra + + const ZC = Zygote.ZygoteRuleConfig{Zygote.Context{false}} + const QTYPES = (QuaternionF64, RotorF64, QuatVecF64, Quaternion{ComplexF64}, QuatVec{Bool}) + const OTHERTYPES = (Float64, Int, ComplexF64, Bool) + + # Every pattern of 1 to 4 argument types from the lists above with at least one + # quaternion, grouped by arity + combos(n) = [c for c ∈ Iterators.product(ntuple(_ -> (QTYPES..., OTHERTYPES...), n)...) + if any(T -> T <: AbstractQuaternion, c)] + const COMBOS = Dict(n => combos(n) for n ∈ 1:4) + + sample(::Type{QuaternionF64}) = quaternion(0.6, -0.31, 0.47, 0.23) + sample(::Type{RotorF64}) = rotor(0.6, -0.31, 0.47, 0.23) + sample(::Type{QuatVecF64}) = quatvec(-0.31, 0.47, 0.23) + sample(::Type{Quaternion{ComplexF64}}) = + Quaternion{ComplexF64}(0.3 + 0.1im, 0.5 - 0.2im, -0.4 + 0.3im, 0.2 + 0.6im) + sample(::Type{QuatVec{Bool}}) = 𝐣 + sample(::Type{Float64}) = 0.7 + sample(::Type{Int}) = 2 + sample(::Type{ComplexF64}) = 0.3 + 0.4im + sample(::Type{Bool}) = true + + # The package (root module) that defines a method + function rootname(m::Method) + M = parentmodule(m) + while parentmodule(M) !== M + M = parentmodule(M) + end + nameof(M) + end + isthirdparty(m::Method) = rootname(m) ∈ (:ChainRules, :ChainRulesCore, :Zygote, :ZygoteRules) + isours(m::Method) = startswith(string(parentmodule(m)), "Quaternionic") + location(m::Method) = "$(rootname(m)) $(basename(string(m.file))):$(m.line)" + + upper(t) = t isa TypeVar ? upper(t.ub) : t + + # The position of the function argument in the signature of a rule method, which follows + # a `RuleConfig` for configured rules, and the tangent tuple for `frule`s + function functionslot(m::Method, kind) + p = Base.unwrap_unionall(m.sig).parameters + i = kind === :rrule ? 2 : 3 + if length(p) ≥ 2 && !(p[2] isa Core.TypeofVararg) && upper(p[2]) isa Type && upper(p[2]) <: RuleConfig + i += 1 + end + (length(p) < i || p[i] isa Core.TypeofVararg) && return nothing, i + return upper(p[i]), i + end + + # The arities (numbers of primal arguments) that a rule method accepts, up to 4 + function arities(m::Method, slot) + p = Base.unwrap_unionall(m.sig).parameters + nfixed = length(p) - slot + if !isempty(p) && p[end] isa Core.TypeofVararg + return max(nfixed - 1, 1):4 + end + return 1 ≤ nfixed ≤ 4 ? (nfixed:nfixed) : (1:0) + end + + # Functions whose primal calls could have side effects are never called: those whose + # names end in `!`, which mutate their arguments, those of `Base.Threads`, and those + # named below. The names are matched whole, because a substring such as `rm` or `eval` + # also occurs in the names of pure functions such as `norm` and `evalpoly`, whose rules + # the audit must see. + const UNSAFE = r"^(show|print|println|printstyled|display|write|read|readline|readlines|readavailable|readuntil|readdir|readlink|rand|randn|randexp|randstring|randperm|randcycle|shuffle|task_local_storage|unsafe_\w+|eval|evalfile|include|include_string|exit|run|rm|cd|mkdir|mkpath|open|close|flush|wait|sleep|lock|unlock|trylock|notify|yield|schedule|ccall)$" + function unsafe(f) + f isa Function && parentmodule(f) === Base.Threads && return true + name = f isa Function ? string(nameof(f)) : string(f) + return endswith(name, "!") || occursin(UNSAFE, name) + end + + # Whether the primal call with sample arguments of the types `c` returns. Calls that + # have no method, or that inference proves always throw, are not made, because thrown + # exceptions are slow. + primalcache = Dict{Any,Bool}() + function callable(f, c) + get!(primalcache, (f, c)) do + unsafe(f) && return false + hasmethod(f, Tuple{c...}) || return false + rt = try Core.Compiler.return_type(f, Tuple{c...}) catch; Any end + rt === Union{} && return false + try + f(map(sample, c)...) + true + catch + false + end + end + end + + safewhich(f, T) = try which(f, T) catch; nothing end + + # Whether a method is one of the third-party rules for specific functions (not the + # fallbacks of ChainRulesCore, whose function argument is `Any`, and which return + # `nothing`) + function isgeneric(m::Method, kind) + isthirdparty(m) || return false + F, _ = functionslot(m, kind) + return F !== nothing && F !== Any + end + + # Sample tangents for the arguments of an `frule` + sampletangent(::AbstractQuaternion) = quaternion(0.3, -0.2, 0.5, 0.1) + sampletangent(::Complex) = 0.3 + 0.1im + sampletangent(::AbstractFloat) = 0.3 + sampletangent(::Integer) = NoTangent() + + # Whether the generic rule that dispatch selects returns no derivative information at + # all for the sample arguments, as the rules of non-differentiable functions (`typeof`, + # `isdefined`, predicates, …) do. Such rules cannot be wrong for quaternions. + function nondifferentiable(kind, f, c, configured) + args = map(sample, c) + try + if kind === :rrule + res = configured ? rrule(Zygote.ZygoteRuleConfig(), f, args...) : rrule(f, args...) + res === nothing && return true + Ω, pb = res + return all(∂ -> unthunk(∂) isa AbstractZero, pb(Ω)) + else + res = frule((NoTangent(), map(sampletangent, args)...), f, args...) + res === nothing && return true + return unthunk(res[2]) isa AbstractZero + end + catch + return false + end + end + + # The generic rules that are correct for quaternions (section 2 of the specification, + # "leave alone"): structural functions, rounding, conversions, reductions, selections + # (`ifelse` and `clamp`), and constructors of arrays, whose rules do not multiply. + # `ChainRules._unsum` is the internal reshaping step of the pullback of `sum`. Unary `+` + # and `*` with one argument are identities. + const ALLOWED = Any[ + adjoint, identity, float, zero, one, round, floor, ceil, transpose, LinearAlgebra.tr, + sum, deg2rad, rad2deg, maximum, minimum, findmax, findmin, Base.vect, vcat, hcat, + hvcat, fill, ifelse, clamp, copy ∘ Base.Broadcast.broadcasted, ChainRules._unsum, + ] + function allowed(f, c, configured) + # Identity comparisons, because `==` of some callable objects is not a `Bool` + isin(f, fs) = any(g -> g === f, fs) + isin(f, ALLOWED) && return true + isin(f, (+, *, Base.FastMath.add_fast, Base.FastMath.mul_fast)) && length(c) == 1 && return true + # The frule of `dot(x, y)` is `dot(ẋ, y) + dot(x, ẏ)`, which keeps the order of the + # factors of Base's `dot(x::Number, y::Number) = conj(x) * y`, so it is correct when + # one argument is not a quaternion. (The extension supplies the rule for two + # quaternions, whose `dot` is the componentwise product.) + isin(f, (LinearAlgebra.dot,)) && !all(T -> T <: AbstractQuaternion, c) && return true + # The known gap of section 2: the n-ary sum of ChainRules is reached when the first + # quaternion is the fourth argument or later (the ninth or later under Zygote, whose + # extension covers positions 4 through 8). Only the type of a real argument's + # cotangent is then wrong. The Zygote extension does not cover `add_fast`. + k = findfirst(T -> T <: AbstractQuaternion, c) + if (!configured && isin(f, (+,))) || isin(f, (Base.FastMath.add_fast,)) + k !== nothing && k ≥ 4 && return true + end + # ChainRules' rule for the product of four or more factors multiplies the first three + # and calls `rrule(*, Ω₃, more...)` on the rest, which reaches the fold rules of the + # extension when the first quaternion is the fourth factor or later; this is checked + # against finite differences in `ad_rules.jl`. + isin(f, (*, Base.FastMath.mul_fast)) && k !== nothing && k ≥ 4 && return true + return false + end + + # The functions that have third-party rules, with the arities that those rules accept + targets = Dict{Tuple{Symbol,Any},Set{Int}}() + for (kind, rulefn) ∈ ((:rrule, rrule), (:frule, frule)), m ∈ methods(rulefn) + isthirdparty(m) || continue + occursin("nondiff", string(m.file)) && continue + F, slot = functionslot(m, kind) + (F === nothing || !(F isa DataType) || !isdefined(F, :instance)) && continue + union!(get!(targets, (kind, F), Set{Int}()), arities(m, slot)) + end + + # For each such function and each pattern of arguments, find the rule that dispatch + # selects, both for plain ChainRules consumers (`rrule(f, args...)` and + # `frule(ṫ, f, args...)`) and for Zygote (`rrule(::ZygoteRuleConfig, f, args...)`, which + # falls back to the plain rule). A rule of the extension, or one of its opt-outs, is + # what should be selected. A generic rule is a problem unless it is allowed, its primal + # call fails anyway, or it returns no derivative information. + problems = Set{String}() + nprobed = Ref(0) + for ((kind, F), ns) ∈ targets, n ∈ sort!(collect(ns)), c ∈ COMBOS[n] + f = F.instance + nprobed[] += 1 + selections = if kind === :rrule + sel = safewhich(rrule, Tuple{F, c...}) + zsel = safewhich(rrule, Tuple{ZC, F, c...}) + if zsel !== nothing && Base.unwrap_unionall(zsel.sig).parameters[2] === RuleConfig + zsel = sel + end + ((sel, false), (zsel, true)) + else + ((safewhich(frule, Tuple{Tuple, F, c...}), false),) + end + for (s, configured) ∈ selections + if s === nothing + # An ambiguity, or no method at all, which is the case only if there is an + # ambiguity with the fallback + callable(f, c) || continue + push!(problems, "$kind $f$(c)$(configured ? " under Zygote" : ""): ambiguous") + elseif isgeneric(s, kind) && !isours(s) && !allowed(f, c, configured) + callable(f, c) || continue + nondifferentiable(kind, f, c, configured) && continue + push!(problems, "$kind $f$(c)$(configured ? " under Zygote" : ""): generic rule at $(location(s))") + end + end + end + @test nprobed[] > 10000 + if !isempty(problems) + println("Generic rules that capture quaternion arguments:") + foreach(p -> println(" ", p), sort!(collect(problems))) + end + @test isempty(problems) +end + + +@testitem "ChainRules: supplied rules and opt-outs" tags=[:ad, :chainrules] begin + using ChainRulesCore + import ChainRulesCore: rrule, frule + import ChainRules, Zygote + using LinearAlgebra: LinearAlgebra, norm, normalize, dot + import Base.FastMath: add_fast, sub_fast, mul_fast, div_fast, inv_fast, exp_fast, + log_fast, sqrt_fast, pow_fast, angle_fast, sign_fast + + q, p = quaternion(1.2, -0.7, 0.5, 0.3), quaternion(0.3, 0.8, -0.4, 1.1) + r, r2 = rotor(0.5, 0.3, -0.2, 0.4), rotor(-0.8, 0.6, 0.5, -0.7) + v = quatvec(0.3, -0.6, 0.2) + qc = Quaternion{ComplexF64}(0.3 + 0.1im, 0.5 - 0.2im, -0.4 + 0.3im, 0.2 + 0.6im) + lc = Rotor{ComplexF64}(1.1 + 0.1im, 0.2 - 0.3im, 0.1im, -0.2) + t, z = 0.7, 0.3 + 0.4im + A = [3.0 0.1 0.2 0.0; 0.1 -1.0 0.0 0.3; 0.2 0.0 -1.0 0.1; 0.0 0.3 0.1 -1.0] + + # Every signature of the rule table of section 2 (and the rules of section 3) must give a + # rule, so that no opt-out has overwritten it. + supplied = Any[ + (+, q, p), (+, q, t), (+, t, q), (-, q, p), (-, q, t), (-, t, q), (*, q, p), (*, q, t), + (*, t, q), (*, r, r2), (*, qc, z), (*, qc, qc), (/, q, p), (/, q, t), (/, t, q), + (/, r, r2), (/, q, r), (/, t, r), (\, q, p), (\, q, t), (\, t, q), + (add_fast, q, p), (sub_fast, q, p), (mul_fast, q, p), (div_fast, q, p), + (add_fast, q, t), (mul_fast, t, q), (div_fast, q, t), + (*, q, p, r), (*, t, q, p), (*, q, t, p), (*, q, p, t), (*, t, t, q), (*, t, q, t), + (*, q, t, t), (*, t, t, q, p), (+, q, p, r), (+, t, q, p), (+, t, t, q, p), + (mul_fast, q, p, r), (add_fast, q, p, r), + (-, q), (sub_fast, q), (inv, q), (inv, r), (inv, qc), (inv_fast, q), (conj, q), (conj, qc), + (exp, q), (exp, qc), (exp, v), (exp, r), (exp, lc), (exp_fast, q), + (log, q), (log, r), (log_fast, q), (sqrt, q), (sqrt, r), (sqrt, v), (sqrt_fast, q), + (^, q, 2), (^, q, -2), (^, qc, 2), (^, v, 3), (^, r, 2), (^, q, 0.3), (^, q, 2//3), + (^, v, 0.3), (^, q, p), (^, q, r), (^, r, p), (^, r, 0.3), (^, r, 2//3), (^, t, q), + (pow_fast, q, 0.3), (pow_fast, q, 2), (Base.literal_pow, ^, q, Val(2)), + (Base.literal_pow, ^, r, Val(-1)), + (muladd, q, p, r), (muladd, q, p, t), (muladd, q, t, p), (muladd, t, q, p), + (muladd, q, t, t), (muladd, t, q, t), (muladd, t, t, q), + (real, q), (real, qc), (imag, q), (vec, q), (components, q), (getindex, q, 2), + (abs, q), (abs, qc), (abs, r), (abs2, q), (abs2, qc), (abs2, r), (abs2, lc), + (abs2vec, q), (absvec, q), (norm, q), (norm, qc), (norm, r), + (angle, q), (angle, r), (angle_fast, q), (dot, q, p), (dot, qc, qc), + (r, v), (distance2, r, r2), (distance, r, r2), + (normalize, q), (normalize, r), (rotor, q), (rotor, 1.0, 2.0, 3.0, 4.0), + (rotor, 2.0, 3.0, 4.0), (rotor, 2.0), (rotor, [1.0, 2.0, 3.0, 4.0]), (Rotor, q), + (quaternion, 1.0, 2.0, 3.0, 4.0), (Quaternion, 1.0), (Quaternion{Float64}, 1.0, 2.0, 3.0, 4.0), + (Rotor{Float64}, 1.0, 2.0, 3.0, 4.0), (QuatVec{Float64}, 2.0, 3.0, 4.0), (quatvec, v), + (quaternion, [1.0, 2.0, 3.0, 4.0]), (quatvec, [2.0, 3.0, 4.0]), + (Quaternionic.csqrt, z), (Quaternionic.dominant_eigenvector_lapack, A, 'U'), + ] + # The frules of n-ary `*` and `+` are opted out. + narywithoutfrule(f, args) = f ∈ (*, +, mul_fast, add_fast) && length(args) ≥ 3 + for (f, args...) ∈ supplied + @testset "$f$(map(typeof, args))" begin + @test rrule(f, args...) !== nothing + ṫ = map(a -> a isa Number ? zero(a) : NoTangent(), args) + ṫ = map(a -> a isa AbstractQuaternion ? quaternion(zero(a)) : a, ṫ) + if narywithoutfrule(f, args) + @test frule((NoTangent(), ṫ...), f, args...) === nothing + elseif f isa Rotor + @test frule((quaternion(zero(f)), ṫ...), f, args...) !== nothing + else + @test frule((NoTangent(), ṫ...), f, args...) !== nothing + end + # Zygote uses the rule (and does not skip it as an opt-out). + @test first(Zygote.has_chain_rrule(Tuple{Zygote.ZygoteRuleConfig{Zygote.Context{false}}, Core.Typeof(f), map(Core.Typeof, args)...}, Base.get_world_counter())) + end + end + + # Every opt-out of section 2 must still opt out, so that the AD system differentiates + # the source: `rrule` returns `nothing`, and Zygote's `no_rrule` check skips the rule. + optedout = Any[ + (log, qc), (sqrt, qc), (log_fast, qc), (sqrt_fast, qc), (log, lc), (sqrt, lc), + (^, qc, 0.3), (^, qc, p), (^, t, qc), (^, lc, 2), (^, lc, 0.3), (pow_fast, qc, 0.3), + (*, lc, lc), (*, lc, r), (*, r, lc), (/, lc, lc), (/, lc, r), (/, r, lc), (\, lc, r), + (mul_fast, lc, lc), (div_fast, lc, lc), + (sign, q), (sign_fast, q), (angle, qc), (angle, lc), (angle_fast, qc), (norm, q, 2), (norm, qc, 1), + (fma, q, p, r), (fma, q, t, t), (fma, t, t, q), (LinearAlgebra.det, q), (LinearAlgebra.logdet, q), + (LinearAlgebra.pinv, q), + ] + for (f, args...) ∈ optedout + @testset "opt-out $f$(map(typeof, args))" begin + @test rrule(f, args...) === nothing + ṫ = map(a -> a isa AbstractQuaternion ? quaternion(zero(a)) : zero(a), args) + @test frule((NoTangent(), ṫ...), f, args...) === nothing + @test !first(Zygote.has_chain_rrule(Tuple{Zygote.ZygoteRuleConfig{Zygote.Context{false}}, Core.Typeof(f), map(Core.Typeof, args)...}, Base.get_world_counter())) + end + end + @test frule((NoTangent(), zero(q)), LinearAlgebra.norm2, q) === nothing +end diff --git a/test/ad_reversediff.jl b/test/ad_reversediff.jl new file mode 100644 index 00000000..97dc8ed6 --- /dev/null +++ b/test/ad_reversediff.jl @@ -0,0 +1,303 @@ +# Tests of ReverseDiff on quaternions and of `QuaternionicReverseDiffExt`. ReverseDiff +# differentiates quaternions of `TrackedReal`s natively, by recording the operations on +# their components. The extension makes the source take the same value-dependent branches +# as it does for plain numbers, broadcasts a `TrackedReal` with an array of quaternions +# elementwise, and records the starting vector of the dominant eigenvector in +# `from_rotation_matrix` and `align` so that replayed tapes recompute it. Every reference +# is a central finite difference evaluated with 256-bit `BigFloat`s (from `ADTestUtils`). + +@testitem "ReverseDiff: value and iszerovalue see through tracking" tags=[:ad, :reversediff] begin + using ReverseDiff, ForwardDiff + using Test: detect_ambiguities + import Quaternionic: value, iszerovalue + + t = ReverseDiff.track(0.3) + @test value(t) === 0.3 + @test iszerovalue(ReverseDiff.track(0.0)) + @test !iszerovalue(t) + # The value is also found through nested tracking, as in `ReverseDiff.hessian`, and + # through a dual number inside the tracking. + @test value(ReverseDiff.track(ReverseDiff.track(0.3))) === 0.3 + @test value(ReverseDiff.track(ForwardDiff.Dual(0.3, 1.0))) === 0.3 + @test iszerovalue(ReverseDiff.track(ForwardDiff.Dual(0.0, 1.0))) + @test iszerovalue(quaternion(ReverseDiff.track(0.0), ReverseDiff.track(0.0), 0.0, 0.0)) + + # The extension's methods are not ambiguous with ReverseDiff's own. + ext = Base.get_extension(Quaternionic, :QuaternionicReverseDiffExt) + @test ext isa Module + ambiguities = detect_ambiguities(ext, ReverseDiff; recursive=true) + @test isempty(filter(a -> a[1].module === ext || a[2].module === ext, ambiguities)) +end + +@testitem "ReverseDiff: gradients at the point set" tags=[:ad, :reversediff] setup=[ADTestUtils] begin + using ReverseDiff + using LinearAlgebra: normalize + using .ADTestUtils + + # Each case maps a four-entry point `x` to a value, which `sc` turns into a real loss. + # The kinds of points are those of `ADTestUtils.points`. + cases = [ + ("Q * P0", x -> Q(x) * P0, :all), + ("P0 * Q", x -> P0 * Q(x), :all), + ("Q / P0", x -> Q(x) / P0, :all), + ("P0 / Q", x -> P0 / Q(x), :all), + ("Q + 2.5", x -> Q(x) + 2.5, :all), + ("x[1] * P0", x -> x[1] * P0, :all), + ("inv(Q)", x -> inv(Q(x)), :all), + ("conj(Q)", x -> conj(Q(x)), :all), + ("abs(Q)", x -> abs(Q(x)), :all), + ("abs2(Q)", x -> abs2(Q(x)), :all), + ("absvec(Q)", x -> absvec(Q(x)), :nonreal), + ("normalize(Q)", x -> normalize(Q(x)), :all), + ("exp(Q)", x -> exp(Q(x)), :all), + ("exp(V)", x -> exp(V(x)), :all), + ("log(Q)", x -> log(Q(x)), :nocut), + ("sqrt(Q)", x -> sqrt(Q(x)), :nocut), + ("Q^2", x -> Q(x)^2, :all), + ("Q^-3", x -> Q(x)^-3, :all), + ("Q^0.3", x -> Q(x)^0.3, :nocut), + ("V^2", x -> V(x)^2, :all), + ("R", x -> R(x), :all), + ("R * R0", x -> R(x) * R0, :all), + ("R / R0", x -> R(x) / R0, :all), + ("Ru * R0", x -> Ru(x) * R0, :offsphere), + ("log(R)", x -> log(R(x)), :nocut), + ("sqrt(R)", x -> sqrt(R(x)), :nocut), + ("R^0.3", x -> R(x)^0.3, :nocut), + ("R(V0)", x -> R(x)(V0), :all), + ("Ru(V0)", x -> Ru(x)(V0), :offsphere), + ("slerp(R, R0, 0.3)", x -> slerp(R(x), R0, 0.3), :all), + ("slerp(R0, R, 0.3)", x -> slerp(R0, R(x), 0.3), :all), + ("distance2(R, R0)", x -> distance2(R(x), R0), :all), + ("distance(R, R0)", x -> distance(R(x), R0), :all), + ("distance2(R, R)", x -> distance2(R(x), R(x)), :all), + ("Q ⋅ P0", x -> Q(x) ⋅ P0, :all), + ("components(Q)", x -> components(Q(x)), :all), + ("to_rotation_matrix(R)", x -> to_rotation_matrix(R(x)), :all), + ("L", x -> L(x), :all), + ("L * L", x -> L(x) * L(x), :all), + ] + # The Lorentz cases at `:identity` and `:minus1`, where the rotor's vector part is zero, + # are regression tests: ReverseDiff records the derivative of `abs(::Complex)`, which is + # `hypot`, as NaN at zero, so `_hypot` in src/quaternion.jl takes its scale from the + # values of the components only. + @testset "$name" for (name, f, kind) ∈ cases + loss = x -> sc(f(x)) + for (pname, x) ∈ points(kind) + g = ReverseDiff.gradient(loss, x) + ref = bigfd(loss, x) + @test all(isfinite, g) + @test relerr(g, ref) < 1e-12 + end + end + # Base's `exp`, `cos`, and `sin` of a `Complex` take shortcuts when the real or imaginary + # part is exactly zero, which ReverseDiff differentiates incorrectly. The package + # computes them from real functions instead, and these cases are regression tests for + # that. `x8` gives a real scalar part, `x8v` a vector part with a negative real square, + # and `x8g` the generator of a boost; `Bp(x)` is a pure boost of rapidity `x[1]`. + x8 = [0.7, 0.3, -0.2, 0.4, 0.0, 0.1, 0.05, -0.2] + x8v = [0.7, 0.0, 0.0, 0.0, 0.2, 0.3, -0.2, 0.4] + x8g = vcat(zeros(5), 0.6 .* NHAT) + Bp(x) = Boost(x[1], NHAT) + zerobranches = [ + ("exp(QC), real scalar part", x -> sc(exp(QC(x))), x8), + ("exp(QC), imaginary absvec", x -> sc(exp(QC(x))), x8v), + ("exp of a boost generator", x -> sc(exp(QC(x))), x8g), + ("power of a boost", x -> sc(Bp(x)^x[2]), [1.0, 0.3]), + ("large power of a small boost", x -> sc(Bp(x)^x[2]), [0.1, 30.0]), + ] + @testset "$name" for (name, loss, x) ∈ zerobranches + @test relerr(ReverseDiff.gradient(loss, x), bigfd(loss, x)) < 1e-12 + end +end + +@testitem "ReverseDiff: Hessians at special points" tags=[:ad, :reversediff] setup=[ADTestUtils] begin + using ReverseDiff + using .ADTestUtils + + # `ReverseDiff.hessian` nests `TrackedReal`s, so the value-based thresholds of the + # source must see through both levels. The slerp Hessian at q₁ == q₂ was wrong by 1.06 + # before `Quaternionic.value(::TrackedReal)` existed. + x₁ = [0.4, -0.2, 0.7, 0.5] + cases = [ + ("slerp at q₁ == q₂", x -> sc(slerp(R(x, 1), R(x, 5), x[9])), [x₁; x₁; 0.3]), + ("slerp near q₁ == q₂", x -> sc(slerp(R(x, 1), R(x, 5), x[9])), [x₁; x₁ .+ 1e-9; 0.3]), + ("R^0.3 at the identity", x -> sc(R(x)^0.3), point(:identity)), + ("R^0.3 near the identity", x -> sc(R(x)^0.3), point(:nearidentity)), + ("R^s at the identity", x -> sc(R(x)^x[5]), [point(:identity); 0.3]), + ("distance2(R, R)", x -> distance2(R(x, 1), R(x, 5)), [x₁; x₁]), + ("log(R) at the identity", x -> sc(log(R(x))), point(:identity)), + ("exp(V) at zero", x -> sc(exp(V(x))), zeros(4)), + ("absvec(Q) near the real axis", x -> absvec(Q(x)), point(:nearidentity)), + ("sqrt(Q) at the identity", x -> sc(sqrt(Q(x))), point(:identity)), + ] + @testset "$name" for (name, f, x) ∈ cases + H = ReverseDiff.hessian(f, x) + @test all(isfinite, H) + @test relerr(H, bigfdH(f, x)) < 1e-10 + end +end + +@testitem "ReverseDiff: a TrackedReal with arrays of quaternions" tags=[:ad, :reversediff] setup=[ADTestUtils] begin + using ReverseDiff + using StaticArrays: SVector + using .ADTestUtils + + # ReverseDiff's own `materialize` methods for a `TrackedReal` and an array of numbers + # call `broadcast` again, which overflowed the stack for arrays of quaternions. + qs = [quaternion(0.3, -0.5, 0.2, 0.9), quaternion(-1.1, 0.4, 0.7, -0.2), P0] + Rs = [R0, rotor(0.1, 0.9, -0.3, 0.2)] + M = [qs[1] qs[2]; qs[3] P0] + sqs = SVector(qs[1], qs[2]) + cases = [ + ("t * qs", t -> t * qs), + ("qs * t", t -> qs * t), + ("qs / t", t -> qs / t), + ("t .* qs", t -> t .* qs), + ("qs .* t", t -> qs .* t), + ("qs ./ t", t -> qs ./ t), + ("t ./ qs", t -> t ./ qs), + ("t .+ qs", t -> t .+ qs), + ("qs .- t", t -> qs .- t), + ("t .- qs", t -> t .- qs), + ("qs .^ t", t -> qs .^ t), + ("t .^ qs", t -> t .^ qs), + ("Rs .* t", t -> Rs .* t), + ("t .* M", t -> t .* M), + ("view(qs) .* t", t -> view(qs, 1:2) .* t), + ("t .* sqs", t -> t .* sqs), + ("sqs ./ t", t -> sqs ./ t), + ] + @testset "$name" for (name, f) ∈ cases + loss = x -> sc(f(x[1])) + x = [0.7] + g = ReverseDiff.gradient(loss, x) + @test relerr(g, bigfd(loss, x)) < 1e-13 + end + # The elementwise results have the same values as plain broadcasting, and the same + # container types, so that static arrays give static results. + t = ReverseDiff.track(0.7) + @test ReverseDiff.value.(components(first(t .* qs))) == components(0.7 * qs[1]) + @test size(t .* M) == size(M) + @test t .* M isa Matrix + @test qs ./ t isa Vector + @test t .* sqs isa SVector{2} + @test sqs ./ t isa SVector{2} +end + +@testitem "ReverseDiff: from_rotation_matrix and align" tags=[:ad, :reversediff] setup=[ADTestUtils] begin + using ReverseDiff + using LinearAlgebra: normalize + import Quaternionic: value + using .ADTestUtils: sc, bigfd, bigfdH, relerr + + # At an exact rotation, the matrix whose dominant eigenvector gives the rotor has a + # triply degenerate eigenvalue. The derivatives were NaN at the identity and at + # pure-vector rotors, and wrong at second order everywhere, before version 4.4.5. At + # w = 0, the sign of the result is chosen by `positive_hemisphere`, so the loss is + # multiplied by the sign that makes the function smooth for the finite differences. + rotors = [ + rotor(1.0, 0.0, 0.0, 0.0), + normalize(rotor(0.0, 0.48, -0.6, 0.64)), + rotor(1.2, -0.7, 0.5, 0.3), + rotor(1.0, 1e-9, -2e-9, 3e-9), + rotor(0.0, 1.0, 0.0, 0.0), + rotor(1e-8, 0.6, -0.48, 0.64), + ] + @testset "$R₀" for R₀ ∈ rotors + f = x -> (S = from_rotation_matrix(reshape(x, 3, 3)); sign(value(S ⋅ R₀)) * sc(S)) + x₀ = vec(Matrix(to_rotation_matrix(R₀))) + # The matrix `x₁` is near the rotation, but not orthogonal. + x₁ = x₀ .+ 1e-3 .* sin.(1:9) + for x ∈ (x₀, x₁) + g = ReverseDiff.gradient(f, x) + @test all(isfinite, g) + @test relerr(g, bigfd(f, x)) < 1e-13 + H = ReverseDiff.hessian(f, x) + @test all(isfinite, H) + @test relerr(H, bigfdH(f, x)) < 1e-12 + end + end + + # The function `align`, given vectors, uses the same dominant eigenvector. + a⃗ = [quatvec(sin(k), cos(2k), sin(3k + 1)) for k ∈ 1:5] + @testset "align at $R₀" for R₀ ∈ (rotor(0.4, -0.2, 0.7, 0.5), rotor(1.0, 0.0, 0.0, 0.0)) + f = x -> sc(align(a⃗, [quatvec(x[3k-2], x[3k-1], x[3k]) for k ∈ 1:5])) + x₀ = reduce(vcat, [collect(vec(R₀(a))) for a ∈ a⃗]) + for x ∈ (x₀, x₀ .+ 1e-2 .* cos.(1:15)) + g = ReverseDiff.gradient(f, x) + @test all(isfinite, g) + @test relerr(g, bigfd(f, x)) < 1e-13 + end + end +end + +@testitem "ReverseDiff: recorded and compiled tapes" tags=[:ad, :reversediff] setup=[ADTestUtils] begin + using ReverseDiff + using .ADTestUtils + + # A tape records the branches taken at the recording point, so it is replayed here at + # generic points, on the same side of every threshold as the recording point. + x₀ = [1.2, -0.7, 0.5, 0.3] + replays = ([1.1, -0.6, 0.55, 0.25], [0.9, 0.1, -0.3, 0.6], x₀) + cases = [ + ("exp(Q)", x -> sc(exp(Q(x)))), + ("log(Q)", x -> sc(log(Q(x)))), + ("sqrt(Q)", x -> sc(sqrt(Q(x)))), + ("Q^0.3", x -> sc(Q(x)^0.3)), + ("R^0.3", x -> sc(R(x)^0.3)), + ("slerp(R, R0, 0.3)", x -> sc(slerp(R(x), R0, 0.3))), + ("distance2(R, R0)", x -> distance2(R(x), R0)), + ("R(V0)", x -> sc(R(x)(V0))), + ("from_rotation_matrix", x -> sc(from_rotation_matrix(to_rotation_matrix(Q(x))))), + ("align", x -> sc(align([V0, quatvec(0.5, 0.1, -0.4), quatvec(-0.2, 0.3, 0.9)], + [R(x)(V0), R(x)(quatvec(0.5, 0.1, -0.4)), R(x)(quatvec(-0.2, 0.3, 0.9))]))), + ] + @testset "$name" for (name, f) ∈ cases + tape = ReverseDiff.GradientTape(f, x₀) + compiled = ReverseDiff.compile(tape) + for x ∈ replays + ref = bigfd(f, x) + @test relerr(ReverseDiff.gradient!(similar(x), tape, x), ref) < 1e-13 + @test relerr(ReverseDiff.gradient!(similar(x), compiled, x), ref) < 1e-13 + end + end + + # The sign chosen by `positive_hemisphere` is frozen on the tape. A replay at a rotation + # in the other hemisphere of the recording (here, `R(x₀) ⋅ R(x) < 0`) therefore returns + # the derivative of the negated rotor, not an unrelated value. + f = x -> sc(from_rotation_matrix(to_rotation_matrix(Q(x)))) + compiled = ReverseDiff.compile(ReverseDiff.GradientTape(f, x₀)) + x = [0.3, 0.8, -0.2, 0.5] + @test R(x₀) ⋅ R(x) < 0 + @test relerr(ReverseDiff.gradient!(similar(x), compiled, x), -bigfd(f, x)) < 1e-13 + + # A `HessianTape` records the inner gradient tape onto an outer tape, so the starting + # vector of the dominant eigenvector must be recomputed on the outer tape as well. + # Before it was, replays away from the recording point were wrong by up to 37. The + # input matrices are slightly non-orthogonal, and every rotation is in the hemisphere + # of the recording point. + a⃗ = [quatvec(sin(k), cos(2k), sin(3k + 1)) for k ∈ 1:5] + hessiancases = [ + ( + "from_rotation_matrix", + x -> sc(from_rotation_matrix(reshape(x, 3, 3))), + R -> vec(Matrix(to_rotation_matrix(R))) .+ 1e-3 .* sin.(1:9), + ), + ( + "align", + x -> sc(align(a⃗, [quatvec(x[3k-2], x[3k-1], x[3k]) for k ∈ 1:5])), + R -> reduce(vcat, [collect(vec(R(a))) for a ∈ a⃗]) .+ 1e-2 .* cos.(1:15), + ), + ] + @testset "HessianTape of $name" for (name, f, input) ∈ hessiancases + tape = ReverseDiff.HessianTape(f, input(rotor(1.2, -0.7, 0.5, 0.3))) + compiled = ReverseDiff.compile(tape) + for Rₓ ∈ (rotor(1.2, -0.7, 0.5, 0.3), rotor(0.9, 0.4, -0.3, 0.2), rotor(1, 0, 0, 0)) + x = input(Rₓ) + ref = bigfdH(f, x) + @test relerr(ReverseDiff.hessian!(tape, x), ref) < 1e-12 + @test relerr(ReverseDiff.hessian!(compiled, x), ref) < 1e-12 + end + end +end diff --git a/test/ad_rules.jl b/test/ad_rules.jl new file mode 100644 index 00000000..7f8eedad --- /dev/null +++ b/test/ad_rules.jl @@ -0,0 +1,1186 @@ +# Tests of the `frule`s, `rrule`s, and projections of `QuaternionicChainRulesCoreExt`. +# +# Each rule is checked in two ways. `checkrule` (in the `RuleChecks` snippet below) compares +# the pullback and the pushforward with central finite differences evaluated in 256-bit +# `BigFloat` arithmetic (`bigvjp` and `bigjvp` from `ADTestUtils`), at every point of the +# point set where the source is differentiable; this includes the points near the identity +# and near -1, where the Float64 finite differences of ChainRulesTestUtils are too coarse. +# `crtu` runs ChainRulesTestUtils' `test_rrule` and `test_frule` at generic points, which +# also check inference, thunks, zero cotangents, and the types of the tangents. Points +# where the source is not differentiable in every direction (the negative real axis, and +# the cone points of norms) are checked explicitly. +# +# ChainRules itself is loaded in every item, because the purpose of many of these rules is +# to displace the generic `Number` rules of ChainRules, which would otherwise capture +# quaternion arguments. + +@testsnippet RuleChecks begin + using Quaternionic + using Test + using ChainRulesCore + using ChainRulesCore: rrule, frule, unthunk + using ChainRulesTestUtils + import ChainRules + using Random: Random, MersenneTwister + using LinearAlgebra: LinearAlgebra, dot, norm, normalize + using StaticArrays: SVector, @SVector + using .ADTestUtils + + rng = MersenneTwister(20261002) + + # Reseed both sources of random tangents: `rng`, from which this module draws the + # tangents it chooses, and the global generator, from which ChainRulesTestUtils draws + # the rest. `checkrule` and `crtu` call this first, so that each check uses the same + # tangents however the test items are filtered or ordered, and a failure can be + # reproduced by running its item alone. + function reseed!() + Random.seed!(rng, 20261002) + Random.seed!(20261002) + nothing + end + + # A random tangent or cotangent of `x`. Arguments that are not numbers or arrays of + # numbers (functions, `Val`s, and characters) get `NoTangent()`, as do integers and + # `Bool`s. + randtangent(x) = NoTangent() + randtangent(x::Union{Number,AbstractArray{<:Number}}) = rand_tangent(rng, x) + randtangent(x::Rational) = randn(rng, float(typeof(x))) + + # Whether `∂` has the type of a tangent of `x` in the conventions of the extension: a + # `Quaternion` for a `Quaternion` or `Rotor`, a `QuatVec` for a `QuatVec`, each with + # floating-point components of the precision of `x`; a number of the same kind for a + # number; and an array of the same kind for an array. + tangentok(∂, x) = true + tangentok(∂, x::AbstractQuaternion) = ∂ isa Quaternion{float(typeof(x[1]))} + tangentok(∂, x::QuatVec) = ∂ isa QuatVec{float(typeof(x[1]))} + tangentok(∂, x::Real) = ∂ isa Real + tangentok(∂, x::Complex) = ∂ isa Number && !(∂ isa AbstractQuaternion) + tangentok(∂, x::AbstractArray) = ∂ isa AbstractArray && size(∂) == size(x) + tangentok(∂, x::Vector) = ∂ isa Vector && size(∂) == size(x) + + # The discrepancy between a tangent `∂` returned by a rule and the reference `ref` for + # the primal `x`: the relative error, or `Inf` if the type is wrong. A reference of + # `NoTangent()` requires a zero tangent, and a zero tangent counts as the zero of the + # reference. + function discrepancy(∂, ref, x) + ∂ = unthunk(∂) + ref isa AbstractZero && return ∂ isa AbstractZero ? 0.0 : Inf + ∂ isa AbstractZero && return Float64(relerr(zero(ref), ref)) + tangentok(∂, x) || return Inf + return Float64(relerr(∂, ref)) + end + + describe(f) = string(f) + describe(f::Rotor) = "R(v)" + describe(f::Type) = string(f) + + """ + checkrule(f, args...; ȳ, ẋs, ref, rtol, pullback, pushforward) + + Check `rrule(f, args...)` and `frule((NoTangent(), ẋs...), f, args...)` against the + 256-bit finite-difference references `bigvjp(ref, args, ȳ)` and `bigjvp(ref, args, ẋs)`, + to the relative error `rtol`. The primal must equal `f(args...)` in value and type, and + each tangent must have the type of the conventions. By default, `ȳ` and `ẋs` are random, + and `ref` is `f` itself. When `f` is a `Rotor`, it is the rotor of `R(v)`, and it is + differentiated as an argument. + """ + function checkrule(f, args...; ȳ=nothing, ẋs=nothing, ref=f, rtol=1e-10, + pullback=true, pushforward=true) + reseed!() + selfdiff = f isa Rotor + g = selfdiff ? ((h, a...) -> h(a...)) : ref + gargs = selfdiff ? (f, args...) : args + Ω₀ = f(args...) + @testset "$(describe(f))($(join(map(a -> string(typeof(a)), args), ", ")))" begin + if pullback + res = rrule(f, args...) + @test res !== nothing + if res !== nothing + Ω, pb = res + @test typeof(Ω) == typeof(Ω₀) + @test Ω ≈ Ω₀ + Δ = ȳ === nothing ? randtangent(Ω₀) : ȳ + ∂ = pb(Δ) + @test length(∂) == length(gargs) + !selfdiff + selfdiff || @test ∂[1] isa NoTangent + refs = bigvjp(g, gargs, Δ) + ∂args = selfdiff ? ∂ : Base.tail(∂) + for i ∈ eachindex(gargs) + a = gargs[i] + if a isa Integer && !(a isa Bool) && unthunk(∂args[i]) isa Real + # The reference cannot perturb an integer, so a real cotangent of + # an integer (which `ProjectTo` of an integer gives) is compared + # with the reference for the equivalent float. + floatrefs = bigvjp(g, Base.setindex(gargs, float(a), i), Δ) + @test discrepancy(∂args[i], floatrefs[i], float(a)) ≤ rtol + else + @test discrepancy(∂args[i], refs[i], a) ≤ rtol + end + end + end + end + if pushforward + ẋ = ẋs === nothing ? map(randtangent, gargs) : ẋs + res = selfdiff ? frule(ẋ, f, args...) : frule((NoTangent(), ẋ...), f, args...) + @test res !== nothing + if res !== nothing + Ω, Ω̇ = res + @test typeof(Ω) == typeof(Ω₀) + @test Ω ≈ Ω₀ + @test discrepancy(Ω̇, bigjvp(g, gargs, ẋ), Ω₀) ≤ rtol + end + end + end + end + + # Tolerances of ChainRulesTestUtils' finite differences, which are computed in the + # precision of the primal + crtutol(::Type{Float32}) = (rtol=5e-3, atol=5e-3) + crtutol(::Type{Float64}) = (rtol=1e-8, atol=1e-8) + crtutol(::Type{BigFloat}) = (rtol=1e-12, atol=1e-12) + + # The type of the real numbers in the arguments + realtypeof(a::Number) = float(real(typeof(a))) + realtypeof(a::Integer) = Union{} + realtypeof(a::AbstractQuaternion) = realtypeof(a[1]) + realtypeof(a::AbstractArray{<:Number}) = realtypeof(first(a)) + realtypeof(a) = Union{} + realtypeof(args::Tuple) = mapreduce(realtypeof, promote_type, args; init=Union{}) + + # Attach explicit random tangents to the arguments with complex components + withtangent(a) = a + withtangent(a::AbstractQuaternion{<:Complex}) = a ⊢ rand_tangent(rng, a) + withtangent(a::Complex) = a ⊢ rand_tangent(rng, a) + + """ + crtu(f, args...; check_inferred=true, frule=true, kwargs...) + + Run ChainRulesTestUtils' `test_rrule` (and `test_frule`, unless `frule` is `false`) on + `f(args...)`, with tolerances for the precision of the arguments and explicit tangents + for arguments with complex components. + """ + function crtu(f, args...; check_inferred=true, frule=true, kwargs...) + reseed!() + tol = crtutol(realtypeof(args)) + targs = map(withtangent, args) + test_rrule(f, targs...; check_inferred=check_inferred, tol..., kwargs...) + frule && test_frule(f, targs...; check_inferred=check_inferred, tol..., kwargs...) + end + + # A quaternion with complex components built from a four-entry point, with fixed + # imaginary parts + QCx(x) = QC([x; [0.2, -0.1, 0.3, 0.05]]) + + # The tolerance of the comparison with the BigFloat references at a point. Near -1 the + # derivatives of `log`, `sqrt`, and the powers are of order 1e7, and roundoff in the + # Float64 rules grows with them. + pointtol(name) = name === :nearminus1 ? 1e-7 : 1e-10 +end + + +@testitem "ChainRules: structural rules" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + # Constructors with explicit types store their arguments without normalizing them, so + # their references are the same constructors with the element type of the (possibly + # BigFloat) perturbed arguments. + numtype(x::Number) = typeof(x) + numtype(x::AbstractArray) = eltype(x) + numtype(x::AbstractQuaternion) = typeof(x[1]) + storing(QT) = (a...) -> QT{promote_type(map(numtype, a)...)}(a...) + + for T ∈ (Float64, Float32, BigFloat) + rtol = T === Float32 ? 1e-5 : T === BigFloat ? 1e-40 : 1e-12 + w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) + @testset "Constructors $T" begin + for QT ∈ (Quaternion, Rotor, QuatVec) + for args ∈ ((w, x, y, z), (x, y, z), (w,), (SVector(w, x, y, z),), ([w, x, y, z],), + ([x, y, z],), ([w],), (Quaternion{T}(w, x, y, z),), (Rotor{T}(w, x, y, z),)) + # `Rotor{T}`, `Quaternion{T}`, and `QuatVec{T}` have no methods for vectors + # of lengths 3 and 1. + if !(args[1] isa AbstractVector && length(args[1]) < 4) + checkrule(QT{T}, args...; ref=storing(QT), rtol=rtol) + end + checkrule(QT, args...; rtol=rtol) + end + end + for f ∈ (quaternion, rotor, quatvec) + for args ∈ ((w, x, y, z), (x, y, z), (w,), (SVector(w, x, y, z),), ([w, x, y, z],), + ([x, y, z],), ([w],), (Quaternion{T}(w, x, y, z),), (Rotor{T}(w, x, y, z),)) + checkrule(f, args...; rtol=rtol) + end + @test_throws DimensionMismatch rrule(f, T[1, 2]) + end + # Integer arguments of a constructor get the floating-point cotangents of the + # equivalent floats. + Δ = quaternion(T(3//10), T(-11//10), T(7//10), T(1//2)) + for (f, ints) ∈ ((quaternion, (1, 2, 3, 4)), (rotor, (1, 2, 3, 4)), (quatvec, (2, 3, 4)), (rotor, (2, 3, 4))) + ∂ints = rrule(f, ints...)[2](Δ) + ∂floats = rrule(f, map(float, ints)...)[2](Δ) + @test all(map((a, b) -> unthunk(a) isa AbstractFloat && unthunk(a) ≈ unthunk(b), ∂ints[2:end], ∂floats[2:end])) + end + end + end + + @testset "Constructors with complex arguments" begin + z1, z2, z3, z4 = 0.3 + 0.1im, -0.5 + 0.2im, 0.7 - 0.4im, 0.2 + 0.6im + for f ∈ (quaternion, Quaternion, Quaternion{ComplexF64}, quatvec, QuatVec, Rotor{ComplexF64}) + ref = f isa Type && !(f isa UnionAll) ? storing(f.name.wrapper) : f + checkrule(f, z1, z2, z3, z4; ref=ref) + checkrule(f, [z1, z2, z3, z4]; ref=ref) + end + checkrule(rotor, z1, z2, z3, z4) + end + + @testset "Structural access at $name" for (name, xp) ∈ points() + tol = pointtol(name) + for q ∈ (Q(xp), R(xp), Ru(xp), V(xp), QCx(xp)) + checkrule(components, q; rtol=tol) + for i ∈ 1:4 + checkrule(getindex, q, i; rtol=tol) + end + checkrule(real, q; rtol=tol) + checkrule(imag, q; rtol=tol) + checkrule(vec, q; rtol=tol) + end + end + + @testset "rotor and normalize at $name" for (name, xp) ∈ points() + tol = pointtol(name) + checkrule(normalize, Q(xp); rtol=tol) + checkrule(normalize, Ru(xp); rtol=tol) + checkrule(normalize, QCx(xp); rtol=tol) + checkrule(rotor, Q(xp); rtol=tol) + checkrule(rotor, Ru(xp); rtol=tol) + checkrule(Rotor, Q(xp); rtol=tol) + checkrule(rotor, xp...; rtol=tol) + checkrule(rotor, xp; rtol=tol) + if !iszero(xp[2:4]) + checkrule(rotor, xp[2:4]...; rtol=tol) + checkrule(normalize, V(xp); rtol=tol) + end + iszero(xp[1]) || checkrule(rotor, xp[1]; rtol=tol) + end + + @testset "ChainRulesTestUtils, $T" for T ∈ (Float64, Float32, BigFloat) + w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) + sv, v4, v3, v1 = @SVector[w, x, y, z], [w, x, y, z], [x, y, z], [w] + for QT ∈ (Quaternion, Rotor, QuatVec) + # This list is ported from the retired `auto_differentiation.jl`. + for args ∈ ((sv,), (v4,), (w, x, y, z), (x, y, z), (w,)) + crtu(QT{T}, args...) + crtu(QT, args...) + end + for args ∈ ((v3,), (v1,)) + crtu(QT, args...) + end + end + for f ∈ (quaternion, rotor, quatvec), args ∈ ((sv,), (v4,), (v3,), (v1,), (w, x, y, z), (x, y, z), (w,)) + crtu(f, args...) + end + for q ∈ (Quaternion{T}(w, x, y, z), Rotor{T}(w, x, y, z), QuatVec{T}(x, y, z)) + crtu(components, q) + crtu(real, q) + crtu(imag, q) + crtu(vec, q) + for i ∈ 1:4 + crtu(getindex, q, i) + end + crtu(normalize, q) + q isa QuatVec || crtu(rotor, q) + end + end +end + + +@testitem "ChainRules: arithmetic" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + import Base.FastMath: add_fast, sub_fast, mul_fast, div_fast, inv_fast + p₀ = quaternion(0.3, 0.8, -0.4, 1.1) + pc = QC([-0.2, 0.1, 0.6, -0.3, 0.4, 0.3, -0.1, 0.2]) + zc = 0.7 + 0.2im + + @testset "Binary operations at $name" for (name, x) ∈ points() + tol = pointtol(name) + q, ru, v, qc = Q(x), Ru(x), V(x), QCx(x) + nonzerovec = !iszero(x[2:4]) + pairs = Any[ + (q, p₀), (p₀, q), (q, 0.7), (0.7, q), (q, 2), (v, p₀), (p₀, v), (v, V0), (V0, v), + (v, 0.7), (0.7, v), (ru, p₀), (p₀, ru), (ru, R0), (R0, ru), (ru, Ru(x[[2, 1, 4, 3]])), + (0.7, ru), (ru, 0.7), (v, ru), (ru, v), (q, ru), (qc, pc), (pc, qc), (qc, zc), + (zc, qc), (qc, 0.7), (q, pc), (pc, q), + ] + for f ∈ (+, -, *, /, \, add_fast, sub_fast, mul_fast, div_fast), (a, b) ∈ pairs + # Division by a `QuatVec` with a zero vector part is division by zero. + divisor = f ∈ (/, div_fast) ? b : f === (\) ? a : nothing + divisor isa QuatVec && !nonzerovec && continue + # The fast-math operations are checked with quaternion pairs and scalars only. + if f ∈ (add_fast, sub_fast, mul_fast, div_fast) + (a isa Rotor || b isa Rotor || a isa QuatVec || b isa QuatVec) && continue + end + checkrule(f, a, b; rtol=tol) + end + end + + @testset "Unary operations at $name" for (name, x) ∈ points() + tol = pointtol(name) + for q ∈ (Q(x), R(x), Ru(x), V(x), QCx(x)) + iszero(q) && continue + for f ∈ (-, conj, inv, sub_fast, inv_fast) + checkrule(f, q; rtol=tol) + end + end + end + + @testset "muladd at $name" for (name, x) ∈ points() + tol = pointtol(name) + q, ru = Q(x), Ru(x) + for (a, b, c) ∈ ((q, p₀, P0), (q, p₀, 0.4), (q, 0.4, p₀), (0.4, q, p₀), (q, 0.4, 0.3), + (0.4, q, 0.3), (0.4, 0.3, q), (ru, p₀, R0), (QCx(x), pc, zc)) + checkrule(muladd, a, b, c; rtol=tol) + end + end + + @testset "n-ary products and sums at $name" for (name, x) ∈ points() + tol = pointtol(name) + q, ru = Q(x), Ru(x) + # The frules of the n-ary operations are opted out (the 3-argument frule of + # ChainRules multiplies in the wrong order), so only the pullbacks are checked. + for f ∈ (*, +, mul_fast, add_fast) + for args ∈ ((q, p₀, P0), (2.0, q, p₀), (q, 2.0, p₀), (q, p₀, 2.0), (2.0, 3.0, q), + (2.0, 3.0, q, p₀), (q, p₀, q, P0), (0.5, q, 2.0, p₀, 3.0), (ru, R0, ru), + (QCx(x), pc, zc, 0.3)) + checkrule(f, args...; rtol=tol, pushforward=false) + end + end + # ChainRules' own rule for four or more factors reaches the fold rules through its + # recursion, also when the first quaternion is the fifth factor or later. + checkrule(*, 2.0, 3.0, 4.0, 5.0, q; rtol=tol, pushforward=false) + checkrule(*, 2.0, 3.0, 4.0, 5.0, 6.0, q, p₀; rtol=tol, pushforward=false) + checkrule(*, 0.3 + 0.1im, 2.0, 0.5im, QCx(x); rtol=tol, pushforward=false) + checkrule(*, 0.3 + 0.1im, 2.0, 0.5im, q, ru; rtol=tol, pushforward=false) + # The known gap of section 2 of the specification: when the first quaternion of a + # sum is its fourth argument or later, ChainRules' unprojected n-ary rule is reached, + # and the real arguments receive quaternion cotangents. Their scalar parts are + # correct. + Δ = quaternion(0.3, -1.1, 0.7, 0.5) + ∂ = map(unthunk, rrule(+, 2.0, 3.0, 4.0, q)[2](Δ)) + scalarpart(x) = x isa AbstractQuaternion ? x[1] : x + @test all(i -> scalarpart(∂[i]) ≈ Δ[1], 2:4) + @test ∂[5] ≈ Δ + end + + @testset "ChainRulesTestUtils, $T" for T ∈ (Float64, Float32, BigFloat) + xs = (T[1.2, -0.7, 0.5, 0.3], T[0.5, 0.3, -0.2, 0.4], T[-0.8, 0.6, 0.5, -0.7]) + q, p, r1, r2, v, t = Q(xs[1]), Q(xs[2]), Ru(xs[2]), Ru(xs[3]), V(xs[3]), T(7//10) + for f ∈ (+, -, *, /, \) + for (a, b) ∈ ((q, p), (q, t), (t, q), (v, q), (q, v), (r1, r2), (r1, q), (q, r1), + (t, r1), (v, r1), (r1, v)) + crtu(f, a, b) + end + end + for f ∈ (-, conj, inv), a ∈ (q, r1, v) + crtu(f, a) + end + crtu(muladd, q, p, r1) + crtu(muladd, t, q, p) + crtu(*, T(2), T(3), q, p; frule=false) + crtu(+, T(2), q, T(3), p; frule=false) + crtu(*, q, p, r1, v; frule=false) + if T === Float64 + qc = QCx(xs[1]) + pc′ = QCx(xs[2]) + for f ∈ (+, -, *, /), (a, b) ∈ ((qc, pc′), (qc, zc), (zc, qc), (q, pc′), (qc, 0.7)) + crtu(f, a, b) + end + for f ∈ (-, conj, inv) + crtu(f, qc) + end + end + end +end + + +@testitem "ChainRules: exp, log, and sqrt" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + import Base.FastMath: exp_fast, log_fast, sqrt_fast + + @testset "exp at $name" for (name, x) ∈ points() + tol = pointtol(name) + for q ∈ (Q(x), V(x), Ru(x), QCx(x), L([x[1] / 2; x[2:4]])) + checkrule(exp, q; rtol=tol) + end + checkrule(exp_fast, Q(x); rtol=tol) + end + @testset "exp near zero vector parts" begin + for ϵ ∈ (1e-3, 1e-6, 1e-12, 0.0) + checkrule(exp, quaternion(0.4, ϵ, -2ϵ, 3ϵ)) + checkrule(exp, quatvec(ϵ, -2ϵ, 3ϵ)) + checkrule(exp, QC([0.4, ϵ, 0, -ϵ, 0.1, 0, 2ϵ, 0])) + end + # On both sides of the series threshold (|v⃗|² = 1) + for a ∈ (0.999, 1.001) + checkrule(exp, quaternion(0.4, a, 0, 0)) + checkrule(exp, quatvec(a / √2, -a / √2, 0)) + end + end + + # `log` and `sqrt` of a `Rotor` evaluate formulas that agree only on the unit sphere on + # the two sides of w = 0, so a finite difference across w = 0 is meaningless unless the + # stored norm is exactly 1. The pure-vector point of the point set is normalized in + # floating point, so it is excluded for rotors, and the rotors at w = 0 are instead + # checked at points whose stored norm is exactly 1. + @testset "log and sqrt of rotors at w = 0" begin + for q ∈ (Rotor{Float64}(0, 1, 0, 0), Rotor{Float64}(0, 0, -1, 0), Rotor{Float64}(0, 0, 0, 1), + Rotor{Float64}(0, 0, 0, -1), Rotor{BigFloat}(0, 0, 1, 0)) + checkrule(log, q) + checkrule(sqrt, q) + end + end + @testset "log at $name" for (name, x) ∈ points(:nocut) + tol = pointtol(name) + checkrule(log, Q(x); rtol=tol) + checkrule(log_fast, Q(x); rtol=tol) + name === :purevector || checkrule(log, Ru(x); rtol=tol) + name === :purevector || checkrule(log, R(x); rtol=tol) + end + @testset "log near the positive real axis" begin + # On both sides of the series threshold a² = w²/16 + for a ∈ (0.2499, 0.2501, 1e-4, 1e-9) + checkrule(log, quaternion(1.0, a, 0, 0)) + checkrule(log, quaternion(2.0, 0, 2a, 0)) + checkrule(log, Rotor{Float64}(1.0, a, 0, 0)) + end + end + @testset "sqrt at $name" for (name, x) ∈ points(:nocut) + tol = pointtol(name) + checkrule(sqrt, Q(x); rtol=tol) + checkrule(sqrt_fast, Q(x); rtol=tol) + iszero(x[2:4]) || checkrule(sqrt, V(x); rtol=tol) + name === :purevector || checkrule(sqrt, Ru(x); rtol=tol) + name === :purevector || checkrule(sqrt, R(x); rtol=tol) + end + @testset "sqrt at extreme magnitudes" begin + # The source rescales by powers of two where the squared norm would overflow or + # underflow. The finite-difference step of the references is absolute, so instead + # the rules are checked against the homogeneity √(s q) = √s √q, with s a power of 2, + # which makes the Jacobian at s q equal to the Jacobian at q divided by √s. + Δ = quaternion(0.3, -1.1, 0.7, 0.5) + for q₀ ∈ (quaternion(1.2, -0.7, 0.5, 0.3), quaternion(-1.2, -0.7, 0.5, 0.3)), k ∈ (-1000, -560, -100, 100, 560, 1000) + s = 2.0^k + q = s * q₀ + ∂ = unthunk(rrule(sqrt, q)[2](Δ)[2]) + ∂₀ = unthunk(rrule(sqrt, q₀)[2](Δ)[2]) + @test ∂ ≈ ∂₀ / sqrt(s) rtol = 1e-14 + @test frule((NoTangent(), Δ), sqrt, q)[2] ≈ frule((NoTangent(), Δ), sqrt, q₀)[2] / sqrt(s) rtol = 1e-14 + end + end + + # On the negative real axis, the source returns log|w| + π𝐤 and √(-w) 𝐤, which depend + # only on w. The rules differentiate exactly that: the pushforward along w matches the + # finite difference along w, and the pullback has a zero vector part. + @testset "On the negative real axis" begin + e₁ = quaternion(1.0, 0, 0, 0) + Δ = quaternion(0.3, -1.1, 0.7, 0.5) + for f ∈ (log, sqrt), q ∈ (quaternion(-1.0, 0, 0, 0), quaternion(-4.0, 0, 0, 0), Rotor{Float64}(-1.0, 0, 0, 0)) + @testset "$f($q)" begin + Ω, Ω̇ = frule((NoTangent(), e₁), f, q) + @test Ω ≈ f(q) + Ω̇ref = bigjvp(f, q, e₁) + @test relerr(Ω̇, Ω̇ref) < 1e-12 + ∂ = unthunk(rrule(f, q)[2](Δ)[2]) + if ∂ isa AbstractZero + @test relerr(zero(Ω̇ref), Ω̇ref) < 1e-12 + else + @test ∂ isa Quaternion + @test ∂[1] ≈ Ω̇ref ⋅ Δ atol=1e-14 + @test iszero(∂[2]) && iszero(∂[3]) && iszero(∂[4]) + end + end + end + # log of a `Rotor` on the negative real axis is the constant π𝐤, whatever its norm. + for q ∈ (Rotor{Float64}(-1.0, 0, 0, 0), Rotor{Float64}(-2.0, 0, 0, 0)) + ∂ = unthunk(rrule(log, q)[2](quatvec(0.3, -1.1, 0.7))[2]) + @test ∂ isa AbstractZero || iszero(∂) + end + end + + @testset "ChainRulesTestUtils, $T" for T ∈ (Float64, Float32, BigFloat) + for xp ∈ (T[1.2, -0.7, 0.5, 0.3], T[0.5, 0.3, -0.2, 0.4], T[-0.8, 0.6, 0.5, -0.7]) + crtu(exp, Q(xp)) + crtu(exp, V(xp)) + crtu(exp, Ru(xp)) + crtu(log, Q(xp)) + crtu(log, Ru(xp)) + crtu(sqrt, Q(xp)) + crtu(sqrt, V(xp)) + crtu(sqrt, Ru(xp)) + end + T === Float64 && crtu(exp, QCx([1.2, -0.7, 0.5, 0.3])) + T === Float64 && crtu(exp, L([0.3, -0.7, 0.5, 0.3])) + end + # Ported from the retired `auto_differentiation.jl` + @testset "exp with given output tangents" begin + w, x, y, z = 1.2, 3.4, 5.6, 7.8 + crtu(exp, Quaternion(w, x, y, z); output_tangent=Quaternion(x, y, z, w)) + crtu(exp, QuatVec(x, y, z); output_tangent=Quaternion(x, y, z, w)) + end +end + + +@testitem "ChainRules: powers" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + import Base.FastMath: pow_fast + + @testset "Integer powers at $name" for (name, x) ∈ points() + tol = pointtol(name) + for n ∈ -3:3 + checkrule(^, Q(x), n; rtol=tol) + checkrule(^, Ru(x), n; rtol=tol) + checkrule(^, R(x), n; rtol=tol) + iszero(x[2:4]) || checkrule(^, V(x), n; rtol=tol) + checkrule(^, QCx(x), n; rtol=tol) + checkrule(pow_fast, Q(x), n; rtol=tol) + checkrule(Base.literal_pow, ^, Q(x), Val(n); rtol=tol) + checkrule(Base.literal_pow, ^, Ru(x), Val(n); rtol=tol) + end + end + + @testset "Real powers at $name" for (name, x) ∈ points(:nocut) + tol = pointtol(name) + for s ∈ (0.3, -1.7, 2//3) + checkrule(^, Q(x), s; rtol=tol) + checkrule(^, Ru(x), s; rtol=tol) + checkrule(^, R(x), s; rtol=tol) + iszero(x[2:4]) || checkrule(^, V(x), s; rtol=tol) + end + checkrule(pow_fast, Q(x), 0.3; rtol=tol) + checkrule(pow_fast, Ru(x), 0.3; rtol=tol) + # Large exponents of rotors near the identity, beyond the series in `y` + checkrule(^, Ru(x), 1e5; rtol=1e-8) + end + + @testset "Quaternion powers at $name" for (name, x) ∈ points(:nocut) + tol = pointtol(name) + checkrule(^, Q(x), P0; rtol=tol) + checkrule(^, Q(x), R0; rtol=tol) + checkrule(^, Q(x), V0; rtol=tol) + checkrule(^, Ru(x), P0; rtol=tol) + checkrule(^, 2.0, Q(x); rtol=tol) + checkrule(^, 0.7, Ru(x); rtol=tol) + checkrule(^, P0, Q(x); rtol=tol) + end + + @testset "Rotor powers at -1" begin + # At exactly -1, `R^s` is cos(πs) + sin(πs) 𝐤 for any norm, so the cotangent of the + # rotor is zero, and that of `s` is ⟨π𝐤 Ω, Δ⟩. + for q ∈ (Rotor{Float64}(-1.0, 0, 0, 0), Rotor{Float64}(-2.0, 0, 0, 0)), s ∈ (0.3, -1.7) + Ω, pb = rrule(^, q, s) + @test Ω ≈ q^s + Δ = quaternion(0.3, -1.1, 0.7, 0.5) + _, ∂q, ∂s = pb(Δ) + ∂q = unthunk(∂q) + @test ∂q isa AbstractZero || iszero(∂q) + @test unthunk(∂s) ≈ (π * 𝐤 * quaternion(Ω)) ⋅ Δ + @test unthunk(∂s) ≈ bigvjp(t -> q^t, s, Δ) + # Integer powers at -1 are exact products, differentiable in every direction. + checkrule(^, q, 3) + end + end + + @testset "ChainRulesTestUtils, $T" for T ∈ (Float64, Float32, BigFloat) + for xp ∈ (T[1.2, -0.7, 0.5, 0.3], T[0.5, 0.3, -0.2, 0.4], T[-0.8, 0.6, 0.5, -0.7]) + for n ∈ (-2, 0, 1, 3) + crtu(^, Q(xp), n) + crtu(^, Ru(xp), n) + crtu(^, V(xp), n) + end + crtu(^, Q(xp), T(3//10)) + crtu(^, Ru(xp), T(3//10)) + crtu(^, V(xp), T(3//10)) + crtu(^, Q(xp), Q(T[0.2, 0.3, -0.1, 0.4])) + crtu(^, T(2), Q(xp)) + crtu(Base.literal_pow, ^, Q(xp), Val(2)) + crtu(Base.literal_pow, ^, Ru(xp), Val(-1)) + end + end +end + + +@testitem "ChainRules: norms and geometry" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + import Base.FastMath: angle_fast + + @testset "Norms at $name" for (name, x) ∈ points() + tol = pointtol(name) + for q ∈ (Q(x), R(x), Ru(x), V(x), QCx(x), L([x[1] / 2; x[2:4]])) + checkrule(abs2, q; rtol=tol) + checkrule(abs2vec, q; rtol=tol) + checkrule(norm, q; rtol=tol) + iszero(q) || checkrule(abs, q; rtol=tol) + # `absvec` has a cone-shaped kink where the vector part vanishes. + iszero(x[2:4]) || checkrule(absvec, q; rtol=tol) + end + end + @testset "Norms of rotors are constant" begin + # `abs`, `abs2`, and (for real components) `norm` of a `Rotor` return 1 without + # reading the stored components, so their derivatives are zero, even off the sphere. + # The old Zygote tests asserted 2R for `abs2`, which was wrong. + for q ∈ (Ru([1.2, -0.7, 0.5, 0.3]), R([1.2, -0.7, 0.5, 0.3])), f ∈ (abs, abs2, norm) + ∂ = unthunk(rrule(f, q)[2](1.0)[2]) + @test ∂ isa AbstractZero || iszero(∂) + Ω̇ = unthunk(frule((NoTangent(), quaternion(0.3, 0.2, -0.1, 0.4)), f, q)[2]) + @test Ω̇ isa AbstractZero || iszero(Ω̇) + end + end + @testset "Subgradients at cone points" begin + # Where a norm vanishes, the cotangent is zero, as for `hypot`. + for q ∈ (quaternion(0.7, 0, 0, 0), quatvec(0.0, 0.0, 0.0), Rotor{Float64}(1, 0, 0, 0)) + ∂ = unthunk(rrule(absvec, q)[2](1.0)[2]) + @test ∂ isa AbstractZero || iszero(∂) + end + for q ∈ (quaternion(0.0, 0, 0, 0), quatvec(0.0, 0.0, 0.0)) + ∂ = unthunk(rrule(abs, q)[2](1.0)[2]) + @test ∂ isa AbstractZero || iszero(∂) + end + for q ∈ (quaternion(0.7, 0, 0, 0), Rotor{Float64}(1, 0, 0, 0), quaternion(-0.7, 0, 0, 0)) + ∂ = unthunk(rrule(angle, q)[2](1.0)[2]) + @test ∂ isa AbstractZero || iszero(∂) + end + end + + @testset "R(v) at $name" for (name, x) ∈ points() + tol = pointtol(name) + for r ∈ (R(x), Ru(x), L([x[1] / 2; x[2:4]])) + checkrule(r, V0; rtol=tol) + iszero(x[2:4]) || checkrule(r, V(x[[4, 3, 2, 1]]); rtol=tol) + end + checkrule(R0, V(x); rtol=tol) + end + + @testset "angle at $name" for (name, x) ∈ points(:nonreal) + tol = pointtol(name) + for q ∈ (Q(x), R(x), Ru(x)) + checkrule(angle, q; rtol=tol) + checkrule(angle_fast, q; rtol=tol) + end + end + + @testset "distance2 and distance at $name" for (name, x) ∈ points() + tol = pointtol(name) + for (a, b) ∈ ((R(x), R0), (R0, R(x)), (Ru(x), Ru([0.3, 0.1, -0.9, 0.2])), (Ru(x), Ru(-x))) + checkrule(distance2, a, b; rtol=tol) + distance(a, b) > 1e-6 && checkrule(distance, a, b; rtol=tol) + end + # At R₁ == R₂, distance2 is smooth with a zero gradient, and distance has a cone. + checkrule(distance2, R(x), R(x); rtol=tol) + checkrule(distance2, Ru(x), Ru(2x); rtol=tol) + ∂ = rrule(distance, R(x), R(x))[2](1.0) + @test all(d -> unthunk(d) isa AbstractZero || iszero(unthunk(d)), ∂[2:3]) + end + @testset "distance2 near the series threshold" begin + # The source switches to a series in x = a²/w² when x ≤ √√eps/2. + x₀ = sqrt(sqrt(eps(Float64))) / 2 + for x ∈ (0.99x₀, 1.01x₀, 1e-12, 1e-30) + a = sqrt(x) + checkrule(distance2, Rotor{Float64}(1.0, a, 0, 0), Rotor{Float64}(1.0, 0, 0, 0)) + checkrule(distance2, rotor(0.5, 0.2, -0.3, 0.1), rotor(0.5, 0.2, -0.3, 0.1) * rotor(1.0, 0, a, 0)) + end + end + + @testset "dot at $name" for (name, x) ∈ points() + tol = pointtol(name) + for (a, b) ∈ ((Q(x), P0), (P0, Q(x)), (Ru(x), R0), (V(x), V0), (Q(x), V0), (QCx(x), QCx(x[[2, 3, 4, 1]]))) + checkrule(dot, a, b; rtol=tol) + end + end + + @testset "ChainRulesTestUtils, $T" for T ∈ (Float64, Float32, BigFloat) + for xp ∈ (T[1.2, -0.7, 0.5, 0.3], T[0.5, 0.3, -0.2, 0.4], T[-0.8, 0.6, 0.5, -0.7]) + for q ∈ (Q(xp), Ru(xp), V(xp)) + for f ∈ (abs2, abs2vec, abs, absvec, norm) + crtu(f, q) + end + end + crtu(angle, Q(xp)) + crtu(angle, Ru(xp)) + crtu(Ru(xp), V(T[0, 0.3, -0.6, 0.2])) + crtu(distance2, Ru(xp), Ru(T[0.3, 0.1, -0.9, 0.2])) + crtu(distance, Ru(xp), Ru(T[0.3, 0.1, -0.9, 0.2])) + crtu(dot, Q(xp), Ru(T[0.3, 0.1, -0.9, 0.2])) + end + if T === Float64 + for f ∈ (abs2, abs, norm, abs2vec, absvec) + crtu(f, QCx([1.2, -0.7, 0.5, 0.3])) + end + crtu(dot, QCx([1.2, -0.7, 0.5, 0.3]), QCx([0.5, 0.3, -0.2, 0.4])) + crtu(L([0.3, -0.7, 0.5, 0.3]), V0) + end + end +end + + +@testitem "ChainRules: primitives that backends cannot trace" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + # `csqrt` is the complex square root, isolated so that Mooncake can import its rule. + for z ∈ (0.3 + 0.4im, -0.7 + 0.1im, -0.7 - 0.1im, 2.0 + 0.0im, 0.3f0 + 0.4f0im, complex(big"0.3", big"0.4")) + checkrule(Quaternionic.csqrt, z; rtol=max(eps(real(typeof(z)))^(3 / 4), 1e-40)) + crtu(Quaternionic.csqrt, z) + end + + # `dominant_eigenvector_lapack(A, uplo)` reads only the triangle of `A` named by `uplo`. + # The rules are checked with an asymmetric matrix, so that reading the wrong triangle is + # detected, at the Bar-Itzhack matrices of a generic rotation, of the identity, and of a + # rotation by π, whose dominant eigenvalues are simple. + using LinearAlgebra: Symmetric, I + using GenericLinearAlgebra + function baritzhack(R::Rotor) + M = to_rotation_matrix(R) + K = zeros(4, 4) + K[1, 1] = (M[1, 1] - M[2, 2] - M[3, 3]) / 3 + K[2, 2] = (M[2, 2] - M[1, 1] - M[3, 3]) / 3 + K[3, 3] = (M[3, 3] - M[1, 1] - M[2, 2]) / 3 + K[4, 4] = (M[1, 1] + M[2, 2] + M[3, 3]) / 3 + K[1, 2] = K[2, 1] = (M[2, 1] + M[1, 2]) / 3 + K[1, 3] = K[3, 1] = (M[3, 1] + M[1, 3]) / 3 + K[2, 3] = K[3, 2] = (M[3, 2] + M[2, 3]) / 3 + K[1, 4] = K[4, 1] = (M[2, 3] - M[3, 2]) / 3 + K[2, 4] = K[4, 2] = (M[3, 1] - M[1, 3]) / 3 + K[3, 4] = K[4, 3] = (M[1, 2] - M[2, 1]) / 3 + K + end + rng′ = MersenneTwister(7) + for R ∈ (R0, rotor(1.0, 0, 0, 0), rotor(0, 1.0, 0, 0)), uplo ∈ ('U', 'L'), T ∈ (Float64, Float32) + A = T.(baritzhack(R) + 0.01 * randn(rng′, 4, 4)) + f(A) = Quaternionic.dominant_eigenvector_lapack(A, uplo) + # The finite differences of ChainRulesTestUtils are too coarse in Float32 for LAPACK. + # Julia 1.10 cannot infer the type of the cotangent of `A` (the values are correct), + # so the inference check runs only on later versions. + T === Float64 && crtu( + Quaternionic.dominant_eigenvector_lapack, A, uplo ⊢ NoTangent(); + check_inferred=VERSION ≥ v"1.11" + ) + # The eigenvector is defined up to its sign, so the reference uses the eigenvector + # with the sign of the primal. + v = f(A) + ȳ = randn(rng′, T, 4) + _, pb = rrule(Quaternionic.dominant_eigenvector_lapack, A, uplo) + _, Ā, ū = pb(ȳ) + @test ū isa NoTangent + Ā = unthunk(Ā) + @test Ā isa Matrix{T} + # The entries outside the triangle named by `uplo` have zero cotangents. + outside = uplo == 'U' ? [i > j for i ∈ 1:4, j ∈ 1:4] : [i < j for i ∈ 1:4, j ∈ 1:4] + @test all(iszero, Ā[outside]) + # The references take the matrix as a vector of its entries, and they compute the + # eigenvector of the BigFloat matrix with GenericLinearAlgebra. + signed(a) = (v′ = Quaternionic.dominant_eigenvector(Symmetric(reshape(a, 4, 4), Symbol(uplo))); + sign(v′ ⋅ v) * v′) + @test relerr(vec(Ā), bigvjp(signed, vec(A), ȳ)) < (T === Float32 ? 1e-4 : 1e-10) + Ȧ = randn(rng′, T, 4, 4) + _, v̇ = frule((NoTangent(), Ȧ, NoTangent()), Quaternionic.dominant_eigenvector_lapack, A, uplo) + @test relerr(v̇, bigjvp(signed, vec(A), vec(Ȧ))) < (T === Float32 ? 1e-4 : 1e-10) + end +end + + +@testitem "ChainRules: cotangent forms" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + # Backends pass cotangents of quaternion outputs in many forms: Zygote's `real` rule + # passes a number, `q.components` gives a `Tangent` or `NamedTuple` of the `SVector`'s + # data, and arrays, tuples, thunks, `nothing`, and stray `Rotor`s or `QuatVec`s occur. + # Every pullback must accept each form and give the same result as for the equivalent + # `Quaternion`, without renormalizing a `Rotor`-typed cotangent. + a, b, c, d = 0.3, -1.1, 0.7, 0.5 + Δ = quaternion(a, b, c, d) + forms(T) = [ + Δ => Δ, + @thunk(Δ) => Δ, + Rotor{Float64}(a, b, c, d) => Δ, + quatvec(b, c, d) => quaternion(0.0, b, c, d), + a => quaternion(a, 0.0, 0.0, 0.0), + Tangent{T}(components=Tangent{SVector{4,Float64}}(data=(a, b, c, d))) => Δ, + (components=(data=(a, b, c, d),),) => Δ, + (a, b, c, d) => Δ, + (a, nothing, c, ZeroTangent()) => quaternion(a, 0.0, c, 0.0), + [a, b, c, d] => Δ, + SVector(a, b, c, d) => Δ, + ] + zeroforms = (nothing, ZeroTangent(), NoTangent(), @thunk(ZeroTangent()), (nothing, nothing, nothing, nothing)) + same(x, y) = (x = unthunk(x); y = unthunk(y); + (x isa AbstractZero && y isa AbstractZero) || (!(x isa AbstractZero) && !(y isa AbstractZero) && typeof(x) == typeof(y) && x ≈ y)) + iszerocot(x) = (x = unthunk(x); x isa AbstractZero) + + q, p, v = quaternion(1.2, -0.7, 0.5, 0.3), quaternion(0.3, 0.8, -0.4, 1.1), quatvec(0.3, -0.6, 0.2) + r1, r2 = Rotor{Float64}(0.5, 0.3, -0.2, 0.4), Rotor{Float64}(-0.8, 0.6, 0.5, -0.7) + cases = Any[ + (exp, (q,)), (exp, (v,)), (log, (q,)), (sqrt, (q,)), (inv, (q,)), (-, (q,)), (conj, (r1,)), + (*, (q, p)), (/, (q, p)), (*, (2.0, q)), (+, (q, 2.0)), (*, (r1, r2)), (/, (q, r1)), + (^, (q, 3)), (^, (q, 0.3)), (^, (r1, 0.3)), (^, (r1, 2)), (normalize, (q,)), (rotor, (q,)), + (quaternion, (1.2, -0.7, 0.5, 0.3)), (Quaternion{Float64}, (1.2, -0.7, 0.5, 0.3)), + (Rotor{Float64}, (1.2, -0.7, 0.5, 0.3)), (rotor, (1.2, -0.7, 0.5, 0.3)), + (quaternion, ([1.2, -0.7, 0.5, 0.3],)), (r1, (v,)), (muladd, (q, p, r1)), (*, (q, p, r1)), + ] + for (f, args) ∈ cases + @testset "$f$(map(typeof, args))" begin + Ω, pb = rrule(f, args...) + T = typeof(Ω) + for (form, equivalent) ∈ forms(T) + # A `QuatVec` output accepts the vector part of any form. + if Ω isa QuatVec + equivalent = quaternion(0.0, equivalent[2], equivalent[3], equivalent[4]) + end + expected = pb(equivalent) + @test all(map(same, pb(form), expected)) + end + for form ∈ zeroforms + @test all(iszerocot, pb(form)) + end + end + end + + # Scalar outputs accept thunks, `nothing`, and zeros. + for (f, args) ∈ ((abs2, (q,)), (abs, (q,)), (absvec, (q,)), (angle, (q,)), (dot, (q, p)), + (distance2, (r1, r2)), (real, (q,)), (getindex, (q, 2))) + pbs = rrule(f, args...)[2] + @test all(map(same, pbs(@thunk(0.7)), pbs(0.7))) + for form ∈ (nothing, ZeroTangent(), NoTangent()) + @test all(iszerocot, pbs(form)) + end + end + # A complex scalar output accepts the `Tangent` of a complex number. + pbc = rrule(abs2, QCx([1.2, -0.7, 0.5, 0.3]))[2] + @test all(map(same, pbc(Tangent{ComplexF64}(re=0.7, im=-0.2)), pbc(0.7 - 0.2im))) +end + + +@testitem "ChainRules: projection" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + q, r, v = quaternion(1.2, -0.7, 0.5, 0.3), Rotor{Float64}(0.5, 0.3, -0.2, 0.4), quatvec(0.3, -0.6, 0.2) + Δ = quaternion(0.3, -1.1, 0.7, 0.5) + + # The tangent of a `Quaternion` or `Rotor` is a `Quaternion`, never a renormalized `Rotor`. + @test ProjectTo(q)(Δ) === Δ + @test ProjectTo(r)(Rotor{Float64}(0.3, -1.1, 0.7, 0.5)) === Δ + @test ProjectTo(r)(Δ) === Δ + # The tangent of a `QuatVec` is a `QuatVec`, with any scalar part discarded. + @test ProjectTo(v)(Δ) === quatvec(-1.1, 0.7, 0.5) + @test ProjectTo(v)(Δ) isa QuatVec{Float64} + # The element type follows the precision of the primal, and integers get floats. + @test ProjectTo(quaternion(1.2f0, 0, 0, 0))(Δ) isa Quaternion{Float32} + @test ProjectTo(quaternion(big"1.2", 0, 0, 0))(big"0.5" * Δ) isa Quaternion{BigFloat} + @test ProjectTo(quaternion(1, 2, 3, 4))(Δ) === Δ + @test ProjectTo(quatvec(1, 2, 3))(Δ) === quatvec(-1.1, 0.7, 0.5) + # Real components project away the imaginary parts of complex cotangents; complex + # components keep them. + Δc = quaternion(0.3 + 0.1im, -1.1, 0.7im, 0.5) + @test ProjectTo(q)(Δc) === quaternion(0.3, -1.1, 0.0, 0.5) + @test ProjectTo(QCx([1.2, -0.7, 0.5, 0.3]))(Δc) === quaternion(0.3 + 0.1im, -1.1 + 0im, 0.0 + 0.7im, 0.5 + 0im) + # Quaternions with `Bool` components, such as 𝐢, are not differentiable. + @test ProjectTo(𝐢) isa ProjectTo{NoTangent} + @test ProjectTo(imz)(Δ) isa NoTangent + @test ProjectTo(quaternion(true, false, false, false))(Δ) isa NoTangent + # A real or complex primal that receives a quaternion cotangent keeps its scalar part. + @test ProjectTo(0.7)(Δ) === 0.3 + @test ProjectTo(0.7f0)(Δ) === 0.3f0 + @test ProjectTo(0.7 + 0.1im)(Δc) === 0.3 + 0.1im + @test ProjectTo(0.7)(Tangent{typeof(q)}(components=Tangent{SVector{4,Float64}}(data=(0.3, 1.0, 2.0, 3.0)))) === 0.3 + @test ProjectTo(true)(Δ) isa NoTangent + # Other forms of quaternion cotangents + @test ProjectTo(q)(0.7) === quaternion(0.7, 0.0, 0.0, 0.0) + @test ProjectTo(q)(Tangent{ComplexF64}(re=0.7, im=0.1)) === quaternion(0.7, 0.0, 0.0, 0.0) + @test ProjectTo(q)((0.3, -1.1, 0.7, 0.5)) === Δ + @test ProjectTo(q)((components=(data=(0.3, -1.1, 0.7, 0.5),),)) === Δ + @test ProjectTo(q)(Tangent{typeof(q)}(components=Tangent{SVector{4,Float64}}(data=(0.3, -1.1, 0.7, 0.5)))) === Δ + @test ProjectTo(q)([0.3, -1.1, 0.7, 0.5]) === Δ + @test ProjectTo(v)([0.3, -1.1, 0.7, 0.5]) === quatvec(-1.1, 0.7, 0.5) + @test ProjectTo(q)(ZeroTangent()) isa AbstractZero + @test ProjectTo(q)(NoTangent()) isa AbstractZero + # An array of quaternions projects elementwise. + @test ProjectTo([q, r])([Δ, Rotor{Float64}(0.3, -1.1, 0.7, 0.5)]) == [Δ, Δ] +end + + +@testitem "ChainRules: integer and Bool primals" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + # ChainRulesTestUtils cannot perturb quaternions with integer components (its finite + # differences rebuild them with integer components and throw an `InexactError`), so + # these rules are checked against the BigFloat references only. Integer quaternions + # have `Float64` tangents, while quaternions with `Bool` components (𝐢, 𝐣, and 𝐤) and + # integer or `Bool` scalars have `NoTangent()`. + qi, pi_, vi = quaternion(1, -2, 3, 4), quaternion(2, 0, 1, -1), quatvec(1, -2, 2) + q = quaternion(1.2, -0.7, 0.5, 0.3) + for f ∈ (+, -, *, /), (a, b) ∈ ((qi, pi_), (qi, q), (q, qi), (qi, 2), (2, qi), (qi, 0.7), (vi, qi), + (𝐢, q), (q, 𝐣), (𝐤, qi), (true, q), (q, true), (vi, 𝐢)) + checkrule(f, a, b) + end + for f ∈ (-, conj, inv, exp, abs2, abs, abs2vec, absvec, normalize, rotor, components, real, imag, vec) + checkrule(f, qi) + checkrule(f, vi) + end + for f ∈ (log, sqrt, angle) + checkrule(f, qi) + end + for n ∈ (-2, 2, 3) + checkrule(^, qi, n) + end + checkrule(^, qi, 0.3) + checkrule(getindex, qi, 3) + checkrule(dot, qi, pi_) + checkrule(muladd, qi, 2, q) + checkrule(*, qi, 2, q; pushforward=false) + checkrule(rotor(qi), vi) + # A real parameter combined with the constants 𝐢, 𝐣, and 𝐤 gets its own cotangent, and + # the constants get `NoTangent()`. + Δ = quaternion(0.3, -1.1, 0.7, 0.5) + for f ∈ (*, +, -, /) + _, ∂t, ∂j = rrule(f, 0.7, 𝐣)[2](Δ) + @test ∂j isa NoTangent + @test unthunk(∂t) isa Float64 + _, ∂j, ∂t = rrule(f, 𝐣, 0.7)[2](Δ) + @test ∂j isa NoTangent + @test unthunk(∂t) isa Float64 + end +end + + +@testitem "ChainRules: method ambiguities" tags=[:ad, :chainrules] begin + import ChainRulesCore, ChainRules + using Test + # Before Julia 1.9, Requires loads the rules into a submodule of Quaternionic. + ext = if isdefined(Base, :get_extension) + Base.get_extension(Quaternionic, :QuaternionicChainRulesCoreExt) + else + Quaternionic.QuaternionicChainRulesCoreExt + end + @test ext !== nothing + @test isempty(Test.detect_ambiguities(ext)) + if isdefined(Base, :get_extension) + import Zygote + zext = Base.get_extension(Quaternionic, :QuaternionicZygoteExt) + @test zext !== nothing + zext === nothing || @test isempty(Test.detect_ambiguities(zext)) + end +end + + +@testitem "ChainRules: method tables" tags=[:ad, :chainrules] begin + # Ported from the retired `auto_differentiation.jl`: every rule must make sense to + # ChainRulesCore. + using ChainRulesTestUtils + import ChainRules + test_method_tables() +end + + +@testitem "ChainRules: gradients through constructors under Zygote" tags=[:ad, :chainrules, :zygote] begin + # Ported from the retired `auto_differentiation.jl`, with every constructor variant. + # `abs2` of a `Rotor` is the constant 1, whatever its stored components, so its gradient + # is zero; the old tests asserted Zygote's former answer of 2R. A `QuatVec` discards its + # scalar part, so the gradient with respect to that argument is zero or `nothing`. As + # in the old tests, the `Quaternion` and `QuatVec` families are also differentiated with + # symbolic arguments, which are here variables rather than constants. + using Zygote + using StaticArrays: @SVector + using LinearAlgebra: I + import Symbolics + zeroish(g) = g === nothing || iszero(g) + small(T) = g -> g === nothing || abs(g) < 10eps(T) + same(g, e) = g ≈ e + same(g::Symbolics.Num, e) = iszero(Symbolics.simplify(g - e; expand=true)) + same(g::Nothing, e) = false + for T ∈ (BigFloat, Float64, Float32, Float16, Symbolics.Num) + @testset "$T" begin + if T === Symbolics.Num + w, x, y, z = Symbolics.@variables w x y z + else + w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) + end + for f ∈ ( + (a, b, c, d) -> abs2(Quaternion{T}(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(Quaternion{T}([a, b, c, d])), + (a, b, c, d) -> abs2(Quaternion{T}(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(Quaternion{T}(a, b, c, d)), + (a, b, c, d) -> abs2(quaternion(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(quaternion([a, b, c, d])), + (a, b, c, d) -> abs2(quaternion(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(quaternion(a, b, c, d)), + (a, b, c, d) -> abs2(Quaternion(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(Quaternion([a, b, c, d])), + (a, b, c, d) -> abs2(Quaternion(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(Quaternion(a, b, c, d)), + ) + @test all(map(same, Zygote.gradient(f, w, x, y, z), (2w, 2x, 2y, 2z))) + end + for f ∈ ( + (a, b, c, d) -> abs2(Quaternion{T}(b, c, d)), + (a, b, c, d) -> abs2(quaternion(b, c, d)), + (a, b, c, d) -> abs2(quaternion([b, c, d])), + (a, b, c, d) -> abs2(Quaternion(b, c, d)), + ) + ∇ = Zygote.gradient(f, w, x, y, z) + @test isnothing(∇[1]) && all(map(same, ∇[2:4], (2x, 2y, 2z))) + end + for f ∈ ( + (a, b, c, d) -> abs2(Quaternion{T}(a)), + (a, b, c, d) -> abs2(quaternion(a)), + (a, b, c, d) -> abs2(quaternion([a])), + (a, b, c, d) -> abs2(Quaternion(a)), + ) + ∇ = Zygote.gradient(f, w, x, y, z) + @test all(isnothing, ∇[2:4]) && same(∇[1], 2w) + end + + for f ∈ ( + (a, b, c, d) -> abs2(QuatVec{T}(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(QuatVec{T}([a, b, c, d])), + (a, b, c, d) -> abs2(QuatVec{T}(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(QuatVec{T}(a, b, c, d)), + (a, b, c, d) -> abs2(quatvec(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(quatvec([a, b, c, d])), + (a, b, c, d) -> abs2(quatvec(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(QuatVec(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(QuatVec([a, b, c, d])), + (a, b, c, d) -> abs2(QuatVec(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(quatvec(a, b, c, d)), + (a, b, c, d) -> abs2(QuatVec(a, b, c, d)), + (a, b, c, d) -> abs2(QuatVec{T}(b, c, d)), + (a, b, c, d) -> abs2(quatvec(b, c, d)), + (a, b, c, d) -> abs2(quatvec([b, c, d])), + (a, b, c, d) -> abs2(QuatVec(b, c, d)), + ) + ∇ = Zygote.gradient(f, w, x, y, z) + @test zeroish(∇[1]) && all(map(same, ∇[2:4], (2x, 2y, 2z))) + end + for f ∈ ( + (a, b, c, d) -> abs2(QuatVec{T}(a)), + (a, b, c, d) -> abs2(quatvec([a])), + (a, b, c, d) -> abs2(quatvec(a)), + (a, b, c, d) -> abs2(QuatVec(a)), + ) + @test all(zeroish, Zygote.gradient(f, w, x, y, z)) + end + + # `abs2` of any `Rotor` is constant. (The rotors are not checked symbolically, + # because normalization takes square roots.) + if T !== Symbolics.Num + for f ∈ ( + (a, b, c, d) -> abs2(Rotor{T}(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(Rotor{T}([a, b, c, d])), + (a, b, c, d) -> abs2(Rotor{T}(Rotor{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(Rotor{T}(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(Rotor{T}(a, b, c, d)), + (a, b, c, d) -> abs2(rotor(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(rotor([a, b, c, d])), + (a, b, c, d) -> abs2(rotor(Rotor{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(rotor(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(rotor(a, b, c, d)), + (a, b, c, d) -> abs2(Rotor(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(Rotor([a, b, c, d])), + (a, b, c, d) -> abs2(Rotor(Rotor{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(Rotor(Quaternion{T}(@SVector[a, b, c, d]))), + (a, b, c, d) -> abs2(Rotor(a, b, c, d)), + (a, b, c, d) -> abs2(Rotor{T}(b, c, d)), + (a, b, c, d) -> abs2(rotor(b, c, d)), + (a, b, c, d) -> abs2(rotor([b, c, d])), + (a, b, c, d) -> abs2(Rotor(b, c, d)), + (a, b, c, d) -> abs2(Rotor([b, c, d])), + (a, b, c, d) -> abs2(Rotor{T}(a)), + (a, b, c, d) -> abs2(rotor(a)), + (a, b, c, d) -> abs2(rotor([a])), + (a, b, c, d) -> abs2(Rotor(a)), + (a, b, c, d) -> abs2(Rotor([a])), + ) + @test all(zeroish, Zygote.gradient(f, w, x, y, z)) + end + # The sum of the squares of the normalized components is 1 to within roundoff, + # so its gradient is zero to within roundoff. + for f ∈ ( + (a, b, c, d) -> sum(abs2, components(rotor(a, b, c, d))), + (a, b, c, d) -> sum(abs2, components(rotor(b, c, d))), + (a, b, c, d) -> sum(abs2, components(rotor([a]))), + ) + @test all(small(T), Zygote.gradient(f, w, x, y, z)) + end + end + + # Jacobians of the components + if T ∈ (BigFloat, Float64) + J = Zygote.jacobian((w, x, y, z) -> components(Quaternion(w, x, y, z)), w, x, y, z) + @test all(J .== eachrow(Matrix{T}(I, 4, 4))) + J = Zygote.jacobian((w, x, y, z) -> components(QuatVec(w, x, y, z)), w, x, y, z) + @test all(J .== (T[0, 0, 0, 0], T[0, 1, 0, 0], T[0, 0, 1, 0], T[0, 0, 0, 1])) + n = √(w^2 + x^2 + y^2 + z^2) + J = Zygote.jacobian((w, x, y, z) -> components(Rotor(w, x, y, z)), w, x, y, z) + c = [w, x, y, z] + @test all(J[i] ≈ ([j == i for j ∈ 1:4] .- c[i] .* c ./ n^2) ./ n for i ∈ 1:4) + end + end + end +end + + +@testitem "ChainRules: series thresholds, folds of complex rotors, and irrational bases" tags=[:ad, :chainrules] setup=[ADTestUtils, RuleChecks] begin + # Near the identity, `R^s` evaluates the cosine and sinc of the angle sθ as series in + # y = (sθ)², below `trigseriestolerance`, and in closed form above it. For θ = 0.07, the + # exponents 1.49 and 1.51 lie on either side of the threshold. The rules are checked on + # and off the unit sphere. + θ = 0.07 + for Rθ ∈ (rotor(cos(θ), (sin(θ) .* NHAT)...), Rotor{Float64}(1.1cos(θ), (1.1sin(θ) .* NHAT)...)) + for s ∈ (1.49, 1.51) + checkrule(^, Rθ, s) + end + end + + # Products of complex rotors are renormalized only when the sum of the squared + # magnitudes of their components is below 16, which the fold rules for three or more + # factors and the rules for `muladd` mirror. `Rbig` is just below the threshold, and its + # products are above it. The frules of the folds are opted out. + Rbig = Rotor{ComplexF64}(2.9 + 0.4im, 1.3 - 1.2im, -1.5 + 0.05im, 0.2 + 1.3im) + Rsmall = Rotor{ComplexF64}(0.9 + 0.1im, 0.2 - 0.1im, -0.3 + 0.05im, 0.1 + 0.2im) + checkrule(*, Rbig, Rbig, Rbig; pushforward=false) + checkrule(*, Rsmall, Rsmall, Rsmall; pushforward=false) + checkrule(*, Rsmall, Rbig, Rsmall, Rbig; pushforward=false) + checkrule(muladd, Rbig, Rbig, Rsmall) + checkrule(muladd, Rsmall, Rsmall, Rbig) + @test frule((NoTangent(), Rbig, Rbig, Rbig), *, Rbig, Rbig, Rbig) === nothing + + # An irrational base, as in `π^q` and `ℯ^q`, once made the rules throw a `MethodError`. + q = quaternion(0.3, -0.2, 0.5, 0.1) + Δ = quaternion(0.3, -1.1, 0.7, 0.5) + @testset "$b^q" for b ∈ (π, ℯ) + Ω, pb = rrule(^, b, q) + @test Ω ≈ b^q + ∂ = pb(Δ) + @test unthunk(∂[2]) ≈ bigvjp(t -> t^q, Float64(b), Δ) + @test relerr(∂[3], bigvjp(p -> b^p, q, Δ), 0) < 1e-12 + Ω₂, Ω̇ = frule((NoTangent(), ZeroTangent(), Δ), ^, b, q) + @test Ω₂ ≈ b^q + @test relerr(Ω̇, bigjvp(p -> b^p, q, Δ), 0) < 1e-12 + end + + # `Quaternionic.value` is non-differentiable, and its rule must not be opted out. + @test rrule(Quaternionic.value, 1.0) !== nothing +end + + +@testitem "ChainRules: Zygote through irrational bases, complex exp, and literal powers" tags=[:ad, :chainrules, :zygote] setup=[ADTestUtils] begin + using Quaternionic + using Test + using .ADTestUtils + import Zygote, ForwardDiff + + # Gradients and Hessians of powers with an irrational base, against ForwardDiff on the + # source and against the BigFloat references + x4 = [0.3, -0.2, 0.5, 0.1] + @testset "$b^q" for b ∈ (π, ℯ) + f = x -> sc(b^quaternion(x...)) + @test relerr(Zygote.gradient(f, x4)[1], ForwardDiff.gradient(f, x4), 0) < 1e-13 + @test relerr(Zygote.gradient(f, x4)[1], bigfd(f, x4), 0) < 1e-13 + @test relerr(Zygote.hessian(f, x4), ForwardDiff.hessian(f, x4), 0) < 1e-12 + @test relerr(Zygote.hessian(f, x4), bigfdH(f, x4), 0) < 1e-12 + end + + # Hessians of `exp` of quaternions with complex components at a pure boost and at a + # quaternion whose complex vector part has a negative real square, through the rules + @testset "exp(QC(x)) at $x" for x ∈ ([0.1, 0, 0, 0, 0, 1.3, -0.8, 0.4], [1.0, 0, 0, 0, 0.2, 0, -0.3, 0]) + f = x -> sc(exp(QC(x))) + @test relerr(Zygote.hessian(f, x), bigfdH(f, x), 0) < 1e-12 + end + + # A literal power of a complex `Rotor`, whose rule returns `nothing` because the power + # is opted out, so that the Zygote extension differentiates `q^p` instead + x8 = [0.7, 0.3, -0.2, 0.4, 0.13, 0.1, 0.05, -0.2] + fpow = x -> sc(rotor(QC(x))^2) + @test relerr(Zygote.gradient(fpow, x8)[1], bigfd(fpow, x8), 0) < 1e-12 +end diff --git a/test/ad_testutils.jl b/test/ad_testutils.jl new file mode 100644 index 00000000..ca45ed66 --- /dev/null +++ b/test/ad_testutils.jl @@ -0,0 +1,615 @@ +# Shared utilities for the automatic-differentiation tests (the `ad_*.jl` files) +# +# Every test item that needs these utilities declares `setup=[ADTestUtils]` and then calls +# `using .ADTestUtils`, which brings every name listed below into scope. A test item that +# assigns one of these names itself (`R = ...`, for example) should instead import only what +# it uses, as in `using .ADTestUtils: bigfd, sc`. The interface is as follows. +# +# References, computed by central differences in 256-bit `BigFloat` arithmetic. None of +# them uses an AD backend, and their errors are far below Float64 roundoff (about 1e-47 +# relative to the function values for first derivatives and 1e-29 for the Hessian). +# +# bigfd(f, x::AbstractVector{<:Real}) Gradient of `f` (a `Vector`) if `f(x)` is real; +# otherwise the Jacobian (a `Matrix`) of +# `realcoords(f(x))` with respect to `x`. +# bigfd(f, t::Real) Derivative of `f` at `t`, in the tangent type of +# `f(t)` (a `Quaternion` for a `Rotor` output). +# bigfdH(f, x::AbstractVector{<:Real}) Hessian (a `Matrix`) of the real function `f`. +# bigjvp(f, args::Tuple, ẋs::Tuple) Directional derivative of `f(args...)` along the +# tangents `ẋs`, in the tangent type of the output: +# the reference for an `frule`. +# bigvjp(f, args::Tuple, ȳ) Cotangents (a `Tuple`, one per argument) pulled +# back from the output cotangent `ȳ`: the +# reference for an `rrule`. Integer, `Bool`, and +# non-numeric arguments get `NoTangent()`. +# bigjvp(f, x, ẋ), bigvjp(f, x, ȳ) The same for a single argument `x` that is not a +# `Tuple`; `bigvjp` then returns one cotangent. +# +# Each result is converted to the floating-point type of the corresponding output or +# argument at its original precision (`Float64` for `Float64` or integer input, +# `BigFloat` for `BigFloat` input). Arguments are perturbed in their own types, so a +# `Rotor{T}` argument stays an unnormalized `Rotor` and a `QuatVec` stays a `QuatVec`. +# +# Losses and comparisons +# +# sc(y) A fixed weighted sum of all the real coordinates of `y`: a real +# number, a complex number, a quaternion with real or complex +# components, or an array or tuple of these. It preserves the +# element type (`Float32`, `Dual`, `TrackedReal`, …). +# realcoords(y) The real coordinates of `y` as a `Vector`: 1 for a real number, 2 +# for a complex number, 4 (or 8 if complex) for a `Quaternion` or +# `Rotor`, 3 (or 6) for a `QuatVec`, concatenated for arrays and tuples. +# Complex components are listed as all real parts, then all imaginary +# parts. +# relerr(a, b, floor=1) +# `norm(a - b) / max(norm(b), floor)`, comparing numbers, quaternions, +# and arrays or tuples of them by their real coordinates. Thunks are +# unthunked; `NoTangent()`, `ZeroTangent()`, and `nothing` count as +# zeros of the other side's shape; a `Tangent` or `NamedTuple` is +# compared by its field values. With the default floor, the result is +# an absolute error wherever the reference is smaller than 1, which is +# true of many derivatives at :nearidentity and :nearminus1 (of order +# 1e-9 to 1e-7). To detect a relative error there, pass a small floor +# or 0. +# +# Builders, from consecutive entries of a real vector `x`, starting at index `i` (default 1) +# +# Q(x, i) quaternion(x[i], x[i+1], x[i+2], x[i+3]) +# R(x, i) rotor(x[i], …, x[i+3]), which normalizes +# Ru(x, i) Rotor{eltype(x)}(x[i], …, x[i+3]), which stores without normalizing +# V(x, i) quatvec(x[i+1], x[i+2], x[i+3]); `x[i]` is ignored, so that `V` takes the +# same four-entry points as the others (its derivative with respect to `x[i]` +# is zero) +# QC(x, i) Quaternion{Complex}: real parts x[i:i+3], imaginary parts x[i+4:i+7] +# L(x, i) Lorentz rotor Boost(x[i], NHAT) * Lorentz(rotor(1, x[i+1], x[i+2], x[i+3])), +# with a rapidity-form boost +# +# Constants +# +# P0, R0, V0, NHAT A fixed generic `Quaternion`, `Rotor`, `QuatVec`, and unit 3-vector +# (a `Vector{Float64}`), for the other argument of binary functions. +# +# Points: four-entry vectors, used as `x` for the builders above +# +# POINTS All points, as `name => x` pairs (a `Vector{Pair{Symbol,Vector{Float64}}}`): +# :generic [1.2, -0.7, 0.5, 0.3] (norm ≈ 1.5, so also off-sphere) +# :identity [1, 0, 0, 0] +# :nearidentity [1, 1e-9, -2e-9, 3e-9] +# :purevector [0, 0.6, -0.48, 0.64] (unit norm) +# :nearminus1 [-1, 1e-7, 2e-7, -1e-7] +# :minus1 [-1, 0, 0, 0] +# :offsphere [0.5, 0.3, -0.2, 0.4] (norm ≈ 0.73, w > 0) +# :offspherenegw [-0.8, 0.6, 0.5, -0.7] (norm ≈ 1.32, w < 0) +# points(kind=:all; exclude=()) The pairs of one kind, in the order above, minus +# points(T, kind=:all; exclude=()) the names in `exclude`, optionally converted to +# element type `T`. The kinds are +# :all every point +# :nocut not on the negative real axis (excludes :minus1), +# for `log`, `sqrt`, and non-integer powers +# :nonreal nonzero vector part (excludes :identity and :minus1), +# for `absvec`, `angle`, and the like +# :unit unit norm (:identity, :nearidentity, :purevector, +# :nearminus1, and :minus1, within 3e-14), where the +# values (not the derivatives) of `R(x)` and `Ru(x)` +# agree +# :offsphere norm different from 1 (:generic, :offsphere, and +# :offspherenegw), for `Ru` +# point(name) The vector of one point. +# +# Both `points` and `point` return fresh copies of the vectors, so that a test item may +# modify its point in place without changing the point set for later items. +# +# Random tangents for ChainRulesTestUtils +# +# This module adds one method, `ChainRulesTestUtils.rand_tangent(rng, ::AbstractQuaternion)`, +# which returns a `Quaternion` for a `Quaternion` or a `Rotor` (never a `Rotor`), a +# `QuatVec` for a `QuatVec`, and `NoTangent()` for `Bool` components (`𝐢`, `𝐣`, `𝐤`). The +# components are drawn with ChainRulesTestUtils' own methods (so complex components get +# complex tangents), after conversion to a floating-point type, so that integer +# components get `Float64` tangents, as `ProjectTo` gives them. The method is defined +# only here, once, because redefining `rand_tangent` in a running session has crashed it +# with SIGILL; no other test file may define it. Note that ChainRulesTestUtils' finite +# differences cannot perturb an integer-valued primal (FiniteDifferences rebuilds it with +# integer components and throws an `InexactError`), so rules with integer quaternion +# arguments are checked against `bigvjp` and `bigjvp` instead. + +@testmodule ADTestUtils begin + using Random: AbstractRNG + using LinearAlgebra: norm, normalize, dot + using Quaternionic + using ChainRulesCore: NoTangent, AbstractZero, AbstractThunk, Tangent, backing, unthunk + import ChainRulesTestUtils + + export bigfd, bigfdH, bigjvp, bigvjp, sc, realcoords, relerr + export Q, R, Ru, V, QC, L, P0, R0, V0, NHAT + export POINTS, points, point + + # ── Real coordinates ───────────────────────────────────────────────────────────────── + + # The finite-difference references treat every argument and output as a vector of + # real coordinates. The layout is fixed by a template value `t` of the primal type, + # and the coordinates are read from a value `x` with the same layout: the primal itself, + # a perturbed primal, or a tangent of it. A `Rotor` and a `Quaternion` both have four + # real coordinates (eight if complex), and a `QuatVec` has three (six if complex), + # because its scalar part is always zero. + + """ + ncoords(t) + + Return the number of real coordinates of a value with the type and shape of `t`. + """ + ncoords(::Real) = 1 + ncoords(::Complex) = 2 + ncoords(::AbstractQuaternion{<:Real}) = 4 + ncoords(::QuatVec{<:Real}) = 3 + ncoords(::AbstractQuaternion{<:Complex}) = 8 + ncoords(::QuatVec{<:Complex}) = 6 + ncoords(t::Union{AbstractArray,Tuple}) = sum(ncoords, t; init=0) + + """ + coords(t, x) + + Return the real coordinates of `x` as a `Vector`, in the layout of the template `t`. + Here, `x` is a value of the same type as `t`, or a tangent of it; a `Quaternion` tangent + of a `QuatVec` contributes only its vector part. A zero tangent (`NoTangent()`, + `ZeroTangent()`, or `nothing`) gives zero coordinates. + """ + coords(::Real, x::Real) = [x] + coords(::Complex, x::Number) = [real(x), imag(x)] + coords(::AbstractQuaternion{<:Real}, x::AbstractQuaternion) = [x[1], x[2], x[3], x[4]] + coords(::QuatVec{<:Real}, x::AbstractQuaternion) = [x[2], x[3], x[4]] + function coords(::AbstractQuaternion{<:Complex}, x::AbstractQuaternion) + c = components(x) + [real(c[1]), real(c[2]), real(c[3]), real(c[4]), + imag(c[1]), imag(c[2]), imag(c[3]), imag(c[4])] + end + function coords(::QuatVec{<:Complex}, x::AbstractQuaternion) + c = components(x) + [real(c[2]), real(c[3]), real(c[4]), imag(c[2]), imag(c[3]), imag(c[4])] + end + coords(t::Union{AbstractArray,Tuple}, x) = + reduce(vcat, [coords(tk, xk) for (tk, xk) in zip(t, x)]; init=Float64[]) + coords(t, ::Union{AbstractZero,Nothing}) = zeros(ncoords(t)) + coords(t::Union{AbstractArray,Tuple}, ::Union{AbstractZero,Nothing}) = zeros(ncoords(t)) + + """ + realcoords(y) + + Return the real coordinates of `y` as a `Vector`; see `coords`. + """ + realcoords(y) = coords(y, y) + + # The type that stores a perturbed primal with components of type `S`, and the type of + # a tangent with components of type `S`. A perturbed `Rotor` is stored without + # normalization, and the tangent of a `Rotor` is a `Quaternion`. + primaltype(::Quaternion, ::Type{S}) where {S} = Quaternion{S} + primaltype(::Rotor, ::Type{S}) where {S} = Rotor{S} + primaltype(::QuatVec, ::Type{S}) where {S} = QuatVec{S} + tangenttype(::AbstractQuaternion, ::Type{S}) where {S} = Quaternion{S} + tangenttype(::QuatVec, ::Type{S}) where {S} = QuatVec{S} + + """ + build(kind, t, c) + + Build a quaternion in the layout of the template `t` from its real coordinates `c`, + with the type `kind(t, S)`, where `S` is the component type and `kind` is `primaltype` + or `tangenttype`. + """ + build(kind, t::AbstractQuaternion{<:Real}, c) = kind(t, eltype(c))(c[1], c[2], c[3], c[4]) + build(kind, t::QuatVec{<:Real}, c) = kind(t, eltype(c))(c[1], c[2], c[3]) + build(kind, t::AbstractQuaternion{<:Complex}, c) = kind(t, Complex{eltype(c)})( + complex(c[1], c[5]), complex(c[2], c[6]), complex(c[3], c[7]), complex(c[4], c[8]) + ) + build(kind, t::QuatVec{<:Complex}, c) = kind(t, Complex{eltype(c)})( + complex(c[1], c[4]), complex(c[2], c[5]), complex(c[3], c[6]) + ) + + # Split the coordinates `c` of an array or tuple into one vector per entry of the + # template `t`. + function splitcoords(t, c) + ts = vec(collect(t)) + ends = cumsum([ncoords(tk) for tk in ts]) + [c[e-ncoords(tk)+1:e] for (tk, e) in zip(ts, ends)] + end + + """ + fromcoords(t, c) + + Return the value of the same type as the template `t` (but with components of the type + of `c`) whose real coordinates are `c`. An array is rebuilt as an `Array` of the same + shape. + """ + fromcoords(::Real, c) = c[1] + fromcoords(::Complex, c) = complex(c[1], c[2]) + fromcoords(t::AbstractQuaternion, c) = build(primaltype, t, c) + fromcoords(t::AbstractArray, c) = reshape(map(fromcoords, vec(collect(t)), splitcoords(t, c)), size(t)) + fromcoords(t::Tuple, c) = Tuple(map(fromcoords, collect(Any, t), splitcoords(t, c))) + + """ + tangentfromcoords(t, c) + + Return the tangent of the template `t` whose real coordinates are `c`, in the tangent + type of the ChainRules conventions: a `Quaternion` for a `Quaternion` or `Rotor`, and a + `QuatVec` for a `QuatVec`. + """ + tangentfromcoords(::Real, c) = c[1] + tangentfromcoords(::Complex, c) = complex(c[1], c[2]) + tangentfromcoords(t::AbstractQuaternion, c) = build(tangenttype, t, c) + tangentfromcoords(t::AbstractArray, c) = + reshape(map(tangentfromcoords, vec(collect(t)), splitcoords(t, c)), size(t)) + tangentfromcoords(t::Tuple, c) = Tuple(map(tangentfromcoords, collect(Any, t), splitcoords(t, c))) + + """ + isdifferentiable(x) + + Return `true` if the argument `x` is perturbed by the finite-difference references. + Integers, `Bool`s, quaternions with `Bool` components (the constants `𝐢`, `𝐣`, and + `𝐤`), and non-numeric values are not, in keeping with ChainRulesTestUtils, which gives + them `NoTangent()`. Quaternions with integer components are, because their tangents + are floating-point quaternions. + """ + isdifferentiable(::Any) = false + isdifferentiable(::Real) = true + isdifferentiable(::Integer) = false + isdifferentiable(::Complex) = true + isdifferentiable(::Complex{Bool}) = false + isdifferentiable(::AbstractQuaternion) = true + isdifferentiable(::AbstractQuaternion{Bool}) = false + isdifferentiable(a::AbstractArray) = !isempty(a) && all(isdifferentiable, a) + + """ + realtype(x) + + Return the floating-point type of the real coordinates of `x` at its own precision. + """ + realtype(x::Real) = float(typeof(x)) + realtype(x::Complex) = float(real(typeof(x))) + realtype(::AbstractQuaternion{T}) where {T} = realtype(zero(T)) + realtype(a::Union{AbstractArray,Tuple}) = + isempty(a) ? Float64 : mapreduce(realtype, promote_type, a) + + """ + tobig(x) + + Return `x` with its real coordinates converted to `BigFloat`, at the current precision, + if `x` is differentiable; otherwise return `x` unchanged. + """ + tobig(x) = isdifferentiable(x) ? fromcoords(x, BigFloat.(coords(x, x))) : x + + # ── Finite-difference references ───────────────────────────────────────────────────── + + const PRECISION = 256 + + # The first-derivative stencil is the fourth-order central difference with the step + # h = 2⁻¹⁰⁰ ≈ 8e-31, an exact power of two. Its truncation error is of order + # h⁴ f⁽⁵⁾ ≈ 4e-121 f⁽⁵⁾, and its rounding error is of order 2⁻²⁵⁶ |f| / h ≈ 1e-47 |f|. + # The Hessian stencil is the second-order central difference with h = 2⁻⁸⁰ ≈ 8e-25. Its + # truncation error is of order h² f⁗ ≈ 7e-49 f⁗, and its rounding error is of order + # 2⁻²⁵⁶ |f| / h² ≈ 1e-29 |f|. + const JVPSTEPEXPONENT = -100 + const HESSIANSTEPEXPONENT = -80 + + """ + coordjacobian(f, y, args, i) + + Return the Jacobian of the real coordinates of `f(args...)` with respect to the real + coordinates of `args[i]`, as a `Matrix{BigFloat}`, where `y = f(args...)` has already + been computed at the original precision. It must be called at 256-bit precision. + """ + function coordjacobian(f, y, args, i) + bigargs = map(tobig, args) + c = coords(args[i], bigargs[i]) + h = BigFloat(2)^JVPSTEPEXPONENT + columns = map(eachindex(c)) do k + function F(s) + ck = copy(c) + ck[k] += s + perturbed = ntuple(j -> j == i ? fromcoords(args[i], ck) : bigargs[j], length(args)) + coords(y, f(perturbed...)) + end + (8 .* (F(h) .- F(-h)) .- (F(2h) .- F(-2h))) ./ (12h) + end + isempty(columns) ? zeros(BigFloat, ncoords(y), 0) : reduce(hcat, columns) + end + + """ + bigjvp(f, args::Tuple, ẋs::Tuple) + bigjvp(f, x, ẋ) + + Return the directional derivative of `f(args...)` along the tangents `ẋs`, computed by + central differences in 256-bit arithmetic, as a tangent of the output: a `Quaternion` + for a `Quaternion` or `Rotor` output, a `QuatVec` for a `QuatVec` output, a real or + complex number for a scalar output, and an array or tuple of these for an array or + tuple output. The tangent of a `Rotor` argument is a `Quaternion`, and the tangents of + integer, `Bool`, and non-numeric arguments are ignored. The second form is for a single + argument `x` that is not a `Tuple`. + """ + function bigjvp(f, args::Tuple, ẋs::Tuple) + y = f(args...) + T = realtype(y) + D = setprecision(BigFloat, PRECISION) do + D = zeros(BigFloat, ncoords(y)) + for i in eachindex(args) + isdifferentiable(args[i]) || continue + ċ = BigFloat.(coords(args[i], ẋs[i])) + iszero(ċ) && continue + D .+= coordjacobian(f, y, args, i) * ċ + end + T.(D) + end + tangentfromcoords(y, D) + end + bigjvp(f, x, ẋ) = bigjvp(f, (x,), (ẋ,)) + + """ + bigvjp(f, args::Tuple, ȳ) + bigvjp(f, x, ȳ) + + Return the cotangents of the arguments of `f(args...)` pulled back from the cotangent + `ȳ` of its output, computed by central differences in 256-bit arithmetic, as a `Tuple` + with one entry per argument. This is the conjugate transpose of the Jacobian applied to + `ȳ`, as in ChainRules: each real coordinate of a cotangent is the real inner product of + `ȳ` with the derivative of the output along that coordinate. The cotangent of a + `Rotor` argument is a `Quaternion`, that of a `QuatVec` is a `QuatVec`, and that of an + integer, `Bool`, or non-numeric argument is `NoTangent()`. The second form is for a + single argument `x` that is not a `Tuple`, and returns its cotangent alone. + """ + function bigvjp(f, args::Tuple, ȳ) + y = f(args...) + cȳ = coords(y, ȳ) + ntuple(length(args)) do i + a = args[i] + isdifferentiable(a) || return NoTangent() + T = realtype(a) + g = setprecision(BigFloat, PRECISION) do + T.(transpose(coordjacobian(f, y, args, i)) * BigFloat.(cȳ)) + end + tangentfromcoords(a, g) + end + end + bigvjp(f, x, ȳ) = bigvjp(f, (x,), ȳ)[1] + + """ + bigfd(f, x::AbstractVector{<:Real}) + bigfd(f, t::Real) + + Return the derivative of `f`, computed by central differences in 256-bit arithmetic. + For a vector `x`, this is the gradient (a `Vector`) if `f(x)` is a real number, and + otherwise the Jacobian (a `Matrix` with one row per entry of `realcoords(f(x))`). For a + real number `t`, this is the derivative as a tangent of `f(t)`, as for `bigjvp`. The + result has the floating-point type of `f(x)` at its original precision. + """ + function bigfd(f, x::AbstractVector{<:Real}) + xf = float.(collect(x)) + y = f(xf) + T = realtype(y) + J = setprecision(BigFloat, PRECISION) do + T.(coordjacobian(f, y, (xf,), 1)) + end + y isa Real ? vec(J) : J + end + bigfd(f, t::Real) = bigjvp(f, (float(t),), (one(float(t)),)) + + """ + bigfdH(f, x::AbstractVector{<:Real}) + + Return the Hessian of the real function `f` at `x`, computed by central second + differences in 256-bit arithmetic, as a symmetric `Matrix` with the floating-point type + of `f(x)` at its original precision. + """ + function bigfdH(f, x::AbstractVector{<:Real}) + xf = float.(collect(x)) + y = f(xf) + y isa Real || throw(ArgumentError("bigfdH needs a real-valued function; got $(typeof(y))")) + T = realtype(y) + n = length(xf) + setprecision(BigFloat, PRECISION) do + xb = BigFloat.(xf) + h = BigFloat(2)^HESSIANSTEPEXPONENT + e(i) = (v = zeros(BigFloat, n); v[i] = h; v) + H = zeros(BigFloat, n, n) + for i in 1:n, j in i:n + H[i, j] = H[j, i] = ( + f(xb .+ e(i) .+ e(j)) - f(xb .+ e(i) .- e(j)) + - f(xb .- e(i) .+ e(j)) + f(xb .- e(i) .- e(j)) + ) / (4h^2) + end + T.(H) + end + end + + # ── Losses and comparisons ─────────────────────────────────────────────────────────── + + # The weights are ratios of integers, so that the loss has the element type of its + # argument: a `Float32` stays a `Float32`, and a `Dual` stays a `Dual`. The weights of + # the imaginary parts differ from those of the real parts, so that a derivative that + # confuses the two is detected. + + """ + sc(y) + + Return a fixed weighted sum of the real coordinates of `y`, which may be a real or + complex number, a quaternion with real or complex components, or an array or tuple of + these. This is the scalar loss of the AD tests. + """ + sc(x::Real) = x + sc(z::Complex) = real(z) + 37 * imag(z) / 100 + function sc(q::AbstractQuaternion{<:Real}) + c = components(q) + (3c[1] - 11c[2] + 7c[3] + 5c[4]) / 10 + end + function sc(q::AbstractQuaternion{<:Complex}) + c = components(q) + (3real(c[1]) - 11real(c[2]) + 7real(c[3]) + 5real(c[4]) + + 5imag(c[1]) + 7imag(c[2]) - 11imag(c[3]) + 3imag(c[4])) / 10 + end + # The entries of an array are weighted by 1, 9/8, 10/8, …, in linear-index order. The + # sum is an explicit loop, which every backend differentiates without any broadcast + # machinery. + function sc(a::AbstractArray) + s = sc(a[1]) + for k in 2:length(a) + s += (7 + k) * sc(a[k]) / 8 + end + s + end + # The entries of a tuple are weighted in the same way. + sc(t::Tuple) = sc(t, 1) + sc(::Tuple{}, ::Integer) = false + sc(t::Tuple, k) = (7 + k) * sc(first(t)) / 8 + sc(Base.tail(t), k + 1) + + """ + relerr(a, b, floor=1) + + Return the error of `a` relative to the reference `b`, as `norm(a - b) / max(norm(b), + floor)`, so that with the default floor a vanishing reference does not demand an exact + zero. Values are compared by their real coordinates, as given by `cmpvec`, and arrays + and tuples are compared entry by entry. Thunks are unthunked first, and a zero tangent + (`NoTangent()`, `ZeroTangent()`, or `nothing`) is compared as zeros of the shape of the + other side. A difference in shape throws a `DimensionMismatch`. If the denominator is + zero, the result is 0 when `a` equals `b` and `Inf` otherwise. + """ + function relerr(a, b, floor=1) + va, vb = pairedcoords(a, b) + e, d = norm(va .- vb), max(norm(vb), floor) + iszero(d) && return iszero(e) ? zero(e) : oftype(e, Inf) + e / d + end + + """ + pairedcoords(a, b) + + Return the real coordinates of `a` and of `b` as two `Vector`s of equal length, for + `relerr`. Arrays and tuples are paired entry by entry, and a zero tangent on one side + is replaced by zeros of the length of the other side. + """ + function pairedcoords(a, b) + a, b = unthunk(a), unthunk(b) + if a isa Union{AbstractArray,Tuple} && b isa Union{AbstractArray,Tuple} + length(a) == length(b) || throw(DimensionMismatch( + "cannot compare containers of lengths $(length(a)) and $(length(b))" + )) + pairs = [pairedcoords(ak, bk) for (ak, bk) in zip(a, b)] + return (reduce(vcat, first.(pairs); init=Float64[]), + reduce(vcat, last.(pairs); init=Float64[])) + end + va, vb = cmpvec(a), cmpvec(b) + isempty(va) && a isa Union{AbstractZero,Nothing} && (va = zero(vb)) + isempty(vb) && b isa Union{AbstractZero,Nothing} && (vb = zero(va)) + length(va) == length(vb) || throw(DimensionMismatch( + "cannot compare $(typeof(a)) with $(length(va)) coordinates " * + "and $(typeof(b)) with $(length(vb)) coordinates" + )) + va, vb + end + + # The real coordinates of a value, for comparisons: a `Rotor` or `QuatVec` gradient is + # compared by all four of its components, like a `Quaternion`. A structural tangent + # (a ChainRulesCore `Tangent` or a `NamedTuple`, such as Zygote may return for a + # quaternion) is compared by the coordinates of its field values, so that the tangent + # of a quaternion's `components` field is compared like the quaternion itself. + cmpvec(x::Real) = [x] + cmpvec(x::Complex) = [real(x), imag(x)] + cmpvec(q::AbstractQuaternion) = coords(quaternion(q), q) + cmpvec(a::Union{AbstractArray,Tuple}) = reduce(vcat, [cmpvec(x) for x in a]; init=Float64[]) + cmpvec(::Union{AbstractZero,Nothing}) = Float64[] + cmpvec(t::Tangent) = cmpvec(Tuple(values(backing(t)))) + cmpvec(t::NamedTuple) = cmpvec(Tuple(t)) + cmpvec(x::AbstractThunk) = cmpvec(unthunk(x)) + + # ── Builders and constants ─────────────────────────────────────────────────────────── + + """ + Q(x, i=1) + R(x, i=1) + Ru(x, i=1) + V(x, i=1) + QC(x, i=1) + L(x, i=1) + + Build a `Quaternion`, a normalized `Rotor`, an unnormalized `Rotor{eltype(x)}`, a + `QuatVec` (ignoring `x[i]`), a `Quaternion` with complex components (real parts + `x[i:i+3]` and imaginary parts `x[i+4:i+7]`), or a Lorentz rotor (a rapidity-form boost + of rapidity `x[i]` along `NHAT` times the rotor of `x[i+1:i+3]`) from consecutive + entries of `x`. + """ + Q(x, i=1) = quaternion(x[i], x[i+1], x[i+2], x[i+3]) + R(x, i=1) = rotor(x[i], x[i+1], x[i+2], x[i+3]) + Ru(x, i=1) = Rotor{eltype(x)}(x[i], x[i+1], x[i+2], x[i+3]) + V(x, i=1) = quatvec(x[i+1], x[i+2], x[i+3]) + QC(x, i=1) = quaternion( + complex(x[i], x[i+4]), complex(x[i+1], x[i+5]), + complex(x[i+2], x[i+6]), complex(x[i+3], x[i+7]) + ) + L(x, i=1) = Boost(x[i], NHAT) * Lorentz(rotor(one(eltype(x)), x[i+1], x[i+2], x[i+3])) + + const P0 = quaternion(-0.5, 0.2, 0.9, -1.3) + const R0 = rotor(0.4, -0.3, 0.8, 0.2) + const V0 = quatvec(0.3, -0.6, 0.2) + const NHAT = normalize([0.3, -0.5, 0.81]) + + # ── Points ─────────────────────────────────────────────────────────────────────────── + + const POINTS = Pair{Symbol,Vector{Float64}}[ + :generic => [1.2, -0.7, 0.5, 0.3], + :identity => [1.0, 0.0, 0.0, 0.0], + :nearidentity => [1.0, 1e-9, -2e-9, 3e-9], + :purevector => [0.0, 0.6, -0.48, 0.64], + :nearminus1 => [-1.0, 1e-7, 2e-7, -1e-7], + :minus1 => [-1.0, 0.0, 0.0, 0.0], + :offsphere => [0.5, 0.3, -0.2, 0.4], + :offspherenegw => [-0.8, 0.6, 0.5, -0.7], + ] + + const POINTKINDS = Dict{Symbol,Vector{Symbol}}( + :all => first.(POINTS), + :nocut => filter(!=(:minus1), first.(POINTS)), + :nonreal => filter(n -> n ∉ (:identity, :minus1), first.(POINTS)), + :unit => [:identity, :nearidentity, :purevector, :nearminus1, :minus1], + :offsphere => [:generic, :offsphere, :offspherenegw], + ) + + """ + points(kind=:all; exclude=()) + points(T, kind=:all; exclude=()) + + Return the points of the given kind as `name => x` pairs, in the order of `POINTS`, + without those whose names are in `exclude`, and with entries converted to `T` if it is + given. The kinds are `:all`, `:nocut` (not on the negative real axis), `:nonreal` + (nonzero vector part), `:unit` (unit norm), and `:offsphere` (norm different from 1). + """ + function points(kind::Symbol=:all; exclude=()) + haskey(POINTKINDS, kind) || throw(ArgumentError("unknown kind of point: $kind")) + for name in exclude + any(p -> p.first === name, POINTS) || throw(ArgumentError("unknown point: $name")) + end + names = POINTKINDS[kind] + [p.first => copy(p.second) for p in POINTS if p.first ∈ names && p.first ∉ exclude] + end + points(::Type{T}, kind::Symbol=:all; exclude=()) where {T} = + [p.first => T.(p.second) for p in points(kind; exclude=exclude)] + + """ + point(name) + + Return the vector of the point called `name` in `POINTS`. + """ + function point(name::Symbol) + i = findfirst(p -> p.first === name, POINTS) + i === nothing && throw(ArgumentError("unknown point: $name")) + copy(POINTS[i].second) + end + + # ── Random tangents for ChainRulesTestUtils ────────────────────────────────────────── + + # ChainRulesTestUtils' generic method for `Number`s calls `randn(rng, T)`, which gives a + # normalized `Rotor` for a `Rotor` and has no method for complex quaternions. This + # method replaces it for every quaternion type. It must be defined only once per + # session; see the comment at the top of this file. + function ChainRulesTestUtils.rand_tangent(rng::AbstractRNG, q::AbstractQuaternion) + isdifferentiable(q) || return NoTangent() + c = components(q) + t(k) = ChainRulesTestUtils.rand_tangent(rng, float(c[k])) + q isa QuatVec ? quatvec(t(2), t(3), t(4)) : quaternion(t(1), t(2), t(3), t(4)) + end +end diff --git a/test/ad_zygote.jl b/test/ad_zygote.jl new file mode 100644 index 00000000..f1e4ac8c --- /dev/null +++ b/test/ad_zygote.jl @@ -0,0 +1,512 @@ +# Tests of Zygote through the package's ChainRules rules and `QuaternionicZygoteExt`. Every +# gradient is compared with a central finite difference evaluated in 256-bit `BigFloat` +# arithmetic (`bigfd` from `ADTestUtils`), and ForwardDiff, which differentiates the source +# natively, is checked against the same reference. The cases are those of the sweep that +# validated the AD design, at the point set of `ADTestUtils`. + +@testsnippet ZygoteSweep begin + using Quaternionic + using Zygote, ForwardDiff + using Test + using .ADTestUtils: bigfd, bigfdH, relerr + + """ + zygote_gradient(f, x) + + Return Zygote's gradient of `f` at `x`, with `nothing` (Zygote's zero) replaced by a + vector of zeros. + """ + function zygote_gradient(f, x) + g = Zygote.gradient(f, x)[1] + return g === nothing ? zero(x) : g + end + + """ + sweep(name, f, pts; tol=1e-10, forwarddiff=true) + + Check the gradients of the real function `f` computed by Zygote (and by ForwardDiff, + unless `forwarddiff` is `false`) at each point `x` of the `name => x` pairs in `pts` + against `bigfd`, to the relative error `tol`. Each point is a separate test set, so + that an error at one point does not hide the results at the others. + """ + function sweep(name, f, pts; tol=1e-10, forwarddiff=true) + @testset "$name" begin + for (pname, x) ∈ pts + @testset "$name at $pname" begin + ref = bigfd(f, x) + g = zygote_gradient(f, x) + @test g isa AbstractVector{<:Real} + @test relerr(g, ref) < tol + if forwarddiff + @test relerr(ForwardDiff.gradient(f, x), ref) < tol + end + end + end + end + end + + """ + sweep(cases; kwargs...) + + Run `sweep(name, f, pts; kwargs...)` for each `(name, f, pts)` in `cases`. + """ + function sweep(cases; kwargs...) + for (name, f, pts) ∈ cases + sweep(name, f, pts; kwargs...) + end + end +end + + +@testitem "Zygote: arithmetic" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + pts = points() + sweep([ + ("q*p", x -> sc(Q(x) * P0), pts), + ("p*q", x -> sc(P0 * Q(x)), pts), + ("q/p", x -> sc(Q(x) / P0), pts), + ("p/q", x -> sc(P0 / Q(x)), pts), + ("q\\p", x -> sc(Q(x) \ P0), pts), + ("p\\q", x -> sc(P0 \ Q(x)), pts), + ("inv q", x -> sc(inv(Q(x))), pts), + ("q+p", x -> sc(Q(x) + P0), pts), + ("q-p", x -> sc(Q(x) - P0), pts), + ("-q", x -> sc(-Q(x)), pts), + ("conj q", x -> sc(conj(Q(x))), pts), + ("q/t", x -> sc(P0 / x[1] + Q(x) / x[1]), points(exclude=(:purevector,))), + ("t/q", x -> sc(x[1] / P0 * Q(x)), pts), + ("t/q 2", x -> sc(x[2] / Q(x)), pts), + ("real(t*q)", x -> real(x[1] * P0) + x[2]^2, pts), + ("t*q", x -> sc(x[1] * Q(x) * x[2]), pts), + ("q-t", x -> sc(Q(x) - x[2]) * sc(x[3] - Q(x)), pts), + ("muladd", x -> sc(muladd(Q(x), P0, x[2])), pts), + ("t*t*t*t*q", x -> sc(x[1] * x[2] * x[3] * x[4] * P0), pts), + ("t*t*t*q*p", x -> sc(x[1] * x[2] * x[3] * Q(x) * P0), pts), + ("2*3*4*q*p", x -> sc(2.0 * 3.0 * 4.0 * Q(x) * P0), pts), + ("q*p*q*p", x -> sc(Q(x) * P0 * Q(x) * P0), pts), + ("t+2t+3t+q", x -> sc(x[1] + 2x[2] + 3x[3] + Q(x)), pts), + ("t+q+p+t", x -> sc((x[1] + Q(x) + P0 + x[4]) * P0), pts), + ("fastmath", x -> sc(@fastmath x[1] * Q(x) + x[2]), pts), + ("fastmath division", x -> sc(@fastmath Q(x) / P0 - x[2] / Q(x)), pts), + ("exp(θ𝐣)", x -> sc(exp(x[1] * 𝐣 + x[2] * 𝐤)), pts), + ("θ+𝐣", x -> sc((x[1] + 𝐣) * Q(x)), pts), + ("θ-2𝐤", x -> sc(x[1] - 2𝐤), pts), + ("q*𝐢", x -> sc(Q(x) * 𝐢 + 𝐤 * Q(x)), pts), + ]) +end + + +@testitem "Zygote: Rotor algebra" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + pts = points() + sweep([ + ("R*R0", x -> sc(R(x) * R0), pts), + ("R0*R", x -> sc(R0 * R(x)), pts), + ("R0/R", x -> sc(R0 / R(x)), pts), + ("R/R0", x -> sc(R(x) / R0), pts), + ("inv R", x -> sc(inv(R(x))), pts), + ("conj R", x -> sc(conj(R(x))), pts), + ("R*R", x -> sc(R(x) * R(x)), pts), + ("R*P0", x -> sc(R(x) * P0), pts), + ("P0/R", x -> sc(P0 / R(x)), pts), + # Off the unit sphere, a `Rotor` stores its components without normalizing them, and + # the derivative is that of what the source computes from them. + ("Ru*R0", x -> sc(Ru(x) * R0), pts), + ("R0*Ru", x -> sc(R0 * Ru(x)), pts), + ("Ru*Ru", x -> sc(Ru(x) * Ru(x)), pts), + ("P0/Ru", x -> sc(P0 / Ru(x)), pts), + ("Ru/R0", x -> sc(Ru(x) / R0), pts), + ("R0/Ru", x -> sc(R0 / Ru(x)), pts), + ("2/Ru", x -> sc(2.0 / Ru(x)), pts), + ("V0/Ru", x -> sc(V0 / Ru(x)), pts), + ("inv Ru", x -> sc(inv(Ru(x))), pts), + ]) +end + + +@testitem "Zygote: exp, log, sqrt, and powers" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + pts, nocut = points(), points(:nocut) + # `log` and `sqrt` of a `Rotor` are discontinuous at w = 0 off the unit sphere, where + # finite differences do not apply, so the pure vector is excluded for `Ru`. + nocutu = points(:nocut; exclude=(:purevector,)) + sweep([ + ("exp q", x -> sc(exp(Q(x))), pts), + ("exp v", x -> sc(exp(V(x))), pts), + ("exp R", x -> sc(exp(R(x))), pts), + ("log q", x -> sc(log(Q(x))), nocut), + ("log R", x -> sc(log(R(x))), nocut), + ("log Ru", x -> sc(log(Ru(x))), nocutu), + ("sqrt q", x -> sc(sqrt(Q(x))), nocut), + ("sqrt R", x -> sc(sqrt(R(x))), nocut), + ("sqrt Ru", x -> sc(sqrt(Ru(x))), nocutu), + ("sqrt v", x -> sc(sqrt(V(x))), points(:nonreal)), + ("q^2", x -> sc(Q(x)^2), pts), + ("q^3", x -> sc(Q(x)^3), pts), + ("q^-2", x -> sc(Q(x)^-2), pts), + ("q^n", x -> sc(Q(x)^(-3) + Q(x)^0 + Q(x)^1 + Q(x)^4), pts), + ("v^2", x -> sc(V(x)^2), pts), + ("q^0.3", x -> sc(Q(x)^0.3), nocut), + ("q^t", x -> sc(Q(x)^(x[2] + 0.5)), nocut), + ("R^0.3", x -> sc(R(x)^0.3), nocut), + ("Ru^0.3", x -> sc(Ru(x)^0.3), nocutu), + ("R^3", x -> sc(R(x)^3), pts), + ("R^-2", x -> sc(R(x)^-2), pts), + ("Ru^2", x -> sc(Ru(x)^2), pts), + ("Ru^-1", x -> sc(Ru(x)^-1), pts), + ("q^P0", x -> sc(Q(x)^P0), nocut), + ("2^q", x -> sc(2.0^Q(x)), pts), + ("R0^q", x -> sc(R0^Q(x)), pts), + ]) +end + + +@testitem "Zygote: norms, normalization, and angles" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + using LinearAlgebra: normalize + pts, nonreal = points(), points(:nonreal) + sweep([ + ("abs", x -> abs(Q(x)), pts), + ("abs2", x -> abs2(Q(x)), pts), + ("abs v", x -> abs(V(x)), nonreal), + ("abs2 v", x -> abs2(V(x)), pts), + ("absvec", x -> absvec(Q(x)), nonreal), + ("abs2vec", x -> abs2vec(Q(x)), pts), + ("normalize", x -> sc(normalize(Q(x))), pts), + ("rotor", x -> sc(rotor(Q(x))), pts), + ("Rotor", x -> sc(Rotor(Q(x))), pts), + ("angle R", x -> angle(R(x)), nonreal), + ("angle q", x -> angle(Q(x)), nonreal), + ("q⋅p", x -> Q(x) ⋅ P0 + Q(x) ⋅ Q(x), pts), + ("abs2 R", x -> abs2(R(x)) + abs(Ru(x)), pts), + ]) +end + + +@testitem "Zygote: slerp, distance2, and rotations" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + pts = points() + sweep([ + ("slerp(R0,R)", x -> sc(slerp(R0, R(x), 0.3)), pts), + ("slerp(R,R0)", x -> sc(slerp(R(x), R0, 0.3)), pts), + ("slerp(R,R)", x -> sc(slerp(R(x), R(x), 0.3)), pts), + ("slerp τ", x -> sc(slerp(R0, R(x), x[1])), pts), + ("distance2", x -> distance2(R(x), R0), pts), + ("distance2 same", x -> distance2(R(x), R(x) * rotor(1.0, 1e-3, 0, 0)), pts), + ("distance2 q", x -> distance2(Q(x), P0), pts), + ("distance", x -> distance(R(x), R0), pts), + ("R(v)", x -> sc(R(x)(V0)), pts), + ("R(V(x))", x -> sc(R0(V(x))), pts), + ("RvR̄", x -> sc(R(x) * V0 * conj(R(x))), pts), + ]) +end + + +@testitem "Zygote: structure and conversion" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + pts = points() + W = [3, -11, 7, 5] ./ 10 + sweep([ + ("imag", x -> sum(imag(Q(x) * P0)), pts), + ("imag and w", x -> imag(Q(x))[1] * Q(x).w, pts), + ("vec", x -> sum(vec(Q(x) * P0) .* W[2:4]), pts), + ("components", x -> sum(Q(x).components .* W), pts), + ("components()", x -> sum(components(R(x) * P0) .* W), pts), + ("getindex", x -> (Q(x) * P0)[2] - 3 * (Q(x) * P0)[4], pts), + ("fields", x -> (Q(x) * P0).x + 2 * (V(x) * P0).w, pts), + ("to_float_array", x -> sum(to_float_array(Q(x) * P0) .* W), pts), + ("quaternion(vector)", x -> sc(quaternion(x) * P0), pts), + ("quatvec(vector)", x -> sc(quatvec(x[2:4]) * P0), pts), + ("rotor(vector)", x -> sc(rotor(x) * P0), pts), + ]) +end + + +@testitem "Zygote: broadcasting" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + pts = points() + sweep([ + ("bcast .*", x -> sc([Q(x), P0] .* [P0, Q(x)]), pts), + ("bcast ./", x -> sc([Q(x), P0] ./ [P0, Q(x)]), pts), + ("q .* qs", x -> sc(Q(x) .* [P0, Q(x)]), pts), + ("qs ./ q", x -> sc([P0, Q(x)] ./ Q(x)), pts), + ("qs .* ts", x -> sc([Q(x), P0] .* [x[2], 2.0]), pts), + ("ts ./ qs", x -> sc([x[2], 2.0] ./ [P0, Q(x)]), pts), + ("q .* ts", x -> sc(Q(x) .* [x[2], 2.0]), pts), + ("t .* qs", x -> sc(x[1] .* [Q(x), P0]), pts), + ("qs ./ t", x -> sc([Q(x), P0] ./ x[1]), points(exclude=(:purevector,))), + ("t * qs", x -> sc(x[1] * [Q(x), P0]), pts), + ("qs / t", x -> sc([Q(x), P0] / x[1]), points(exclude=(:purevector,))), + ("qs .* true", x -> sc([Q(x), P0] .* true) + sc(false .* [Q(x)]), pts), + ("qs .^ 2", x -> sc([Q(x), P0] .^ 2), pts), + ("qs .^ -1", x -> sc([Q(x), P0] .^ -1), pts), + ("abs2.(qs)", x -> sum(abs2.([Q(x), P0])), pts), + ("imag.(qs)", x -> sc(imag.([Q(x), P0 * Q(x)])), pts), + ("qs .+ t", x -> sc([Q(x), P0] .+ x[2]), pts), + ("conj.(qs)", x -> sc(conj.([Q(x), P0 * Q(x)])), pts), + ("real.(qs)", x -> sum(real.([Q(x), P0 * Q(x)])), pts), + ("map", x -> sc(map(q -> q * P0, [Q(x), R(x)])), pts), + ("sum", x -> sc(sum([Q(x), P0 * Q(x)])), pts), + ("prod", x -> sc(prod([Q(x), P0, Q(x)])), pts), + # A broadcast whose operands are all scalars computes the scalar call. + ("p .* q", x -> sc(P0 .* Q(x)), pts), + ("q .* p .* q", x -> sc(Q(x) .* P0 .* Q(x)), pts), + ("p ./ q", x -> sc(P0 ./ Q(x)), pts), + ("t ./ q", x -> sc(x[2] ./ Q(x)), pts), + ("q ./ t", x -> sc(Q(x) ./ x[1]), points(exclude=(:purevector,))), + ("q .^ 2", x -> sc(Q(x) .^ 2), pts), + ("q .^ 3", x -> sc(Q(x) .^ 3), pts), + ("q .^ -1", x -> sc(Q(x) .^ -1), pts), + ("abs2.(Ru)", x -> abs2.(Ru(x)) + abs2.(Q(x) * P0), pts), + ("imag.(q)", x -> sum(imag.(Q(x) * P0)), pts), + ("broadcast(*, t, p, q)", x -> sc(broadcast(*, x[1], P0, Q(x))), pts), + ("broadcast(*, R, R0, Ru)", x -> sc(broadcast(*, R(x), R0, Ru(x))), pts), + ("L .* B", x -> sc(L(x) .* Boost(0.2, NHAT) ./ L(x)), pts), + ("L .^ 2", x -> sc(L(x) .^ 2 + L(x) .^ -1), pts), + ]) +end + + +@testitem "Zygote: complex components and Lorentz rotors" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + pts = points() + # `C(x)` is a quaternion with complex components built from the four entries of a point. + C(x) = QC(vcat(x, [x[2] / 3, -x[3] / 2, x[4] / 5 + 0.2, x[1] / 4 - 0.1])) + B = Boost(0.2, NHAT) + # At `:minus1`, both `L(x)` and `C(x)` have negative real eigenvalues (as complex 2×2 + # matrices), so they lie on the branch cut of `log` and `sqrt`. + nocut = points(exclude=(:minus1,)) + sweep([ + ("Lorentz prod", x -> sc(L(x) * B), pts), + ("Lorentz quot", x -> sc(L(x) / B), pts), + ("Lorentz L*L", x -> sc(L(x) * L(x)), pts), + ("Lorentz literal powers", x -> sc(L(x)^2 + L(x)^-1 + L(x)^3), pts), + ("big boost prod", x -> sc(Boost(3.0 + x[1], NHAT) * Lorentz(rotor(1.0, x[2], x[3], x[4]))), pts), + ("complex log", x -> sc(log(L(x))), nocut), + ("complex sqrt", x -> sc(sqrt(L(x))), nocut), + ("complex abs", x -> sc(abs(quaternion(L(x)))), pts), + ("complex inv", x -> sc(inv(L(x))), pts), + ("Lorentz action", x -> sum(L(x)([1.0, 0.2, -0.3, 0.5])), pts), + ("complex q*p", x -> sc(C(x) * P0 + P0 * C(x)), pts), + ("complex q/p", x -> sc(C(x) / P0 + P0 / C(x)), pts), + ("complex inv q", x -> sc(inv(C(x))), pts), + ("complex exp", x -> sc(exp(C(x))), pts), + ("complex log q", x -> sc(log(C(x))), nocut), + ("complex sqrt q", x -> sc(sqrt(C(x))), nocut), + ("complex q^2", x -> sc(C(x)^2), pts), + ("complex abs2", x -> sc(abs2(C(x))), pts), + ("complex conj", x -> sc(conj(C(x)) * C(x)), pts), + ("complex t*q", x -> sc((x[2] + 0.5im) * C(x)), pts), + ("complex real and imag", x -> sc(real(C(x))) + sc(sum(imag(C(x)))), pts), + ]) +end + + +@testitem "Zygote: from_rotation_matrix and align" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + using ChainRulesCore: ignore_derivatives + # The sign of the result of `from_rotation_matrix` and `align` is arbitrary. Multiplying + # by the sign that matches the result to `R(x)` gives a smooth loss. The sign is + # treated as a constant. + signed(Ra, Rb) = ignore_derivatives() do + c, d = components(Ra), components(Rb) + sign(Quaternionic.value(c[1] * d[1] + c[2] * d[2] + c[3] * d[3] + c[4] * d[4])) + end + function frm(x) + Rf = from_rotation_matrix(to_rotation_matrix(R(x))) + return signed(Rf, R(x)) * sc(Rf) + end + a⃗ = [V0, quatvec(0.2, 0.9, -0.4), quatvec(-1.1, 0.1, 0.5)] + function aligned(x) + b⃗ = [R(x)(a) for a ∈ a⃗] + Ra = align(a⃗, b⃗) + return signed(Ra, R(x)) * sc(Ra) + end + sweep([ + ("from_rotation_matrix", frm, points()), + ("align", aligned, points()), + ]; tol=1e-9) +end + + +@testitem "Zygote: Hessians" tags=[:ad, :zygote] setup=[ADTestUtils, ZygoteSweep] begin + using .ADTestUtils + using LinearAlgebra: normalize + # `Zygote.hessian` is ForwardDiff over Zygote, so these run every pullback on `Dual`s. + pts = points(:nocut; exclude=(:nearminus1,)) + nonreal = points(:nonreal; exclude=(:nearminus1,)) + cases = [ + ("q*p", x -> sc(Q(x) * P0 * Q(x)), pts), + ("q/p", x -> sc(Q(x) / P0 + P0 / Q(x)), pts), + ("inv q", x -> sc(inv(Q(x))), pts), + ("t*q", x -> sc(x[1] * Q(x) + x[2] / Q(x)), pts), + ("exp q", x -> sc(exp(Q(x))), pts), + ("exp v", x -> sc(exp(V(x))), pts), + ("log q", x -> sc(log(Q(x))), pts), + ("sqrt q", x -> sc(sqrt(Q(x))), pts), + ("q^3", x -> sc(Q(x)^3), pts), + ("q^0.3", x -> sc(Q(x)^0.3), pts), + ("R^0.3", x -> sc(R(x)^0.3), pts), + ("R*R0", x -> sc(R(x) * R0 * R(x)), pts), + ("slerp(R0,R)", x -> sc(slerp(R0, R(x), 0.3)), pts), + ("slerp(R,R)", x -> sc(slerp(R(x), R(x), 0.3)), pts), + ("distance2", x -> distance2(R(x), R0), pts), + ("abs", x -> abs(Q(x)), pts), + ("angle R", x -> angle(R(x)), nonreal), + ("normalize", x -> sc(normalize(Q(x))), pts), + ("R(v)", x -> sc(R(x)(V0)), pts), + ("Lorentz prod", x -> sc(L(x) * L(x)), pts), + ] + for (name, f, ps) ∈ cases + @testset "$name" begin + for (pname, x) ∈ ps + @testset "$name at $pname" begin + ref = bigfdH(f, x) + @test relerr(Zygote.hessian(f, x), ref) < 1e-8 + @test relerr(ForwardDiff.hessian(f, x), ref) < 1e-8 + end + end + end + end +end + + +@testitem "Zygote: gradient types" tags=[:ad, :zygote] setup=[ADTestUtils] begin + using .ADTestUtils: sc, bigvjp, relerr, P0, R0, V0 + using Zygote + # A `Rotor` argument gets a `Quaternion` gradient, never a `Rotor` (which would be + # renormalized), and it is the ambient gradient of what the source computes. + f(r) = sc(r * P0) + g = Zygote.gradient(f, R0)[1] + @test g isa QuaternionF64 + @test relerr(g, bigvjp(f, R0, 1.0)) < 1e-12 + Ru0 = Rotor{Float64}(0.5, 0.3, -0.2, 0.4) + g = Zygote.gradient(r -> sc(log(r)), Ru0)[1] + @test g isa QuaternionF64 + @test relerr(g, bigvjp(r -> sc(log(r)), Ru0, 1.0)) < 1e-12 + # A `QuatVec` argument gets a `QuatVec` gradient. + h(v) = sc(exp(v)) + sc(v * P0) + g = Zygote.gradient(h, V0)[1] + @test g isa QuatVecF64 + @test relerr(g, bigvjp(h, V0, 1.0)) < 1e-12 + # A `Quaternion` argument gets a `Quaternion` gradient, and a `Float32` quaternion gets a + # `Float32` gradient. + g = Zygote.gradient(q -> sc(q * P0), P0)[1] + @test g isa QuaternionF64 + g = Zygote.gradient(q -> sc(q * q), quaternion(1.0f0, 2.0f0, -0.5f0, 0.25f0))[1] + @test g isa Quaternion{Float32} + # A real argument gets a real gradient, also when it is added to a quaternion. + for k ∈ (t -> sc(t * P0), t -> sc(t + P0), t -> sc(P0 - t), t -> sc(t / P0), + t -> sc(1.0 + 2.0 + t + P0), t -> sc(1.0 + 2.0 + 3.0 + t + P0)) + gk = Zygote.gradient(k, 0.3)[1] + @test gk isa Float64 + @test gk ≈ bigvjp(k, 0.3, 1.0) rtol=1e-12 + end + # The constants 𝐢, 𝐣, and 𝐤 have `Bool` components and no gradient, but functions that + # use them can be differentiated with respect to other arguments. + @test Zygote.gradient(c -> sc(c * P0), 𝐣)[1] === nothing + g = Zygote.gradient(θ -> sc(exp(θ * 𝐣)), 0.7)[1] + @test g ≈ (-3sin(0.7) + 7cos(0.7)) / 10 rtol=1e-14 + # `abs2` and `abs` of a `Rotor` are the constant 1, so their gradients are zero, even + # off the unit sphere. + for r ∈ (R0, Ru0) + @test let gr = Zygote.gradient(abs2, r)[1] + gr === nothing || iszero(gr) + end + @test let gr = Zygote.gradient(abs, r)[1] + gr === nothing || iszero(gr) + end + end + # The `imag` rule of Zygote's own number rules would give a complex vector here. + q = quaternion(1.2, -0.7, 0.5, 0.3) + @test Zygote.gradient(q -> imag(q)[1] * q.w, q)[1] ≈ quaternion(-0.7, 1.2, 0, 0) +end + + +@testitem "Zygote: constructors and components" tags=[:ad, :zygote] begin + # These checks are ported from the retired `auto_differentiation.jl`. + using Zygote + using StaticArrays: @SVector + using LinearAlgebra: I + iszeroish(g) = g === nothing || iszero(g) + for T ∈ (BigFloat, Float64, Float32) + w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) + J = Zygote.jacobian((w, x, y, z) -> components(Quaternion(w, x, y, z)), w, x, y, z) + @test all(J .== eachcol(Matrix{T}(I, 4, 4))) + J = Zygote.jacobian((w, x, y, z) -> components(QuatVec(w, x, y, z)), w, x, y, z) + @test iszero(J[1]) && all(J[2:4] .== eachcol(Matrix{T}(I, 4, 4))[2:4]) + n = √(w^2 + x^2 + y^2 + z^2) + J = Zygote.jacobian((w, x, y, z) -> components(Rotor(w, x, y, z)), w, x, y, z) + q = [w, x, y, z] + @test all(J[i] ≈ ([j == i for j ∈ 1:4] .- q[i] .* q ./ n^2) ./ n for i ∈ 1:4) + + # The gradient of `abs2` is checked through each constructor of `Quaternion`. + for f ∈ ( + (a, b, c, d) -> abs2(Quaternion{T}(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(Quaternion{T}([a, b, c, d])), + (a, b, c, d) -> abs2(Quaternion{T}(a, b, c, d)), + (a, b, c, d) -> abs2(quaternion(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(quaternion([a, b, c, d])), + (a, b, c, d) -> abs2(quaternion(a, b, c, d)), + (a, b, c, d) -> abs2(Quaternion([a, b, c, d])), + (a, b, c, d) -> abs2(Quaternion(a, b, c, d)), + ) + @test all(Zygote.gradient(f, w, x, y, z) .≈ (2w, 2x, 2y, 2z)) + end + for f ∈ ((a, b, c, d) -> abs2(quaternion(b, c, d)), (a, b, c, d) -> abs2(Quaternion([b, c, d]))) + ∇ = Zygote.gradient(f, w, x, y, z) + @test ∇[1] === nothing && all(∇[2:4] .≈ (2x, 2y, 2z)) + end + ∇ = Zygote.gradient((a, b, c, d) -> abs2(quaternion(a)), w, x, y, z) + @test ∇[1] ≈ 2w && all(isnothing, ∇[2:4]) + + # `abs2` of a `Rotor` is the constant 1, whatever its stored components. + for f ∈ ( + (a, b, c, d) -> abs2(Rotor{T}(a, b, c, d)), + (a, b, c, d) -> abs2(Rotor{T}([a, b, c, d])), + (a, b, c, d) -> abs2(rotor(a, b, c, d)), + (a, b, c, d) -> abs2(rotor([a, b, c, d])), + (a, b, c, d) -> abs2(Rotor(b, c, d)), + (a, b, c, d) -> abs2(rotor(a)), + ) + @test all(iszeroish, Zygote.gradient(f, w, x, y, z)) + end + # The norm of the normalized components is 1 to within roundoff, so its gradient is + # zero to within roundoff. + for f ∈ ((a, b, c, d) -> sum(abs2, components(rotor(a, b, c, d))), + (a, b, c, d) -> sum(abs2, components(rotor(b, c, d)))) + @test maximum(g -> g === nothing ? zero(T) : abs(g), Zygote.gradient(f, w, x, y, z)) < 10eps(T) + end + + # The gradient of `abs2` is checked through each constructor of `QuatVec`, which + # discards a scalar part. + for f ∈ ( + (a, b, c, d) -> abs2(QuatVec{T}(@SVector[a, b, c, d])), + (a, b, c, d) -> abs2(QuatVec{T}([a, b, c, d])), + (a, b, c, d) -> abs2(QuatVec{T}(a, b, c, d)), + (a, b, c, d) -> abs2(quatvec([a, b, c, d])), + (a, b, c, d) -> abs2(quatvec(a, b, c, d)), + (a, b, c, d) -> abs2(QuatVec(a, b, c, d)), + (a, b, c, d) -> abs2(quatvec(b, c, d)), + (a, b, c, d) -> abs2(QuatVec([b, c, d])), + ) + ∇ = Zygote.gradient(f, w, x, y, z) + @test iszeroish(∇[1]) && all(∇[2:4] .≈ (2x, 2y, 2z)) + end + @test all(iszeroish, Zygote.gradient((a, b, c, d) -> abs2(quatvec(a)), w, x, y, z)) + end +end + + +@testitem "Zygote: exp of a rotation generator" tags=[:ad, :zygote] begin + # Ported from the retired `auto_differentiation.jl`: rotating 𝐢 by θ about 𝐣 and + # projecting back onto 𝐢 gives cos θ. + using Zygote + for T ∈ (BigFloat, Float64, Float32, Float16) + f(θ) = exp((θ / 2) * 𝐣)(𝐢) ⋅ 𝐢 + for θ ∈ LinRange(0, 2T(π), 25) + @test f(θ) ≈ cos(θ) atol=10eps(T) + @test Zygote.gradient(f, θ)[1] ≈ -sin(θ) atol=10eps(T) + end + end +end diff --git a/test/algebra.jl b/test/algebra.jl index 630a5faf..d6032a99 100644 --- a/test/algebra.jl +++ b/test/algebra.jl @@ -3,6 +3,7 @@ module FundamentalTests using Test: @test using Quaternionic + import ..isapproxexpanded # Defined in runtests.jl # Algebra ## Vector space @@ -61,9 +62,9 @@ module FundamentalTests # Normed test_norm_maps_to_field(q::Quaternion) = @test typeof(abs2(q)) == basetype(q) test_norm_nondegenerate(v::Quaternion) = @test iszero(v) ⊻ !iszero(abs2(v)) - test_norm_quadratic(v::Quaternion) = @test abs2(2*v) ≈ 4*abs2(v) rtol=eps(v) - test_norm_quadratic(a, v::Quaternion) = @test abs2(a*v) ≈ a^2*abs2(v) rtol=eps(v) - test_norm_composition(x::Quaternion, y::Quaternion) = @test abs2(x*y) ≈ abs2(x)*abs2(y) rtol=eps(x) + test_norm_quadratic(v::Quaternion) = @test isapproxexpanded(abs2(2*v), 4*abs2(v); rtol=eps(v)) + test_norm_quadratic(a, v::Quaternion) = @test isapproxexpanded(abs2(a*v), a^2*abs2(v); rtol=eps(v)) + test_norm_composition(x::Quaternion, y::Quaternion) = @test isapproxexpanded(abs2(x*y), abs2(x)*abs2(y); rtol=eps(x)) # Associative test_associativity(u::Quaternion, v::Quaternion, w::Quaternion) = @test (u * v) * w ≈ u * (v * w) rtol=eps(v) @@ -85,10 +86,13 @@ end end f = getproperty(FundamentalTests, n) if !isempty(methods(f)) && startswith(string(f), "test_") - types = methods(f).ms[1].sig.parameters[2:end] - args = Base.Iterators.product([type===Any ? scalars : quaternions for type in types]...) - for arg in args - f(arg...) + # Some test functions have more than one method, so every method is run. + for m in methods(f) + types = m.sig.parameters[2:end] + args = Base.Iterators.product([type===Any ? scalars : quaternions for type in types]...) + for arg in args + f(arg...) + end end end end @@ -113,9 +117,12 @@ end if !isempty(methods(f)) && startswith(string(f), "test_") # ≈ with atol/rtol uses <= internally, which doesn't work for Symbolics.Num n === :test_involution_norm_imag && continue - types = methods(f).ms[1].sig.parameters[2:end] - args = [type===Any ? next_scalar!(chars) : next_quaternion!(chars) for type in types] - f(args...) + # Some test functions have more than one method, so every method is run. + for m in methods(f) + types = m.sig.parameters[2:end] + args = [type===Any ? next_scalar!(chars) : next_quaternion!(chars) for type in types] + f(args...) + end end end end diff --git a/test/alignment.jl b/test/alignment.jl index 00510942..43e411b1 100644 --- a/test/alignment.jl +++ b/test/alignment.jl @@ -1,8 +1,8 @@ @testset verbose=true "Alignment" begin Random.seed!(1234) - # `align` on `QuatVec`s goes through an eigen-decomposition, so it needs - # `GenericLinearAlgebra` (imported in runtests.jl) for non-LAPACK types. + # `align` on `QuatVec`s goes through an eigen-decomposition, which uses + # `GenericLinearAlgebra` (a dependency of Quaternionic) for non-LAPACK types. @testset verbose=true "Align QuatVec{$T}" for T in [Float16, Float32, Float64, Double64, BigFloat] for N in [1, 2, 3, 4, 5, 10, 20] a⃗ = randn(QuatVec{T}, N) diff --git a/test/auto_differentiation.jl b/test/auto_differentiation.jl deleted file mode 100644 index 63f94c7a..00000000 --- a/test/auto_differentiation.jl +++ /dev/null @@ -1,367 +0,0 @@ -@testset verbose=true "Auto Diff" begin - # Make sure everything makes sense to ChainRulesCore - test_method_tables() - - @testset "Quaternion $T rrules" for T ∈ (BigFloat, Float64, Float32) - ϵ = max(√eps(T), 1e-9) # Because Float64 is used internally by test_rrule - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - sv = @SVector[w,x,y,z] - v4 = [w,x,y,z] - v3 = [x,y,z] - v1 = [w] - test_rrule(Quaternion{T}, sv; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion, sv; rtol=ϵ, atol=ϵ) - test_rrule(quaternion, sv; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion{T}, v4; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion, v4; rtol=ϵ, atol=ϵ) - test_rrule(quaternion, v4; rtol=ϵ, atol=ϵ) - #test_rrule(Quaternion{T}, v3) # This method doesn't exist - test_rrule(Quaternion, v3; rtol=ϵ, atol=ϵ) - test_rrule(quaternion, v3; rtol=ϵ, atol=ϵ) - #test_rrule(Quaternion{T}, v1) # This method doesn't exist - test_rrule(Quaternion, v1; rtol=ϵ, atol=ϵ) - test_rrule(quaternion, v1; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion{T}, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(quaternion, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion{T}, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(quaternion, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion{T}, w; rtol=ϵ, atol=ϵ) - test_rrule(Quaternion, w; rtol=ϵ, atol=ϵ) - test_rrule(quaternion, w; rtol=ϵ, atol=ϵ) - @test_throws DimensionMismatch rrule(quaternion, T[1,2]) - end - @testset "Quaternion $T components" for T ∈ (BigFloat, Float64) - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - f(w,x,y,z) = components(Quaternion(w,x,y,z)) - @test all( - Zygote.jacobian(f, w, x, y, z) - .== - eachrow(Matrix{T}(LinearAlgebra.I, 4, 4)) - ) - end - @testset "abs2 Quaternion $T" for T ∈ [FloatTypes; SymbolicTypes] - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(Quaternion{T}(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(Quaternion{T}([a,b,c,d])), - (a,b,c,d)->abs2(Quaternion{T}(Quaternion{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(Quaternion{T}(a,b,c,d)), - - (a,b,c,d)->abs2(quaternion(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(quaternion([a,b,c,d])), - (a,b,c,d)->abs2(quaternion(Quaternion{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(quaternion(a,b,c,d)), - - (a,b,c,d)->abs2(Quaternion(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(Quaternion([a,b,c,d])), - (a,b,c,d)->abs2(Quaternion(Quaternion{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(Quaternion(a,b,c,d)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - #@info "A" i f(w, x, y, z) ∇ - @test all(∇ .≈ (2w, 2x, 2y, 2z)) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(Quaternion{T}(b,c,d)), - - (a,b,c,d)->abs2(quaternion(b,c,d)), - (a,b,c,d)->abs2(quaternion([b,c,d])), - - (a,b,c,d)->abs2(Quaternion(b,c,d)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test isnothing(∇[1]) && all(∇[2:4] .≈ (2x, 2y, 2z)) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(Quaternion{T}(a)), - - (a,b,c,d)->abs2(quaternion(a)), - (a,b,c,d)->abs2(quaternion([a])), - - (a,b,c,d)->abs2(Quaternion(a)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test all(isnothing, ∇[2:4]) && ∇[1] .≈ 2w - end - end - - @testset "Rotor $T rrules" for T ∈ (BigFloat, Float64, Float32) - ϵ = max(√eps(T), 1e-9) # Because Float64 is used internally by test_rrule - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - sv = @SVector[w,x,y,z] - v4 = [w,x,y,z] - v3 = [x,y,z] - v1 = [w] - test_rrule(Rotor{T}, sv; rtol=ϵ, atol=ϵ) - test_rrule(Rotor, sv; rtol=ϵ, atol=ϵ) - test_rrule(rotor, sv; rtol=ϵ, atol=ϵ) - test_rrule(Rotor{T}, v4; rtol=ϵ, atol=ϵ) - test_rrule(Rotor, v4; rtol=ϵ, atol=ϵ) - test_rrule(rotor, v4; rtol=ϵ, atol=ϵ) - #test_rrule(Rotor{T}, v3) # This method doesn't exist - test_rrule(Rotor, v3; rtol=ϵ, atol=ϵ) - test_rrule(rotor, v3; rtol=ϵ, atol=ϵ) - #test_rrule(Rotor{T}, v1) # This method doesn't exist - test_rrule(Rotor, v1; rtol=ϵ, atol=ϵ) - test_rrule(rotor, v1; rtol=ϵ, atol=ϵ) - test_rrule(Rotor{T}, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Rotor, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(rotor, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Rotor{T}, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Rotor, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(rotor, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(Rotor{T}, w; rtol=ϵ, atol=ϵ) - test_rrule(Rotor, w; rtol=ϵ, atol=ϵ) - test_rrule(rotor, w; rtol=ϵ, atol=ϵ) - @test_throws DimensionMismatch rrule(rotor, T[1,2]) - end - @testset "Rotor $T components" for T ∈ (BigFloat, Float64) - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - f(w,x,y,z) = components(Rotor(w,x,y,z)) - n = √(w^2 + x^2 + y^2 + z^2) - @test all( - Zygote.jacobian(f, w, x, y, z) - .≈ - ( - [(1 - w^2/n^2) / n, - w*x/n^3, - w*y/n^3, - w*z/n^3], - [- x*w/n^3, (1 - x^2/n^2) / n, - x*y/n^3, - x*z/n^3], - [- y*w/n^3, - y*x/n^3, (1 - y^2/n^2) / n, - y*z/n^3], - [- z*w/n^3, - z*x/n^3, - z*y/n^3, (1 - z^2/n^2) / n], - ) - ) - end - @testset "abs2 Rotor $T" for T ∈ FloatTypes - # Note that we can define - # f(a,b,c,d) = sum(abs2, @SVector[a,b,c,d] / √(a^2 + b^2 + c^2 + d^2)) - # g(a,b,c,d) = sum(abs2, @SVector[false,b,c,d] / √(b^2 + c^2 + d^2)) - # h(a,b,c,d) = sum(abs2, @SVector[a,false,false,false] / √(a^2)) - # And evaluate the gradients to give us guidance on what we expect to find - # when differentiating these functions for `rotor` and `Rotor`: - # Zygote.gradient(f, w, x, y, z) = (0.0, 0.0, 0.0, 0.0) - # Zygote.gradient(g, w, x, y, z) = (nothing, 0.0, 0.0, 0.0) - # Zygote.gradient(h, w, x, y, z) = (0.0, nothing, nothing, nothing) - # But remember that `Rotor{T}`` is basically the same as Quaternion{T} in - # this context. - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(Rotor{T}(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(Rotor{T}([a,b,c,d])), - (a,b,c,d)->abs2(Rotor{T}(Rotor{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(Rotor{T}(Quaternion{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(Rotor{T}(a,b,c,d)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test all(∇ .≈ (2w, 2x, 2y, 2z)) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(rotor(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(rotor([a,b,c,d])), - (a,b,c,d)->abs2(rotor(Rotor{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(rotor(Quaternion{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(rotor(a,b,c,d)), - - (a,b,c,d)->abs2(Rotor(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(Rotor([a,b,c,d])), - (a,b,c,d)->abs2(Rotor(Rotor{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(Rotor(Quaternion{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(Rotor(a,b,c,d)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test maximum(abs, ∇) < 10eps(T) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(Rotor{T}(b,c,d)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test isnothing(∇[1]) && all(∇[2:4] .≈ (2x, 2y, 2z)) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(rotor(b,c,d)), - (a,b,c,d)->abs2(rotor([b,c,d])), - - (a,b,c,d)->abs2(Rotor(b,c,d)), - (a,b,c,d)->abs2(Rotor([b,c,d])), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test isnothing(∇[1]) && maximum(abs, ∇[2:4]) < 10eps(T) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(Rotor{T}(a)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test ∇[1] .≈ 2w && all(isnothing, ∇[2:4]) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(rotor(a)), - (a,b,c,d)->abs2(rotor([a])), - - (a,b,c,d)->abs2(Rotor(a)), - (a,b,c,d)->abs2(Rotor([a])), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test abs(∇[1]) < 10eps(T) && all(isnothing, ∇[2:4]) - end - end - - @testset "QuatVec $T rrules" for T ∈ (BigFloat, Float64, Float32) - ϵ = max(√eps(T), 1e-9) # Because Float64 is used internally by test_rrule - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - sv = @SVector[w,x,y,z] - v4 = [w,x,y,z] - v3 = [x,y,z] - v1 = [w] - test_rrule(QuatVec{T}, sv; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec, sv; rtol=ϵ, atol=ϵ) - test_rrule(quatvec, sv; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec{T}, v4; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec, v4; rtol=ϵ, atol=ϵ) - test_rrule(quatvec, v4; rtol=ϵ, atol=ϵ) - #test_rrule(QuatVec{T}, v3) # This method doesn't exist - test_rrule(QuatVec, v3; rtol=ϵ, atol=ϵ) - test_rrule(quatvec, v3; rtol=ϵ, atol=ϵ) - #test_rrule(QuatVec{T}, v1) # This method doesn't exist - test_rrule(QuatVec, v1; rtol=ϵ, atol=ϵ) - test_rrule(quatvec, v1; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec{T}, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(quatvec, w, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec{T}, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(quatvec, x, y, z; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec{T}, w; rtol=ϵ, atol=ϵ) - test_rrule(QuatVec, w; rtol=ϵ, atol=ϵ) - test_rrule(quatvec, w; rtol=ϵ, atol=ϵ) - @test_throws DimensionMismatch rrule(quatvec, T[1,2]) - end - @testset "QuatVec $T components" for T ∈ (BigFloat, Float64) - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - f(w,x,y,z) = components(QuatVec(w,x,y,z)) - @test all( - Zygote.jacobian(f, w, x, y, z) - .== - ( - T[false, false, false, false], - T[false, true, false, false], - T[false, false, true, false], - T[false, false, false, true], - ) - ) - end - @testset "abs2 QuatVec $T" for T ∈ [FloatTypes; SymbolicTypes] - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(QuatVec{T}(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(QuatVec{T}([a,b,c,d])), - (a,b,c,d)->abs2(QuatVec{T}(Quaternion{T}(@SVector[a,b,c,d]))), - (a,b,c,d)->abs2(QuatVec{T}(a,b,c,d)), - - (a,b,c,d)->abs2(quatvec(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(quatvec([a,b,c,d])), - (a,b,c,d)->abs2(quatvec(Quaternion{T}(@SVector[a,b,c,d]))), - - (a,b,c,d)->abs2(QuatVec(@SVector[a,b,c,d])), - (a,b,c,d)->abs2(QuatVec([a,b,c,d])), - (a,b,c,d)->abs2(QuatVec(Quaternion{T}(@SVector[a,b,c,d]))), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test all(∇ .≈ (0, 2x, 2y, 2z)) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(quatvec(a,b,c,d)), - - (a,b,c,d)->abs2(QuatVec(a,b,c,d)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test isnothing(∇[1]) && all(∇[2:4] .≈ (2x, 2y, 2z)) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(QuatVec{T}(b,c,d)), - - (a,b,c,d)->abs2(quatvec(b,c,d)), - (a,b,c,d)->abs2(quatvec([b,c,d])), - - (a,b,c,d)->abs2(QuatVec(b,c,d)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test isnothing(∇[1]) && all(∇[2:4] .≈ (2x, 2y, 2z)) - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(QuatVec{T}(a)), - - (a,b,c,d)->abs2(quatvec([a])) - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test all(isnothing, ∇[2:4]) && ∇[1] .≈ 0 - end - for (i,f) ∈ enumerate([ - (a,b,c,d)->abs2(quatvec(a)), - - (a,b,c,d)->abs2(QuatVec(a)), - ]) - ∇ = Zygote.gradient(f, w, x, y, z) - @test all(isnothing, ∇) - end - end - - @testset "exp(Quaternion::$T) rrules" for T ∈ (Float64,)#(BigFloat, Float64, Float32) - ϵ = max(√eps(T), 1e-9) # Because Float64 is used internally by test_rrule - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - Q = Quaternion{T}(w,x,y,z) - R̄ = Quaternion{T}(x, y, z, w) - test_rrule(exp, Q; rtol=ϵ, atol=ϵ) - test_rrule(exp, Q ⊢ R̄; rtol=ϵ, atol=ϵ) - end - @testset "exp(QuatVec::$T) rrules" for T ∈ (Float64,)#(BigFloat, Float64, Float32) - ϵ = max(√eps(T), 1e-9) # Because Float64 is used internally by test_rrule - w, x, y, z = T(12//10), T(34//10), T(56//10), T(78//10) - v⃗ = QuatVec{T}(x,y,z) - R̄ = Quaternion{T}(x, y, z, w) - test_rrule(exp, v⃗; rtol=ϵ, atol=ϵ) - test_rrule(exp, v⃗ ⊢ R̄; rtol=ϵ, atol=ϵ) - end - @testset verbose=true "exp $T" for T ∈ FloatTypes - f(θ) = exp((θ / 2) * 𝐣)(𝐢) ⋅ 𝐢 # should equal cos(θ) - #f(θ) = (exp((θ / 2) * 𝐣)(𝐢))[2] # should equal cos(θ) - @test f(T(0)) ≈ 1 - @test Zygote.gradient(f, T(0))[1] ≈ -sin(T(0)) atol=10eps(T) - @test f(T(π)/2) ≈ 0 atol=10eps(T) - @test Zygote.gradient(f, T(π)/2)[1] ≈ -sin(T(π)/2) - @test f(T(π)) ≈ -1 - @test Zygote.gradient(f, T(π))[1] ≈ -sin(T(π)) atol=10eps(T) - @test f(3T(π)/2) ≈ 0 atol=10eps(T) - @test Zygote.gradient(f, 3T(π)/2)[1] ≈ -sin(3T(π)/2) - @test f(2T(π)) ≈ 1 - @test Zygote.gradient(f, 2T(π))[1] ≈ -sin(2T(π)) atol=10eps(T) - for θ ∈ LinRange(0, 2T(π), 100) - @test f(θ) ≈ cos(θ) atol=10eps(T) - @test Zygote.gradient(f, θ)[1] ≈ -sin(θ) atol=10eps(T) - end - - # for v̂ ∈ normalize.(randn(QuatVec{T}, 5)) - # g(t) = exp(t * v̂) # = cos(t) + v̂*sin(t) - # for t ∈ LinRange(0, 2T(π), 100) - # @test g(t) ≈ cos(t) + v̂*sin(t) - # @show Zygote.gradient(g, t) - # # @test Zygote.jacobian(g, t)[1] ≈ components(-sin(t) + v̂*cos(t)) - # end - # end - - # f(x,y,z) = exp(x*𝐢 + y*𝐣 + z*𝐤)(𝐢)[1:4] - # @test f(T(0), T(0), T(0)) ≈ T[0, 1, 0, 0] - - # g(x,y,z) = components(exp(x*𝐢 + y*𝐣 + z*𝐤)(𝐢)) - # @info "jacobian starting" - # @show Zygote.jacobian(g, T(0), T(0), T(0)) - end - - # @testset verbose=true "log" begin - # ∂log∂q(q) = [ - # ForwardDiff.derivative(ϵ->log(q+ϵ), 0), - # ForwardDiff.derivative(ϵ->log(q+ϵ*imx), 0), - # ForwardDiff.derivative(ϵ->log(q+ϵ*imy), 0), - # ForwardDiff.derivative(ϵ->log(q+ϵ*imz), 0) - # ] - # end -end diff --git a/test/base.jl b/test/base.jl index 309c82ec..a1336fde 100644 --- a/test/base.jl +++ b/test/base.jl @@ -60,8 +60,17 @@ for v ∈ basis @test !(quatvec(v) == one(T)) @test !(one(T) == quatvec(v)) - @test isequal(quatvec(v), v) - @test isequal(v, quatvec(v)) + if v === u + # `quatvec(u)` is the zero vector, which is not equal to `u`, because the + # scalar part of `u` is nonzero. + @test !(quatvec(v) == v) + @test !(v == quatvec(v)) + @test !isequal(quatvec(v), v) + @test !isequal(v, quatvec(v)) + else + @test isequal(quatvec(v), v) + @test isequal(v, quatvec(v)) + end @test isequal(quatvec(v), quatvec(v)) for (i_v,v′) ∈ enumerate(basis) if v !== v′ diff --git a/test/basis.jl b/test/basis.jl index 8048d1b3..e2350150 100644 --- a/test/basis.jl +++ b/test/basis.jl @@ -44,16 +44,24 @@ # Addition/subtraction for Q in [Quaternion, QuatVec] - # Define basis elements + # Define basis elements. A `QuatVec` has no scalar basis element, so + # `QuatVec{T}(1)` is the zero vector, and only the vector basis elements are used + # for `QuatVec` below. u = Q{T}(1) i = Q{T}(𝐢) j = Q{T}(𝐣) k = Q{T}(𝐤) basis = [u, i, j, k] + indices = Q === QuatVec ? (2:4) : (1:4) + if Q === QuatVec + @test iszero(u) + end # Basic self-addition/subtraction - @test u + u == 2u - @test u - u == 0u + if Q === Quaternion + @test u + u == 2u + @test u - u == 0u + end @test i + i == 2i @test i - i == 0i @test j + j == 2j @@ -62,8 +70,8 @@ @test k - k == 0k # Full addition/subtraction table - for i1 in 1:4 - for i2 in 1:4 + for i1 in indices + for i2 in indices a = zeros(T, 4) s = zeros(T, 4) a[i1] += one(T) @@ -79,12 +87,9 @@ # Symbolics.Num: normalize(q) returns e.g. 1/sqrt(1) which doesn't simplify # to 1 symbolically, so == comparisons fail for symbolic types. if !(T in SymbolicTypes) - for q in basis + for q in basis[indices] n = normalize(q) @test typeof(n) === Q{float(T)} - if Q === QuatVec && q == u - continue - end @test q == n @test q == normalize(2n) end diff --git a/test/compat16_smoke.jl b/test/compat16_smoke.jl new file mode 100644 index 00000000..2a6ebabb --- /dev/null +++ b/test/compat16_smoke.jl @@ -0,0 +1,117 @@ +# Smoke tests for the oldest Julia versions allowed by the compat bounds. +# +# The workspace test environment (test/Project.toml) cannot be instantiated on Julia +# versions before 1.9, so these checks run in a fresh environment instead. The CI job that +# uses this file runs, from the root of the package, +# +# julia -e 'using Pkg; Pkg.develop(path="."); Pkg.add(["ChainRulesCore", "ForwardDiff", "StaticArrays"])' +# julia test/compat16_smoke.jl +# +# The file is not included by test/runtests.jl, and it contains no test items. + +using Test +using Quaternionic +import Quaternionic: squad! +using ChainRulesCore, ForwardDiff, StaticArrays, LinearAlgebra, Random + +@testset "Julia $VERSION smoke tests" begin + Random.seed!(1) + q = quaternion(1.0, 2.0, 3.0, 4.0) + p = quaternion(-0.5, 0.25, 1.5, -2.0) + R = rotor(1, 2, 3, 4) + v = quatvec(1.0, -2.0, 0.5) + Rs = [rotor(1, 0.1i, 0.2, -0.1i) for i ∈ 1:5] + t = collect(1.0:5.0) + + @testset "Algebra" begin + @test q * inv(q) ≈ 1 + @test q / q == 1 + @test (q / p) * p ≈ q + @test quaternion(2e200, 0, 0, 0) / quaternion(1e200, 1e200, 0, 0) ≈ quaternion(1.0, -1.0, 0, 0) + @test typeof(R * 2.0) <: Quaternion + @test typeof(R + 1) <: Quaternion + @test typeof(R * (1 + 2im)) <: Quaternion + @test iszero(quatvec(quaternion(5, 1, 2, 3))[1]) + @test iszero(QuatVec(5.0, 1.0, 2.0, 3.0)[1]) + @test iszero(convert(QuatVecF64, quaternion(5.0, 1, 2, 3))[1]) + @test (v ⋅ v) ≈ abs2vec(v) + @test v × v == quatvec(0, 0, 0) + @test imx^2 == -1 + @test typeof(imx^3) == typeof(imx^2) + @test zero(QuatVecF64) == 0 + @test !isequal(quaternion(5, 1, 2, 3), quatvec(1, 2, 3)) + end + + @testset "Math functions" begin + @test exp(log(q)) ≈ q + @test sqrt(q)^2 ≈ q + @test sqrt(p)^2 ≈ p + @test sqrt(quaternion(1e300, 1e300, 0, 0))^2 ≈ quaternion(1e300, 1e300, 0, 0) + @test sqrt(quaternion(3e-310, 1e-310, 0, 0))^2 ≈ quaternion(3e-310, 1e-310, 0, 0) + @test log(quaternion(1e300, 1e300, 0, 0)) ≈ quaternion(log(sqrt(2) * 1e300), π / 4, 0, 0) + @test R^0.5 * R^0.5 ≈ R + @test R^3 ≈ R * R * R + @test R^0.5 isa Rotor + @test exp(big(1) * imx) ≈ cos(big(1)) + sin(big(1)) * imx + end + + @testset "Conversions" begin + @test from_rotation_matrix(to_rotation_matrix(R)) ≈ R + @test from_euler_angles(to_euler_angles(R)) ≈ R + @test from_euler_phases(to_euler_phases(R)) ≈ R + @test from_spherical_coordinates(to_spherical_coordinates(rotor(1, 0.2, -0.1, 0.3))) isa Rotor + @test from_float_array(to_float_array([q, p])) == [q, p] + @test sprint(show, quaternion(1, 2, 3, 4)) == "1 + 2𝐢 + 3𝐣 + 4𝐤" + @test sprint(show, MIME("text/plain"), R) isa String + end + + @testset "Distance, interpolation, and alignment" begin + @test distance(R, R) == 0 + @test distance2(rotor(1, 0, 0, 0), rotor(cos(0.1), sin(0.1), 0, 0)) ≈ 0.01 + @test slerp(R, -R, 0.0) ≈ R + @test all(squad(Rs, t, t) .≈ Rs) + out = similar(Rs, 3) + squad!(out, Rs, t, [1.5, 2.5, 3.5]) + @test out ≈ squad(Rs, t, [1.5, 2.5, 3.5]) + @test unflip([R, -R, R]) == [R, R, R] + A = [R, -R, R] + @test unflip!(A) === A + s, ∂s1, ∂s2, ∂sτ = slerp∂slerp(R, rotor(2, 1, 0, 1), 0.3) + @test s ≈ slerp(R, rotor(2, 1, 0, 1), 0.3) + L, dL = log∂log(R) + @test L ≈ log(R) + E, dE = exp∂exp(quatvec(0.1, 0.2, 0.3)) + @test E ≈ exp(quatvec(0.1, 0.2, 0.3)) + @test align([quatvec(1.0, 0, 0), quatvec(0, 1.0, 0)], [quatvec(0, 1.0, 0), quatvec(-1.0, 0, 0)]) isa Rotor + end + + @testset "ForwardDiff" begin + @test ForwardDiff.derivative(τ -> components(exp(τ * imx))[2], 0.0) ≈ 1 + @test ForwardDiff.derivative(τ -> components(log(rotor(cos(τ), sin(τ), 0, 0)))[2], 0.0) ≈ 1 + f(τ) = components(sqrt(quaternion(1.0 + τ, 2, 3, 4)))[1] + @test ForwardDiff.derivative(f, 0.1) ≈ (f(0.1 + 1e-6) - f(0.1 - 1e-6)) / 2e-6 rtol=1e-8 + g(x) = components(log(Quaternion(x...))) + x = [0.3, -0.5, 0.7, 0.2] + @test 1e160 * ForwardDiff.jacobian(g, 1e160 * x) ≈ ForwardDiff.jacobian(g, x) + end + + @testset "ChainRulesCore" begin + # Before Julia 1.9, Requires loads the extension when ChainRulesCore is loaded. + y, pullback = rrule(abs2, q) + @test y == abs2(q) + @test unthunk(pullback(1.0)[2]) ≈ 2q + y, pullback = rrule(distance2, R, rotor(2, 1, 0, 1)) + @test y ≈ distance2(R, rotor(2, 1, 0, 1)) + @test pullback(1.0)[2] isa Union{Rotor, Quaternion, AbstractThunk, Tangent} + end + + @testset "Lorentz and random" begin + B = Boost(quatvec(0.3, 0.0, 0.4)) + @test B([1.0, 0, 0, 0])[1] ≈ 1 / sqrt(1 - 0.25) + @test Quaternionic.RB(B * Lorentz(R))[1] isa Rotor + @test Lorentz(2.0) isa Rotor + @test randn(QuaternionF64) isa QuaternionF64 + @test randn(RotorF32) isa RotorF32 + @test iszero(randn(QuatVecF64)[1]) + end +end diff --git a/test/conversion.jl b/test/conversion.jl index a5df8765..4c9d8349 100644 --- a/test/conversion.jl +++ b/test/conversion.jl @@ -38,7 +38,7 @@ @testset "Euler angles" begin N = 5_000 - random_angles = [2π .* rand(T, 3) .- π for _ in 1:5000] + random_angles = [2π .* rand(T, 3) .- π for _ in 1:N] for i in 1:N α, β, γ = random_angles[i] q1 = from_euler_angles(α, β, γ) @@ -66,7 +66,7 @@ dumb_to_euler_phases(α, β, γ) = [exp(α*im), exp(β*im), exp(γ*im)] - random_angles = [[3(π*rand(T))-π, π*rand(T), 3(π*rand(T))-π] for _ in 1:5000] + random_angles = [[3(π*rand(T))-π, π*rand(T), 3(π*rand(T))-π] for _ in 1:N] for i in 1:N α, β, γ = random_angles[i] z1 = dumb_to_euler_phases(α, β, γ) @@ -135,7 +135,7 @@ @testset "Spherical coordinates" begin N = 5_000 - random_angles = [2π .* rand(T, 3) .- π for _ in 1:5000] + random_angles = [2π .* rand(T, 3) .- π for _ in 1:N] for i in 1:N α, β, γ = random_angles[i] q1 = from_spherical_coordinates(β, α) diff --git a/test/differentiation_interface.jl b/test/differentiation_interface.jl index cfdc1763..99dc1fd9 100644 --- a/test/differentiation_interface.jl +++ b/test/differentiation_interface.jl @@ -1,4 +1,4 @@ -@testitem "Differentiation Interface" begin +@testitem "Differentiation Interface" tags=[:ad] begin using DifferentiationInterface, DifferentiationInterfaceTest import Enzyme, FastDifferentiation, FiniteDifferences, ForwardDiff, Mooncake, @@ -14,8 +14,8 @@ AutoForwardDiff(); AutoMooncake(config=nothing); AutoReverseDiff(); - AutoZygote(); # Fails with incorrect results when return type is Quaternionic - AutoChainRules(Zygote.ZygoteRuleConfig()); # Same as above + AutoZygote(); + AutoChainRules(Zygote.ZygoteRuleConfig()); ] P = randn(QuaternionF64) @@ -58,7 +58,9 @@ # θ->θ[1] * vec(v⃗)[1], θ->vec(v⃗)[1] ), - # # Zygote doesn't work with constant functions + # # A constant function: DifferentiationInterface errors for Zygote and + # # AutoChainRules (whose gradients are `nothing` or `NoTangent()`), Enzyme (which + # # requests runtime activity), and FastDifferentiation. # ( # θ->Vector(components(Q)), # θ->Vector(components(0.0Q)) @@ -79,10 +81,6 @@ θ->Vector(components(Q - 1.2θ[1])), θ->Vector(components(0.0Q - 1.2)) ), - ( - θ -> real(1.2θ[1] + Q), - θ -> real(1.2 + 0.0Q) - ), ( θ->real(1.2θ[1] + Q), θ->real(1.2 + 0.0Q) @@ -109,6 +107,9 @@ ), ) + # The scenario of `absvec(θ * v⃗)`, whose kink at θ = 0 is skipped below + absvec_index = 6 + f∇f_conditionals = ( ( θ->Vector(components(exp(0 + θ[1] * v̂))), @@ -160,8 +161,7 @@ scenarios = [ Scenario{:derivative,:out}(f, θ; res1=∇f(θ)) for θ in x - for (i,(f, ∇f)) in enumerate(f∇f_conditionals) - if i≠6 || θ ≠ 0.0 # skip absvec at 0 because it's not differentiable there + for (f, ∇f) in f∇f_conditionals ] test_differentiation( backends, # the backends you want to compare @@ -175,7 +175,7 @@ Scenario{:derivative,:out}(f, θ; res1=∇f(θ)) for θ in x for (i,(f, ∇f)) in enumerate(f∇f_simple) - if i≠6 || θ ≠ 0.0 # skip absvec at 0 because it's not differentiable there + if i≠absvec_index || θ ≠ 0.0 # skip absvec at 0 because it's not differentiable there ] test_differentiation( [backends; AutoFastDifferentiation()], # the backends you want to compare diff --git a/test/fastmath.jl b/test/fastmath.jl index 83b7364c..8e99a69d 100644 --- a/test/fastmath.jl +++ b/test/fastmath.jl @@ -32,7 +32,10 @@ """ unit_norm(R) = isapprox(sum(abs2, components(R)), 1; rtol=10eps(Float32)) - const scalars = (2.0, 3, 1.5f0) + # The signed zeros, and the complex and rational scalars, make sure that the binary + # `add_fast` and `sub_fast` methods are needed: the promoting fallbacks in + # `Base.FastMath` give the same nonzero values, but can change the signs of zeros. + const scalars = (2.0, 3, 1.5f0, -0.0, 2.0 - 1.0im, 3//2, true) const quaternions = ( quaternion(1.0, 2.0, 3.0, 4.0), rotor(1.0, 2.0, 3.0, 4.0), @@ -40,6 +43,9 @@ quaternion(1.0f0, -2.0f0, 3.0f0, 0.5f0), rotor(-1.0f0, 2.0f0, 0.5f0, 4.0f0), quatvec(-1.0f0, 2.0f0, 0.5f0), + quaternion(-0.0, 0.0, -0.0, 0.0), + quatvec(-0.0, 0.0, -0.0), + Quaternion(1.0+1im, 2.0im, 0.0im, 1.0+0im), ) const values = (scalars..., quaternions...) end @@ -114,10 +120,8 @@ end @test matches(@fastmath(abs(q)), abs(q)) @test matches(@fastmath(abs2(q)), abs2(q)) @test matches(@fastmath(sqrt(q)), sqrt(q)) - # `exp` is not defined for a `Rotor`, nor `log` for a `QuatVec`. - if !(q isa Rotor) - @test matches(@fastmath(exp(q)), exp(q)) - end + @test matches(@fastmath(exp(q)), exp(q)) + # `log` is not defined for a `QuatVec`. if !(q isa QuatVec) @test matches(@fastmath(log(q)), log(q)) end diff --git a/test/gradients.jl b/test/gradients.jl index 46b62213..8d266129 100644 --- a/test/gradients.jl +++ b/test/gradients.jl @@ -20,13 +20,14 @@ @test ∂3[i] ≈ ∂2[i] rtol=ϵ end end + # At the identity, log(1 + δ) ≈ δ, so the gradient is [1, 𝐢, 𝐣, 𝐤]. ∂1 = ∂log(rotor(1)) - ∂2 = QuaternionF64[1, 0, 0, imz] + ∂2 = QuaternionF64[1, imx, imy, imz] for i in 1:4 @test ∂1[i] ≈ ∂2[i] rtol=ϵ end l, ∂1 = log∂log(rotor(1)) - ∂2 = QuaternionF64[1, 0, 0, imz] + ∂2 = QuaternionF64[1, imx, imy, imz] @test l ≈ QuaternionF64(0) rtol=4eps() atol=10eps() for i in 1:4 @test ∂1[i] ≈ ∂2[i] rtol=ϵ diff --git a/test/lorentz.jl b/test/lorentz.jl index 6ea5fde6..33dbbe7d 100644 --- a/test/lorentz.jl +++ b/test/lorentz.jl @@ -2,8 +2,9 @@ @testset "Lorentz/STA normalization" begin - # Use Float64 and Float32 only; Float16 lacks precision for cosh/sinh near the - # cancellation cosh² - sinh² = 1, and BigFloat is tested in algebra.jl. + # Use Float64 and Float32 only. Float16 lacks precision for cosh/sinh near the + # cancellation cosh² - sinh² = 1. Complex{BigFloat} is covered by the multi-precision + # items in lorentz_decomposition.jl and regressions_lorentz.jl, not here. LorentzTypes = [Float64, Float32] # ──────────────────────────────────────────────────────────────────────────────── @@ -514,252 +515,4 @@ end end - # ──────────────────────────────────────────────────────────────────────────────── - # 6. exp of boost bivectors - # - # A boost bivector in the x-direction is im*(φ/2)·𝐢, i.e. the QuatVec (0, im*φ/2, 0, 0). - # Exponentiating gives the boost rotor because cos(ix) = cosh(x) and sin(ix) = i·sinh(x): - # exp(im*φ/2·𝐢) = cosh(φ/2) + im·sinh(φ/2)·𝐢 - # ──────────────────────────────────────────────────────────────────────────────── - @testset "exp of boost bivectors, $T" for T in LorentzTypes - ϵ = 32eps(T) - - for φ ∈ T[0.5, 1.0, 1.5, 2.0] - ch, sh = cosh(φ/2), sinh(φ/2) - - # Boost in x: exp(im*φ/2·𝐢) = (cosh(φ/2), im·sinh(φ/2), 0, 0) - r_x = exp(QuatVec{Complex{T}}(im*T(φ/2), zero(Complex{T}), zero(Complex{T}))) - @test r_x[1] ≈ Complex{T}(ch) rtol=ϵ - @test r_x[2] ≈ Complex{T}(0, sh) rtol=ϵ - @test r_x[3] ≈ zero(Complex{T}) atol=ϵ - @test r_x[4] ≈ zero(Complex{T}) atol=ϵ - - # Boost in y: exp(im*φ/2·𝐣) = (cosh(φ/2), 0, im·sinh(φ/2), 0) - r_y = exp(QuatVec{Complex{T}}(zero(Complex{T}), im*T(φ/2), zero(Complex{T}))) - @test r_y[1] ≈ Complex{T}(ch) rtol=ϵ - @test r_y[2] ≈ zero(Complex{T}) atol=ϵ - @test r_y[3] ≈ Complex{T}(0, sh) rtol=ϵ - @test r_y[4] ≈ zero(Complex{T}) atol=ϵ - - # Boost in z: exp(im*φ/2·𝐤) = (cosh(φ/2), 0, 0, im·sinh(φ/2)) - r_z = exp(QuatVec{Complex{T}}(zero(Complex{T}), zero(Complex{T}), im*T(φ/2))) - @test r_z[1] ≈ Complex{T}(ch) rtol=ϵ - @test r_z[2] ≈ zero(Complex{T}) atol=ϵ - @test r_z[3] ≈ zero(Complex{T}) atol=ϵ - @test r_z[4] ≈ Complex{T}(0, sh) rtol=ϵ - end - end - - # ──────────────────────────────────────────────────────────────────────────────── - # 7. log of boost rotors - # - # The inverse of §6: log recovers the boost bivector. - # log(cosh(φ/2) + im·sinh(φ/2)·𝐢) = im*(φ/2)·𝐢 - # ──────────────────────────────────────────────────────────────────────────────── - @testset "log of boost rotors, $T" for T in LorentzTypes - ϵ = 32eps(T) - - for φ ∈ T[0.5, 1.0, 1.5, 2.0] - ch, sh = cosh(φ/2), sinh(φ/2) - - # Via Rotor type (log returns QuatVec) - lq_x = log(rotor(Complex{T}(ch), im*T(sh), zero(Complex{T}), zero(Complex{T}))) - @test lq_x[2] ≈ Complex{T}(0, φ/2) rtol=ϵ - @test lq_x[3] ≈ zero(Complex{T}) atol=ϵ - @test lq_x[4] ≈ zero(Complex{T}) atol=ϵ - - lq_y = log(rotor(Complex{T}(ch), zero(Complex{T}), im*T(sh), zero(Complex{T}))) - @test lq_y[2] ≈ zero(Complex{T}) atol=ϵ - @test lq_y[3] ≈ Complex{T}(0, φ/2) rtol=ϵ - @test lq_y[4] ≈ zero(Complex{T}) atol=ϵ - - lq_z = log(rotor(Complex{T}(ch), zero(Complex{T}), zero(Complex{T}), im*T(sh))) - @test lq_z[2] ≈ zero(Complex{T}) atol=ϵ - @test lq_z[3] ≈ zero(Complex{T}) atol=ϵ - @test lq_z[4] ≈ Complex{T}(0, φ/2) rtol=ϵ - - # Via Quaternion type (log returns Quaternion with zero scalar part) - q = Quaternion{Complex{T}}(Complex{T}(ch), im*T(sh), zero(Complex{T}), zero(Complex{T})) - lq = log(q) - @test lq[1] ≈ zero(Complex{T}) atol=ϵ - @test lq[2] ≈ Complex{T}(0, φ/2) rtol=ϵ - end - end - - # ──────────────────────────────────────────────────────────────────────────────── - # 8. exp/log round-trips - # - # exp(log(q)) ≈ q and log(exp(v)) ≈ v for boost and rotation rotors. - # ──────────────────────────────────────────────────────────────────────────────── - @testset "exp/log round-trips, $T" for T in LorentzTypes - ϵ = 128eps(T) - - for φ ∈ T[0.5, 1.0, 1.5, 2.0] - ch, sh = cosh(φ/2), sinh(φ/2) - - q = Quaternion{Complex{T}}(Complex{T}(ch), im*T(sh), zero(Complex{T}), zero(Complex{T})) - eq = exp(log(q)) - @test eq[1] ≈ q[1] rtol=ϵ - @test eq[2] ≈ q[2] rtol=ϵ - @test eq[3] ≈ q[3] atol=ϵ - @test eq[4] ≈ q[4] atol=ϵ - - v = QuatVec{Complex{T}}(im*T(φ/2), zero(Complex{T}), zero(Complex{T})) - lv = log(exp(v)) - @test lv[2] ≈ Complex{T}(0, φ/2) rtol=ϵ - @test lv[3] ≈ zero(Complex{T}) atol=ϵ - @test lv[4] ≈ zero(Complex{T}) atol=ϵ - end - - for θ ∈ T[π/7, π/4, π/3, 2π/3] - c, s = cos(θ/2), sin(θ/2) - q = Quaternion{Complex{T}}(Complex{T}(c), zero(Complex{T}), zero(Complex{T}), Complex{T}(s)) - eq = exp(log(q)) - @test eq[1] ≈ q[1] rtol=ϵ - @test eq[4] ≈ q[4] rtol=ϵ - end - end - - # ──────────────────────────────────────────────────────────────────────────────── - # 9. sqrt of boost and rotation rotors - # - # sqrt(boost(φ)) = boost(φ/2) and sqrt(rotation(θ)) = rotation(θ/2). - # Equivalently, sqrt(q)^2 ≈ q. - # ──────────────────────────────────────────────────────────────────────────────── - @testset "sqrt of boost and rotation rotors, $T" for T in LorentzTypes - ϵ = 64eps(T) - - for φ ∈ T[0.5, 1.0, 1.5, 2.0] - ch4, sh4 = cosh(φ/4), sinh(φ/4) # half-rapidity - q = Quaternion{Complex{T}}(Complex{T}(cosh(φ/2)), im*T(sinh(φ/2)), zero(Complex{T}), zero(Complex{T})) - sq = sqrt(q) - @test sq[1] ≈ Complex{T}(ch4) rtol=ϵ - @test sq[2] ≈ Complex{T}(0, sh4) rtol=ϵ - @test sq[3] ≈ zero(Complex{T}) atol=ϵ - @test sq[4] ≈ zero(Complex{T}) atol=ϵ - - sq2 = sq * sq - @test sq2[1] ≈ q[1] rtol=ϵ - @test sq2[2] ≈ q[2] rtol=ϵ - @test sq2[3] ≈ q[3] atol=ϵ - @test sq2[4] ≈ q[4] atol=ϵ - end - - for θ ∈ T[π/7, π/4, π/3, 2π/3] - q = Quaternion{Complex{T}}(Complex{T}(cos(θ/2)), zero(Complex{T}), zero(Complex{T}), Complex{T}(sin(θ/2))) - sq = sqrt(q) - @test sq[1] ≈ Complex{T}(cos(θ/4)) rtol=ϵ - @test sq[4] ≈ Complex{T}(sin(θ/4)) rtol=ϵ - - sq2 = sq * sq - @test sq2[1] ≈ q[1] rtol=ϵ - @test sq2[4] ≈ q[4] rtol=ϵ - end - end - - # ──────────────────────────────────────────────────────────────────────────────── - # 10. inv of unit complexified quaternions - # - # For a unit spinor norm, inv(q) = conj(q): the scalar is unchanged and the vector - # components are negated — without conjugating the complex coefficients. - # Therefore q * inv(q) = inv(q) * q = 1. - # ──────────────────────────────────────────────────────────────────────────────── - @testset "inv of unit complexified quaternions, $T" for T in LorentzTypes - ϵ = 32eps(T) - - for φ ∈ T[0.5, 1.0, 1.5, 2.0] - q = Quaternion{Complex{T}}(Complex{T}(cosh(φ/2)), im*T(sinh(φ/2)), zero(Complex{T}), zero(Complex{T})) - qi = inv(q) - @test qi[1] ≈ q[1] rtol=ϵ # scalar unchanged - @test qi[2] ≈ -q[2] rtol=ϵ # vector negated (not complex-conjugated) - @test qi[3] ≈ -q[3] atol=ϵ - @test qi[4] ≈ -q[4] atol=ϵ - - for r ∈ [qi * q, q * qi] - @test r[1] ≈ one(Complex{T}) rtol=ϵ - @test r[2] ≈ zero(Complex{T}) atol=ϵ - @test r[3] ≈ zero(Complex{T}) atol=ϵ - @test r[4] ≈ zero(Complex{T}) atol=ϵ - end - end - - for θ ∈ T[π/7, π/4, π/3, 2π/3] - q = Quaternion{Complex{T}}(Complex{T}(cos(θ/2)), zero(Complex{T}), zero(Complex{T}), Complex{T}(sin(θ/2))) - qi = inv(q) - for r ∈ [qi * q, q * qi] - @test r[1] ≈ one(Complex{T}) rtol=ϵ - @test r[2] ≈ zero(Complex{T}) atol=ϵ - @test r[3] ≈ zero(Complex{T}) atol=ϵ - @test r[4] ≈ zero(Complex{T}) atol=ϵ - end - end - end - - # ──────────────────────────────────────────────────────────────────────────────── - # 11. angle and ^ for complexified quaternions - # - # For a rotation rotor cast to Complex{T}: angle(q) = Complex{T}(θ). - # For a boost rotor with rapidity φ: angle(q) = Complex{T}(0, φ). - # A Lorentz boost is a "rotation by imaginary angle" in the STA. - # - # q ^ s uses exp(s·log(q)) and gives: - # rotation^s = rotation by s·θ - # boost^s = boost with rapidity s·φ - # ──────────────────────────────────────────────────────────────────────────────── - @testset "angle and ^ for complexified quaternions, $T" for T in LorentzTypes - ϵ = 64eps(T) - - for θ ∈ T[π/7, π/4, π/3, 2π/3] - q = Quaternion{Complex{T}}(Complex{T}(cos(θ/2)), zero(Complex{T}), zero(Complex{T}), Complex{T}(sin(θ/2))) - @test angle(q) ≈ Complex{T}(θ) rtol=ϵ - - qs = q ^ T(0.5) - @test qs[1] ≈ Complex{T}(cos(θ/4)) rtol=ϵ - @test qs[4] ≈ Complex{T}(sin(θ/4)) rtol=ϵ - end - - for φ ∈ T[0.5, 1.0, 1.5, 2.0] - q = Quaternion{Complex{T}}(Complex{T}(cosh(φ/2)), im*T(sinh(φ/2)), zero(Complex{T}), zero(Complex{T})) - @test angle(q) ≈ Complex{T}(0, φ) rtol=ϵ - - # q^2 = boost with double rapidity - qs = q ^ T(2) - @test qs[1] ≈ Complex{T}(cosh(φ)) rtol=ϵ - @test qs[2] ≈ Complex{T}(0, sinh(φ)) rtol=ϵ - @test qs[3] ≈ zero(Complex{T}) atol=ϵ - @test qs[4] ≈ zero(Complex{T}) atol=ϵ - end - end - - # ──────────────────────────────────────────────────────────────────────────────── - # 12. log and exp of pure-phase scalar quaternions - # - # A pure phase embedded as q = (exp(im*φ), 0, 0, 0) ∈ ℍ(ℂ) is NOT a Lorentz - # rotor (spinor norm = exp(im*φ) ≠ 1), but log and exp still invert each other: - # log(exp(im*φ), 0, 0, 0) = (im*φ, 0, 0, 0) - # Restricted to φ ∈ (0, π/2) to stay in the principal branch. - # ──────────────────────────────────────────────────────────────────────────────── - @testset "log/exp of pure-phase scalar quaternions, $T" for T in LorentzTypes - ϵ = 32eps(T) - - for φ ∈ T[π/6, π/4, π/3] - λ = Complex{T}(cos(φ), sin(φ)) # exp(im*φ) - q = Quaternion{Complex{T}}(λ, zero(Complex{T}), zero(Complex{T}), zero(Complex{T})) - lq = log(q) - @test lq[1] ≈ Complex{T}(0, φ) rtol=ϵ - @test lq[2] ≈ zero(Complex{T}) atol=ϵ - @test lq[3] ≈ zero(Complex{T}) atol=ϵ - @test lq[4] ≈ zero(Complex{T}) atol=ϵ - - # exp(log(q)) ≈ q - @test exp(log(q))[1] ≈ λ rtol=ϵ - - # log(exp(v)) ≈ v where v = (im*φ, 0, 0, 0) - v = Quaternion{Complex{T}}(Complex{T}(0, φ), zero(Complex{T}), zero(Complex{T}), zero(Complex{T})) - lv = log(exp(v)) - @test lv[1] ≈ Complex{T}(0, φ) rtol=ϵ - @test lv[2] ≈ zero(Complex{T}) atol=ϵ - end - end - end # @testset "Lorentz/STA normalization" diff --git a/test/lorentz_decomposition.jl b/test/lorentz_decomposition.jl index bb15b886..1934b92a 100644 --- a/test/lorentz_decomposition.jl +++ b/test/lorentz_decomposition.jl @@ -4,7 +4,7 @@ # - Round-trip: Lorentz(R) * B ≈ ±Λ (and B * Lorentz(R) ≈ ±Λ for BR) # - Structural: R has zero imaginary components; B has zero real vector components # - Special cases: identity, pure rotation, pure boost, minus-identity -# - Multi-precision: error shrinks as precision increases +# - Multi-precision: checks run at several precisions with tolerances scaled by eps(T) @testmodule LorentzDecompData begin using Random: Xoshiro @@ -74,7 +74,7 @@ ℓ_vec(::Type{T}) where {T} = T[1, 0, 0, 1] / sqrt(T(2)) # Structural predicate for A: pure z-boost (w real, x=y=0, z pure imaginary). - # Accepts any AbstractQuaternion (KAN returns Rₐ as a bare `Quaternion`). + # Accepts any AbstractQuaternion, although KAN returns Rₐ as a `Lorentz` rotor. function is_z_boost(R; atol) w, x, y, z = components(R) abs(imag(w)) < atol && abs(x) < atol && abs(y) < atol && abs(real(z)) < atol diff --git a/test/lorentz_group.jl b/test/lorentz_group.jl index 9b65c937..1ae84d5e 100644 --- a/test/lorentz_group.jl +++ b/test/lorentz_group.jl @@ -4,44 +4,44 @@ # predicate functions, then called for many random inputs. """Minkowski inner product with signature −+++.""" -_minkowski(v, w) = -v[1]*w[1] + v[2]*w[2] + v[3]*w[3] + v[4]*w[4] +minkowski_inner(v, w) = -v[1]*w[1] + v[2]*w[2] + v[3]*w[3] + v[4]*w[4] """Minkowski norm squared (signed; negative for timelike vectors).""" -_minkowski_norm²(v) = _minkowski(v, v) +minkowski_norm²(v) = minkowski_inner(v, v) -_metric_preserved(Λ, v, w; atol=1e-12) = - abs(_minkowski(Λ(v), Λ(w)) - _minkowski(v, w)) ≤ atol +metric_preserved(Λ, v, w; atol=1e-12) = + abs(minkowski_inner(Λ(v), Λ(w)) - minkowski_inner(v, w)) ≤ atol -_composition_consistent(Λ₁, Λ₂, v; atol=1e-12) = +composition_consistent(Λ₁, Λ₂, v; atol=1e-12) = norm((Λ₁ * Λ₂)(v) - Λ₁(Λ₂(v))) ≤ atol -_inverse_law(Λ, v; atol=1e-12) = +inverse_law(Λ, v; atol=1e-12) = norm((Λ * inv(Λ))(v) - v) ≤ atol && norm((inv(Λ) * Λ)(v) - v) ≤ atol -_identity_law(Λ, v; atol=1e-12) = norm(one(Λ)(v) - v) ≤ atol +identity_law(Λ, v; atol=1e-12) = norm(one(Λ)(v) - v) ≤ atol -_associativity_law(Λ₁, Λ₂, Λ₃, v; atol=1e-12) = +associativity_law(Λ₁, Λ₂, Λ₃, v; atol=1e-12) = norm(((Λ₁ * Λ₂) * Λ₃)(v) - (Λ₁ * (Λ₂ * Λ₃))(v)) ≤ atol -_preserves_time(Λ, v; atol=1e-12) = abs(Λ(v)[1] - v[1]) ≤ atol +preserves_time(Λ, v; atol=1e-12) = abs(Λ(v)[1] - v[1]) ≤ atol -_preserves_spatial_norm(Λ, v; atol=1e-12) = +preserves_spatial_norm(Λ, v; atol=1e-12) = abs(norm(Λ(v)[2:4]) - norm(v[2:4])) ≤ atol -_double_cover(Λ_pos, Λ_neg, v; atol=1e-12) = +double_cover(Λ_pos, Λ_neg, v; atol=1e-12) = norm(Λ_pos(v) - Λ_neg(v)) ≤ atol -_rotor_homomorphism(Λ₁₂, Λ₁, Λ₂, v; atol=1e-12) = +rotor_homomorphism(Λ₁₂, Λ₁, Λ₂, v; atol=1e-12) = norm(Λ₁₂(v) - (Λ₁ * Λ₂)(v)) ≤ atol -function _ga_norm_conditions(Λ; atol=1e-12) +function ga_norm_conditions(Λ; atol=1e-12) R¹, Rᶻʸ, Rˣᶻ, Rʸˣ, Rᵗˣ, Rᵗʸ, Rᵗᶻ, Rᵗˣʸᶻ = ga_components(Λ) quad = R¹^2 + Rᶻʸ^2 + Rˣᶻ^2 + Rʸˣ^2 - Rᵗˣ^2 - Rᵗʸ^2 - Rᵗᶻ^2 - Rᵗˣʸᶻ^2 cross = R¹ * Rᵗˣʸᶻ + Rᶻʸ * Rᵗˣ + Rˣᶻ * Rᵗʸ + Rʸˣ * Rᵗᶻ return abs(quad - 1) ≤ atol && abs(cross) ≤ atol end -function _ga_reverse_components(Λ; atol=1e-12) +function ga_reverse_components(Λ; atol=1e-12) c = ga_components(Λ) ci = ga_components(inv(Λ)) abs(ci[1] - c[1]) ≤ atol && # R¹ unchanged (grade 0) @@ -57,99 +57,99 @@ end # ─── Shared random data ──────────────────────────────────────────────────────── Random.seed!(42) -const _lT = Float64 -const _ln = 20 +const lg_T = Float64 +const lg_n = 20 -_rot_rotors = [randn(Rotor{_lT}) for _ ∈ 1:_ln] -_rot_Λs = [Lorentz{_lT}(R) for R ∈ _rot_rotors] -_gen_vecs = [randn(_lT, 4) for _ ∈ 1:_ln] -_spatial_vecs = [[zero(_lT); randn(_lT, 3)] for _ ∈ 1:_ln] +lg_rot_rotors = [randn(Rotor{lg_T}) for _ ∈ 1:lg_n] +lg_rot_Λs = [Lorentz{lg_T}(R) for R ∈ lg_rot_rotors] +lg_gen_vecs = [randn(lg_T, 4) for _ ∈ 1:lg_n] +lg_spatial_vecs = [[zero(lg_T); randn(lg_T, 3)] for _ ∈ 1:lg_n] Random.seed!(123) -_boost_rapidities = abs.(randn(_lT, _ln)) .+ _lT(0.1) -_boost_directions = [QuatVec(normalize(randn(_lT, 3))) for _ ∈ 1:_ln] -_boost_Λs = [Boost(η, n̂) for (η, n̂) ∈ zip(_boost_rapidities, _boost_directions)] +lg_boost_rapidities = abs.(randn(lg_T, lg_n)) .+ lg_T(0.1) +lg_boost_directions = [QuatVec(normalize(randn(lg_T, 3))) for _ ∈ 1:lg_n] +lg_boost_Λs = [Boost(η, n̂) for (η, n̂) ∈ zip(lg_boost_rapidities, lg_boost_directions)] -_mixed_seq = [x for pair ∈ zip(_rot_Λs, _boost_Λs) for x ∈ pair] -_composed = accumulate(*, _mixed_seq) +lg_mixed_seq = [x for pair ∈ zip(lg_rot_Λs, lg_boost_Λs) for x ∈ pair] +lg_composed = accumulate(*, lg_mixed_seq) @testset "Lorentz group" begin # ── Group structure: rotations ───────────────────────────────────────────── @testset "Rotation: identity element" begin - for v ∈ _gen_vecs, Λ ∈ _rot_Λs - @test _identity_law(Λ, v) + for v ∈ lg_gen_vecs, Λ ∈ lg_rot_Λs + @test identity_law(Λ, v) end end @testset "Rotation: composition" begin - for i ∈ 1:(_ln-1), v ∈ _gen_vecs - @test _composition_consistent(_rot_Λs[i], _rot_Λs[i+1], v) + for i ∈ 1:(lg_n-1), v ∈ lg_gen_vecs + @test composition_consistent(lg_rot_Λs[i], lg_rot_Λs[i+1], v) end end @testset "Rotation: inverse" begin - for Λ ∈ _rot_Λs, v ∈ _gen_vecs - @test _inverse_law(Λ, v) + for Λ ∈ lg_rot_Λs, v ∈ lg_gen_vecs + @test inverse_law(Λ, v) end end @testset "Rotation: associativity" begin - for i ∈ 1:(_ln-2), v ∈ _gen_vecs - @test _associativity_law(_rot_Λs[i], _rot_Λs[i+1], _rot_Λs[i+2], v) + for i ∈ 1:(lg_n-2), v ∈ lg_gen_vecs + @test associativity_law(lg_rot_Λs[i], lg_rot_Λs[i+1], lg_rot_Λs[i+2], v) end end # ── Minkowski isometry: rotations ────────────────────────────────────────── @testset "Rotation: preserves Minkowski metric" begin - for Λ ∈ _rot_Λs, i ∈ 1:(_ln-1) - @test _metric_preserved(Λ, _gen_vecs[i], _gen_vecs[i+1]) + for Λ ∈ lg_rot_Λs, i ∈ 1:(lg_n-1) + @test metric_preserved(Λ, lg_gen_vecs[i], lg_gen_vecs[i+1]) end end @testset "Rotation: null vectors remain null" begin - for Λ ∈ _rot_Λs, v ∈ _spatial_vecs + for Λ ∈ lg_rot_Λs, v ∈ lg_spatial_vecs v_sp = v[2:4] ℓ = [norm(v_sp); v_sp] ℓ′ = Λ(ℓ) - @test abs(_minkowski_norm²(ℓ′)) ≤ 1e-12 + @test abs(minkowski_norm²(ℓ′)) ≤ 1e-12 end end # ── Rotation-specific invariants ─────────────────────────────────────────── @testset "Rotation: preserves time component" begin - for Λ ∈ _rot_Λs, v ∈ _gen_vecs - @test _preserves_time(Λ, v) + for Λ ∈ lg_rot_Λs, v ∈ lg_gen_vecs + @test preserves_time(Λ, v) end end @testset "Rotation: preserves spatial norm" begin - for Λ ∈ _rot_Λs, v ∈ _spatial_vecs - @test _preserves_spatial_norm(Λ, v) + for Λ ∈ lg_rot_Λs, v ∈ lg_spatial_vecs + @test preserves_spatial_norm(Λ, v) end end # ── Double cover ─────────────────────────────────────────────────────────── @testset "Rotation: double cover — R and −R give the same transformation" begin - for (R, v) ∈ zip(_rot_rotors, _gen_vecs) - @test _double_cover(Lorentz{_lT}(R), Lorentz{_lT}(-R), v) + for (R, v) ∈ zip(lg_rot_rotors, lg_gen_vecs) + @test double_cover(Lorentz{lg_T}(R), Lorentz{lg_T}(-R), v) end end # ── Spin(3) → Lorentz homomorphism ──────────────────────────────────────── @testset "Rotation: Spin(3) → Lorentz is a group homomorphism" begin - for i ∈ 1:(_ln-1) - R₁, R₂ = _rot_rotors[i], _rot_rotors[i+1] - Λ₁₂ = Lorentz{_lT}(R₁ * R₂) - Λ₁ = Lorentz{_lT}(R₁) - Λ₂ = Lorentz{_lT}(R₂) - for v ∈ _gen_vecs - @test _rotor_homomorphism(Λ₁₂, Λ₁, Λ₂, v) + for i ∈ 1:(lg_n-1) + R₁, R₂ = lg_rot_rotors[i], lg_rot_rotors[i+1] + Λ₁₂ = Lorentz{lg_T}(R₁ * R₂) + Λ₁ = Lorentz{lg_T}(R₁) + Λ₂ = Lorentz{lg_T}(R₂) + for v ∈ lg_gen_vecs + @test rotor_homomorphism(Λ₁₂, Λ₁, Λ₂, v) end end end @@ -242,7 +242,7 @@ _composed = accumulate(*, _mixed_seq) for (vx, vy, vz) ∈ [(0.5, 0.0, 0.0), (0.0, 0.3, 0.0), (0.0, 0.0, 0.4), (0.2, 0.2, 0.2)] v⃗ = QuatVec(vx, vy, vz) β = abs(v⃗) - @test Boost(v⃗) == Boost(atanh(β), v⃗ / β) + @test Boost(v⃗) ≈ Boost(atanh(β), v⃗ / β) @test Boost([vx, vy, vz]) == Boost(v⃗) end # zero velocity → identity @@ -337,49 +337,49 @@ _composed = accumulate(*, _mixed_seq) # ── GA norm conditions ───────────────────────────────────────────────────── @testset "GA norm conditions hold for pure transformations" begin - for Λ ∈ _rot_Λs - @test _ga_norm_conditions(Λ) + for Λ ∈ lg_rot_Λs + @test ga_norm_conditions(Λ) end - for Λ ∈ _boost_Λs - @test _ga_norm_conditions(Λ) + for Λ ∈ lg_boost_Λs + @test ga_norm_conditions(Λ) end end @testset "GA norm conditions preserved under composition" begin - for Λ ∈ _composed - @test _ga_norm_conditions(Λ) + for Λ ∈ lg_composed + @test ga_norm_conditions(Λ) end end @testset "GA reverse is the group inverse (component test)" begin - for Λ ∈ _rot_Λs - @test _ga_reverse_components(Λ) + for Λ ∈ lg_rot_Λs + @test ga_reverse_components(Λ) end - for Λ ∈ _boost_Λs - @test _ga_reverse_components(Λ) + for Λ ∈ lg_boost_Λs + @test ga_reverse_components(Λ) end - for Λ ∈ _composed - @test _ga_reverse_components(Λ) + for Λ ∈ lg_composed + @test ga_reverse_components(Λ) end end # ── Group structure: boosts ──────────────────────────────────────────────── @testset "Boost: group properties" begin - for Λ ∈ _boost_Λs, v ∈ _gen_vecs - @test _identity_law(Λ, v) + for Λ ∈ lg_boost_Λs, v ∈ lg_gen_vecs + @test identity_law(Λ, v) end - for i ∈ 1:(_ln-1), v ∈ _gen_vecs - @test _composition_consistent(_boost_Λs[i], _boost_Λs[i+1], v) + for i ∈ 1:(lg_n-1), v ∈ lg_gen_vecs + @test composition_consistent(lg_boost_Λs[i], lg_boost_Λs[i+1], v) end - for Λ ∈ _boost_Λs, v ∈ _gen_vecs - @test _inverse_law(Λ, v) + for Λ ∈ lg_boost_Λs, v ∈ lg_gen_vecs + @test inverse_law(Λ, v) end - for i ∈ 1:(_ln-2), v ∈ _gen_vecs - @test _associativity_law(_boost_Λs[i], _boost_Λs[i+1], _boost_Λs[i+2], v) + for i ∈ 1:(lg_n-2), v ∈ lg_gen_vecs + @test associativity_law(lg_boost_Λs[i], lg_boost_Λs[i+1], lg_boost_Λs[i+2], v) end - for Λ ∈ _boost_Λs, i ∈ 1:(_ln-1) - @test _metric_preserved(Λ, _gen_vecs[i], _gen_vecs[i+1]) + for Λ ∈ lg_boost_Λs, i ∈ 1:(lg_n-1) + @test metric_preserved(Λ, lg_gen_vecs[i], lg_gen_vecs[i+1]) end end diff --git a/test/math.jl b/test/math.jl index 0f27f2a5..9894fa64 100644 --- a/test/math.jl +++ b/test/math.jl @@ -191,10 +191,12 @@ ) Δ = s*f*v - # log(1) + Δ = Δ + # log(1 + Δ) ≈ log|1 + Δ| + Δ. The scalar part is log(1 + f²)/2, which + # `log(abs(q))` would round to zero. q = quaternion(one(T)) + Δ - @test q ≈ exp(quaternion(log(abs(q))) + Δ) rtol=ϵ nans=true - @test log(q) ≈ quaternion(log(abs(q))) + Δ rtol=ϵ nans=true + @test q ≈ exp(quaternion(log1p(f^2)/2) + Δ) rtol=ϵ nans=true + @test log(q) ≈ quaternion(log1p(f^2)/2) + Δ rtol=ϵ nans=true + @test log(q)[1] ≈ log1p(f^2)/2 rtol=ϵ r = rotor(q) @test r ≈ exp(Δ) rtol=ϵ nans=true @test log(r) ≈ Δ rtol=ϵ nans=true diff --git a/test/nested_forwarddiff.jl b/test/nested_forwarddiff.jl index 50955e88..54ffa82a 100644 --- a/test/nested_forwarddiff.jl +++ b/test/nested_forwarddiff.jl @@ -112,12 +112,14 @@ end n̂ = normalize(quatvec(1.0, -2.0, 3.0)) nx, ny, nz = vec(n̂) - # Orders beyond 4 would exceed the accuracy of the Taylor series in `Boost` + # `Boost(v⃗)` uses a closed form without series, so its derivatives of every order are + # accurate at β = 0. @test compare_derivatives( t -> [f(c) for c ∈ components(Boost(t * n̂)) for f ∈ (real, imag)], t -> let ch = cosh(atanh(t)/2), sh = sinh(atanh(t)/2) [ch, zero(t), zero(t), sh*nx, zero(t), sh*ny, zero(t), sh*nz] - end, + end; + orders=1:6, ) end diff --git a/test/property_based.jl b/test/property_based.jl index 6f783f30..18b02660 100644 --- a/test/property_based.jl +++ b/test/property_based.jl @@ -20,6 +20,11 @@ # or `BigFloat`. See `PropertyGens.floats`. # * Properties are written as *named predicate functions* in the # `PropertyGens` test module, and invoked with `@check`'s call syntax. +# * Every `@check` is wrapped in `counted`, which records its outcome as an +# ordinary `@test`. Supposition records each check in its own test set, a +# `SuppositionReport`, and the test-item runner (TestItemControllers) does +# not count the results in that kind of child test set, so without the +# wrapper a failing property would let its test item pass. # This is not stylistic: `@check function foo(...)` defines a global # method, so it cannot appear inside a `for T ∈ FloatTypes` loop. The # call syntax can, which is what lets one property sweep every precision. @@ -58,6 +63,7 @@ using Supposition, Supposition.Data using DoubleFloats: Double64 using Random: Xoshiro, RandomDevice + using Test: @test # ── Configuration ───────────────────────────────────────────────────────── @@ -111,6 +117,17 @@ db = Supposition.DirectoryDB(mkpath(joinpath(@__DIR__, "SuppositionDB"))), ) + """ + counted(report) + + Record whether the Supposition `report` returned by `@check` passed, as an ordinary + `@test`, which every test runner counts. Under plain `Test`, a failing property is + then reported twice: once by Supposition and once by this test. + """ + function counted(report) + @test Supposition.results(report).ispass + end + # ── Generators ──────────────────────────────────────────────────────────── """ @@ -324,20 +341,20 @@ end @testitem "properties: normed division algebra" tags=[:unit, :fast, :validation] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: FloatTypes, CFG, quats, wildfloats, + using .PropertyGens: counted, FloatTypes, CFG, quats, wildfloats, associativity, left_distributivity, right_distributivity, conj_involution, conj_antiautomorphism, norm_composition, inverse_law for T ∈ FloatTypes @testset "$T" begin Q = quats(T) - @check config=CFG associativity(Q, Q, Q) - @check config=CFG left_distributivity(Q, Q, Q) - @check config=CFG right_distributivity(Q, Q, Q) - @check config=CFG conj_involution(Q) - @check config=CFG conj_antiautomorphism(Q, Q) - @check config=CFG norm_composition(Q, Q) - @check config=CFG inverse_law(Q) + counted(@check config=CFG associativity(Q, Q, Q)) + counted(@check config=CFG left_distributivity(Q, Q, Q)) + counted(@check config=CFG right_distributivity(Q, Q, Q)) + counted(@check config=CFG conj_involution(Q)) + counted(@check config=CFG conj_antiautomorphism(Q, Q)) + counted(@check config=CFG norm_composition(Q, Q)) + counted(@check config=CFG inverse_law(Q)) end end @@ -346,8 +363,8 @@ end for T ∈ (Float32, Float64) @testset "$T (bit-pattern inputs)" begin W = quats(wildfloats(T)) - @check config=CFG conj_involution(W) - @check config=CFG norm_composition(W, W) + counted(@check config=CFG conj_involution(W)) + counted(@check config=CFG norm_composition(W, W)) end end end @@ -355,24 +372,24 @@ end @testitem "properties: conversion round-trips" tags=[:validation, :fast] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: FloatTypes, MatrixFloatTypes, CFG, quats, rotors, + using .PropertyGens: counted, FloatTypes, MatrixFloatTypes, CFG, quats, rotors, euler_roundtrip, euler_phase_roundtrip, spherical_roundtrip, matrix_roundtrip, floatarray_roundtrip for T ∈ FloatTypes @testset "$T" begin R, Q = rotors(T), quats(T) - @check config=CFG euler_roundtrip(R) - @check config=CFG euler_phase_roundtrip(R) - @check config=CFG spherical_roundtrip(R) - @check config=CFG floatarray_roundtrip(Q) + counted(@check config=CFG euler_roundtrip(R)) + counted(@check config=CFG euler_phase_roundtrip(R)) + counted(@check config=CFG spherical_roundtrip(R)) + counted(@check config=CFG floatarray_roundtrip(Q)) end end # `from_rotation_matrix` needs `eigen`; see MatrixFloatTypes. for T ∈ MatrixFloatTypes @testset "$T (via eigen)" begin - @check config=CFG matrix_roundtrip(rotors(T)) + counted(@check config=CFG matrix_roundtrip(rotors(T))) end end end @@ -380,17 +397,17 @@ end @testitem "properties: exp, log, sqrt, powers" tags=[:validation, :fast] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: FloatTypes, CFG, quats, rotors, + using .PropertyGens: counted, FloatTypes, CFG, quats, rotors, explog, logexp_rotor, sqrt_squares, pow_addition for T ∈ FloatTypes @testset "$T" begin Q, R = quats(T), rotors(T) - @check config=CFG explog(Q) - @check config=CFG logexp_rotor(R) - @check config=CFG sqrt_squares(Q) - @check config=CFG pow_addition( - R, Data.Integers(-4, 4), Data.Integers(-4, 4)) + counted(@check config=CFG explog(Q)) + counted(@check config=CFG logexp_rotor(R)) + counted(@check config=CFG sqrt_squares(Q)) + counted(@check config=CFG pow_addition( + R, Data.Integers(-4, 4), Data.Integers(-4, 4))) end end end @@ -398,16 +415,16 @@ end @testitem "properties: rotation semantics" tags=[:validation, :fast] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: FloatTypes, CFG, rotors, quatvecs, + using .PropertyGens: counted, FloatTypes, CFG, rotors, quatvecs, sandwich_matches_matrix, rotation_is_isometry, matrix_homomorphism, double_cover for T ∈ FloatTypes @testset "$T" begin R, V = rotors(T), quatvecs(T) - @check config=CFG sandwich_matches_matrix(R, V) - @check config=CFG rotation_is_isometry(R, V) - @check config=CFG matrix_homomorphism(R, R) - @check config=CFG double_cover(R, V) + counted(@check config=CFG sandwich_matches_matrix(R, V)) + counted(@check config=CFG rotation_is_isometry(R, V)) + counted(@check config=CFG matrix_homomorphism(R, R)) + counted(@check config=CFG double_cover(R, V)) end end end @@ -415,17 +432,17 @@ end @testitem "properties: slerp" tags=[:validation, :fast] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: FloatTypes, CFG, rotors, unitinterval, + using .PropertyGens: counted, FloatTypes, CFG, rotors, unitinterval, slerp_endpoints, slerp_stays_unit, slerp_constant_speed, slerp_unflip_is_the_short_way for T ∈ FloatTypes @testset "$T" begin R, τ = rotors(T), unitinterval(T) - @check config=CFG slerp_endpoints(R, R) - @check config=CFG slerp_stays_unit(R, R, τ) - @check config=CFG slerp_constant_speed(R, R, τ) - @check config=CFG slerp_unflip_is_the_short_way(R, R, τ) + counted(@check config=CFG slerp_endpoints(R, R)) + counted(@check config=CFG slerp_stays_unit(R, R, τ)) + counted(@check config=CFG slerp_constant_speed(R, R, τ)) + counted(@check config=CFG slerp_unflip_is_the_short_way(R, R, τ)) end end end @@ -433,13 +450,13 @@ end @testitem "properties: align recovers a rotation" tags=[:validation, :fast] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: AlignFloatTypes, CFG, rotors, quatvecs, + using .PropertyGens: counted, AlignFloatTypes, CFG, rotors, quatvecs, align_recovers_rotation for T ∈ AlignFloatTypes @testset "$T" begin R, V = rotors(T), quatvecs(T) - @check config=CFG align_recovers_rotation(R, V, V, V) + counted(@check config=CFG align_recovers_rotation(R, V, V, V)) end end end @@ -447,17 +464,17 @@ end @testitem "properties: distance is a bi-invariant metric" tags=[:validation, :fast] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: FloatTypes, CFG, rotors, + using .PropertyGens: counted, FloatTypes, CFG, rotors, distance_symmetric, distance_left_invariant, distance_right_invariant, distance_triangle for T ∈ FloatTypes @testset "$T" begin R = rotors(T) - @check config=CFG distance_symmetric(R, R) - @check config=CFG distance_left_invariant(R, R, R) - @check config=CFG distance_right_invariant(R, R, R) - @check config=CFG distance_triangle(R, R, R) + counted(@check config=CFG distance_symmetric(R, R)) + counted(@check config=CFG distance_left_invariant(R, R, R)) + counted(@check config=CFG distance_right_invariant(R, R, R)) + counted(@check config=CFG distance_triangle(R, R, R)) end end end @@ -467,7 +484,7 @@ end @testitem "regression: from_rotation_matrix ignores eigenvalue ordering" tags=[:validation, :slow] setup=[PropertyGens] begin using Supposition: @check, Data - using .PropertyGens: CFG, rotors, matrix_roundtrip + using .PropertyGens: counted, CFG, rotors, matrix_roundtrip # `dominant_eigenvector` (src/conversion.jl) used to take `eigen(M).vectors[:, 4]`, # assuming `eigen` returns eigenvalues in ascending order. LAPACK does, and so @@ -487,5 +504,5 @@ end # # This test item is only meaningful with GenericSchur loaded, which the # `using DoubleFloats` in `PropertyGens` guarantees. - @check config=CFG matrix_roundtrip(rotors(BigFloat)) + counted(@check config=CFG matrix_roundtrip(rotors(BigFloat))) end diff --git a/test/quaternion.jl b/test/quaternion.jl index a04d6a77..50d1aeec 100644 --- a/test/quaternion.jl +++ b/test/quaternion.jl @@ -45,8 +45,11 @@ continue end @test promote_rule(T1, T2) === T1 - if Q === QuatVec + if Q === QuatVec || Q === Rotor + # Neither a `QuatVec` nor a `Rotor` can represent a general number @test promote_rule(Q{T1}, T2) === Quaternion{T1} + @test promote_type(Q{T1}, T2) === Quaternion{T1} + @test promote_type(Q{T1}, Complex{T2}) === Quaternion{Complex{T1}} else @test promote_rule(Q{T1}, T2) === Q{T1} end diff --git a/test/regressions_algebra.jl b/test/regressions_algebra.jl new file mode 100644 index 00000000..dfff0c5a --- /dev/null +++ b/test/regressions_algebra.jl @@ -0,0 +1,179 @@ +# Regression tests for fixes to src/algebra.jl and src/Quaternionic.jl. + +@testitem "Division: mixed types are not short-circuited" begin + # `q / p` once returned exactly 1 whenever `p == q`, and `==` between a `QuatVec` and + # another quaternion compares only the vector parts. So a quaternion divided by a + # `QuatVec` with the same vector part returned 1, whatever its scalar part. + q = quaternion(5.0, 1.0, 2.0, 3.0) + v = quatvec(1.0, 2.0, 3.0) + @test q / v ≈ q * inv(v) + @test v / q ≈ v * inv(q) + @test q / v ≉ one(q) + @test v / q ≉ one(q) + + R = rotor(1.0, 2.0, 3.0, 4.0) + w = quatvec(R[2], R[3], R[4]) + @test R / w ≈ R * inv(w) + @test w / R ≈ w * conj(R) + @test v / v ≈ one(QuaternionF64) + @test typeof(v / v) === QuaternionF64 +end + +@testitem "Division: q/q is exactly one for real floats" begin + using Random + rng = Random.MersenneTwister(1234) + for T in (Float64, Float32, Float16, BigFloat) + # The scales keep `abs2(q)` well inside the range of each type. + scales = T === Float16 ? (-1:1) : T === Float32 ? (-8:8) : (-60:60) + qs = [randn(rng, Quaternion{T}) * T(10)^rand(rng, scales) for _ in 1:2000] + @test all(qs) do q + r = q / q + typeof(r) === typeof(q) && components(r) == components(one(q)) + end + end + Rs = [randn(rng, RotorF64) for _ in 1:2000] + @test all(R -> (r = R / R; r isa RotorF64 && components(r) == components(one(R))), Rs) + vs = [randn(rng, QuatVecF64) for _ in 1:2000] + @test all(v -> components(v / v) == components(one(QuaternionF64)), vs) +end + +@testitem "Division: agrees with a BigFloat reference" begin + using Random + rng = Random.MersenneTwister(7) + @test all(1:1000) do _ + q = randn(rng, QuaternionF64) + p = randn(rng, QuaternionF64) + ref = big(q) * inv(big(p)) + maximum(abs, components(q / p - ref)) ≤ 4eps(Float64) * abs(ref) + end +end + +@testitem "Division: the result type does not depend on the values" begin + a32 = quaternion(1f0, 2f0, 3f0, 4f0) + @test typeof(a32 / quaternion(1, 2, 3, 4)) === typeof(a32 / quaternion(1, 2, 3, 5)) + @test (@inferred a32 / quaternion(1, 2, 3, 4)) isa QuaternionF32 + + ar = quaternion(1//2, 1//3, 0//1, 1//1) + @test (@inferred ar / ar) isa Quaternion{Rational{Int}} + @test ar / ar == one(ar) + @test typeof(ar / ar) === typeof(ar / quaternion(1//1, 0//1, 0//1, 0//1)) + + @test (@inferred Rotor{Float32}(1, 0, 0, 0) / Rotor{Int}(1, 0, 0, 0)) isa RotorF32 + @test (@inferred QuatVec{Float32}(0, 1, 2, 3) / QuatVec{Int}(0, 1, 2, 3)) isa QuaternionF32 +end + +@testitem "Division: reverse-mode derivative at q == p" begin + # A backend whose `==` compares only primal values used to take the shortcut branch + # and return a zero derivative at q == p. + using ForwardDiff, ReverseDiff + W = [0.3, -1.1, 0.7, 0.45] + wsum(q) = sum(W .* components(q)) + P0 = quaternion(0.3, 1.2, -0.5, 0.7) + R0 = rotor(0.3, -0.7, 0.2, 0.5) + f1(x) = wsum(quaternion(x...) / P0) + f2(x) = wsum(P0 / quaternion(x...)) + f3(x) = wsum(slerp(R0, rotor(x...), 0.37)) + for (f, x) in ((f1, collect(components(P0))), (f2, collect(components(P0))), + (f3, collect(components(R0)))) + ref = ForwardDiff.gradient(f, x) + @test !iszero(ref) + @test ReverseDiff.gradient(f, x) ≈ ref atol=10eps() + end +end + +@testitem "Division: FastDifferentiation variables" begin + # The shortcut evaluated `p == q` in a boolean context, which threw a `TypeError` for + # FastDifferentiation, whose `==` returns a `Node`. + import FastDifferentiation + FastDifferentiation.@variables u1 u2 u3 u4 + Qn = quaternion(u1, u2, u3, u4) + p = quaternion(1.0, 2.0, 3.0, 4.0) + @test (Qn / p) isa Quaternion{FastDifferentiation.Node} + @test (Qn / Qn) isa Quaternion{FastDifferentiation.Node} + x = [0.3, 0.1, 0.2, 0.4] + f = FastDifferentiation.make_function(collect(components(Qn / p)), [u1, u2, u3, u4]) + @test f(x) ≈ collect(components(quaternion(x...) / p)) +end + +@testitem "Cross product extends LinearAlgebra.cross" begin + using LinearAlgebra + @test Quaternionic.:× === LinearAlgebra.:× + @test Quaternionic.:× === LinearAlgebra.cross + a = quatvec(1.0, 2.0, 3.0) + b = quatvec(-2.0, 0.5, 1.0) + # With both `LinearAlgebra` and `Quaternionic` loaded, `×` is not ambiguous. + @test a × b ≈ quatvec(cross([1.0, 2.0, 3.0], [-2.0, 0.5, 1.0])...) + @test cross(a, b) == a × b + @test [1, 0, 0] × [0, 1, 0] == [0, 0, 1] +end + +@testitem "Normalized cross product: type stability and null vectors" begin + for T in (Int, Rational{Int}, BigInt, Float32, Float64) + a = QuatVec{T}(0, 1, 0, 0) + @test typeof(a ×̂ QuatVec{T}(0, 2, 0, 0)) === typeof(a ×̂ QuatVec{T}(0, 0, 1, 0)) + @test iszero(a ×̂ QuatVec{T}(0, 2, 0, 0)) + @test a ×̂ QuatVec{T}(0, 0, 3, 0) == quatvec(0, 0, 1) + end + @test (@inferred quatvec(1, 0, 0) ×̂ quatvec(2, 0, 0)) isa QuatVecF64 + @test (@inferred quatvec(1//1, 0, 0) ×̂ quatvec(2//1, 0, 0)) isa QuatVecF64 + + # A nonzero null vector has zero spinor norm, so it is returned unchanged. + a = quatvec(1.0, 0, 0) + b = quatvec(0, 1.0, 1.0im) + @test a ×̂ b == a × b + @test !iszero(a ×̂ b) +end + +@testitem "Division: divisors whose abs2 overflows or underflows" begin + # `abs2(p)` overflows or underflows when `abs(p)` is far from 1, and division by it once + # gave NaN, even for `q / q`. Now both arguments are rescaled by a power of two first. + using Random + rng = Random.MersenneTwister(2468) + relerr(r, ref) = Float64(abs(big(r) - ref) / abs(ref)) + for T in (Float64, Float32) + E = exponent(floatmax(T)) + # Each pair of exponents makes `abs2(p)` overflow or underflow, while the quotients + # stay well inside the range of `T`. The last pair makes the components of `p` + # subnormal. + for (eq, ep) in ((3E÷4, 3E÷4), (-3E÷4, -3E÷4), (3E÷4, E÷2 + 8), (-E÷2 - 8, -3E÷4), + (-E - 4, -E - 4)) + @test all(1:200) do _ + q = randn(rng, Quaternion{T}) * ldexp(one(T), eq) + p = randn(rng, Quaternion{T}) * ldexp(one(T), ep) + s = 3 * ldexp(one(T), eq) + components(p / p) == components(one(p)) && + components(quatvec(p) / quatvec(p)) == components(one(p)) && + relerr(q / p, big(q) / big(p)) < 8eps(T) && + relerr(s / p, big(s) / big(p)) < 8eps(T) && + relerr(quatvec(q) / quatvec(p), big(quatvec(q)) / big(quatvec(p))) < 8eps(T) + end + end + end + q = quaternion(1e200, 2e200, 3e200, 4e200) + t = quaternion(1e-170, 2e-170, 3e-170, 4e-170) + @test q / q == one(q) + @test t / t == one(t) + @test quaternion(2e200, 0, 0, 0) / quaternion(1e200, 1e200, 0, 0) ≈ quaternion(1, -1, 0, 0) + @test 1 / quaternion(1e-200) ≈ quaternion(1e200) +end + +@testitem "Division: dual numbers are rescaled too" begin + using ForwardDiff + W = [0.3, -1.1, 0.7, 0.45] + for scale in (1e200, 1e-170) + P = quaternion(3.0, -1.0, 2.0, 5.0) * scale + x0 = [0.2, 1.3, -0.4, 0.8] * scale + for f in (x -> sum(W .* components(P / quaternion(x...))), + x -> sum(W .* components(quaternion(x...) / P))) + g = ForwardDiff.gradient(f, x0) + ref = map(1:4) do i + h = big(1e-30) * abs(big(x0[i])) + xp = big.(x0); xp[i] += h + xm = big.(x0); xm[i] -= h + (f(xp) - f(xm)) / 2h + end + @test all(isfinite, g) + @test maximum(abs, g - ref) ≤ 4eps() * maximum(abs, ref) + end + end +end diff --git a/test/regressions_conv.jl b/test/regressions_conv.jl new file mode 100644 index 00000000..2099883d --- /dev/null +++ b/test/regressions_conv.jl @@ -0,0 +1,321 @@ +# Regression tests for conversions, distances, and alignment. + +@testitem "distance2 near-identity series matches BigFloat" tags=[:validation, :fast] begin + using DoubleFloats: Double64 + import Quaternionic: absvec + + # Rotors separated from the identity by a rotation through θ are a distance θ/2 away. + # The reference is computed in BigFloat from the very same rotor, so that the rounding + # of its components does not enter. The grid straddles the threshold at which + # `distance2` switches from its series to the closed form, and a tolerance of a few + # ulps detects an error in any coefficient of the series, or in the threshold. + θs = exp10.(range(-10, log10(0.2), length=400)) + @testset "$T" for T ∈ (Float32, Float64, Double64) + n̂ = normalize(quatvec(T(1), T(-2), T(3))) + worst = maximum(θs) do θ + R = exp(T(θ) * n̂ / 2) + d = distance2(R, one(R)) + Rb = Rotor{BigFloat}(R) + ref = atan(absvec(Rb), Rb[1])^2 + Float64(abs(d - ref) / (eps(T) * ref)) + end + @test worst ≤ 4 + # The same for `distance`, which is the square root + worst_sqrt = maximum(θs) do θ + R = exp(T(θ) * n̂ / 2) + d = distance(one(R), R) + Rb = Rotor{BigFloat}(R) + ref = atan(absvec(Rb), Rb[1]) + Float64(abs(d - ref) / (eps(T) * ref)) + end + @test worst_sqrt ≤ 4 + # Away from the identity, the distance is half the angle, up to the rounding + # incurred by forming the two rotors + R₀ = rotor(T(0.4), T(-0.2), T(0.7), T(0.5)) + @test all(θs) do θ + abs(distance(exp(T(θ) * n̂ / 2) * R₀, R₀) - T(θ) / 2) ≤ 10eps(T) + end + end +end + +@testitem "distance2 on symbolic and Lorentz rotors" tags=[:unit, :fast] begin + import Symbolics + + # For a symbolic rotor, the comparison that selects the series does not evaluate to a + # `Bool`, so the closed form is used, and it must still evaluate symbolically. + Symbolics.@variables w x y z a b c d + Q₁ = Rotor{Symbolics.Num}(w, x, y, z) + Q₂ = Rotor{Symbolics.Num}(a, b, c, d) + expr = distance2(Q₁, Q₂) + @test expr isa Symbolics.Num + R₁ = rotor(0.4, -0.2, 0.7, 0.5) + R₂ = rotor(-0.1, 0.3, 0.2, 0.9) + f = Symbolics.build_function(expr, [w, x, y, z, a, b, c, d]; expression=Val(false)) + @test f([components(R₁)...; components(R₂)...]) ≈ distance2(R₁, R₂) rtol=1e-14 + + # The Lorentz group has no positive-definite bi-invariant metric + L = rotor(1.0 + 0.2im, 0.3, 0.1im, 0.2) + @test_throws ArgumentError distance2(L, L) + @test_throws ArgumentError distance(L, rotor(1.0, 0, 0, 0)) +end + +@testitem "distance2 gradients and the series branch" tags=[:unit, :fast] begin + using ForwardDiff + + # Dual numbers must take the series branch at the identity, where the closed form has + # a NaN derivative, and agree with plain floats elsewhere + R₀ = rotor(0.4, -0.2, 0.7, 0.5) + g = ForwardDiff.gradient(u -> distance2(rotor(u...), R₀), collect(components(R₀))) + @test g ≈ zeros(4) atol=1e-14 + @test !any(isnan, g) + # A point where the scalar part of the quotient is zero must not divide by zero + v = ForwardDiff.gradient(u -> distance2(rotor(u...), rotor(1.0, 0, 0, 0)), [0.0, 1.0, 0.0, 0.0]) + @test !any(isnan, v) +end + +@testitem "distance2 Hessians under ReverseDiff take the series" tags=[:unit, :fast] begin + using ForwardDiff, ReverseDiff + + # `ReverseDiff.TrackedReal` is not an `AbstractFloat`, but it must still take the + # series at the identity. The closed form has a singular second derivative there, so + # the ReverseDiff Hessian of the closed form was wrong by O(1), with no NaN. + R₀ = rotor(0.4, -0.2, 0.7, 0.5) + f(u) = distance2(rotor(u...), R₀) + for u ∈ (collect(components(R₀)), collect(components(rotor(0.3, 0.5, -0.1, 0.8)))) + Hr = ReverseDiff.hessian(f, u) + Hf = ForwardDiff.hessian(f, u) + @test !any(isnan, Hr) + @test Hr ≈ Hf atol=1e-14 + end + # The Hessian at the minimum, compared with the explicit formula. At the identity, + # `distance2(rotor(u...), R₀)` is the squared length of the vector part of the + # normalized `u/R₀`, to second order, so its Hessian is twice the projector onto the + # tangent space spanned by `imx * R₀`, `imy * R₀`, and `imz * R₀`. + u₀ = collect(components(R₀)) + P = sum(e -> (v = collect(components(e * R₀)); v * v'), (imx, imy, imz)) + @test ReverseDiff.hessian(f, u₀) ≈ 2P atol=1e-14 +end + +@testitem "to_spherical_coordinates is accurate near the poles" tags=[:validation, :fast] begin + using ForwardDiff + + # The polar angle was computed with acos, which lost half the digits near θ = 0 + @testset "$T" for T ∈ (Float16, Float32, Float64) + θs = T === Float16 ? T[1e-3, 1e-2, 0.1] : T[1e-12, 1e-8, 1e-6, 1e-3, 0.1] + for θ ∈ θs, ϕ ∈ T[0.7, -2.5] + R = from_spherical_coordinates(θ, ϕ) + Rb = Rotor{BigFloat}(R) + θref = 2atan(hypot(Rb[2], Rb[3]), hypot(Rb[1], Rb[4])) + @test abs(to_spherical_coordinates(R)[1] - θref) ≤ 2eps(T) * θref + end + end + # The near-pole rotor found by the property test of round trips + R = rotor(-0.7074310290501881, -0.007599356757375066, -0.0013817012286136486, -0.7067401784358812) + θ, ϕ = to_spherical_coordinates(R) + S = from_spherical_coordinates(θ, ϕ) + @test maximum(abs, to_rotation_matrix(S)[:, 3] - to_rotation_matrix(R)[:, 3]) ≤ 10eps(Float64) + # The gradient is finite and matches the exact value at a small polar angle + s = 1e-9 + F(u) = to_spherical_coordinates(rotor(u...))[1] + u = [1.0, s, -2s, 0.5s] + @test F(u) ≈ 2atan(√5 * s, hypot(1.0, 0.5s)) rtol=4eps() + g = ForwardDiff.gradient(F, u) + @test all(isfinite, g) + @test g[2:3] ≈ [2, -4] / √5 rtol=1e-6 + # The normalization scales out, even where the sum of squares would underflow + @test to_spherical_coordinates(1e-170 * rotor(0.4, -0.2, 0.7, 0.5)) ≈ + to_spherical_coordinates(rotor(0.4, -0.2, 0.7, 0.5)) +end + +@testitem "to_euler_phases handles integers" tags=[:validation, :fast] begin + q = quaternion(0.4, -0.2, 0.7, 0.5) + z = to_euler_phases(q) + # Integer input used to throw an `InexactError` + @test to_euler_phases(quaternion(1, 2, 3, 4)) == to_euler_phases(quaternion(1.0, 2, 3, 4)) + @test to_euler_phases(rotor(1, 0, 0, 0)) == to_euler_phases(rotor(1.0, 0, 0, 0)) + # The normalization scales out + for s ∈ (1e-100, 1e-10, 1e10, 1e100) + @test to_euler_phases(s * q) ≈ z atol=4eps() + end + # Agreement with a BigFloat evaluation + for _ ∈ 1:100 + R = randn(RotorF64) + @test to_euler_phases(R) ≈ to_euler_phases(Rotor{BigFloat}(R)) atol=4eps() + end +end + +@testitem "from_euler_phases has no NaN gradients under ReverseDiff" tags=[:unit, :fast] begin + using ForwardDiff, ReverseDiff + + # The sign test used `abs` of a complex number that is often exactly zero, whose + # derivative ReverseDiff recorded as NaN + wsum(R) = sum((1:4) .* components(R)) + f(x) = wsum(from_euler_phases(cis(x[1]), cis(x[2]), cis(x[3]))) + for x ∈ ([0.3, 1.1, -0.4], [0.3, 0.5, -0.1], [1.0, 0.5, 2.0]) + gr = ReverseDiff.gradient(f, x) + gf = ForwardDiff.gradient(f, x) + @test !any(isnan, gr) + @test gr ≈ gf atol=1e-14 + end +end + +@testitem "conversions keep their values after leaving the literal macros" tags=[:unit, :fast] begin + using StaticArrays + + # Explicit formulas, independent of the package's implementation + q = quaternion(0.3, 0.5, -0.1, 0.8) + n = abs2(q) + w, x, y, z = components(q) + ℛ = [ + w^2+x^2-y^2-z^2 2(x*y-w*z) 2(x*z+w*y); + 2(x*y+w*z) w^2-x^2+y^2-z^2 2(y*z-w*x); + 2(x*z-w*y) 2(y*z+w*x) w^2-x^2-y^2+z^2 + ] / n + M = to_rotation_matrix(q) + @test M isa SMatrix{3,3,Float64} + @test M ≈ ℛ atol=4eps() + v = randn(QuatVecF64) + @test M * vec(v) ≈ vec(rotor(q)(v)) atol=8eps() + @test to_euler_angles(q) isa SVector{3,Float64} + @test to_euler_phases(q) isa SVector{3,ComplexF64} + @test to_spherical_coordinates(q) isa SVector{2,Float64} +end + +@testitem "to_euler_angles round trips at gimbal lock" tags=[:unit, :fast] begin + for α ∈ (-2.0, 0.3, 1.7), γ ∈ (-0.4, 0.9), β ∈ (0.0, Float64(π)) + R = from_euler_angles(α, β, γ) + R′ = from_euler_angles(to_euler_angles(R)) + @test distance(R, R′) ≤ 10eps() + end +end + +@testitem "conversions reject complex input with an ArgumentError" tags=[:unit, :fast] begin + using LinearAlgebra + + L = rotor(1.0 + 0.1im, 0.2, 0.3im, 0.1) + @test_throws ArgumentError to_euler_angles(L) + @test_throws ArgumentError to_euler_phases(L) + @test_throws ArgumentError to_spherical_coordinates(L) + @test_throws ArgumentError from_rotation_matrix(ComplexF64[1 0 0; 0 1 0; 0 0 1]) + a⃗ = [quatvec(1.0 + 0im, 0, 0), quatvec(0, 1.0 + 0im, 0)] + b⃗ = [quatvec(0, 1.0 + 0im, 0), quatvec(1.0 + 0im, 0, 0)] + @test_throws ArgumentError align(a⃗, b⃗) + # `to_rotation_matrix` of a Lorentz rotor is its complex-orthogonal action on bivectors + Mx = to_rotation_matrix(L) + @test transpose(Mx) * Mx ≈ I atol=1e-14 +end + +@testitem "from_rotation_matrix and align: types and sign convention" tags=[:validation, :fast] begin + using DoubleFloats: Double64 + using ForwardDiff, ReverseDiff + + # The result has the same element type as the input, including Float16 + for T ∈ (Float16, Float32, Float64, Double64, BigFloat) + R = randn(Rotor{T}) + @test from_rotation_matrix(to_rotation_matrix(R)) isa Rotor{T} + a⃗ = randn(QuatVec{T}, 5) + @test align(a⃗, conj(R).(a⃗)) isa Rotor{T} + end + + # The scalar part of the result is positive, whatever the element type, so that the + # LAPACK and generic backends agree + for _ ∈ 1:100 + R = randn(RotorF64) + M = to_rotation_matrix(R) + R₁ = from_rotation_matrix(M) + R₂ = from_rotation_matrix(Double64.(M)) + R₃ = from_rotation_matrix(BigFloat.(M)) + @test R₁[1] > 0 && R₂[1] > 0 && R₃[1] > 0 + @test abs(R₁ - (R[1] < 0 ? -R : R)) ≤ 50eps() + @test abs(R₁ - RotorF64(R₂)) ≤ 50eps() + @test abs(R₁ - RotorF64(R₃)) ≤ 50eps() + a⃗ = randn(QuatVecF64, 6) + b⃗ = randn(QuatVecF64, 6) + A₁ = align(a⃗, b⃗) + A₂ = align(QuatVec{Double64}.(a⃗), QuatVec{Double64}.(b⃗)) + @test A₁[1] > 0 && A₂[1] > 0 + @test abs(A₁ - RotorF64(A₂)) ≤ 1e-12 + end + + # Rotations through π have zero scalar part, and the first nonzero component is positive + for R ∈ (rotor(imx), rotor(imy), rotor(imz), rotor(0, 1, 1, 0), rotor(0, -1, 1, 0), rotor(0, 0, -1, 1)) + R′ = from_rotation_matrix(to_rotation_matrix(R)) + @test abs(R′[1]) ≤ 10eps() + i = findfirst(c -> abs(c) > 10eps(), components(R′)) + @test R′[i] > 0 + @test min(abs(R′ - R), abs(R′ + R)) ≤ 10eps() + end + + # A slightly non-orthogonal matrix gives the nearby rotor + R = randn(RotorF64) + M = to_rotation_matrix(R) + 1e-9 * randn(3, 3) + R′ = from_rotation_matrix(M) + @test min(abs(R′ - R), abs(R′ + R)) ≤ 1e-8 + + # Because the sign is fixed, ReverseDiff and ForwardDiff differentiate the same branch + wsum(R) = sum((1:4) .* components(R)) + f(x) = wsum(from_rotation_matrix(to_rotation_matrix(rotor(x...)))) + for x ∈ (normalize([0.3, -0.7, 0.5, 1.1]), normalize([-0.2, 0.4, 0.1, -0.9])) + @test ReverseDiff.gradient(f, x) ≈ ForwardDiff.gradient(f, x) atol=1e-12 + end +end + +@testitem "align on QuatVecs: docstring matrix, direction, and allocations" tags=[:validation, :fast] begin + using LinearAlgebra + + a⃗ = randn(QuatVecF64, 6) + b⃗ = randn(QuatVecF64, 6) + R = align(a⃗, b⃗) + # The matrix given in the docstring, whose dominant eigenvector is (w, x, y, z) + S = sum(vec(a⃗[i]) * vec(b⃗[i])' for i in eachindex(a⃗, b⃗)) + s⃗ = [S[2,3]-S[3,2], S[3,1]-S[1,3], S[1,2]-S[2,1]] + M = [tr(S) -s⃗'; -s⃗ (S + S' - tr(S) * I)] + v = eigen(Symmetric(M)).vectors[:, end] + @test min(abs(rotor(v...) - R), abs(rotor(v...) + R)) ≤ 1e-14 + + # The result rotates b⃗ onto a⃗ + R₀ = randn(RotorF64) + b⃗′ = conj(R₀).(a⃗) + R′ = align(a⃗, b⃗′) + @test maximum(abs, R′.(b⃗′) - a⃗) ≤ 1e-14 + + # Forming S no longer allocates for each point + function allocations(N) + a⃗, b⃗, w = randn(QuatVecF64, N), randn(QuatVecF64, N), rand(N) + align(a⃗, b⃗, w) + align(a⃗, b⃗) + (@allocated(align(a⃗, b⃗, w)), @allocated(align(a⃗, b⃗))) + end + small, large = allocations(10), allocations(1000) + @test large[1] ≤ small[1] + 256 + @test large[2] ≤ small[2] + 256 +end + +@testitem "to_float_array of a single quaternion" tags=[:unit, :fast] begin + f = to_float_array(quaternion(1, 2, 3, 4)) + @test f isa Vector{Float64} + @test f == [1.0, 2.0, 3.0, 4.0] + @test to_float_array(imx) == [0.0, 1.0, 0.0, 0.0] + @test to_float_array(rotor(1.0f0, 0, 0, 0)) isa Vector{Float32} +end + +@testitem "Zygote differentiates the conversions to static arrays" tags=[:unit, :fast, :ad] begin + using ForwardDiff, Zygote + + # Zygote cannot differentiate the `@SVector [...]` and `@SMatrix [...]` literal forms, + # which these functions used to build their results + u = [0.3, 0.5, -0.1, 0.8] + fs = ( + m -> to_rotation_matrix(quaternion(m...))[1, 2], + m -> to_rotation_matrix(quaternion(m...))[3, 1], + m -> to_euler_angles(quaternion(m...))[1], + m -> to_euler_angles(quaternion(m...))[2], + m -> real(to_euler_phases(quaternion(m...))[1]), + m -> imag(to_euler_phases(quaternion(m...))[2]), + m -> to_spherical_coordinates(quaternion(m...))[1], + m -> to_spherical_coordinates(quaternion(m...))[2], + ) + for f ∈ fs + @test Zygote.gradient(f, u)[1] ≈ ForwardDiff.gradient(f, u) atol=1e-14 + end +end diff --git a/test/regressions_core.jl b/test/regressions_core.jl new file mode 100644 index 00000000..d59a8fb6 --- /dev/null +++ b/test/regressions_core.jl @@ -0,0 +1,476 @@ +# Regression tests for the core types: construction, promotion, conversion, equality, +# hashing, display, and the `_sincu` helper. + +@testitem "core: QuatVec equality with quaternions and numbers" tags=[:unit, :fast] begin + v = quatvec(1.0, 2.0, 3.0) + q0 = quaternion(0.0, 1.0, 2.0, 3.0) + q5 = quaternion(5.0, 1.0, 2.0, 3.0) + + # The scalar part of the other operand must be zero + @test v == q0 + @test q0 == v + @test v != q5 + @test q5 != v + @test !isequal(v, q5) + @test !isequal(q5, v) + @test v != rotor(1.0, 1.0, 2.0, 3.0) + @test isequal(v, q0) + @test isequal(q0, v) + + # `==` is transitive through a QuatVec + @test !(q5 == v && v == q0) + + # A QuatVec equals a number exactly when both are zero + @test zero(QuatVecF64) == 0 + @test 0 == zero(QuatVecF64) + @test 𝐢 - 𝐢 == 0 + @test 0.0 == 𝐢 - 𝐢 + @test count(==(0), [𝐢 - 𝐢, quatvec(0.0, 0.0, 0.0), 𝐢]) == 2 + @test quatvec(1.0, 0.0, 0.0) != 0 + @test zero(QuatVecF64) != 1 + @test 1 != zero(QuatVecF64) +end + +@testitem "core: isequal agrees with hash across types" tags=[:unit, :fast] begin + pairs = [ + (quatvec(1.0, 2.0, 3.0), quaternion(0.0, 1.0, 2.0, 3.0)), + (quatvec(1.0, 2.0, 3.0), quaternion(-0.0, 1.0, 2.0, 3.0)), + (quatvec(1.0, 2.0, 3.0), quaternion(5.0, 1.0, 2.0, 3.0)), + (quatvec(1, 2, 3), quaternion(0.0, 1.0, 2.0, 3.0)), + (zero(QuatVecF64), 0.0), + (zero(QuatVecF64), -0.0), + (zero(QuatVecF64), 0), + (quaternion(1.0), 1.0), + (quaternion(1.0), 1), + (quaternion(1.0, -0.0, 0.0, 0.0), 1.0), + (quaternion(0.0), -0.0), + (quaternion(NaN), NaN), + (quaternion(2.5), 5//2), + (quaternion(1.0 + 2.0im), 1.0 + 2.0im), + ] + for (a, b) in pairs + @test isequal(a, b) == isequal(b, a) + if isequal(a, b) + @test hash(a) == hash(b) + end + end + @test isequal(quatvec(1.0, 2.0, 3.0), quaternion(0.0, 1.0, 2.0, 3.0)) + @test !isequal(quatvec(1.0, 2.0, 3.0), quaternion(-0.0, 1.0, 2.0, 3.0)) + @test isequal(zero(QuatVecF64), 0.0) + @test !isequal(zero(QuatVecF64), -0.0) + @test isequal(quaternion(1.0), 1.0) + @test !isequal(quaternion(1.0, -0.0, 0.0, 0.0), 1.0) + @test !isequal(quaternion(0.0), -0.0) + @test isequal(quaternion(NaN), NaN) + + # Set and Dict lookups merge values that are `isequal` + v = quatvec(1.0, 2.0, 3.0) + q0 = quaternion(0.0, 1.0, 2.0, 3.0) + @test length(Set([v, q0, quatvec(1, 2, 3)])) == 1 + @test haskey(Dict(v => 1), q0) + @test !haskey(Dict(v => 1), quaternion(5.0, 1.0, 2.0, 3.0)) +end + +@testitem "core: QuatVec never stores a scalar part" tags=[:unit, :fast] begin + for T in (Float64, Float32, Int) + q = quaternion(T(1), T(2), T(3), T(4)) + @test components(convert(QuatVec{T}, q))[1] == 0 + @test components(QuatVec{T}(1, 2, 3, 4))[1] == 0 + @test iszero(QuatVec{T}(1)) + w = QuatVec{T}[] + push!(w, q) + push!(w, T(2)) + @test all(x -> iszero(components(x)[1]), w) + @test iszero(w[2]) + @test w[1] == quatvec(q) + end + + # The multiplicative identity is not a pure vector, so these return Quaternions + @test one(QuatVecF64) === one(QuaternionF64) + @test oneunit(QuatVecF64) === one(QuaternionF64) + @test oneunit(quatvec(1.0, 2.0, 3.0)) === one(QuaternionF64) + # `ones` keeps the requested element type, so the scalar part of the identity is + # discarded, and no hidden scalar part is stored + @test ones(QuatVecF64, 2) isa Vector{QuatVecF64} + @test ones(QuatVecF64, 2, 3) isa Matrix{QuatVecF64} + @test ones(QuatVecF64, (2, 3)) isa Matrix{QuatVecF64} + @test ones(QuatVecF64) isa Array{QuatVecF64,0} + @test all(x -> iszero(components(x)), ones(QuatVecF64, 3)) + @test zeros(QuatVecF64, 2) isa Vector{QuatVecF64} + @test all(iszero, zeros(QuatVecF64, 2)) + + # The UnionAll types follow the same conventions + @test isone(one(QuatVec)) + @test isone(prod(QuatVec[])) + @test iszero(zero(Rotor)) + @test iszero(sum(Rotor[])) + + # A product of two equal-looking vectors does not depend on a hidden scalar + x = convert(QuatVec{Float64}, quaternion(1.0, 2.0, 3.0, 4.0)) + y = quatvec(1.0, 2.0, 3.0, 4.0) + @test x * x == y * y + @test hash(x) == hash(y) +end + +@testitem "core: Rotor promotion and conversion" tags=[:unit, :fast] begin + R = rotor(1, 2, 3, 4) + + # Mixing a Rotor with a plain number gives a Quaternion + @test promote_type(RotorF64, Float64) === QuaternionF64 + @test promote_type(RotorF32, Float64) === QuaternionF64 + @test promote_type(RotorF64, Int) === QuaternionF64 + @test promote_type(RotorF64, ComplexF64) === Quaternion{ComplexF64} + @test promote_type(RotorF64, QuaternionF32) === QuaternionF64 + @test promote_type(RotorF64, RotorF32) === RotorF64 + @test typeof(promote(R, 2.0)) === Tuple{QuaternionF64, QuaternionF64} + @test promote(R, 2.0)[2] == quaternion(2.0) + @test [R, 2.0] isa Vector{QuaternionF64} + @test [R, 1im] isa Vector{Quaternion{ComplexF64}} + + # Conversion to Rotor{T} normalizes, like `rotor` and `convert(Rotor, x)` + @test convert(Rotor, 3.0) == rotor(1.0) + @test convert(RotorF64, 3.0) == rotor(1.0) + @test convert(RotorF64, -3.0) == rotor(-1.0, 0, 0, 0) + @test convert(RotorF64, quaternion(1, 2, 3, 4)) ≈ R + @test convert(RotorF64, R) === R + @test convert(RotorF32, R) === RotorF32(R) + @test convert(Rotor{BigFloat}, quaternion(1, 2, 3, 4)) ≈ rotor(big.((1, 2, 3, 4))...) atol=10eps(BigFloat) + w = RotorF64[] + push!(w, 2.0) + push!(w, quaternion(1, 2, 3, 4)) + push!(w, quatvec(0, 0, 3)) + @test w[1] == rotor(1.0) + @test w[2] ≈ R + @test w[3] == rotor(0, 0, 0, 1) + @test all(x -> abs2(quaternion(x)) ≈ 1, w) + w[1] = quaternion(0, 5, 0, 0) + @test w[1] == rotor(0, 1, 0, 0) + + # The zero quaternion is not a unit quaternion, so `zero` gives a Quaternion. But `zeros` + # keeps the element type, filling the array with unnormalized zero rotors (rather than + # the NaN that normalizing them would give), so that it can be used for preallocation. + @test zero(RotorF64) === zero(QuaternionF64) + @test zeros(RotorF64, 2) isa Vector{RotorF64} + @test zeros(RotorF64, 2, 3) isa Matrix{RotorF64} + @test zeros(RotorF64, (2,)) isa Vector{RotorF64} + @test zeros(RotorF64, Int32(2)) isa Vector{RotorF64} + @test zeros(RotorF64) isa Array{RotorF64,0} + @test zeros(Rotor{Float32}, 2) isa Vector{Rotor{Float32}} + @test all(x -> iszero(components(x)), zeros(RotorF64, 3)) + let R⃗ = zeros(RotorF64, 4) + for i ∈ eachindex(R⃗) + R⃗[i] = rotor(1.0, i, 0.5i, -0.25i) + end + @test R⃗ isa Vector{RotorF64} + @test all(x -> abs2(quaternion(x)) ≈ 1, R⃗) + @test squad(R⃗, 1.0:4.0, 2.5) isa RotorF64 + end + + # Rounding a Rotor gives a Quaternion + @test round(rotor(1.0, 1.1, 0.2, 0.3)) === quaternion(1.0, 1.0, 0.0, 0.0) + @test round(quaternion(1.2, 2.7, 0.2, 0.3)) === quaternion(1.0, 3.0, 0.0, 0.0) +end + +@testitem "core: single-argument rotor" tags=[:unit, :fast] begin + @test rotor(2) === rotor(2, 0, 0, 0) + @test rotor(2) isa RotorF64 + @test rotor(true) isa RotorF64 + @test rotor(-2.0) == rotor(-1.0, 0, 0, 0) + @test all(isnan, components(rotor(0))) + @test all(isnan, components(rotor(-0.0))) + @test isnan(rotor(NaN)) + @test rotor(2.0 + 1im) ≈ Rotor{ComplexF64}(1, 0, 0, 0) + @test Base.return_types(rotor, (Vector{Int},)) == [RotorF64] + @test rotor([2]) === rotor(2) +end + +@testitem "core: indexing" tags=[:unit, :fast] begin + q = quaternion(1.0, 2.0, 3.0, 4.0) + @test q[end] == 4.0 + @test q[begin] == 1.0 + @test firstindex(q) == 1 + @test lastindex(q) == 4 + @test q[begin:end] == [1.0, 2.0, 3.0, 4.0] + @test q[2:end] == [2.0, 3.0, 4.0] + @test q[:] == [1.0, 2.0, 3.0, 4.0] + @test q[CartesianIndex()] === q + v = quatvec(2.0, 3.0, 4.0) + @test v[end] == 4.0 + @test v[:] == [0.0, 2.0, 3.0, 4.0] +end + +@testitem "core: conversion to real types" tags=[:unit, :fast] begin + @test Float64(quaternion(2.0)) === 2.0 + @test Float32(quaternion(2.0)) === 2.0f0 + @test Int(quaternion(3)) === 3 + @test Bool(quaternion(true)) === true + @test convert(Float64, quaternion(2.0)) === 2.0 + @test round(Int, quaternion(2.2)) === 2 + @test Float64(zero(QuatVecF64)) === 0.0 + x = zeros(2) + x[1] = quaternion(5.0) + @test x[1] === 5.0 + @test_throws InexactError Float64(quaternion(1.0, 1.0, 0.0, 0.0)) + @test_throws InexactError Float64(quatvec(1.0, 0.0, 0.0)) + @test_throws InexactError Int(quaternion(2.5)) +end + +@testitem "core: isapprox with complex components" tags=[:unit, :fast] begin + a1 = quaternion(1.0 + 1im, 2, 3, 4) + a2 = a1 + 1e-12 + @test a1 ≈ a2 + @test a1 ≈ a2 atol=1e-8 + @test a1 ≉ a1 + 1e-3 + @test a1 ≉ a2 rtol=0 atol=1e-14 + @test quaternion(1.0 + 0im) ≈ 1.0 + @test 1.0 ≈ quaternion(1.0 + 0im) + @test quaternion(1.0 + 1e-12im) ≈ 1.0 + @test quaternion(1.0 + 1im) ≉ 1.0 + @test Rotor{ComplexF64}(1, 0, 0, 0) ≈ quaternion(1.0) + @test quaternion(1.0) ≈ Rotor{ComplexF64}(1, 0, 0, 0) + @test quatvec(1.0 + 1im, 2, 3) ≈ quatvec(1.0 + 1im, 2, 3 + 1e-12) + @test a1 ≈ a1 + 1e-6 atol=1e-5 +end + +@testitem "core: plain-text display" tags=[:unit, :fast] begin + str(x) = sprint(show, x) + # The sign of a complex component stays inside its parentheses + @test str(quaternion(0, -1 + 2im, 0, 0)) == "0 + 0im + (-1 + 2im)𝐢 + (0 + 0im)𝐣 + (0 + 0im)𝐤" + @test str(quaternion(0.0, -1.0 + 2.0im, -3.0 - 4.0im, 1.0 - 2.0im)) == + "0.0 + 0.0im + (-1.0 + 2.0im)𝐢 + (-3.0 - 4.0im)𝐣 + (1.0 - 2.0im)𝐤" + @test str(quatvec(-1 - 2im, 0, 0)) == " + (-1 - 2im)𝐢 + (0 + 0im)𝐣 + (0 + 0im)𝐤" + # A single negative real may keep its sign outside the parentheses + @test str(quaternion(1.0, -3.0e-9, 2.0, -4.0)) == "1.0 - (3.0e-9)𝐢 + 2.0𝐣 - 4.0𝐤" + @test str(quaternion(1//2, -1//3, 0//1, 0//1)) == "1//2 - (1//3)𝐢 + (0//1)𝐣 + (0//1)𝐤" + # Non-finite and Bool components are followed by `*`, so that the output parses + @test str(quaternion(1.0, NaN, -Inf, Inf)) == "1.0 + NaN*𝐢 - Inf*𝐣 + Inf*𝐤" + @test str(quaternion(true, false, true, false)) == "true + false*𝐢 + true*𝐣 + false*𝐤" + for q in ( + quaternion(1.0, 0.0, 2.0, NaN), + quaternion(true, false, true, false), + quaternion(1.5, -Inf, 2.0, -3.0e-9), + quaternion(1.0 - 2.0im, -1.0 + 2.0im, 0.5im, -3.0), + ) + p = eval(Meta.parse(repr(q))) + @test isequal(components(p), components(q)) + end + # Vector components are printed with the IOContext, like the scalar part + @test sprint(show, quaternion(1/3, 2/3, 1.0, 2.0); context=:compact => true) == + "0.333333 + 0.666667𝐢 + 1.0𝐣 + 2.0𝐤" +end + +@testitem "core: Lorentz compositions at large rapidity" tags=[:unit, :fast] begin + relerr(a, b) = maximum(abs, components(a) .- components(b)) / maximum(abs, components(b)) + ẑ = [0.0, 0.0, 1.0] + for η in (20.0, 30.0, 40.0, 60.0) + exact = setprecision(BigFloat, 256) do + Boost(big(η), big.(ẑ)) + end + B = Boost(η / 2, ẑ) + @test B * B isa Rotor{ComplexF64} + @test relerr(B * B, exact) < 1e-14 + @test relerr(Boost(η / 4, ẑ) * Boost(3η / 4, ẑ), exact) < 1e-14 + @test relerr(B / Boost(-η / 2, ẑ), exact) < 1e-14 + @test all(isfinite, components(B * B)) + + # Products of noncollinear boosts with a rotation + x̂, ŷ = [1.0, 0.0, 0.0], [0.0, 1.0, 0.0] + R = rotor(1.0, 2.0, 3.0, 4.0) + P = Lorentz(R) * Boost(η / 3, ŷ) * Boost(η / 3, x̂) * Boost(η / 3, ẑ) + Pb = setprecision(BigFloat, 256) do + Lorentz(rotor(big.((1, 2, 3, 4))...)) * Boost(big(η) / 3, big.(ŷ)) * + Boost(big(η) / 3, big.(x̂)) * Boost(big(η) / 3, big.(ẑ)) + end + @test relerr(P, Pb) < 1e-14 + end + + # Real rotors are still renormalized + R1 = Rotor{Float64}(2.0, 0.0, 0.0, 0.0) # Deliberately not normalized + @test R1 * R1 == rotor(1.0) +end + +@testitem "core: long chains of Lorentz products at moderate rapidity" tags=[:unit, :fast] begin + using Random + using LinearAlgebra: normalize + # Each factor is a rotation seen in a frame boosted by rapidity 0.7. Its spinor norm is + # 1 only to rounding error, so a chain of products drifts unless products of complex + # rotors are renormalized while that is accurate. The reference multiplies the same + # factors, each normalized exactly, in BigFloat. + rng = Xoshiro(1234) + n̂ = normalize(randn(rng, 3)) + P, maxerr, maxdefect = setprecision(BigFloat, 128) do + P = Lorentz(rotor(1.0)) + Pb = Lorentz(rotor(big(1.0))) + maxerr = maxdefect = 0.0 + for i ∈ 1:3000 + F = Boost(0.7, n̂) * Lorentz(rotor(randn(rng, 4))) * Boost(-0.7, n̂) + P = P * F + Pb = Pb * rotor(Complex{BigFloat}.(components(F))) + maxerr = max(maxerr, Float64(maximum(abs, components(P) .- components(Pb)))) + maxdefect = max(maxdefect, abs(sum(z -> z * z, components(P)) - 1)) + end + P, maxerr, maxdefect + end + @test P isa Rotor{ComplexF64} + @test maxerr < 3e-14 + @test maxdefect < 1e-14 +end + +@testitem "core: _sincu derivatives near zero" tags=[:unit, :fast] begin + using ForwardDiff + import Quaternionic: _sincu + + # The `k`th derivative of sin(x)/x, from its Taylor series, evaluated in BigFloat + function reference(x, k) + setprecision(BigFloat, 1024) do + b = big(x) + sum(0:120) do n + p = 2n + p < k ? zero(BigFloat) : + (-1)^n / factorial(big(2n + 1)) * factorial(big(p)) / factorial(big(p - k)) * b^(p - k) + end + end + end + nth_derivative(f, n, t) = + n == 0 ? f(t) : ForwardDiff.derivative(τ -> nth_derivative(f, n - 1, τ), t) + + # The series is used below 3 for Float64 and Float32, and the closed form above it, so + # points on both sides of the threshold are included, where the errors are largest. The + # measured errors there are at most about 3 ulps for k ≤ 4 and 10 ulps for k = 5. + for T in (Float64, Float32) + points = vcat( + T[3.5, 3.1, 3.02, 2.98, 2.5, 2.0, 1.5, 1.0, 1e-1, 1e-2, 1e-4, 1e-6, 1e-8, 1e-12, 1e-16, 1e-20, -1e-8, -2.9], + [prevfloat(T(3), 2), prevfloat(T(3)), T(3), nextfloat(T(3)), nextfloat(T(3), 2)], + ) + bad = count((x, k) for x in points for k in 0:5) do (x, k) + d = nth_derivative(_sincu, k, x) + r = reference(x, k) + # The `k`th derivative near zero is of order 1/(k+1) + abs(d - r) > (k ≤ 4 ? 8 : 32) * eps(T) * max(abs(r), 1 / (k + 1)) + end + @test bad == 0 + end + + # BigFloat Duals also take the series, below a precision-dependent threshold, which is + # about 0.0285 for 256 bits + setprecision(BigFloat, 256) do + bad = count( + (x0, k) for x0 in (1e-1, 0.03, 0.0285, 0.028, 1e-3, 1e-5, 1e-10, 1e-20) for k in 0:4 + ) do (x0, k) + x = BigFloat(x0) + d = nth_derivative(_sincu, k, x) + r = reference(x, k) + abs(d - r) > 1e-66 * max(abs(r), 1 / (k + 1)) + end + @test bad == 0 + end +end + +@testitem "core: Hessians of exp near a zero vector part" tags=[:unit, :fast] begin + using ForwardDiff + W = [0.3, -0.7, 1.1, 0.5] + f(x) = sum(W .* components(exp(quaternion(x...)))) + g(x) = sum(W[2:4] .* vec(exp(quatvec(x...)))) + + # The references are independent of the package: the explicit formula + # exp(a + v⃗) = eᵃ (cos|v⃗| + v⃗ sin|v⃗|/|v⃗|), evaluated in 512-bit BigFloat, where sin(r)/r + # suffers no cancellation, and differentiated by central finite differences with a step + # of 2⁻¹³⁰, whose truncation and rounding errors are both below 1e-70. + function expref(a, v) + r = sqrt(sum(abs2, v)) + vcat(exp(a) * cos(r), exp(a) * sin(r) / r .* v) + end + fref(x) = sum(W .* expref(x[1], x[2:4])) + gref(x) = sum(W[2:4] .* expref(zero(eltype(x)), x)[2:4]) + function fd_hessian(F, p) + setprecision(BigFloat, 512) do + x = big.(p) + h = big(2)^-130 + n = length(x) + e(i) = [j == i ? h : zero(h) for j in 1:n] + [(F(x + e(i) + e(j)) - F(x + e(i) - e(j)) - F(x - e(i) + e(j)) + F(x - e(i) - e(j))) / (4h^2) + for i in 1:n, j in 1:n] + end + end + + for s in (1e-4, 1e-8, 1e-12, 1e-20) + p = [0.7, s, -2s, 0.5s] + H = ForwardDiff.hessian(f, p) + Hb = fd_hessian(fref, p) + @test maximum(abs, H - Hb) < 4e-15 * maximum(abs, Hb) + pv = [s, -2s, 0.5s] + Hv = ForwardDiff.hessian(g, pv) + Hvb = fd_hessian(gref, pv) + @test maximum(abs, Hv - Hvb) < 1e-14 * max(maximum(abs, Hvb), s) + end +end + +@testitem "core: random quaternion statistics" tags=[:unit] begin + using Random + mean(f, x) = sum(f, x) / length(x) + mean(x) = mean(identity, x) + var(x) = (m = mean(x); sum(y -> (y - m)^2, x) / (length(x) - 1)) + rng = MersenneTwister(20240917) + N = 200_000 + q = randn(rng, QuaternionF64, N) + for i in 1:4 + cᵢ = [x[i] for x in q] + @test abs(mean(cᵢ)) < 5 * sqrt(1 / 4 / N) + @test abs(var(cᵢ) - 1 / 4) < 0.01 + end + @test abs(mean(abs2, q) - 1) < 0.01 + + v = randn(rng, QuatVecF64, N) + @test all(x -> iszero(x[1]), v) + for i in 2:4 + @test abs(var([x[i] for x in v]) - 1 / 3) < 0.01 + end + + # The rotation angle of a uniformly random rotation has E[cos θ] = -1/2, where + # cos θ = 2w² - 1 for a unit rotor with scalar part w + R = randn(rng, RotorF64, N) + @test abs(mean(r -> 2r[1]^2 - 1, R) + 1 / 2) < 0.01 +end + +@testitem "core: ReverseDiff through rotor and complex norms" tags=[:unit, :fast] begin + using ReverseDiff, ForwardDiff + + # `_hypot` squares complex components by multiplication, which ReverseDiff can handle + f(x) = real(abs(quaternion(complex(x[1], x[2]), complex(x[3], 0.1), 0.3, 0.2))) + x₀ = [0.7, 0.2, -0.4] + @test ReverseDiff.gradient(f, x₀) ≈ ForwardDiff.gradient(f, x₀) rtol=1e-14 + + # `rotor` normalizes without a broadcast, so recorded tapes can be replayed + W = [0.3, -0.2, 0.5, 0.7] + g(x) = sum(W .* components(rotor(x[1], x[2], x[3], x[4]))) + h(x) = sum(W .* components(rotor(x[1], x[2], x[3], x[4]) * rotor(x[4], x[3], x[2], x[1]))) + q₀ = [0.4, -0.3, 0.8, 0.1] + for F in (g, h) + tape = ReverseDiff.GradientTape(F, q₀) + @test ReverseDiff.gradient!(similar(q₀), tape, q₀) ≈ ForwardDiff.gradient(F, q₀) rtol=1e-14 + compiled = ReverseDiff.compile(tape) + @test ReverseDiff.gradient!(similar(q₀), compiled, q₀) ≈ ForwardDiff.gradient(F, q₀) rtol=1e-14 + end +end + +@testitem "core: reverse-mode gradients with respect to Rotor arguments" tags=[:unit, :fast, :ad] begin + using ForwardDiff, Zygote + # `convert(Rotor{T}, x)` normalizes, so the projection of a cotangent onto a `Rotor` + # argument must not use `convert`; a cotangent is not a unit quaternion. Each gradient + # is compared with ForwardDiff with respect to the raw components. + q = quaternion(0.3, -0.2, 0.5, 0.7) + f(R) = (R * q)[1] + R = rotor(1.0, 2.0, 3.0, 4.0) + gz = Zygote.gradient(f, R)[1] + gf = ForwardDiff.gradient(c -> f(Rotor{eltype(c)}(c)), Vector(components(R))) + @test components(gz) ≈ gf rtol=1e-14 + + fv(Rs) = sum(x -> (x * q)[2], Rs) + Rs = [rotor(1.0, 2.0, 3.0, 4.0), rotor(0.5, -1.0, 0.2, 0.3)] + gzv = Zygote.gradient(fv, Rs)[1] + gfv = ForwardDiff.gradient( + c -> fv([Rotor{eltype(c)}(c[1:4]), Rotor{eltype(c)}(c[5:8])]), + vcat(Vector(components(Rs[1])), Vector(components(Rs[2]))) + ) + @test vcat(Vector(components(gzv[1])), Vector(components(gzv[2]))) ≈ gfv rtol=1e-14 +end diff --git a/test/regressions_interp.jl b/test/regressions_interp.jl new file mode 100644 index 00000000..faa55f42 --- /dev/null +++ b/test/regressions_interp.jl @@ -0,0 +1,364 @@ +# Regression tests for the analytic gradients of `log` and `exp`, for `slerp∂slerp`, and +# for `unflip` and `squad`. The references are either high-precision finite differences in +# `BigFloat` or ForwardDiff applied to the plain functions. + +@testmodule InterpReference begin + using Quaternionic + + # The off-shell extension of `log` that `∂log` differentiates, written out explicitly. + function log_reference(q::Quaternion{BigFloat}) + w = q[1] + a = sqrt(q[2]^2 + q[3]^2 + q[4]^2) + f = iszero(a) ? 1 / w : atan(a, w) / a + log(abs(q)) + f * Quaternion{BigFloat}(0, q[2], q[3], q[4]) + end + + # The off-shell extension of `exp` that `∂exp` differentiates, written out explicitly. + function exp_reference(q::Quaternion{BigFloat}) + a = sqrt(q[2]^2 + q[3]^2 + q[4]^2) + g = iszero(a) ? one(a) : sin(a) / a + exp(q[1]) * (cos(a) + g * Quaternion{BigFloat}(0, q[2], q[3], q[4])) + end + + # Central finite differences of `F` at `q` along each component, in 1024-bit BigFloat. + function gradient_reference(F, q) + setprecision(BigFloat, 1024) do + h = big"1e-120" + Q = Quaternion{BigFloat}(components(q)...) + basis = [Quaternion{BigFloat}((1:4 .== k)...) for k in 1:4] + [(F(Q + h*b) - F(Q - h*b)) / (2h) for b in basis] + end + end + + maxabs(q::AbstractQuaternion) = maximum(abs, components(q)) + maxerr(a, b) = maximum(maxabs(Quaternion{BigFloat}(components(x)...) - y) for (x, y) in zip(a, b)) + + # Machine epsilon of the working precision; BigFloat inputs are made with 256 bits. + working_eps(::Type{T}) where {T} = eps(T) + working_eps(::Type{BigFloat}) = big(2.0)^-255 + + export log_reference, exp_reference, gradient_reference, maxabs, maxerr, working_eps +end + + +@testitem "∂log and log∂log are accurate near the identity and the antipode" setup=[InterpReference] tags=[:unit, :validation] begin + n̂ = normalize(QuatVecF64(0, 0.3, -0.5, 0.8)) + for T in (Float64, Float32, BigFloat) + ϵ = working_eps(T) + for size in (1, 1e-2, 1e-4, 1e-8, 1e-12, 0), antipode in (false, true) + # The exact antipode is a singular point of the logarithm. + antipode && size == 0 && continue + Z, (l, ∂l), ∂l′ = setprecision(BigFloat, 256) do + R = exp(T(size) * QuatVec{T}(n̂)) + Z = antipode ? -R : R + Z, log∂log(Z), ∂log(Z) + end + ref = gradient_reference(log_reference, Z) + scale = maximum(maxabs, ref) + @test maxerr(∂l, ref) ≤ 10ϵ * scale + @test maxerr(∂l′, ref) ≤ 10ϵ * scale + lref = setprecision(BigFloat, 1024) do + quatvec(log_reference(Quaternion{BigFloat}(components(Z)...))) + end + @test l isa QuatVec + @test maxerr([quaternion(l)], [quaternion(lref)]) ≤ 10ϵ * max(maxabs(lref), floatmin(T)) + end + end + # The identity itself + @test ∂log(rotor(1)) == QuaternionF64[1, imx, imy, imz] + l, ∂l = log∂log(rotor(1.0)) + @test iszero(l) + @test ∂l == QuaternionF64[1, imx, imy, imz] + # The antipode returns the same value as `log` + @test log∂log(-rotor(1.0))[1] == log(-rotor(1.0)) +end + + +@testitem "∂exp and exp∂exp are accurate near zero" setup=[InterpReference] tags=[:unit, :validation] begin + n̂ = normalize(QuatVecF64(0, 0.3, -0.5, 0.8)) + for T in (Float64, Float32, BigFloat) + ϵ = working_eps(T) + for size in (3, 1, 1e-1, 1e-2, 1e-4, 1e-8, 1e-12, 0) + Z, (e, ∂e), ∂e′ = setprecision(BigFloat, 256) do + Z = T(size) * QuatVec{T}(n̂) + Z, exp∂exp(Z), ∂exp(Z) + end + ref = gradient_reference(exp_reference, Z) + @test maxerr(∂e, ref) ≤ 10ϵ + @test maxerr(∂e′, ref) ≤ 10ϵ + eref = setprecision(BigFloat, 1024) do + exp_reference(Quaternion{BigFloat}(components(Z)...)) + end + @test e isa Rotor + @test maxerr([e], [eref]) ≤ 10ϵ + # The tiny vector part is kept, rather than being rounded to zero + @test maxerr([quaternion(quatvec(e))], [quaternion(quatvec(eref))]) ≤ 10ϵ * max(maxabs(quatvec(eref)), floatmin(T)) + end + end +end + + +@testitem "Nested ForwardDiff through the analytic gradients at the identity" setup=[InterpReference] tags=[:unit, :validation] begin + using ForwardDiff + D = ForwardDiff.derivative + v = QuatVecF64(0, 0.3, -0.5, 0.8) + c = QuatVecF64(0, 0.1, 0.2, -0.3) + + # The values carry the partials of the input + @test D(t -> log∂log(exp(t*v))[1], 0.0) ≈ v atol=2eps() + @test D(t -> exp∂exp(t*v)[1], 0.0) ≈ v atol=2eps() + + # Derivatives of the gradients along curves through the special points, compared with + # finite differences of the BigFloat finite-difference gradients + Zcurve(t) = Rotor{typeof(t)}(1 + t/5, 3t/10, -t/2, 4t/5) # Not normalized: off shell + for t₀ in (0.0, 1e-12, 1e-8, 1e-4, 0.5) + d = D(t -> ∂log(Zcurve(t)), t₀) + ref = setprecision(BigFloat, 1024) do + h = big"1e-50" + (gradient_reference(log_reference, Zcurve(big(t₀)+h)) .- gradient_reference(log_reference, Zcurve(big(t₀)-h))) ./ (2h) + end + @test maxerr(d, ref) ≤ 10eps() + end + for t₀ in (0.0, 1e-12, 1e-8, 1e-4, 0.5), offset in (0, 1) + d = D(t -> ∂exp(t*v + offset*c), t₀) + ref = setprecision(BigFloat, 1024) do + h = big"1e-50" + vb, cb = QuatVec{BigFloat}(components(v)...), QuatVec{BigFloat}(components(c)...) + (gradient_reference(exp_reference, (big(t₀)+h)*vb + offset*cb) .- gradient_reference(exp_reference, (big(t₀)-h)*vb + offset*cb)) ./ (2h) + end + @test maxerr(d, ref) ≤ 10eps() + end +end + + +@testitem "slerp∂slerp for nearly equal rotors" tags=[:unit, :validation] begin + using ForwardDiff, Random + D = ForwardDiff.derivative + Random.seed!(1234) + one_ = Quaternion{Bool}(true, false, false, false) + n̂ = normalize(QuatVecF64(0, 0.3, -0.5, 0.8)) + for q₁ in randn(RotorF64, 3), size in (1, 1e-2, 1e-4, 1e-8, 1e-12, 0), τ in (0.0, 0.3, 1.0) + q₂ = exp(size * n̂) * q₁ + s, ∂s∂q₁, ∂s∂q₂, ∂s∂τ = slerp∂slerp(q₁, q₂, τ) + @test s isa Rotor + @test distance(s, slerp(q₁, q₂, τ)) ≤ 4eps() + for (k, b) in enumerate((one_, imx, imy, imz)) + @test ∂s∂q₁[k] ≈ D(ϵ -> slerp(q₁ + ϵ*b, q₂, τ), 0.0) atol=10eps() + @test ∂s∂q₂[k] ≈ D(ϵ -> slerp(q₁, q₂ + ϵ*b, τ), 0.0) atol=10eps() + end + @test ∂s∂τ ≈ slerp∂slerp∂τ(q₁, q₂, τ)[2] atol=4eps() + end + # The value at τ = 0 carries the partials of τ + q₁, q₂ = randn(RotorF64, 2) + @test D(τ -> slerp∂slerp(q₁, q₂, τ)[1], 0.0) ≈ D(τ -> slerp(q₁, q₂, τ), 0.0) atol=10eps() + @test D(τ -> slerp∂slerp(q₁, q₁, τ)[1], 0.0) ≈ zero(QuaternionF64) atol=10eps() +end + + +@testitem "squad derivatives agree with ForwardDiff for finely sampled data" tags=[:unit, :validation] begin + using ForwardDiff, Random + D = ForwardDiff.derivative + R, ω⃗, Ṙ = precessing_nutating_example() + for N in (100, 1000) + tin = collect(range(0, 1, length=N)) + Rin = rotor.(R.(tin)) + tout = sort([tin[1:7:end]; tin[end]; rand(Random.MersenneTwister(N), 50)]) + Rplain = squad(Rin, tin, tout) + R₁, Ω⃗₁, Ṙ₁ = squad(Rin, tin, tout; compute_angular_velocity=true, compute_derivative=true) + R₂, Ṙ₂ = squad(Rin, tin, tout; compute_derivative=true) + R₃, Ω⃗₃ = squad(Rin, tin, tout; compute_angular_velocity=true) + ṘFD = [D(t -> squad(Rin, tin, t), t) for t in tout] + Ω⃗FD = [2quatvec(ṘFD[k] / Rplain[k]) for k in eachindex(tout)] + # Both derivatives are limited by the conditioning of the interpolant: rounding + # errors of size eps in the input rotors become relative errors of about eps/(|Ω| dt) + # in Ṙ, with |Ω| ≈ 6e-3. Before the accuracy of `log∂log` was fixed, the analytic + # derivative had relative errors of about 1e-6 here. + scale = maximum(abs, ṘFD) + @test maximum(abs, Ṙ₁ .- ṘFD) ≤ 1e-13 * N * scale + @test maximum(abs, Ω⃗₁ .- Ω⃗FD) ≤ 2e-13 * N * scale + # The rotors agree with those computed without derivatives + @test maximum(distance.(Rplain, R₁)) ≤ 4eps() + @test R₁ == R₂ == R₃ + @test Ṙ₁ == Ṙ₂ + @test Ω⃗₁ == Ω⃗₃ + end +end + + +@testitem "Nested ForwardDiff through squad derivatives at the knots" tags=[:unit, :validation] begin + using ForwardDiff + D = ForwardDiff.derivative + qs = [exp(quatvec(0.3k, sin(k), 0.2cos(2k))) for k in 1:6] + ts = collect(1.0:6.0) + for t in (1.0, 1.0 + 1e-9, 2.0, 2.5, 3.0, 6.0) + @test D(τ -> squad(qs, ts, τ; compute_derivative=true)[2], t) ≈ D(s -> D(τ -> squad(qs, ts, τ), s), t) atol=20eps() + end +end + + +@testitem "ForwardDiff of squad at the first and last knots" tags=[:unit, :validation] begin + using ForwardDiff + D = ForwardDiff.derivative + qs = [exp(quatvec(0.3k, sin(k), 0.2cos(2k))) for k in 1:6] + ts = collect(1.0:6.0) + # One-sided BigFloat finite differences + function reference(t, side) + setprecision(BigFloat, 512) do + Rb = [Rotor{BigFloat}(components(q)...) for q in qs] + tb, h = big.(ts), side * big"1e-40" + T = big(t) + (-3squad(Rb, tb, T) + 4squad(Rb, tb, T + h) - squad(Rb, tb, T + 2h)) / (2h) + end + end + for (t, side) in ((1.0, 1), (6.0, -1)) + ref = reference(t, side) + @test D(τ -> squad(qs, ts, τ), t) ≈ ref atol=10eps() + @test D(τ -> squad(qs, ts, -τ), -t) ≈ -ref atol=10eps() + @test squad(qs, ts, t; compute_derivative=true)[2] ≈ ref atol=10eps() + end +end + + +@testitem "squad time types and range errors" tags=[:unit, :validation] begin + using ForwardDiff + import Quaternionic: squad! + qs = [exp(quatvec(0.3k, sin(k), 0.2cos(2k))) for k in 1:6] + ts = collect(1.0:6.0) + # Integer and rational times + @test squad(qs, 1:6, 2.5) ≈ squad(qs, ts, 2.5) + @test squad(qs, collect(1:6), [2, 3]) ≈ squad(qs, ts, [2.0, 3.0]) + @test squad(qs, collect(1//1:6//1), 5//2) ≈ squad(qs, ts, 2.5) + # Out-of-range times give the range error at either end + @test_throws ErrorException squad(qs, ts, 0.5) + @test_throws ErrorException squad(qs, ts, 6.5) + @test_throws ErrorException squad(qs, ts, [0.5, 1.0]) + @test_throws ErrorException squad(qs, ts, [5.5, 6.5]) + @test_throws ArgumentError squad(qs, ts, [2.0, 6.5]; validate=true) + @test_throws ArgumentError squad(qs, ts, [3.0, 2.0]; validate=true) + @test_throws ArgumentError squad(qs, [1.0, 2.0, 2.0, 4.0, 5.0, 6.0], 2.5; validate=true) + @test_throws ArgumentError squad(qs[1:5], ts, 2.5) + # A repeated first time is allowed + @test squad(qs, ts, [1.0, 1.0]) == [qs[1], qs[1]] + @test squad(qs, ts, 1.0) == qs[1] + # Derivatives with respect to the knot times + e₃ = (1:6 .== 3) + d = ForwardDiff.derivative(h -> squad(qs, ts .+ h .* e₃, 2.5), 0.0) + ref = setprecision(BigFloat, 512) do + Rb = [Rotor{BigFloat}(components(q)...) for q in qs] + h = big"1e-40" + (squad(Rb, big.(ts) .+ h .* e₃, big(2.5)) - squad(Rb, big.(ts) .- h .* e₃, big(2.5))) / (2h) + end + @test d ≈ ref atol=10eps() + # The documented four-argument method of `squad!` + Rout = Vector{RotorF64}(undef, 3) + squad!(Rout, qs, ts, [1.5, 2.5, 3.5]) + @test Rout == squad(qs, ts, [1.5, 2.5, 3.5]) +end + + +@testitem "squad_control_points and squad infer concrete types" tags=[:unit, :fast] begin + import Quaternionic: squad_control_points + qs = [exp(quatvec(0.3k, sin(k), 0.2cos(2k))) for k in 1:6] + ts = collect(1.0:6.0) + for i in 1:6 + @test (@inferred squad_control_points(qs, ts, i)) isa Tuple{RotorF64, RotorF64} + end + # The control point past the end extrapolates linearly + @test squad_control_points(qs, ts, 6)[2] ≈ qs[6] * conj(qs[5]) * qs[6] + @test (@inferred squad_control_points(qs, 1:6, 3)) isa Tuple{RotorF64, RotorF64} + if VERSION ≥ v"1.10" + sq(R, t, τ) = squad(R, t, τ) + sqΩṘ(R, t, τ) = squad(R, t, τ; compute_angular_velocity=true, compute_derivative=true) + @test (@inferred sq(qs, ts, [1.5, 2.5])) isa Vector{RotorF64} + @test (@inferred sq(qs, ts, 2.5)) isa RotorF64 + @test (@inferred sqΩṘ(qs, ts, 2.5)) isa Tuple{RotorF64, QuatVecF64, QuaternionF64} + end +end + + +@testitem "unflip edge cases" tags=[:unit, :fast] begin + # Empty arrays along the unflipped dimension + @test unflip(QuaternionF64[]) == QuaternionF64[] + @test size(unflip(Array{QuaternionF64}(undef, 3, 0); dim=2)) == (3, 0) + @test size(unflip(Array{QuaternionF64}(undef, 0, 3); dim=1)) == (0, 3) + @test unflip!(QuaternionF64[]) == QuaternionF64[] + # `unflip!` returns its argument + q = [imx, -imx, imx, -imx] + p = unflip!(q) + @test p === q + @test q == [imx, imx, imx, imx] + # Complex quaternions, using the real part of the inner product + qc = [ + Quaternion{ComplexF64}(1 + 0.1im, 0.2im, 0, 0.1), + -Quaternion{ComplexF64}(1 + 0.2im, 0.1im, 0, 0.1), + Quaternion{ComplexF64}(1, 0, 0.3im, 0), + ] + expected = [qc[1], -qc[2], qc[3]] + @test unflip(qc) == expected + @test unflip!(copy(qc)) == expected + @test slerp(qc[1], qc[2], 0.3; unflip=true) ≈ slerp(qc[1], -qc[2], 0.3) +end + + +@testitem "Analytic-gradient docstring examples run" tags=[:unit, :fast] begin + ∂log∂w, ∂log∂x, ∂log∂y, ∂log∂z = ∂log(randn(RotorF64)) + @test ∂log∂w isa Quaternion + (q₁, q₂), τ = randn(RotorF64, 2), rand() + s, ∂s∂q₁, ∂s∂q₂, ∂s∂τ = slerp∂slerp(q₁, q₂, τ) + @test length(∂s∂q₁) == length(∂s∂q₂) == 4 +end + + +@testitem "log∂log near the antipode with an underflowing vector norm" setup=[InterpReference] tags=[:unit, :validation] begin + # For vector parts below about 1.5e-154, `abs2vec` underflows to zero, but the logarithm + # still points along the vector part, as `log` does. + for s in (1e-100, 1e-170, 1e-200, 1e-300) + Z = Rotor{Float64}(-1, 3s, -5s, 8s) + l, ∂l = log∂log(Z) + @test maxabs(quaternion(l) - quaternion(log(Z))) ≤ 4eps() + @test all(isfinite, components(quaternion(l))) + ref = setprecision(BigFloat, 4096) do + Q = Quaternion{BigFloat}(components(Z)...) + h = absvec(Q) * big"1e-60" + basis = [Quaternion{BigFloat}((1:4 .== k)...) for k in 1:4] + [(log_reference(Q + h*b) - log_reference(Q - h*b)) / (2h) for b in basis] + end + for i in 1:4 + @test maxerr([∂l[i]], [ref[i]]) ≤ 10eps() * maxabs(ref[i]) + end + end +end + + +@testitem "squad handles tout in any order" tags=[:unit, :fast] begin + qs = [exp(quatvec(0.3k, sin(k), 0.2cos(2k))) for k in 1:6] + ts = collect(1.0:6.0) + touts = [3.5, 1.5, 5.5, 1.0, 6.0, 2.0, 2.0, 4.25] + one_at_a_time = [squad(qs, ts, t) for t in touts] + @test squad(qs, ts, touts) == one_at_a_time + R, Ω, Ṙ = squad(qs, ts, touts; compute_angular_velocity=true, compute_derivative=true) + @test R ≈ one_at_a_time + @test Ω ≈ [squad(qs, ts, t; compute_angular_velocity=true)[2] for t in touts] + @test Ṙ ≈ [squad(qs, ts, t; compute_derivative=true)[2] for t in touts] + # Out-of-range times are still caught in any position. + @test_throws ErrorException squad(qs, ts, [3.5, 0.5]) + @test_throws ErrorException squad(qs, ts, [3.5, 6.5, 2.0]) +end + + +@testitem "unflip! on Rotor arrays negates exactly" tags=[:unit, :fast] begin + qs = [exp(quatvec(0.3k, sin(k), 0.2cos(2k))) for k in 1:6] + r = [qs[1], -qs[2], qs[3], -qs[4]] + p = unflip!(copy(r)) + @test p isa Vector{RotorF64} + @test p == unflip(r) + @test p == qs[1:4] + @test p[2] === -r[2] + @test p[4] === -r[4] + # The same holds along the second dimension of a matrix. + m = permutedims(hcat(r, r)) + pm = unflip!(copy(m); dim=2) + @test pm isa Matrix{RotorF64} + @test pm == unflip(m; dim=2) + @test pm[1, :] == qs[1:4] +end diff --git a/test/regressions_lorentz.jl b/test/regressions_lorentz.jl new file mode 100644 index 00000000..505f7c45 --- /dev/null +++ b/test/regressions_lorentz.jl @@ -0,0 +1,347 @@ +# Regression tests for fixes to src/Lorentz.jl. +# +# Reference values are computed independently of the package, from explicit 4×4 matrices or +# closed-form expressions evaluated in BigFloat. + +@testmodule LorentzReference begin + using LinearAlgebra + + # The 4×4 matrix of an active boost with rapidity η along the unit direction n + function boost_matrix(η, n) + ch, sh = cosh(η), sinh(η) + [ch sh*n'; sh*n I + (ch - 1)*n*n'] + end + + # The derivative of `boost_matrix` with respect to η + function boost_matrix_derivative(η, n) + ch, sh = cosh(η), sinh(η) + [sh ch*n'; ch*n sh*n*n'] + end + + # The 4×4 matrix of the rotation given by the unit quaternion with components (w, x, y, z) + function rotation_matrix(w, x, y, z) + R = [ + 1-2(y^2+z^2) 2(x*y-w*z) 2(x*z+w*y); + 2(x*y+w*z) 1-2(x^2+z^2) 2(y*z-w*x); + 2(x*z-w*y) 2(y*z+w*x) 1-2(x^2+y^2) + ] + [one(w) zeros(typeof(w), 1, 3); zeros(typeof(w), 3, 1) R] + end + + # The 4×4 matrix of the action of Λ on 4-vectors, column by column + function action_matrix(Λ, ::Type{T}) where {T} + e(i) = T[j == i for j ∈ 1:4] + reduce(hcat, [Λ(e(i)) for i ∈ 1:4]) + end + + # The components (cosh(η/2), sinh(η/2) v⃗/β) of `Boost(v⃗)`, from the rapidity η = atanh(β) + function boost_from_velocity(v) + β = norm(v) + η = atanh(β) + shc = iszero(β) ? one(β)/2 : sinh(η/2)/β + [cosh(η/2); shc .* v] + end +end + +@testitem "Lorentz regressions: the action promotes the element type" tags=[:unit, :fast] setup=[LorentzReference] begin + using StaticArrays, ForwardDiff, LinearAlgebra + using .LorentzReference: boost_matrix, boost_matrix_derivative + + n = [0.6, -0.48, 0.64] + Λ = Boost(0.5, n) + M = boost_matrix(big(0.5), big.(n)) + + v = [1, 0, 0, 0] + @test Λ(v) isa Vector{Float64} + @test Λ(v) ≈ Float64.(M * v) rtol=4eps() + @test Λ(Float32[1, 0, 0, 0]) isa Vector{Float64} + @test Λ(Float32[1, 0, 0, 0]) ≈ Float64.(M * v) rtol=4eps() + w = view([0.3, 1.2, -0.5, 0.7, 9.0], 1:4) + @test Λ(w) isa Vector{Float64} + @test Λ(w) ≈ Float64.(M * big.(w)) rtol=4eps() + @test Λ(SA[1, 0, 0, 0]) isa SVector{4, Float64} + @test Λ(SA[1, 0, 0, 0]) ≈ Λ(v) rtol=4eps() + @test Λ(1:4) isa Vector{Float64} + @test Λ(1:4) ≈ Float64.(M * (1:4)) rtol=4eps() + @test Λ(MVector(1, 0, 0, 0)) isa MVector{4, Float64} + @test Λ(MVector(1, 0, 0, 0)) ≈ Float64.(M * v) rtol=4eps() + + # A BigFloat transformation is not narrowed to the element type of the vector + nB = normalize(big.(n)) + ΛB = Boost(big(0.5), nB) + MB = boost_matrix(big(0.5), nB) + @test ΛB([0.3, 1.2, -0.5, 0.7]) isa Vector{BigFloat} + @test ΛB([0.3, 1.2, -0.5, 0.7]) ≈ MB * big.([0.3, 1.2, -0.5, 0.7]) rtol=100eps(BigFloat) + + @test_throws DimensionMismatch Λ([1.0, 0.0, 0.0]) + @test_throws DimensionMismatch Λ([1.0, 0.0, 0.0, 0.0, 0.0]) + + # ForwardDiff through the transformation applied to an ordinary `Vector` + v4 = [0.3, 1.2, -0.5, 0.7] + for η ∈ (0.0, 0.4, 2.0) + d = ForwardDiff.derivative(t -> Boost(t, n)(v4), η) + @test d ≈ Float64.(boost_matrix_derivative(big(η), big.(n)) * big.(v4)) atol=8eps(cosh(η)) + end +end + +@testitem "Lorentz regressions: Boost promotes the element type" tags=[:unit, :fast] begin + using ForwardDiff, LinearAlgebra + + n = [0.6, -0.48, 0.64] + @test Boost(1, [0, 0, 1]) isa Lorentz{Float64} + @test components(Boost(1, [0, 0, 1])) ≈ components(Boost(1.0, [0.0, 0.0, 1.0])) + @test Boost(0.7f0, n) isa Lorentz{Float64} + @test Boost(0.7f0, QuatVec(n...)) isa Lorentz{Float64} + @test Boost(0.7, Float32.(n)) isa Lorentz{Float64} + @test Boost(0.7f0, Float32.(n)) isa Lorentz{Float32} + @test Boost(0.7, big.(n)) isa Lorentz{BigFloat} + + # The result is as precise as its element type claims, so a Float32 rapidity does not + # limit the precision of a Float64 result, and similarly for BigFloat. + spinor_norm_defect(L) = abs(sum(components(L) .^ 2) - 1) + @test spinor_norm_defect(Boost(0.7f0, n)) ≤ 4eps() + @test spinor_norm_defect(Boost(0.7f0, QuatVec(n...))) ≤ 4eps() + @test components(Boost(0.7f0, n)) ≈ components(Boost(Float64(0.7f0), n)) rtol=4eps() + nB = normalize(big.(n)) + @test spinor_norm_defect(Boost(0.7, nB)) ≤ 10eps(BigFloat) + @test components(Boost(0.7, nB)) ≈ components(Boost(big(0.7), nB)) rtol=10eps(BigFloat) + @test components(Boost(0.7, QuatVec(nB...))) ≈ components(Boost(big(0.7), nB)) rtol=10eps(BigFloat) + @test Boost([0, 0, 0]) isa Lorentz{Float64} + @test Boost([1//3, 0, 0]) isa Lorentz{Float64} + @test components(Boost([1//3, 0, 0])) ≈ components(Boost(atanh(1/3), [1.0, 0, 0])) + + # Differentiation with respect to the direction alone. The components are + # (cosh(η/2), im*sinh(η/2)*n), so this weighted sum has gradient sinh(η/2) .* [2, 3, 4]. + weighted(L) = sum(real.(components(L))) + sum(imag.(components(L)) .* (1:4)) + expected = sinh(0.25) .* [2, 3, 4] + @test ForwardDiff.gradient(nn -> weighted(Boost(0.5, nn)), n) ≈ expected rtol=4eps() + @test ForwardDiff.gradient(nn -> weighted(Boost(0.5, quatvec(nn...))), n) ≈ expected rtol=4eps() +end + +@testitem "Lorentz regressions: Boost from a velocity" tags=[:unit, :fast] setup=[LorentzReference] begin + using ForwardDiff, LinearAlgebra + using .LorentzReference: boost_from_velocity + + function boost_components(v) + c = components(Boost(v)) + [real(c[1]); imag.(c[2:4])] + end + + dir = [0.6, -0.48, 0.64] + setprecision(BigFloat, 256) do + # Values, including velocities so small that β² underflows + for s ∈ (0.0, 1e-300, 1e-170, 1e-16, 1e-8, 1e-3, 0.3, 0.9, 0.99) + v = s .* dir + b = boost_components(v) + r = boost_from_velocity(big.(v)) + @test all(isfinite, b) + @test maximum(abs.(b .- r) ./ abs.(r .+ (r .== 0))) ≤ 10eps() / (1 - s^2) + end + + # Second derivatives near zero velocity, compared with central finite differences + # of the BigFloat reference + W = [0.3, -1.1, 0.7, 0.45] + F(x) = W ⋅ boost_components(x) + Fref(x) = W ⋅ boost_from_velocity(x) + h = big"1e-25" + function hessian_reference(x) + e(i) = BigFloat[j == i ? h : 0 for j ∈ 1:3] + [(Fref(x+e(i)+e(j)) - Fref(x+e(i)-e(j)) - Fref(x-e(i)+e(j)) + Fref(x-e(i)-e(j))) / 4h^2 + for i ∈ 1:3, j ∈ 1:3] + end + for s ∈ (0.0, 1e-12, 1e-8, 1e-5, 0.3) + x = s .* dir + # Offset the reference point slightly from zero to avoid its special case there + Href = hessian_reference(big.(x) .+ (s == 0 ? big"1e-40" : big(0))) + @test maximum(abs.(ForwardDiff.hessian(F, x) .- Href)) ≤ 2eps() + end + end + + # The QuatVec and AbstractVector forms agree with the rapidity form + for v ∈ ([0.5, 0.0, 0.0], [0.2, 0.2, 0.2], [0.0, -0.3, 0.4]) + β = norm(v) + @test components(Boost(QuatVec(v...))) == components(Boost(v)) + @test components(Boost(v)) ≈ components(Boost(atanh(β), v ./ β)) rtol=4eps() + end + @test Boost(QuatVec(0.0, 0.0, 0.0)) == one(Lorentz{Float64}) +end + +@testitem "Lorentz regressions: Boost input validation" tags=[:unit, :fast] begin + @test_throws DomainError Boost([0.0, 0.0, 1.0]) + @test_throws DomainError Boost([0.0, 0.0, 1.5]) + @test_throws DomainError Boost(QuatVec(0.8, 0.6, 0.0)) + @test_throws DimensionMismatch Boost([0.1]) + @test_throws DimensionMismatch Boost([0.1, 0.2, 0.3, 0.4]) + @test_throws DimensionMismatch Boost(0.5, [0.0, 1.0]) + @test_throws DomainError Boost([NaN, 0.0, 0.0]) +end + +@testitem "Lorentz regressions: symbolic Boost" tags=[:unit] begin + using Symbolics + + # The domain check of the velocity forms must not require a `Bool` from a symbolic + # comparison. + Symbolics.@variables a b c η + @test Boost(QuatVec(a, b, c)) isa Lorentz{Symbolics.Num} + @test Boost([a, b, c]) isa Lorentz{Symbolics.Num} + @test Boost(η, [0.6, -0.48, 0.64]) isa Lorentz{Symbolics.Num} + @test Boost(0.5, [a, b, c]) isa Lorentz{Symbolics.Num} + + # Substituting numbers into the symbolic result reproduces the numerical boost. + v = [0.3, -0.2, 0.4] + L = Boost([a, b, c]) + numeric(z) = Symbolics.build_function(z, a, b, c; expression=Val(false))(v...) + w = components(L) + @test [complex(numeric(real(z)), numeric(imag(z))) for z ∈ w] ≈ components(Boost(v)) rtol=4eps() +end + +@testitem "Lorentz regressions: Zygote through the action" tags=[:unit, :ad] setup=[LorentzReference] begin + using Zygote + using .LorentzReference: boost_matrix, boost_matrix_derivative + + n = [0.6, -0.48, 0.64] + v4 = [0.3, 1.2, -0.5, 0.7] + weights = [1.0, -2.0, 3.0, 0.5] + for η ∈ (0.0, 0.4, 2.0) + M = boost_matrix(big(η), big.(n)) + dM = boost_matrix_derivative(big(η), big.(n)) + # Gradient with respect to the vector, for a `Vector` and for a view + g = Zygote.gradient(v -> weights' * Boost(η, n)(v), v4)[1] + @test g ≈ Float64.(M' * weights) rtol=8eps(cosh(η)) + gview = Zygote.gradient(v -> weights' * Boost(η, n)(view(v, 2:5)), [0.0; v4])[1] + @test gview ≈ [0.0; Float64.(M' * weights)] rtol=8eps(cosh(η)) + # Derivative with respect to the rapidity + d = Zygote.gradient(t -> weights' * Boost(t, n)(v4), η)[1] + @test d ≈ Float64(weights' * (dM * big.(v4))) rtol=8eps(cosh(η)) + end +end + +@testitem "Lorentz regressions: constructors" tags=[:unit, :fast] begin + for w ∈ (1.0, -2.0, 1.0im, 3, 0.5f0) + L = Lorentz(w) + @test L isa Lorentz + @test components(L) ≈ components(Lorentz(w, 0, 0, 0)) + end + @test components(Lorentz(1.0)) == components(one(Lorentz{Float64})) + @test components(Lorentz(-2.0)) == components(-one(Lorentz{Float64})) + @test Lorentz(Float64) === Lorentz{Float64} + @test Lorentz(Float32) === Lorentz{Float32} + @test Lorentz(QuaternionF64) === Lorentz{Float64} + @test components(Lorentz([2.0])) == components(one(Lorentz{Float64})) + @test components(Lorentz([1.0, 0.0, 0.0])) == components(Lorentz(0.0, 1.0, 0.0, 0.0)) + @test components(Lorentz([1.0, 2, 3, 4])) ≈ components(Lorentz(rotor(1.0, 2, 3, 4))) + @test_throws DimensionMismatch Lorentz([1.0, 2.0]) + # Normalization uses the complex spinor norm, so the bivector 𝐭𝐱 becomes the rotation 𝐢 + @test components(Lorentz(QuatVec(0, 1.0im, 0, 0))) ≈ components(Lorentz(imx)) + # ga_components is unaffected by the move to `components` + @test ga_components(Boost(0.7, [0.0, 0.0, 1.0])) ≈ [cosh(0.35), 0, 0, 0, 0, 0, sinh(0.35), 0] +end + +@testitem "Lorentz regressions: ℂ helpers" tags=[:unit, :fast] begin + import Quaternionic: ℂconj, ℂreal, ℂimag, ℂreim, RB + using LinearAlgebra + + q = Quaternion(1.0+2im, 3.0-1im, 0.5im, 2.0+0im) + @test ℂconj(q) isa Quaternion{ComplexF64} + @test components(ℂconj(q)) == conj.(components(q)) + @test ℂreim(q) == (ℂreal(q), ℂimag(q)) + @test ℂreal(q) == Quaternion(1.0, 3.0, 0.0, 2.0) + @test ℂimag(q) == Quaternion(2.0, -1.0, 0.5, 0.0) + + # For Λ = R*B, ℂconj(Λ) = R*inv(B), and abs(ℂreal(Λ)) = cosh(η/2) + R = rotor(0.4, 1.1, -0.7, 0.3) + B = Boost(0.7, normalize([0.3, -0.5, 0.8])) + Λ = Lorentz(R) * B + @test ℂconj(Λ) isa Lorentz{Float64} + @test components(ℂconj(Λ)) ≈ components(Lorentz(R) * inv(B)) atol=4eps() + @test abs(ℂreal(Λ)) ≈ cosh(0.35) rtol=4eps() +end + +@testitem "Lorentz regressions: RB and BR at large rapidity" tags=[:unit, :fast] setup=[LorentzReference] begin + import Quaternionic: RB, BR, Rv + using LinearAlgebra + using .LorentzReference: action_matrix + + Rx = Rotor(cos(0.3), sin(0.3), 0, 0) + n̂ = normalize([0.3, -0.5, 0.8]) + relerr(A, B) = maximum(abs.(components(A) .- components(B))) / maximum(abs.(components(B))) + for η ∈ (2.0, 10.0, 20.0, 30.0) + Bη = Boost(η, n̂) + # Build the products without renormalization, so that they are accurate + ΛRB = Lorentz{Float64}(Quaternion(Lorentz(Rx)) * Quaternion(Bη)) + ΛBR = Lorentz{Float64}(Quaternion(Bη) * Quaternion(Lorentz(Rx))) + + R, B = RB(ΛRB) + @test B isa Lorentz{Float64} + @test relerr(B, Bη) ≤ 4eps() + @test min(relerr(R, Rx), relerr(-R, Rx)) ≤ 4eps() + # In Λ = R * B, the boost acts first and then the rotation + v = [0.3, 1.2, -0.5, 0.7] + @test ΛRB(v) ≈ Lorentz(R)(B(v)) rtol=16eps() + + B2, R2 = BR(ΛBR) + @test B2 isa Lorentz{Float64} + @test relerr(B2, Bη) ≤ 4eps() + @test min(relerr(R2, Rx), relerr(-R2, Rx)) ≤ 4eps() + @test ΛBR(v) ≈ B2(Lorentz(R2)(v)) rtol=16eps() + end +end + +@testitem "Lorentz regressions: KAN return types" tags=[:unit, :fast] setup=[LorentzReference] begin + import Quaternionic: KAN + using LinearAlgebra + using .LorentzReference: boost_matrix, action_matrix + + for T ∈ (Float32, Float64, BigFloat) + Λ = Lorentz(rotor(T(0.4), T(1.1), T(-0.7), T(0.3))) * Boost(T(0.6), normalize(T[0.2, -0.3, 0.25])) + Rₖ, Rₐ, Rₙ = KAN(Λ) + @test Rₖ isa Rotor{T} + @test Rₐ isa Lorentz{T} + @test Rₙ isa Lorentz{T} + # Rₐ is a boost along 𝐳 that can be used directly as a Lorentz transformation + c = ga_components(Rₐ) + φ = 2asinh(c[7]) + @test c[[2, 3, 4, 5, 6, 8]] ≈ zeros(T, 6) atol=10eps(T) + @test action_matrix(Rₐ, T) ≈ boost_matrix(φ, T[0, 0, 1]) rtol=10eps(T) + @test Lorentz(Rₖ) * Rₐ * Rₙ isa Lorentz{T} + @test components(Lorentz(Rₖ) * Rₐ * Rₙ) ≈ components(Λ) rtol=20eps(T) + end +end + +@testitem "Lorentz regressions: composition at large rapidity" tags=[:unit, :fast] setup=[LorentzReference] begin + using LinearAlgebra + using .LorentzReference: boost_matrix, rotation_matrix, action_matrix + + # The action of a composition is compared with the product of explicit BigFloat + # matrices. The relative error is measured against the largest matrix entry, which is + # of order cosh(η). The spinor norm of a rounded rotor with large rapidity is + # ill-conditioned, but the action is not, so it must remain accurate in this sense. + relerr(L, M) = Float64(maximum(abs.(L .- M)) / maximum(abs.(M))) + setprecision(BigFloat, 256) do + n̂ = normalize([0.3, -0.5, 0.8]) + x̂, ŷ, ẑ = [1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0] + for (η₁, n₁, η₂, n₂) ∈ ( + (10.0, n̂, 10.0, n̂), # total rapidity 20 + (19.0, n̂, 19.0, n̂), # total rapidity 38 + (30.0, n̂, 30.0, n̂), # total rapidity 60 + (19.0, ẑ, 19.0, ẑ), + (10.0, x̂, 10.0, ŷ), + ) + Λ = Boost(η₁, n₁) * Boost(η₂, n₂) + M = boost_matrix(big(η₁), big.(n₁)) * boost_matrix(big(η₂), big.(n₂)) + @test relerr(action_matrix(Λ, Float64), M) ≤ 20eps() + end + + # A rotation composed with a large boost + R = rotor(0.4, 1.1, -0.7, 0.3) + Λ = Lorentz(R) * Boost(38.0, ẑ) + M = rotation_matrix(big.(components(R))...) * boost_matrix(big(38.0), big.(ẑ)) + @test relerr(action_matrix(Λ, Float64), M) ≤ 20eps() + + # Float32, at a total rapidity of 16 + n̂32 = normalize(Float32[0.3, -0.5, 0.8]) + Λ = Boost(8f0, n̂32) * Boost(8f0, n̂32) + M = boost_matrix(big(8.0), big.(n̂32)) * boost_matrix(big(8.0), big.(n̂32)) + @test relerr(action_matrix(Λ, Float32), M) ≤ 20eps(Float32) + end +end diff --git a/test/regressions_math.jl b/test/regressions_math.jl new file mode 100644 index 00000000..b393937a --- /dev/null +++ b/test/regressions_math.jl @@ -0,0 +1,498 @@ +# Regression tests for the math functions in src/math.jl: `abs`, `norm`, `inv`, `log`, +# `exp`, `sqrt`, `angle`, and `^`. + +@testmodule MathRegressions begin + using Quaternionic + import ForwardDiff + + """ + rotorpower(R, s) + + Return the components of the unit rotor `R` raised to the real power `s`, computed in + `BigFloat` directly from the axis-angle form of `R`. This is independent of the + package's own `log` and `^`. + """ + function rotorpower(R, s) + c = big.(components(R)) + c = c / sqrt(sum(abs2, c)) + vn = sqrt(c[2]^2 + c[3]^2 + c[4]^2) + θ = atan(vn, c[1]) + n̂ = iszero(vn) ? [big(0), big(0), big(1)] : collect(c[2:4]) / vn + [cos(big(s)*θ); sin(big(s)*θ) * n̂] + end + + """ + maxerror(q, ref) + + Return the largest absolute difference between the components of `q` and `ref`. + """ + maxerror(q, ref) = Float64(maximum(abs, big.(collect(components(q))) - big.(collect(ref)))) + + """ + nthderivative(f, t, n) + + Return the `n`th derivative of `f` at `t`, computed with nested ForwardDiff. + """ + function nthderivative(f, t, n) + n == 0 && return f(t) + ForwardDiff.derivative(τ -> nthderivative(f, τ, n-1), t) + end +end + + +@testitem "math: complex log chooses its branch by q[1]/abs(q)" tags=[:unit, :fast] begin + using Random + # The one-argument `atan` returns the angle whose cosine has a nonnegative real part, + # so the branch depends on the sign of real(q[1]/abs(q)), not of real(q[1]). The two + # differ for about 17% of these inputs. + rng = Random.Xoshiro(2) + ok(a, b) = maximum(abs, components(a) - components(b)) ≤ 1e-10 * max(1, maximum(abs, components(b))) + nfail = count(1:2000) do _ + q = Quaternion{ComplexF64}(randn(rng, ComplexF64, 4)...) + !ok(exp(log(q)), q) + end + @test nfail == 0 + nfail = count(1:2000) do _ + q = Quaternion{ComplexF64}(randn(rng, ComplexF64, 4)...) + R = Rotor{ComplexF64}((components(q) / abs(q))...) + !ok(exp(log(R)), R) + end + @test nfail == 0 + # A specific failing input from the review + q = Quaternion{ComplexF64}(0.2565-0.4387im, 0.0510-0.0888im, 0.7445+0.5311im, -0.2963-0.5571im) + @test ok(exp(log(q)), q) +end + + +@testitem "math: complex log with zero scalar part" tags=[:unit, :fast] begin + # The general formula would divide by q[1] == 0 and return NaN. + for T ∈ (Float64, Float32, BigFloat) + qi = Quaternion{Complex{T}}(0, 1, 0, 0) + @test log(qi) ≈ Quaternion{Complex{T}}(0, T(π)/2, 0, 0) + ri = Rotor{Complex{T}}(0, 1, 0, 0) + @test log(ri) ≈ QuatVec{Complex{T}}(0, T(π)/2, 0, 0) + @test angle(ri) ≈ T(π) + @test !isnan(angle(Lorentz(rotor(imx)))) + @test exp(0.5 * log(Lorentz(rotor(imx)))) ≈ Lorentz(rotor(1, 1, 0, 0)) + @test qi^T(0.5) ≈ sqrt(qi) + end + # A pure-vector complex quaternion, raised to a non-integer power + v = quatvec(1+0.2im, 0.3-0.5im, 0.7im) + @test v^2.0 ≈ v^2 + q = Quaternion{ComplexF64}(0, 0.3+0.4im, 1-0.2im, 0.5im) + @test exp(log(q)) ≈ q +end + + +@testitem "math: complex log is differentiable at zero scalar part" tags=[:unit, :fast] begin + using ForwardDiff + # A branch that returned the angle π/2 whenever q[1] == 0 gave zero derivatives with + # respect to q[1] there. Compare with central differences in BigFloat. + base = [0.0+0im, 0.6+0.2im, 0.3+0im, -0.5im] + logq(c) = collect(components(log(Quaternion{eltype(c)}(c...)))) + function logR(c) + n = sqrt(sum(z -> z*z, c)) # Normalize by the complex spinor norm + collect(components(log(Rotor{eltype(c)}((c ./ n)...)))) + end + e₁ = [1, 0, 0, 0] + for f ∈ (logq, logR) + d = ForwardDiff.derivative(t -> f(base .+ t .* e₁), 0.0) + h = big"1e-30" + dref = setprecision(BigFloat, 256) do + b = Complex{BigFloat}.(base) + (f(b .+ h .* e₁) - f(b .- h .* e₁)) / (2h) + end + @test maximum(abs, d - dref) ≤ 1e-14 + @test maximum(abs, d) > 0.5 + end + q = Quaternion{ComplexF64}(base...) + @test exp(log(q)) ≈ q +end + + +@testitem "math: norm and isapprox for complex components" tags=[:unit, :fast] begin + import LinearAlgebra: norm + qa = Quaternion{ComplexF64}(1, 2im, 3, 4) + @test norm(qa) isa Float64 + @test norm(qa) ≈ sqrt(30) + @test norm(Quaternion{ComplexF64}(1, 1im, 0, 0)) ≈ sqrt(2) + @test abs2(Quaternion{ComplexF64}(1, 1im, 0, 0)) == 0 # The spinor norm is unchanged + @test qa ≈ qa + 1e-12 + @test qa ≉ qa + 1e-3 + L = Boost(0.3, [0, 0, 1.0]) * Lorentz(rotor(1, 2, 3, 4)) + @test norm(L) ≈ norm(components(L)) + @test L ≈ L + 1e-12 + @test norm(quaternion(1.0, 2, 4, 10)) == 11.0 +end + + +@testitem "math: sqrt of a QuatVec is a Quaternion" tags=[:unit, :fast] begin + for T ∈ (Float64, Float32, Float16, BigFloat) + v = quatvec(T(1), T(2), T(3)) + s = sqrt(v) + @test s isa Quaternion{T} + @test s * s ≈ v rtol=10eps(T) + @test s ≈ sqrt(quaternion(v)) + @test !iszero(s[1]) + end + vc = QuatVec{ComplexF64}(1, 2im, 3) + @test sqrt(vc) isa Quaternion{ComplexF64} + @test sqrt(vc) * sqrt(vc) ≈ vc +end + + +@testitem "math: sqrt does not overflow or underflow" tags=[:unit, :fast] begin + # Compare with Base's complex `sqrt`, which handles all of these inputs. + for (a, b) ∈ ( + (-1.0, 1e-200), (-1.0, 1e-160), (1e-310, 0.0), (1e308, 1e308), (6e307, 6e307), + (-1e-200, 1e-200), (1e-310, 1e-310), (-1e300, 1e-300), (floatmax(), floatmax()), + (1e-320, -1e-321), (3.0, 4.0), (-3.0, 4.0), (-1e308, 1e-300), (1e308, 1e-20), + (-1e308, 1e-20), (1e-310, 1e-320), (-1e-310, 1e-320), (-4e35, 1e-310), + ) + r = sqrt(quaternion(a, b, 0, 0)) + c = sqrt(complex(a, b)) + @test r[1] ≈ real(c) rtol=4eps() + @test r[2] ≈ imag(c) rtol=4eps() + @test iszero(r[3]) && iszero(r[4]) + end + for (a, b) ∈ ((1f38, 1f38), (-1f0, 1f-30), (1f-40, 0f0), (-floatmax(Float32), 1f0)) + r = sqrt(quaternion(a, b, 0, 0)) + c = sqrt(complex(a, b)) + @test r[1] ≈ real(c) rtol=4eps(Float32) + @test r[2] ≈ imag(c) rtol=4eps(Float32) + end + @test sqrt(Rotor{Float64}(-1.0, 1e-200, 0, 0)) ≈ rotor(5e-201, 1.0, 0, 0) + # The direction of a vector part that is tiny compared to a negative scalar part + for q ∈ (quaternion(-1e308, 1e-10, 2e-10, 0), quaternion(-1e308, 1e-300, -3e-301, 2e-300), + quaternion(-1.0, 1e-310, 3e-311, 0), quaternion(-3f35, 1f-42, 2f-43, 0)) + T = eltype(components(q)) + r = sqrt(q) + v = big.(collect(vec(q))) + @test vec(r) / absvec(r) ≈ v / sqrt(sum(abs2, v)) rtol=4eps(T) + @test absvec(r) ≈ sqrt(-q[1]) rtol=4eps(T) + end +end + + +@testitem "math: log is accurate for tiny, huge, and nearly unit inputs" tags=[:unit, :fast] begin + using Random + # Compare with Base's complex `log` along one quaternionic axis. + rng = Random.Xoshiro(7) + for _ ∈ 1:2000 + z = complex(randn(rng), randn(rng)) * exp10(rand(rng, -300:300)) + rand(rng) < 0.3 && (z = complex(real(z), imag(z) * exp10(-rand(rng, 1:20)))) + l = log(quaternion(real(z), imag(z), 0, 0)) + lz = log(z) + @test l[1] ≈ real(lz) atol=4eps()*max(1, abs(real(lz))) + @test l[2] ≈ imag(lz) atol=4eps()*max(1, abs(imag(lz))) + end + # Near |q| = 1, the scalar part must keep its relative accuracy. + @test log(quaternion(1.0, 1e-8, 0, 0))[1] ≈ real(log(1.0 + 1e-8im)) rtol=4eps() + @test log(quaternion(1.0 - 1e-9, 3e-5, 0, 0))[1] ≈ real(log(1.0 - 1e-9 + 3e-5im)) rtol=4eps() + # Subnormal and nearly negative-real inputs gave Inf or NaN. + @test log(quaternion(-1.0, 1e-320, 0, 0)) ≈ quaternion(0, π, 0, 0) + @test log(Rotor{Float64}(-1.0, 1e-320, 0, 0)) ≈ quatvec(π, 0, 0) + @test log(quaternion(-1e10, 1e-310, 0, 0)) ≈ quaternion(log(1e10), π, 0, 0) + @test log(quaternion(1e-170, 0, 0, 0)) ≈ quaternion(log(1e-170), 0, 0, 0) rtol=2eps() + @test log(quaternion(1f-23, 0, 0, 0)) ≈ quaternion(log(1f-23), 0, 0, 0) + @test all(isfinite, components(log(quaternion(1e-310, 1e-310, 0, 0)))) +end + +@testitem "math: derivatives of log at huge and tiny norms" tags=[:unit, :fast] begin + import ForwardDiff + using LinearAlgebra: norm + # Since log(sq) = log(s) + log(q) for a real s > 0, the Jacobian of `log` at sq is that + # at q divided by s. The derivatives of `x / y` and `atan(y, x)` overflowed or underflowed + # beyond about 1e154 or below about 1e-146, giving wrong values or NaN. + f(x) = collect(components(log(Quaternion(x...)))) + for q ∈ (Quaternion(0.3, -0.5, 0.7, 0.2), Quaternion(-0.3, -0.5, 0.7, 0.2), + Quaternion(0.9, 1e-9, 0, 0), Quaternion(-0.9, 0, 0, 0)) + x = collect(components(q)) + J = ForwardDiff.jacobian(f, x) + for s ∈ (1e100, 1e160, 1e300, 1e-140, 1e-160, 1e-300) + @test f(s * x) ≈ f(x) + [log(s), 0, 0, 0] rtol=4eps() + Js = ForwardDiff.jacobian(f, s * x) + @test all(isfinite, Js) + @test norm(s * Js - J) ≤ 8eps() * norm(J) + end + end + # The rescaling also applies to other float types. + @test log(Quaternion{Float32}(1f30, 2f30, 0, 0)) ≈ Quaternion{Float32}(log(5f0) / 2 + log(1f30), atan(2f0), 0, 0) + @test log(Quaternion{BigFloat}(1e200, 1, 2, 3))[1] ≈ log(big(1e200)) rtol=4eps(BigFloat) +end + + +@testitem "math: integer and rational components" tags=[:unit, :fast] begin + @test log(quaternion(0, 0, 0, 0)) == quaternion(-Inf, 0, 0, 0) + @test log(quaternion(-2, 0, 0, 0)) ≈ quaternion(log(2), 0, 0, π) + @test log(quaternion(-2//1, 0, 0, 0)) isa QuaternionF64 + @test sqrt(quaternion(2, 0, 0, 0)) ≈ quaternion(√2, 0, 0, 0) + @test sqrt(quaternion(4, 0, 0, 0)) isa QuaternionF64 + @test sqrt(quaternion(1, 2, 3, 4))^2 ≈ quaternion(1, 2, 3, 4) + @test sqrt(Rotor{Int}(0, 1, 0, 0)) ≈ rotor(1, 1, 0, 0) + @test angle(quaternion(-1, 0, 0, 0)) ≈ 2π + @test quaternion(-4, 0, 0, 0)^0.5 ≈ quaternion(0, 0, 0, 2) atol=4eps() + @test (@inferred log(quaternion(1//2, 1//3, 0, 0))) isa QuaternionF64 + @test (@inferred log(Rotor{Rational{Int}}(1//2, 1//3, 0, 0))) isa QuatVecF64 + @test (@inferred exp(quatvec(0//1, 0//1, 0//1))) isa RotorF64 + @test (@inferred exp(quatvec(1//2, 0//1, 0//1))) isa RotorF64 +end + + +@testitem "math: inv does not overflow or underflow" tags=[:unit, :fast] begin + @test inv(quaternion(1e200)) ≈ quaternion(1e-200) + @test inv(quaternion(1e-200)) ≈ quaternion(1e200) + @test inv(quaternion(1e200, 1e200, 0, 0)) ≈ quaternion(0.5e-200, -0.5e-200, 0, 0) + @test inv(quatvec(1e-200, 0, 0)) ≈ quatvec(-1e200, 0, 0) + @test inv(quatvec(1e-200, 0, 0)) isa QuatVecF64 + @test inv(quaternion(1f30, 0, 0, 0)) ≈ quaternion(1f-30) + @test inv(quaternion(Float16(1e-3), 0, 0, 0)) ≈ quaternion(Float16(1e3)) + # A largest component below floatmin, whose rescaling factor 2⁻ᵉ is not representable + @test inv(quaternion(1e-308)) ≈ quaternion(1/big(1e-308)) + @test inv(quaternion(1e-308, 1e-308, 0, 0)) ≈ quaternion(0.5/big(1e-308), -0.5/big(1e-308), 0, 0) + @test inv(quatvec(1e-308, 0, 0)) ≈ quatvec(-1/big(1e-308), 0, 0) + @test inv(quaternion(Float16(3e-5))) ≈ quaternion(1/Float16(3e-5)) # A subnormal input + @test inv(quaternion(1f-41))[1] == Inf # The true inverse overflows. + @test !any(isnan, components(inv(quaternion(1f-39, 1f-39, 0, 0)))) + @test inv(quaternion(1e-320)) == quaternion(Inf, -0.0, -0.0, -0.0) + q = quaternion(1.0, 2.0, 3.0, 4.0) + @test inv(q) == conj(q) / abs2(q) + @test all(isnan, components(inv(quaternion(0.0)))) # 0/0, as before +end + + +@testitem "math: exp of a Rotor" tags=[:unit, :fast] begin + R = rotor(1.0, 2.0, 3.0, 4.0) + @test exp(R) isa QuaternionF64 + @test exp(R) ≈ exp(quaternion(R)) + @test ℯ^R ≈ exp(quaternion(R)) +end + + +@testitem "math: angle is accurate, with accurate gradients, near -1" tags=[:unit, :fast] setup=[MathRegressions] begin + using ForwardDiff + # angle = 2atan(|v⃗|, w), whose gradient is computed analytically here. + function ∇angle(x) + w, v = x[1], x[2:4] + a = sqrt(sum(abs2, v)) + n = w^2 + a^2 + [-2a/n; 2w .* v ./ (a*n)] + end + for x ∈ ([-1.0, 1e-17, 2e-17, 0], [-1.0, 1e-8, 2e-8, 0], [0.3, 0.5, -0.2, 0.1]) + @test ForwardDiff.gradient(x -> angle(Rotor(x...)), x) ≈ ∇angle(x) rtol=10eps() + @test ForwardDiff.gradient(x -> angle(quaternion(x...)), x) ≈ ∇angle(x) rtol=10eps() + end + # The kinks at ±1 give zero derivatives rather than NaN + @test ForwardDiff.gradient(x -> angle(Rotor(x...)), [-1.0, 0, 0, 0]) == zeros(4) + @test ForwardDiff.gradient(x -> angle(Rotor(x...)), [1.0, 0, 0, 0]) == zeros(4) + @test angle(rotor(-1.0)) == 2π + @test angle(quaternion(0.0)) == 0 + @test angle(exp(6.2 * imz / 2)) ≈ 6.2 +end + + +@testitem "math: Rotor^s is accurate across the series threshold" tags=[:unit, :fast] setup=[MathRegressions] begin + using .MathRegressions: rotorpower, maxerror + n̂ = [1.0, -2.0, 3.0] / sqrt(14) + for T ∈ (Float64, Float32, Float16), s ∈ (0.3, 2.5, 10.0, -0.7) + worst = maximum([0; exp10.(range(-9, 0.4, length=200))]) do θ + R = Rotor{T}(cos(T(θ)/2), (sin(T(θ)/2) .* T.(n̂))...) + maxerror(R^T(s), rotorpower(R, T(s))) + end + @test worst ≤ 2eps(T) * max(1, abs(s)) + end + # For high precision, the series in y = |f 𝐯|² must stop at a smaller threshold. Here + # y = (sθ/2)² lies on either side of it. + setprecision(BigFloat, 256) do + y₀ = Quaternionic.trigseriestolerance(BigFloat) + n̂ = [big(1), -2, 3] / sqrt(big(14)) + worst = maximum(Iterators.product(big.((1e-6, 1e-5, 3e-5)), big.((0.5, 0.99, 1.01, 3.0)))) do (θ, f) + s = 2sqrt(f*y₀)/θ + R = Rotor{BigFloat}(cos(θ/2), (sin(θ/2) .* n̂)...) + maxerror(R^s, rotorpower(R, s)) / max(1, Float64(s)) + end + @test worst ≤ 2eps(BigFloat) + R = Rotor{BigFloat}(1, big"1e-9", 0, 0) + @test maxerror(R^big"12247.5", rotorpower(R, big"12247.5")) ≤ 2eps(BigFloat) * 12247.5 + end +end + + +@testitem "math: exp is accurate across the series threshold" tags=[:unit, :fast] begin + # The series for cos and sinc stop after the y⁵ term, so their threshold must be smaller + # for high precision. + for p ∈ (53, 113, 256, 1000) + setprecision(BigFloat, p) do + y₀ = Quaternionic.trigseriestolerance(BigFloat) + worst = maximum(big.((0.5, 0.99, 1.01, 2.0, 100.0))) do f + t = sqrt(f * y₀ / 6) + a = sqrt(big(6)) * t # The norm of the vector part + ref = [cos(a); sin(a) / a .* [t, 2t, -t]] + e₁ = maximum(abs, collect(components(exp(quatvec(t, 2t, -t)))) - ref) + e₂ = maximum(abs, collect(components(exp(quaternion(0, t, 2t, -t)))) - ref) + max(e₁, e₂) + end + @test worst ≤ 2eps(BigFloat) + end + end + for T ∈ (Float64, Float32, Float16) + @test Quaternionic.trigseriestolerance(T) == Quaternionic.seriestolerance(T) + end +end + + +@testitem "math: Rotor^s near -1 and at the identity" tags=[:unit, :fast] setup=[MathRegressions] begin + using ForwardDiff + using .MathRegressions: rotorpower, maxerror + # A tiny vector part must keep its direction. + R = Rotor{Float64}(-1.0, 1e-17, 0, 0) + @test maxerror(R^0.5, rotorpower(R, 0.5)) ≤ 2eps() + @test (R^0.5)[2] ≈ 1 + R32 = Rotor{Float32}(-1f0, 1f-8, 0, 0) + @test maxerror(R32^0.5f0, rotorpower(R32, 0.5f0)) ≤ 2eps(Float32) + @test all(isfinite, components(Rotor{Float64}(-1.0, 1e-310, 0, 0)^0.5)) + # Exactly at -1, the result follows the π𝐤 convention of `log`. + @test (-one(RotorF64))^0.5 ≈ rotor(0, 0, 0, 1) atol=eps() + # A dual-number exponent must work at -1, and slerp of antipodal rotors. + @test ForwardDiff.derivative(s -> components((-one(RotorF64))^s), 0.3) ≈ + π .* [-sinpi(0.3), 0, 0, cospi(0.3)] + @test ForwardDiff.derivative(τ -> components(slerp(one(RotorF64), -one(RotorF64), τ)), 0.3) ≈ + π .* [-sinpi(0.3), 0, 0, cospi(0.3)] + # The result type is the promoted type in every branch. + for R ∈ (Rotor{Float32}(1, 0, 0, 0), Rotor{Float32}(-1, 0, 0, 0), rotor(1f0, 2, 3, 4)) + @test (@inferred R^0.3) isa RotorF64 + end + @test (@inferred rotor(Float16(1), 2, 3, 4)^0.5f0) isa RotorF32 + @test (@inferred Rotor{Float64}(-1, 0, 0, 0)^big(0.3)) isa Rotor{BigFloat} + @test (@inferred slerp(rotor(1f0, 2, 3, 4), rotor(2f0, 1, 3, 4), 0.3)) isa RotorF64 +end + + +@testitem "math: Rotor^s with complex exponents and Lorentz rotors" tags=[:unit, :fast] begin + # A real rotor raised to a complex power near the identity + R0 = rotor(1, 1e-3, 0, 0) + s = 0.5 + 0.1im + @test R0^s ≈ exp(s * log(R0)) + @test one(RotorF64)^(0.5im) ≈ one(Rotor{ComplexF64}) + @test exp(0.05imx/2)^s ≈ exp(s * log(exp(0.05imx/2))) + # Lorentz rotors + L = Boost(0.3, [0, 0, 1.0]) * Lorentz(rotor(1, 2, 3, 4)) + M = Lorentz(rotor(1, 0, 0, 0.1)) + @test L^0.3 ≈ exp(0.3 * log(quaternion(L))) + @test (L^0.5)^2 ≈ L + @test L^0.5 isa Lorentz{Float64} + @test Boost(0.3, [0, 0, 1.0])^0.5 ≈ Boost(0.15, [0, 0, 1.0]) + @test one(L)^0.5 ≈ one(L) + @test Lorentz(rotor(imx))^0.5 ≈ Lorentz(rotor(1, 1, 0, 0)) + @test quaternion(slerp(L, M, 0.3)) ≈ (quaternion(M) / quaternion(L))^0.3 * quaternion(L) + @test squad([L, M, L*M, M*L], [0.0, 1, 2, 3], [0.5, 1.5]) isa Vector + Ls = Boost(1e-6, [0, 0, 1.0]) * Lorentz(exp(1e-6imx)) + @test Ls^2.5 ≈ Ls * Ls * sqrt(Ls) + # A quaternion exponent gives the quaternion exp(s log(q)) + R = rotor(1.0, 2, 3, 4) + p = quaternion(0.5, 0.1, 0, 0) + @test R^p ≈ quaternion(R)^p +end + + +@testitem "math: rational exponents" tags=[:unit, :fast] setup=[MathRegressions] begin + using .MathRegressions: rotorpower, maxerror + # These were method ambiguities with Base's `^(::Number, ::Rational)`. + R = rotor(big(1.0), 2, 3, 4) + @test maxerror(R^(1//3), rotorpower(R, big(1)/3)) ≤ 10eps(BigFloat) + q = quaternion(big(1.0), 2, 3, 4) + @test maxerror((q^(1//2))^2, components(q)) ≤ 100eps(BigFloat) + v = quatvec(big(1.0), 2, 3) + @test maxerror((v^(1//2))^2, components(v)) ≤ 100eps(BigFloat) + @test rotor(1.0, 2, 3, 4)^(1//2) ≈ rotor(1.0, 2, 3, 4)^0.5 + @test (@fastmath rotor(1.0, 2, 3, 4)^(1//2)) ≈ rotor(1.0, 2, 3, 4)^0.5 + @test quaternion(1, 2, 3, 4)^(1//2) ≈ sqrt(quaternion(1, 2, 3, 4)) + q1, q2 = rotor(1.0, 2, 3, 4), rotor(2.0, 1, 3, 4) + @test slerp(q1, q2, 1//3) ≈ slerp(q1, q2, 1/3) +end + + +@testitem "math: integer powers match Base.power_by_squaring" tags=[:unit, :fast] begin + # The powers are computed by a hand-written loop (Enzyme's reverse mode aborts on + # `Base.power_by_squaring`), which must give identical results and types. + qs = (quatvec(1.0, 2, 3), quaternion(1.0, 2, 3, 4), rotor(1.0, 2, 3, 4), quaternion(1, 2, 3, 4), + quatvec(1, 2, 3), quaternion(1f0, 2, 3, 4), rotor(1f0, 2, 3, 4), Rotor{Int}(1, 0, 0, 0), + quaternion(0.3, -1.1, 0.7, 0.2), Lorentz(rotor(1, 2, 3, 4)), imx, + quaternion(true, false, true, false)) + mismatches = count(Iterators.product(qs, 0:20)) do (q, n) + a = q^n + b = Base.power_by_squaring(q, n) + !(typeof(a) === typeof(b) && components(a) == components(b)) + end + @test mismatches == 0 + @test imx^0 isa Quaternion{Int} && imx^1 isa Quaternion{Int} && imx^3 isa Quaternion{Int} + mismatches = count(Iterators.product(qs, 1:20)) do (q, n) + eltype(components(q)) <: Integer && return false + a = q^(-n) + b = inv(Base.power_by_squaring(q, n)) + !(typeof(a) === typeof(b) && components(a) == components(b)) + end + @test mismatches == 0 +end + + +@testitem "math: reverse mode at rotors with zero scalar part" tags=[:unit, :fast] setup=[MathRegressions] begin + using ForwardDiff, ReverseDiff, Random + # `x = abs2vec(q)/q[1]^2` used to be computed before testing q[1] > 0, so reverse + # mode recorded a division by zero and returned NaN gradients. + W = randn(Random.Xoshiro(1234), 4) + wsum(q) = sum(W .* components(q)) + for x ∈ ([0.0, 0.3, -0.4, 1.2], [0.0, 1.0, 0.0, 0.0], [1e-300, 0.3, -0.4, 1.2]) + for s ∈ (1.3, 0.5, -0.7, 50.0) + f(x) = wsum(Rotor(x...)^s) + g = ReverseDiff.gradient(f, x) + @test all(isfinite, g) + @test g ≈ ForwardDiff.gradient(f, x) + end + end + fs(x) = wsum(slerp(one(RotorF64), Rotor(x...), 0.37)) + x = [0.0, 0.6, 0.8, 0.0] + @test ReverseDiff.gradient(fs, x) ≈ ForwardDiff.gradient(fs, x) + @test all(isfinite, ReverseDiff.gradient(fs, x)) +end + + +@testitem "math: nested derivatives of exp and log near the identity" tags=[:unit] setup=[MathRegressions] begin + using .MathRegressions: nthderivative + n̂ = normalize(quatvec(1.0, -2.0, 3.0)) + v = vec(n̂) + E(t) = collect(components(exp(t * n̂ / 2))) + Eref(t) = [cos(t/2); sin(t/2) .* v] + Q(t) = collect(components(exp(quaternion(0.5, (t .* v)...)))) + Qref(t) = exp(0.5) .* [cos(t); sin(t) .* v] + Λ(t) = collect(components(log(Rotor(cos(t), (sin(t) .* v)...)))) + Λref(t) = [0; t .* v] + for t ∈ (1e-8, 1e-5, 1e-3), n ∈ 1:4 + @test maximum(abs, nthderivative(E, t, n) - nthderivative(Eref, t, n)) ≤ 1e-14 + @test maximum(abs, nthderivative(Q, t, n) - nthderivative(Qref, t, n)) ≤ 1e-14 + @test maximum(abs, nthderivative(Λ, t, n) - nthderivative(Λref, t, n)) ≤ 1e-14 + end +end + + +@testitem "math: Taylor-series coefficients" tags=[:unit, :fast] begin + import Quaternionic: cosseries, sincseries, atanseries, logseries + # Each series is compared with its exact function at points where the truncation error + # is far below an error in any one coefficient. + setprecision(BigFloat, 256) do + for y ∈ big.((1e-1, 1e-2)) + @test abs(cosseries(y) - cos(sqrt(y))) ≤ y^6 / factorial(big(12)) + @test abs(sincseries(y) - sin(sqrt(y)) / sqrt(y)) ≤ y^6 / factorial(big(13)) + end + # At the threshold, the truncation error is below ε. + y = Quaternionic.trigseriestolerance(BigFloat) + @test abs(cosseries(y) - cos(sqrt(y))) ≤ eps(BigFloat) + @test abs(sincseries(y) - sin(sqrt(y)) / sqrt(y)) ≤ eps(BigFloat) + x = Quaternionic.seriestolerance(BigFloat) + @test abs(atanseries(x) - atan(sqrt(x)) / sqrt(x)) ≤ eps(BigFloat) + for x ∈ big.((1e-2, 1e-3)) + @test abs(atanseries(x) - atan(sqrt(x)) / sqrt(x)) ≤ x^8 / 17 + @test abs(logseries(x) - atan(sqrt(x)) * sqrt(1 + x) / sqrt(x)) ≤ x^8 / 16 + end + end +end diff --git a/test/regressions_symbolic.jl b/test/regressions_symbolic.jl new file mode 100644 index 00000000..2df65ba8 --- /dev/null +++ b/test/regressions_symbolic.jl @@ -0,0 +1,335 @@ +# Regression tests for fixes to the Symbolics, FastDifferentiation, and Latexify extensions. +# +# Numerical results are compared with references computed independently of the extensions: +# explicit formulas evaluated in BigFloat, or central finite differences in BigFloat. + +@testmodule SymbolicReference begin + using Test + + # The Jacobian of the vector-valued function `f` at the point `x`, computed by central + # finite differences in 256-bit BigFloat, and rounded to Float64 + function bigfloat_jacobian(f, x) + setprecision(BigFloat, 256) do + h = big"1e-30" + xb = big.(x) + n = length(xb) + columns = [ + (f(xb .+ h .* ((1:n) .== j)) .- f(xb .- h .* ((1:n) .== j))) ./ (2h) + for j ∈ 1:n + ] + Float64.(reduce(hcat, columns)) + end + end + + # The ambiguities among the methods of `checked_modules` that involve a method defined + # in any of `modules` + function ambiguities_involving(modules, checked_modules...) + ambiguities = Test.detect_ambiguities(checked_modules...; recursive=true) + filter(ambiguities) do (m1, m2) + parentmodule(m1) ∈ modules || parentmodule(m2) ∈ modules + end + end +end + +@testitem "Symbolics: no method ambiguities involving the extension" tags=[:unit] setup=[SymbolicReference] begin + import Symbolics, FastDifferentiation, Latexify + if isdefined(Base, :get_extension) + extensions = [ + Base.get_extension(Quaternionic, name) + for name ∈ ( + :QuaternionicSymbolicsExt, + :QuaternionicFastDifferentiationExt, + :QuaternionicLatexifyExt, + ) + ] + modules = (extensions..., Symbolics, FastDifferentiation, Latexify) + ambiguities = SymbolicReference.ambiguities_involving(modules, Quaternionic, extensions...) + @test isempty(ambiguities) + end +end + +@testitem "Symbolics: mixed == with numeric values" tags=[:unit] begin + import Symbolics + Symbolics.@variables a b c d + qs = quaternion(a, b, c, d) + qf = quaternion(1.0, 2.0, 3.0, 4.0) + + # These comparisons used to throw ambiguity errors. + @test (a == qf) == false + @test (qf == a) == false + @test (𝐢 == a) == false + @test (a == 𝐢) == false + @test (qf == qs) == false + @test (quatvec(qf) == qs) == false + @test (rotor(qf) == qs) == false + @test (qs == qf) == false + + # Numerically equal values compare equal in either order. + qn = quaternion(Symbolics.Num(1.0), Symbolics.Num(2), Symbolics.Num(3), Symbolics.Num(4)) + @test qf == qn + @test qn == qf + @test quatvec(qf) == quatvec(qn) + @test quatvec(qn) == quatvec(qf) + @test quatvec(qn) == quaternion(0.0, 2, 3, 4) + @test quaternion(0.0, 2, 3, 4) == quatvec(qn) + @test rotor(qf) == Rotor{Symbolics.Num}(components(rotor(qf))) + @test Rotor{Symbolics.Num}(components(rotor(qf))) == rotor(qf) + @test Symbolics.Num(1) == quaternion(1.0) + @test quaternion(1.0) == Symbolics.Num(1) + @test quaternion((a + b)^2) == a^2 + 2a*b + b^2 + @test a^2 + 2a*b + b^2 == quaternion((a + b)^2) +end + +@testitem "Symbolics: QuatVec equals a scalar exactly when both are zero" tags=[:unit] begin + import Symbolics + Symbolics.@variables a b c + v = quatvec(a, b, c) + z = v - v + @test z isa QuatVec{Symbolics.Num} + @test z == 0 + @test 0 == z + @test z == 0.0 + @test z == Symbolics.Num(0) + @test Symbolics.Num(0) == z + @test (z == 1) == false + @test (1 == z) == false + @test (v == 0) == false + @test (0 == v) == false + @test (v == a) == false + @test (a == v) == false + # A numeric QuatVec compared with a symbolic zero + @test zero(QuatVecF64) == Symbolics.Num(0) + @test Symbolics.Num(0) == zero(QuatVecF64) + @test (𝐢 == Symbolics.Num(0)) == false +end + +@testitem "Symbolics: promotion with QuatVec and Rotor gives Quaternion" tags=[:unit] begin + import Symbolics + Num = Symbolics.Num + Symbolics.@variables a + @test promote_type(QuatVecF64, Num) === Quaternion{Num} + @test promote_type(Num, QuatVecF64) === Quaternion{Num} + @test promote_type(QuatVec{Bool}, Num) === Quaternion{Num} + @test promote_type(RotorF64, Num) === Quaternion{Num} + @test promote_type(Num, RotorF64) === Quaternion{Num} + @test promote_type(QuaternionF64, Num) === Quaternion{Num} + @test promote_type(QuatVec{Num}, Num) === Quaternion{Num} + @test promote_type(Rotor{Num}, Num) === Quaternion{Num} + @test promote_type(Quaternion{Num}, Num) === Quaternion{Num} + @test [imx, a] isa Vector{Quaternion{Num}} + @test [quatvec(1.0, 2, 3), a] isa Vector{Quaternion{Num}} + @test promote(quatvec(1.0, 2, 3), a) isa Tuple{Quaternion{Num}, Quaternion{Num}} + @test promote(rotor(1.0, 2, 3, 4), a) isa Tuple{Quaternion{Num}, Quaternion{Num}} +end + +@testitem "Symbolics: dividing a symbolic quaternion by a numeric one" tags=[:unit] begin + import Symbolics + Symbolics.@variables a b c d + # These values have unit norm to Float64 precision, so that they can be substituted + # into a symbolic `Rotor` built without symbolic normalization. + values = Tuple(components(rotor(0.1, -0.2, 0.35, 0.9))) + # Each component is evaluated numerically by a compiled function, which does not depend + # on Symbolics folding constant subexpressions such as `sqrt(1.0)`. + evaluate(x) = Symbolics.build_function(x, a, b, c, d; expression=Val(false))(values...) + symbolic = (quaternion(a, b, c, d), Rotor{Symbolics.Num}(quaternion(a, b, c, d))) + for p ∈ (rotor(0.3, -0.4, 0.5, 0.7), quaternion(0.3, -0.4, 0.5, 0.7)) + for qs ∈ symbolic + r = qs / p + @test r isa (p isa Rotor && qs isa Rotor ? Rotor : Quaternion){Symbolics.Num} + # Reference: q / p = q p̄ / |p|², from explicit components in BigFloat + q1, q2, q3, q4 = big.(values) + p1, p2, p3, p4 = big.(components(p)) + n = p1^2 + p2^2 + p3^2 + p4^2 + expected = [ + (q1*p1 + q2*p2 + q3*p3 + q4*p4) / n, + (-q1*p2 + q2*p1 - q3*p4 + q4*p3) / n, + (-q1*p3 + q2*p4 + q3*p1 - q4*p2) / n, + (-q1*p4 - q2*p3 + q3*p2 + q4*p1) / n, + ] + computed = [evaluate(x) for x ∈ components(r)] + @test maximum(abs, computed .- expected) < 10eps(Float64) + end + end +end + +@testitem "Symbolics: scalar constructors" tags=[:unit] begin + import Symbolics + Num = Symbolics.Num + Symbolics.@variables a + + # Zero components print as `0`, not as `false`. + @test !occursin("false", string(quaternion(a))) + @test !occursin("false", string(quatvec(a))) + @test !occursin("false", string(rotor(a))) + @test quaternion(a) == quaternion(a, 0, 0, 0) + @test quatvec(a) == 0 + + # The rotor of a numerical constant has the same components as the rotor of that + # constant as a real number: it has the sign of a finite nonzero constant, and it is a + # NaN rotor for a zero, NaN, or infinite constant. + @test rotor(Num(-2)) isa Rotor{Num} + @test Symbolics.value(rotor(Num(-2))[1]) == -1 + @test Symbolics.value(rotor(Num(2.5))[1]) == 1 + @test rotor(Num(-2)) == rotor(-2.0) + @test rotor(Num(2.5)) == rotor(2.5) + @test string(rotor(Num(-2))) == string(rotor(-2)) + @test all( + isequal( + Float64.(Symbolics.value.(components(rotor(Num(x))))), + Float64.(components(rotor(x))) + ) + for x ∈ (0, false, 0.0, -0.0, NaN, Inf, -Inf, -2, 2.5, 3//2) + ) + @test all(isnan, Symbolics.value.(components(rotor(Num(0))))) + @test all(isnan, Symbolics.value.(components(rotor(Num(NaN))))) + # For a free symbol, the sign is unknown, and the identity rotor is returned. + @test rotor(a) == one(QuaternionF64) + @test string(rotor(a)) == "rotor(1 + 0𝐢 + 0𝐣 + 0𝐤)" +end + +@testitem "Symbolics: mixed operations used in the precompile workload" tags=[:unit] begin + import Symbolics + Symbolics.@variables w x y z a b c d + values = ( + 0.7, quatvec(0.1, -0.2, 0.3), rotor(0.3, -0.4, 0.5, 0.7), quaternion(1.0, 2.0, -3.0, 0.5), + w, quatvec(x, y, z), rotor(a, b, c, d), quaternion(w, x, y, z) + ) + succeeds(f) = try + f() + true + catch + false + end + nfailures = count( + !succeeds(() -> (conj(p); p * q; p / q; p + q; p - q)) + for p ∈ values for q ∈ values + ) + @test nfailures == 0 +end + +@testitem "FastDifferentiation: unsupported functions raise their messages" tags=[:unit] begin + import FastDifferentiation + import Quaternionic: to_euler_phases + u = FastDifferentiation.make_variables(:u, 4) + Q = quaternion(u...) + R = rotor(u...) + V = quatvec(u[2], u[3], u[4]) + for (name, f) ∈ ( + ("Base.exp", () -> exp(Q)), + ("Base.exp", () -> exp(V)), + ("Base.log", () -> log(Q)), + ("Base.log", () -> log(R)), + ("Base.sqrt", () -> sqrt(Q)), + ("Base.sqrt", () -> sqrt(V)), + ("Base.sqrt", () -> sqrt(R)), + ("Base.:^", () -> Q^2), + ("Base.:^", () -> V^2), + ("Base.:^", () -> R^2), + ("Base.:^", () -> R^0.5), + ("Base.:^", () -> R^(1//2)), + ("Base.log", () -> Q^1.5), + ("Quaternionic.to_euler_phases", () -> to_euler_phases(R)), + ) + err = try + f() + nothing + catch e + e + end + @test err isa ErrorException + @test err isa ErrorException && occursin("`$(name)` cannot yet be used", err.msg) + end +end + +@testitem "FastDifferentiation: scalar constructors and promotion" tags=[:unit] begin + import FastDifferentiation + Node = FastDifferentiation.Node + u = FastDifferentiation.make_variables(:u, 1) + @test !occursin("false", string(quaternion(u[1]))) + @test !occursin("false", string(quatvec(u[1]))) + @test !occursin("false", string(rotor(u[1]))) + @test string(rotor(Node(-2))) == string(rotor(-2)) + # As for Symbolics, the rotor of a constant matches the rotor of that real number. + @test all( + isequal( + Float64.(FastDifferentiation.value.(components(rotor(Node(x))))), + Float64.(components(rotor(x))) + ) + for x ∈ (0, false, 0.0, -0.0, NaN, Inf, -Inf, -2, 2.5, 3//2) + ) + @test all(isnan, FastDifferentiation.value.(components(rotor(Node(0))))) + @test string(rotor(u[1])) == "rotor(1 + 0𝐢 + 0𝐣 + 0𝐤)" + @test promote_type(QuatVecF64, Node) === Quaternion{Node} + @test promote_type(Node, QuatVecF64) === Quaternion{Node} + @test promote_type(RotorF64, Node) === Quaternion{Node} + @test promote_type(QuaternionF64, Node) === Quaternion{Node} +end + +@testitem "FastDifferentiation: Jacobian of quaternion division" tags=[:unit] setup=[SymbolicReference] begin + import FastDifferentiation + u = FastDifferentiation.make_variables(:u, 8) + D = quaternion(u[1:4]...) / quaternion(u[5:8]...) + J = FastDifferentiation.jacobian(collect(components(D)), u) + point = [0.3, -0.4, 0.5, 0.7, 0.2, 0.9, -0.6, 0.1] + computed = FastDifferentiation.make_function(J, u)(point) + # Reference: q / p = q p̄ / |p|², from explicit components + function divide(x) + q1, q2, q3, q4, p1, p2, p3, p4 = x + n = p1^2 + p2^2 + p3^2 + p4^2 + [ + (q1*p1 + q2*p2 + q3*p3 + q4*p4) / n, + (-q1*p2 + q2*p1 - q3*p4 + q4*p3) / n, + (-q1*p3 + q2*p4 + q3*p1 - q4*p2) / n, + (-q1*p4 - q2*p3 + q3*p2 + q4*p1) / n, + ] + end + expected = SymbolicReference.bigfloat_jacobian(divide, point) + @test maximum(abs, computed .- expected) < 100eps(Float64) +end + +@testitem "FastDifferentiation: Jacobian through rotor normalization" tags=[:unit] setup=[SymbolicReference] begin + import FastDifferentiation + u = FastDifferentiation.make_variables(:u, 4) + point = [0.3, -0.4, 0.5, 0.7] + + # Normalization alone is differentiated correctly. + J = FastDifferentiation.jacobian(collect(components(rotor(u...))), u) + computed = FastDifferentiation.make_function(J, u)(point) + expected = SymbolicReference.bigfloat_jacobian(x -> collect(components(rotor(x...))), point) + @test maximum(abs, computed .- expected) < 100eps(Float64) + + # FastDifferentiation 0.4.5 returns wrong derivatives for expressions in which several + # products share a common subexpression, which rotor normalization produces. This is an + # upstream bug; the function values are correct. A reproduction is kept with the notes + # of the 4.4.5 patch, as `scratchpad/upstream/fastdifferentiation_1.jl`. + M = to_rotation_matrix(rotor(u...)) + J = FastDifferentiation.jacobian(vec(M), u) + computed = FastDifferentiation.make_function(J, u)(point) + expected = SymbolicReference.bigfloat_jacobian( + x -> vec(to_rotation_matrix(rotor(x...))), point + ) + @test_broken maximum(abs, computed .- expected) < 100eps(Float64) +end + +@testitem "Latexify: latexify agrees with the text/latex form" tags=[:unit] begin + import Latexify, Symbolics + Symbolics.@variables a b c d + for q ∈ ( + quaternion(1.0, 2, 3, 4), Quaternion{Float64}(1, 2, 3, 4e-9), QuatVec{Float64}(1, 2, 3, 4), + rotor(1, 3, 3, 9), quaternion(a, b, c, d), quaternion(a - b, b*c, c/d, d + a) + ) + @test string(Latexify.latexify(q)) == repr(MIME("text/latex"), q) + end + @test string(Latexify.latexify(quaternion(1.0, 2, 3, 4))) == + "\$1.0 + 2.0\\,\\mathbf{i} + 3.0\\,\\mathbf{j} + 4.0\\,\\mathbf{k}\$" + + # Arrays of quaternions use the same form for each element, without Unicode units. + s = string(Latexify.latexify([quaternion(1.0, 2, 3, 4), quaternion(5.0, 6, 7, 8)])) + @test occursin("1.0 + 2.0\\,\\mathbf{i} + 3.0\\,\\mathbf{j} + 4.0\\,\\mathbf{k}", s) + @test occursin("5.0 + 6.0\\,\\mathbf{i} + 7.0\\,\\mathbf{j} + 8.0\\,\\mathbf{k}", s) + @test !occursin("𝐢", s) + + # NaN is set upright, as text, rather than as a product of italic letters. + @test repr(MIME("text/latex"), quaternion(NaN, Inf, -Inf, 0)) == + "\$\\mathrm{NaN} + \\infty\\,\\mathbf{i} - \\infty\\,\\mathbf{j} + 0.0\\,\\mathbf{k}\$" +end diff --git a/test/runtests.jl b/test/runtests.jl index b0100f3b..5554a42c 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -63,14 +63,19 @@ QTypes = [Quaternion, Rotor, QuatVec] Base.eps(::Quaternion{T}) where {T} = eps(T) Base.eps(T::Type{<:Integer}) = zero(T) Base.eps(n::Symbolics.Num) = zero(n) -Base.:≈(a::Symbolics.Num, b::Symbolics.Num; kwargs...) = - iszero(Symbolics.simplify(a-b; expand=true)) function _sym_iszero(diff) d = Symbolics.simplify(diff; expand=true) iszero(d) || iszero(Symbolics.simplify(d^2; expand=true)) end Base.:≈(a::Symbolics.Num, b::Number; kwargs...) = _sym_iszero(a - b) Base.:≈(a::Number, b::Symbolics.Num; kwargs...) = _sym_iszero(a - b) +# Symbolics defines `isapprox(::Num, ::Num)` itself, and its method returns `false` unless +# the difference of the two expressions is already a number. Redefining that method here +# would overwrite Symbolics' own, so tests that compare two symbolic expressions that are +# equal only after expansion use this function instead, which falls back to `isapprox` for +# every other type. +isapproxexpanded(a, b; kwargs...) = isapprox(a, b; kwargs...) +isapproxexpanded(a::Symbolics.Num, b::Symbolics.Num; kwargs...) = _sym_iszero(a - b) Base.:≈(a::AbstractQuaternion{Symbolics.Num}, b::AbstractQuaternion{Symbolics.Num}; kwargs...) = all(iszero(Symbolics.simplify(x - y; expand=true)) for (x, y) in zip(components(a), components(b))) @@ -123,6 +128,15 @@ const TAGS_DATA = Dict( # Complexity (How resource-intensive?) :fast => "Quick tests suitable for frequent execution", :slow => "Resource-intensive tests requiring significant time or memory", + + # Automatic differentiation (Which rules or backend?) + :ad => "Automatic-differentiation tests", + :chainrules => "ChainRules rules, projections, and opt-outs", + :zygote => "Zygote tests", + :forwarddiff => "ForwardDiff and AutoForwardDiff tests", + :enzyme => "Enzyme tests", + :mooncake => "Mooncake tests", + :reversediff => "ReverseDiff tests", ) """ @@ -275,10 +289,13 @@ elseif args.list else filter_func = _create_filter(args) - # Run a file-based test module if its name matches the --file filter + # Run a file-based test module if its name matches the --file filter. These files are + # not test items and have no tags or names, so the filters for test items (--tags, + # --name, and --pattern) exclude them. function addtests(fname) key = lowercase(splitext(fname)[1]) - if isnothing(args.file) || contains(key, args.file) + itemfilter = !isnothing(args.tags) || !isnothing(args.name) || !isnothing(args.pattern) + if !itemfilter && (isnothing(args.file) || contains(key, args.file)) println("Running $fname") Random.seed!(42) include(joinpath(@__DIR__, fname)) @@ -310,7 +327,6 @@ else addtests("alignment.jl") addtests("interpolation.jl") addtests("gradients.jl") - addtests("auto_differentiation.jl") addtests("doctests.jl") end end