/* ************************************************************ PROCEDURE mexFunction - Entry for Matlab y = fwblksolve(L,b, [y]) y = L.L \ b(L.perm) ************************************************************ */ void mexFunction(const int nlhs, mxArray *plhs[], const int nrhs, const mxArray *prhs[]) { const mxArray *L_FIELD; mwIndex m,n, j, k, nsuper, inz; double *y,*fwork; const double *permPr, *b, *xsuperPr; const mwIndex *yjc, *yir, *bjc, *bir; mwIndex *perm, *invperm, *snode, *xsuper, *iwork; jcir L; char bissparse; /* ------------------------------------------------------------ Check for proper number of arguments ------------------------------------------------------------ */ mxAssert(nrhs >= MINNPARIN, "fwblkslv requires more input arguments."); mxAssert(nlhs <= NPAROUT, "fwblkslv generates only 1 output argument."); /* ------------------------------------------------------------ Disassemble block Cholesky structure L ------------------------------------------------------------ */ mxAssert(mxIsStruct(L_IN), "Parameter `L' should be a structure."); if( (L_FIELD = mxGetField(L_IN,(mwIndex)0,"perm")) == NULL) /* L.perm */ mexErrMsgTxt("Missing field L.perm."); m = mxGetM(L_FIELD) * mxGetN(L_FIELD); permPr = mxGetPr(L_FIELD); if( (L_FIELD = mxGetField(L_IN,(mwIndex)0,"L")) == NULL) /* L.L */ mexErrMsgTxt("Missing field L.L."); if( m != mxGetM(L_FIELD) || m != mxGetN(L_FIELD) ) mexErrMsgTxt("Size L.L mismatch."); if(!mxIsSparse(L_FIELD)) mexErrMsgTxt("L.L should be sparse."); L.jc = mxGetJc(L_FIELD); L.ir = mxGetIr(L_FIELD); L.pr = mxGetPr(L_FIELD); if( (L_FIELD = mxGetField(L_IN,(mwIndex)0,"xsuper")) == NULL) /* L.xsuper */ mexErrMsgTxt("Missing field L.xsuper."); nsuper = mxGetM(L_FIELD) * mxGetN(L_FIELD) - 1; if( nsuper > m ) mexErrMsgTxt("Size L.xsuper mismatch."); xsuperPr = mxGetPr(L_FIELD); /* ------------------------------------------------------------ Get rhs matrix b. If it is sparse, then we also need the sparsity structure of y. ------------------------------------------------------------ */ b = mxGetPr(B_IN); if( mxGetM(B_IN) != m ) mexErrMsgTxt("Size mismatch b."); n = mxGetN(B_IN); if( (bissparse = mxIsSparse(B_IN)) ){ bjc = mxGetJc(B_IN); bir = mxGetIr(B_IN); if(nrhs < NPARIN) mexErrMsgTxt("fwblkslv requires more inputs in case of sparse b."); if(mxGetM(Y_IN) != m || mxGetN(Y_IN) != n) mexErrMsgTxt("Size mismatch y."); if(!mxIsSparse(Y_IN)) mexErrMsgTxt("y should be sparse."); } /* ------------------------------------------------------------ Allocate output y. If bissparse, then Y_IN gives the sparsity structure. ------------------------------------------------------------ */ if(!bissparse) Y_OUT = mxCreateDoubleMatrix(m, n, mxREAL); else{ yjc = mxGetJc(Y_IN); yir = mxGetIr(Y_IN); Y_OUT = mxCreateSparse(m,n, yjc[n],mxREAL); memcpy(mxGetJc(Y_OUT), yjc, (n+1) * sizeof(mwIndex)); memcpy(mxGetIr(Y_OUT), yir, yjc[n] * sizeof(mwIndex)); } y = mxGetPr(Y_OUT); /* ------------------------------------------------------------ Allocate working arrays fwork(m) and iwork(2*m + nsuper+1) ------------------------------------------------------------ */ fwork = (double *) mxCalloc(m, sizeof(double)); iwork = (mwIndex *) mxCalloc(2*m+nsuper+1, sizeof(mwIndex)); perm = iwork; invperm = perm; xsuper = iwork + m; snode = xsuper + (nsuper+1); /* ------------------------------------------------------------ Convert real to integer array, and from Fortran to C style. In case of sparse b, we store the inverse perm, instead of perm itself. ------------------------------------------------------------ */ for(k = 0; k <= nsuper; k++) xsuper[k] = xsuperPr[k] - 1; if(!bissparse) for(k = 0; k < m; k++) /* Get perm if !bissparse */ perm[k] = permPr[k] - 1; else{ for(k = 0; k < m; k++){ /* Get invperm if bissparse */ j = permPr[k]; invperm[--j] = k; } /* ------------------------------------------------------------ In case of sparse b, we also create snode, which maps each subnode to the supernode containing it. ------------------------------------------------------------ */ for(j = 0, k = 0; k < nsuper; k++) while(j < xsuper[k+1]) snode[j++] = k; } /* ------------------------------------------------------------ The actual job is done here: y = L\b(perm). ------------------------------------------------------------ */ if(!bissparse) for(j = 0; j < n; j++){ for(k = 0; k < m; k++) /* y = b(perm) */ y[k] = b[perm[k]]; fwsolve(y,L.jc,L.ir,L.pr,xsuper,nsuper,fwork); y += m; b += m; } else for(j = 0, inz = 0; j < n; j++){ for(k = inz; k < yjc[j+1]; k++) /* fwork = all-0 */ fwork[yir[k]] = 0.0; for(k = bjc[j]; k < bjc[j+1]; k++) /* fwork = b(perm) */ fwork[invperm[bir[k]]] = b[k]; selfwsolve(fwork,L.jc,L.ir,L.pr,xsuper,nsuper, snode, yir+inz,yjc[j+1]-inz); for(; inz < yjc[j+1]; inz++) y[inz] = fwork[yir[inz]]; } /* ------------------------------------------------------------ RELEASE WORKING ARRAYS. ------------------------------------------------------------ */ mxFree(iwork); mxFree(fwork); }
static float update_one (const mxArray* hashxtic, const mxArray* oas, const mxArray* filtmat, const mxArray* momentum, mwIndex node, mwIndex example, float* mybias, float* mymombias, const mxArray* ytic, const mxArray* C, float eta, float alpha, mwIndex nexamples) { const mwIndex* fmir = mxGetIr (filtmat); const mwIndex* fmjc = mxGetJc (filtmat); const mwIndex* hashxir = mxGetIr (hashxtic); const mwIndex* hashxjc = mxGetJc (hashxtic); const double* hashxs = mxGetPr (hashxtic); mwSize nfeatures = mxGetM (oas); mwSize ncandidates = mxGetN (oas); float* oasptr = (float*) mxGetPr (oas); float* momptr = (float*) mxGetPr (momentum); const mwIndex* yir = mxGetIr (ytic); const mwIndex* yjc = mxGetJc (ytic); const double* ys = mxGetPr (ytic); const float* Cptr = (const float *) mxGetPr (C); float max = -FLT_MAX; // ... compute predictions ... // mwIndex candidates = fmjc[node+1]-fmjc[node]; float* preds = (float*) alloca (candidates * sizeof (float)); memset (preds, 0, candidates * sizeof (float)); for (mwIndex fmk = fmjc[node]; fmk < fmjc[node+1]; ++fmk) { mwIndex candidate = fmir[fmk]; mwIndex c = fmk - fmjc[node]; const float* oascandidate = oasptr + (nfeatures * candidate); for (mwIndex hk = hashxjc[example]; hk < hashxjc[example+1]; ++hk) { mwIndex feature = hashxir[hk]; preds[c] += oascandidate[feature] * hashxs[hk]; } preds[c] += mybias[c]; if (preds[c] > max) { max = preds[c]; } } if (softmax) { float sumpreds = 0; for (mwIndex c = 0; c < candidates; ++c) { preds[c] = exp (preds[c] - max); sumpreds += preds[c]; } for (mwIndex c = 0; c < candidates; ++c) { preds[c] = preds[c] / sumpreds; } } else { for (mwIndex c = 0; c < candidates; ++c) { if (preds[c] > 0) { preds[c] = 1.0 / (1.0 + exp (-preds[c])); } else { float exppred = exp (preds[c]); preds[c] = exppred / (1.0 + exppred); } } } // ... subtract true labels ... // for (mwIndex fmk = fmjc[node], yk = yjc[example]; fmk < fmjc[node+1] && yk < yjc[example+1]; ) { mwIndex candidate = fmir[fmk]; mwIndex truecandidate = yir[yk]; if (candidate == truecandidate) { mwIndex c = fmk - fmjc[node]; preds[c] -= ys[yk]; ++fmk; ++yk; } else if (candidate < truecandidate) { ++fmk; } else { ++yk; } } // ... compute norm gradient ... // float norm_delta = 0; for (mwIndex c = 0; c < candidates; ++c) { norm_delta += preds[c] * preds[c]; } // ... update model ... // for (mwIndex fmk = fmjc[node]; fmk < fmjc[node+1]; ++fmk) { mwIndex candidate = fmir[fmk]; mwIndex c = fmk - fmjc[node]; float* momcandidate = momptr + (nfeatures * candidate); float* oascandidate = oasptr + (nfeatures * candidate); for (mwIndex hk = hashxjc[example]; hk < hashxjc[example+1]; ++hk) { mwIndex feature = hashxir[hk]; float g = hashxs[hk] * preds[c] / Cptr[feature]; momcandidate[feature] = alpha * momcandidate[feature] - eta * g; oascandidate[feature] += momcandidate[feature]; } mymombias[c] = alpha * mymombias[c] - (eta / nexamples) * preds[c]; mybias[c] += mymombias[c]; } return norm_delta; }
mxArray *sfmult_AN_XN_YT // y = (A*x)' ( const mxArray *A, const mxArray *X, int ac, // if true: conj(A) if false: A. ignored if A real int xc, // if true: conj(x) if false: x. ignored if x real int yc // if true: conj(y) if false: y. ignored if y real ) { mxArray *Y ; double *Ax, *Az, *Xx, *Xz, *Yx, *Yz, *Wx, *Wz ; Int *Ap, *Ai ; Int m, n, k, k1, i ; int Acomplex, Xcomplex, Ycomplex ; //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- m = mxGetM (A) ; n = mxGetN (A) ; k = mxGetN (X) ; if (n != mxGetM (X)) sfmult_invalid ( ) ; Acomplex = mxIsComplex (A) ; Xcomplex = mxIsComplex (X) ; Ap = mxGetJc (A) ; Ai = mxGetIr (A) ; Ax = mxGetPr (A) ; Az = mxGetPi (A) ; Xx = mxGetPr (X) ; Xz = mxGetPi (X) ; //-------------------------------------------------------------------------- // allocate result //-------------------------------------------------------------------------- Ycomplex = Acomplex || Xcomplex ; Y = sfmult_yalloc (k, m, Ycomplex) ; Yx = mxGetPr (Y) ; Yz = mxGetPi (Y) ; //-------------------------------------------------------------------------- // special cases //-------------------------------------------------------------------------- if (k == 0 || m == 0 || n == 0 || Ap [n] == 0) { // Y = 0 return (sfmult_yzero (Y)) ; } if (k == 1) { // Y = A*X sfmult_AN_x_1 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ; return (Y) ; } if (k == 2) { // Y = (A * X)' sfmult_AN_XN_YT_2 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ; return (Y) ; } if (k == 4) { // Y = (A * X)' sfmult_AN_XN_YT_4 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ; return (Y) ; } //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- sfmult_walloc (4, m, &Wx, &Wz) ; //-------------------------------------------------------------------------- // Y = (A*X)', in blocks of up to 4 columns of X, using sfmult_anxnyt //-------------------------------------------------------------------------- k1 = k % 4 ; if (k1 == 1) { // W = A * X(:,1) sfmult_AN_x_1 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ; // Y (1,:) = W for (i = 0 ; i < m ; i++) { Yx [k*i] = Wx [i] ; } Yx += 1 ; Yz += 1 ; Xx += n ; Xz += n ; } else if (k1 == 2) { // W = (A * X(:,1:2))' sfmult_AN_XN_YT_2 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ; // Y (1:2,:) = W for (i = 0 ; i < m ; i++) { Yx [k*i ] = Wx [2*i ] ; Yx [k*i+1] = Wx [2*i+1] ; } Yx += 2 ; Yz += 2 ; Xx += 2*n ; Xz += 2*n ; } else if (k1 == 3) { // W = (A * X(:,1:3))' sfmult_AN_XN_YT_3 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ; // Y (1:3,:) = W for (i = 0 ; i < m ; i++) { Yx [k*i ] = Wx [4*i ] ; Yx [k*i+1] = Wx [4*i+1] ; Yx [k*i+2] = Wx [4*i+2] ; } Yx += 3 ; Yz += 3 ; Xx += 3*n ; Xz += 3*n ; } for ( ; k1 < k ; k1 += 4) { // W = (A*X(:,1:4))' sfmult_AN_XN_YT_4 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ; // Y (k1+(1:4),:) = W for (i = 0 ; i < m ; i++) { Yx [k*i ] = Wx [4*i ] ; Yx [k*i+1] = Wx [4*i+1] ; Yx [k*i+2] = Wx [4*i+2] ; Yx [k*i+3] = Wx [4*i+3] ; } Yx += 4 ; Yz += 4 ; Xx += 4*n ; Xz += 4*n ; } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- mxFree (Wx) ; return (Y) ; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *srwd, *srad, *MUZIN, *MUXIN, *theta, *phi, *thetad, *muz, *mux; double ALPHA,BETA; int W, J, D, A, MA = 0, NN, SEED, OUTPUT, nzmaxwd, nzmaxad, i, j, a, startcond; mwIndex *irwd, *jcwd, *irad, *jcad; /* Check for proper number of arguments. */ if (nrhs < 8) { mexErrMsgTxt("At least 8 input arguments required"); } else if (nlhs < 1) { mexErrMsgTxt("At least 1 output arguments required"); } startcond = 0; if (nrhs > 8) startcond = 1; /* dealing with sparse array WD */ if (mxIsDouble(prhs[0]) != 1) mexErrMsgTxt("WD must be a double precision matrix"); srwd = mxGetPr(prhs[0]); irwd = mxGetIr(prhs[0]); jcwd = mxGetJc(prhs[0]); nzmaxwd = (int) mxGetNzmax(prhs[0]); W = (int) mxGetM(prhs[0]); D = (int) mxGetN(prhs[0]); /* dealing with sparse array AD */ if (mxIsDouble(prhs[1]) != 1) mexErrMsgTxt("AD must be a double precision matrix"); srad = mxGetPr(prhs[1]); irad = mxGetIr(prhs[1]); jcad = mxGetJc(prhs[1]); nzmaxad = (int) mxGetNzmax(prhs[1]); A = (int) mxGetM(prhs[1]); if ((int) mxGetN(prhs[1]) != D) mexErrMsgTxt("WD and AD must have the same number of columns"); /* check that every document has some authors */ for (i=0; i<D; i++) { if ((jcad[i + 1] - jcad[i]) == 0) mexErrMsgTxt("there are some documents without authors in AD matrix "); if ((jcad[i + 1] - jcad[i]) > NAMAX) mexErrMsgTxt("Too many authors in some documents ... reached the NAMAX limit"); if ((jcad[i + 1] - jcad[i]) > MA) MA = (int) (jcad[i + 1] - jcad[i]); } phi = mxGetPr(prhs[2]); J = (int) mxGetM(prhs[2]); if (J<=0) mexErrMsgTxt("Number of topics must be greater than zero"); if ((int) mxGetN(prhs[2]) != W) mexErrMsgTxt("Vocabulary mismatches"); NN = (int) mxGetScalar(prhs[3]); if (NN<0) mexErrMsgTxt("Number of iterations must be greater than zero"); ALPHA = (double) mxGetScalar(prhs[4]); if (ALPHA<0) mexErrMsgTxt("ALPHA must be greater than zero"); BETA = (double) mxGetScalar(prhs[5]); if (BETA<0) mexErrMsgTxt("BETA must be greater than zero"); SEED = (int) mxGetScalar(prhs[6]); // set the seed of the random number generator OUTPUT = (int) mxGetScalar(prhs[7]); if (startcond == 1) { MUZIN = mxGetPr(prhs[8]); if (nzmaxwd != mxGetN(prhs[8])) mexErrMsgTxt("WD and MUZIN mismatch"); if (J != mxGetM( prhs[ 8 ])) mexErrMsgTxt("J and MUZIN mismatch"); MUXIN = mxGetPr(prhs[9]); if (nzmaxwd != mxGetN( prhs[9])) mexErrMsgTxt("WD and MUXIN mismatch"); if (MA != mxGetM(prhs[9])) mexErrMsgTxt("MA and MUXIN mismatch"); } // seeding seedMT( 1 + SEED * 2 ); // seeding only works on uneven numbers /* allocate memory */ muz = dvec(J*nzmaxwd); mux = dvec(MA*nzmaxwd); if (startcond == 1) { for (i=0; i<J*nzmaxwd; i++) muz[i] = (double) MUZIN[i]; for (a=0; a<MA*nzmaxwd; a++) mux[i] = (double) MUXIN[i]; } theta = dvec(J*A); /* run the model */ ATMBP( ALPHA, BETA, W, J, D, A, MA, NN, OUTPUT, irwd, jcwd, srwd, irad, jcad, muz, mux, phi, theta, startcond ); /* output */ plhs[0] = mxCreateDoubleMatrix(J, A, mxREAL); mxSetPr(plhs[0], theta); plhs[1] = mxCreateDoubleMatrix(J, nzmaxwd, mxREAL); mxSetPr(plhs[1], muz); plhs[2] = mxCreateDoubleMatrix(MA, nzmaxwd, mxREAL); mxSetPr(plhs[2], mux); }
const char *model_to_matlab_structure(mxArray *plhs[], int num_of_feature, struct svm_model *model) { int i, j, n; double *ptr; mxArray *return_model, **rhs; int out_id = 0; rhs = (mxArray **)mxMalloc(sizeof(mxArray *)*NUM_OF_RETURN_FIELD); /* Parameters */ rhs[out_id] = mxCreateDoubleMatrix(5, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); ptr[0] = model->param.svm_type; ptr[1] = model->param.kernel_type; ptr[2] = model->param.degree; ptr[3] = model->param.gamma; ptr[4] = model->param.coef0; out_id++; /* nr_class */ rhs[out_id] = mxCreateDoubleMatrix(1, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); ptr[0] = model->nr_class; out_id++; /* total SV */ rhs[out_id] = mxCreateDoubleMatrix(1, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); ptr[0] = model->l; out_id++; /* rho */ n = model->nr_class*(model->nr_class-1)/2; rhs[out_id] = mxCreateDoubleMatrix(n, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); for(i = 0; i < n; i++) ptr[i] = model->rho[i]; out_id++; /* Label */ if(model->label) { rhs[out_id] = mxCreateDoubleMatrix(model->nr_class, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); for(i = 0; i < model->nr_class; i++) ptr[i] = model->label[i]; } else rhs[out_id] = mxCreateDoubleMatrix(0, 0, mxREAL); out_id++; /* probA */ if(model->probA != NULL) { rhs[out_id] = mxCreateDoubleMatrix(n, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); for(i = 0; i < n; i++) ptr[i] = model->probA[i]; } else rhs[out_id] = mxCreateDoubleMatrix(0, 0, mxREAL); out_id ++; /* probB */ if(model->probB != NULL) { rhs[out_id] = mxCreateDoubleMatrix(n, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); for(i = 0; i < n; i++) ptr[i] = model->probB[i]; } else rhs[out_id] = mxCreateDoubleMatrix(0, 0, mxREAL); out_id++; /* nSV */ if(model->nSV) { rhs[out_id] = mxCreateDoubleMatrix(model->nr_class, 1, mxREAL); ptr = mxGetPr(rhs[out_id]); for(i = 0; i < model->nr_class; i++) ptr[i] = model->nSV[i]; } else rhs[out_id] = mxCreateDoubleMatrix(0, 0, mxREAL); out_id++; /* sv_coef */ rhs[out_id] = mxCreateDoubleMatrix(model->l, model->nr_class-1, mxREAL); ptr = mxGetPr(rhs[out_id]); for(i = 0; i < model->nr_class-1; i++) for(j = 0; j < model->l; j++) ptr[(i*(model->l))+j] = model->sv_coef[i][j]; out_id++; /* SVs */ { int ir_index, nonzero_element; mwIndex *ir, *jc; mxArray *pprhs[1], *pplhs[1]; if(model->param.kernel_type == PRECOMPUTED) { nonzero_element = model->l; num_of_feature = 1; } else { nonzero_element = 0; for(i = 0; i < model->l; i++) { j = 0; while(model->SV[i][j].index != -1) { nonzero_element++; j++; } } } /* SV in column, easier accessing */ rhs[out_id] = mxCreateSparse(num_of_feature, model->l, nonzero_element, mxREAL); ir = mxGetIr(rhs[out_id]); jc = mxGetJc(rhs[out_id]); ptr = mxGetPr(rhs[out_id]); jc[0] = ir_index = 0; for(i = 0;i < model->l; i++) { if(model->param.kernel_type == PRECOMPUTED) { /* make a (1 x model->l) matrix */ ir[ir_index] = 0; ptr[ir_index] = model->SV[i][0].value; ir_index++; jc[i+1] = jc[i] + 1; } else { int x_index = 0; while (model->SV[i][x_index].index != -1) { ir[ir_index] = model->SV[i][x_index].index - 1; ptr[ir_index] = model->SV[i][x_index].value; ir_index++, x_index++; } jc[i+1] = jc[i] + x_index; } } /* transpose back to SV in row */ pprhs[0] = rhs[out_id]; if(mexCallMATLAB(1, pplhs, 1, pprhs, "transpose")) return "cannot transpose SV matrix"; rhs[out_id] = pplhs[0]; out_id++; } /* Create a struct matrix contains NUM_OF_RETURN_FIELD fields */ return_model = mxCreateStructMatrix(1, 1, NUM_OF_RETURN_FIELD, field_names); /* Fill struct matrix with input arguments */ for(i = 0; i < NUM_OF_RETURN_FIELD; i++) mxSetField(return_model,0,field_names[i],mxDuplicateArray(rhs[i])); /* return */ plhs[0] = return_model; mxFree(rhs); return NULL; }
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { /* Sparse matrix-dense vector product * * Inputs: * * A - m x n sparse matrix * b - n x 1 dense vector * * Outputs: * * x = A*b * * Darren Engwirda 2006. */ double *s, *b, *x; int *ir, *jc, i, ncol, k; /* Check I/O number */ if (nlhs!=1) { mexErrMsgTxt("Incorrect number of outputs"); } if (nrhs!=2) { mexErrMsgTxt("Incorrect number of inputs"); } /* Brief error checking */ ncol = mxGetN(prhs[0]); if ((ncol!=mxGetM(prhs[1])) || (mxGetN(prhs[1])!=1)) { mexErrMsgTxt("Wrong input dimensions"); } if (!mxIsSparse(prhs[0])) { mexErrMsgTxt("Matrix must be sparse"); } /* Allocate output */ plhs[0] = mxCreateDoubleMatrix(mxGetM(prhs[0]), 1, mxREAL); /* I/O pointers */ ir = mxGetIr(prhs[0]); /* Row indexing */ jc = mxGetJc(prhs[0]); /* Column count */ s = mxGetPr(prhs[0]); /* Non-zero elements */ b = mxGetPr(prhs[1]); /* Rhs vector */ x = mxGetPr(plhs[0]); /* Output vector */ /* Multiplication */ for (i=0; i<ncol; i++) { /* Loop through columns */ int stop = jc[i+1]; double rhs = b[i]; for (k=jc[i]; k<stop; k++) { /* Loop through non-zeros in ith column */ x[ir[k]] += s[k] * rhs; } } /* End */ }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int k; long i,j,nVars,nSamples,one=1; double gi,Hi,alphaOld,c,d,UB,LB,scaling,scaling2; char trans='N'; mwIndex *jc, *ir; if (nrhs < 4) mexErrMsgTxt("At least 4 arguments are needed: {alpha,yXt,lambda,jVals[,w,yxxy]}"); double *alpha = mxGetPr(prhs[0]); double *yXt = mxGetPr(prhs[1]); double lambda = mxGetScalar(prhs[2]); int *iVals = (int*)mxGetPr(prhs[3]); /* Compute Sizes */ nSamples = mxGetN(prhs[1]); nVars = mxGetM(prhs[1]); int maxIter = mxGetM(prhs[3]); /* Basic input checking */ if (nSamples != mxGetM(prhs[0]) || 1 != mxGetN(prhs[0])) mexErrMsgTxt("alpha should be a column vector, with length equal to the number of columns of yXt"); if (!mxIsClass(prhs[3],"int32") || 1 != mxGetN(prhs[3])) mexErrMsgTxt("iVals must be an int32 column vector"); int sparse = 0; if (mxIsSparse(prhs[1])) { sparse = 1; jc = mxGetJc(prhs[1]); ir = mxGetIr(prhs[1]); } lambda = lambda*nSamples; /* Initialize w */ double *w; if (nrhs >= 5) { w = mxGetPr(prhs[4]); if (nVars != mxGetM(prhs[4]) || 1 != mxGetN(prhs[4])) mexErrMsgTxt("w should be a column vector, with the same number of rows as yXt"); } else { w = mxCalloc(nVars,sizeof(double)); if (sparse) { for(i = 0;i < nSamples;i++) { if (sparse) { for(j = jc[i];j < jc[i+1];j++) { w[ir[j]] -= yXt[j]*alpha[i]/lambda; } } } } else { scaling = -1/lambda; scaling2 = 0; dgemv(&trans,&nVars,&nSamples,&scaling,yXt,&nVars,alpha,&one,&scaling2,w,&one); } } /* Compute yxxy */ double *yxxy; if (nrhs >= 6) { yxxy = mxGetPr(prhs[5]); if (nSamples != mxGetM(prhs[5]) || 1 != mxGetN(prhs[5])) mexErrMsgTxt("yxxy should be a column vector, with length equal to the number of columns in yXt"); } else { yxxy = mxCalloc(nSamples,sizeof(double)); for(i = 0;i < nSamples;i++) { if (sparse) { for(j = jc[i];j < jc[i+1];j++) { yxxy[i] += yXt[j]*yXt[j]; } } else { yxxy[i] = ddot(&nVars,&yXt[nVars*i],&one,&yXt[nVars*i],&one); } } } for(k=0;k<maxIter;k++) { /* Select next sample to update */ i = iVals[k]-1; alphaOld = alpha[i]; if(alphaOld == 0 || alphaOld == 1) alpha[i] = 0.5; LB = 0.0; UB = 1.0; c = (alphaOld/lambda)*yxxy[i]; if (sparse) { for(j = jc[i];j < jc[i+1];j++) { c += w[ir[j]]*yXt[j]; } } else c += ddot(&nVars,w,&one,&yXt[nVars*i],&one); d = yxxy[i]/lambda; gi = log(alpha[i]) - log(1-alpha[i]) - c + alpha[i]*d; while (fabs(gi) > 1e-8 && UB-LB > 1e-15) { Hi = 1/alpha[i] + 1/(1-alpha[i]) + d; alpha[i] -= gi/Hi; if (alpha[i] <= LB || alpha[i] >= UB) alpha[i] = (LB+UB)/2; gi = log(alpha[i]) - log(1-alpha[i]) - c + alpha[i]*d; if (gi > 0) UB = alpha[i]; else LB = alpha[i]; } if (sparse) { for(j = jc[i];j < jc[i+1];j++) { w[ir[j]] += yXt[j]*(alphaOld - alpha[i])/lambda; } } else { scaling = (alphaOld - alpha[i])/lambda; daxpy(&nVars,&scaling,&yXt[i*nVars],&one,w,&one); } } if (nrhs < 5) mxFree(w); if (nrhs < 6) mxFree(yxxy); }
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 (!mexCheckType<int>(prhs[2])) mexErrMsgTxt("type of argument 3 is not consistent"); if (!mxIsStruct(prhs[3])) mexErrMsgTxt("argument 4 should be struct"); T* prX=reinterpret_cast<T*>(mxGetPr(prhs[0])); const mwSize* dims=mxGetDimensions(prhs[0]); INTM n=static_cast<INTM>(dims[0]); INTM M=static_cast<INTM>(dims[1]); T * prD = reinterpret_cast<T*>(mxGetPr(prhs[1])); const mwSize* dimsD=mxGetDimensions(prhs[1]); INTM nD=static_cast<INTM>(dimsD[0]); if (nD != n) mexErrMsgTxt("wrong size for argument 2"); INTM K=static_cast<INTM>(dimsD[1]); const mwSize* dimsList = mxGetDimensions(prhs[2]); int Ng = static_cast<int>(dimsList[0]*dimsList[1]); int* list_groups=reinterpret_cast<int*>(mxGetPr(prhs[2])); int L= getScalarStruct<int>(prhs[3],"L"); T eps= getScalarStructDef<T>(prhs[3],"eps",0); int numThreads = getScalarStructDef<int>(prhs[3],"numThreads",-1); Matrix<T> D(prD,n,K); Matrix<T>* X = new Matrix<T>[Ng]; if (list_groups[0] != 0) mexErrMsgTxt("First group index should be zero"); for (int i = 0; i<Ng-1; ++i) { if (list_groups[i] >= M) mexErrMsgTxt("Size of groups is not consistent"); if (list_groups[i] >= list_groups[i+1]) mexErrMsgTxt("Group indices should be a strictly non-decreasing sequence"); X[i].setData(prX+list_groups[i]*n,n,list_groups[i+1]-list_groups[i]); } X[Ng-1].setData(prX+list_groups[Ng-1]*n,n,M-list_groups[Ng-1]); SpMatrix<T>* spAlpha = new SpMatrix<T>[Ng]; somp(X,D,spAlpha,Ng,L,eps,numThreads); INTM nzmax=0; for (INTM i = 0; i<Ng; ++i) { nzmax += spAlpha[i].nzmax(); } plhs[0]=mxCreateSparse(K,M,nzmax,mxREAL); double* Pr = mxGetPr(plhs[0]); mwSize* Ir = mxGetIr(plhs[0]); mwSize* Jc = mxGetJc(plhs[0]); INTM count=0; INTM countcol=0; INTM offset=0; for (INTM i = 0; i<Ng; ++i) { const T* v = spAlpha[i].v(); const INTM* r = spAlpha[i].r(); const INTM* pB = spAlpha[i].pB(); INTM nn = spAlpha[i].n(); nzmax = spAlpha[i].nzmax(); if (nn != 0) { for (INTM j = 0; j<pB[nn]; ++j) { Pr[count]=static_cast<double>(v[j]); Ir[count++]=static_cast<mwSize>(r[j]); } for (INTM j = 0; j<=nn; ++j) Jc[countcol++]=static_cast<mwSize>(offset+pB[j]); --countcol; offset = Jc[countcol]; } } delete[](X); delete[](spAlpha); }
/******************************************************************** PROCEDURE mexFunction - Entry for Matlab *********************************************************************/ void mexFunction(const int nlhs, mxArray *plhs[], const int nrhs, const mxArray *prhs[]) { double *x, *b, *btmp, *Rt; int *irb, *jcb, *irRt, *jcRt; int n, isspb; int j, k, kstart, kend, idx; double tmp; if(nrhs < 1) mexErrMsgTxt("mexbwsolve: requires 2 input arguments."); if(nlhs > 1) mexErrMsgTxt("mexbwsolve: requires 1 output argument."); n = mxGetM(prhs[1]); isspb = mxIsSparse(prhs[1]); if (isspb) { btmp = mxGetPr(prhs[1]); irb = mxGetIr(prhs[1]); jcb = mxGetJc(prhs[1]); b = mxCalloc(n,sizeof(double)); kstart = jcb[0]; kend = jcb[1]; for (k=kstart; k<kend; k++) { b[irb[k]] = btmp[k]; } } else { b = mxGetPr(prhs[1]); } if ( n != mxGetN(prhs[0]) ) { mexErrMsgTxt("mexbwsolve: Rt should be square."); } if (!mxIsSparse(prhs[0])) { mexErrMsgTxt("mexbwsolve: Rt should be sparse."); } Rt = mxGetPr(prhs[0]); irRt = mxGetIr(prhs[0]); jcRt = mxGetJc(prhs[0]); if (irRt[jcRt[n]-1] < n-1) { mexErrMsgTxt("mexbwsolve: Rt not lower triangular."); } /*****************************/ plhs[0] = mxCreateDoubleMatrix(n,1,mxREAL); x = mxGetPr(plhs[0]); /************************************************ x[j]*Rt[j,j] + x[j+1:n]*Rt[j+1:n,j] = b[j] ************************************************/ x[n-1] = b[n-1]/Rt[jcRt[n]-1]; for (j=n-2; j>=0; j--) { kstart = jcRt[j]+1; kend = jcRt[j+1]; tmp = 0.0; for (k=kstart; k<kend; k++) { idx = irRt[k]; tmp += Rt[k]*x[idx]; } x[j] = (b[j]-tmp)/Rt[kstart-1]; } /*****************************/ if (isspb) { mxFree(b); } return; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { FILE *log; Options_Interface *o; Void *timer; MCP *m; MCP_Termination t; Information info; double *tempZ; double *status, *tot_time; double dnnz; int i, len; mat_install_error(); mat_install_memory(); log = fopen("logfile.tmp", "w"); Output_SetLog(log); /* Options. 1. Get options associated with the algorithm 2. Set to default values 3. Read in an options file 4. Print out the options */ o = Options_Create(); Path_AddOptions(o); Options_Default(o); if (nrhs < 7) { Error("Not enough input arguments.\n"); } if (nlhs < 2) { Error("Not enough output arguments.\n"); } nMax = (int) mxGetScalar(prhs[0]); nnzMax = (int) mxGetScalar(prhs[1]); plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL); if (nlhs > 2) { plhs[2] = mxCreateDoubleMatrix(nMax,1,mxREAL); } if (nlhs > 3) { plhs[3] = mxCreateDoubleMatrix(nMax,1,mxREAL); } /* Create a timer and start it. */ timer = Timer_Create(); Timer_Start(timer); /* Derefencing to get the status argument. */ status = mxGetPr(plhs[0]); tot_time = mxGetPr(plhs[1]); /* First print out some version information. */ Output_Printf(Output_Log | Output_Status | Output_Listing, "%s: Matlab Link\n", Path_Version()); /* Now check the arguments. If the dimension of the problem is 0, there is nothing to do. */ if (nMax == 0) { Output_Printf(Output_Log | Output_Status, "\n ** EXIT - solution found (degenerate model).\n"); (*status) = 1.0; (*tot_time) = Timer_Query(timer); Timer_Destroy(timer); Options_Destroy(o); fclose(log); return; } /* Check size of the jacobian. nnz < n*n. Need to convert to double so we do not run out of integers. dnnz - max number of nonzeros as a double */ dnnz = MIN(1.0*nnzMax, 1.0*nMax*nMax); if (dnnz > INT_MAX) { Output_Printf(Output_Log | Output_Status, "\n ** EXIT - model too large.\n"); (*status) = 0.0; (*tot_time) = Timer_Query(timer); Timer_Destroy(timer); Options_Destroy(o); fclose(log); return; } nnzMax = (int) dnnz; /* Have correct number of nonzeros. Print some statistics. Print out the density. */ Output_Printf(Output_Log | Output_Status | Output_Listing, "%d row/cols, %d non-zeros, %3.2f%% dense.\n\n", nMax, nnzMax, 100.0*nnzMax/(1.0*nMax*nMax)); if (nnzMax == 0) { nnzMax++; } zp = mxGetPr(prhs[2]); lp = mxGetPr(prhs[3]); up = mxGetPr(prhs[4]); m_start = mxGetJc(prhs[5]); m_row = mxGetIr(prhs[5]); m_data = mxGetPr(prhs[5]); m_len = (int *)Memory_Allocate(nMax*sizeof(int)); for (i = 0; i < nMax; i++) { m_len[i] = m_start[i+1] - m_start[i]; m_start[i]++; } actualNnz = m_start[nMax]; for (i = 0; i < actualNnz; i++) { m_row[i]++; } q = mxGetPr(prhs[6]); /* Create a structure for the problem. */ m = MCP_Create(nMax, nnzMax); MCP_Jacobian_Structure_Constant(m, 1); MCP_Jacobian_Data_Contiguous(m, 1); install_interface(m); Options_Read(o, "path.opt"); Options_Display(o); info.generate_output = Output_Log | Output_Status | Output_Listing; info.use_start = True; info.use_basics = True; /* Solve the problem. m - MCP to solve, info - information, t - termination */ t = Path_Solve(m, &info); /* Read in the results. First get the solution vector. The report. */ tempZ = MCP_GetX(m); for (i = 0; i < nMax; i++) { zp[i] = tempZ[i]; } /* If the final function evaluation is wanted, report it. */ if (nlhs > 2) { double *fval = mxGetPr(plhs[2]); tempZ = MCP_GetF(m); for (i = 0; i < nMax; i++) { fval[i] = tempZ[i]; } } /* If the final basis is wanted, report it. */ if (nlhs > 3) { double *bval = mxGetPr(plhs[3]); int *tempB; tempB = MCP_GetB(m); for (i = 0; i < nMax; i++) { switch(tempB[i]) { case Basis_LowerBound: bval[i] = -1; break; case Basis_UpperBound: bval[i] = 1; break; default: bval[i] = 0; break; } } } switch(t) { case MCP_Solved: *status = 1.0; break; default: *status = 0.0; break; } /* Stop the timer and report the results. */ (*tot_time) = Timer_Query(timer); Timer_Destroy(timer); /* Clean up. Deallocate memory used and close the log. */ MCP_Destroy(m); Memory_Free(m_len); Options_Destroy(o); fclose(log); return; }
void mexFunction ( /* === Parameters ======================================================= */ int nlhs, /* number of left-hand sides */ mxArray *plhs [], /* left-hand side matrices */ int nrhs, /* number of right--hand sides */ const mxArray *prhs [] /* right-hand side matrices */ ) { Zmat A; ZAMGlevelmat *PRE; ZILUPACKparam *param; integer n; const char **fnames; const mwSize *dims; mxClassID *classIDflags; mxArray *tmp, *fout, *A_input , *b_input, *x0_input, *options_input, *PRE_input, *options_output, *x_output; char *pdata, *input_buf, *output_buf; mwSize mrows, ncols, buflen, ndim,nnz; int ifield, status, nfields, ierr,i,j,k,l,m; size_t sizebuf; double dbuf, *A_valuesR, *A_valuesI, *convert, *sr, *pr, *pi; doublecomplex *sol, *rhs; mwIndex *irs, *jcs, *A_ja, /* row indices of input matrix A */ *A_ia; /* column pointers of input matrix A */ if (nrhs != 5) mexErrMsgTxt("five input arguments required."); else if (nlhs !=2) mexErrMsgTxt("Too many output arguments."); else if (!mxIsStruct(prhs[2])) mexErrMsgTxt("Third input must be a structure."); else if (!mxIsNumeric(prhs[0])) mexErrMsgTxt("First input must be a matrix."); /* The first input must be a square matrix.*/ A_input = (mxArray *) prhs [0] ; /* get size of input matrix A */ mrows = mxGetM (A_input) ; ncols = mxGetN (A_input) ; nnz = mxGetNzmax(A_input); if (mrows!=ncols) { mexErrMsgTxt("First input must be a square matrix."); } if (!mxIsSparse (A_input)) { mexErrMsgTxt ("ILUPACK: input matrix must be in sparse format.") ; } /* copy input matrix to sparse row format */ A.nc=A.nr=mrows; A.ia=(integer *) MAlloc((size_t)(A.nc+1)*sizeof(integer),"ZGNLSYMilupacksolver"); A.ja=(integer *) MAlloc((size_t)nnz *sizeof(integer),"ZGNLSYMilupacksolver"); A. a=(doublecomplex *) MAlloc((size_t)nnz *sizeof(doublecomplex), "ZGNLSYMilupacksolver"); A_ja = (mwIndex *) mxGetIr (A_input) ; A_ia = (mwIndex *) mxGetJc (A_input) ; A_valuesR = (double *) mxGetPr(A_input); if (mxIsComplex(A_input)) A_valuesI = (double *) mxGetPi(A_input); /* -------------------------------------------------------------------- */ /* .. Convert matrix from 0-based C-notation to Fortran 1-based */ /* notation. */ /* -------------------------------------------------------------------- */ /* for (i = 0 ; i < ncols ; i++) for (j = A_ia[i] ; j < A_ia[i+1] ; j++) printf("i=%d j=%d A.real=%e\n", i+1, A_ja[j]+1, A_valuesR[j]); */ for (i=0; i<=A.nr; i++) A.ia[i]=0; /* remember that MATLAB uses storage by columns and NOT by rows! */ for (i=0; i<A.nr; i++) { for (j=A_ia[i]; j<A_ia[i+1]; j++) { k=A_ja[j]; A.ia[k+1]++; } } /* now we know how many entries are located in every row */ /* switch to pointer structure */ for (i=0; i<A.nr; i++) A.ia[i+1]+=A.ia[i]; if (mxIsComplex(A_input)) { for (i=0; i<ncols; i++) { for (j=A_ia[i]; j<A_ia[i+1]; j++) { /* row index l in C-notation */ l=A_ja[j]; /* where does row l currently start */ k=A.ia[l]; /* column index will be i in FORTRAN notation */ A.ja[k]=i+1; A.a [k].r =A_valuesR[j]; A.a [k++].i=A_valuesI[j]; A.ia[l]=k; } } } else { for (i=0; i<ncols; i++) { for (j=A_ia[i]; j<A_ia[i+1]; j++) { /* row index l in C-notation */ l=A_ja[j]; /* where does row l currently start */ k=A.ia[l]; /* column index will be i in FORTRAN notation */ A.ja[k]=i+1; A.a [k].r =A_valuesR[j]; A.a [k++].i=0; A.ia[l]=k; } } } /* switch to FORTRAN style */ for (i=A.nr; i>0; i--) A.ia[i]=A.ia[i-1]+1; A.ia[0]=1; /* for (i = 0 ; i < A.nr ; i++) for (j = A.ia[i]-1 ; j < A.ia[i+1]-1 ; j++) printf("i=%d j=%d A.real=%e A.imag=%e\n", i+1, A.ja[j], A.a[j].r, A.a[j].i); */ /* import pointer to the preconditioner */ PRE_input = (mxArray*) prhs [1] ; /* get number of levels of input preconditioner structure `PREC' */ /* nlev=mxGetN(PRE_input); */ nfields = mxGetNumberOfFields(PRE_input); /* allocate memory for storing pointers */ fnames = mxCalloc((size_t)nfields, (size_t)sizeof(*fnames)); for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(PRE_input,ifield); /* check whether `PREC.ptr' exists */ if (!strcmp("ptr",fnames[ifield])) { /* field `ptr' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(&PRE, pdata, (size_t)sizeof(size_t)); } else if (!strcmp("param",fnames[ifield])) { /* field `param' */ tmp = mxGetFieldByNumber(PRE_input,0,ifield); pdata = mxGetData(tmp); memcpy(¶m, pdata, (size_t)sizeof(size_t)); } } mxFree(fnames); /* rescale input matrix */ /* obsolete for (i=0; i <A.nr; i++) { for (j=A.ia[i]-1; j<A.ia[i+1]-1; j++) { A.a[j].r*=PRE->rowscal[i].r*PRE->colscal[A.ja[j]-1].r; A.a[j].i*=PRE->rowscal[i].r*PRE->colscal[A.ja[j]-1].r; } } */ /* Get third input argument `options' */ options_input=(mxArray*)prhs[2]; nfields = mxGetNumberOfFields(options_input); /* Allocate memory for storing classIDflags */ classIDflags = (mxClassID *) mxCalloc((size_t)nfields+1, (size_t)sizeof(mxClassID)); /* allocate memory for storing pointers */ fnames = mxCalloc((size_t)nfields+1, (size_t)sizeof(*fnames)); /* Get field name pointers */ j=-1; for (ifield = 0; ifield < nfields; ifield++) { fnames[ifield] = mxGetFieldNameByNumber(options_input,ifield); /* check whether `options.niter' already exists */ if (!strcmp("niter",fnames[ifield])) j=ifield; } if (j==-1) fnames[nfields]="niter"; /* mexPrintf("search for niter completed\n"); fflush(stdout); */ /* import data */ for (ifield = 0; ifield < nfields; ifield++) { /* mexPrintf("%2d\n",ifield+1); fflush(stdout); */ tmp = mxGetFieldByNumber(options_input,0,ifield); classIDflags[ifield] = mxGetClassID(tmp); ndim = mxGetNumberOfDimensions(tmp); dims = mxGetDimensions(tmp); /* Create string/numeric array */ if (classIDflags[ifield] == mxCHAR_CLASS) { /* Get the length of the input string. */ buflen = (mxGetM(tmp) * mxGetN(tmp)) + 1; /* Allocate memory for input and output strings. */ input_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); /* Copy the string data from tmp into a C string input_buf. */ status = mxGetString(tmp, input_buf, buflen); if (!strcmp("amg",fnames[ifield])) { if (strcmp(param->amg,input_buf)) { param->amg=(char *)MAlloc((size_t)buflen*sizeof(char),"ilupacksolver"); strcpy(param->amg,input_buf); } } else if (!strcmp("presmoother",fnames[ifield])) { if (strcmp(param->presmoother,input_buf)) { param->presmoother=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->presmoother,input_buf); } } else if (!strcmp("postsmoother",fnames[ifield])) { if (strcmp(param->postsmoother,input_buf)) { param->postsmoother=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->postsmoother,input_buf); } } else if (!strcmp("typecoarse",fnames[ifield])) { if (strcmp(param->typecoarse,input_buf)) { param->typecoarse=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->typecoarse,input_buf); } } else if (!strcmp("typetv",fnames[ifield])) { if (strcmp(param->typetv,input_buf)) { param->typetv=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->typetv,input_buf); } } else if (!strcmp("FCpart",fnames[ifield])) { if (strcmp(param->FCpart,input_buf)) { param->FCpart=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->FCpart,input_buf); } } else if (!strcmp("solver",fnames[ifield])) { if (strcmp(param->solver,input_buf)) { param->solver=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->solver,input_buf); } } else if (!strcmp("ordering",fnames[ifield])) { if (strcmp(param->ordering,input_buf)) { param->ordering=(char *)MAlloc((size_t)buflen*sizeof(char), "ilupacksolver"); strcpy(param->ordering,input_buf); } } else { /* mexPrintf("%s ignored\n",fnames[ifield]);fflush(stdout); */ } } else { if (!strcmp("elbow",fnames[ifield])) { param->elbow=*mxGetPr(tmp); } else if (!strcmp("lfilS",fnames[ifield])) { param->lfilS=*mxGetPr(tmp); } else if (!strcmp("lfil",fnames[ifield])) { param->lfil=*mxGetPr(tmp); } else if (!strcmp("maxit",fnames[ifield])) { param->maxit=*mxGetPr(tmp); } else if (!strcmp("droptolS",fnames[ifield])) { param->droptolS=*mxGetPr(tmp); } else if (!strcmp("droptolc",fnames[ifield])) { param->droptolc=*mxGetPr(tmp); } else if (!strcmp("droptol",fnames[ifield])) { param->droptol=*mxGetPr(tmp); } else if (!strcmp("condest",fnames[ifield])) { param->condest=*mxGetPr(tmp); } else if (!strcmp("restol",fnames[ifield])) { param->restol=*mxGetPr(tmp); } else if (!strcmp("npresmoothing",fnames[ifield])) { param->npresmoothing=*mxGetPr(tmp); } else if (!strcmp("npostmoothing",fnames[ifield])) { param->npostsmoothing=*mxGetPr(tmp); } else if (!strcmp("ncoarse",fnames[ifield])) { param->ncoarse=*mxGetPr(tmp); } else if (!strcmp("matching",fnames[ifield])) { param->matching=*mxGetPr(tmp); } else if (!strcmp("nrestart",fnames[ifield])) { param->nrestart=*mxGetPr(tmp); } else if (!strcmp("damping",fnames[ifield])) { param->damping.r=*mxGetPr(tmp); if (mxIsComplex(tmp)) param->damping.i=*mxGetPi(tmp); else param->damping.i=0; } else if (!strcmp("mixedprecision",fnames[ifield])) { param->mixedprecision=*mxGetPr(tmp); } else { /* mexPrintf("%s ignored\n",fnames[ifield]);fflush(stdout); */ } } } /* copy right hand side `b' */ b_input = (mxArray *) prhs [3] ; /* get size of input matrix A */ rhs=(doublecomplex*) MAlloc((size_t)A.nr*sizeof(doublecomplex),"ZGNLSYMilupacksolver:rhs"); pr=mxGetPr(b_input); if (!mxIsComplex(b_input)) { for (i=0; i<A.nr; i++) { rhs[i].r=pr[i]; rhs[i].i=0; } } else { pi=mxGetPi(b_input); for (i=0; i<A.nr; i++) { rhs[i].r=pr[i]; rhs[i].i=pi[i]; } } /* copy initial solution `x0' */ x0_input = (mxArray *) prhs [4] ; /* numerical solution */ sol=(doublecomplex *)MAlloc((size_t)A.nr*sizeof(doublecomplex),"ZGNLSYMilupacksolver:sol"); pr=mxGetPr(x0_input); if (!mxIsComplex(x0_input)) { for (i=0; i<A.nr; i++) { sol[i].r=pr[i]; sol[i].i=0; } } else { pi=mxGetPi(x0_input); for (i=0; i<A.nr; i++) { sol[i].r=pr[i]; sol[i].i=pi[i]; } } /* set bit 2, transpose */ param->ipar[4]|=4; /* set bit 3, conjugate */ param->ipar[4]|=8; ierr=ZGNLSYMAMGsolver(&A, PRE, param, rhs, sol); /* Create a struct matrices for output */ nlhs=2; if (j==-1) plhs[1] = mxCreateStructMatrix((mwSize)1, (mwSize)1, (mwSize)nfields+1, fnames); else plhs[1] = mxCreateStructMatrix((mwSize)1, (mwSize)1, (mwSize)nfields, fnames); if (plhs[1]==NULL) mexErrMsgTxt("Could not create structure mxArray\n"); options_output=plhs[1]; /* export data */ for (ifield = 0; ifield<nfields; ifield++) { tmp = mxGetFieldByNumber(options_input,0,ifield); classIDflags[ifield] = mxGetClassID(tmp); ndim = mxGetNumberOfDimensions(tmp); dims = mxGetDimensions(tmp); /* Create string/numeric array */ if (classIDflags[ifield] == mxCHAR_CLASS) { if (!strcmp("amg",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->amg)+1, (size_t)sizeof(char)); strcpy(output_buf,param->amg); fout = mxCreateString(output_buf); } else if (!strcmp("presmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->presmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param->presmoother); fout = mxCreateString(output_buf); } else if (!strcmp("postsmoother",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->postsmoother)+1, (size_t)sizeof(char)); strcpy(output_buf,param->postsmoother); fout = mxCreateString(output_buf); } else if (!strcmp("typecoarse",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->typecoarse)+1, (size_t)sizeof(char)); strcpy(output_buf,param->typecoarse); fout = mxCreateString(output_buf); } else if (!strcmp("typetv",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->typetv)+1, (size_t)sizeof(char)); strcpy(output_buf,param->typetv); fout = mxCreateString(output_buf); } else if (!strcmp("FCpart",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->FCpart)+1, (size_t)sizeof(char)); strcpy(output_buf,param->FCpart); fout = mxCreateString(output_buf); } else if (!strcmp("solver",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->solver)+1, (size_t)sizeof(char)); strcpy(output_buf, param->solver); fout = mxCreateString(output_buf); } else if (!strcmp("ordering",fnames[ifield])) { output_buf = (char *) mxCalloc((size_t)strlen(param->ordering)+1, (size_t)sizeof(char)); strcpy(output_buf, param->ordering); fout = mxCreateString(output_buf); } else { /* Get the length of the input string. */ buflen = (mxGetM(tmp) * mxGetN(tmp)) + 1; /* Allocate memory for input and output strings. */ input_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); output_buf = (char *) mxCalloc((size_t)buflen, (size_t)sizeof(char)); /* Copy the string data from tmp into a C string input_buf. */ status = mxGetString(tmp, input_buf, buflen); sizebuf = (size_t)buflen*sizeof(char); memcpy(output_buf, input_buf, sizebuf); fout = mxCreateString(output_buf); } } else { /* real case */ if (mxGetPi(tmp)==NULL && strcmp("damping",fnames[ifield])) fout = mxCreateNumericArray(ndim, dims, classIDflags[ifield], mxREAL); else { /* complex case */ fout = mxCreateNumericArray(ndim, dims, classIDflags[ifield], mxCOMPLEX); } pdata = mxGetData(fout); sizebuf = mxGetElementSize(tmp); if (!strcmp("elbow",fnames[ifield])) { dbuf=param->elbow; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("lfilS",fnames[ifield])) { dbuf=param->lfilS; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("lfil",fnames[ifield])) { dbuf=param->lfil; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("maxit",fnames[ifield])) { dbuf=param->maxit; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptolS",fnames[ifield])) { dbuf=param->droptolS; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptolc",fnames[ifield])) { dbuf=param->droptolc; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("droptol",fnames[ifield])) { dbuf=param->droptol; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("condest",fnames[ifield])) { dbuf=param->condest; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("restol",fnames[ifield])) { dbuf=param->restol; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("npresmoothing",fnames[ifield])) { dbuf=param->npresmoothing; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("npostmoothing",fnames[ifield])) { dbuf=param->npostsmoothing; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("ncoarse",fnames[ifield])) { dbuf=param->ncoarse; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("matching",fnames[ifield])) { dbuf=param->matching; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("nrestart",fnames[ifield])) { dbuf=param->nrestart; memcpy(pdata, &dbuf, sizebuf); } else if (!strcmp("damping",fnames[ifield])) { pr=mxGetPr(fout); pi=mxGetPi(fout); *pr=param->damping.r; *pi=param->damping.i; } else if (!strcmp("mixedprecision",fnames[ifield])) { dbuf=param->mixedprecision; memcpy(pdata, &dbuf, sizebuf); } else { memcpy(pdata, mxGetData(tmp), sizebuf); } } /* Set each field in output structure */ mxSetFieldByNumber(options_output, (mwIndex)0, ifield, fout); } /* store number of iteration steps */ if (j==-1) ifield=nfields; else ifield=j; fout=mxCreateDoubleMatrix((mwSize)1,(mwSize)1, mxREAL); pr=mxGetPr(fout); *pr=param->ipar[26]; /* set each field in output structure */ mxSetFieldByNumber(options_output, (mwIndex)0, ifield, fout); mxFree(fnames); mxFree(classIDflags); /* mexPrintf("options exported\n"); fflush(stdout); */ /* export approximate solution */ plhs[0] = mxCreateDoubleMatrix((mwSize)A.nr, (mwSize)1, mxCOMPLEX); x_output=plhs[0]; pr=mxGetPr(x_output); pi=mxGetPi(x_output); for (i=0; i<A.nr; i++) { pr[i]=sol[i].r; pi[i]=sol[i].i; } /* release right hand side */ free(rhs); /* release solution */ free(sol); /* release input matrix */ free(A.ia); free(A.ja); free(A.a); switch (ierr) { case 0: /* perfect! */ break; case -1: /* too many iteration steps */ mexPrintf("!!! ILUPACK Warning !!!\n"); mexPrintf("number of iteration steps exceeded its limit.\nEither increase `options.maxit'\n or recompute ILUPACK preconditioner using a smaller `options.droptol'"); break; case -2: /* weird, should not occur */ mexErrMsgTxt("not enough workspace provided."); plhs[0]=NULL; break; case -3: /* breakdown */ mexErrMsgTxt("iterative solver breaks down.\nMost likely you need to recompute ILUPACK preconditioner using a smaller `options.droptol'"); plhs[0]=NULL; break; default: /* zero pivot encountered at step number ierr */ mexPrintf("iterative solver exited with error code %d",ierr); mexErrMsgTxt("."); plhs[0]=NULL; break; } /* end switch */ return; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { mxArray *rhs[2]; mxArray *blk_cell_pr, *A_cell_pr; double *A, *B, *blksize, *AI, *BI; mwIndex *irA, *jcA, *irB, *jcB; int *cumblksize, *blknnz; int mblk, mA, nA, m1, n1, rowidx, colidx, isspA, isspB; int iscellA, iscmpA; mwIndex subs[2]; mwSize nsubs=2; int n, n2, k, nsub, index, numblk, NZmax; double ir2=1/sqrt(2); /* CHECK FOR PROPER NUMBER OF ARGUMENTS */ if (nrhs < 2){ mexErrMsgTxt("mexsmat: requires at least 2 input arguments."); } else if (nlhs>1){ mexErrMsgTxt("mexsmat: requires 1 output argument."); } /* CHECK THE DIMENSIONS */ iscellA = mxIsCell(prhs[1]); if (iscellA) { mA = mxGetM(prhs[1]); nA = mxGetN(prhs[1]); } else { mA = 1; nA = 1; } if (mxGetM(prhs[0]) != mA) { mexErrMsgTxt("mexsmat: blk and Avec not compatible"); } /***** main body *****/ if (nrhs > 3) {rowidx = (int)*mxGetPr(prhs[3]); } else {rowidx = 1;} if (rowidx > mA) { mexErrMsgTxt("mexsmat: rowidx exceeds size(Avec,1)."); } subs[0] = rowidx-1; /* subtract 1 to adjust for Matlab index */ subs[1] = 1; index = mxCalcSingleSubscript(prhs[0],nsubs,subs); blk_cell_pr = mxGetCell(prhs[0],index); if (blk_cell_pr == NULL) { mexErrMsgTxt("mexsmat: blk not properly specified"); } numblk = mxGetN(blk_cell_pr); blksize = mxGetPr(blk_cell_pr); cumblksize = mxCalloc(numblk+1,sizeof(int)); blknnz = mxCalloc(numblk+1,sizeof(int)); cumblksize[0] = 0; blknnz[0] = 0; n = 0; n2 = 0; for (k=0; k<numblk; ++k) { nsub = (int) blksize[k]; n += nsub; n2 += nsub*(nsub+1)/2; cumblksize[k+1] = n; blknnz[k+1] = n2; } /***** assign pointers *****/ if (iscellA) { subs[0] = rowidx-1; subs[1] = 0; index = mxCalcSingleSubscript(prhs[1],nsubs,subs); A_cell_pr = mxGetCell(prhs[1],index); A = mxGetPr(A_cell_pr); m1 = mxGetM(A_cell_pr); n1 = mxGetN(A_cell_pr); isspA = mxIsSparse(A_cell_pr); iscmpA = mxIsComplex(A_cell_pr); if (isspA) { irA = mxGetIr(A_cell_pr); jcA = mxGetJc(A_cell_pr); } if (iscmpA) { AI = mxGetPi(A_cell_pr); } } else { A = mxGetPr(prhs[1]); m1 = mxGetM(prhs[1]); n1 = mxGetN(prhs[1]); isspA = mxIsSparse(prhs[1]); iscmpA = mxIsComplex(prhs[1]); if (isspA) { irA = mxGetIr(prhs[1]); jcA = mxGetJc(prhs[1]); } if (iscmpA) { AI = mxGetPi(prhs[1]); } } if (numblk > 1) { isspB = 1; } else { if (nrhs > 2) {isspB = (int)*mxGetPr(prhs[2]);} else {isspB = isspA;} } if (nrhs > 4) {colidx = (int)*mxGetPr(prhs[4]) -1;} else {colidx = 0;} if (colidx > n1) { mexErrMsgTxt("mexsmat: colidx exceeds size(Avec,2)."); } /***** create return argument *****/ if (isspB) { if (isspA) { NZmax = jcA[colidx+1]-jcA[colidx]; } else { NZmax = blknnz[numblk]; } if (iscmpA) { rhs[0] = mxCreateSparse(n,n,2*NZmax,mxCOMPLEX); } else { rhs[0] = mxCreateSparse(n,n,2*NZmax,mxREAL); } B = mxGetPr(rhs[0]); irB = mxGetIr(rhs[0]); jcB = mxGetJc(rhs[0]); if (iscmpA) { BI = mxGetPi(rhs[0]); } } else { if (iscmpA) { plhs[0] = mxCreateDoubleMatrix(n,n,mxCOMPLEX); } else { plhs[0] = mxCreateDoubleMatrix(n,n,mxREAL); } B = mxGetPr(plhs[0]); if (iscmpA) { BI = mxGetPi(plhs[0]); } } /***** Do the computations in a subroutine *****/ if (iscmpA) { if (numblk == 1) { smat1cmp(n,ir2,A,irA,jcA,isspA,m1,colidx,B,irB,jcB,isspB,AI,BI); } else { smat2cmp(n,numblk,cumblksize,blknnz,ir2,A,irA,jcA,isspA,m1,colidx,B,irB,jcB,isspB,AI,BI); } } else { if (numblk == 1) { smat1(n,ir2,A,irA,jcA,isspA,m1,colidx,B,irB,jcB,isspB); } else { smat2(n,numblk,cumblksize,blknnz,ir2,A,irA,jcA,isspA,m1,colidx,B,irB,jcB,isspB); } } if (isspB) { /*** if isspB, (actual B) = B+B' ****/ mexCallMATLAB(1, &rhs[1], 1, &rhs[0], "ctranspose"); mexCallMATLAB(1, &plhs[0],2, rhs, "+"); mxDestroyArray(*rhs); } mxFree(blknnz); mxFree(cumblksize); return; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /*declaration of variables*/ /*iteration variables*/ mwIndex i,j,k,numofnz; /*Auxillary variables*/ double tmplij, tmpljj; mwIndex tmprowind; /*Step 2:*/ mwSize m, n;/*m:number of rows, n:number of columns*/ mwSize nzmax;/*nnz of input*/ mwIndex rnzmax=100000000;/*rnzmax should be comparable with nzmax*/ mwIndex *ajc, *air; double *apr;/*CSC format of prhs[0]*/ double mu, eta1, eta2;/* mu is the shift, and eta1 is threshold*/ double *threshold; /*Step 3: */ mwIndex *zcolstart, *zcolend, *zrow; double *zval; mwIndex gap = 5000; /*Step 4:*/ double pjj,pij,lambda,zji; double *tmpAzj; /*Output:*/ mwIndex *ljc, *lir; double *lpr; /*---------------------------------------------*/ /* Step 1: Check input---------*/ if(nrhs != 4 && nrhs !=5) { mexErrMsgTxt("Four or Five Input Arguments are required"); } if(nlhs != 1) mexErrMsgTxt("One Output Argument Required\n"); /*Check whether prhs[] is sparse*/ if(mxIsSparse(prhs[0]) != 1) mexErrMsgTxt("Input Matrix Must Be Sparse\n"); /* ------------------------------*/ /* Step 2: Get Input Values------------*/ /*Read m and n from prhs[0]*/ m = mxGetM(prhs[0]); n = mxGetN(prhs[0]); nzmax = mxGetNzmax(prhs[0]); /*CSC format of A=prhs[0]*/ ajc = mxGetJc(prhs[0]); air = mxGetIr(prhs[0]); apr = mxGetPr(prhs[0]); /* Get shift*/ mu = mxGetScalar(prhs[1]); /*Get threshold*/ eta1 = mxGetScalar(prhs[2]); threshold = (double *)mxCalloc(n,sizeof(double)); for(j=0;j<n;j++) { for(i=ajc[j];i<ajc[j+1];i++)threshold[j] += absval(apr[i]); threshold[j] = eta1 * threshold[j]; } /*Get threshold parameter for Z*/ eta2 = mxGetScalar(prhs[3]); /* Get allocation parameter*/ if(nrhs == 5) { gap = (mwIndex)mxGetScalar(prhs[4]); if(gap > n)gap = n; } if(gap * m > rnzmax)rnzmax = (mwIndex)(gap*m); /*---------------------------------------*/ /*Step 3: Initialization of Z and L---------- */ zcolstart = (mwIndex *)mxCalloc(n, sizeof(mwIndex)); zcolend = (mwIndex *)mxCalloc(n, sizeof(mwIndex)); zrow = (mwIndex *)mxCalloc(rnzmax,sizeof(mwIndex)); zval = (double *)mxCalloc(rnzmax,sizeof(double)); if(zrow == NULL || zval == NULL){ printf("Out of memory, please use a smaller gap value\n"); return; } eyeinit(n, zcolstart, zcolend, zrow, zval, gap);/* Let Z be eye(n,n)*/ /*---------------------------------------*/ /* Step : Output */ plhs[0] = mxCreateSparse(n,n,rnzmax,mxREAL); ljc = mxGetJc(plhs[0]); lir = mxGetIr(plhs[0]); lpr = mxGetPr(plhs[0]); /*Step 4: Compute L*/ numofnz = 0; for(j=0;j<n;j++) { pjj = 0; tmpAzj = (double *)mxCalloc(m,sizeof(double)); matxvec(n,ajc,air,apr,zcolstart,zcolend,zrow,zval,j,tmpAzj); for(k=0;k<m;k++) if(tmpAzj[k] != 0)pjj += tmpAzj[k] * tmpAzj[k]; if(mu != 0){ for(i = zcolstart[j]; i <= zcolend[j]; i++) pjj -= mu * mu * zval[i] * zval[i]; } ljc[j] = numofnz; lir[numofnz] = j; lpr[numofnz] = sqrt(absval(pjj)); tmpljj = lpr[numofnz]; numofnz = numofnz + 1; if(tmpljj < 2.2e-16 ){ lpr[numofnz-1] = (threshold[j]>0)?threshold[j]:2.2e-16; continue; } for(i=j+1;i<n;i++) { pij = 0; for(k=ajc[i];k<ajc[i+1];k++) { tmprowind = air[k]; pij += apr[k] * tmpAzj[tmprowind]; } zji = 0; for(k=zcolend[i];k>=zcolstart[i];k--) { if(zrow[k]==j)zji = zval[k]; } pij -= mu * mu * zji; lambda = pij / pjj; tmplij = pij / tmpljj * signfun(pjj); if(absval(tmplij) > threshold[i]) { lir[numofnz] = i; lpr[numofnz] = tmplij; numofnz = numofnz + 1; addspvecs(zcolstart,zcolend,zrow,zval,i,j,-lambda,eta2); } } mxFree(tmpAzj); } ljc[n] = numofnz; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { ASL_pfgh *asl = (ASL_pfgh*)cur_ASL; FILE *nl; Jmp_buf err_jmp0; cgrad *cg, **cgp; char *buf1, buf[512], *what, **whatp; fint *hcs, *hr, i, nerror; int *cs; mwIndex *Ir, *Jc; real *H, *He, *J1, *W, *c, *f, *g, *v, *t, *x; static fint n, nc, nhnz, nz; static real *Hsp; static char ignore_complementarity[] = "Warning: ignoring %d complementarity conditions.\n"; if (nrhs == 1 && mxIsChar(prhs[0])) { if (nlhs < 6 || nlhs > 7) usage(); if (mxGetString(prhs[0], buf1 = buf, sizeof(buf))) mexErrMsgTxt("Expected 'stub' as argument\n"); at_end(); mexAtExit(at_end); asl = (ASL_pfgh*)ASL_alloc(ASL_read_pfgh); return_nofile = 1; if (!(nl = jac0dim(buf1,strlen(buf)))) { sprintf(msgbuf, "Can't open %.*s\n", sizeof(msgbuf)-20, buf); mexErrMsgTxt(msgbuf); } if (n_obj <= 0) printf("Warning: objectve == 0\n"); n = n_var; nc = n_con; nz = nzc; X0 = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL)); LUv = mxGetPr(plhs[1] = mxCreateDoubleMatrix(n, 1, mxREAL)); Uvx = mxGetPr(plhs[2] = mxCreateDoubleMatrix(n, 1, mxREAL)); pi0 = mxGetPr(plhs[3] = mxCreateDoubleMatrix(nc, 1, mxREAL)); LUrhs = mxGetPr(plhs[4] = mxCreateDoubleMatrix(nc, 1, mxREAL)); Urhsx = mxGetPr(plhs[5] = mxCreateDoubleMatrix(nc, 1, mxREAL)); if (nlhs == 7) { cvar = (int*)M1alloc(nc*sizeof(int)); plhs[6] = mxCreateDoubleMatrix(nc, 1, mxREAL); x = mxGetPr(plhs[6]); } else if (n_cc) printf(ignore_complementarity, n_cc); pfgh_read(nl, ASL_findgroups); if (nlhs == 7) for(i = 0; i < nc; i++) x[i] = cvar[i]; /* Arrange to compute the whole sparese Hessian */ /* of the Lagrangian function (both triangles). */ nhnz = sphsetup(0, 0, nc > 0, 0); Hsp = (real *)M1alloc(nhnz*sizeof(real)); return; } if (!asl) mexErrMsgTxt("spamfunc(\"stub\") has not been called\n"); nerror = -1; err_jmp1 = &err_jmp0; what = "(?)"; whatp = &what; if (nlhs == 2) { if (nrhs != 2) usage(); x = sizechk(prhs[0],"x",n); t = sizechk(prhs[1],"0 or 1", 1); if (setjmp(err_jmp0.jb)) { sprintf(msgbuf, "Trouble evaluating %s\n", *whatp); mexErrMsgTxt(msgbuf); } if (t[0] == 0.) { f = mxGetPr(plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL)); c = mxGetPr(plhs[1] = mxCreateDoubleMatrix(nc, 1, mxREAL)); what = "f"; *f = n_obj > 0 ? objval(0, x, &nerror) : 0; what = "c"; conval(x, c, &nerror); return; } g = mxGetPr(plhs[0] = mxCreateDoubleMatrix(n, 1, mxREAL)); J1 = mxGetPr(plhs[1] = mxCreateSparse(nc, n, nz, mxREAL)); what = "g"; if (n_obj > 0) objgrd(0, x, g, &nerror); else memset(g, 0, n*sizeof(real)); if (nc) { what = "J"; jacval(x, J1, &nerror); Ir = mxGetIr(plhs[1]); /*memcpy(mxGetJc(plhs[1]), A_colstarts, (n+1)*sizeof(int));*/ for(Jc = mxGetJc(plhs[1]), cs = A_colstarts, i = 0; i <= n; ++i) Jc[i] = cs[i]; cgp = Cgrad; for(i = 0; i < nc; i++) for(cg = *cgp++; cg; cg = cg->next) Ir[cg->goff] = i; } return; } if (nlhs == 0 && (nrhs == 3 || nrhs == 4)) { /* eval2('solution message', x, v): x = primal, v = dual */ /* optional 4th arg = solve_result_num */ if (!mxIsChar(prhs[0])) usage(); x = sizechk(prhs[1],"x",n); v = sizechk(prhs[2],"v",nc); if (mxGetString(prhs[0], buf, sizeof(buf))) mexErrMsgTxt( "Expected 'solution message' as first argument\n"); solve_result_num = nrhs == 3 ? -1 /* unknown */ : (int)*sizechk(prhs[3],"solve_result_num",1); write_sol(buf, x, v, 0); return; } if (nlhs != 1 || nrhs != 1) usage(); v = sizechk(prhs[0],"v",nc); W = mxGetPr(plhs[0] = mxCreateSparse(n, n, nhnz, mxREAL)); what = "W"; sphes(H = Hsp, 0, 0, v); /* Expand the Hessian lower triangle into the full Hessian... */ Ir = mxGetIr(plhs[0]); Jc = mxGetJc(plhs[0]); hcs = sputinfo->hcolstarts; hr = sputinfo->hrownos; for(i = 0; i <= n; i++) Jc[i] = hcs[i]; He = H + hcs[n]; while(H < He) { *W++ = *H++; *Ir++ = *hr++; } }
void multiply_null_by_spPot(mxArray *bigPot, const mxArray *smallPot){ int i, j, count, count1, match, temp, bdim, sdim, diffdim, NB, NS, ND, NZB, NZS, bindex, sindex, nzCounts=0; int *samemask, *diffmask, *sir, *sjc, *bCumprod, *sCumprod, *ssubv, *sequence, *weight; double *bigTable, *pbDomain, *psDomain, *pbSize, *psSize, *spr; mxArray *pTemp, *pTemp1; pTemp = mxGetField(bigPot, 0, "domain"); pbDomain = mxGetPr(pTemp); bdim = mxGetNumberOfElements(pTemp); pTemp = mxGetField(smallPot, 0, "domain"); psDomain = mxGetPr(pTemp); sdim = mxGetNumberOfElements(pTemp); pTemp = mxGetField(bigPot, 0, "sizes"); pbSize = mxGetPr(pTemp); pTemp = mxGetField(smallPot, 0, "sizes"); psSize = mxGetPr(pTemp); NB = 1; for(i=0; i<bdim; i++){ NB *= (int)pbSize[i]; } NS = 1; for(i=0; i<sdim; i++){ NS *= (int)psSize[i]; } ND = NB / NS; if(ND == 1){ pTemp = mxGetField(bigPot, 0, "T"); if(pTemp)mxDestroyArray(pTemp); pTemp1 = mxGetField(smallPot, 0, "T"); pTemp = mxDuplicateArray(pTemp1); mxSetField(bigPot, 0, "T", pTemp); return; } pTemp = mxGetField(smallPot, 0, "T"); spr = mxGetPr(pTemp); sir = mxGetIr(pTemp); sjc = mxGetJc(pTemp); NZS = sjc[1]; NZB = ND * NZS; diffdim = bdim - sdim; sequence = malloc(NZB * 2 * sizeof(int)); bigTable = malloc(NZB * sizeof(double)); samemask = malloc(sdim * sizeof(int)); diffmask = malloc(diffdim * sizeof(int)); bCumprod = malloc(bdim * sizeof(int)); sCumprod = malloc(sdim * sizeof(int)); weight = malloc(ND * sizeof(int)); ssubv = malloc(sdim * sizeof(int)); count = 0; count1 = 0; for(i=0; i<bdim; i++){ match = 0; for(j=0; j<sdim; j++){ if(pbDomain[i] == psDomain[j]){ samemask[count] = i; match = 1; count++; break; } } if(match == 0){ diffmask[count1] = i; count1++; } } bCumprod[0] = 1; for(i=0; i<bdim-1; i++){ bCumprod[i+1] = bCumprod[i] * (int)pbSize[i]; } sCumprod[0] = 1; for(i=0; i<sdim-1; i++){ sCumprod[i+1] = sCumprod[i] * (int)psSize[i]; } count = 0; compute_fixed_weight(weight, pbSize, diffmask, bCumprod, ND, diffdim); for(i=0; i<NZS; i++){ sindex = sir[i]; ind_subv(sindex, sCumprod, sdim, ssubv); temp = 0; for(j=0; j<sdim; j++){ temp += ssubv[j] * bCumprod[samemask[j]]; } for(j=0; j<ND; j++){ bindex = weight[j] + temp; bigTable[nzCounts] = spr[i]; sequence[count] = bindex; count++; sequence[count] = nzCounts; nzCounts++; count++; } } pTemp = mxGetField(bigPot, 0, "T"); if(pTemp)mxDestroyArray(pTemp); qsort(sequence, nzCounts, sizeof(int) * 2, compare); pTemp = convert_ill_table_to_sparse(bigTable, sequence, nzCounts, NB); mxSetField(bigPot, 0, "T", pTemp); free(sequence); free(bigTable); free(samemask); free(diffmask); free(bCumprod); free(sCumprod); free(weight); free(ssubv); }
/* * s e t u p H e s s i a n M a t r i x */ returnValue setupHessianMatrix( const mxArray* prhsH, int_t nV, SymmetricMatrix** H, sparse_int_t** Hir, sparse_int_t** Hjc, real_t** Hv ) { if ( prhsH == 0 ) return SUCCESSFUL_RETURN; if ( mxIsSparse( prhsH ) != 0 ) { mwIndex *mat_ir = mxGetIr( prhsH ); mwIndex *mat_jc = mxGetJc( prhsH ); double *v = (double*)mxGetPr( prhsH ); sparse_int_t nfill = 0; mwIndex i, j; BooleanType needInsertDiag; /* copy indices to avoid 64/32-bit integer confusion */ /* also add explicit zeros on diagonal for regularization strategy */ /* copy values, too */ *Hir = new sparse_int_t[mat_jc[nV] + nV]; *Hjc = new sparse_int_t[nV+1]; *Hv = new real_t[mat_jc[nV] + nV]; for (j = 0; j < nV; j++) { needInsertDiag = BT_TRUE; (*Hjc)[j] = (sparse_int_t)(mat_jc[j]) + nfill; /* fill up to diagonal */ for (i = mat_jc[j]; i < mat_jc[j+1]; i++) { if ( mat_ir[i] == j ) needInsertDiag = BT_FALSE; /* add zero diagonal element if not present */ if ( ( mat_ir[i] > j ) && ( needInsertDiag == BT_TRUE ) ) { (*Hir)[i + nfill] = (sparse_int_t)j; (*Hv)[i + nfill] = 0.0; nfill++; /* only add diag once */ needInsertDiag = BT_FALSE; } (*Hir)[i + nfill] = (sparse_int_t)(mat_ir[i]); (*Hv)[i + nfill] = (real_t)(v[i]); } } (*Hjc)[nV] = (sparse_int_t)(mat_jc[nV]) + nfill; SymSparseMat *sH; *H = sH = new SymSparseMat(nV, nV, *Hir, *Hjc, *Hv); sH->createDiagInfo(); } else { /* make a deep-copy in order to avoid modifying input data when regularising */ real_t* H_for = (real_t*) mxGetPr( prhsH ); real_t* H_mem = new real_t[nV*nV]; memcpy( H_mem,H_for, nV*nV*sizeof(real_t) ); *H = new SymDenseMat( nV,nV,nV, H_mem ); (*H)->doFreeMemory( ); } return SUCCESSFUL_RETURN; }
void multiply_spPot_by_spPot(mxArray *bigPot, const mxArray *smallPot){ int i, j, count, bdim, sdim, NB, NZB, NZS, position, bindex, sindex, nzCounts=0; int *mask, *index, *result, *bir, *sir, *bjc, *sjc, *bCumprod, *sCumprod, *bsubv, *ssubv; double *bigTable, *pbDomain, *psDomain, *pbSize, *psSize, *bpr, *spr, value; mxArray *pTemp; pTemp = mxGetField(bigPot, 0, "domain"); pbDomain = mxGetPr(pTemp); bdim = mxGetNumberOfElements(pTemp); pTemp = mxGetField(smallPot, 0, "domain"); psDomain = mxGetPr(pTemp); sdim = mxGetNumberOfElements(pTemp); pTemp = mxGetField(bigPot, 0, "sizes"); pbSize = mxGetPr(pTemp); pTemp = mxGetField(smallPot, 0, "sizes"); psSize = mxGetPr(pTemp); NB = 1; for(i=0; i<bdim; i++){ NB *= (int)pbSize[i]; } pTemp = mxGetField(bigPot, 0, "T"); bpr = mxGetPr(pTemp); bir = mxGetIr(pTemp); bjc = mxGetJc(pTemp); NZB = bjc[1]; pTemp = mxGetField(smallPot, 0, "T"); spr = mxGetPr(pTemp); sir = mxGetIr(pTemp); sjc = mxGetJc(pTemp); NZS = sjc[1]; bigTable = malloc(NZB * sizeof(double)); index = malloc(NZB * sizeof(double)); mask = malloc(sdim * sizeof(int)); bCumprod = malloc(bdim * sizeof(int)); sCumprod = malloc(sdim * sizeof(int)); bsubv = malloc(bdim * sizeof(int)); ssubv = malloc(sdim * sizeof(int)); for(i=0; i<NZB; i++){ bigTable[i] = 0; } count = 0; for(i=0; i<sdim; i++){ for(j=0; j<bdim; j++){ if(psDomain[i] == pbDomain[j]){ mask[count] = j; count++; break; } } } bCumprod[0] = 1; for(i=0; i<bdim-1; i++){ bCumprod[i+1] = bCumprod[i] * (int)pbSize[i]; } sCumprod[0] = 1; for(i=0; i<sdim-1; i++){ sCumprod[i+1] = sCumprod[i] * (int)psSize[i]; } for(i=0; i<NZB; i++){ value = bpr[i]; bindex = bir[i]; ind_subv(bindex, bCumprod, bdim, bsubv); for(j=0; j<sdim; j++){ ssubv[j] = bsubv[mask[j]]; } sindex = subv_ind(sdim, sCumprod, ssubv); result = (int *) bsearch(&sindex, sir, NZS, sizeof(int), compare); if(result){ position = result - sir; value *= spr[position]; bigTable[nzCounts] = value; index[nzCounts] = bindex; nzCounts++; } } pTemp = mxGetField(bigPot, 0, "T"); if(pTemp)mxDestroyArray(pTemp); pTemp = convert_table_to_sparse(bigTable, index, nzCounts, NB); mxSetField(bigPot, 0, "T", pTemp); free(bigTable); free(index); free(mask); free(bCumprod); free(sCumprod); free(bsubv); free(ssubv); }
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { double *m_w_d, *p_w_z, *p_z_d, *p_w_d; mwIndex *ir, *jc; size_t d, k; size_t n_w, n_d, n_z; mwSize ndim = 1, dims[1]; mwSize nsubs = 1; mxArray *temp_array; double *temp; size_t beg_row_id, end_row_id, cur_row_id; mwIndex index, subs[1]; mwIndex *beg_of_ir, *beg_of_jc; mwSize nzmax; size_t total = 0; if(!mxIsSparse(prhs[0])) { printf("word-doc matrix should be sparse matrix\n"); return; } else if(nrhs != 4 || nlhs != 1) { printf("usage: p_z_wd = mex_Estep_sparse(m_w_d, p_w_z_n, p_z_d_n, p_w_d)\n"); return; } m_w_d = mxGetPr(prhs[0]); jc = mxGetJc(prhs[0]); ir = mxGetIr(prhs[0]); nzmax = mxGetNzmax(prhs[0]); n_w = mxGetM(prhs[0]); n_d = mxGetN(prhs[0]); p_w_z = mxGetPr(prhs[1]); n_z = mxGetN(prhs[1]); p_z_d = mxGetPr(prhs[2]); p_w_d = mxGetPr(prhs[3]); dims[0] = n_z; plhs[0] = mxCreateCellArray(ndim, dims); //total_num_of_cells = mxGetNumberOfElements(plhs[0]); for(k = 0; k < n_z; k++) { total = 0; subs[0] = k; index = mxCalcSingleSubscript(plhs[0], nsubs, subs); temp_array = mxCreateSparse(n_w, n_d, nzmax, mxREAL); temp = mxGetPr(temp_array); mxSetNzmax(temp_array, nzmax); //Place ir data into the newly created sparse array. beg_of_ir = mxGetIr(temp_array); memcpy(beg_of_ir, ir, nzmax * sizeof(mwIndex)); //Place jc data into the newly created sparse array. beg_of_jc = mxGetJc(temp_array); memcpy(beg_of_jc, jc, (n_d + 1) * sizeof(mwIndex)); for (d = 0; d < n_d; d++) { beg_row_id = jc[d]; end_row_id = jc[d + 1]; if (beg_row_id == end_row_id) continue; else { for (cur_row_id = beg_row_id; cur_row_id < end_row_id; cur_row_id++) { temp[total] = p_w_z[k * n_w + ir[cur_row_id]] * p_z_d[d * n_z + k] / p_w_d[total]; total++; } } } mxSetCell(plhs[0], index, temp_array); } return; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *srwp, *srdp, *srtd, *probs, *Z, *WS, *DS, *ZIN; double ALPHA,BETA; mwIndex *irwp, *jcwp, *irdp, *jcdp, *irtd, *jctd; int *z,*d,*w, *order, *wp, *ztot; int W,T,D,NN,SEED,OUTPUT, nzmax, nzmaxwp, nzmaxdp, ntokens; int i,j,c,n,nt,wi,di, startcond, n1,n2, TAVAIL, topic; /* Check for proper number of arguments. */ if (nrhs < 8) { mexErrMsgTxt("At least 8 input arguments required"); } else if (nlhs < 3) { mexErrMsgTxt("3 output arguments required"); } startcond = 0; if (nrhs == 9) startcond = 1; /* process the input arguments */ if (mxIsDouble( prhs[ 0 ] ) != 1) mexErrMsgTxt("WS input vector must be a double precision matrix"); if (mxIsDouble( prhs[ 1 ] ) != 1) mexErrMsgTxt("DS input vector must be a double precision matrix"); // pointer to word indices WS = mxGetPr( prhs[ 0 ] ); // pointer to document indices DS = mxGetPr( prhs[ 1 ] ); // get the number of tokens ntokens = (int) mxGetM( prhs[ 0 ] ) * (int) mxGetN( prhs[ 0 ] ); if (ntokens == 0) mexErrMsgTxt("WS vector is empty"); if (ntokens != ( mxGetM( prhs[ 1 ] ) * mxGetN( prhs[ 1 ] ))) mexErrMsgTxt("WS and DS vectors should have same number of entries"); // Input Sparse-Tag-Document Matrix srtd = mxGetPr(prhs[2]); irtd = mxGetIr(prhs[2]); jctd = mxGetJc(prhs[2]); nzmaxdp = (int) mxGetNzmax(prhs[2]); // number of nonzero entries in tag-document matrix NN = (int) mxGetScalar(prhs[3]); if (NN<0) mexErrMsgTxt("Number of iterations must be positive"); ALPHA = (double) mxGetScalar(prhs[4]); if (ALPHA<=0) mexErrMsgTxt("ALPHA must be greater than zero"); BETA = (double) mxGetScalar(prhs[5]); if (BETA<=0) mexErrMsgTxt("BETA must be greater than zero"); SEED = (int) mxGetScalar(prhs[6]); OUTPUT = (int) mxGetScalar(prhs[7]); if (startcond == 1) { ZIN = mxGetPr( prhs[ 8 ] ); if (ntokens != ( mxGetM( prhs[ 8 ] ) * mxGetN( prhs[ 8 ] ))) mexErrMsgTxt("WS and ZIN vectors should have same number of entries"); } // seeding seedMT( 1 + SEED * 2 ); // seeding only works on uneven numbers /* allocate memory */ z = (int *) mxCalloc( ntokens , sizeof( int )); if (startcond == 1) { for (i=0; i<ntokens; i++) z[ i ] = (int) ZIN[ i ] - 1; } d = (int *) mxCalloc( ntokens , sizeof( int )); w = (int *) mxCalloc( ntokens , sizeof( int )); order = (int *) mxCalloc( ntokens , sizeof( int )); // copy over the word and document indices into internal format for (i=0; i<ntokens; i++) { w[ i ] = (int) WS[ i ] - 1; d[ i ] = (int) DS[ i ] - 1; } n = ntokens; W = 0; D = 0; for (i=0; i<n; i++) { if (w[ i ] > W) W = w[ i ]; if (d[ i ] > D) D = d[ i ]; } W = W + 1; D = D + 1; // Number of topics is based on number of tags in sparse tag-document matrix T = (int) mxGetM( prhs[ 2 ] ); // check number of docs in sparse tag-document matrix if (D != (int) mxGetN( prhs[ 2 ])) mexErrMsgTxt("Mismatch in number of documents in DS vector TAGSET sparse matrix"); ztot = (int *) mxCalloc( T , sizeof( int )); probs = (double *) mxCalloc( T , sizeof( double )); wp = (int *) mxCalloc( T*W , sizeof( int )); // create sparse DP matrix that is T x D and not the other way around !!!! plhs[1] = mxCreateSparse( T,D,nzmaxdp,mxREAL); srdp = mxGetPr(plhs[1]); irdp = mxGetIr(plhs[1]); jcdp = mxGetJc(plhs[1]); // now copy the structure from TD over to DP for (i=0; i<D; i++) { n1 = (int) *( jctd + i ); n2 = (int) *( jctd + i + 1 ); // copy over the row-index start and end indices *( jcdp + i ) = (int) n1; // number of available topics for this document TAVAIL = (n2-n1); for (j = 0; j < TAVAIL; j++) { topic = (int) *( irtd + n1 + j ); *( irdp + n1 + j ) = topic; *( srdp + n1 + j ) = 0; // initialize DP counts with ZERO } } // copy over final column indices n1 = (int) *( jctd + D ); *( jcdp + D ) = (int) n1; if (OUTPUT==2) { mexPrintf( "Running LDA Gibbs Sampler Version 1.0\n" ); if (startcond==1) mexPrintf( "Starting from previous state ZIN\n" ); mexPrintf( "Arguments:\n" ); mexPrintf( "\tNumber of words W = %d\n" , W ); mexPrintf( "\tNumber of docs D = %d\n" , D ); mexPrintf( "\tNumber of tags T = %d\n" , T ); mexPrintf( "\tNumber of iterations N = %d\n" , NN ); mexPrintf( "\tHyperparameter ALPHA = %4.4f\n" , ALPHA ); mexPrintf( "\tHyperparameter BETA = %4.4f\n" , BETA ); mexPrintf( "\tSeed number = %d\n" , SEED ); mexPrintf( "\tNumber of tokens = %d\n" , ntokens ); mexPrintf( "\tNumber of nonzeros in tag matrix = %d\n" , nzmaxdp ); } /* run the model */ GibbsSamplerLDA( ALPHA, BETA, W, T, D, NN, OUTPUT, n, z, d, w, wp, ztot, order, probs, startcond, irtd, jctd, srdp, irdp, jcdp ); /* convert the full wp matrix into a sparse matrix */ nzmaxwp = 0; for (i=0; i<W; i++) { for (j=0; j<T; j++) nzmaxwp += (int) ( *( wp + j + i*T )) > 0; } // MAKE THE WP SPARSE MATRIX plhs[0] = mxCreateSparse( W,T,nzmaxwp,mxREAL); srwp = mxGetPr(plhs[0]); irwp = mxGetIr(plhs[0]); jcwp = mxGetJc(plhs[0]); n = 0; for (j=0; j<T; j++) { *( jcwp + j ) = n; for (i=0; i<W; i++) { c = (int) *( wp + i*T + j ); if (c >0) { *( srwp + n ) = c; *( irwp + n ) = i; n++; } } } *( jcwp + T ) = n; plhs[ 2 ] = mxCreateDoubleMatrix( 1,ntokens , mxREAL ); Z = mxGetPr( plhs[ 2 ] ); for (i=0; i<ntokens; i++) Z[ i ] = (double) z[ i ] + 1; }
// USAGE // [bestset,cond,cut,vol] = hkgrow_mex(A,set,t,eps,debugflag) // Note that targetvol is currently ignored void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { if (nrhs != 5) { mexErrMsgIdAndTxt("hkgrow_mex:notEnoughArguments", "hkgrow_mex needs six arguments not %i", nrhs); } debugflag = (int)mxGetScalar(prhs[4]); DEBUGPRINT(("hkgrow_mex: preprocessing start: \n")); const mxArray* mat = prhs[0]; const mxArray* set = prhs[1]; mxAssert(mxIsSparse(mat), "Input matrix is not sparse"); mxAssert(mxGetM(mat) == mxGetN(mat), "Input matrix not square"); mxArray* cond = mxCreateDoubleMatrix(1,1,mxREAL); mxArray* cut = mxCreateDoubleMatrix(1,1,mxREAL); mxArray* vol = mxCreateDoubleMatrix(1,1,mxREAL); if (nlhs > 1) { plhs[1] = cond; } if (nlhs > 2) { plhs[2] = cut; } if (nlhs > 3) { plhs[3] = vol; } mxAssert(nlhs <= 4, "Too many output arguments"); double eps = pow(10,-3); double t = 15.; if (nrhs >= 4) { t = mxGetScalar(prhs[2]); eps = mxGetScalar(prhs[3]); } sparserow r; r.m = mxGetM(mat); r.n = mxGetN(mat); r.ai = mxGetJc(mat); r.aj = mxGetIr(mat); r.a = mxGetPr(mat); std::vector< mwIndex > seeds; copy_array_to_index_vector( set, seeds ); DEBUGPRINT(("hkgrow_mex: preprocessing end: \n")); hkgrow(&r, seeds, t, eps, mxGetPr(cond), mxGetPr(cut), mxGetPr(vol) ); DEBUGPRINT(("hkgrow_mex: call to hkgrow() done\n")); if (nlhs > 0) { mxArray* cassign = mxCreateDoubleMatrix(seeds.size(),1,mxREAL); plhs[0] = cassign; double *ci = mxGetPr(cassign); for (size_t i=0; i<seeds.size(); ++i) { ci[i] = (double)(seeds[i] + 1); } } }
void mexFunction ( /* === Parameters ======================================================= */ int nlhs, /* number of left-hand sides */ mxArray *plhs [], /* left-hand side matrices */ int nrhs, /* number of right--hand sides */ const mxArray *prhs [] /* right-hand side matrices */ ) { /* === Local variables ================================================== */ Long *perm ; /* column ordering of M and ordering of A */ Long *A ; /* row indices of input matrix A */ Long *p ; /* column pointers of input matrix A */ Long n_col ; /* number of columns of A */ Long n_row ; /* number of rows of A */ Long full ; /* TRUE if input matrix full, FALSE if sparse */ double knobs [COLAMD_KNOBS] ; /* colamd user-controllable parameters */ double *out_perm ; /* output permutation vector */ double *out_stats ; /* output stats vector */ double *in_knobs ; /* input knobs vector */ Long i ; /* loop counter */ mxArray *Ainput ; /* input matrix handle */ Long spumoni ; /* verbosity variable */ Long stats [COLAMD_STATS] ; /* stats for symamd */ colamd_printf = mexPrintf ; /* COLAMD printf routine */ /* === Check inputs ===================================================== */ if (nrhs < 1 || nrhs > 2 || nlhs < 0 || nlhs > 2) { mexErrMsgTxt ( "symamd: incorrect number of input and/or output arguments.") ; } /* === Get knobs ======================================================== */ colamd_l_set_defaults (knobs) ; spumoni = 0 ; /* check for user-passed knobs */ if (nrhs == 2) { in_knobs = mxGetPr (prhs [1]) ; i = mxGetNumberOfElements (prhs [1]) ; if (i > 0) knobs [COLAMD_DENSE_ROW] = in_knobs [0] ; if (i > 1) spumoni = (Long) (in_knobs [1] != 0) ; } /* print knob settings if spumoni is set */ if (spumoni) { mexPrintf ("\nsymamd version %d.%d, %s:\n", COLAMD_MAIN_VERSION, COLAMD_SUB_VERSION, COLAMD_DATE) ; if (knobs [COLAMD_DENSE_ROW] >= 0) { mexPrintf ("knobs(1): %g, rows/cols with > " "max(16,%g*sqrt(size(A,2))) entries removed\n", in_knobs [0], knobs [COLAMD_DENSE_ROW]) ; } else { mexPrintf ("knobs(1): %g, no dense rows removed\n", in_knobs [0]) ; } mexPrintf ("knobs(2): %g, statistics and knobs printed\n", in_knobs [1]) ; } /* === If A is full, convert to a sparse matrix ========================= */ Ainput = (mxArray *) prhs [0] ; if (mxGetNumberOfDimensions (Ainput) != 2) { mexErrMsgTxt ("symamd: input matrix must be 2-dimensional.") ; } full = !mxIsSparse (Ainput) ; if (full) { mexCallMATLAB (1, &Ainput, 1, (mxArray **) prhs, "sparse") ; } /* === Allocate workspace for symamd ==================================== */ /* get size of matrix */ n_row = mxGetM (Ainput) ; n_col = mxGetN (Ainput) ; if (n_col != n_row) { mexErrMsgTxt ("symamd: matrix must be square.") ; } A = (Long *) mxGetIr (Ainput) ; p = (Long *) mxGetJc (Ainput) ; perm = (Long *) mxCalloc (n_col+1, sizeof (Long)) ; /* === Order the rows and columns of A (does not destroy A) ============= */ if (!symamd_l (n_col, A, p, perm, knobs, stats, &mxCalloc, &mxFree)) { symamd_l_report (stats) ; mexErrMsgTxt ("symamd error!") ; } if (full) { mxDestroyArray (Ainput) ; } /* === Return the permutation vector ==================================== */ plhs [0] = mxCreateDoubleMatrix (1, n_col, mxREAL) ; out_perm = mxGetPr (plhs [0]) ; for (i = 0 ; i < n_col ; i++) { /* symamd is 0-based, but MATLAB expects this to be 1-based */ out_perm [i] = perm [i] + 1 ; } mxFree (perm) ; /* === Return the stats vector ========================================== */ /* print stats if spumoni is set */ if (spumoni) { symamd_l_report (stats) ; } if (nlhs == 2) { plhs [1] = mxCreateDoubleMatrix (1, COLAMD_STATS, mxREAL) ; out_stats = mxGetPr (plhs [1]) ; for (i = 0 ; i < COLAMD_STATS ; i++) { out_stats [i] = stats [i] ; } /* fix stats (5) and (6), for 1-based information on jumbled matrix. */ /* note that this correction doesn't occur if symamd returns FALSE */ out_stats [COLAMD_INFO1] ++ ; out_stats [COLAMD_INFO2] ++ ; } }
/******************************************************************** PROCEDURE mexFunction - Entry for Matlab *********************************************************************/ void mexFunction(const int nlhs, mxArray *plhs[], const int nrhs, const mxArray *prhs[]) { int n; double *X, *dd; int *irX, *jcX; int isspX, j, jn, k, kstart, kend, r; int options; double tmp, tmp2, ddtmp; if(nrhs < 2) mexErrMsgTxt("mexschurfun: requires at least 2 input arguments."); if(nlhs > 0) mexErrMsgTxt("mexschurfun: requires no output argument."); X = mxGetPr(prhs[0]); isspX = mxIsSparse(prhs[0]); if (isspX) { irX = mxGetIr(prhs[0]); jcX = mxGetJc(prhs[0]); } n = mxGetM(prhs[0]); if ( n != mxGetN(prhs[0]) ) mexErrMsgTxt("X should be square."); dd = mxGetPr(prhs[1]); if (mxIsSparse(prhs[1])) mexErrMsgTxt("Sparse dd not supported by mexschurfun."); if (nrhs == 2) { options = 1; } else { options = (int) (*mxGetPr(prhs[2])); ddtmp = dd[0]; } /********************************************************/ if (options==1) { if (isspX) { for (j=0; j<n; j++) { kstart = jcX[j]; kend = jcX[j+1]; for (k=kstart; k<kend; k++) { r = irX[k]; if (r==j) { X[k] += dd[j]; break; } } } } else { for (j=0; j<n; j++) { jn = j*n; X[j+jn] += dd[j]; } } } else { if (isspX) { for (j=0; j<n; j++) { kstart = jcX[j]; kend = jcX[j+1]; for (k=kstart; k<kend; k++) { r = irX[k]; X[k] += ddtmp; } } } else { for (j=0; j<n; j++) { jn = j*n; for (k=0; k<n; k++) { X[k+jn] += ddtmp; } } } } return; }
struct svm_model *matlab_matrix_to_model(const mxArray *matlab_struct, const char **msg) { int i, j, n, num_of_fields; double *ptr; int id = 0; struct svm_node *x_space; struct svm_model *model; mxArray **rhs; num_of_fields = mxGetNumberOfFields(matlab_struct); if(num_of_fields != NUM_OF_RETURN_FIELD) { *msg = "number of return field is not correct"; return NULL; } rhs = (mxArray **) mxMalloc(sizeof(mxArray *)*num_of_fields); for(i=0;i<num_of_fields;i++) rhs[i] = mxGetFieldByNumber(matlab_struct, 0, i); model = Malloc(struct svm_model, 1); model->rho = NULL; model->probA = NULL; model->probB = NULL; model->label = NULL; model->nSV = NULL; model->free_sv = 1; /* XXX */ ptr = mxGetPr(rhs[id]); model->param.svm_type = (int)ptr[0]; model->param.kernel_type = (int)ptr[1]; model->param.degree = (int)ptr[2]; model->param.gamma = ptr[3]; model->param.coef0 = ptr[4]; id++; ptr = mxGetPr(rhs[id]); model->nr_class = (int)ptr[0]; id++; ptr = mxGetPr(rhs[id]); model->l = (int)ptr[0]; id++; /* rho */ n = model->nr_class * (model->nr_class-1)/2; model->rho = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->rho[i] = ptr[i]; id++; /* label */ if(mxIsEmpty(rhs[id]) == 0) { model->label = (int*) malloc(model->nr_class*sizeof(int)); ptr = mxGetPr(rhs[id]); for(i=0;i<model->nr_class;i++) model->label[i] = (int)ptr[i]; } id++; /* probA */ if(mxIsEmpty(rhs[id]) == 0) { model->probA = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->probA[i] = ptr[i]; } id++; /* probB */ if(mxIsEmpty(rhs[id]) == 0) { model->probB = (double*) malloc(n*sizeof(double)); ptr = mxGetPr(rhs[id]); for(i=0;i<n;i++) model->probB[i] = ptr[i]; } id++; /* nSV */ if(mxIsEmpty(rhs[id]) == 0) { model->nSV = (int*) malloc(model->nr_class*sizeof(int)); ptr = mxGetPr(rhs[id]); for(i=0;i<model->nr_class;i++) model->nSV[i] = (int)ptr[i]; } id++; /* sv_coef */ ptr = mxGetPr(rhs[id]); model->sv_coef = (double**) malloc((model->nr_class-1)*sizeof(double)); for( i=0 ; i< model->nr_class -1 ; i++ ) model->sv_coef[i] = (double*) malloc((model->l)*sizeof(double)); for(i = 0; i < model->nr_class - 1; i++) for(j = 0; j < model->l; j++) model->sv_coef[i][j] = ptr[i*(model->l)+j]; id++; /* SV */ { int sr, sc, elements; int num_samples; mwIndex *ir, *jc; mxArray *pprhs[1], *pplhs[1]; /* transpose SV */ pprhs[0] = rhs[id]; if(mexCallMATLAB(1, pplhs, 1, pprhs, "transpose")) { svm_destroy_model(model); *msg = "cannot transpose SV matrix"; return NULL; } rhs[id] = pplhs[0]; sr = (int)mxGetN(rhs[id]); sc = (int)mxGetM(rhs[id]); ptr = mxGetPr(rhs[id]); ir = mxGetIr(rhs[id]); jc = mxGetJc(rhs[id]); num_samples = (int)mxGetNzmax(rhs[id]); elements = num_samples + sr; model->SV = (struct svm_node **) malloc(sr * sizeof(struct svm_node *)); x_space = (struct svm_node *)malloc(elements * sizeof(struct svm_node)); /* SV is in column */ for(i=0;i<sr;i++) { int low = (int)jc[i], high = (int)jc[i+1]; int x_index = 0; model->SV[i] = &x_space[low+i]; for(j=low;j<high;j++) { model->SV[i][x_index].index = (int)ir[j] + 1; model->SV[i][x_index].value = ptr[j]; x_index++; } model->SV[i][x_index].index = -1; } id++; } mxFree(rhs); return model; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *A, *y; mwIndex *irA, *jcA, *iry, *jcy; double *ytmp, *Ay; int isspA, isspy, options; int m1, n1, m2, n2, j, jm1; int i, r, k, istart, iend, kstart, kend; double tmp; /* CHECK THE DIMENSIONS */ if (mxIsCell(prhs[0]) || mxIsCell(prhs[1])) { mexErrMsgTxt(" mexMatvec: A, x must be a double array"); } if (nrhs <2) { mexErrMsgTxt(" mexMatvec: must have at least 2 inputs"); } if (nlhs > 2) { mexErrMsgTxt("mexMatvec: requires 1 output argument"); } if (nrhs == 2) { options = 0; } else { options = (int) *mxGetPr(prhs[2]); } /***** assign pointers *****/ A = mxGetPr(prhs[0]); m1 = mxGetM(prhs[0]); n1 = mxGetN(prhs[0]); isspA = mxIsSparse(prhs[0]); if (isspA) { irA = mxGetIr(prhs[0]); jcA = mxGetJc(prhs[0]); } isspy = mxIsSparse(prhs[1]); m2 = mxGetM(prhs[1]); n2 = mxGetN(prhs[1]); if (n2 > 1) { mexErrMsgTxt("mexMatvec: 2ND input must be a column vector"); } if (isspy) { iry = mxGetIr(prhs[1]); jcy = mxGetJc(prhs[1]); ytmp = mxGetPr(prhs[1]); /***** copy ytmp to y *****/ y = (double*)mxCalloc(m2,sizeof(double)); kstart = jcy[0]; kend = jcy[1]; for (k=kstart; k<kend; k++) { r = iry[k]; y[r] = ytmp[k]; } } else { y = mxGetPr(prhs[1]); } if (options == 0 && n1 != m2) { mexErrMsgTxt("mexMatvec: 1ST and 2ND input not compatible."); } else if (options && m1 != m2) { mexErrMsgTxt("mexMatvec: 1ST and 2ND input not compatible."); } /***** create return argument *****/ if (options==0) { plhs[0] = mxCreateDoubleMatrix(m1,1,mxREAL); } else { plhs[0] = mxCreateDoubleMatrix(n1,1,mxREAL); } Ay = mxGetPr(plhs[0]); /***** main body *****/ if (options==0) { if (!isspA) { for (j=0; j<n1; j++){ jm1 = j*m1; tmp = y[j]; if (tmp !=0) { saxpymat(A,jm1,0,m1,tmp,Ay,0); } } } else { for (j=0; j<n1; j++){ tmp = y[j]; if (tmp != 0) { istart = jcA[j]; iend = jcA[j+1]; for (i=istart; i<iend; i++) { r = irA[i]; Ay[r] += tmp*A[i]; } } } } } else { if (!isspA) { for (j=0; j<n1; j++){ jm1 = j*m1; Ay[j] = realdotde(A,jm1,y,m1); } } else { for (j=0; j<n1; j++){ istart = jcA[j]; iend = jcA[j+1]; tmp = 0; for (i=istart; i<iend; i++) { r = irA[i]; tmp += y[r]*A[i]; } Ay[j] = tmp; } } } return; }
/* * The mex function runs a shortest path problem. */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mwIndex mrows, ncols; mwIndex n,nz; /* sparse matrix */ mwIndex *ia, *ja; /* source */ mwIndex u; /* output data */ double *pred; /* * The current calling pattern is * dominator_tree_mex(A,u) * u is the source vertex */ const mxArray* arg_matrix; const mxArray* arg_source; int required_arguments = 2; if (nrhs != required_arguments) { mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument", "the function requires %i arguments, not %i\n", required_arguments, nrhs); } arg_matrix = prhs[0]; arg_source = prhs[1]; u = (mwIndex)load_scalar_arg(arg_source,1); /* The first input must be a sparse matrix. */ mrows = mxGetM(arg_matrix); ncols = mxGetN(arg_matrix); mrows = mxGetM(arg_matrix); ncols = mxGetN(arg_matrix); if (mrows != ncols || !mxIsSparse(arg_matrix)) { mexErrMsgIdAndTxt("matlab_bgl:invalidMexArgument", "the matrix must be sparse and square"); } n = mrows; /* Get the sparse matrix */ /* recall that we've transposed the matrix */ ja = mxGetIr(arg_matrix); ia = mxGetJc(arg_matrix); nz = ia[n]; /* Process the scalar target */ u = u-1; if (u < 0 || u >= n) { mexErrMsgIdAndTxt("matlab_bgl:invalidMexParameter", "start vertex (%i) not a valid vertex.", u+1); } plhs[0] = mxCreateDoubleMatrix(1,n,mxREAL); /* create the output vectors */ pred = mxGetPr(plhs[0]); #ifdef _DEBUG mexPrintf("dominator_tree..."); #endif dominator_tree(n, ja, ia, u, (mwIndex*)pred); #ifdef _DEBUG mexPrintf("done\n"); #endif expand_index_to_double_zero_equality((mwIndex*)pred, pred, n, 1.0); /* expand_index_to_double((mwIndex*)pred, pred, n, 0.0); */ #ifdef _DEBUG mexPrintf("return\n"); #endif }
/* ************************************************************ PROCEDURE mexFunction - Entry for Matlab ************************************************************ */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { jcir At, Ablk; mwIndex i,j, nblk,m, blknnz, njc, iwsize, blk0,blk1; mwIndex *iwork, *Ajc, *blkstart; const double *blkstartPr, *AjcPr; bool *cwork; bool isblk0negative; /* ------------------------------------------------------------ Check for proper number of arguments ------------------------------------------------------------ */ mxAssert(nrhs >= NPARIN, "findblks requires more input arguments."); mxAssert(nlhs <= NPAROUT, "findblks produces less output arguments."); /* -------------------------------------------------- GET inputs At, blkstart, Ablkjc, blk0, blk1 -------------------------------------------------- */ mxAssert(mxIsSparse(AT_IN), "At must be a sparse matrix."); At.jc = mxGetJc(AT_IN); At.ir = mxGetIr(AT_IN); m = mxGetN(AT_IN); nblk = mxGetM(BLKSTART_IN) * mxGetN(BLKSTART_IN) - 1; blkstartPr = mxGetPr(BLKSTART_IN); AjcPr = mxGetPr(ABLKJC_IN); mxAssert(m == mxGetM(ABLKJC_IN), "Ablkjc size mismatch."); njc = mxGetN(ABLKJC_IN); blk0 = (mwIndex) mxGetScalar(BLK0_IN); /* double to mwIndex */ isblk0negative=0; mxAssert(blk0>0,""); if(blk0>0) --blk0; /* Fortran to C */ else isblk0negative=1; if(mxGetM(BLK1_IN) * mxGetN(BLK1_IN) != 1) blk1 = njc; /*default to end */ else{ blk1 = (mwIndex) mxGetScalar(BLK1_IN); /* double to mwIndex (thus inf not allowed) */ mxAssert(blk1>0,""); --blk1; /* Fortran to C */ } /* ------------------------------------------------------------ Allocate working array iwork(nblk+2+log_2(1+nblk)), blkstart(2*nblk), Ajc(2*m) char cwork(nblk) ------------------------------------------------------------ */ iwsize = nblk + 2 + (mwIndex) floor(log(1.0+nblk)/log(2.0)); iwork = (mwIndex *) mxCalloc(iwsize, sizeof(mwIndex)); blkstart = (mwIndex *) mxCalloc(MAX(2*nblk,1), sizeof(mwIndex)); Ajc = (mwIndex *) mxCalloc(MAX(2*m,1), sizeof(mwIndex)); cwork = (bool *) mxCalloc(MAX(nblk,1), sizeof(bool)); /* ------------------------------------------------------------ Translate blkstart from Fortran-double to C-mwIndex ------------------------------------------------------------ */ for(i = 0; i < nblk; i++){ /* to integers */ j = (mwIndex) blkstartPr[i]; mxAssert(j>0,""); blkstart[i] = --j; mxAssert(j>0,""); blkstart[nblk+i] = --j; /* blkstart minus 1 */ } /* ------------------------------------------------------------ Convert Ajc from double to mwIndex: ------------------------------------------------------------ */ mxAssert(blk0 < njc, "Ablkjc size mismatches blk0."); if(isblk0negative) memcpy(Ajc,At.jc,m*sizeof(mwIndex)); /* default: start of column */ else for(i = 0; i < m; i++){ /* to integers */ Ajc[i] = (mwIndex) AjcPr[m*blk0 + i]; } mxAssert(blk1 >= 0, "blk1 must be positive."); if(blk1 >= njc) memcpy(Ajc+m,At.jc+1,m*sizeof(mwIndex)); /* default: end of column */ else for(i = 0; i < m; i++){ /* to integers */ Ajc[m+i] = (mwIndex) AjcPr[blk1*m + i]; } /* ------------------------------------------------------------ Ablk = sparse(nblk,m,blknnz); ------------------------------------------------------------ */ blknnz = 0; for(i = 0; i < m; i++) blknnz += Ajc[m+i]-Ajc[i]; /* upper bound on nnz blocks */ blknnz = MAX(blknnz,1); ABLK_OUT = mxCreateSparse(nblk,m, blknnz,mxREAL); Ablk.jc = mxGetJc(ABLK_OUT); Ablk.ir = mxGetIr(ABLK_OUT); /* ------------------------------------------------------------ The real job: ------------------------------------------------------------ */ findblks(Ablk.ir,Ablk.jc, Ajc,Ajc+m,At.ir, blkstart,blkstart+nblk, m,nblk, iwsize,cwork,iwork); /* ------------------------------------------------------------ REALLOC (shrink) Ablk to Ablk.jc[m] nonzeros. ------------------------------------------------------------ */ mxAssert(Ablk.jc[m] <= blknnz,""); blknnz = MAX(Ablk.jc[m],1); if((Ablk.ir = (mwIndex *) mxRealloc(Ablk.ir, blknnz * sizeof(mwIndex))) == NULL) mexErrMsgTxt("Memory allocation error"); if((Ablk.pr = (double *) mxRealloc(mxGetPr(ABLK_OUT), blknnz*sizeof(double))) == NULL) mexErrMsgTxt("Memory allocation error"); mxSetPr(ABLK_OUT,Ablk.pr); mxSetIr(ABLK_OUT,Ablk.ir); mxSetNzmax(ABLK_OUT,blknnz); for(i = 0; i < blknnz; i++) Ablk.pr[i] = 1.0; /* ------------------------------------------------------------ Release working arrays ------------------------------------------------------------ */ mxFree(cwork); mxFree(iwork); mxFree(Ajc); mxFree(blkstart); }
int read_problem_sparse(const mxArray *label_vec, const mxArray *instance_mat) { int i, j, k, low, high; mwIndex *ir, *jc; int elements, max_index, num_samples, label_vector_row_num; double *samples, *labels; mxArray *instance_mat_col; // transposed instance sparse matrix prob.x = NULL; prob.y = NULL; x_space = NULL; // transpose instance matrix { mxArray *prhs[1], *plhs[1]; prhs[0] = mxDuplicateArray(instance_mat); if(mexCallMATLAB(1, plhs, 1, prhs, "transpose")) { mexPrintf("Error: cannot transpose training instance matrix\n"); return -1; } instance_mat_col = plhs[0]; mxDestroyArray(prhs[0]); } // each column is one instance labels = mxGetPr(label_vec); samples = mxGetPr(instance_mat_col); ir = mxGetIr(instance_mat_col); jc = mxGetJc(instance_mat_col); num_samples = (int)mxGetNzmax(instance_mat_col); // the number of instance prob.l = (int)mxGetN(instance_mat_col); label_vector_row_num = (int)mxGetM(label_vec); if(label_vector_row_num!=prob.l) { mexPrintf("Length of label vector does not match # of instances.\n"); return -1; } elements = num_samples + prob.l; max_index = (int)mxGetM(instance_mat_col); prob.y = Malloc(double,prob.l); prob.x = Malloc(struct svm_node *,prob.l); x_space = Malloc(struct svm_node, elements); j = 0; for(i=0;i<prob.l;i++) { prob.x[i] = &x_space[j]; prob.y[i] = labels[i]; low = (int)jc[i], high = (int)jc[i+1]; for(k=low;k<high;k++) { x_space[j].index = (int)ir[k] + 1; x_space[j].value = samples[k]; j++; } x_space[j++].index = -1; } if(param.gamma == 0 && max_index > 0) param.gamma = 1.0/max_index; return 0; }
void multiply_null_by_fuPot(mxArray *bigPot, const mxArray *smallPot){ int i, j, count, NB, NS, siz_b, siz_s, ndim, nzCounts=0; int *mask, *sx, *sy, *cpsy, *subs, *s, *cpsy2, *bir, *bjc; double *pbDomain, *psDomain, *pbSize, *psSize, *spr, *bpr, value; mxArray *pTemp, *pTemp1; pTemp = mxGetField(bigPot, 0, "domain"); pbDomain = mxGetPr(pTemp); siz_b = mxGetNumberOfElements(pTemp); pTemp = mxGetField(smallPot, 0, "domain"); psDomain = mxGetPr(pTemp); siz_s = mxGetNumberOfElements(pTemp); pTemp = mxGetField(bigPot, 0, "sizes"); pbSize = mxGetPr(pTemp); pTemp = mxGetField(smallPot, 0, "sizes"); psSize = mxGetPr(pTemp); NB = 1; for(i=0; i<siz_b; i++){ NB *= (int)pbSize[i]; } NS = 1; for(i=0; i<siz_s; i++){ NS *= (int)psSize[i]; } pTemp = mxGetField(smallPot, 0, "T"); spr = mxGetPr(pTemp); pTemp1 = mxCreateSparse(NB, 1, NB, mxREAL); bpr = mxGetPr(pTemp1); bir = mxGetIr(pTemp1); bjc = mxGetJc(pTemp1); bjc[0] = 0; bjc[1] = NB; if(NS == 1){ value = *spr; for(i=0; i<NB; i++){ bpr[i] = value; bir[i] = i; } nzCounts = NB; pTemp = mxGetField(bigPot, 0, "T"); if(pTemp)mxDestroyArray(pTemp); reset_nzmax(pTemp1, NB, nzCounts); mxSetField(bigPot, 0, "T", pTemp1); return; } if(NS == NB){ for(i=0; i<NB; i++){ if(spr[i] != 0){ bpr[nzCounts] = spr[i]; bir[nzCounts] = i; nzCounts++; } } pTemp = mxGetField(bigPot, 0, "T"); if(pTemp)mxDestroyArray(pTemp); reset_nzmax(pTemp1, NB, nzCounts); mxSetField(bigPot, 0, "T", pTemp1); return; } mask = malloc(siz_s * sizeof(int)); count = 0; for(i=0; i<siz_s; i++){ for(j=0; j<siz_b; j++){ if(psDomain[i] == pbDomain[j]){ mask[count] = j; count++; break; } } } ndim = siz_b; sx = (int *)malloc(sizeof(int)*ndim); sy = (int *)malloc(sizeof(int)*ndim); for(i=0; i<ndim; i++){ sx[i] = (int)pbSize[i]; sy[i] = 1; } for(i=0; i<count; i++){ sy[mask[i]] = sx[mask[i]]; } s = (int *)malloc(sizeof(int)*ndim); *(cpsy = (int *)malloc(sizeof(int)*ndim)) = 1; subs = (int *)malloc(sizeof(int)*ndim); cpsy2 = (int *)malloc(sizeof(int)*ndim); for(i = 0; i < ndim; i++){ subs[i] = 0; s[i] = sx[i] - 1; } for(i = 0; i < ndim-1; i++){ cpsy[i+1] = cpsy[i]*sy[i]--; cpsy2[i] = cpsy[i]*sy[i]; } cpsy2[ndim-1] = cpsy[ndim-1]*(--sy[ndim-1]); for(j=0; j<NB; j++){ if(*spr != 0){ bpr[nzCounts] = *spr; bir[nzCounts] = j; nzCounts++; } for(i = 0; i < ndim; i++){ if(subs[i] == s[i]){ subs[i] = 0; if(sy[i]) spr -= cpsy2[i]; } else{ subs[i]++; if(sy[i]) spr += cpsy[i]; break; } } } pTemp = mxGetField(bigPot, 0, "T"); if(pTemp)mxDestroyArray(pTemp); reset_nzmax(pTemp1, NB, nzCounts); mxSetField(bigPot, 0, "T", pTemp1); free(sx); free(sy); free(s); free(cpsy); free(subs); free(cpsy2); free(mask); }
// read in a problem (in libsvm format) void read_problem(const char *filename, mxArray *plhs[]) { int max_index, min_index, inst_max_index, i; long elements, k; FILE *fp = fopen(filename,"r"); int l = 0; char *endptr; mwIndex *ir, *jc; double *labels, *samples; if(fp == NULL) { mexPrintf("can't open input file %s\n",filename); fake_answer(plhs); return; } max_line_len = 1024; line = (char *) malloc(max_line_len*sizeof(char)); max_index = 0; min_index = 1; // our index starts from 1 elements = 0; while(readline(fp) != NULL) { char *idx, *val; // features int index = 0; inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0 strtok(line," \t"); // label while (1) { idx = strtok(NULL,":"); // index:value val = strtok(NULL," \t"); if(val == NULL) break; errno = 0; index = (int) strtol(idx,&endptr,10); if(endptr == idx || errno != 0 || *endptr != '\0' || index <= inst_max_index) { mexPrintf("Wrong input format at line %d\n",l+1); fake_answer(plhs); return; } else inst_max_index = index; min_index = min(min_index, index); elements++; } max_index = max(max_index, inst_max_index); l++; } rewind(fp); // y plhs[0] = mxCreateDoubleMatrix(l, 1, mxREAL); // x^T if (min_index <= 0) plhs[1] = mxCreateSparse(max_index-min_index+1, l, elements, mxREAL); else plhs[1] = mxCreateSparse(max_index, l, elements, mxREAL); labels = mxGetPr(plhs[0]); samples = mxGetPr(plhs[1]); ir = mxGetIr(plhs[1]); jc = mxGetJc(plhs[1]); k=0; for(i=0;i<l;i++) { char *idx, *val, *label; jc[i] = k; readline(fp); label = strtok(line," \t\n"); if(label == NULL) { mexPrintf("Empty line at line %d\n",i+1); fake_answer(plhs); return; } labels[i] = strtod(label,&endptr); if(endptr == label || *endptr != '\0') { mexPrintf("Wrong input format at line %d\n",i+1); fake_answer(plhs); return; } // features while(1) { idx = strtok(NULL,":"); val = strtok(NULL," \t"); if(val == NULL) break; ir[k] = (mwIndex) (strtol(idx,&endptr,10) - min_index); // precomputed kernel has <index> start from 0 errno = 0; samples[k] = strtod(val,&endptr); if (endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr))) { mexPrintf("Wrong input format at line %d\n",i+1); fake_answer(plhs); return; } ++k; } } jc[l] = k; fclose(fp); free(line); { mxArray *rhs[1], *lhs[1]; rhs[0] = plhs[1]; if(mexCallMATLAB(1, lhs, 1, rhs, "transpose")) { mexPrintf("Error: cannot transpose problem\n"); fake_answer(plhs); return; } plhs[1] = lhs[0]; } }
void mexFunction ( int nlhs, mxArray *plhs [], int nrhs, const mxArray *prhs [] ) { /* Compressed column form of L, x and b */ mwIndex *Lp, *Ap, *Ai, *Up, *pp, *pi ; Int *Li, *Ui; mwIndex *Lp1, *Li1, *Up1, *Ui1 ; double *Axr, *Axi; double *Lx1r, *Lx1i, *Ux1r, *Ux1i; double *br, *bi; complex<double> *Ax; complex<double> *Ux; complex<double> *Lx; complex<double> *b; complex<double> *sol; double *t1, *t2 ; mwIndex anrow ; mwIndex ancol ; mwIndex lnnz ; mwIndex unnz ; mwIndex i ; mwIndex j ; mwIndex app_xnnz ; mwIndex memsize ; if ( nlhs != 3 || nrhs < 3 ) { //mexErrMsgTxt (" Incorrect number of arguments to sproductmex \n") ; } Ap = mxGetJc(prhs[0]) ; Ai = mxGetIr(prhs[0]) ; Axr = mxGetPr(prhs[0]) ; Axi = mxGetPi(prhs[0]); anrow = mxGetM (prhs[0]) ; ancol = mxGetN (prhs[0]) ; t1 = mxGetPr (prhs[1]) ; t2 = mxGetPr (prhs[2]) ; br = mxGetPr(prhs[3]); bi = mxGetPi(prhs[3]); lnnz = (mwIndex)*t1 ; unnz = (mwIndex)*t2 ; /*Form complex numbers*/ Ax = (complex<double> *) mxCalloc(lnnz, sizeof(complex<double>)); b = (complex<double> *) mxCalloc(ancol, sizeof(complex<double>)); sol = (complex<double> *) mxCalloc(ancol, sizeof(complex<double>)); for(i = 0; i < lnnz; i++) { Ax[i] = complex<double>(Axr[i], Axi[i]); } for(i =0 ; i < ancol; i++) { b[i] = complex<double>(br[i], bi[i]); } int result; Basker::Basker <mwIndex, complex<double> > mybasker; result = mybasker.factor(anrow, ancol, lnnz, Ap, Ai, Ax); if(result == 0) { mybasker.returnL(&anrow, &lnnz, &Lp, &Li, &Lx); mybasker.returnU(&anrow, &unnz, &Up, &Ui, &Ux); mybasker.returnP(&pp); mybasker.solve(b, sol); } else { Lp = (mwIndex *) mxCalloc(anrow, sizeof(mwIndex)); Li = (mwIndex *) mxCalloc(anrow, sizeof(mwIndex)); Lx = (complex<double> *) mxCalloc(anrow, sizeof(complex<double>)); Up = (mwIndex *) mxCalloc(anrow, sizeof(mwIndex)); Ui = (mwIndex *) mxCalloc(anrow, sizeof(mwIndex)); Ux = (complex<double> *) mxCalloc(anrow, sizeof(complex<double>)); pp = (mwIndex *) mxCalloc(anrow, sizeof(mwIndex)); solution = (complex<double> *) mxCalloc(anrow, sizeof(complex<double>)); } plhs[0] = mxCreateSparse (anrow, ancol, lnnz+1, mxCOMPLEX) ; Lp1 = mxGetJc (plhs[0]) ; Li1 = mxGetIr (plhs[0]) ; Lx1r = mxGetPr (plhs[0]) ; Lx1i = mxGetPi (plhs[0]); plhs[1] = mxCreateSparse (anrow, ancol, unnz, mxCOMPLEX) ; Up1 = mxGetJc (plhs[1]) ; Ui1 = mxGetIr (plhs[1]) ; Ux1r = mxGetPr (plhs[1]); Ux1i = mxGetPi (plhs[1]); mwIndex *pp1, *pp2; double *ppx; plhs[2] = mxCreateSparse (ancol, ancol, ancol, mxREAL); pp1 = mxGetJc (plhs[2]); pp2 = mxGetIr (plhs[2]); ppx = mxGetPr (plhs[2]); double *soloutr, *solouti; plhs[3] = mxCreateDoubleMatrix(ancol, 1, mxCOMPLEX); soloutr = mxGetPr(plhs[3]); solouti = mxGetPi(plhs[3]); Lp1[0] = Lp[0]; for ( i = 0 ; i < ancol ; i++) { Lp1[i+1] = Lp[i+1]; for ( j = Lp[i] ; j < Lp[i+1] ; j++ ) { Li1[j] = Li[j]; Lx1r[j] = std::real(Lx[j]); Lx1i[j] = std::imag(Lx[j]); } } Up1[0] = Up[0]; for ( i = 0 ; i < ancol ; i++) { Up1[i+1] = Up[i+1]; for ( j = Up[i] ; j < Up[i+1] ; j++ ) { Ui1[j] = Ui[j]; Ux1r[j] = std::real(Ux[j]); Ux1i[j] = std::imag(Ux[j]); } } //mexPrintf("Perm \n"); for ( i = 0; i < ancol; i++) { //mexPrintf("%d ", pp[i]); pp1[i] = i; //pp2[i] = i; pp2[pp[i]] = i ; ppx[i] = 1; } pp1[ancol] = ancol; for (i = 0; i < ancol; i++) { soloutr[i] = std::real(sol[i]); solouti[i] = std::imag(sol[i]); } mxFree (pp) ; mxFree (Lp) ; mxFree (Li) ; mxFree (Lx) ; mxFree (Up) ; mxFree (Ui) ; mxFree (Ux) ; }