Example #1
0
void buildMatrix(SpMatrix &M1, SpMatrix &M2, SpMatrix &FF, double sigma, double r, double lambda, double alpha, int N, double dx, double dt){
        
        double diff=sigma*sigma/2;
        double trasp=r-sigma*sigma/2-alpha;
        double reaz=-lambda;
       
        
        SpMatrix DD(N-1,N-1);
        SpMatrix DF(N-1,N-1);
        
        // Assemblaggio
        for (int i=0; i<N-1; ++i) {
                DD.insert(i,i)=2/dx;
                FF.insert(i,i)=2*dx/3;
        }
        for (int i=0; i<N-2; ++i) {
                DD.insert(i+1,i)=-1/dx;
                FF.insert(i+1,i)=dx/6;
                DF.insert(i+1,i)=-0.5;
        }
        for (int i=0; i<N-2; ++i) {
                DD.insert(i,i+1)=-1/dx;
                FF.insert(i,i+1)=dx/6;
                DF.insert(i,i+1)=0.5;
        }
        
        cout<<dt<<"\t"<<diff<<"\t"<<trasp<<"\t"<<reaz<<"\n";
        
        M1=FF/dt+0.5*(diff*DD-trasp*DF-reaz*FF);
        M2=FF/dt-0.5*(diff*DD-trasp*DF-reaz*FF);
        
        return;
}
Example #2
0
void gen_sparse_data(int n, SpMatrix& A, SpMatrix& B)
{
    // Eigen solver only uses the lower triangle of A,
    // so we don't need to make A symmetric here.
    A = sprand(n, 0.1);
    B = A.transpose() * A;
    // To make sure B is positive definite
    for(int i = 0; i < n; i++)
        B.coeffRef(i, i) += 0.1;
}
Example #3
0
void LoadSpMatrix(const char* filename, SpMatrix& m){
	
	int NbRow, NbCol;
	string      line;
	int        j0,k0;
	Cplx         val;
	
	// Ouverture fichier
	ifstream file; file.open(filename);
	if(!file.good()){
		cout << "LoadSpMatrix in loading.hpp: error opening the matrix file" << endl;
        cout << filename << endl;
		abort();}
	
	// Lecture nombre de lignes et de colonnes
	file >> NbRow; file >> NbCol;
	m.resize(NbRow,NbCol,NbRow*max(NbCol/10,10));

	// Lecture parametres
	int ndofperelt=GetNdofPerElt();
	
	int NbCoef=0;
	
	getline(file,line);
	getline(file,line);
	while(!file.eof()){
		
		// Lecture de la ligne
		istringstream iss(line);
		
		// Pour chaque ligne, stockage
		// du bloc d'interaction
		iss >> j0; j0 = ndofperelt*(j0-1);
		iss >> k0; k0 = ndofperelt*(k0-1);
		
		for(int j=0; j<ndofperelt; j++){
			for(int k=0; k<ndofperelt; k++){
				iss >> val;
				m.I_(NbCoef) = j0+j;
				m.J_(NbCoef) = k0+k;
				m.K_(NbCoef) = val;
				//m(j0+j,k0+k) = val;
				NbCoef++;
			}
		}
		getline(file,line);
	}
	
	file.close();
	
	m.resize(NbRow,NbCol,NbCoef);
}
Example #4
0
inline void callFunction(mxArray* plhs[], const mxArray*prhs[]) {
   if (!mexCheckType<T>(prhs[0])) 
      mexErrMsgTxt("type of argument 1 is not consistent");
   if (mxIsSparse(prhs[0])) 
      mexErrMsgTxt("argument 1 should be full");
   if (!mexCheckType<T>(prhs[1])) 
      mexErrMsgTxt("type of argument 2 is not consistent");
   if (mxIsSparse(prhs[1])) 
      mexErrMsgTxt("argument 2 should be full");
   if (!mexCheckType<bool>(prhs[2])) 
      mexErrMsgTxt("type of argument 3 should be boolean");
   if (mxIsSparse(prhs[2])) 
      mexErrMsgTxt("argument 3 should be full");
   if (!mxIsStruct(prhs[3])) 
      mexErrMsgTxt("argument 4 should be struct");

   T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
   const mwSize* dimsX=mxGetDimensions(prhs[0]);
   INTM n=static_cast<INTM>(dimsX[0]);
   INTM M=static_cast<INTM>(dimsX[1]);

   T* prD = reinterpret_cast<T*>(mxGetPr(prhs[1]));
   const mwSize* dimsD=mxGetDimensions(prhs[1]);
   INTM nD=static_cast<INTM>(dimsD[0]);
   INTM K=static_cast<INTM>(dimsD[1]);
   if (n != nD) mexErrMsgTxt("argument sizes are not consistent");

   bool* prmask = reinterpret_cast<bool*>(mxGetPr(prhs[2]));
   const mwSize* dimsM=mxGetDimensions(prhs[2]);
   INTM nM=static_cast<INTM>(dimsM[0]);
   INTM mM=static_cast<INTM>(dimsM[1]);
   if (nM != n || mM != M) mexErrMsgTxt("argument sizes are not consistent");

   T lambda = getScalarStruct<T>(prhs[3],"lambda");
   T lambda2 = getScalarStructDef<T>(prhs[3],"lambda2",0);
   int L = getScalarStructDef<int>(prhs[3],"L",K);
   int numThreads = getScalarStructDef<int>(prhs[3],"numThreads",-1);
   bool pos = getScalarStructDef<bool>(prhs[3],"pos",false);
   bool verbose = getScalarStructDef<bool>(prhs[3],"verbose",true);
   constraint_type mode = (constraint_type)getScalarStructDef<int>(prhs[3],"mode",PENALTY);
   if (L > n && !(mode == PENALTY && isZero(lambda) && !pos && lambda2 > 0)) {
      if (verbose)
         printf("L is changed to %d\n",(int)n);
      L=n;
   }
   if (L > K) {
      if (verbose)
         printf("L is changed to %d\n",(int)K);
      L=K;
   }
   Matrix<T> X(prX,n,M);
   Matrix<T> D(prD,n,K);
   Matrix<bool> mask(prmask,n,M);
   SpMatrix<T> alpha;

   lasso_mask<T>(X,D,alpha,mask,L,lambda,lambda2,mode,pos,numThreads);
   convertSpMatrix(plhs[0],alpha.m(),alpha.n(),alpha.n(),
         alpha.nzmax(),alpha.v(),alpha.r(),alpha.pB());
}
Example #5
0
Matrix mult(const SpMatrix &lhs, const SpMatrix &rhs, int row, int col) {
  Matrix res(row, Array(col, 0));
  for (auto& l:lhs) {
    for (auto& v:l.second){
      int i=l.first;
      int k=v.first;
      if (!rhs.count(k)) continue;
      for (auto& r:rhs.find(k)->second){
        int j=r.first;
        res[i][j] = res[i][j] + v.second * r.second;
      }
    }
  }
  return res;
}
inline void callFunction(mxArray* plhs[], const mxArray*prhs[]) {
    if (!mexCheckType<T>(prhs[0]))
        mexErrMsgTxt("type of argument 1 is not consistent");
    if (mxIsSparse(prhs[0]))
        mexErrMsgTxt("argument 1 should be full");
    if (!mexCheckType<T>(prhs[1]))
        mexErrMsgTxt("type of argument 2 is not consistent");
    if (mxIsSparse(prhs[1]))
        mexErrMsgTxt("argument 2 should be full");
    if (mxIsSparse(prhs[2]))
        mexErrMsgTxt("argument 3 should be full");
    if (!mxIsStruct(prhs[3]))
        mexErrMsgTxt("argument 4 should be struct");


    T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
    const mwSize* dimsX=mxGetDimensions(prhs[0]);
    long n=static_cast<long>(dimsX[0]);
    long M=static_cast<long>(dimsX[1]);

    T* prD = reinterpret_cast<T*>(mxGetPr(prhs[1]));
    const mwSize* dimsD=mxGetDimensions(prhs[1]);
    long nD=static_cast<long>(dimsD[0]);
    long K=static_cast<long>(dimsD[1]);
    if (n != nD) mexErrMsgTxt("argument sizes are not consistent");

    T lambda = getScalarStruct<T>(prhs[3],"lambda");
    long L = getScalarStructDef<long>(prhs[3],"L",K);
    long numThreads = getScalarStructDef<long>(prhs[3],"numThreads",-1);
    bool pos = getScalarStructDef<bool>(prhs[3],"pos",false);
    constraint_type mode = (constraint_type)getScalarStructDef<long>(prhs[3],"mode",PENALTY);
    if (L > n) {
        printf("L is changed to %ld\n",n);
        L=n;
    }
    if (L > K) {
        printf("L is changed to %ld\n",K);
        L=K;
    }
    Matrix<T> X(prX,n,M);
    Matrix<T> D(prD,n,K);


    T* prWeight = reinterpret_cast<T*>(mxGetPr(prhs[2]));
    const mwSize* dimsW=mxGetDimensions(prhs[2]);
    long KK=static_cast<long>(dimsW[0]);
    long MM=static_cast<long>(dimsW[1]);
    if (K != KK || M != MM) mexErrMsgTxt("argument sizes are not consistent");


    Matrix<T> weight(prWeight,KK,MM);

    SpMatrix<T> alpha;
    lassoWeight<T>(X,D,weight,alpha,L,lambda,mode,pos,numThreads);
    convertSpMatrix(plhs[0],alpha.m(),alpha.n(),alpha.n(),
                    alpha.nzmax(),alpha.v(),alpha.r(),alpha.pB());
}
Example #7
0
void EC2D2T3::BEBlocks(size_t            n1,
                       size_t            n2,
                       SpMatrix<real_t>& L,
                       SpMatrix<real_t>& U,
                       SpMatrix<real_t>& D)
{
   real_t aa = -0.5*_ll1;
   if (_ns==_nt) {
      U.add(2*_i1-1,2*_ns-1,aa);
      U.add(2*_i1  ,2*_ns  ,aa);
      U.add(2*_j1-1,2*_ns-1,aa);
      U.add(2*_j1  ,2*_ns  ,aa);
      L.add(2*_ns-1,2*_i1-1,aa);
      L.add(2*_ns  ,2*_i1  ,aa);
      L.add(2*_ns-1,2*_j1-1,aa);
      L.add(2*_ns  ,2*_j1  ,aa);
   }
   real_t d1, d2;
   _Dkl(_N1, _N2, _M1, _M2, d1);
   D.add(2*(_ns+n1)-1,2*(_nt+n2)-1,d1);
   D.add(2*(_ns+n1)  ,2*(_nt+n2)  ,d1);
   if (_ns != _nt) {
      _Lkl(_N1, _N2, _M1, _M2, d1, d2);
      L.add(2*_ns-1,2*_i2-1,d1);
      L.add(2*_ns  ,2*_i2  ,d1);
      L.add(2*_ns-1,2*_j2-1,d2);
      L.add(2*_ns  ,2*_j2  ,d2);
   }
}
Example #8
0
inline void callFunction(mxArray* plhs[], const mxArray*prhs[],const int nlhs) {
  if (!mxIsCell(prhs[0])) 
    mexErrMsgTxt("argument 2 should be a cell");
  std::vector<NodeElem *> *gstruct = mexMatlabToCgroups(prhs[0]);
  mwSize dims[1] = {1};
  const char *names[] = {"eta_g", "groups", "own_variables","N_own_variables"};
  plhs[1]=mxCreateStructArray(1,dims,4,names);
  SpMatrix<bool> *groups;
  Vector<int> *own_variables;
  Vector<int> *N_own_variables;
  Vector<double> *eta_g;
  int *permutations;
  int nb_perm;
  int nb_vars = _treeOfGroupStruct<double>(gstruct,&permutations,&nb_perm,&eta_g,&groups,&own_variables,&N_own_variables);
  del_gstruct(gstruct);
  mxArray* mxeta_g = makeVector<double>(eta_g);
  mxArray* mxown_variables = makeVector<int>(own_variables);
  mxArray* mxN_own_variables = makeVector<int>(N_own_variables);
  mxArray* mxgroups[1];
  convertSpMatrix<bool>(mxgroups[0],groups->m(),groups->n(),groups->n(),
			groups->nzmax(),groups->v(),groups->r(),groups->pB());
  delete eta_g;
  delete groups;
  delete own_variables;
  delete N_own_variables;
  mxSetField(plhs[1],0,"eta_g",mxeta_g);
  mxSetField(plhs[1],0,"groups",mxgroups[0]);
  mxSetField(plhs[1],0,"own_variables",mxown_variables);
  mxSetField(plhs[1],0,"N_own_variables",mxN_own_variables);
  dims[0] = nb_perm;
  mxArray *mxperm = mxCreateNumericArray((mwSize)1,dims,mxINT32_CLASS,mxREAL);
  if(nb_perm > 0)
    memcpy(mxGetPr(mxperm),permutations,nb_perm * sizeof(int));
  plhs[0] = mxperm;
  dims[0] = 1;
  plhs[2]=mxCreateNumericArray((mwSize)1,dims,mxINT32_CLASS,mxREAL);
  int* pr_out=reinterpret_cast<int *>(mxGetPr(plhs[2]));
  *pr_out = nb_vars;
}
Example #9
0
inline void callFunction(mxArray* plhs[], const mxArray*prhs[],const int nrhs,
      const int nlhs) {
   if (nrhs==3) {
      if (!mexCheckType<T>(prhs[0])) 
         mexErrMsgTxt("type of argument 1 is not consistent");
      if (mxIsSparse(prhs[0])) 
         mexErrMsgTxt("argument 1 should be full");
      if (!mexCheckType<T>(prhs[1])) 
         mexErrMsgTxt("type of argument 2 is not consistent");
      if (mxIsSparse(prhs[1])) 
         mexErrMsgTxt("argument 2 should be full");
      if (!mxIsStruct(prhs[2])) 
         mexErrMsgTxt("argument 3 should be struct");

      T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
      const mwSize* dimsX=mxGetDimensions(prhs[0]);
      int n=static_cast<int>(dimsX[0]);
      int M=static_cast<int>(dimsX[1]);

      T* prD = reinterpret_cast<T*>(mxGetPr(prhs[1]));
      const mwSize* dimsD=mxGetDimensions(prhs[1]);
      int nD=static_cast<int>(dimsD[0]);
      int K=static_cast<int>(dimsD[1]);
      if (n != nD) mexErrMsgTxt("argument sizes are not consistent");
      T lambda = getScalarStruct<T>(prhs[2],"lambda");
      T lambda2 = getScalarStructDef<T>(prhs[2],"lambda2",0);
      int L = getScalarStructDef<int>(prhs[2],"L",K);
      int length_path = MAX(2,getScalarStructDef<int>(prhs[2],"length_path",4*L));
      int numThreads = getScalarStructDef<int>(prhs[2],"numThreads",-1);
      bool pos = getScalarStructDef<bool>(prhs[2],"pos",false);
      //bool verbose = getScalarStructDef<bool>(prhs[2],"verbose",false);
      bool ols = getScalarStructDef<bool>(prhs[2],"ols",false);
      bool cholesky = ols || getScalarStructDef<bool>(prhs[2],"cholesky",false);
      constraint_type mode = (constraint_type)getScalarStructDef<int>(prhs[2],"mode",PENALTY);
      if (L > n && !(mode == PENALTY && isZero(lambda) && !pos && lambda2 > 0)) {
//         if (verbose)
//            printf("L is changed to %d\n",n);
         L=n;
      }
      if (L > K) {
//         if (verbose)
//            printf("L is changed to %d\n",K);
         L=K;
      }
      Matrix<T> X(prX,n,M);
      Matrix<T> D(prD,n,K);
      SpMatrix<T> alpha;

      if (nlhs == 2) {
         Matrix<T> norm(K,length_path);
         norm.setZeros();
         if (cholesky) {
            lasso<T>(X,D,alpha,L,lambda,lambda2,mode,pos,ols,numThreads,&norm,length_path);
         } else {
            lasso2<T>(X,D,alpha,L,lambda,lambda2,mode,pos,numThreads,&norm,length_path);
         }
         Vector<T> norms_col;
         norm.norm_2_cols(norms_col);
         int length=1;
         for (int i = 1; i<norms_col.n(); ++i)
            if (norms_col[i]) ++length;
         plhs[1]=createMatrix<T>(K,length);
         T* pr_norm=reinterpret_cast<T*>(mxGetPr(plhs[1]));
         Matrix<T> norm2(pr_norm,K,length);
         Vector<T> col;
         for (int i = 0; i<length; ++i) {
            norm2.refCol(i,col);
            norm.copyCol(i,col);
         }
      } else {
         if (cholesky) {
            lasso<T>(X,D,alpha,L,lambda,lambda2,mode,pos,ols,numThreads,NULL,length_path);
         } else {
            lasso2<T>(X,D,alpha,L,lambda,lambda2,mode,pos,numThreads,NULL,length_path);
         }
      }
      convertSpMatrix(plhs[0],alpha.m(),alpha.n(),alpha.n(),
            alpha.nzmax(),alpha.v(),alpha.r(),alpha.pB());
   } else {
      if (!mexCheckType<T>(prhs[0])) 
         mexErrMsgTxt("type of argument 1 is not consistent");
      if (mxIsSparse(prhs[0])) 
         mexErrMsgTxt("argument 1 should be full");
      if (!mexCheckType<T>(prhs[1])) 
         mexErrMsgTxt("type of argument 2 is not consistent");
      if (mxIsSparse(prhs[1])) 
         mexErrMsgTxt("argument 2 should be full");
      if (!mexCheckType<T>(prhs[2])) 
         mexErrMsgTxt("type of argument 3 is not consistent");
      if (mxIsSparse(prhs[2])) 
         mexErrMsgTxt("argument 3 should be full");
      if (!mxIsStruct(prhs[3])) 
         mexErrMsgTxt("argument 4 should be struct");

      T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
      const mwSize* dimsX=mxGetDimensions(prhs[0]);
      int n=static_cast<int>(dimsX[0]);
      int M=static_cast<int>(dimsX[1]);

      T* prG = reinterpret_cast<T*>(mxGetPr(prhs[1]));
      const mwSize* dimsD=mxGetDimensions(prhs[1]);
      int K1=static_cast<int>(dimsD[0]);
      int K2=static_cast<int>(dimsD[1]);
      if (K1 != K2) mexErrMsgTxt("argument sizes are not consistent");
      int K=K1;

      T* prDtR = reinterpret_cast<T*>(mxGetPr(prhs[2]));
      const mwSize* dimsDtR=mxGetDimensions(prhs[2]);
      int K3=static_cast<int>(dimsDtR[0]);
      int M2=static_cast<int>(dimsDtR[1]);
      if (K1 != K3) mexErrMsgTxt("argument sizes are not consistent");
      if (M != M2) mexErrMsgTxt("argument sizes are not consistent");

      T lambda = getScalarStruct<T>(prhs[3],"lambda");
      T lambda2 = getScalarStructDef<T>(prhs[3],"lambda2",0);
      int L = getScalarStructDef<int>(prhs[3],"L",K1);
      int length_path = getScalarStructDef<int>(prhs[3],"length_path",4*L);
      int numThreads = getScalarStructDef<int>(prhs[3],"numThreads",-1);
      bool pos = getScalarStructDef<bool>(prhs[3],"pos",false);
//      bool verbose = getScalarStructDef<bool>(prhs[3],"verbose",true);
      bool ols = getScalarStructDef<bool>(prhs[3],"ols",false);
      bool cholesky = ols || getScalarStructDef<bool>(prhs[3],"cholesky",false);
      constraint_type mode = (constraint_type)getScalarStructDef<int>(prhs[3],"mode",PENALTY);
      if (L > n && !(mode == PENALTY && isZero(lambda) && !pos && lambda2 > 0)) {
//         if (verbose)
//            printf("L is changed to %d\n",n);
         L=n;
      }
      if (L > K) {
//         if (verbose)
//            printf("L is changed to %d\n",K);
         L=K;
      }
      Matrix<T> X(prX,n,M);
      Matrix<T> G(prG,K,K);
      Matrix<T> DtR(prDtR,K,M);
      SpMatrix<T> alpha;

      if (nlhs == 2) {
         Matrix<T> norm(K,length_path);
         norm.setZeros();
         if (cholesky) {
            lasso<T>(X,G,DtR,alpha,L,lambda,mode,pos,ols,numThreads,&norm,length_path);
         } else {
            lasso2<T>(X,G,DtR,alpha,L,lambda,mode,pos,numThreads,&norm,length_path);
         }
         Vector<T> norms_col;
         norm.norm_2_cols(norms_col);
         int length=1;
         for (int i = 1; i<norms_col.n(); ++i)
            if (norms_col[i]) ++length;
         plhs[1]=createMatrix<T>(K,length);
         T* pr_norm=reinterpret_cast<T*>(mxGetPr(plhs[1]));
         Matrix<T> norm2(pr_norm,K,length);
         Vector<T> col;
         for (int i = 0; i<length; ++i) {
            norm2.refCol(i,col);
            norm.copyCol(i,col);
         }
      } else {
         if (cholesky) {
            lasso<T>(X,G,DtR,alpha,L,lambda,mode,pos,ols,numThreads,NULL,length_path);
         } else {
            lasso2<T>(X,G,DtR,alpha,L,lambda,mode,pos,numThreads,NULL,length_path);
         }
      }
      convertSpMatrix(plhs[0],alpha.m(),alpha.n(),alpha.n(),
            alpha.nzmax(),alpha.v(),alpha.r(),alpha.pB());
   }
}
inline void callFunction(mxArray* plhs[], const mxArray*prhs[],
      const int nlhs) {
   if (!mexCheckType<T>(prhs[0])) 
      mexErrMsgTxt("type of argument 1 is not consistent");
   if (mxIsSparse(prhs[0])) 
      mexErrMsgTxt("argument 1 should not be sparse");

   if (!mxIsStruct(prhs[1])) 
      mexErrMsgTxt("argument 2 should be struct");
   if (!mxIsStruct(prhs[2])) 
      mexErrMsgTxt("argument 3 should be struct");

   T* pr_alpha0 = reinterpret_cast<T*>(mxGetPr(prhs[0]));
   const mwSize* dimsAlpha=mxGetDimensions(prhs[0]);
   int pAlpha=static_cast<int>(dimsAlpha[0]);
   int nAlpha=static_cast<int>(dimsAlpha[1]);
   Matrix<T> alpha0(pr_alpha0,pAlpha,nAlpha);

   mxArray* ppr_GG = mxGetField(prhs[1],0,"weights");
   if (!mxIsSparse(ppr_GG)) 
      mexErrMsgTxt("field groups should be sparse");
   T* graph_weights = reinterpret_cast<T*>(mxGetPr(ppr_GG));
   mwSize* GG_r=mxGetIr(ppr_GG);
   mwSize* GG_pB=mxGetJc(ppr_GG);
   const mwSize* dims_GG=mxGetDimensions(ppr_GG);
   int GGm=static_cast<int>(dims_GG[0]);
   int GGn=static_cast<int>(dims_GG[1]);
   if (GGm != GGn || GGm != pAlpha)
      mexErrMsgTxt("size of field groups is not consistent");

   mxArray* ppr_weights = mxGetField(prhs[1],0,"start_weights");
   if (mxIsSparse(ppr_weights)) 
      mexErrMsgTxt("field start_weights should not be sparse");
   T* start_weights = reinterpret_cast<T*>(mxGetPr(ppr_weights));
   const mwSize* dims_weights=mxGetDimensions(ppr_weights);
   int nweights=static_cast<int>(dims_weights[0])*static_cast<int>(dims_weights[1]);
   if (nweights != pAlpha)
      mexErrMsgTxt("size of field start_weights is not consistent");

   mxArray* ppr_weights2 = mxGetField(prhs[1],0,"stop_weights");
   if (mxIsSparse(ppr_weights2)) 
      mexErrMsgTxt("field stop_weights should not be sparse");
   T* stop_weights = reinterpret_cast<T*>(mxGetPr(ppr_weights2));
   const mwSize* dims_weights2=mxGetDimensions(ppr_weights2);
   int nweights2=static_cast<int>(dims_weights2[0])*static_cast<int>(dims_weights2[1]);
   if (nweights2 != pAlpha)
      mexErrMsgTxt("size of field stop_weights is not consistent");


   FISTA::ParamFISTA<T> param;
   param.num_threads = getScalarStructDef<int>(prhs[2],"numThreads",-1);
   getStringStruct(prhs[2],"regul",param.name_regul,param.length_names);
   param.regul = regul_from_string(param.name_regul);
   if (param.regul==INCORRECT_REG)
      mexErrMsgTxt("Unknown regularization");
   param.intercept = getScalarStructDef<bool>(prhs[2],"intercept",false);
   param.verbose = getScalarStructDef<bool>(prhs[2],"verbose",false);
   param.eval_dual_norm = getScalarStructDef<bool>(prhs[2],"dual_norm",false);

   if (param.regul != GRAPH_PATH_L0 && param.regul != GRAPH_PATH_CONV)
      mexErrMsgTxt("Use a different mexEvalGraphPath function");

   if (param.num_threads == -1) {
      param.num_threads=1;
#ifdef _OPENMP
      param.num_threads =  MIN(MAX_THREADS,omp_get_num_procs());
#endif
   }
   
   GraphPathStruct<T> graph;
   graph.n=pAlpha;
   graph.m=GG_pB[graph.n]-GG_pB[0];
   graph.weights=graph_weights;
   graph.start_weights=start_weights;
   graph.stop_weights=stop_weights;
   graph.ir=GG_r;
   graph.jc=GG_pB;
   graph.precision = getScalarStructDef<long long>(prhs[2],"precision",100000000000000000);

   Vector<T> val;
   SpMatrix<T> path;
   if (nlhs==1) {
      FISTA::EvalGraphPath<T>(alpha0,param,val,&graph);
   } else {
      FISTA::EvalGraphPath<T>(alpha0,param,val,&graph,&path);
   }

   plhs[0]=createMatrix<T>(1,val.n());
   T* pr_val=reinterpret_cast<T*>(mxGetPr(plhs[0]));
   for (int i = 0; i<val.n(); ++i) pr_val[i]=val[i];

   if (nlhs==2)
      convertSpMatrix(plhs[1],path.m(),path.n(),path.n(),
            path.nzmax(),path.v(),path.r(),path.pB());
}
Example #11
0
void large_cg_test(uint i){
  message("Blocksize = %d", N);
  char filename[255];

  sprintf(filename, "%s", matrixFiles[(uint)i].c_str());

  SpMatrix<N, T>* mat = 0;

  /*Load a matrix from file*/
  mat = load_matrix_market_exchange<N, T>(filename);
  if(mat == 0){
    warning("Failed loading %s", filename);
    return;
  }

  if(mat){
    Vector<T> vec(mat->getWidth());
    for(int j=0;j<mat->getWidth();j++){
      if(j%2==0)
	vec[j] = 1;
      else
	vec[j] = 1;
    }

    mat->finalize();

    LinSolve<N, T>* solver = 0; 

    /*Enable the tests you like to perform.*/
#if 1
    message("Single non-threaded test");
    solver = new LinSolveCG<N, T>(mat->getWidth());
    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();

    delete solver;
#endif
#if 1
    message("Single threaded test");
    solver = new LinSolveCGParallel<N, T>(mat->getWidth(), 1);
    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif
#if 1
    message("Dual threaded test");
    solver = new LinSolveCGParallel<N, T>(mat->getWidth(), 2);
    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif
#if 1    
    message("Quad threaded test");

    solver = new LinSolveCGParallel<N, T>(mat->getWidth(), 4);
    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif
#if 1
    message("Oct threaded test");

    solver = new LinSolveCGParallel<N, T>(mat->getWidth(), 8);
    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif
#if 1
    message("16 threaded test");

    solver = new LinSolveCGParallel<N, T>(mat->getWidth(), 16);
    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif
#if 1
    message("32 threaded test");

    solver = new LinSolveCGParallel<N, T>(mat->getWidth(), 32);
    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif


#ifdef CUDA
#if 1
    message("Single cuda test");
    solver = new LinSolveCGGPU<N, T>(mat->getWidth(), 1);

    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif
#if 0
    message("Dual cuda test");
    solver = new LinSolveCGGPU<N, T>(mat->getWidth(), 2);

    solver->setMatrix(mat);
    solver->setb(&vec);
    solver->preSolve();
    solver->solve();
    
    delete solver;
#endif
#endif
    
    delete mat;
  }else{
    warning("File %s not found. Test skipped.", filename);
  }
}
Example #12
0
   inline void callFunction(mxArray* plhs[], const mxArray*prhs[], 
         const long nlhs) {
      if (!mexCheckType<T>(prhs[0])) 
         mexErrMsgTxt("type of argument 1 is not consistent");
      if (mxIsSparse(prhs[0])) 
         mexErrMsgTxt("argument 1 should be full");
      if (!mexCheckType<T>(prhs[1])) 
         mexErrMsgTxt("type of argument 2 is not consistent");
      if (mxIsSparse(prhs[1])) 
         mexErrMsgTxt("argument 2 should be full");
      if (!mexCheckType<bool>(prhs[2])) 
         mexErrMsgTxt("type of argument 3 should be boolean");
      if (mxIsSparse(prhs[2])) 
         mexErrMsgTxt("argument 3 should be full");

      if (!mxIsStruct(prhs[3])) 
         mexErrMsgTxt("argument 4 should be struct");
      
      T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
      const mwSize* dimsX=mxGetDimensions(prhs[0]);
      long n=static_cast<long>(dimsX[0]);
      long M=static_cast<long>(dimsX[1]);

      T* prD = reinterpret_cast<T*>(mxGetPr(prhs[1]));
      const mwSize* dimsD=mxGetDimensions(prhs[1]);
      long nD=static_cast<long>(dimsD[0]);
      long K=static_cast<long>(dimsD[1]);
      if (n != nD) mexErrMsgTxt("argument sizes are not consistent");

      bool* prmask = reinterpret_cast<bool*>(mxGetPr(prhs[2]));
      const mwSize* dimsM=mxGetDimensions(prhs[2]);
      long nM=static_cast<long>(dimsM[0]);
      long mM=static_cast<long>(dimsM[1]);
      if (nM != n || mM != M) mexErrMsgTxt("argument sizes are not consistent");

      Matrix<T> X(prX,n,M);
      Matrix<bool> mask(prmask,n,M);
      Matrix<T> D(prD,n,K);
      SpMatrix<T> alpha;

      long numThreads = getScalarStructDef<long>(prhs[3],"numThreads",-1);
      mxArray* pr_L=mxGetField(prhs[3],0,"L");
      mxArray* pr_eps=mxGetField(prhs[3],0,"eps");
      mxArray* pr_lambda=mxGetField(prhs[3],0,"lambda");
      if (!pr_L && !pr_eps && !pr_lambda) mexErrMsgTxt("You should either provide L, eps or lambda");
      
      long sizeL = 1;
      long L=MIN(n,K);
      long *pL = &L;
      if (pr_L) {
         const mwSize* dimsL= mxGetDimensions(pr_L);
         sizeL=static_cast<long>(dimsL[0])*static_cast<long>(dimsL[1]);
         if (sizeL > 1) {
            if (!mexCheckType<long>(pr_L)) 
               mexErrMsgTxt("Type of param.L should be int32");
            pL = reinterpret_cast<long*>(mxGetPr(pr_L));
         }
         L=MIN(L,static_cast<long>(mxGetScalar(pr_L)));
      }

      long sizeE=1;
      T eps=0;
      T* pE=&eps;
      if (pr_eps) {
         const mwSize* dimsE=mxGetDimensions(pr_eps);
         sizeE=static_cast<long>(dimsE[0])*static_cast<long>(dimsE[1]);
         eps=static_cast<T>(mxGetScalar(pr_eps));
         if (sizeE > 1)
            pE = reinterpret_cast<T*>(mxGetPr(pr_eps));
      }

      T lambda=0;
      long sizeLambda=1;
      T* pLambda=&lambda;
      if (pr_lambda) {
         const mwSize* dimsLambda=mxGetDimensions(pr_lambda);
         sizeLambda=static_cast<long>(dimsLambda[0])*static_cast<long>(dimsLambda[1]);
         lambda=static_cast<T>(mxGetScalar(pr_lambda));
         if (sizeLambda > 1)
            pLambda = reinterpret_cast<T*>(mxGetPr(pr_lambda));
      }

      Matrix<T>* prPath=NULL;
      if (nlhs == 2) {
         plhs[1]=createMatrix<T>(K,L);
         T* pr_path=reinterpret_cast<T*>(mxGetPr(plhs[1]));
         Matrix<T> path(pr_path,K,L);
         path.setZeros();
         prPath=&path;
      }
      omp_mask<T>(X,D,alpha,mask,pL,pE,pLambda,sizeL > 1,sizeE > 1,sizeLambda > 1,
            numThreads,prPath);
      convertSpMatrix(plhs[0],K,M,alpha.n(),alpha.nzmax(),alpha.v(),alpha.r(),
            alpha.pB());
   }
Example #13
0
   inline void callFunction(mxArray* plhs[], const mxArray*prhs[], 
         const int nlhs) {
      if (!mexCheckType<T>(prhs[0])) 
         mexErrMsgTxt("type of argument 1 is not consistent");
      if (mxIsSparse(prhs[0])) 
         mexErrMsgTxt("argument 1 should be full");
      if (!mexCheckType<T>(prhs[1])) 
         mexErrMsgTxt("type of argument 2 is not consistent");
      if (mxIsSparse(prhs[1])) 
         mexErrMsgTxt("argument 2 should be full");
      if (!mexCheckType<bool>(prhs[2])) 
         mexErrMsgTxt("type of argument 3 should be boolean");
      if (mxIsSparse(prhs[2])) 
         mexErrMsgTxt("argument 3 should be full");

      if (!mxIsStruct(prhs[3])) 
         mexErrMsgTxt("argument 3 should be struct");

      T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
      const mwSize* dimsX=mxGetDimensions(prhs[0]);
      int n=static_cast<int>(dimsX[0]);
      int M=static_cast<int>(dimsX[1]);

      T* prD = reinterpret_cast<T*>(mxGetPr(prhs[1]));
      const mwSize* dimsD=mxGetDimensions(prhs[1]);
      int nD=static_cast<int>(dimsD[0]);
      int K=static_cast<int>(dimsD[1]);
      if (n != nD) mexErrMsgTxt("argument sizes are not consistent");

      bool* prmask = reinterpret_cast<bool*>(mxGetPr(prhs[2]));
      const mwSize* dimsM=mxGetDimensions(prhs[2]);
      int nM=static_cast<int>(dimsM[0]);
      int mM=static_cast<int>(dimsM[1]);
      if (nM != n || mM != M) mexErrMsgTxt("argument sizes are not consistent");


      Matrix<T> X(prX,n,M);
      Matrix<T> D(prD,n,K);
      SpMatrix<T> alpha;

      mxArray* pr_L=mxGetField(prhs[3],0,"L");
      if (!pr_L) mexErrMsgTxt("Missing field L in param");
      const mwSize* dimsL=mxGetDimensions(pr_L);
      int sizeL=static_cast<int>(dimsL[0])*static_cast<int>(dimsL[1]);

      mxArray* pr_eps=mxGetField(prhs[3],0,"eps");
      if (!pr_eps) mexErrMsgTxt("Missing field eps in param");
      const mwSize* dimsE=mxGetDimensions(pr_eps);
      int sizeE=static_cast<int>(dimsE[0])*static_cast<int>(dimsE[1]);
      int numThreads = getScalarStructDef<int>(prhs[3],"numThreads",-1);
      Matrix<bool> mask(prmask,n,M);

      if (nlhs == 2) {
         int L=MIN(n,MIN(static_cast<int>(mxGetScalar(pr_L)),K));
         plhs[1]=createMatrix<T>(K,L);
         T* pr_path=reinterpret_cast<T*>(mxGetPr(plhs[1]));
         Matrix<T> path(pr_path,K,L);
         path.setZeros();
         T eps=static_cast<T>(mxGetScalar(pr_eps));
         omp_mask<T>(X,D,alpha,mask,L,eps,numThreads,path);
      } else {

         if (sizeL == 1) {
            int L=static_cast<int>(mxGetScalar(pr_L));
            if (sizeE == 1) {
               T eps=static_cast<T>(mxGetScalar(pr_eps));
               omp_mask<T>(X,D,alpha,mask,L,eps,numThreads);
            } else {
               T* pE = reinterpret_cast<T*>(mxGetPr(pr_eps));
               omp_mask<T>(X,D,alpha,mask,L,pE,numThreads);
            }
         } else {
            if (!mexCheckType<int>(pr_L)) 
               mexErrMsgTxt("Type of param.L should be int32");
            int* pL = reinterpret_cast<int*>(mxGetPr(pr_L));
            if (sizeE == 1) {
               T eps=static_cast<T>(mxGetScalar(pr_eps));
               omp_mask<T>(X,D,alpha,mask,pL,eps,numThreads);
            } else {
               T* pE = reinterpret_cast<T*>(mxGetPr(pr_eps));
               omp_mask<T>(X,D,alpha,mask,pL,pE,numThreads,true,true);
            }
         }
      }

      convertSpMatrix(plhs[0],K,M,alpha.n(),alpha.nzmax(),alpha.v(),alpha.r(),
            alpha.pB());
   }
Example #14
0
void
L1Graph::L1Minimization(SpMatrix<float>& alpha,std::vector<int>& neighborhood)
{
    //neighborhood contains cidx
    int p_num=index_->size();
    int f_dim=(*features_)[0].size();
    Matrix<float> X(f_dim, p_num - 1);

    //construct matrix X
    std::map<int,int> map_gl; //map between global and local point index
    for(int j = 0, k = 0; j < p_num; j++) { //cols
        int id=(*index_)[j];
        if(id==cidx_) {
            continue;
        }
        Util::StdVector2MatrixCol((*features_)[id], X, k);
        map_gl.insert(make_pair<int,int>(k,id));
        ++k;
    }

    //TODO:dont use I
    //construct I
    // Matrix<float> I(f_dim,f_dim);
    // I.eye();
    // Util::Matrix2File(I,"I.txt");
    // Matrix<float> B(f_dim, f_dim + p_num - 1);
    // X.merge(I, B);
    // Util::Matrix2File(B,"B.txt");
    //clean
    // X.clear();
    // I.clear();
    //using lasso
    Matrix<float> x; //x=Ba
    Util::StdVector2Matrix((*features_)[cidx_], x);
    float lambda = 0.01; //lambda
    int L = (*features_)[0].size(); //max non-zero number
    // int L = 20; //max non-zero number
    SpMatrix<float> all;

    //TODO:debug in matlab
    ofstream fout("f.txt");
    for (int i = 0; i < x.m(); i++) {
        for (int j = 0; j < x.n(); j++) {
            fout<<x(i,j)<<" "; 
        }
        fout<<std::endl;
    }
    fout.close();
    ofstream dout("d.txt");
    for (int i = 0; i < X.m(); i++) {
        for (int j = 0; j < X.n(); j++) {
            dout<<X(i,j)<<" "; 
        }
        dout<<std::endl;
    }
    dout.close();


    lasso2<float>(x, X, all, L, lambda , 0 , PENALTY , true); //TODO:X->B

    Util::SubSpMatrix(all,alpha,p_num-1);
    // all.print("all");
    // alpha.print("alpha");
    // getchar();


    Matrix<float> tmp;
    X.mult(alpha,tmp);
    x.add(tmp,-1);
    std::cout<<(0.5*x.normFsq())<<" "<<(lambda*alpha.asum())<<" "<<(0.5*x.normFsq())/(lambda*alpha.asum())<<std::endl;


    //save for vis
    std::vector<int> mk;
    std::vector<float> mv;

    for(int ii = 0; ii < alpha.n(); ++ii) {
        //TODO:calls for pB and pE are not consist
        for(int j = alpha.pB(ii); j < alpha.pE()[ii]; ++j) {
            //<i,j>->all.v(j)
            mk.push_back(map_gl[j]);
            mv.push_back(alpha.v(j));
            neighborhood.push_back(map_gl[j]);
        }
    }

    std::string namev = "debug/" + boost::lexical_cast<std::string>(cidx_) + ".xyznq";
    ofstream ov(namev.c_str());

    for(int ii = 0; ii < cloud_->size(); ++ii) {
        if(ii == cidx_) {
            ov << cloud_->points[ii].x << " " << cloud_->points[ii].y << " " << cloud_->points[ii].z << " 0 0 0 1" << std::endl;
        } else {
            std::vector<int>::iterator it = find(mk.begin(), mk.end(), ii);
            if(it != mk.end()) {
                int dis = std::distance(mk.begin(), it);
                ov << cloud_->points[ii].x << " " << cloud_->points[ii].y << " " << cloud_->points[ii].z << " 0 0 0 " << mv[dis] << std::endl;
                // ov << cloud_->points[ii].x <<" " << cloud_->points[ii].y << " " << cloud_->points[ii].z << " 0 0 0 0" << std::endl;
            } else {
                ov << cloud_->points[ii].x << " " << cloud_->points[ii].y << " " << cloud_->points[ii].z << " 0 0 0 -1" << std::endl;
            }
        }
    }

    ov.close();
    return ;
}       /* -----  end of method L1Graph::L1Minimization  ----- */