00001 #ifndef LSHKIT_MATRIX
00002 #define LSHKIT_MATRIX
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022 #include <fstream>
00023 #include <boost/dynamic_bitset.hpp>
00024
00046 namespace lshkit {
00047
00049
00053 template <class T>
00054 class Matrix
00055 {
00056 int dim, N;
00057 T *dims;
00058 T **vecs;
00059
00060 void load (const char *);
00061 void save (const char *);
00062
00063 #ifdef MATRIX_MMAP
00064 int fd;
00065 #endif
00066 public:
00068
00072 void reset (int _dim, int _N)
00073 {
00074 dim = _dim;
00075 N = _N;
00076 if (dims != NULL) delete[] dims;
00077 if (vecs != NULL) delete[] vecs;
00078 dims = new T[dim * N];
00079 vecs = new T*[N];
00080 for (int i = 0; i < N; i++) {
00081 vecs[i] = dims + i * dim;
00082 }
00083 }
00084
00086 void free (void) {
00087 dim = N = 0;
00088 if (dims != NULL) delete[] dims;
00089 if (vecs != NULL) delete[] dims;
00090 dims = NULL;
00091 vecs = NULL;
00092 }
00093
00095
00096 Matrix () :dim(0), N(0), dims(NULL), vecs(NULL) {}
00097
00099 Matrix (int _dim, int _N) : dims(NULL), vecs(NULL) { reset(_dim, _N); }
00100
00102 ~Matrix () { if (dims != NULL) delete[] dims; if (vecs != NULL) delete[] vecs; }
00103
00105 const T *operator [] (int i) const { return vecs[i]; }
00106
00108 T *operator [] (int i) { return vecs[i]; }
00109
00111 T **const getVecs () const {
00112 return vecs;
00113 }
00114
00115 int getDim () const {return dim; }
00116 int getSize () const {return N; }
00117
00118
00120
00128 static void peek (const std::string &path, int *elem_size, int *size, int *dim);
00129
00130 void load (const std::string &path);
00131 void save (const std::string &path);
00132 void load (std::istream &is);
00133 void save (std::ostream &os);
00134
00135 #ifdef MATRIX_MMAP
00136 void map (const std::string &path);
00137 void unmap ();
00138 #endif
00139
00141 Matrix (const std::string &path): dims(NULL),vecs(NULL) { load(path); }
00142
00144 class Accessor
00145 {
00146 const Matrix &matrix_;
00147 boost::dynamic_bitset<> flags_;
00148 public:
00149 typedef unsigned Key;
00150 typedef const float *Value;
00151
00152 Accessor(const Matrix &matrix)
00153 : matrix_(matrix), flags_(matrix.getSize()) {}
00154
00155 void reset () {
00156 flags_.reset();
00157 }
00158
00159 bool mark (unsigned key) {
00160 if (flags_[key]) return false;
00161 flags_.set(key);
00162 return true;
00163 }
00164
00165 const float *operator () (unsigned key) {
00166 return matrix_[key];
00167 }
00168 };
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193 };
00194
00195 typedef Matrix<float> FloatMatrix;
00196
00197 }
00198
00199 #include <lshkit/matrix-io.h>
00200 #endif