sparse_helper.cpp
Go to the documentation of this file.
00001 #include "sparse_helper.h"
00002 
00003 #include <string>
00004 #include <fstream>
00005 #include <iomanip>
00006 #include <vector>
00007 #include <algorithm>
00008 
00009 using namespace std;
00010 
00011 namespace g2o {
00012 
00013   namespace {
00014     struct TripletEntry
00015     {
00016       int r, c;
00017       double x;
00018       TripletEntry(int r_, int c_, double x_) : r(r_), c(c_), x(x_) {}
00019     };
00020     struct TripletColSort
00021     {
00022       bool operator()(const TripletEntry& e1, const TripletEntry& e2) const
00023       {
00024         return e1.c < e2.c || (e1.c == e2.c && e1.r < e2.r);
00025       }
00026     };
00027   }
00028 
00029   bool writeVector(const char* filename, const double*v, int n)
00030   {
00031     ofstream os(filename);
00032     os << fixed;
00033     for (int i=0; i<n; i++)
00034       os << *v++ << endl;
00035     return os.good();
00036   }
00037 
00038   bool writeCCSMatrix(const char* filename, int rows, int cols, const int* Ap, const int* Ai, const double* Ax, bool upperTriangleSymmetric)
00039   {
00040     vector<TripletEntry> entries;
00041     entries.reserve(Ap[cols]);
00042     for (int i=0; i < cols; i++) {
00043       const int& rbeg = Ap[i];
00044       const int& rend = Ap[i+1];
00045       for (int j = rbeg; j < rend; j++) {
00046         entries.push_back(TripletEntry(Ai[j], i, Ax[j]));
00047         if (upperTriangleSymmetric && Ai[j] != i)
00048           entries.push_back(TripletEntry(i, Ai[j], Ax[j]));
00049       }
00050     }
00051     sort(entries.begin(), entries.end(), TripletColSort());
00052 
00053     string name = filename;
00054     std::string::size_type lastDot = name.find_last_of('.');
00055     if (lastDot != std::string::npos) 
00056       name = name.substr(0, lastDot);
00057 
00058     std::ofstream fout(filename);
00059     fout << "# name: " << name << std::endl;
00060     fout << "# type: sparse matrix" << std::endl;
00061     fout << "# nnz: " << entries.size() << std::endl;
00062     fout << "# rows: " << rows << std::endl;
00063     fout << "# columns: " << cols << std::endl;
00064     //fout << fixed;
00065     fout << setprecision(9) << endl;
00066     for (vector<TripletEntry>::const_iterator it = entries.begin(); it != entries.end(); ++it) {
00067       const TripletEntry& entry = *it;
00068       fout << entry.r+1 << " " << entry.c+1 << " " << entry.x << std::endl;
00069     }
00070     return fout.good();
00071   }
00072 
00073 } // end namespace


re_vision
Author(s): Dorian Galvez-Lopez
autogenerated on Sun Jan 5 2014 11:32:45