ACloudViewer  3.9.4
A Modern Library for 3D Data Processing
Det.cpp
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // - CloudViewer: www.cloudViewer.org -
3 // ----------------------------------------------------------------------------
4 // Copyright (c) 2018-2024 www.cloudViewer.org
5 // SPDX-License-Identifier: MIT
6 // ----------------------------------------------------------------------------
7 
9 
12 
13 namespace cloudViewer {
14 namespace core {
15 
16 double Det(const Tensor& A) {
18  const Dtype dtype = A.GetDtype();
19 
20  double det = 1.0;
21 
22  if (A.GetShape() == cloudViewer::core::SizeVector({3, 3})) {
24  core::Tensor A_3x3 =
25  A.To(core::Device("CPU:0"), false).Contiguous();
26  const scalar_t* A_3x3_ptr = A_3x3.GetDataPtr<scalar_t>();
27  det = static_cast<double>(linalg::kernel::det3x3(A_3x3_ptr));
28  });
29  } else if (A.GetShape() == cloudViewer::core::SizeVector({2, 2})) {
31  core::Tensor A_2x2 =
32  A.To(core::Device("CPU:0"), false).Contiguous();
33  const scalar_t* A_2x2_ptr = A_2x2.GetDataPtr<scalar_t>();
34  det = static_cast<double>(linalg::kernel::det2x2(A_2x2_ptr));
35  });
36  } else {
37  Tensor ipiv, output;
38  LUIpiv(A, ipiv, output);
39  // Sequential loop to compute determinant from LU output, is more
40  // efficient on CPU.
41  Tensor output_cpu = output.To(core::Device("CPU:0"));
42  Tensor ipiv_cpu = ipiv.To(core::Device("CPU:0"));
43  int n = A.GetShape()[0];
44 
46  scalar_t* output_ptr = output_cpu.GetDataPtr<scalar_t>();
47  int* ipiv_ptr = static_cast<int*>(ipiv_cpu.GetDataPtr());
48 
49  for (int i = 0; i < n; i++) {
50  det *= output_ptr[i * n + i];
51  if (ipiv_ptr[i] != i) {
52  det *= -1;
53  }
54  }
55  });
56  }
57  return det;
58 }
59 
60 } // namespace core
61 } // namespace cloudViewer
#define DISPATCH_FLOAT_DTYPE_TO_TEMPLATE(DTYPE,...)
Definition: Dispatch.h:78
#define AssertTensorDtypes(tensor,...)
Definition: TensorCheck.h:33
Dtype GetDtype() const
Definition: Tensor.h:1164
SizeVector GetShape() const
Definition: Tensor.h:1127
Tensor To(Dtype dtype, bool copy=false) const
Definition: Tensor.cpp:739
CLOUDVIEWER_DEVICE CLOUDVIEWER_FORCE_INLINE scalar_t det3x3(const scalar_t *A_3x3)
Definition: Matrix.h:102
CLOUDVIEWER_DEVICE CLOUDVIEWER_FORCE_INLINE scalar_t det2x2(const scalar_t *A_2x2)
Definition: Matrix.h:96
void LUIpiv(const Tensor &A, Tensor &ipiv, Tensor &output)
Definition: LU.cpp:62
const Dtype Float64
Definition: Dtype.cpp:43
double Det(const Tensor &A)
Definition: Det.cpp:16
const Dtype Float32
Definition: Dtype.cpp:42
Generic file read and write utility for python interface.