procrustes.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Union
  15. import torch
  16. from torch import Tensor, linalg
  17. from torchmetrics.utilities.checks import _check_same_shape
  18. from torchmetrics.utilities.prints import rank_zero_warn
  19. def procrustes_disparity(
  20. point_cloud1: Tensor, point_cloud2: Tensor, return_all: bool = False
  21. ) -> Union[Tensor, tuple[Tensor, Tensor, Tensor]]:
  22. """Runs procrustrus analysis on a batch of data points.
  23. Works similar ``scipy.spatial.procrustes`` but for batches of data points.
  24. Args:
  25. point_cloud1: The first set of data points
  26. point_cloud2: The second set of data points
  27. return_all: If True, returns the scale and rotation matrices along with the disparity
  28. """
  29. _check_same_shape(point_cloud1, point_cloud2)
  30. if point_cloud1.ndim != 3:
  31. raise ValueError(
  32. "Expected both datasets to be 3D tensors of shape (N, M, D), where N is the batch size, M is the number of"
  33. f" data points and D is the dimensionality of the data points, but got {point_cloud1.ndim} dimensions."
  34. )
  35. point_cloud1 = point_cloud1 - point_cloud1.mean(dim=1, keepdim=True)
  36. point_cloud2 = point_cloud2 - point_cloud2.mean(dim=1, keepdim=True)
  37. point_cloud1 /= linalg.norm(point_cloud1, dim=[1, 2], keepdim=True)
  38. point_cloud2 /= linalg.norm(point_cloud2, dim=[1, 2], keepdim=True)
  39. try:
  40. u, w, v = linalg.svd(
  41. torch.matmul(point_cloud2.transpose(1, 2), point_cloud1).transpose(1, 2), full_matrices=False
  42. )
  43. except Exception as ex:
  44. rank_zero_warn(
  45. f"SVD calculation in procrustes_disparity failed with exception {ex}. Returning 0 disparity and identity"
  46. " scale/rotation.",
  47. UserWarning,
  48. )
  49. return torch.tensor(0.0), torch.ones(point_cloud1.shape[0]), torch.eye(point_cloud1.shape[2])
  50. rotation = torch.matmul(u, v)
  51. scale = w.sum(1, keepdim=True)
  52. point_cloud2 = scale[:, None] * torch.matmul(point_cloud2, rotation.transpose(1, 2))
  53. disparity = (point_cloud1 - point_cloud2).square().sum(dim=[1, 2])
  54. if return_all:
  55. return disparity, scale, rotation
  56. return disparity