Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #include "matrix_structure.h"
00018
00019 #include <string>
00020 #include <vector>
00021 #include <fstream>
00022 #include <algorithm>
00023 using namespace std;
00024
00025 namespace g2o {
00026
00027 struct ColSort
00028 {
00029 bool operator()(const pair<int, int>& e1, const pair<int, int>& e2) const
00030 {
00031 return e1.second < e2.second || (e1.second == e2.second && e1.first < e2.first);
00032 }
00033 };
00034
00035 MatrixStructure::MatrixStructure() :
00036 n(0), m(0), Ap(0), Aii(0), maxN(0), maxNz(0)
00037 {
00038 }
00039
00040 MatrixStructure::~MatrixStructure()
00041 {
00042 free();
00043 }
00044
00045 void MatrixStructure::alloc(int n_, int nz)
00046 {
00047 if (n == 0) {
00048 maxN = n = n_;
00049 maxNz = nz;
00050 Ap = new int[maxN + 1];
00051 Aii = new int[maxNz];
00052 }
00053 else {
00054 n = n_;
00055 if (maxNz < nz) {
00056 maxNz = 2 * nz;
00057 delete[] Aii;
00058 Aii = new int[maxNz];
00059 }
00060 if (maxN < n) {
00061 maxN = 2 * n;
00062 delete[] Ap;
00063 Ap = new int[maxN + 1];
00064 }
00065 }
00066 }
00067
00068 void MatrixStructure::free()
00069 {
00070 n = 0;
00071 m = 0;
00072 maxN = 0;
00073 maxNz = 0;
00074 delete[] Aii; Aii = 0;
00075 delete[] Ap; Ap = 0;
00076 }
00077
00078 bool MatrixStructure::write(const char* filename) const
00079 {
00080 const int& cols = n;
00081 const int& rows = m;
00082
00083 string name = filename;
00084 std::string::size_type lastDot = name.find_last_of('.');
00085 if (lastDot != std::string::npos)
00086 name = name.substr(0, lastDot);
00087
00088 vector<pair<int, int> > entries;
00089 for (int i=0; i < cols; i++) {
00090 const int& rbeg = Ap[i];
00091 const int& rend = Ap[i+1];
00092 for (int j = rbeg; j < rend; j++) {
00093 entries.push_back(make_pair(Aii[j], i));
00094 if (Aii[j] != i)
00095 entries.push_back(make_pair(i, Aii[j]));
00096 }
00097 }
00098
00099 sort(entries.begin(), entries.end(), ColSort());
00100
00101 std::ofstream fout(filename);
00102 fout << "# name: " << name << std::endl;
00103 fout << "# type: sparse matrix" << std::endl;
00104 fout << "# nnz: " << entries.size() << std::endl;
00105 fout << "# rows: " << rows << std::endl;
00106 fout << "# columns: " << cols << std::endl;
00107 for (vector<pair<int, int> >::const_iterator it = entries.begin(); it != entries.end(); ++it) {
00108 const pair<int, int>& entry = *it;
00109 fout << entry.first << " " << entry.second << " 0" << std::endl;
00110 }
00111
00112 return fout.good();
00113 }
00114
00115 }