Smooth, Invertible Flip-Invariant Vector Embeddings for Undirected 3D Paths

Author

Valentin von Bornhaupt

Published

November 25, 2026

TL;DR

Handling millions of simple undirected 3D paths in geometric deep learning comes with a tradeoff: either you are locked into specific architectures (like graph neural networks) or you handle each path as a vector, which allows usage of more general methods. But by storing undirected paths as vectors you have to handle flips (i.e., cases where you start at one or the other end). This post highlights some solutions for this challenge.

Motivation

Inside the RapidParc project1 I had the following issue: A streamline can be seen as an undirected 3D path: i.e., a chain of vertices with two ends. Each point on the chain is a 3D coordinate. We can assume every streamline to be resampled to 15 supporting points. We get a chain v_{1} - v_{2} - \cdots - v_{15} \; \; \text{ where } v_i \in \mathbb{R}^3. But the catch is: These chains have neither a fixed beginning nor an end. Selecting v_1 as a starting point is as valid as selecting v_{15}.

This results in a problem: we want to reduce each streamline into a single vector, i.e., s_1 := (v_1, \dots, v_{15}) \in \mathbb{R}^{15 \times 3} \text{ or } s_2:= (v_{15}, \dots, v_{1}) \in \mathbb{R}^{15 \times 3}. But mathematically speaking s_1 does not equal s_2.

But is this something that happens only in theory or can we see this behavior in the data?

Figure 1: Principal Component Analysis of 3 x 1200 streamlines taken from one HCP-subject. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III). We see that every cluster is separated into two disconnected sub-clusters. As further investigation shows, this is due to the fact that this vanilla vector representation pays no attention to the flip.

So yes, as Figure 1 shows, this is a real problem. Another point of view: RapidParc processes bags of streamlines simultaneously. What if some of them are all stored in one direction during training and during inference they are flipped? Can this influence the predictions for a single streamline?

NoteWhat has been done in the literature before?

Brun et al. Clustering Fiber Traces Using Normalized Cuts2 (2004)

Brun et al. reduced fiber paths to a 9D representation:

  • 3 values represent a path mean, i.e., one mean value per dimension: (\text{mean}_x, \, \text{mean}_y, \, \text{mean}_z)
  • 6 values from the (symmetric) 3x3 covariance matrix (\text{cov}_{xx}, \, \text{cov}_{xy}, \, \text{cov}_{xz}, \, \text{cov}_{yy}, \, \text{cov}_{yz}, \, \text{cov}_{zz})

This representation is fully flip invariant (as the mean and the covariance matrix are independent of the order of elements). But it also loses a lot of information on its way.

Fan Zhang et al. DeepWMA3 (2020)

DeepWMA also stores each streamline as a sequence of 15 3D supporting points. But to handle flip-invariance, they translated each 15x3 vector into a [15x2, 15x2, 3] tensor (called FiberMap) using a zig-zag pattern on each dimension. This embedding into higher dimensional space can be processed by convolutional neural networks (CNNs). This technique handles flip invariance by using shift invariance of convolutions. For analytical flip invariance it is important that circular padding4 and a position-independent pooling layer (like GlobalMaxPooling2D) are used. Note that the data expansion is quite extensive: handling a single path with 15 \times 3 = 45 entries results in a picture with 30 \times 30 \times 3 = 2700 entries.

Figure 2: Illustration for the zig-zag pattern used within DeepWMA. One single 15x3 path gets copied and flipped multiple times to create an image tensor. This image is taken from DeepWMA’s publication.

Tengfei Xue et al. TractCloud5 (2023)

TractCloud does not use a flip-invariant data representation. It utilizes a PointNet/DGCNN-style local-global point cloud architecture. Therefore, instead of handling paths v_1 - \dots - v_{15}, it processes the point cloud \left\{v_{i} \, \vert \, i \in \{1, \dots, 15\}\right\}, which is permutation invariant and therefore flip invariant.

For direct comparison with the RapidParc model, please look inside the RapidParc paper.

Initial Flip-Invariant Embedding

It would be great to have a function f such that f(v) = f(\text{flip}(v)) where flip is the function that reorders the elements (1, \dots, 15 to 15, \dots, 1).

But not every function f with this attribute is a great choice. (f(x) = 0 does the job, but also discards all information). So f has to be invertible up to the decision whether v_1 or v_{15} is the first element.

My solution for this problem combines two main ideas:

  1. If f(v) = f(\text{flip}(v)), the first and the last element of the chain have some kind of correspondence, the 2nd with the 14th and so on. Think about a horseshoe.
  2. The midpoint formula: \frac{x + y \pm \vert x - y \vert}{2} = \{x, y\} \; \; \text{ for any } x, y \in \mathbb{R} While the left-hand side of the equation is (kind of) ordered (x: 1st, y: 2nd), the right-hand side is not (as sets are unordered). In practice, we store the midpoints \frac{x+y}{2} and the signed half-differences \frac{|x-y|_\text{entangle}}{2} (defined in Note 1 below) instead of the sets \{x, y\}.

Combining both ideas, we can define \alpha(v) := \begin{bmatrix}\{v_1, v_{15}\} & \{v_2, v_{14}\}& \cdots & \{v_7, v_{9}\} & \{v_8\} \end{bmatrix}. Note that this representation is flip-invariant as sets do not have an order.

But these sets have a problem. They contain too little information to reconstruct the whole path: If you select for example v_{15} as the first element for reconstruction, v_{14} should be the next choice. But the selection of v_{15} \in \{v_1, v_{15}\} and v_{14} \in \{v_2, v_{14}\} happens independently of each other. That said, v_{15} - v_{2} - \cdots - v_{14} - v_{1} could be a possible reconstruction from the embedding \alpha. Therefore, we have to connect them to a chain again, adding the term:

\delta(v) := \begin{bmatrix}\{v_2-v_1, v_{14} - v_{15}\} & \{v_3 - v_2 , v_{13} - v_{14}\}& \cdots & \{v_7 - v_6, v_9 - v_{10}\}\end{bmatrix}. The final embedding is then defined as: f(v) := \begin{bmatrix}\alpha(v) & \delta(v)\end{bmatrix}

We can also apply the flip-invariant embedding to the example from above:

Figure 3: Principal Component Analysis of 3 x 1200 streamlines taken from one HCP-subject - but now embedded using the flip-invariant embedding from above. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III). We see that every cluster is now continuous.

The midpoint formula from above \{x, y\} = \frac{x+y}{2} \pm \frac{\vert x-y \vert}{2} \; \; \text{ for any } x,y \in \mathbb{R} contains a norm. For 1D values, this is the absolute value norm. But if x,y \in \mathbb{R}^d are vectors this breaks: If we tried to extend the absolute norm to multiple dimensions by applying it on every component separately, we would lose the relationship of the signs within vectors. E.g., the d=2 vector (1, -2)^T would become (1, 2)^T, resulting in 2^2 = 4 possibilities to reconstruct it (\pm 1, \pm 2)^T. And for d=3 we would even have 2^3 = 8 possibilities. But we want exactly 2 possibilities. Therefore, we replace the absolute value norm from above by the following vector absolute value: \left \vert \vec{v} \right \vert_\text{entangle} := \text{sign}(v_1) \cdot \vec{v} \; \; \text{ for } \vec{v}=(v_1, \dots, v_d)^T \in \mathbb{R}^d.

Note that for v \in \mathbb{R} we have \left \vert v \right \vert_\text{entangle} = \left \vert v \right \vert_\text{abs}.

As a result, the midpoint formula generalizes to: \{x, y\} = \frac{x+y}{2} \pm \frac{\left\vert x-y \right\vert_\text{entangle}}{2} \; \; \text{ for any } x,y \in \mathbb{R}^d

Further generalization uses the first non-zero entry of each component for sign calculations. Please read the code below for more information.

Note that I designed f as an embedding function. It was never designed to have a nice decoding function. But reconstruction is interesting from a mathematical perspective: to understand how the embedding contains all path information.

The input to the following algorithm is f(v) := \begin{bmatrix}\alpha(v) & \delta(v)\end{bmatrix}. The goal is to reconstruct the path in any orientation.

  • Select one element as a starting element and the other one as the last. \begin{align*}x^{(1)} &\in \{v_1, v_{15}\} = \alpha(v)_1 \\ x^{(15)} &:= \{v_1, v_{15}\} \setminus x^{(1)} = \alpha(v)_1 \setminus x^{(1)} \end{align*}

  • For i in 1, \dots, 6 do: \begin{align*}x^{(i+1)} :=& \underset{y \, \in \, \alpha(v)_{i+1}}{\text{argmin}} \left\{ \| x^{(i)} + d - y \| \; : \; d \in \delta(v)_i \right\}\\ =& \underset{y \, \in \, \{v_{i+1}, v_{15-i}\}}{\text{argmin}} \left\{ \| x^{(i)} + d - y \| \; : \; d \in \{v_{i+1} - v_i, v_{15-i} - v_{16 - i}\}\right\}\\ x^{(15-i)} :=& \alpha(v)_{i+1} \setminus x^{(i+1)} \end{align*}

  • Insert x^{(8)} from \alpha(v)_8 in the chain to obtain x^{(1)} - \dots - x^{(7)} - x^{(8)} - x^{(9)} \dots - x^{(15)}

Correctness & Uniqueness

The reconstruction is unique (up to the choice of x^{(1)} \in \{v_1, v_{n}\}) as long as v_i \neq v_{n + 1 - i} and v_i - v_{n + 1 - i} \neq v_{i + 1} - v_{n - i} for i \in \{1, \dots, 7\}.

On random float paths these conditions will never be violated; on streamline datasets (3D float) this is nearly impossible. If you apply this technique to data where the condition might not hold: You can extend the \delta-function to consider skip-neighbors as well.

Proof

Proof by induction.

  • Path length = 1: \alpha(v) = [\{a_1\}] contains the only element.
  • Path length = 3: \alpha(v) is of the form [\{a_1, a_2\} \{a_3\}]. Select a_1-a_3-a_2 or a_2-a_3-a_1.
  • Path length > 3: \alpha(v) is of the form [\{a_1, a_2\} \{a_3, a_4\} \dots]. Without loss of generality we select x^{(1)}:=a_1 and x^{(n)}:=a_2. Further assume without loss of generality \{(a_3 - a_1), (a_4 - a_2)\} = \delta(v)_1. For x^{(1)}=a_1 we have

\begin{align*}0& \overset{\phantom{\text{1st condition}}}{=} & \| a_1 + (a_3 - a_1) - a_3 \| \\ 0 &\overset{\text{1st condition}}{<} & \| a_1 + (a_3 - a_1) - a_4 \|\\ 0 &\overset{\text{1st condition}}{<} & \| a_1 + (a_4 - a_2) - a_4 \|\\ 0 &\overset{\text{2nd condition}}{<} & \| a_1 + (a_4 - a_2) - a_3 \| \end{align*}

Therefore, we can clearly identify a_3 as a successor of x^{(1)}=a_1 (the side of the inequality that is zero assumes the argmin). The same is true for x^{(n)}=a_2. Following the induction argument, the inner sequence is uniquely solved.

If this condition does not hold, for example because v_2 = v_{14}, we have v_3 - v_2 = v_3 - v_{14}, which implies that the reconstruction algorithm could end up with the following chains: v_1 - v_2 - v_3 - \dots - v_{13} - v_{14} - v_{15} and v_1 - v_2 - v_{13} - \dots - v_3 - v_{14} - v_{15}

Reconstructing the Embedding by Hand (Example)

Take a look at a simple 1D chain with 7 elements: v = \left[1, 4, 2, (-1), 1, 0, 4 \right]

Embedding:

  • \alpha(v) = \begin{bmatrix} \{ 1, 4 \} & \{ 0, 4 \} & \{ 1, 2 \} & \{ -1 \} \end{bmatrix}
  • \delta\,(v) = \begin{bmatrix} \{ -4, 3 \} & \{-2, 1\} \end{bmatrix}

Reconstruction

  • Let’s select x^{(1)} := 4, x^{(7)} := 1 from \alpha(v)_1.
  • Iteration i=1:
    • Calculate 4+3 = 7 and 4 + (-4) = 0.
    • Since 0 \in \alpha(v)_2 = \{ 0, 4 \} and 7\notin \{ 0, 4 \}, we select x^{(2)}:= 0 and x^{(6)}:= 4.
    • We can continue the chain to 4 - 0 - * - * - * - 4 - 1
  • Iteration i=2:
    • Calculate 0 + (-2) = -2 and 0 + 1 = 1.
    • Since 1 \in \alpha(v)_3 = \{ 1, 2 \}, we select x^{(3)}:= 1 and x^{(5)}:= 2.
    • We can continue the chain to 4 - 0 - 1 - * - 2 - 4 - 1
  • The missing element \alpha(v)_4 = \{-1\} completes the sequence to 4 - 0 - 1 - (-1) - 2 - 4 - 1

Alternative Reconstruction: Choose Other End as Initial Value

  • Let’s select x^{(1)} := 1, x^{(7)} := 4 from \alpha(v)_1.
  • Iteration i=1:
    • Calculate 1+3 = 4 and 1 + (-4) = -3.
    • Since 4 \in \alpha(v)_2 = \{ 0, 4 \} and -3\notin \{ 0, 4 \}, we select x^{(2)}:= 4 and x^{(6)}:= 0.
    • We can continue the chain to 1 - 4 - * - * - * - 0 - 4
  • Iteration i=2:
    • Calculate 4 + (-2) = 2 and 4 + 1 = 5.
    • Since 2 \in \alpha(v)_3 = \{ 1, 2 \}, we select x^{(3)}:= 2 and x^{(5)}:= 1.
    • We can continue the chain to 1 - 4 - 2 - * - 1 - 0 - 4
  • The missing element \alpha(v)_4 = \{-1\} completes the sequence to 1 - 4 - 2 - (-1) - 1 - 0 - 4
import math
import torch
from typing import Union, Tuple

def lex_sign(v: torch.Tensor) -> torch.Tensor:
    # more generalized version of sign(v_0) 
    # due to the fact that v_0 might be zero
    first_nonzero = (v != 0).to(torch.uint8).argmax(dim=-1, keepdim=True)
    return torch.sign(v.gather(-1, first_nonzero))

def flip_invariant_embedding(
      paths: torch.Tensor, 
      concatenate_results: bool = True
      ) -> Union[torch.Tensor, 
           Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]]:
    # Assumes path_len to be odd
    n, path_len, dimension = paths.size()
    
    flipped_paths = torch.flip(input=paths, dims=[1])

    # Shape [n, half, dimension]
    half = math.ceil(path_len / 2) # = 8
    alpha_sum = 0.5 * (paths[:, :half] + flipped_paths[:, :half])

    # Shape [n, half -1, dimension]
    alpha_abs_diff = 0.5 * (paths[:, :half-1] - flipped_paths[:, :half-1])
    # Calculate the abs for dim 0, for the rest: use relative signing
    alpha_abs_diff = alpha_abs_diff * lex_sign(alpha_abs_diff)

    # Shape [n,  (path_len-3) / 2, dimension]
    delta_half_len = (path_len - 3) // 2
    delta_sum = 0.5 * (
        paths[:, 1 : delta_half_len + 1]
        - paths[:, : delta_half_len]
        + flipped_paths[:, 1 : delta_half_len + 1]
        - flipped_paths[:, : delta_half_len]
    )

    # Shape [n,  (path_len-3) / 2, dimension]
    delta_abs_diff = 0.5 * (
        paths[:, 1 : delta_half_len + 1]
        - paths[:, : delta_half_len]
        - (flipped_paths[:, 1 : delta_half_len + 1]
        - flipped_paths[:, : delta_half_len])
    )
    # Calculate the abs for dim 0, for the rest: use relative signing
    delta_abs_diff = delta_abs_diff * lex_sign(delta_abs_diff)
    
    if concatenate_results:
        return torch.cat(
            (alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff), dim = 1)
    else: 
        return alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff
Code
####### Example Tensor #######
paths = torch.randn(100,15,3)

print(f"If we embed a tensor of shape {paths.shape},\nwe get "
      f"a tensor of shape {flip_invariant_embedding(paths).shape}. \n")

####### Test if flip invariant #######
is_flip_invariant = \
  torch.allclose(
    flip_invariant_embedding(paths), 
    flip_invariant_embedding(torch.flip(input=paths, dims=[1])), 
    atol=1e-6, rtol=1e-5)

if is_flip_invariant:
    print("On random data, the embedding is flip invariant.")
else:
    print("The embedding is not flip invariant on random data.")
If we embed a tensor of shape torch.Size([100, 15, 3]),
we get a tensor of shape torch.Size([100, 27, 3]). 

On random data, the embedding is flip invariant.
Code
simple_path = torch.tensor([1, 4, 2, -1, 1, 0, 4]).reshape(1, -1, 1)
result = flip_invariant_embedding(simple_path).flatten()
print(f"The simple 1D "
      f"{simple_path.flatten()} has the embedding \n" 
      f"[{', '.join([f"{res:.2g}" for res in result])}] \n")
      
simple_path_flipped = torch.flip(simple_path, dims=[1])
result_flipped = flip_invariant_embedding(simple_path_flipped).flatten()
print(f"The flipped "
      f"{simple_path_flipped.flatten()} has the embedding \n" 
      f"[{', '.join([f"{res:.2g}" for res in result_flipped])}]")
The simple 1D tensor([ 1,  4,  2, -1,  1,  0,  4]) has the embedding 
[2.5, 2, 1.5, -1, 1.5, 2, 0.5, -0.5, -0.5, 3.5, 1.5] 

The flipped tensor([ 4,  0,  1, -1,  2,  4,  1]) has the embedding 
[2.5, 2, 1.5, -1, 1.5, 2, 0.5, -0.5, -0.5, 3.5, 1.5]

To get the representation used in Section 2.0.2, we do some basic computations:

Code
alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff = \
  flip_invariant_embedding(simple_path, concatenate_results=False)

alpha_sum, alpha_abs_diff, delta_sum, delta_abs_diff = \
  alpha_sum.flatten(), alpha_abs_diff.flatten(), delta_sum.flatten(), delta_abs_diff.flatten()

####### Important part #######
alpha_1 = alpha_sum[:-1] + alpha_abs_diff
alpha_2 = alpha_sum[:-1] - alpha_abs_diff
# alpha_sum[-1] is a single value, will be added later

delta_1 = delta_sum + delta_abs_diff
delta_2 = delta_sum - delta_abs_diff

####### Code for pretty print outs: #######
alpha_print = []
for a1, a2 in zip(alpha_1, alpha_2):
    if a1 < a2: alpha_print.append("{"+f"{int(a1)}, {int(a2)}"+"}")
    else: alpha_print.append("{"+f"{int(a2)}, {int(a1)}"+"}")
alpha_print.append("{"+f"{int(alpha_sum[-1])}" +"}")

delta_print = []
for d1, d2 in zip(delta_1, delta_2):
    if d1 < d2: delta_print.append("{"+f"{int(d1)}, {int(d2)}"+"}")
    else: delta_print.append("{"+f"{int(d2)}, {int(d1)}"+"}")

print(f"alpha: [{'  '.join(alpha_print)}]")
print(f"delta: [{'  '.join(delta_print)}]")
alpha: [{1, 4}  {0, 4}  {1, 2}  {-1}]
delta: [{-4, 3}  {-2, 1}]

Improvement: A Smooth Flip-Invariant Embedding

The code above works as shown, but there is one issue with the flip-invariant method itself: Assume we have v_1 - v_{15} = (-0.0001, 2)^T. But if we apply some augmentations first, we get v'_1 - v_{15}' = (0.0001, 2)^T. If we now apply \lvert \cdot \rvert_\text{entangle} we get (0.0001, -2)^T or (0.0001, 2)^T depending on whether the minor augmentation had been applied or not. These points are very far away from each other and we see that \lvert x \rvert_\text{entangle} might behave just as discontinuously as \text{sign}(x).

The solution: Get rid of absolute value calculations altogether.

Smooth Flip-Invariant Embedding

In this section, we define \bar{v}:= \text{flip}(v) to improve readability. As above, we use the good parts of the midpoint formula:

  • \text{sym}(v) := \frac{1}{2}(v + \bar{v}) symmetric part, flip-invariant
  • \text{asym}(v) := \frac{1}{2}(v - \bar{v}) anti-symmetric part, not flip-invariant

Note:

  • v = \text{sym}(v) + \text{asym}(v)
  • \text{flip}(v) = \text{sym}(v) - \text{asym}(v)
  • \text{sym}(v) is a palindrome (i.e., we only keep the first “half” in memory)
  • \text{asym}(v) = \frac{1}{2}(v - \bar{v}) = -\frac{1}{2}(\bar{v} - v) = -\text{asym}(\bar{v}) is point-symmetric (i.e., we only keep the first “half” in memory)

While \text{sym}(v) is already flip-invariant, \text{asym}(v) is not. Therefore, we flatten it a := \text{flatten}(\text{asym}(v)) and then apply a normalized version of the outer product o(a) := \frac{a \cdot a^T}{\| a \|_2 + \varepsilon}. The outer product acts here as a fine-grained sign absorber (like x^2 = (-x)^2) which does not discard the sign-interactions between components.

The resulting smooth flip-invariant embedding is: f_\text{smooth}(v) := \begin{bmatrix} \text{sym}(v) & o(a) \end{bmatrix}

Note:

  • The embedding is flip invariant: As \text{asym}(v) = -\text{asym}(\bar{v}) we have a = -\bar{a} where we define \bar{a} := \text{flatten}(\text{asym}(\bar{v})). Therefore, we have \begin{align*} o(a) = \frac{a \cdot a^T}{\| a \|_2 + \varepsilon} = \frac{-\bar{a} \cdot (-\bar{a})^T}{\| -\bar{a} \|_2 + \varepsilon} = \frac{\bar{a} \cdot \bar{a}^T}{\| \bar{a} \|_2 + \varepsilon} = o(\bar{a}) \end{align*}
  • We only have to store the upper triangle of o(a) since the outer product is symmetric.

Applying the smooth flip-invariant embedding to the example above, we get:

Figure 4: Principal Component Analysis of 3 x 1200 streamlines taken from one HCP-subject - but now embedded using the smooth flip-invariant embedding from above. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III).
def smooth_flip_invariant_embedding(
      paths: torch.Tensor, 
      eps: float = 1e-8) -> torch.Tensor:

    # Assumes path_len to be odd.  
    N, path_len, dimension = paths.size()

    half = (path_len + 1) // 2  # 8
    flipped = torch.flip(paths, dims=[1])

    # Symmetric part: [N, 24]
    sym = 0.5 * (paths[:, :half] + flipped[:, :half]).flatten(1)

    # Antisymmetric part: [N, 21]
    asym = 0.5 * (paths[:, :half - 1] - flipped[:, :half - 1]).flatten(1)

    # Normalized outer product (upper triangle): [N, 231]
    normalized_outer = torch.einsum("bi,bj->bij", asym, asym) / (
      asym.norm(dim=-1, keepdim=True).unsqueeze(-1) + eps)
    tri_indices = torch.triu_indices(
      asym.shape[1], asym.shape[1], device=paths.device)
    upper_triangle = normalized_outer[:, tri_indices[0], tri_indices[1]]

    return torch.cat([sym, upper_triangle], dim=-1)  # [N, 255]
Code
####### Example Tensor #######
paths = torch.randn(100,15,3)

print(f"If we embed a tensor of shape {paths.shape},\nwe get "
      f"a tensor of shape {smooth_flip_invariant_embedding(paths).shape}. \n")

####### Test if flip invariant #######
is_flip_invariant = \
  torch.allclose(
    smooth_flip_invariant_embedding(paths), 
    smooth_flip_invariant_embedding(torch.flip(input=paths, dims=[1])), 
    atol=1e-6, rtol=1e-5)

if is_flip_invariant:
    print("On random data, the embedding is flip invariant.")
else:
    print("The embedding is not flip invariant on random data.")
If we embed a tensor of shape torch.Size([100, 15, 3]),
we get a tensor of shape torch.Size([100, 255]). 

On random data, the embedding is flip invariant.

Assume we have been given f_\text{smooth}(v) := \begin{bmatrix} \text{sym}(v) & o(a) \end{bmatrix} and we want to reconstruct v. Therefore, we have to get \text{sym} and \text{asym} back. Since \text{sym} is part of f_\text{smooth}(v), we only need to extract \text{asym} from M:=o(a) = \frac{a \cdot a^T}{\| a \| + \varepsilon}

We can construct \text{asym} using the following formulas:

  • For any column index k we have M_{:, k} = \frac{1}{\|a\|_2 + \varepsilon} \begin{bmatrix} a_1 \, a_k \\ a_2 \, a_k \\ \vdots \\ a_{21} \, a_k \end{bmatrix} = \underbrace{\left(\frac{a_k}{\|a\|_2 + \varepsilon}\right)}_{c_k} \begin{bmatrix} a_1 \\ a_2 \\ \vdots \\ a_{21} \end{bmatrix} = c_k \cdot a.

  • For best numerical conditioning we choose the column with the biggest diagonal entry6, i.e., k := \underset{i}{\text{argmax}} \; M_{ii}.

  • To get the vector a, we use \frac{M_{:, k}}{\|M_{:, k}\|_2} = \frac{c_k \cdot a}{\|c_k \cdot a \|_2} = \frac{c_k}{|c_k|} \cdot \frac{a}{\|a\|_2} = \text{sign}(a_k) \, \frac{a}{\|a\|_2}

  • We can easily see that \|a\|_2 = \frac{\text{trace}(M) + \sqrt{\text{trace}(M)^2 + 4\varepsilon\,\text{trace}(M)}}{2} if we remember that \text{trace}(M) = \sum M_{ii} = \frac{\lVert a \rVert_2^2}{\lVert a \rVert_2 + \varepsilon}.

  • Finally, we obtain \text{sign}(a_k) \cdot a = \|a\|_2 \cdot \frac{M_{:, k}}{\|M_{:, k}\|_2}. Remember, flipping the sign of a corresponds to flipping the sign of \text{asym} and therefore just flipping v one more time.

  • From a we get \text{asym} by reshaping and therefore, we get the reconstructions v = \text{sym}(v) + \text{asym}(v) and \bar{v} = \text{sym}(v) - \text{asym}(v).

def reconstruct_from_smooth_embedding(
    emb: torch.Tensor,
    path_len: int = 15,
    dim: int = 3,
    eps: float = 1e-8,
    flip_orientation: bool = False,
) -> torch.Tensor:
    """
    Reconstructs 3D paths of shape [N, path_len, dim] from the smooth flip-invariant embedding.
    """
    N = emb.shape[0]
    half = (path_len + 1) // 2 # 8
    sym_size = half * dim # 24
    asym_size = (half - 1) * dim # 21

    # 1. Split sym and upper-triangle entries
    sym = emb[:, :sym_size].view(N, half, dim)
    upper_tri_vals = emb[:, sym_size:]

    normalized_outer = torch.zeros(N, asym_size, asym_size, device=emb.device, dtype=emb.dtype)
    idx = torch.triu_indices(asym_size, asym_size, device=emb.device)
    normalized_outer[:, idx[0], idx[1]] = upper_tri_vals
    normalized_outer[:, idx[1], idx[0]] = upper_tri_vals  # symmetric filling

    # 2. Recover ||a||_2 from trace(normalized_outer)
    diag = torch.diagonal(normalized_outer, dim1=-2, dim2=-1) # [N, 21]
    trace = diag.sum(dim=-1, keepdim=True) # [N, 1]
    a_norm = 0.5 * (trace + torch.sqrt(trace**2 + 4.0 * eps * trace)) 

    # 3. Pick the column with the largest diagonal entry and normalize column k
    k = diag.argmax(dim=-1)# [N]
    col_k = normalized_outer[torch.arange(N, device=emb.device), :, k] # [N, 21]
    col_norm = col_k.norm(dim=-1, keepdim=True)

    # Do a safe division: if col_norm == 0, the path is symmetric so a_recon stays 0
    a_recon = torch.where(
        col_norm > 0,
        a_norm * col_k / col_norm.clamp_min(1e-12),
        torch.zeros_like(col_k),
    )
    if flip_orientation:
        a_recon = -a_recon

    asym_half = a_recon.view(N, half - 1, dim)

    # 4. Reassemble full path = sym ± asym (midpoint formula)
    first_half = sym[:, :half - 1] + asym_half
    middle = sym[:, half - 1 : half]
    second_half = torch.flip(sym[:, :half - 1] - asym_half, dims=[1])

    return torch.cat([first_half, middle, second_half], dim=1)
Code
####### Embed Paths, reconstruct them, calculate error #######
paths = torch.randn(100, 15, 3)
emb = smooth_flip_invariant_embedding(paths)
rec = reconstruct_from_smooth_embedding(emb)

err_orig = (rec - paths).abs().amax(dim=(1, 2)) # [100]
err_flip = (rec - torch.flip(paths, dims=[1])).abs().amax(dim=(1, 2)) # [100]
max_min_flip_error = torch.minimum(err_orig, err_flip).max().item()
print(f"Max reconstruction error across 100 paths: {max_min_flip_error:.2e}")

err_orig = (rec - paths).norm(2, dim=(1,2)) # [100]
err_flip = (rec - torch.flip(paths, dims=[1])).norm(2, dim=(1,2)) # [100]
mean_min_flip_error = torch.minimum(err_orig, err_flip).mean().item()
print(f"Mean l2 reconstruction error across 100 paths: {mean_min_flip_error:.2e}")
Max reconstruction error across 100 paths: 4.77e-07
Mean l2 reconstruction error across 100 paths: 4.60e-07

Alternative: Learned Flip Invariance through Data Augmentation

Data augmentation is a well-established method for telling a model what invariances the data should have. For example: A picture of a cow is still a picture of a cow if you flip it horizontally. Therefore, it is common to apply some random data augmentations to image classification training pipelines (PyTorch transforms gallery lists some examples).

So in terms of streamline paths, randomly flipping them (i.e., reversing the order of supporting points from last to first) during training can teach the model that both forms represent the same streamline path.

Comparison of the Approaches

Method Output Size (for 15 \times 3) Flip-Invariant? Preserves all Information? Smooth? (w.r.t. v)
No Embedding 45 No Yes Yes
9D Embedding 9 Yes No Yes
DeepWMA (FiberMap) 2,700 Depends on implementation Usable through / after CNN CNN: at least C^0
Initial Embedding 81 Yes Yes No
Smooth Embedding 255 Yes Yes Yes7
Flip Augmentation 45 Not guaranteed Yes Yes

Comparison of the Flip-Invariant Embeddings

As we can see in Figure 5, using clustering without an embedding leads to no clear cluster separation. Using the initial flip-invariant embedding leads to a more distinct result. The smooth flip-invariant embedding yields the best results.

Figure 5: Comparison of the flip-invariant embeddings using k-means clustering with k=3. The streamlines are part of three anatomical sub-regions of the left superior longitudinal fasciculus (SLF I, SLF II and SLF III).

Flip-Invariant Embedding vs. Flip Augmentations

  • Both flip-invariant embeddings from above guarantee flip invariance of the model in any case. They can be implemented in fast PyTorch code (see above).
  • The flip-augmentation-based approach is faster during inference time (no embedding calculations at all) and actually also very flip-stable (see paper).
  • During an earlier stage of RapidParc, we compared the (non-smooth) flip-invariant embedding with the flip augmentation approach. Unfortunately, I did not correctly extend the approach to 3D data (see Note 1). This might be why the flip-invariant model performed a bit worse compared to the flip-augmented model in this paper draft. But since the augmentation-based method performed very well (and even a bit faster), there was no fundamental argument to introduce the novel concept of a flip-invariant embedding in the resulting RapidParc paper.

Footnotes

  1. Valentin von Bornhaupt, Justus Bisten et al. RapidParc: A Global-Context Transformer for Parallel, Accurate, and Lesion-Robust Tractogram Parcellation, Imaging Neuroscience (2026) 10.1162/IMAG.a.1168↩︎

  2. Anders Brun et al. Clustering Fiber Traces Using Normalized Cuts, Medical Image Computing and Computer-Assisted Intervention (MICCAI) (2004) 10.1007/978-3-540-30135-6_45↩︎

  3. Fan Zhang et al. Deep white matter analysis (DeepWMA): Fast and consistent tractography segmentation, Medical Image Analysis (2020) 10.1016/j.media.2020.101761↩︎

  4. DeepWMA’s Implementation uses zero-padding with MaxPooling2D. Note that this breaks the exact flip invariance of the network. For exact analytical flip invariance, the architecture must avoid boundary effects (such as zero-padding) and strided pooling misalignment. Note that this does not mean that the network is not able to learn to handle these ambiguities during training.↩︎

  5. Tengfei Xue et al. TractCloud: Registration-Free Tractography Parcellation with a Novel Local-Global Streamline Point Cloud Representation, MICCAI (2023) 10.1007/978-3-031-43993-3_40↩︎

  6. All entries in \text{diag}(a a^T) are non-negative. If they are all zero, then a = \vec{0}.↩︎

  7. The normalized outer product o(a) = \frac{a \cdot a^T}{\|a\|_2 + \varepsilon} is at least in C^2 (in fact, C^\infty everywhere except zero). Select o^*(a) = \frac{a \cdot a^T}{\sqrt{\|a\|_2^2 + \varepsilon^2}} if you are aiming for C^\infty.↩︎

Citation

BibTeX citation:
@online{von_bornhaupt2026,
  author = {von Bornhaupt, Valentin},
  title = {Smooth, {Invertible} {Flip-Invariant} {Vector} {Embeddings}
    for {Undirected} {3D} {Paths}},
  date = {2026-11-25},
  url = {https://vavobo.de/posts/flip_invariance.html},
  langid = {en}
}
For attribution, please cite this work as:
Bornhaupt, Valentin von. 2026. “Smooth, Invertible Flip-Invariant Vector Embeddings for Undirected 3D Paths.” November 25. https://vavobo.de/posts/flip_invariance.html.