Analysis Software
Documentation for sPHENIX simulation software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TensorVectorConversion.hpp
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file TensorVectorConversion.hpp
1 // This file is part of the Acts project.
2 //
3 // Copyright (C) 2023 CERN for the benefit of the Acts project
4 //
5 // This Source Code Form is subject to the terms of the Mozilla Public
6 // License, v. 2.0. If a copy of the MPL was not distributed with this
7 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 
9 #pragma once
10 
12 
13 #include <cstdint>
14 #include <vector>
15 
16 #include <torch/torch.h>
17 
18 namespace Acts::detail {
19 
21 template <typename T>
22 struct TorchTypeMap {};
23 
24 template <>
25 struct TorchTypeMap<int64_t> {
26  constexpr static torch::Dtype type = torch::kInt64;
27 };
28 
29 template <>
30 struct TorchTypeMap<int32_t> {
31  constexpr static torch::Dtype type = torch::kInt32;
32 };
33 
34 template <>
35 struct TorchTypeMap<int16_t> {
36  constexpr static torch::Dtype type = torch::kInt16;
37 };
38 
39 template <>
40 struct TorchTypeMap<int8_t> {
41  constexpr static torch::Dtype type = torch::kInt8;
42 };
43 
44 template <>
45 struct TorchTypeMap<float> {
46  constexpr static torch::Dtype type = torch::kFloat32;
47 };
48 
49 template <>
51  constexpr static torch::Dtype type = torch::kFloat64;
52 };
53 
59 template <typename T>
60 at::Tensor vectorToTensor2D(std::vector<T> &vec, std::size_t cols) {
61  assert(vec.size() % cols == 0);
62 
63  auto opts =
64  at::TensorOptions().dtype(TorchTypeMap<T>::type).device(torch::kCPU);
65 
66  return torch::from_blob(
67  vec.data(),
68  {static_cast<long>(vec.size() / cols), static_cast<long>(cols)}, opts);
69 }
70 
73 template <typename T>
74 std::vector<T> tensor2DToVector(const at::Tensor &tensor) {
75  assert(tensor.sizes().size() == 2);
76 
77  // clone to make sure we own the data
78  // bring to CPU
79  // convert to requested type
80  // ensure the tensor is contiguous (e.g. not the case if indexed with step)
81 
82  at::Tensor transformedTensor =
83  tensor.to(torch::kCPU).to(TorchTypeMap<T>::type).contiguous();
84 
85  std::vector<T> edgeIndex(
86  transformedTensor.template data_ptr<T>(),
87  transformedTensor.template data_ptr<T>() + transformedTensor.numel());
88 
89  return edgeIndex;
90 }
91 
92 } // namespace Acts::detail