PetaVision  Alpha
SparseList.hpp
1 #ifndef __SPARSELIST_HPP__
2 #define __SPARSELIST_HPP__
3 
4 #include "Buffer.hpp"
5 #include "utils/PVLog.hpp"
6 
7 #include <vector>
8 
9 using std::vector;
10 
11 namespace PV {
12 
13 template <typename T>
14 class SparseList {
15  public:
16  struct Entry {
17  uint32_t index;
18  T value;
19  };
20 
21  SparseList() {}
22  SparseList(const Buffer<T> &source, T zeroVal) { fromBuffer(source, zeroVal); }
23 
24  void fromBuffer(const Buffer<T> &source, T zeroVal) {
25  mList.clear();
26  uint32_t index = 0;
27  for (int y = 0; y < source.getHeight(); ++y) {
28  for (int x = 0; x < source.getWidth(); ++x) {
29  for (int f = 0; f < source.getFeatures(); ++f) {
30  T val = source.at(x, y, f);
31  if (val != zeroVal) {
32  mList.push_back({index, val});
33  }
34  index++;
35  }
36  }
37  }
38  }
39 
40  void toBuffer(Buffer<T> &dest, T zeroVal) {
41  int numElements = dest.getTotalElements();
42  vector<T> newData(numElements, zeroVal);
43  for (auto entry : mList) {
44  FatalIf(
45  entry.index > numElements,
46  "Buffer is not large enough to hold index %d / %d\n",
47  entry.index,
48  numElements);
49  newData.at(entry.index) = entry.value;
50  }
51  dest.set(newData, dest.getWidth(), dest.getHeight(), dest.getFeatures());
52  }
53 
54  void addEntry(Entry entry) { mList.push_back(entry); }
55 
56  void appendToList(SparseList<T> &dest) {
57  for (auto entry : mList) {
58  dest.addEntry(entry);
59  }
60  }
61 
62  void set(const vector<Entry> &values) { mList = values; }
63 
64  vector<Entry> getContents() { return mList; }
65 
66  private:
67  vector<Entry> mList;
68 };
69 }
70 
71 #endif