Loading [MathJax]/extensions/TeX/AMSsymbols.js
Open3D (C++ API)  0.14.1
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros
Tensor.h
Go to the documentation of this file.
1 // ----------------------------------------------------------------------------
2 // - Open3D: www.open3d.org -
3 // ----------------------------------------------------------------------------
4 // The MIT License (MIT)
5 //
6 // Copyright (c) 2018-2021 www.open3d.org
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining a copy
9 // of this software and associated documentation files (the "Software"), to deal
10 // in the Software without restriction, including without limitation the rights
11 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 // copies of the Software, and to permit persons to whom the Software is
13 // furnished to do so, subject to the following conditions:
14 //
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
17 //
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 // IN THE SOFTWARE.
25 // ----------------------------------------------------------------------------
26 
27 #pragma once
28 
29 #include <cstddef>
30 #include <memory>
31 #include <string>
32 #include <type_traits>
33 
34 #include "open3d/core/Blob.h"
35 #include "open3d/core/DLPack.h"
36 #include "open3d/core/Device.h"
37 #include "open3d/core/Dtype.h"
38 #include "open3d/core/Scalar.h"
39 #include "open3d/core/ShapeUtil.h"
40 #include "open3d/core/SizeVector.h"
42 #include "open3d/core/TensorInit.h"
43 #include "open3d/core/TensorKey.h"
44 
45 namespace open3d {
46 namespace core {
47 
50 class Tensor {
51 public:
52  Tensor() {}
53 
55  Tensor(const SizeVector& shape,
56  Dtype dtype,
57  const Device& device = Device("CPU:0"))
58  : shape_(shape),
59  strides_(shape_util::DefaultStrides(shape)),
60  dtype_(dtype),
61  blob_(std::make_shared<Blob>(shape.NumElements() * dtype.ByteSize(),
62  device)) {
63  data_ptr_ = blob_->GetDataPtr();
64  }
65 
67  template <typename T>
68  Tensor(const std::vector<T>& init_vals,
69  const SizeVector& shape,
70  Dtype dtype,
71  const Device& device = Device("CPU:0"))
72  : Tensor(shape, dtype, device) {
73  // Check number of elements
74 
75  if (static_cast<int64_t>(init_vals.size()) != shape_.NumElements()) {
77  "Tensor initialization values' size {} does not match the "
78  "shape {}",
79  init_vals.size(), shape_.NumElements());
80  }
81 
82  // Check data types
83  AssertTemplateDtype<T>();
84  if (!std::is_pod<T>()) {
85  utility::LogError("Object must be a POD.");
86  }
87 
88  // Copy data to blob
90  init_vals.data(),
91  init_vals.size() * dtype.ByteSize());
92  }
93 
95  template <typename T>
96  Tensor(const T* init_vals,
97  const SizeVector& shape,
98  Dtype dtype,
99  const Device& device = Device("CPU:0"))
100  : Tensor(shape, dtype, device) {
101  // Check data types
102  AssertTemplateDtype<T>();
103 
104  // Copy data to blob
106  init_vals,
107  shape_.NumElements() * dtype.ByteSize());
108  }
109 
113  Tensor(const SizeVector& shape,
114  const SizeVector& strides,
115  void* data_ptr,
116  Dtype dtype,
117  const std::shared_ptr<Blob>& blob)
118  : shape_(shape),
119  strides_(strides),
120  data_ptr_(data_ptr),
121  dtype_(dtype),
122  blob_(blob) {}
123 
126  Tensor(const Tensor& other) = default;
127 
130  Tensor(Tensor&& other) = default;
131 
134  Tensor& operator=(const Tensor& other) &;
135 
138  Tensor& operator=(Tensor&& other) &;
139 
142  Tensor& operator=(const Tensor& other) &&;
143 
146  Tensor& operator=(Tensor&& other) &&;
147 
153  template <typename T>
154  Tensor& operator=(const T v) && {
155  this->Fill(v);
156  return *this;
157  }
158 
162  template <typename Object>
163  Tensor& AssignObject(const Object& v) && {
164  if (shape_.size() != 0) {
166  "Assignment with scalar only works for scalar Tensor of "
167  "shape ()");
168  }
169  AssertTemplateDtype<Object>();
171  sizeof(Object));
172  return *this;
173  }
174 
177  template <typename S>
178  void Fill(S v);
179 
180  template <typename Object>
181  void FillObject(const Object& v);
182 
184  static Tensor Empty(const SizeVector& shape,
185  Dtype dtype,
186  const Device& device = Device("CPU:0"));
187 
190  static Tensor EmptyLike(const Tensor& other) {
191  return Tensor::Empty(other.shape_, other.dtype_, other.GetDevice());
192  }
193 
195  template <typename T>
196  static Tensor Full(const SizeVector& shape,
197  T fill_value,
198  Dtype dtype,
199  const Device& device = Device("CPU:0")) {
200  Tensor t = Empty(shape, dtype, device);
201  t.Fill(fill_value);
202  return t;
203  }
204 
206  static Tensor Zeros(const SizeVector& shape,
207  Dtype dtype,
208  const Device& device = Device("CPU:0"));
209 
211  static Tensor Ones(const SizeVector& shape,
212  Dtype dtype,
213  const Device& device = Device("CPU:0"));
214 
217  template <typename T>
218  static Tensor Init(const T val, const Device& device = Device("CPU:0")) {
219  Dtype type = Dtype::FromType<T>();
220  std::vector<T> ele_list{val};
221  SizeVector shape;
222  return Tensor(ele_list, shape, type, device);
223  }
224 
227  template <typename T>
228  static Tensor Init(const std::initializer_list<T>& in_list,
229  const Device& device = Device("CPU:0")) {
230  return InitWithInitializerList<T, 1>(in_list, device);
231  }
232 
235  template <typename T>
236  static Tensor Init(
237  const std::initializer_list<std::initializer_list<T>>& in_list,
238  const Device& device = Device("CPU:0")) {
239  return InitWithInitializerList<T, 2>(in_list, device);
240  }
241 
244  template <typename T>
245  static Tensor Init(
246  const std::initializer_list<
247  std::initializer_list<std::initializer_list<T>>>& in_list,
248  const Device& device = Device("CPU:0")) {
249  return InitWithInitializerList<T, 3>(in_list, device);
250  }
251 
253  static Tensor Eye(int64_t n, Dtype dtype, const Device& device);
254 
256  static Tensor Diag(const Tensor& input);
257 
259  static Tensor Arange(const Scalar start,
260  const Scalar stop,
261  const Scalar step = 1,
262  const Dtype dtype = core::Int64,
263  const Device& device = core::Device("CPU:0"));
264 
266  Tensor Reverse() const;
267 
287  Tensor GetItem(const TensorKey& tk) const;
288 
307  Tensor GetItem(const std::vector<TensorKey>& tks) const;
308 
310  Tensor SetItem(const Tensor& value);
311 
327  Tensor SetItem(const TensorKey& tk, const Tensor& value);
328 
343  Tensor SetItem(const std::vector<TensorKey>& tks, const Tensor& value);
344 
375  Tensor Append(
376  const Tensor& other,
377  const utility::optional<int64_t>& axis = utility::nullopt) const;
378 
380  Tensor Broadcast(const SizeVector& dst_shape) const;
381 
386  Tensor Expand(const SizeVector& dst_shape) const;
387 
400  Tensor Reshape(const SizeVector& dst_shape) const;
401 
422  Tensor Flatten(int64_t start_dim = 0, int64_t end_dim = -1) const;
423 
442  Tensor View(const SizeVector& dst_shape) const;
443 
445  Tensor Clone() const { return To(GetDevice(), /*copy=*/true); }
446 
448  void CopyFrom(const Tensor& other);
449 
454  Tensor To(Dtype dtype, bool copy = false) const;
455 
460  Tensor To(const Device& device, bool copy = false) const;
461 
468  Tensor To(const Device& device, Dtype dtype, bool copy = false) const;
469 
470  std::string ToString(bool with_suffix = true,
471  const std::string& indent = "") const;
472 
474  Tensor operator[](int64_t i) const;
475 
478  Tensor IndexExtract(int64_t dim, int64_t idx) const;
479 
486  Tensor Slice(int64_t dim,
487  int64_t start,
488  int64_t stop,
489  int64_t step = 1) const;
490 
501  Tensor AsRvalue() { return *this; }
502 
504  const Tensor AsRvalue() const { return *this; }
505 
510  Tensor IndexGet(const std::vector<Tensor>& index_tensors) const;
511 
519  void IndexSet(const std::vector<Tensor>& index_tensors,
520  const Tensor& src_tensor);
521 
526  Tensor Permute(const SizeVector& dims) const;
527 
530  Tensor AsStrided(const SizeVector& new_shape,
531  const SizeVector& new_strides) const;
532 
537  Tensor Transpose(int64_t dim0, int64_t dim1) const;
538 
542  Tensor T() const;
543 
546  double Det() const;
547 
550  template <typename T>
551  T Item() const {
552  if (shape_.NumElements() != 1) {
554  "Tensor::Item() only works for Tensor with exactly one "
555  "element.");
556  }
557  AssertTemplateDtype<T>();
558  T value;
559  MemoryManager::MemcpyToHost(&value, data_ptr_, GetDevice(), sizeof(T));
560  return value;
561  }
562 
564  Tensor Add(const Tensor& value) const;
565  Tensor Add(Scalar value) const;
566  Tensor operator+(const Tensor& value) const { return Add(value); }
567  Tensor operator+(Scalar value) const { return Add(value); }
568 
571  Tensor Add_(const Tensor& value);
572  Tensor Add_(Scalar value);
573  Tensor operator+=(const Tensor& value) { return Add_(value); }
574  Tensor operator+=(Scalar value) { return Add_(value); }
575 
577  Tensor Sub(const Tensor& value) const;
578  Tensor Sub(Scalar value) const;
579  Tensor operator-(const Tensor& value) const { return Sub(value); }
580  Tensor operator-(Scalar value) const { return Sub(value); }
581 
584  Tensor Sub_(const Tensor& value);
585  Tensor Sub_(Scalar value);
586  Tensor operator-=(const Tensor& value) { return Sub_(value); }
587  Tensor operator-=(Scalar value) { return Sub_(value); }
588 
590  Tensor Mul(const Tensor& value) const;
591  Tensor Mul(Scalar value) const;
592  Tensor operator*(const Tensor& value) const { return Mul(value); }
593  Tensor operator*(Scalar value) const { return Mul(value); }
594 
597  Tensor Mul_(const Tensor& value);
598  Tensor Mul_(Scalar value);
599  Tensor operator*=(const Tensor& value) { return Mul_(value); }
600  Tensor operator*=(Scalar value) { return Mul_(value); }
601 
603  Tensor Div(const Tensor& value) const;
604  Tensor Div(Scalar value) const;
605  Tensor operator/(const Tensor& value) const { return Div(value); }
606  Tensor operator/(Scalar value) const { return Div(value); }
607 
610  Tensor Div_(const Tensor& value);
611  Tensor Div_(Scalar value);
612  Tensor operator/=(const Tensor& value) { return Div_(value); }
613  Tensor operator/=(Scalar value) { return Div_(value); }
614 
618  Tensor Sum(const SizeVector& dims, bool keepdim = false) const;
619 
623  Tensor Mean(const SizeVector& dims, bool keepdim = false) const;
624 
628  Tensor Prod(const SizeVector& dims, bool keepdim = false) const;
629 
633  Tensor Min(const SizeVector& dims, bool keepdim = false) const;
634 
638  Tensor Max(const SizeVector& dims, bool keepdim = false) const;
639 
648  Tensor ArgMin(const SizeVector& dims) const;
649 
658  Tensor ArgMax(const SizeVector& dims) const;
659 
661  Tensor Sqrt() const;
662 
664  Tensor Sqrt_();
665 
667  Tensor Sin() const;
668 
670  Tensor Sin_();
671 
673  Tensor Cos() const;
674 
676  Tensor Cos_();
677 
679  Tensor Neg() const;
680 
682  Tensor Neg_();
683 
685  Tensor Exp() const;
686 
688  Tensor Exp_();
689 
691  Tensor Abs() const;
692 
694  Tensor Abs_();
695 
698  Tensor IsNan() const;
699 
702  Tensor IsInf() const;
703 
707  Tensor IsFinite() const;
708 
713  Tensor Clip(Scalar min_val, Scalar max_val) const;
714 
719  Tensor Clip_(Scalar min_val, Scalar max_val);
720 
722  Tensor Floor() const;
723 
725  Tensor Ceil() const;
726 
728  Tensor Round() const;
729 
731  Tensor Trunc() const;
732 
737  Tensor LogicalNot() const;
738 
746 
751  Tensor LogicalAnd(const Tensor& value) const;
752  Tensor operator&&(const Tensor& value) const { return LogicalAnd(value); }
753  Tensor LogicalAnd(Scalar value) const;
754 
761  Tensor LogicalAnd_(const Tensor& value);
762  Tensor LogicalAnd_(Scalar value);
763 
768  Tensor LogicalOr(const Tensor& value) const;
769  Tensor operator||(const Tensor& value) const { return LogicalOr(value); }
770  Tensor LogicalOr(Scalar value) const;
771 
778  Tensor LogicalOr_(const Tensor& value);
779  Tensor LogicalOr_(Scalar value);
780 
786  Tensor LogicalXor(const Tensor& value) const;
787  Tensor LogicalXor(Scalar value) const;
788 
795  Tensor LogicalXor_(const Tensor& value);
796  Tensor LogicalXor_(Scalar value);
797 
799  Tensor Gt(const Tensor& value) const;
800  Tensor operator>(const Tensor& value) const { return Gt(value); }
801  Tensor Gt(Scalar value) const;
802 
805  Tensor Gt_(const Tensor& value);
806  Tensor Gt_(Scalar value);
807 
809  Tensor Lt(const Tensor& value) const;
810  Tensor operator<(const Tensor& value) const { return Lt(value); }
811  Tensor Lt(Scalar value) const;
812 
815  Tensor Lt_(const Tensor& value);
816  Tensor Lt_(Scalar value);
817 
820  Tensor Ge(const Tensor& value) const;
821  Tensor operator>=(const Tensor& value) const { return Ge(value); }
822  Tensor Ge(Scalar value) const;
823 
826  Tensor Ge_(const Tensor& value);
827  Tensor Ge_(Scalar value);
828 
831  Tensor Le(const Tensor& value) const;
832  Tensor operator<=(const Tensor& value) const { return Le(value); }
833  Tensor Le(Scalar value) const;
834 
837  Tensor Le_(const Tensor& value);
838  Tensor Le_(Scalar value);
839 
841  Tensor Eq(const Tensor& value) const;
842  Tensor operator==(const Tensor& value) const { return Eq(value); }
843  Tensor Eq(Scalar value) const;
844 
847  Tensor Eq_(const Tensor& value);
848  Tensor Eq_(Scalar value);
849 
851  Tensor Ne(const Tensor& value) const;
852  Tensor operator!=(const Tensor& value) const { return Ne(value); }
853  Tensor Ne(Scalar value) const;
854 
857  Tensor Ne_(const Tensor& value);
858  Tensor Ne_(Scalar value);
859 
863  std::vector<Tensor> NonZeroNumpy() const;
864 
869  Tensor NonZero() const;
870 
880  bool IsNonZero() const;
881 
885  bool All() const;
886 
890  bool Any() const;
891 
903  bool AllEqual(const Tensor& other) const;
904 
922  bool AllClose(const Tensor& other,
923  double rtol = 1e-5,
924  double atol = 1e-8) const;
925 
944  Tensor IsClose(const Tensor& other,
945  double rtol = 1e-5,
946  double atol = 1e-8) const;
947 
951  bool IsSame(const Tensor& other) const;
952 
954  template <typename T>
955  std::vector<T> ToFlatVector() const {
956  AssertTemplateDtype<T>();
957  std::vector<T> values(NumElements());
959  GetDevice(),
960  GetDtype().ByteSize() * NumElements());
961  return values;
962  }
963 
966  inline bool IsContiguous() const {
968  }
969 
973  Tensor Contiguous() const;
974 
977  Tensor Matmul(const Tensor& rhs) const;
978 
981  Tensor Solve(const Tensor& rhs) const;
982 
985  Tensor LeastSquares(const Tensor& rhs) const;
986 
994  std::tuple<Tensor, Tensor, Tensor> LU(const bool permute_l = false) const;
995 
1008  std::tuple<Tensor, Tensor> LUIpiv() const;
1009 
1019  Tensor Triu(const int diagonal = 0) const;
1020 
1030  Tensor Tril(const int diagonal = 0) const;
1031 
1043  std::tuple<Tensor, Tensor> Triul(const int diagonal = 0) const;
1044 
1047  Tensor Inverse() const;
1048 
1051  std::tuple<Tensor, Tensor, Tensor> SVD() const;
1052 
1055  inline int64_t GetLength() const { return GetShape().GetLength(); }
1056 
1057  inline SizeVector GetShape() const { return shape_; }
1058 
1059  inline const SizeVector& GetShapeRef() const { return shape_; }
1060 
1061  inline int64_t GetShape(int64_t dim) const {
1062  return shape_[shape_util::WrapDim(dim, NumDims())];
1063  }
1064 
1065  inline SizeVector GetStrides() const { return strides_; }
1066 
1067  inline const SizeVector& GetStridesRef() const { return strides_; }
1068 
1069  inline int64_t GetStride(int64_t dim) const {
1070  return strides_[shape_util::WrapDim(dim, NumDims())];
1071  }
1072 
1073  template <typename T>
1074  inline T* GetDataPtr() {
1075  return const_cast<T*>(const_cast<const Tensor*>(this)->GetDataPtr<T>());
1076  }
1077 
1078  template <typename T>
1079  inline const T* GetDataPtr() const {
1080  if (!dtype_.IsObject() && Dtype::FromType<T>() != dtype_) {
1082  "Requested values have type {} but Tensor has type {}. "
1083  "Please use non templated GetDataPtr() with manual "
1084  "casting.",
1085  Dtype::FromType<T>().ToString(), dtype_.ToString());
1086  }
1087  return static_cast<T*>(data_ptr_);
1088  }
1089 
1090  inline void* GetDataPtr() { return data_ptr_; }
1091 
1092  inline const void* GetDataPtr() const { return data_ptr_; }
1093 
1094  inline Dtype GetDtype() const { return dtype_; }
1095 
1096  Device GetDevice() const;
1097 
1098  inline std::shared_ptr<Blob> GetBlob() const { return blob_; }
1099 
1100  inline int64_t NumElements() const { return shape_.NumElements(); }
1101 
1102  inline int64_t NumDims() const { return shape_.size(); }
1103 
1104  template <typename T>
1105  void AssertTemplateDtype() const {
1106  if (!dtype_.IsObject() && Dtype::FromType<T>() != dtype_) {
1108  "Requested values have type {} but Tensor has type {}",
1109  Dtype::FromType<T>().ToString(), dtype_.ToString());
1110  }
1111  if (dtype_.ByteSize() != sizeof(T)) {
1112  utility::LogError("Internal error: element size mismatch {} != {}",
1113  dtype_.ByteSize(), sizeof(T));
1114  }
1115  }
1116 
1118  DLManagedTensor* ToDLPack() const;
1119 
1121  static Tensor FromDLPack(const DLManagedTensor* dlmt);
1122 
1124  void Save(const std::string& file_name) const;
1125 
1127  static Tensor Load(const std::string& file_name);
1128 
1130  struct Iterator {
1131  using iterator_category = std::forward_iterator_tag;
1132  using difference_type = std::ptrdiff_t;
1135  using reference = value_type; // Typically Tensor&, but a tensor slice
1136  // creates a new Tensor object with
1137  // shared memory.
1138 
1139  // Iterator must be constructible, copy-constructible, copy-assignable,
1140  // destructible and swappable.
1141  Iterator(pointer tensor, int64_t index);
1142  Iterator(const Iterator&);
1143  ~Iterator();
1144  reference operator*() const;
1145  pointer operator->() const;
1146  Iterator& operator++();
1147  Iterator operator++(int);
1148  bool operator==(const Iterator& other) const;
1149  bool operator!=(const Iterator& other) const;
1150 
1151  private:
1152  struct Impl;
1153  std::unique_ptr<Impl> impl_;
1154  };
1155 
1157  struct ConstIterator {
1158  using iterator_category = std::forward_iterator_tag;
1159  using difference_type = std::ptrdiff_t;
1160  using value_type = const Tensor;
1162  using reference = value_type; // Typically Tensor&, but a tensor slice
1163  // creates a new Tensor object with
1164  // shared memory.
1165 
1166  // ConstIterator must be constructible, copy-constructible,
1167  // copy-assignable, destructible and swappable.
1168  ConstIterator(pointer tensor, int64_t index);
1169  ConstIterator(const ConstIterator&);
1170  ~ConstIterator();
1171  reference operator*() const;
1172  pointer operator->() const;
1175  bool operator==(const ConstIterator& other) const;
1176  bool operator!=(const ConstIterator& other) const;
1177 
1178  private:
1179  struct Impl;
1180  std::unique_ptr<Impl> impl_;
1181  };
1182 
1186  Iterator begin();
1187 
1191  Iterator end();
1192 
1196  ConstIterator cbegin() const;
1197 
1201  ConstIterator cend() const;
1202 
1207  ConstIterator begin() const { return cbegin(); }
1208 
1213  ConstIterator end() const { return cend(); }
1214 
1215 protected:
1216  std::string ScalarPtrToString(const void* ptr) const;
1217 
1218 private:
1220  template <typename T, size_t D>
1221  static Tensor InitWithInitializerList(
1222  const tensor_init::NestedInitializerList<T, D>& nested_list,
1223  const Device& device = Device("CPU:0")) {
1224  SizeVector shape = tensor_init::InferShape(nested_list);
1225  std::vector<T> values =
1226  tensor_init::ToFlatVector<T, D>(shape, nested_list);
1227  return Tensor(values, shape, Dtype::FromType<T>(), device);
1228  }
1229 
1230 protected:
1233 
1242 
1256  void* data_ptr_ = nullptr;
1257 
1260 
1262  std::shared_ptr<Blob> blob_ = nullptr;
1263 }; // namespace core
1264 
1265 template <>
1266 inline Tensor::Tensor(const std::vector<bool>& init_vals,
1267  const SizeVector& shape,
1268  Dtype dtype,
1269  const Device& device)
1270  : Tensor(shape, dtype, device) {
1271  // Check number of elements
1272  if (static_cast<int64_t>(init_vals.size()) != shape_.NumElements()) {
1274  "Tensor initialization values' size {} does not match the "
1275  "shape {}",
1276  init_vals.size(), shape_.NumElements());
1277  }
1278 
1279  // Check data types
1280  AssertTemplateDtype<bool>();
1281 
1282  // std::vector<bool> possibly implements 1-bit-sized boolean storage.
1283  // Open3D uses 1-byte-sized boolean storage for easy indexing.
1284  std::vector<uint8_t> init_vals_uchar(init_vals.size());
1285  std::transform(init_vals.begin(), init_vals.end(), init_vals_uchar.begin(),
1286  [](bool v) -> uint8_t { return static_cast<uint8_t>(v); });
1287 
1289  init_vals_uchar.data(),
1290  init_vals_uchar.size() * dtype.ByteSize());
1291 }
1292 
1293 template <>
1294 inline std::vector<bool> Tensor::ToFlatVector() const {
1295  AssertTemplateDtype<bool>();
1296  std::vector<bool> values(NumElements());
1297  std::vector<uint8_t> values_uchar(NumElements());
1298  MemoryManager::MemcpyToHost(values_uchar.data(), Contiguous().GetDataPtr(),
1299  GetDevice(),
1300  GetDtype().ByteSize() * NumElements());
1301 
1302  // std::vector<bool> possibly implements 1-bit-sized boolean storage.
1303  // Open3D uses 1-byte-sized boolean storage for easy indexing.
1304  std::transform(values_uchar.begin(), values_uchar.end(), values.begin(),
1305  [](uint8_t v) -> bool { return static_cast<bool>(v); });
1306  return values;
1307 }
1308 
1309 template <>
1310 inline bool Tensor::Item() const {
1311  if (shape_.NumElements() != 1) {
1313  "Tensor::Item only works for Tensor with one element.");
1314  }
1315  AssertTemplateDtype<bool>();
1316  uint8_t value;
1318  sizeof(uint8_t));
1319  return static_cast<bool>(value);
1320 }
1321 
1322 template <typename S>
1323 inline void Tensor::Fill(S v) {
1325  scalar_t casted_v = static_cast<scalar_t>(v);
1326  Tensor tmp(std::vector<scalar_t>({casted_v}), SizeVector({}),
1327  GetDtype(), GetDevice());
1328  AsRvalue() = tmp;
1329  });
1330 }
1331 
1332 template <typename Object>
1333 inline void Tensor::FillObject(const Object& v) {
1334  Tensor tmp(std::vector<Object>({v}), SizeVector({}), GetDtype(),
1335  GetDevice());
1336  AsRvalue() = tmp;
1337 }
1338 
1339 template <typename T>
1340 inline Tensor operator+(T scalar_lhs, const Tensor& rhs) {
1341  return rhs + scalar_lhs;
1342 }
1343 
1344 template <typename T>
1345 inline Tensor operator-(T scalar_lhs, const Tensor& rhs) {
1346  return Tensor::Full({}, scalar_lhs, rhs.GetDtype(), rhs.GetDevice()) - rhs;
1347 }
1348 
1349 template <typename T>
1350 inline Tensor operator*(T scalar_lhs, const Tensor& rhs) {
1351  return rhs * scalar_lhs;
1352 }
1353 
1354 template <typename T>
1355 inline Tensor operator/(T scalar_lhs, const Tensor& rhs) {
1356  return Tensor::Full({}, scalar_lhs, rhs.GetDtype(), rhs.GetDevice()) / rhs;
1357 }
1358 
1359 } // namespace core
1360 } // namespace open3d
Tensor Cos_()
Element-wise cosine of a tensor, in-place.
Definition: Tensor.cpp:1254
const Tensor AsRvalue() const
Convert to constant rvalue.
Definition: Tensor.h:504
bool operator==(const Iterator &other) const
Definition: Tensor.cpp:246
Tensor(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Constructor for creating a contiguous Tensor.
Definition: Tensor.h:55
int64_t NumElements() const
Definition: Tensor.h:1100
Tensor operator[](int64_t i) const
Extract the i-th Tensor along the first axis, returning a new view.
Definition: Tensor.cpp:813
constexpr nullopt_t nullopt
Definition: Optional.h:171
Tensor GetItem(const TensorKey &tk) const
Definition: Tensor.cpp:447
Tensor Sin_()
Element-wise sine of a tensor, in-place.
Definition: Tensor.cpp:1243
Tensor Sqrt_()
Element-wise square root of a tensor, in-place.
Definition: Tensor.cpp:1232
std::string ToString(bool with_suffix=true, const std::string &indent="") const
Definition: Tensor.cpp:754
Tensor operator*=(const Tensor &value)
Definition: Tensor.h:599
Tensor LogicalOr(const Tensor &value) const
Definition: Tensor.cpp:1417
The common header of DLPack.
int64_t NumDims() const
Definition: Tensor.h:1102
static void MemcpyFromHost(void *dst_ptr, const Device &dst_device, const void *host_ptr, size_t num_bytes)
Same as Memcpy, but with host (CPU:0) as default src_device.
Definition: MemoryManager.cpp:86
Tensor Sum(const SizeVector &dims, bool keepdim=false) const
Definition: Tensor.cpp:1170
Tensor(const SizeVector &shape, const SizeVector &strides, void *data_ptr, Dtype dtype, const std::shared_ptr< Blob > &blob)
Definition: Tensor.h:113
static Tensor Init(const std::initializer_list< std::initializer_list< T >> &in_list, const Device &device=Device("CPU:0"))
Definition: Tensor.h:236
const Dtype Int64
Definition: Dtype.cpp:66
ConstIterator end() const
Definition: Tensor.h:1213
Tensor operator||(const Tensor &value) const
Definition: Tensor.h:769
Tensor Lt_(const Tensor &value)
Definition: Tensor.cpp:1534
Tensor Inverse() const
Definition: Tensor.cpp:1867
Tensor Ge(const Tensor &value) const
Definition: Tensor.cpp:1548
Tensor SetItem(const Tensor &value)
Set all items. Equivalent to tensor[:] = value in Python.
Definition: Tensor.cpp:538
static Tensor Full(const SizeVector &shape, T fill_value, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor fill with specified value.
Definition: Tensor.h:196
bool AllClose(const Tensor &other, double rtol=1e-5, double atol=1e-8) const
Definition: Tensor.cpp:1780
std::shared_ptr< Blob > blob_
Underlying memory buffer for Tensor.
Definition: Tensor.h:1262
Tensor ArgMin(const SizeVector &dims) const
Definition: Tensor.cpp:1212
C Tensor object, manage memory of DLTensor. This data structure is intended to facilitate the borrowi...
Definition: DLPack.h:193
Tensor Solve(const Tensor &rhs) const
Definition: Tensor.cpp:1813
Tensor AsStrided(const SizeVector &new_shape, const SizeVector &new_strides) const
Create a Tensor view of specified shape and strides. The underlying buffer and data_ptr offsets remai...
Definition: Tensor.cpp:998
Tensor Gt_(const Tensor &value)
Definition: Tensor.cpp:1502
void * GetDataPtr()
Definition: Tensor.h:1090
Tensor Mul_(const Tensor &value)
Definition: Tensor.cpp:1121
Definition: Dtype.h:39
Tensor LogicalXor(const Tensor &value) const
Definition: Tensor.cpp:1450
TensorKey is used to represent single index, slice or advanced indexing on a Tensor.
Definition: TensorKey.h:45
void Save(const std::string &file_name) const
Save tensor to numpy&#39;s npy format.
Definition: Tensor.cpp:1762
static Tensor Arange(const Scalar start, const Scalar stop, const Scalar step=1, const Dtype dtype=core::Int64, const Device &device=core::Device("CPU:0"))
Create a 1D tensor with evenly spaced values in the given interval.
Definition: Tensor.cpp:410
Tensor IsClose(const Tensor &other, double rtol=1e-5, double atol=1e-8) const
Definition: Tensor.cpp:1785
pointer operator->() const
Definition: Tensor.cpp:230
std::ptrdiff_t difference_type
Definition: Tensor.h:1159
Tensor LogicalAnd_(const Tensor &value)
Definition: Tensor.cpp:1402
Tensor value_type
Definition: Tensor.h:1133
Tensor operator==(const Tensor &value) const
Definition: Tensor.h:842
Tensor(const T *init_vals, const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Constructor from raw host buffer. The memory will be copied.
Definition: Tensor.h:96
reference operator*() const
Definition: Tensor.cpp:226
Tensor Exp() const
Element-wise exponential of a tensor, returning a new tensor.
Definition: Tensor.cpp:1270
Definition: Device.h:138
const SizeVector & GetStridesRef() const
Definition: Tensor.h:1067
Tensor Broadcast(const SizeVector &dst_shape) const
Broadcast Tensor to a new broadcastable shape.
Definition: Tensor.cpp:602
Tensor Eq(const Tensor &value) const
Element-wise equals-to of tensors, returning a new boolean tensor.
Definition: Tensor.cpp:1612
Tensor operator/(const Tensor &value) const
Definition: Tensor.h:605
Tensor IsInf() const
Definition: Tensor.cpp:1302
Tensor operator*=(Scalar value)
Definition: Tensor.h:600
Tensor NonZero() const
Definition: Tensor.cpp:1685
Tensor Sub_(const Tensor &value)
Definition: Tensor.cpp:1087
Tensor operator>=(const Tensor &value) const
Definition: Tensor.h:821
int64_t GetLength() const
Definition: SizeVector.cpp:142
Definition: Scalar.h:42
Tensor LogicalNot() const
Definition: Tensor.cpp:1372
Tensor LogicalXor_(const Tensor &value)
Definition: Tensor.cpp:1469
std::tuple< Tensor, Tensor, Tensor > LU(const bool permute_l=false) const
Computes LU factorisation of the 2D square tensor, using A = P * L * U; where P is the permutation ma...
Definition: Tensor.cpp:1833
Tensor operator+=(const Tensor &value)
Definition: Tensor.h:573
static void MemcpyToHost(void *host_ptr, const void *src_ptr, const Device &src_device, size_t num_bytes)
Same as Memcpy, but with host (CPU:0) as default dst_device.
Definition: MemoryManager.cpp:94
std::tuple< Tensor, Tensor, Tensor > SVD() const
Definition: Tensor.cpp:1875
Tensor Min(const SizeVector &dims, bool keepdim=false) const
Definition: Tensor.cpp:1198
std::string ToString() const
Definition: Dtype.h:83
bool IsNonZero() const
Definition: Tensor.cpp:1687
Iterator for Tensor.
Definition: Tensor.h:1130
Tensor Ceil() const
Element-wise ceil value of a tensor, returning a new tensor.
Definition: Tensor.cpp:1347
Tensor Reverse() const
Reverse a Tensor&#39;s elements by viewing the tensor as a 1D array.
Definition: Tensor.cpp:439
Device GetDevice() const
Definition: Tensor.cpp:1365
Definition: SizeVector.h:79
Const iterator for Tensor.
Definition: Tensor.h:1157
std::tuple< Tensor, Tensor > LUIpiv() const
Computes LU factorisation of the 2D square tensor, using A = P * L * U; where P is the permutation ma...
Definition: Tensor.cpp:1841
std::forward_iterator_tag iterator_category
Definition: Tensor.h:1158
Tensor View(const SizeVector &dst_shape) const
Definition: Tensor.cpp:695
std::forward_iterator_tag iterator_category
Definition: Tensor.h:1131
Tensor Permute(const SizeVector &dims) const
Permute (dimension shuffle) the Tensor, returns a view.
Definition: Tensor.cpp:965
SizeVector strides_
Definition: Tensor.h:1241
static Tensor Diag(const Tensor &input)
Create a square matrix with specified diagonal elements in input.
Definition: Tensor.cpp:398
Tensor Matmul(const Tensor &rhs) const
Definition: Tensor.cpp:1804
Tensor operator+(Scalar value) const
Definition: Tensor.h:567
Tensor Max(const SizeVector &dims, bool keepdim=false) const
Definition: Tensor.cpp:1205
Dtype GetDtype() const
Definition: Tensor.h:1094
static Tensor EmptyLike(const Tensor &other)
Definition: Tensor.h:190
Tensor operator*(const Tensor &value) const
Definition: Tensor.h:592
Tensor operator<=(const Tensor &value) const
Definition: Tensor.h:832
bool Any() const
Definition: Tensor.cpp:1707
int64_t GetStride(int64_t dim) const
Definition: Tensor.h:1069
Definition: Blob.h:56
Tensor Clip_(Scalar min_val, Scalar max_val)
Definition: Tensor.cpp:1328
Iterator end()
Definition: Tensor.cpp:262
Tensor Lt(const Tensor &value) const
Element-wise less-than of tensors, returning a new boolean tensor.
Definition: Tensor.cpp:1516
Tensor ArgMax(const SizeVector &dims) const
Definition: Tensor.cpp:1219
Tensor Transpose(int64_t dim0, int64_t dim1) const
Transpose a Tensor by swapping dimension dim0 and dim1.
Definition: Tensor.cpp:1005
Tensor IndexGet(const std::vector< Tensor > &index_tensors) const
Advanced indexing getter.
Definition: Tensor.cpp:879
Tensor T() const
Expects input to be <= 2-D Tensor by swapping dimension 0 and 1.
Definition: Tensor.cpp:1016
static Tensor Empty(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor with uninitialized values.
Definition: Tensor.cpp:374
Tensor LogicalAnd(const Tensor &value) const
Definition: Tensor.cpp:1383
bool AllEqual(const Tensor &other) const
Definition: Tensor.cpp:1770
Tensor Neg() const
Element-wise negation of a tensor, returning a new tensor.
Definition: Tensor.cpp:1259
const Dtype Undefined
Definition: Dtype.cpp:60
Tensor Le(const Tensor &value) const
Definition: Tensor.cpp:1580
bool All() const
Definition: Tensor.cpp:1700
Tensor Ge_(const Tensor &value)
Definition: Tensor.cpp:1566
Tensor operator &&(const Tensor &value) const
Definition: Tensor.h:752
~Iterator()
Definition: Tensor.cpp:224
Tensor Prod(const SizeVector &dims, bool keepdim=false) const
Definition: Tensor.cpp:1191
Tensor Neg_()
Element-wise negation of a tensor, in-place.
Definition: Tensor.cpp:1265
void IndexSet(const std::vector< Tensor > &index_tensors, const Tensor &src_tensor)
Advanced indexing getter.
Definition: Tensor.cpp:910
Tensor operator-=(Scalar value)
Definition: Tensor.h:587
Tensor Clip(Scalar min_val, Scalar max_val) const
Definition: Tensor.cpp:1322
Tensor To(Dtype dtype, bool copy=false) const
Definition: Tensor.cpp:713
Tensor Contiguous() const
Definition: Tensor.cpp:746
Tensor & operator=(const Tensor &other) &
Definition: Tensor.cpp:341
ConstIterator cbegin() const
Definition: Tensor.cpp:324
Tensor IsNan() const
Definition: Tensor.cpp:1292
Tensor operator-(const Tensor &value) const
Definition: Tensor.h:579
Tensor Ne_(const Tensor &value)
Definition: Tensor.cpp:1662
Definition: Device.h:39
SizeVector shape_
SizeVector of the Tensor. shape_[i] is the legnth of dimension i.
Definition: Tensor.h:1232
std::shared_ptr< Blob > GetBlob() const
Definition: Tensor.h:1098
bool IsContiguous() const
Definition: Tensor.h:966
std::tuple< Tensor, Tensor > Triul(const int diagonal=0) const
Returns the tuple of upper and lower triangular matrix of the 2D tensor, above and below the given di...
Definition: Tensor.cpp:1861
char type
Definition: FilePCD.cpp:60
const void * GetDataPtr() const
Definition: Tensor.h:1092
Tensor operator+=(Scalar value)
Definition: Tensor.h:574
Tensor Eq_(const Tensor &value)
Definition: Tensor.cpp:1630
Tensor Mean(const SizeVector &dims, bool keepdim=false) const
Definition: Tensor.cpp:1177
Tensor LogicalOr_(const Tensor &value)
Definition: Tensor.cpp:1436
Tensor Div_(const Tensor &value)
Definition: Tensor.cpp:1155
void AssertTemplateDtype() const
Definition: Tensor.h:1105
int64_t WrapDim(int64_t dim, int64_t max_dim, bool inclusive)
Wrap around negative dim.
Definition: ShapeUtil.cpp:150
void FillObject(const Object &v)
Definition: Tensor.h:1333
Tensor Expand(const SizeVector &dst_shape) const
Definition: Tensor.cpp:612
Tensor & AssignObject(const Object &v) &&
Definition: Tensor.h:163
Tensor IsFinite() const
Definition: Tensor.cpp:1312
static Tensor Zeros(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor fill with zeros.
Definition: Tensor.cpp:380
#define DISPATCH_DTYPE_TO_TEMPLATE_WITH_BOOL(DTYPE,...)
Definition: Dispatch.h:86
ConstIterator begin() const
Definition: Tensor.h:1207
typename NestedInitializerImpl< T, D >::type NestedInitializerList
Definition: TensorInit.h:55
SizeVector InferShape(const L &list)
Definition: TensorInit.h:101
Dtype dtype_
Data type.
Definition: Tensor.h:1259
void CopyFrom(const Tensor &other)
Copy Tensor values to current tensor from the source tensor.
Definition: Tensor.cpp:744
static Tensor Load(const std::string &file_name)
Load tensor from numpy&#39;s npy format.
Definition: Tensor.cpp:1766
Tensor Gt(const Tensor &value) const
Element-wise greater-than of tensors, returning a new boolean tensor.
Definition: Tensor.cpp:1484
Tensor Add_(const Tensor &value)
Definition: Tensor.cpp:1053
SizeVector GetShape() const
Definition: Tensor.h:1057
Tensor operator+(const Tensor &value) const
Definition: Tensor.h:566
bool IsSame(const Tensor &other) const
Definition: Tensor.cpp:1797
int64_t NumElements() const
Definition: SizeVector.cpp:126
Tensor LogicalNot_()
Definition: Tensor.cpp:1378
Tensor operator-=(const Tensor &value)
Definition: Tensor.h:586
Tensor Trunc() const
Element-wise trunc value of a tensor, returning a new tensor.
Definition: Tensor.cpp:1359
DLManagedTensor * ToDLPack() const
Convert the Tensor to DLManagedTensor.
Definition: Tensor.cpp:1714
int64_t GetShape(int64_t dim) const
Definition: Tensor.h:1061
Tensor AsRvalue()
Definition: Tensor.h:501
SizeVector GetStrides() const
Definition: Tensor.h:1065
Tensor Reshape(const SizeVector &dst_shape) const
Definition: Tensor.cpp:645
Definition: PinholeCameraIntrinsic.cpp:35
Iterator begin()
Definition: Tensor.cpp:255
std::ptrdiff_t difference_type
Definition: Tensor.h:1132
Definition: Tensor.h:50
Tensor Div(const Tensor &value) const
Divides a tensor and returns the resulting tensor.
Definition: Tensor.cpp:1136
static Tensor Ones(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor fill with ones.
Definition: Tensor.cpp:386
Tensor()
Definition: Tensor.h:52
int64_t ByteSize() const
Definition: Dtype.h:77
Tensor Triu(const int diagonal=0) const
Returns the upper triangular matrix of the 2D tensor, above the given diagonal index. [The value of diagonal = col - row, therefore 0 is the main diagonal (row = col), and it shifts towards right for positive values (for diagonal = 1, col - row = 1), and towards left for negative values. The value of the diagonal parameter must be between [-m, n] for a {m,n} shaped tensor.
Definition: Tensor.cpp:1849
Tensor Sub(const Tensor &value) const
Substracts a tensor and returns the resulting tensor.
Definition: Tensor.cpp:1068
Tensor Mul(const Tensor &value) const
Multiplies a tensor and returns the resulting tensor.
Definition: Tensor.cpp:1102
Tensor operator/=(const Tensor &value)
Definition: Tensor.h:612
bool operator!=(const Iterator &other) const
Definition: Tensor.cpp:251
Tensor Flatten(int64_t start_dim=0, int64_t end_dim=-1) const
Definition: Tensor.cpp:659
Tensor Slice(int64_t dim, int64_t start, int64_t stop, int64_t step=1) const
Definition: Tensor.cpp:831
Tensor Sqrt() const
Element-wise square root of a tensor, returns a new tensor.
Definition: Tensor.cpp:1226
Tensor Ne(const Tensor &value) const
Element-wise not-equals-to of tensors, returning a new boolean tensor.
Definition: Tensor.cpp:1644
Tensor Le_(const Tensor &value)
Definition: Tensor.cpp:1598
double Det() const
Compute the determinant of a 2D square tensor.
Definition: Tensor.cpp:1029
Iterator & operator++()
Definition: Tensor.cpp:235
Tensor operator!=(const Tensor &value) const
Definition: Tensor.h:852
Tensor Round() const
Element-wise round value of a tensor, returning a new tensor.
Definition: Tensor.cpp:1353
Tensor operator-(Scalar value) const
Definition: Tensor.h:580
Tensor Exp_()
Element-wise base-e exponential of a tensor, in-place.
Definition: Tensor.cpp:1276
Tensor Append(const Tensor &other, const utility::optional< int64_t > &axis=utility::nullopt) const
Appends the other tensor, along the given axis and returns a copy of the tensor. The other tensors mu...
Definition: Tensor.cpp:596
T * GetDataPtr()
Definition: Tensor.h:1074
static Tensor Init(const T val, const Device &device=Device("CPU:0"))
Definition: Tensor.h:218
Tensor operator/(Scalar value) const
Definition: Tensor.h:606
Tensor IndexExtract(int64_t dim, int64_t idx) const
Definition: Tensor.cpp:815
Tensor operator*(Scalar value) const
Definition: Tensor.h:593
const T * GetDataPtr() const
Definition: Tensor.h:1079
static Tensor Eye(int64_t n, Dtype dtype, const Device &device)
Create an identity matrix of size n x n.
Definition: Tensor.cpp:392
Iterator(pointer tensor, int64_t index)
Definition: Tensor.cpp:210
static Tensor Init(const std::initializer_list< std::initializer_list< std::initializer_list< T >>> &in_list, const Device &device=Device("CPU:0"))
Definition: Tensor.h:245
std::vector< Tensor > NonZeroNumpy() const
Definition: Tensor.cpp:1676
Tensor operator<(const Tensor &value) const
Definition: Tensor.h:810
Tensor operator>(const Tensor &value) const
Definition: Tensor.h:800
Tensor Tril(const int diagonal=0) const
Returns the lower triangular matrix of the 2D tensor, above the given diagonal index. [The value of diagonal = col - row, therefore 0 is the main diagonal (row = col), and it shifts towards right for positive values (for diagonal = 1, col - row = 1), and towards left for negative values. The value of the diagonal parameter must be between [-m, n] where {m, n} is the shape of input tensor.
Definition: Tensor.cpp:1855
Tensor Abs() const
Element-wise absolute value of a tensor, returning a new tensor.
Definition: Tensor.cpp:1281
Tensor(const std::vector< T > &init_vals, const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Constructor for creating a contiguous Tensor with initial values.
Definition: Tensor.h:68
void * data_ptr_
Definition: Tensor.h:1256
Tensor LeastSquares(const Tensor &rhs) const
Definition: Tensor.cpp:1823
ConstIterator cend() const
Definition: Tensor.cpp:331
int64_t GetLength() const
Definition: Tensor.h:1055
SizeVector DefaultStrides(const SizeVector &shape)
Compute default strides for a shape when a tensor is contiguous.
Definition: ShapeUtil.cpp:233
bool IsObject() const
Definition: Dtype.h:81
static Tensor FromDLPack(const DLManagedTensor *dlmt)
Convert DLManagedTensor to Tensor.
Definition: Tensor.cpp:1718
std::vector< T > ToFlatVector() const
Retrive all values as an std::vector, for debugging and testing.
Definition: Tensor.h:955
Tensor & operator=(const T v) &&
Definition: Tensor.h:154
Tensor Abs_()
Element-wise absolute value of a tensor, in-place.
Definition: Tensor.cpp:1287
T Item() const
Definition: Tensor.h:551
Tensor Add(const Tensor &value) const
Adds a tensor and returns the resulting tensor.
Definition: Tensor.cpp:1034
Tensor Sin() const
Element-wise sine of a tensor, returning a new tensor.
Definition: Tensor.cpp:1237
std::string ScalarPtrToString(const void *ptr) const
Definition: Tensor.cpp:799
Tensor Clone() const
Copy Tensor to the same device.
Definition: Tensor.h:445
Tensor Floor() const
Element-wise floor value of a tensor, returning a new tensor.
Definition: Tensor.cpp:1341
void Fill(S v)
Fill the whole Tensor with a scalar value, the scalar will be casted to the Tensor&#39;s Dtype...
Definition: Tensor.h:1323
#define LogError(...)
Definition: Logging.h:72
Tensor Cos() const
Element-wise cosine of a tensor, returning a new tensor.
Definition: Tensor.cpp:1248
static Tensor Init(const std::initializer_list< T > &in_list, const Device &device=Device("CPU:0"))
Definition: Tensor.h:228
const SizeVector & GetShapeRef() const
Definition: Tensor.h:1059
Tensor operator/=(Scalar value)
Definition: Tensor.h:613