Skip to content

Instantly share code, notes, and snippets.

@john9francis
Created September 20, 2024 02:52
Show Gist options
  • Save john9francis/a0acf2ce4ee5542baf4c85dbf496fdec to your computer and use it in GitHub Desktop.
Save john9francis/a0acf2ce4ee5542baf4c85dbf496fdec to your computer and use it in GitHub Desktop.
An idea for a tensor class that holds positions as keys and energy as values. That way accessing it by simply myTensor[vector]+=energy adds the energy to that position or creates position and adds the energy. It's just a clever use of std::map.
// Demonstrating a Tensor class. This tensor holds vector3's as
// keys and doubles as values. It has the benefit of ordering the
// vector3's and counting duplicates in the value slot.
// Easy addition to the values.
//
// My use case is storing voxelized information about a phantom
// in a medical physics application and recording total energy
// deposited in each position voxel.
// pos_energy_tensor
#include <map>
#include <iostream>
#include <vector>
struct Vector3{
int x, y, z;
};
// Custom comparator for Vector3, to be used for the tensor datatype
// This helps the tensor put the values in order
struct Vector3Compare {
bool operator()(const Vector3& lhs, const Vector3& rhs) const {
if (lhs.x != rhs.x) return lhs.x < rhs.x;
if (lhs.y != rhs.y) return lhs.y < rhs.y;
return lhs.z < rhs.z;
}
};
// Maps double values to Vector3 keys
using Tensor = std::map<Vector3, double, Vector3Compare>;
int main(){
Tensor myTensor;
// To store a bunch of Vector3's
std::vector <Vector3> vecs;
// All these random Vector3's will be sorted soon
vecs.push_back(Vector3{3,1,1});
vecs.push_back(Vector3{1,1,1});
vecs.push_back(Vector3{1,1,1});
vecs.push_back(Vector3{1,2,1});
vecs.push_back(Vector3{1,1,2});
vecs.push_back(Vector3{2,1,1});
vecs.push_back(Vector3{4,2,1});
vecs.push_back(Vector3{1,2,60});
vecs.push_back(Vector3{2,2,1});
vecs.push_back(Vector3{6,2,1});
vecs.push_back(Vector3{1,2,1});
// Add each vector to the tensor map
for (auto& vec : vecs){
myTensor[vec]++;
}
// Print to show we successfully sorted the data
for (const auto& i : myTensor) {
std::cout << "(" << i.first.x << ", " << i.first.y << ", " << i.first.z
<< "): " << i.second << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment