CovMatrix.cpp

00001 /**************************************************
00002 
00003   CovMatrix class
00004 
00005   Antoni Chan,
00006   City University of Hong Kong, Copyright 2014
00007   libdt - OpenCV library for Dynamic Textures - version 1.0
00008 
00009   
00010 
00011 ***************************************************/
00012 
00013 #include <iostream>
00014 #include <string>
00015 #include<fstream>
00016 
00017 #include "opencv/cxcore.h"
00018 
00019 #include "options.h"
00020 #include "utils/libutils.h"
00021 #include "stats/CovMatrix.hpp"
00022 
00023 // constructor
00024 CovMatrix::CovMatrix(int n, cov_type covopt) : 
00025   mtx( (covopt == COV_IID ? 1 : n), (covopt == COV_FULL ? n : 1), OPT_MAT_TYPE),  // initialize mtx
00026   regopt(COV_REG_NONE), regval(0.0)                                         // initialize regs
00027 {
00028   this->covopt = covopt;
00029   this->n      = n;
00030   switch(covopt) {
00031   case COV_FULL: case COV_DIAG: case COV_IID:
00032     break;
00033   default:
00034     CV_Error(-1, "Error: invalid cov_type");
00035   }
00036   if (n<1)
00037     CV_Error(-1, "Error: invalid n");
00038 
00039   sqrtmtx = 0;
00040 }
00041 
00042 // desctructor
00043 CovMatrix::~CovMatrix() {
00044   if (sqrtmtx)
00045     delete sqrtmtx;
00046 }
00047 
00048 
00049 // calculate a covariance matrix from data
00050 void CovMatrix::calculate(const Mat &data, bool use_unbiased, bool assume_zero_mean) {
00051   int N = 0;
00052   
00053   // non-zero mean not supported yet
00054   CV_Assert(assume_zero_mean == true);
00055   
00056   // check data
00057   CV_Assert(data.rows == n);
00058 
00059   // calculate sum
00060   switch(covopt) {
00061   case COV_FULL:
00062     mulTransposed(data, mtx, false);  // data*data^T
00063     N = data.cols;
00064     break;
00065 
00066   case COV_DIAG:
00067   case COV_IID:
00068     {
00069       Mat tmp;
00070       // square: data.*data
00071       multiply(data, data, tmp);
00072       
00073       if (covopt == COV_IID) {
00074         // sum everything       
00075         mtx = sum(tmp);
00076         N   = data.cols*data.rows;
00077       } else {
00078         // sum over rows
00079         reduce(tmp, mtx, 1, CV_REDUCE_SUM);
00080         N = data.cols;
00081       }
00082     }
00083     break;
00084 
00085   default:
00086     CV_Error(-1, "unknown cov");
00087   }   
00088 
00089   // average
00090   if (use_unbiased)
00091     mtx /= (N-1);
00092   else
00093     mtx /= N;
00094 }
00095 
00096 
00097 
00098 // set regularization mode
00099 void CovMatrix::setRegularizer(cov_reg_type regopt, double regval) {
00100   switch(regopt) {
00101   case COV_REG_NONE: case COV_REG_MIN: case COV_REG_ADD:
00102     break;
00103   default:
00104     CV_Error(-1, "ERROR: invalid cov_reg_type!");
00105   }
00106 
00107   if (regval < 0)
00108     CV_Error(-1, "ERROR: invalid regval");
00109   
00110   this->regopt = regopt;
00111   this->regval = regval;
00112 }
00113 
00114 // regularize
00115 void CovMatrix::regularize() {
00116   switch(regopt) {
00117   case COV_REG_NONE:
00118     // do nothing
00119     break;
00120 
00121   case COV_REG_MIN:
00122     switch(covopt) {
00123     case COV_FULL:
00124       // min bound on eigenvalues
00125       {
00126         Size sz = mtx.size();
00127         Mat eigS(sz.height, 1, OPT_MAT_TYPE), 
00128             eigV(sz.height, sz.width, OPT_MAT_TYPE);
00129         eigen(mtx, eigS, eigV);
00130         // min bound on eigenvalues
00131         bool doRecon = inp_minbnd<OPT_F_TYPE>(eigS, regval);
00132 
00133         //cout << "eigS = \n" << eigS << "\n";
00134         //cout << "eigV = \n" << eigV << "\n";
00135 
00136         // reconstruct matrix (if something changed)
00137         if (doRecon) {
00138           // note: eigV rows are the eigenvalues
00139           Mat S = repeat(eigS, 1, sz.width);   // S = [eigS, eigS ...]
00140           multiply(S, eigV, S);                // S = S .* eigV
00141           mtx = eigV.t() * S;                  // mtx = eigV'*diag(S)*eigV
00142         }
00143       }
00144       break;
00145     case COV_DIAG: case COV_IID: 
00146       // min of elements 
00147       inp_minbnd<OPT_F_TYPE>(mtx, regval);
00148       break;
00149     }
00150     break;
00151 
00152   case COV_REG_ADD:
00153     // regularize by adding to diagonal
00154     switch(covopt) {
00155     case COV_FULL:
00156       {
00157         // add to just diagonal
00158         // TODO: can optimize this (add in-place)
00159         Mat dmtx = mtx.diag();
00160         add(dmtx, regval, dmtx);
00161       }
00162       break;
00163 
00164     case COV_DIAG:
00165     case COV_IID:
00166       // add to diagonal (all elements)
00167       // TODO: can optimize this (add in-place)
00168       add(mtx, regval, mtx);
00169       break;
00170     }
00171     break;    
00172 
00173   default:
00174     CV_Error(-1, "ERROR: invalid cov_reg_type!");
00175   }
00176 }
00177 
00178 // convert to full matrix, store in fmtx (creates a copy if necessary).
00179 void CovMatrix::toFullMatrix(Mat & fmtx) const {
00180   fmtx.create(n, n, OPT_MAT_TYPE);
00181   switch(covopt) {
00182   case COV_FULL:
00183     mtx.copyTo(fmtx);
00184     break;
00185   case COV_DIAG:
00186     fmtx = Mat::diag(mtx);
00187     break;
00188   case COV_IID:
00189     fmtx = Mat::eye(n, n, OPT_MAT_TYPE) * mtx.at<OPT_F_TYPE>(0);    
00190     break;
00191   default:
00192     CV_Error(-1, "ERROR: invalid cov_type!");
00193   }
00194 }
00195 
00196 // convert to full matrix, return it
00197 Mat  CovMatrix::toFullMatrix() const {
00198   Mat out;
00199   toFullMatrix(out);
00200   return out;
00201 }
00202 
00203 // set from a matrix M
00204 void CovMatrix::set(const Mat &M) {
00205   // check dimensions of M...
00206 
00207   // it's a scalar
00208   if (M.cols == 1 && M.rows == 1) {
00209     CV_Error(-1, "not implemented");
00210 
00211   } else if ((M.cols == M.rows) && (M.cols == n)) {
00212   // it's a full matrix
00213     switch(covopt) {
00214     case COV_FULL:
00215       // just copy
00216       M.copyTo(mtx);
00217       break;
00218     case COV_DIAG:
00219       // copy the diagonal
00220       M.diag(0).copyTo(mtx);
00221       break;
00222     case COV_IID:
00223       // copy the mean of the diagonal
00224       {
00225         const Mat tmp = M.diag(0);
00226         mtx.setTo(mean(tmp));
00227       }
00228       break;
00229     }
00230 
00231   // it's a vector
00232   } else if ( ((M.cols == n) && (M.rows == 1)) || 
00233               ((M.rows == n) && (M.cols == 1)) ) {
00234     CV_Error(-1, "not implemented");
00235 
00236   } else {
00237     CV_Error(-1, "bad M");
00238   }
00239 }
00240 
00241 // generate random vector
00242 void CovMatrix::randvec(Mat &X, RNG &rng) {
00243   if (sqrtmtx == 0) {
00244     // initialize sqrt(mtx)
00245     sqrtmtx = new Mat();
00246     switch(covopt) {
00247     case COV_FULL:
00248       {
00249         SVD svd(mtx);
00250         Mat ww;
00251         sqrt(svd.w, ww);
00252         svd.u.copyTo(*sqrtmtx);
00253         scaleCols(*sqrtmtx, ww);
00254       }
00255       break;
00256     case COV_DIAG:      
00257     case COV_IID:
00258       sqrt(mtx, *sqrtmtx);
00259       break;
00260     default:
00261       CV_Error(-1, "bad covopt");
00262     }
00263   }
00264   
00265   switch(covopt) {
00266   case COV_FULL:
00267     {
00268       Mat Xtmp(X.rows, X.cols, X.type());
00269       rng.fill(Xtmp, RNG::NORMAL, 0.0, 1.0);
00270       X = (*sqrtmtx)*Xtmp;
00271     }
00272     break;
00273   case COV_DIAG:
00274     rng.fill(X, RNG::NORMAL, 0.0, 1.0);
00275     scaleRows(X, *sqrtmtx);
00276     break;
00277   case COV_IID:
00278     rng.fill(X, RNG::NORMAL, 0.0, 1.0);
00279     X *= sqrtmtx->at<OPT_F_TYPE>(0);
00280     break;
00281   default:
00282     CV_Error(-1, "bad covopt");
00283   }
00284 
00285 }
00286 
00287 // return the inverse of a covariance matrix
00288 CovMatrix CovMatrix::inv() const {
00289   CovMatrix out(n, covopt);
00290 
00291   switch(covopt) {
00292   case COV_FULL:
00293     invert(mtx, out.mtx, DECOMP_CHOLESKY);
00294     break;
00295   case COV_DIAG:
00296   case COV_IID:
00297     divide(1.0, mtx, out.mtx);
00298     break;
00299   default:
00300     CV_Error(-1, "bad covopt");
00301   }
00302 
00303   return out;
00304 }
00305 
00306 
00307 // dst = src*cov  (m x n) = (m x n) * (n x n)
00308 void CovMatrix::premultiply(const Mat &src, Mat &dst) const {
00309   // allocate the output matrix
00310   CV_Assert(src.cols == n);
00311   dst.create(src.rows, n, OPT_MAT_TYPE);
00312   switch(covopt) {
00313   case COV_FULL:
00314     dst = src*mtx;
00315     break;
00316   case COV_DIAG:
00317     src.copyTo(dst);
00318     scaleCols(dst, mtx);
00319     break;
00320   case COV_IID:
00321     src.copyTo(dst);
00322     dst *= mtx.at<OPT_F_TYPE>(0);
00323     break;
00324   default:
00325     CV_Error(-1, "bad covopt");
00326   }
00327 }
00328 
00329 // dst = cov*src  (n x m) = (n x n) * (n x m)
00330 void CovMatrix::postmultiply(const Mat &src, Mat &dst) const {
00331   // allocate the output matrix
00332   CV_Assert(src.rows == n);
00333   dst.create(n, src.cols, OPT_MAT_TYPE);
00334   switch(covopt) {
00335   case COV_FULL:
00336     dst = mtx*src;
00337     break;
00338   case COV_DIAG:
00339     src.copyTo(dst);
00340     scaleRows(dst, mtx);
00341     break;
00342   case COV_IID:
00343     src.copyTo(dst);
00344     dst *= mtx.at<OPT_F_TYPE>(0);
00345     break;
00346   default:
00347     CV_Error(-1, "bad covopt");
00348   }
00349 }
00350 
00351 
00352 const char* CovMatrix::cov_type_to_string(cov_type opt) {
00353   switch(opt) {
00354   case CovMatrix::COV_FULL: return("full"); break;
00355   case CovMatrix::COV_DIAG: return("diag"); break;
00356   case CovMatrix::COV_IID:  return("iid"); break;    
00357   default:
00358     CV_Error(-1, "ERROR: bad cov_type");
00359   }
00360   return "?";
00361 }
00362 
00363 const char* CovMatrix::cov_reg_type_to_string(cov_reg_type opt) {
00364   switch(opt) {
00365   case CovMatrix::COV_REG_NONE: return("none"); break;
00366   case CovMatrix::COV_REG_MIN:  return("min"); break;
00367   case CovMatrix::COV_REG_ADD:  return("add"); break;
00368   default:
00369     CV_Error(-1, "ERROR: bad cov_reg_type");
00370   }
00371   return "?";
00372 }
00373 
00374 
00375 // convert to string
00376 ostream& operator<<(ostream& output, const CovMatrix& cov) {
00377   output << "CovMatrix (n=" << cov.n << "; ";
00378   output << CovMatrix::cov_type_to_string(cov.covopt) << "; ";
00379   output << "reg:" << CovMatrix::cov_reg_type_to_string(cov.regopt) << "(" << cov.regval << ")";
00380   output << ")";
00381   return output;
00382 }
00383 
00384 
00385 
00386 
00387 
00388 
00389 char* CovMatrix::writeToMemory(char *mptr)
00390 {
00391         char *ptr=mptr;
00392         int objSize;
00393 
00394 
00395         strcpy(ptr,"CovMatrix");
00396         ptr+=10;
00397         strcpy(ptr,"1.0");
00398         ptr+=4;
00399 
00400         char* sizeptr=ptr;   //Here to write the size of this object
00401         ptr+=4;
00402         char* startptr=ptr;  //Here the data is started
00403 
00404 
00406 
00407         //Write n
00408         strcpy(ptr,"n");
00409         ptr+=2; 
00410         strcpy(ptr,"1.0"); //version
00411         ptr+=4; 
00412         int tsize=4;
00413         memcpy(ptr,&tsize,4); //size
00414         ptr+=4; 
00415         memcpy(ptr,&n,4);
00416         ptr+=4;
00417 
00418 
00419         //Write covopt
00420         strcpy(ptr,"covopt");
00421         ptr+=7; 
00422         strcpy(ptr,"1.0"); //version
00423         ptr+=4; 
00424         tsize=1;
00425         memcpy(ptr,&tsize,4); //size
00426         ptr+=4; 
00427         memcpy(ptr,&covopt,1);
00428         ptr+=1;
00429 
00430 
00431         //Write regopt
00432         strcpy(ptr,"regopt");
00433         ptr+=7; 
00434         strcpy(ptr,"1.0"); //version
00435         ptr+=4; 
00436         tsize=1;
00437         memcpy(ptr,&tsize,4); //size
00438         ptr+=4; 
00439         memcpy(ptr,&regopt,1);
00440         ptr+=1;
00441 
00442 
00443         //Write regval
00444         strcpy(ptr,"regval");
00445         ptr+=7; 
00446         strcpy(ptr,"1.0"); //version
00447         ptr+=4; 
00448         tsize=8;
00449         memcpy(ptr,&tsize,4); //size
00450         ptr+=4; 
00451         memcpy(ptr,&regval,8);
00452         ptr+=8;
00453 
00454         //Write mtx
00455         strcpy(ptr,"mtx");
00456         ptr+=4; 
00457         strcpy(ptr,"1.0"); //version
00458         ptr+=4;
00459         ptr=writeMatrix(ptr,mtx); //First Write Size then data
00460         
00461 
00463         objSize=ptr-startptr; //writing now the size of this object
00464         memcpy(sizeptr,&objSize,4);
00465 
00466         return ptr;  //Stream is At this Point Now
00467 }
00468 
00469 
00470 
00471 char* CovMatrix::readFromMemory(char *mptr)
00472 {
00473         char *ptr=mptr;
00474 
00475         string tmpStr(ptr); //Check name
00476         if(tmpStr!="CovMatrix")
00477                 CV_Error(-1,"Dytex object not found!");
00478         ptr+=(tmpStr.length()+1);
00479 
00480         tmpStr=ptr;  //check version    
00481         if(tmpStr!="1.0")
00482                 CV_Error(-1,"Invalid Version of Decoder");
00483         ptr+=(tmpStr.length()+1);
00484 
00485         //Get the size
00486         int size;
00487         memcpy(&size,ptr,4);
00488         ptr+=4;
00489 
00490         char *startPtr=ptr;
00491 
00492         //Read the parameters of this object from size bytes
00493         while( (ptr-startPtr)<size )
00494         {
00495                 tmpStr=ptr;  //Get Next Parameter
00496                 ptr+=(tmpStr.length()+1);
00497 
00498                 string vstr=ptr;  //Get version of parameter
00499                 ptr+=(vstr.length()+1);
00500 
00501                 if(vstr!="1.0")
00502                         CV_Error(-1,"Invalid Version of Parameter");
00503 
00504                 int psize;  //Get The size of the Parameter
00505                 memcpy(&psize,ptr,4);
00506                 ptr+=4;
00507 
00508                 if(tmpStr=="n")
00509                 {
00510                         memcpy(&n,ptr,4);
00511                         ptr+=4;
00512                 }
00513                 else if(tmpStr=="covopt")
00514                 {
00515                         memcpy(&covopt,ptr,1);
00516                         ptr+=1;
00517                 }
00518                 else if(tmpStr=="regopt")
00519                 {
00520                         memcpy(&regopt,ptr,1);
00521                         ptr+=1;
00522                 }
00523 
00524                 else if(tmpStr=="regval")
00525                 {
00526                         memcpy(&regval,ptr,8);
00527                         ptr+=8;
00528                 }
00529                 else if(tmpStr=="mtx")
00530                 {
00531                         Mat tmp;
00532                         ptr=readMatrix(ptr,tmp);
00533                         tmp.copyTo(mtx);
00534                 }               
00535                 else
00536                 {
00537                         ptr+=psize; //Skip the unknown object
00538                 }
00539         }
00540 
00541 
00542         return ptr;
00543 }
00544 
00545 
00546 
00547 
00548 

Generated on 18 Dec 2014 for libdt-OpenCV by  doxygen 1.6.1