// Calling convention: // comp_filterbank(f,g,a); void mexFunction( int UNUSED(nlhs), mxArray *plhs[], int UNUSED(nrhs), const mxArray *prhs[] ) { static int atExitRegistered = 0; if(!atExitRegistered) { atExitRegistered = 1; mexAtExit(filterbankAtExit); } const mxArray* mxf = prhs[0]; const mxArray* mxg = prhs[1]; const mxArray* mxa = prhs[2]; // input data length const mwSize L = mxGetM(mxf); const mwSize W = mxGetN(mxf); // filter number const mwSize M = mxGetNumberOfElements(mxg); // a col count mwSize acols = mxGetN(mxa); // pointer to a double *a = (double*) mxGetData(mxa); if (acols > 1) { int isOnes = 1; for (mwIndex m = 0; m < M; m++) { isOnes = isOnes && a[M + m] == 1; } if (isOnes) { acols = 1; } } // Cell output plhs[0] = mxCreateCellMatrix(M, 1); // Stuff for sorting the filters mwSize tdCount = 0; mwSize fftCount = 0; mwSize fftblCount = 0; mwIndex tdArgsIdx[M]; mwIndex fftArgsIdx[M]; mwIndex fftblArgsIdx[M]; // WALK the filters to determine what has to be done for (mwIndex m = 0; m < M; m++) { mxArray * gEl = mxGetCell(mxg, m); if (mxGetField(gEl, 0, "h") != NULL) { tdArgsIdx[tdCount++] = m; continue; } if (mxGetField(gEl, 0, "H") != NULL) { if (acols == 1 && L == mxGetNumberOfElements(mxGetField(gEl, 0, "H"))) { fftArgsIdx[fftCount++] = m; continue; } else { fftblArgsIdx[fftblCount++] = m; continue; } } } if (tdCount > 0) { /* Here, we have to reformat the inputs and pick up results to comply with: c=comp_filterbank_td(f,g,a,offset,ext); BEWARE OF THE AUTOMATIC DEALLOCATION!! by the Matlab engine. Arrays can be very easily freed twice causing segfaults. This happends particulary when using mxCreateCell* which stores pointers to other mxArray structs. Setting all such pointers to NULL after they are used seems to solve it. */ mxArray* plhs_td[1]; mxArray* prhs_td[5]; prhs_td[0] = (mxArray*) mxf; prhs_td[1] = mxCreateCellMatrix(tdCount, 1); prhs_td[2] = mxCreateDoubleMatrix(tdCount, 1, mxREAL); double* aPtr = mxGetData(prhs_td[2]); prhs_td[3] = mxCreateDoubleMatrix(tdCount, 1, mxREAL); double* offsetPtr = mxGetData(prhs_td[3]); prhs_td[4] = mxCreateString("per"); for (mwIndex m = 0; m < tdCount; m++) { mxArray * gEl = mxGetCell(mxg, tdArgsIdx[m]); mxSetCell(prhs_td[1], m, mxGetField(gEl, 0, "h")); // This has overhead //mxSetCell((mxArray*)prhs_td[1],m,mxDuplicateArray(mxGetField(gEl,0,"h"))); aPtr[m] = a[tdArgsIdx[m]]; offsetPtr[m] = mxGetScalar(mxGetField(gEl, 0, "offset")); } // Finally call it! // comp_filterbank_td(1,plhs_td,5, prhs_td); // This has overhead: mexCallMATLAB(1, plhs_td, 5, prhs_td, "comp_filterbank_td"); // Copy pointers to a proper index in the output + unset all duplicate cell elements for (mwIndex m = 0; m < tdCount; m++) { mxSetCell(plhs[0], tdArgsIdx[m], mxGetCell(plhs_td[0], m)); mxSetCell(plhs_td[0], m, NULL); mxSetCell(prhs_td[1], m, NULL); } mxDestroyArray(plhs_td[0]); mxDestroyArray(prhs_td[1]); mxDestroyArray(prhs_td[2]); mxDestroyArray(prhs_td[3]); mxDestroyArray(prhs_td[4]); } if (fftCount > 0 || fftblCount > 0) { // Need to do FFT of mxf mwIndex ndim = 2; const mwSize dims[] = {L, W}; if (mxF == NULL || mxGetM(mxF) != L || mxGetN(mxF) != W || mxGetClassID(mxF) != mxGetClassID(mxf)) { if (mxF != NULL) { mxDestroyArray(mxF); mxF = NULL; // printf("Should be called just once\n"); } if (mxIsDouble(mxf)) { mxF = mxCreateNumericArray(ndim, dims, mxDOUBLE_CLASS, mxCOMPLEX); fftw_iodim fftw_dims[1]; fftw_iodim howmanydims[1]; fftw_dims[0].n = L; fftw_dims[0].is = 1; fftw_dims[0].os = 1; howmanydims[0].n = W; howmanydims[0].is = L; howmanydims[0].os = L; if (p_double == NULL) p_double = (fftw_plan*) malloc(sizeof(fftw_plan)); else fftw_destroy_plan(*p_double); // FFTW_MEASURE sometimes hangs here *p_double = fftw_plan_guru_split_dft( 1, fftw_dims, 1, howmanydims, mxGetData(mxF), mxGetImagData(mxF), mxGetData(mxF), mxGetImagData(mxF), FFTW_ESTIMATE); } else if (mxIsSingle(mxf)) { mxF = mxCreateNumericArray(ndim, dims, mxSINGLE_CLASS, mxCOMPLEX); // mexPrintf("M= %i, N= %i\n",mxGetM(mxF),mxGetN(mxF)); fftwf_iodim fftw_dims[1]; fftwf_iodim howmanydims[1]; fftw_dims[0].n = L; fftw_dims[0].is = 1; fftw_dims[0].os = 1; howmanydims[0].n = W; howmanydims[0].is = L; howmanydims[0].os = L; if (p_float == NULL) p_float = (fftwf_plan*) malloc(sizeof(fftwf_plan)); else fftwf_destroy_plan(*p_float); *p_float = fftwf_plan_guru_split_dft( 1, fftw_dims, 1, howmanydims, mxGetData(mxF), mxGetImagData(mxF), mxGetData(mxF), mxGetImagData(mxF), FFTW_ESTIMATE); } } if (mxIsDouble(mxf)) { memcpy(mxGetPr(mxF), mxGetPr(mxf), L * W * sizeof(double)); memset(mxGetPi(mxF), 0, L * W * sizeof(double)); if (mxIsComplex(mxf)) memcpy(mxGetPi(mxF), mxGetPi(mxf), L * W * sizeof(double)); fftw_execute(*p_double); } else if (mxIsSingle(mxf)) { memcpy(mxGetPr(mxF), mxGetPr(mxf), L * W * sizeof(float)); memset(mxGetPi(mxF), 0, L * W * sizeof(float)); if (mxIsComplex(mxf)) memcpy(mxGetPi(mxF), mxGetPi(mxf), L * W * sizeof(float)); fftwf_execute(*p_float); } } if (fftCount > 0) { mxArray* plhs_fft[1]; mxArray* prhs_fft[3]; prhs_fft[0] = mxF; prhs_fft[1] = mxCreateCellMatrix(fftCount, 1); prhs_fft[2] = mxCreateDoubleMatrix(fftCount, 1, mxREAL); double* aPtr = mxGetData(prhs_fft[2]); for (mwIndex m = 0; m < fftCount; m++) { mxArray * gEl = mxGetCell(mxg, fftArgsIdx[m]); mxSetCell(prhs_fft[1], m, mxGetField(gEl, 0, "H")); // This has overhead //mxSetCell((mxArray*)prhs_td[1],m,mxDuplicateArray(mxGetField(gEl,0,"h"))); aPtr[m] = a[fftArgsIdx[m]]; } //comp_filterbank_fft(1,plhs_fft,3, prhs_fft); mexCallMATLAB(1, plhs_fft, 3, prhs_fft, "comp_filterbank_fft"); for (mwIndex m = 0; m < fftCount; m++) { mxSetCell(plhs[0], fftArgsIdx[m], mxGetCell(plhs_fft[0], m)); mxSetCell(plhs_fft[0], m, NULL); mxSetCell(prhs_fft[1], m, NULL); } mxDestroyArray(plhs_fft[0]); mxDestroyArray(prhs_fft[1]); mxDestroyArray(prhs_fft[2]); } if (fftblCount > 0) { mxArray* plhs_fftbl[1]; mxArray* prhs_fftbl[5]; prhs_fftbl[0] = mxF; prhs_fftbl[1] = mxCreateCellMatrix(fftblCount, 1); prhs_fftbl[2] = mxCreateDoubleMatrix(fftblCount, 1, mxREAL); prhs_fftbl[3] = mxCreateDoubleMatrix(fftblCount, 2, mxREAL); prhs_fftbl[4] = mxCreateDoubleMatrix(fftblCount, 1, mxREAL); double* foffPtr = mxGetData(prhs_fftbl[2]); double* aPtr = mxGetData(prhs_fftbl[3]); double* realonlyPtr = mxGetData(prhs_fftbl[4]); // Set all realonly flags to zero memset(realonlyPtr, 0, fftblCount * sizeof * realonlyPtr); for (mwIndex m = 0; m < fftblCount; m++) { mxArray * gEl = mxGetCell(mxg, fftblArgsIdx[m]); mxSetCell(prhs_fftbl[1], m, mxGetField(gEl, 0, "H")); foffPtr[m] = mxGetScalar(mxGetField(gEl, 0, "foff")); aPtr[m] = a[fftblArgsIdx[m]]; if (acols > 1) aPtr[m + fftblCount] = a[fftblArgsIdx[m] + M]; else aPtr[m + fftblCount] = 1; // Only if realonly is specified mxArray* mxrealonly; if ((mxrealonly = mxGetField(gEl, 0, "realonly"))) realonlyPtr[m] = mxGetScalar(mxrealonly); } // comp_filterbank_fftbl(1,plhs_fftbl,5, prhs_fftbl); mexCallMATLAB(1, plhs_fftbl, 5, prhs_fftbl, "comp_filterbank_fftbl"); for (mwIndex m = 0; m < fftblCount; m++) { mxSetCell(plhs[0], fftblArgsIdx[m], mxGetCell(plhs_fftbl[0], m)); mxSetCell(plhs_fftbl[0], m, NULL); mxSetCell(prhs_fftbl[1], m, NULL); } mxDestroyArray(plhs_fftbl[0]); mxDestroyArray(prhs_fftbl[1]); mxDestroyArray(prhs_fftbl[2]); mxDestroyArray(prhs_fftbl[3]); mxDestroyArray(prhs_fftbl[4]); } if (mxF != NULL) mexMakeArrayPersistent(mxF); if (L * W > MAXARRAYLEN && mxF != NULL) { //printf("Damn. Should not get here\n"); mxDestroyArray(mxF); mxF = NULL; } }
mxArray *sf_c39_CSE1_Oculus_gesture_updateBuildInfo_args_info(void) { mxArray *mxBIArgs = mxCreateCellMatrix(1,0); return mxBIArgs; }
mxArray *sf_c39_Demo_KinectWaveWalkInvade_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
mxArray *sf_c1_Model_justmodel2_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
/* here comes the main function */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* default settings */ /* connectivity pattern: 2 */ const double DEF_clconn = 2.0; /* threshold 1 (consider also single voxel clusters) */ const double DEF_kthr = 1.0; /* setting pointers (for argument read-out) */ const double *clconn = NULL; const double *kthr = NULL; /* settings (internal) */ /* max directions */ unsigned int md = 2; /* cluster threshold */ unsigned int kthrl = 1; /* sizes and position */ const int *dim = NULL; int idim[3] = {1, 1, 1}; int tdim[3] = {1, 1, 1}; /* offset (must be variable, as copy might not require additional slices) */ unsigned int toff[3] = {1, 1, 1}; /* dimX, dimY, dimZ, dimXY, next position */ unsigned int dx = 0, dy = 0, dz = 0, dxy = 0, dxyz = 0, np = 0; /* data pointers */ /* (enlarged) copy */ unsigned char *copy = NULL; /* list of cluster voxels */ unsigned int clvoxcnt; unsigned int clnxtvox; signed int *clvox = NULL; /* list of cluster sizes and total number of clustered voxels */ unsigned int mxclnum = 0; unsigned int clnum = 0; unsigned int *clsiz = NULL; unsigned int cltvox = 0, cltvox2 = 0, cltvox3 = 0; /* clustered volume (internal) */ unsigned int *clvol = NULL; /* direction increments (as index differences) */ signed int dlxyz[26] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; /* next positions (signed!) */ signed int nextp = 0, nextpi = 0; /* counters */ signed char dc = 0; unsigned int cx = 0, cy = 0, cz = 0; /* output pointer(s) */ mxArray *ma = NULL; double *op = NULL, *sop = NULL; /* variable output text */ /* char vstr[256]; */ /* code starts here */ /* nr. of arguments check */ if ((nrhs < 1) || (nlhs > 4)) mexErrMsgTxt("Bad number of input/output arguments."); /* first argument class and size check */ if (!mxIsLogical(prhs[0]) || (mxGetNumberOfElements(prhs[0]) < 8) || (mxGetNumberOfDimensions(prhs[0]) > 3)) mexErrMsgTxt("Invalid argument type or dimension."); /* check connectivity flag */ if ((nrhs < 2) || !mxIsDouble(prhs[1]) || (mxGetNumberOfElements(prhs[1]) != 1)) clconn = &DEF_clconn; else { clconn = (const double*) mxGetPr(prhs[1]); if (mxIsNaN(*clconn) || mxIsInf(*clconn) || ((*clconn) < 1.0) || ((*clconn) > 5.0)) clconn = &DEF_clconn; } /* check threshold */ if ((nrhs < 3) || !mxIsDouble(prhs[2]) || (mxGetNumberOfElements(prhs[2]) != 1)) kthr = &DEF_kthr; else { kthr = (const double*) mxGetPr(prhs[2]); if (mxIsNaN(*kthr) || mxIsInf(*kthr) || ((*kthr) < 1.0) || ((*kthr) > (0.5 * mxGetNumberOfElements(prhs[0])))) kthr = &DEF_kthr; } kthrl = (unsigned int) *kthr; /* get & check argument content */ dim = mxGetDimensions(prhs[0]); idim[0] = dim[0]; idim[1] = dim[1]; if (mxGetNumberOfDimensions(prhs[0]) > 2) idim[2] = dim[2]; dx = idim[0]; dy = idim[1]; dz = idim[2]; dxy = dx * dy; dxyz = dxy * dz; mxclnum = (unsigned int) (((double) (dxyz + 3)) / 4.0); /* set connectivity flag -> max directions (opposite direction later) */ /* face connectivity -> three main directions */ if ((*clconn >= 1.0) && (*clconn < 1.5)) md = 3; /* edge connectivity -> add 6 edge diagonals */ else if ((*clconn >= 1.5) && (*clconn < 2.5)) md = 9; /* vertex connectivity -> add 4 3D diagonals */ else if ((*clconn >= 2.5) && (*clconn < 3.5)) md = 13; /* otherwise, leave at 2, we stay "in-plane" */ /* reserve space for next cluster list and cluster sizes */ clvox = (signed int *) mxCalloc(dxyz, sizeof(signed int)); if (clvox == NULL) mexErrMsgTxt("Error allocating next cluster voxel list."); clsiz = (unsigned int *) mxCalloc(mxclnum, sizeof(signed int)); if (clsiz == NULL) { mxFree(clvox); mexErrMsgTxt("Error allocating next cluster voxel list."); } /* increase numbers accordingly */ if (idim[0] > 1) dx += 2; else toff[0] = 0; if (idim[1] > 1) dy += 2; else toff[1] = 0; if (idim[2] > 1) dz += 2; else toff[2] = 0; /* compute new plane/vol numel */ dxy = dx * dy; dxyz = dxy * dz; /* reserve space for clustered volume (if needed) */ if (nlhs > 1) { clvol = (unsigned int *) mxCalloc(dxyz, sizeof(unsigned int)); if (clvol == NULL) { mxFree(clsiz); mxFree(clvox); mexErrMsgTxt("Error allocating clustered volume."); } } /* set temp dim array */ tdim[0] = dx; tdim[1] = dy; tdim[2] = dz; /* fill direction increment array */ np = 0; for (dc = 0; dc < md; ++dc) { if (((idim[0] > 1) || (dlx[dc] == 0)) && ((idim[1] > 1) || (dly[dc] == 0)) && (((idim[2] > 1) && (*clconn < 3.5)) || (dlz[dc] == 0))) { dlxyz[np] = dlx[dc] + dly[dc] * dx + dlz[dc] * dxy; dlxyz[np+1] = -dlxyz[np]; np += 2; } } if ((*clconn >= 4.5) && (idim[0] > 1) && (idim[1] > 1)) { for (dc = 3; dc < 5; ++dc) { dlxyz[np] = dlx[dc] + dly[dc] * dx + dlz[dc] * dxy; dlxyz[np+1] = -dlxyz[np]; np += 2; } } /* re-set */ md = np - 1; /* create temp. copy array */ copy = (unsigned char *) mxCalloc(dxyz, sizeof(unsigned char)); if (copy == NULL) { mxFree(clsiz); mxFree(clvox); mexErrMsgTxt("Error allocating temporary memory"); } /* copy into temporary array */ ff_copy_intopart(idim[0], idim[1], idim[2], (unsigned char *) mxGetPr(prhs[0]), tdim, copy, toff); /* preparations complete, now we can "search"... */ /* iterate while new points found */ for (np = 0; np < dxyz; ++np) { /* check voxel */ if (copy[np] == 1) { /* start new cluster */ clvoxcnt = 1; clvox[0] = np; /* remove from search volume */ copy[np] = 0; /* continue until no more neighbors found */ for (clnxtvox = 0; clnxtvox < clvoxcnt; ++clnxtvox) { /* check neighbors */ nextp = clvox[clnxtvox]; for (dc = md; dc >= 0; --dc) { /* check voxel with increment */ nextpi = nextp + dlxyz[dc]; if (copy[nextpi] == 1) { /* equally remove from search volume */ copy[nextpi] = 0; /* and add to list */ clvox[clvoxcnt++] = nextpi; } } } /* rest of code only if surpasses threshold */ if (clvoxcnt >= kthrl) { /* write to list of sizes and increase cluster number count */ clsiz[clnum++] = clvoxcnt; cltvox += clvoxcnt; /* write to output volume (if needed) */ if (nlhs > 1) { for (nextp = clvoxcnt - 1; nextp >= 0; --nextp) clvol[clvox[nextp]] = clnum; } } } } /* we're done with this */ mxFree(copy); /* create output argument #1 */ CREATE_MxN(plhs[0], 1, clnum); if (plhs[0] == NULL) { if (clvol != NULL) mxFree(clvol); mxFree(clsiz); mxFree(clvox); mexErrMsgTxt("Error creating output argument cs."); } /* if requested create other outputs first */ if (nlhs > 1) { plhs[1] = mxCreateNumericArray(3, idim, mxUINT32_CLASS, mxREAL); if (plhs[1] == NULL) { mxDestroyArray(plhs[0]); mxFree(clvol); mxFree(clsiz); mxFree(clvox); mexErrMsgTxt("Error creating output argument cv."); } } /* if requested create other outputs first */ if (nlhs > 2) { CREATE_MxN(plhs[2], cltvox, 4); if (plhs[2] == NULL) { mxDestroyArray(plhs[1]); mxDestroyArray(plhs[0]); mxFree(clvol); mxFree(clsiz); mxFree(clvox); mexErrMsgTxt("Error creating output argument l."); } } /* if requested create other outputs first */ if (nlhs > 3) { plhs[3] = mxCreateCellMatrix(1, clnum); if (plhs[3] == NULL) { mxDestroyArray(plhs[2]); mxDestroyArray(plhs[1]); mxDestroyArray(plhs[0]); mxFree(clvol); mxFree(clsiz); mxFree(clvox); mexErrMsgTxt("Error creating output argument c."); } /* put numeric array into each cell */ for (nextp = 0; nextp < clnum; ++nextp) { CREATE_MxN(ma, clsiz[nextp], 3); if (ma == NULL) { mxDestroyArray(plhs[3]); mxDestroyArray(plhs[2]); mxDestroyArray(plhs[1]); mxDestroyArray(plhs[0]); mxFree(clvol); mxFree(clsiz); mxFree(clvox); mexErrMsgTxt("Error creating output cell contents in argument c."); } mxSetCell(plhs[3], nextp, ma); } } /* copy cluster sizes into output */ op = (double *) mxGetPr(plhs[0]); for (nextp = 0; nextp < clnum; ++nextp) *op++ = (double) clsiz[nextp]; /* copy volume to output */ if (nlhs > 1) { ff_copy_frompart(dx, dy, clvol, idim, (unsigned int*) mxGetData(plhs[1]), toff); mxFree(clvol); clvol = (unsigned int *) mxGetPr(plhs[1]); } /* create list of voxels */ if (nlhs > 2) { /* get output pointer */ op = (double *) mxGetPr(plhs[2]); /* 2/3 * total count for fast indexing */ cltvox2 = 2 * cltvox; cltvox3 = 3 * cltvox; /* if required re-init counter */ if (nlhs > 3) { for (nextp = clnum - 1; nextp >= 0; --nextp) clvox[nextp] = 0; } dx = idim[0]; dy = idim[1]; dz = idim[2]; dxy = dx * dy; for (cz = 0; cz < dz; ++cz) { dxyz = dxy * cz; for (cy = 0; cy < dy; ++cy) { np = dxyz + cy * dx; for (cx = 0; cx < dx; ++cx) { clnum = *clvol++; if (clnum > 0) { op[cltvox3] = (double) clnum; op[cltvox2] = (double) (cz + 1); op[cltvox] = (double) (cy + 1); *op++ = (double) (cx + 1); if (nlhs > 3) { --clnum; sop = (double *) mxGetPr(mxGetCell(plhs[3], clnum)); sop[2 * clsiz[clnum] + clvox[clnum]] = (double) (cz + 1); sop[clsiz[clnum] + clvox[clnum]] = (double) (cy + 1); sop[clvox[clnum]++] = (double) (cx + 1); } } } } } } /* free other temp arrays */ mxFree(clsiz); mxFree(clvox); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){ //setting up inputs //first, set up the structs const mxArray* data = mxDuplicateArray(prhs[0]); const mxArray* model = mxDuplicateArray(prhs[1]); const mxArray* samp = mxDuplicateArray(prhs[2]); if (data == NULL || model == NULL || samp == NULL){ mexPrintf("Error duplicating inputs\n"); exit(EXIT_FAILURE); } const mxLogical* params = mxGetLogicals(prhs[3]); int numExamples = 0; //then, set up the cell array pointers mxArray* exampsByUserItem = NULL; mxArray* sampkuM = NULL; mxArray* samptuM = NULL; mxArray* sampnuM = NULL; //then, the double data matrices (as vectors) double* c = NULL; double* d = NULL; double* muC = NULL; double* muD = NULL; double* mC = NULL; double* nC = NULL; double* nD = NULL; //the scalar values double c0, betaM, gammaM; c0 = betaM = gammaM = 0; int length_mC, length_nC, length_kM, length_muC; length_mC = length_nC = length_kM = length_muC = 0; //the uint32_t numerical matrices uint32_t* kM = NULL; uint32_t* kU = NULL; const double* resids = mxGetPr(mxGetField(samp, 0, "resids")); const double d0 = (*mxGetPr(mxGetField(model, 0, "d0"))); const double sigmaSqd = (*mxGetPr(mxGetField(model, 0, "sigmaSqd"))); const double sigmaSqd0 = (*mxGetPr(mxGetField(model, 0, "sigmaSqd0"))); const double invsigmaSqd = (*mxGetPr(mxGetField(model, 0, "invsigmaSqd"))); const double invsigmaSqd0 = (*mxGetPr(mxGetField(model, 0, "invsigmaSqd0"))); if (params[0]){ //isItemTopic == true mexPrintf("Sampling dishes for users\n"); numExamples = (*mxGetPr(mxGetField(data, 0, "numUsers"))); //dereference to get value of numUsers exampsByUserItem = mxGetField(data, 0, "exampsByUser"); c = mxGetPr(mxGetField(samp, 0, "c")); d = mxGetPr(mxGetField(samp, 0, "d")); sampkuM = mxGetField(samp, 0, "kuM"); samptuM = mxGetField(samp, 0, "tuM"); sampnuM = mxGetField(samp, 0, "nuM"); length_mC = mxGetN(mxGetField(samp, 0, "mC")); mC = (double*)mxMalloc((length_mC)*sizeof(double)); memcpy(mC, mxGetPr(mxGetField(samp, 0, "mC")), length_mC*sizeof(double)); length_nC = mxGetN(mxGetField(samp, 0, "nC")); nC = (double*)mxMalloc((length_nC)*sizeof(double)); memcpy(nC, mxGetPr(mxGetField(samp, 0, "nC")), length_nC*sizeof(double)); nD = mxGetPr(mxGetField(samp, 0, "nD")); //we don't modify nD, so it's OK to just have it be a pointer length_kM = mxGetN(mxGetField(samp, 0, "kM")); kM = (uint32_t*)mxMalloc((length_kM)*sizeof(uint32_t)); memcpy(kM, (uint32_t*)mxGetData(mxGetField(samp, 0, "kM")), length_kM*sizeof(uint32_t)); kU = (uint32_t*)mxGetData(mxGetField(samp, 0, "kU")); //not being modified length_muC = mxGetN(mxGetField(samp, 0, "muC")); muC = (double*)mxMalloc((length_muC)*sizeof(double)); memcpy(muC, mxGetPr(mxGetField(samp, 0, "muC")), length_muC*sizeof(double)); muD = mxGetPr(mxGetField(samp, 0, "muD")); c0 = (*mxGetPr(mxGetField(model, 0, "c0"))); betaM = (*mxGetPr(mxGetField(model, 0, "betaM"))); gammaM = (*mxGetPr(mxGetField(model, 0, "gammaM"))); } else{ //isItemTopic == false mexPrintf("Sampling dishes for items\n"); numExamples = (*mxGetPr(mxGetField(data, 0, "numItems"))); exampsByUserItem = mxGetField(data, 0, "exampsByItem"); c = mxGetPr(mxGetField(samp, 0, "d")); d = mxGetPr(mxGetField(samp, 0, "c")); sampkuM = mxGetField(samp, 0, "kjU"); samptuM = mxGetField(samp, 0, "tjU"); sampnuM = mxGetField(samp, 0, "njU"); length_mC = mxGetN(mxGetField(samp, 0, "mD")); mC = (double*)mxMalloc((length_mC)*sizeof(double)); memcpy(mC, mxGetPr(mxGetField(samp, 0, "mD")), length_mC*sizeof(double)); length_nC = mxGetN(mxGetField(samp, 0, "nD")); nC = (double*)mxMalloc((length_nC)*sizeof(double)); memcpy(nC, mxGetPr(mxGetField(samp, 0, "nD")), length_nC*sizeof(double)); nD = mxGetPr(mxGetField(samp, 0, "nC")); length_kM = mxGetN(mxGetField(samp, 0, "kU")); kM = (uint32_t*)mxMalloc((length_kM)*sizeof(uint32_t)); memcpy(kM, (uint32_t*)mxGetData(mxGetField(samp, 0, "kU")), length_kM*sizeof(uint32_t)); kU = (uint32_t*)mxGetData(mxGetField(samp, 0, "kM")); length_muC = mxGetN(mxGetField(samp, 0, "muD")); muC = (double*)mxMalloc((length_muC)*sizeof(double)); memcpy(muC, mxGetPr(mxGetField(samp, 0, "muD")), length_muC*sizeof(double)); muD = mxGetPr(mxGetField(samp, 0, "muC")); c0 = (*mxGetPr(mxGetField(model, 0, "d0"))); betaM = (*mxGetPr(mxGetField(model, 0, "betaU"))); gammaM = (*mxGetPr(mxGetField(model, 0, "gammaU"))); } mexPrintf("Initialized values successfully\n"); //outputs mxArray* sampkuM_out = mxCreateCellMatrix(numExamples, 1); omp_set_num_threads(MAX_NUM_THREADS); gsl_rng** rngs = getRngArray(); //RNG part int thread = omp_get_thread_num(); const gsl_rng* rng = rngs[thread]; //#pragma omp parallel for for (int uu = 0; uu < numExamples; uu++){ mwSize kuM_size = mxGetN(mxGetCell(sampkuM, uu)); mwSize tuM_size = mxGetN(mxGetCell(samptuM, uu)); mwSize TuM = mxGetN(mxGetCell(sampnuM, uu)); //initialize TuM when going to new user; TuM = nuM_size uint32_t* kuM = (uint32_t*)mxMalloc((kuM_size)*sizeof(uint32_t)); //needs to be modified, so allocating on heap memcpy(kuM, (uint32_t*)mxGetData(mxGetCell(sampkuM, uu)), kuM_size*sizeof(uint32_t)); //copying onto heap uint32_t* tuM = (uint32_t*)mxMalloc(tuM_size*sizeof(uint32_t)); memcpy(tuM, (uint32_t*)mxGetData(mxGetCell(samptuM, uu)), tuM_size*sizeof(uint32_t)); uint32_t* examps = (uint32_t*)mxGetData(mxGetCell(exampsByUserItem, uu)); int numExamples_uu = mxGetN(mxGetCell(exampsByUserItem, uu)); //size of examps uint32_t** tuM_cell = (uint32_t**)mxMalloc(TuM*sizeof(uint32_t*)); uint32_t tuM_cell_size[TuM]; for (int i = 0; i < TuM; i++ ){ tuM_cell[i] = NULL; tuM_cell_size[i] = 0; } if (tuM_size != numExamples_uu){ mexPrintf("Error: size of tuM matrix for user %d is %d; it should equal numExamples, which is %d\n", uu, tuM_size, numExamples_uu); exit(EXIT_FAILURE); } for (mwSize ee_i = 0; ee_i < numExamples_uu; ee_i++){ //numExamples_uu == tuM_size; assembling all the examples for this user sorted by table in a cell array if (tuM[ee_i] > TuM){ mexPrintf("Error: table number for user %d, example %d, exceeds number of tables!\n", uu, ee_i); } uint32_t* tuM_cell_table = tuM_cell[tuM[ee_i]-1]; if (tuM_cell_table == NULL){ //i.e., the entry is empty thus far tuM_cell_table = (uint32_t*)mxMalloc(sizeof(uint32_t)); tuM_cell_table[0] = examps[ee_i]; tuM_cell[tuM[ee_i]-1] = tuM_cell_table; tuM_cell_size[tuM[ee_i]-1] = 1; } else { int orig_size = tuM_cell_size[tuM[ee_i]-1]; uint32_t* tuM_cell_expanded = (uint32_t*)mxRealloc(tuM_cell_table, (orig_size+1)*sizeof(uint32_t)); if (tuM_cell_expanded){ tuM_cell_expanded[orig_size] = examps[ee_i]; tuM_cell[tuM[ee_i]-1] = tuM_cell_expanded; tuM_cell_size[tuM[ee_i]-1] += 1; } else { mexPrintf("Could not enlarge tuM cell array for user %d, example %d\n", uu, ee_i); } } } //sample a new dish for each table for (mwSize tt = 0; tt < TuM; tt++ ){ uint32_t* examp_tuM = tuM_cell[tt]; int table_size = tuM_cell_size[tt]; if (table_size > 0){ int old_k = kuM[tt] - 1; //update global dish sufficient stats immediately mC[old_k] -= 1; if (mC[old_k] < 0){ mC[old_k] = 0; } for (mwSize ee_i = 0; ee_i < table_size; ee_i++){ //loop through all examples assigned to table uint32_t ee = examp_tuM[ee_i] - 1; double residC = (params[1]) ? resids[ee] - muD[kU[ee]-1] : resids[ee] - d[kU[ee]-1]; muC[old_k] = updateCRFMu(muC, nC, residC, old_k, false, model); //remove current rating from global sufficient stats //NOTE! this is a hack if (fabs(muC[old_k]) > 30){ int sign = (muC[old_k] > 0) - (muC[old_k] < 0); muC[old_k] = sign*30; } nC[old_k] -= 1; } int new_k = sampleDishFull(examp_tuM, resids, mC, muC, muD, kU, nC, nD, betaM, c0, sigmaSqd, invsigmaSqd, invsigmaSqd0, length_mC, table_size, rng); //skipping if condition that checks if length(new_k) > 1 int empty_dish = linearSearchDouble(nC, 0, length_nC); //see what table we selected if (empty_dish > -1){ new_k = empty_dish; } //if empty_dish is found, then set new_k to it kuM[tt] = new_k + 1; //+1 to be consistent with matlab notations if (new_k + 1 > length_mC){ //length_mC tells us number of active dishes right now double* mC_expanded = (double*)mxRealloc(mC, (length_mC+1)*sizeof(double)); if (mC_expanded) { mC = mC_expanded; } length_mC++; mC[new_k] = 0; //new dish } mC[new_k] += 1; if (new_k + 1 > length_nC){ double* muC_expanded = (double*)mxRealloc(muC, (length_muC+1)*sizeof(double)); if (muC_expanded) { muC = muC_expanded; } double* nC_expanded = (double*)mxRealloc(nC, (length_nC+1)*sizeof(double)); if (nC_expanded) { nC = nC_expanded; } length_nC++; length_muC++; muC[new_k] = d0 * sigmaSqd / sigmaSqd0; nC[new_k] = 0; } for (mwSize ee_i = 0; ee_i < table_size; ee_i++){ uint32_t ee = examp_tuM[ee_i] - 1; kM[ee] = new_k+1; double residC = (params[1]) ? resids[ee] - muD[kU[ee]-1] : resids[ee] - d[kU[ee]-1]; muC[new_k] = updateCRFMu(muC, nC, residC, new_k, true, model); //NOTE: this is a hack! if (fabs(muC[new_k]) > 30){ int sign = (muC[new_k] > 0) - (muC[new_k] < 0); muC[new_k] = sign*30; } nC[new_k] += 1; } } } //close loop that goes through the tables for a given user mxArray* kuM_out; kuM_out = mxCreateNumericMatrix(1, TuM, mxUINT32_CLASS, mxREAL); if (kuM_out){ mxSetPr(kuM_out, kuM); mxSetCell(sampkuM_out, uu, kuM_out); } } //close loop over all users //set up outputs for remaining variables mxArray* mC_out = mxCreateDoubleMatrix(1, length_mC, mxREAL); mxArray* nC_out = mxCreateDoubleMatrix(1, length_nC, mxREAL); mxArray* muC_out = mxCreateDoubleMatrix(1, length_muC, mxREAL); mxArray* kM_out = mxCreateNumericMatrix(1, length_kM, mxUINT32_CLASS, mxREAL); mxSetPr(mC_out, mC); mxSetPr(nC_out, nC); mxSetPr(muC_out, muC); mxSetPr(kM_out, kM); plhs[0] = sampkuM_out; plhs[1] = mC_out; plhs[2] = nC_out; plhs[3] = muC_out; plhs[4] = kM_out; mexPrintf("Finished sampling dishes\n"); }
mxArray * mp_create_mxDict_from_dict(MP_Dict_c *dict) { const char *func = "mp_create_mxDict_from_dict"; map<string,string,mp_ltstring> *paramMap; mxArray *mxBlockCell; mxArray *mxBlock; mxArray *mxDict; mxArray *mxTable; MP_Block_c *block; int numDictFieldNames; int iFieldNumber; const char *dictFieldNames[] = {"block"}; // Case of a NULL input if(NULL==dict) { mp_error_msg(func,"the input is NULL\n"); return(NULL); } // Create the block cell mxBlockCell = mxCreateCellMatrix((mwSize)dict->numBlocks,(mwSize)1); if(mxBlockCell == NULL) { mp_error_msg(func,"could not create block cell\n"); return(NULL); } // Loop to create each block for (unsigned int i=0; i < dict->numBlocks; i++) { block = dict->block[i]; if(block == NULL) { mp_error_msg(func,"block 0<=i=%d<%d is NULL\n",i,dict->numBlocks); mxDestroyArray(mxBlockCell); return(NULL); } paramMap = block->get_block_parameters_map(); if (NULL==paramMap) { mp_error_msg(func,"empty paramMap for block 0<=i=%d<%d\n", i,dict->numBlocks); mxDestroyArray(mxBlockCell); return(NULL); } // Create mxBlock mxBlock = mxCreateStructMatrix((mwSize)1,(mwSize)1,0,NULL); if(mxBlock == NULL) { mp_error_msg(func,"could not create block 0<=i=%d<%d\n",i,dict->numBlocks); mxDestroyArray(mxBlockCell); return(NULL); } // Add all fields map<string, string, mp_ltstring>::const_iterator iter; for ( iter = (*paramMap).begin(); iter != (*paramMap).end(); iter++ ) { // TODO: we shouldn't need to know what fields are possible in the first place if(!strcmp(iter->first.c_str(),"data")) { // Adding the table Field mxAddField(mxBlock,"data"); if((mxTable = anywaveTableRead(paramMap, NULL)) == NULL) { mp_error_msg(func,"could not load the anywaveTable %s\n",iter->second.c_str()); mxDestroyArray(mxBlockCell); return(NULL); } iFieldNumber = mxGetFieldNumber(mxBlock, "data"); mxSetCell(mxBlock,iFieldNumber,mxTable); } else { // Add the field mxAddField(mxBlock,iter->first.c_str()); // TODO: Here should query the type of the field to set it appropriately! // Set the field value mxArray *mxTmp = mxCreateString(iter->second.c_str()); if(NULL==mxTmp) { mp_error_msg(func,"could not create field %s in block 0<=i=%d<%d\n",iter->second.c_str(),i,dict->numBlocks); mxDestroyArray(mxBlockCell); return(NULL); } mxSetField(mxBlock,0,iter->first.c_str(),mxTmp); // If the paramMap contains a file link to xml, then go search it ! // TODO: we shouldn't need to know what fields are possible in the first place if(!strcmp(iter->first.c_str(),"tableFileName")) { // Adding the table Field mxAddField(mxBlock,"data"); if((mxTable = anywaveTableRead(paramMap, (char *)iter->second.c_str())) == NULL) { mp_error_msg(func,"could not load the anywaveTable %s\n",iter->second.c_str()); mxDestroyArray(mxBlockCell); return(NULL); } iFieldNumber = mxGetFieldNumber(mxBlock, "data"); mxSetCell(mxBlock,iFieldNumber,mxTable); } } } // Put the mxBlock in the mxBlockCell mxSetCell(mxBlockCell,i,mxBlock); // Delete tmp variables delete paramMap; } // Create the output information structure // dict.block{numBlocks} numDictFieldNames = 1; mxDict = mxCreateStructMatrix((mwSize)1,(mwSize)1,numDictFieldNames,dictFieldNames); if(NULL==mxDict) { mp_error_msg(func,"could not create dict\n"); mxDestroyArray(mxBlockCell); return(NULL); } mxSetField(mxDict,0,"block",mxBlockCell); return(mxDict); }
mxArray *sf_c2_DYNctl_ver4_etud_nonlineaire_updateBuildInfo_args_info(void) { mxArray *mxBIArgs = mxCreateCellMatrix(1,0); return mxBIArgs; }
mxArray *sf_c12_DemoWalk_K_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Usage: [runs, {lengths}, {starts}] = extract_runs(x, inds); */ int *pnLengths, *pnStarts, *pnEnds; double *pfInds; int nElements,i,j,iRun,nRuns,n,m; char bInRun; mxArray *mxTemp; double *prData, *prTemp; mxClassID mxIntClass; mxIntClass = mxINT32_CLASS; switch(sizeof(int)) { case 1: mxIntClass = mxINT8_CLASS; break; case 2: mxIntClass = mxINT16_CLASS; break; case 4: mxIntClass = mxINT32_CLASS; break; case 8: mxIntClass = mxINT64_CLASS; break; default: mexErrMsgTxt("sizeof(int) is not 1,2,4, or 8 bytes."); break; } pnLengths = NULL; pnStarts = NULL; pnEnds = NULL; if (nrhs!=2) mexErrMsgTxt("Usage: [runs, {lengths}, {starts}] = extract_runs(x, inds)\n"); if (nlhs<1) mexErrMsgTxt("At least one output argument required.\n"); if (nlhs>3) mexErrMsgTxt("At most 3 output arguments required.\n"); nElements = mxGetNumberOfElements(prhs[1]); if (nElements != mxGetNumberOfElements(prhs[0])) mexErrMsgTxt("Data and indices vectors must have the same number of elements.\n"); if (nElements == 0) { for (i = 0; i<nlhs; i++) plhs[i] = mxCreateDoubleMatrix(0,0,mxREAL); return; } if (mxIsComplex(prhs[0])) mexErrMsgTxt("Data vector must be real, not complex."); if (!mxIsDouble(prhs[0])) mexErrMsgTxt("Data vector must be of type double. Cast to double before call."); if (!mxIsDouble(prhs[1])) mexErrMsgTxt("Indices vector must be of type double. Cast to double before call."); pfInds = mxGetPr(prhs[1]); nRuns = 0; bInRun = (pfInds[0] == 1); for (i = 1; i<nElements; i++) { if (bInRun) { if (!pfInds[i]) { bInRun = 0; nRuns++; } } else { if (pfInds[i]) { bInRun = 1; } } } if (bInRun) nRuns++; if (nRuns) { pnLengths = mxCalloc(nRuns, sizeof(int)); pnStarts = mxCalloc(nRuns, sizeof(int)); pnEnds = mxCalloc(nRuns, sizeof(int)); iRun = 0; bInRun = (pfInds[0]==1); pnStarts[iRun] = (bInRun) ? 0 : -1; pnEnds[iRun] = -1; for (i = 1; i<nElements; i++) { if (bInRun) { if (pfInds[i]==0) { bInRun = 0; pnEnds[iRun] = i-1; pnLengths[iRun] = pnEnds[iRun] - pnStarts[iRun] + 1; iRun++; } } else { if (pfInds[i]==1) { bInRun = 1; pnStarts[iRun] = i; } } } if (bInRun) { pnEnds[iRun] = nElements-1; pnLengths[iRun] = pnEnds[iRun] - pnStarts[iRun] + 1; iRun++; } /* Load the runs into the cell */ plhs[0] = mxCreateCellMatrix(nRuns, 1); prData = mxGetPr(prhs[0]); for (i = 0; i<nRuns;i++) { mxTemp = mxCreateDoubleMatrix(1, pnLengths[i], mxREAL); prTemp = mxGetPr(mxTemp); m = pnStarts[i]; n = pnEnds[i]; for (j = m; j<=n;j++) { prTemp[j-m] = prData[j]; } mxSetCell(plhs[0],i,mxTemp); } } else { plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL); } switch(nlhs) { case 3: if (pnStarts) { plhs[2] = mxCreateNumericMatrix(1,nRuns,mxIntClass,mxREAL); for (i = 0; i<nRuns; i++) pnStarts[i]++; /* +1 to account for MATLAB being base 1. */ mxSetData(plhs[2], pnStarts); } else { plhs[2] = mxCreateDoubleMatrix(0,0,mxREAL); } case 2: if (pnLengths) { plhs[1] = mxCreateNumericMatrix(1,nRuns,mxIntClass,mxREAL); mxSetData(plhs[1], pnLengths); } else { plhs[1] = mxCreateDoubleMatrix(0,0,mxREAL); } } if (pnEnds) mxFree(pnEnds); if (pnStarts && nlhs < 3) mxFree(pnStarts); if (pnLengths && nlhs < 2) mxFree(pnLengths); }
mxArray *sf_c2_DYNctl_ver4_etud_nonlineaire_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
mxArray *sf_c3_Ensayos_Friccion_updateBuildInfo_args_info(void) { mxArray *mxBIArgs = mxCreateCellMatrix(1,0); return mxBIArgs; }
mxArray *sf_c3_Ensayos_Friccion_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
void mexFunction( int nOUT, mxArray *pOUT[], int nINP, const mxArray *pINP[]) { int n; int n_int; double *t; double *istart, *iend; /* check number of arguments: expects 3 inputs, 1 output */ if (nINP != 3) mexErrMsgTxt("Call with t, istart, iend as inputs."); if (nOUT != 1) mexErrMsgTxt("Requires one output."); /* unpack inputs */ n = mxGetM(pINP[0]) * mxGetN(pINP[0]); t = (double *)mxGetPr(pINP[0]); n_int = mxGetM(pINP[1]) * mxGetN(pINP[1]); if(mxGetM(pINP[2]) * mxGetN(pINP[2]) != n_int) mexErrMsgTxt("istart and iend must have same size"); istart = (double *)mxGetPr(pINP[1]); iend = (double *)mxGetPr(pINP[2]); pOUT[0] = mxCreateCellMatrix(n_int, 1); /* sequential search */ { int i, j, k; int ii, ll; i = 0; j = 0; mxArray *mxa; double *pr; while (i < n && j < n_int) { while(t[i] < istart[j] && i < n) i++; k = i-1; while(t[k] < iend[j] && k < n) k++; mxa = mxCreateDoubleMatrix(1, k-i+1, mxREAL); pr = mxGetPr(mxa); ll = 0; for (ii = i; ii <= k; ii++) { pr[ll] = ii; ll++; } mxSetCell(pOUT[0], j, mxa); j++; } for(ii=j+1; ii< n_int; ii++) { mxa = mxCreateDoubleMatrix(1, 0, mxREAL); mxSetCell(pOUT[0], ii, mxa); } } }
mxArray *sf_c38_old_Demo_RPS_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
// matlab entry point // C = fconv(A, cell of B, start, end); void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if (nrhs != 4) mexErrMsgTxt("Wrong number of inputs"); if (nlhs != 1) mexErrMsgTxt("Wrong number of outputs"); // get A const mxArray *mxA = prhs[0]; if (mxGetClassID(mxA) != mxDOUBLE_CLASS) mexErrMsgTxt("Invalid input: A"); // get B and start/end const mxArray *cellB = prhs[1]; mwSize num_bs = mxGetNumberOfElements(cellB); int start = (int)mxGetScalar(prhs[2]) - 1; int end = (int)mxGetScalar(prhs[3]) - 1; if (start < 0 || end >= num_bs || start > end) mexErrMsgTxt("Invalid input: start/end"); int len = end-start+1; // start threads thread_data *td = (thread_data *)mxCalloc(len, sizeof(thread_data)); HANDLE *hThreadArray = (HANDLE *)mxCalloc(len, sizeof(HANDLE)); const mwSize *A_dims = mxGetDimensions(mxA); double *A = (double *)mxGetPr(mxA); // return value plhs[0] = mxCreateCellMatrix(1, len); int batch_len = ceil(1.0*len/THREAD_MAX); for(int b = 0; b<batch_len; b++) { int nthread = 0; for (int t = 0; t < THREAD_MAX; t++) { int i = b*THREAD_MAX + t; if(i >= len) break; nthread++; //mexPrintf("i = %d\n", i); const mxArray *mxB = mxGetCell(cellB, i+start); td[i].A = A; const mwSize *B_dims = mxGetDimensions(mxB); td[i].B = (double *)mxGetPr(mxB); if (mxGetClassID(mxB) != mxDOUBLE_CLASS) mexErrMsgTxt("Invalid input: B"); td[i].A_dims[0] = A_dims[0]; td[i].A_dims[1] = A_dims[1]; if ((mxGetNumberOfDimensions(mxA) == 3)) td[i].A_dims[2] = A_dims[2]; else td[i].A_dims[2] = 1; td[i].B_dims[0] = B_dims[0]; td[i].B_dims[1] = B_dims[1]; if ((mxGetNumberOfDimensions(mxB) == 3)) td[i].B_dims[2] = B_dims[2]; else td[i].B_dims[2] = 1; if(td[i].A_dims[2] != td[i].B_dims[2]) mexErrMsgTxt("Invalid input: B"); // compute size of output int height = td[i].A_dims[0] - td[i].B_dims[0] + 1; int width = td[i].A_dims[1] - td[i].B_dims[1] + 1; if (height < 1 || width < 1) mexErrMsgTxt("Invalid input: B should be smaller than A"); td[i].C_dims[0] = height; td[i].C_dims[1] = width; td[i].mxC = mxCreateNumericArray(2, td[i].C_dims, mxDOUBLE_CLASS, mxREAL); td[i].C = (double *)mxGetPr(td[i].mxC); hThreadArray[i] = CreateThread( NULL, 0, process, &td[i], 0, NULL); if (hThreadArray[i] == NULL) mexErrMsgTxt("Error creating thread"); } // wait for the treads to finish and set return values WaitForMultipleObjects(nthread, hThreadArray+b*THREAD_MAX, TRUE, INFINITE); void *status; for (int t = 0; t < nthread; t++) { int i = b*THREAD_MAX + t; CloseHandle(hThreadArray[i]); mxSetCell(plhs[0], i, td[i].mxC); } } mxFree(td); mxFree(hThreadArray); }
mxArray *sf_c38_old_Demo_RPS_updateBuildInfo_args_info(void) { mxArray *mxBIArgs = mxCreateCellMatrix(1,0); return mxBIArgs; }
mxArray *sf_c4_MigrationBGOW_Proto6_MultiSwarm_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
//Main Function void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { //Input Args double *f, *A = NULL, *b = NULL, *lb = NULL, *ub = NULL, *y0 = NULL; double *sdpDIM = NULL, *SDP_pr = NULL; //Return Args double *x, *pval, *dval, *exitflag, *iter, *pdflag; //Options (most get defaults written in) int maxiter = 1500; int reuse=4,rpos=0,drho=1,ndim,sdpnmax=1; double penalty,rho,dbound,dlbound,zbar,r0,mu0,ylow,yhigh,gaptol,pnormtol,maxtrust,steptol,inftol,infptol; double lpb=1.0, datanorm[3], *dreuse, *fixed = NULL; //Internal Vars size_t nlincon = 0, ndec = 0, ncones = 0, nfix = 0; size_t lincon_nz = 0; size_t i, j; size_t nLB = 0, nUB = 0; int *temp_ir = NULL, *temp_jc = NULL; double *temp_pr = NULL; const char *onames[2] = {"pval","dval"}; const char *fnames[11] = {"iter","pdflag","r","mu","pstep","dstep","pnorm","ynorm","tracex","reuse","rho"}; double evaltime, *X = NULL; int iters = 0, status, indcell = 0; //DSDP Vars DSDP dsdp; SDPCone sdpcone = NULL; LPCone lpcone = NULL; BCone bcone = NULL; DSDPTerminationReason reason; DSDPSolutionType pdfeasible; //Sparse Indicing mwIndex *A_ir, *A_jc; //Version Return if(nrhs < 1) { if(nlhs < 1) printSolverInfo(); else plhs[0] = mxCreateString(DSDP_VERSION); return; } //Check Inputs checkInputs(prhs,nrhs); //Get pointers to Input variables f = mxGetPr(pF); ndec = mxGetNumberOfElements(pF); if(!mxIsEmpty(pA)) { A = mxGetPr(pA); A_ir = mxGetIr(pA); A_jc = mxGetJc(pA); b = mxGetPr(pB); nlincon = mxGetM(pA); lincon_nz = A_jc[mxGetN(pA)]; } if(nrhs > eLB && !mxIsEmpty(pLB)) lb = mxGetPr(pLB); if(nrhs > eUB && !mxIsEmpty(pUB)) ub = mxGetPr(pUB); if(nrhs > eSDP && !mxIsEmpty(pSDP)) { if(mxIsCell(pSDP)) ncones = mxGetNumberOfElements(pSDP); else ncones = 1; } if(nrhs > eY0 && !mxIsEmpty(pY0)) y0 = mxGetPr(pY0); if(nrhs > eOPTS && !mxIsEmpty(pOPTS) && mxGetField(pOPTS,0,"fixed") && !mxIsEmpty(mxGetField(pOPTS,0,"fixed"))) { fixed = mxGetPr(mxGetField(pOPTS,0,"fixed")); nfix = mxGetM(mxGetField(pOPTS,0,"fixed")); } //Create Outputs plhs[0] = mxCreateDoubleMatrix(ndec,1, mxREAL); plhs[1] = mxCreateStructMatrix(1,1,2,onames); mxSetField(plhs[1],0,onames[0],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[1],0,onames[1],mxCreateDoubleMatrix(1,1, mxREAL)); plhs[2] = mxCreateDoubleMatrix(1,1, mxREAL); x = mxGetPr(plhs[0]); pval = mxGetPr(mxGetField(plhs[1],0,onames[0])); dval = mxGetPr(mxGetField(plhs[1],0,onames[1])); exitflag = mxGetPr(plhs[2]); //Info Output plhs[3] = mxCreateStructMatrix(1,1,11,fnames); mxSetField(plhs[3],0,fnames[0],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[1],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[2],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[3],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[4],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[5],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[6],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[7],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[8],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[9],mxCreateDoubleMatrix(1,1, mxREAL)); mxSetField(plhs[3],0,fnames[10],mxCreateDoubleMatrix(1,1, mxREAL)); iter = mxGetPr(mxGetField(plhs[3],0,fnames[0])); pdflag = mxGetPr(mxGetField(plhs[3],0,fnames[1])); dreuse = mxGetPr(mxGetField(plhs[3],0,"reuse")); if(nlhs > 4) plhs[4] = mxCreateCellMatrix(ncones+(int)(nlincon>0)+(int)(nfix>0),1); //Set Defaults maxtime = 1000; printLevel = 0; //Create DSDP Problem DSDP_ERR( DSDPCreate((int)ndec,&dsdp), "Error Creating DSDP Problem"); //Set Monitor DSDP_ERR( DSDPSetMonitor(dsdp,DSDPMonitor,0), "Error Setting DSDP Monitor"); //Set Dual Objective for (i=0;i<ndec;i++){ DSDP_ERR( DSDPSetDualObjective(dsdp,(int)i+1,f[i]), "Error Adding Objective Coefficients"); } //Check finite bounds for allocation if(lb || ub) for(i=0;i<ndec;i++) { if(lb) if(!mxIsInf(lb[i])) nLB++; if(ub) if(!mxIsInf(ub[i])) nUB++; } //Set Bounds as BCone if(nLB || nUB) { DSDP_ERR( DSDPCreateBCone(dsdp, &bcone), "Error creating BCone"); DSDP_ERR( BConeAllocateBounds(bcone, (int)(nLB+nUB)), "Error allocating bounds"); for(i=0;i<ndec;i++) { if(nLB > 0 && !mxIsInf(lb[i])) DSDP_ERR( BConeSetLowerBound(bcone, (int)i+1, lb[i]), "Error setting lower bound"); if(nUB > 0 && !mxIsInf(ub[i])) DSDP_ERR( BConeSetUpperBound(bcone, (int)i+1, ub[i]), "Error setting upper bound"); } } //Set Linear Inequality Constraints as LPCone if(nlincon) { int M = (int)mxGetM(pA); int N = (int)mxGetN(pA); DSDP_ERR( DSDPCreateLPCone(dsdp, &lpcone), "Error creating LPCone (inequalities)"); //Create Memory to store A*x <= b in dsdp and integer format temp_jc = mxCalloc(N+2,sizeof(int)); temp_ir = mxCalloc(lincon_nz+M,sizeof(int)); temp_pr = mxCalloc(lincon_nz+M,sizeof(double)); //Copy over linear A for(i=0;i<=(size_t)N;i++) temp_jc[i] = (int)A_jc[i]; for(i=0;i<lincon_nz;i++) { temp_ir[i] = (int)A_ir[i]; temp_pr[i] = A[i]; } //Append linear rhs (b) temp_jc[N+1] = temp_jc[N] + M; for(i=lincon_nz,j=0;j<(size_t)M;j++) { if(b[j] != 0) { temp_ir[i] = (int)j; temp_pr[i++] = b[j]; } else temp_jc[N+1]--; } #ifdef DEBUG mexPrintf("---- Inequality Constraints ----\n"); for(i=0;i<=(size_t)(N+1);i++) mexPrintf("jc[%d] = %d\n",i,temp_jc[i]); for(i=0;i<lincon_nz+M;i++) mexPrintf("ir[%d] = %d, pr[%d] = %f\n",i,temp_ir[i],i,temp_pr[i]); #endif //Set LP Cone Data DSDP_ERR( LPConeSetData2(lpcone, M, temp_jc, temp_ir, temp_pr), "Error setting LP Cone data (inequality)" ); //Optionally set X data if(nlhs > 4) { mxSetCell(plhs[4],indcell,mxCreateDoubleMatrix(M,1,mxREAL)); DSDP_ERR( LPConeSetXVec(lpcone,mxGetPr(mxGetCell(plhs[4],indcell++)),M), "Error setting LP Cone X data" ); } } //Set Semidefinite Constraints as SDPCone if(ncones) { //Create the cone structure, specifying each constraint as a block DSDP_ERR( DSDPCreateSDPCone(dsdp,(int)ncones,&sdpcone), "Error creating SDPCone"); //Add each constraint cone for(i=0;i<ncones;i++) { if(ncones == 1 && !mxIsCell(pSDP)) { if(nlhs > 4) { mxSetCell(plhs[4],indcell,mxCreateDoubleMatrix(mxGetM(pSDP),1,mxREAL)); X = mxGetPr(mxGetCell(plhs[4],indcell++)); } ndim = addSDPCone(sdpcone,pSDP,(int)i,X); } else { if(nlhs > 4) { mxSetCell(plhs[4],indcell,mxCreateDoubleMatrix(mxGetM(mxGetCell(pSDP,i)),1,mxREAL)); X = mxGetPr(mxGetCell(plhs[4],indcell++)); } ndim = addSDPCone(sdpcone,mxGetCell(pSDP,i),(int)i,X); } //Update max dim if(sdpnmax < ndim) sdpnmax = ndim; } } //Set y0 if (y0) for (i=0;i<ndec;i++) { DSDP_ERR( DSDPSetY0(dsdp,(int)i+1,y0[i]), "Error setting Y0"); } //Determine whether to reuse schur complement matrix (dsdp authors' heuristic) if(ndec == 1) reuse = 1/sdpnmax; else reuse = ((int)ndec-2)/sdpnmax; if (ndec<50 && reuse==0) reuse=1; if (reuse>=1) reuse++; reuse=reuse*reuse; if (ndec<2000 && ndec>10) reuse=10; if (ndec>12) reuse=12; //Get DSDP Default Options DSDP_ERR( DSDPGetR(dsdp,&r0), "Error Getting R"); DSDP_ERR( DSDPGetPenaltyParameter(dsdp,&penalty), "Error Getting Penalty Parameter"); DSDP_ERR( DSDPGetPotentialParameter(dsdp,&rho), "Error Getting Potential Parameter"); DSDP_ERR( DSDPGetDualBound(dsdp,&dbound), "Error Getting Dual Bound"); DSDP_ERR( DSDPGetGapTolerance(dsdp,&gaptol), "Error Getting Gap Tolerance"); DSDP_ERR( DSDPGetRTolerance(dsdp,&inftol), "Error Getting R Tolerance"); DSDP_ERR( DSDPGetBarrierParameter(dsdp,&mu0), "Error Getting Barrier Parameter"); DSDP_ERR( DSDPGetMaxTrustRadius(dsdp,&maxtrust), "Error Getting Max Trust Radius"); DSDP_ERR( DSDPGetStepTolerance(dsdp,&steptol), "Error Getting Step Tolerance"); DSDP_ERR( DSDPGetPTolerance(dsdp,&infptol), "Error Getting P Tolerance"); DSDP_ERR( DSDPGetPNormTolerance(dsdp,&pnormtol), "Error Getting PNorm Tolerance"); //Get Data Norms to establish y bounds DSDP_ERR( DSDPGetDataNorms(dsdp, datanorm), "Error Getting Data Norms"); DSDP_ERR( DSDPGetYBounds(dsdp,&ylow,&yhigh), "Error Getting Y Bounds"); if (datanorm[0]==0){DSDP_ERR( DSDPSetYBounds(dsdp,-1.0,1.0), "Error Setting Y Bounds");} //Get User Options (overwrites defaults above) if(nrhs > eOPTS && !mxIsEmpty(pOPTS)) { //OPTI Options GetIntegerOption(pOPTS,"maxiter",&maxiter); GetDoubleOption(pOPTS,"maxtime",&maxtime); GetIntegerOption(pOPTS,"display",&printLevel); //DSDP Options GetDoubleOption(pOPTS,"r0",&r0); GetDoubleOption(pOPTS,"penalty",&penalty); GetDoubleOption(pOPTS,"rho",&rho); GetDoubleOption(pOPTS,"dbound",&dbound); GetDoubleOption(pOPTS,"gaptol",&gaptol); GetDoubleOption(pOPTS,"rtol",&inftol); GetDoubleOption(pOPTS,"mu0",&mu0); GetDoubleOption(pOPTS,"maxtrust",&maxtrust); GetDoubleOption(pOPTS,"steptol",&steptol); GetDoubleOption(pOPTS,"ptol",&infptol); GetDoubleOption(pOPTS,"pnormtol",&pnormtol); GetIntegerOption(pOPTS,"reuse",&reuse); GetIntegerOption(pOPTS,"rpos",&rpos); GetIntegerOption(pOPTS,"drho",&drho); //Check and set DSDP options without valid defaults if(mxGetField(pOPTS,0,"zbar") && !mxIsEmpty(mxGetField(pOPTS,0,"zbar"))) { GetDoubleOption(pOPTS,"zbar",&zbar); DSDP_ERR( DSDPSetZBar(dsdp,zbar), "Error Setting Z Bar"); } if(mxGetField(pOPTS,0,"dlbound") && !mxIsEmpty(mxGetField(pOPTS,0,"dlbound"))) { GetDoubleOption(pOPTS,"dlbound",&dlbound); DSDP_ERR( DSDPSetDualLowerBound(dsdp,dlbound), "Error Setting Dual Lower Bound"); } if(mxGetField(pOPTS,0,"ybound") && !mxIsEmpty(mxGetField(pOPTS,0,"ybound"))) { GetDoubleOption(pOPTS,"ybound",&yhigh); ylow = -yhigh; DSDP_ERR( DSDPSetYBounds(dsdp,ylow,yhigh), "Error Setting Y Bounds"); } } //Set DSDP Options with Defaults DSDP_ERR( DSDPSetMaxIts(dsdp,maxiter), "Error Setting Max Iterations"); DSDP_ERR( DSDPSetR0(dsdp,r0), "Error Setting Option R0 "); DSDP_ERR( DSDPSetPenaltyParameter(dsdp,penalty), "Error Setting Penalty Parameter"); DSDP_ERR( DSDPSetPotentialParameter(dsdp,rho), "Error Setting Potential Parameter"); DSDP_ERR( DSDPSetDualBound(dsdp,dbound), "Error Setting Dual Bound"); DSDP_ERR( DSDPSetGapTolerance(dsdp,gaptol), "Error Setting Gap Tolerance"); DSDP_ERR( DSDPSetRTolerance(dsdp,inftol), "Error Setting R Tolerance"); DSDP_ERR( DSDPSetBarrierParameter(dsdp,mu0), "Error Setting Barrier Parameter"); DSDP_ERR( DSDPSetMaxTrustRadius(dsdp,maxtrust), "Error Setting Max Trust Radius"); DSDP_ERR( DSDPSetStepTolerance(dsdp,steptol), "Error Setting Step Tolerance") DSDP_ERR( DSDPSetPTolerance(dsdp,infptol), "Error Setting P Tolerance"); DSDP_ERR( DSDPSetPNormTolerance(dsdp,pnormtol), "Error Setting PNorm Tolerance"); if(reuse < 0) reuse = 0; if(reuse > 15) reuse = 15; DSDP_ERR( DSDPReuseMatrix(dsdp,reuse), "Error Setting Reuse Matrix"); //Set Other DSDP Options DSDP_ERR( DSDPUsePenalty(dsdp,rpos), "Error Setting Use Penalty"); DSDP_ERR( DSDPUseDynamicRho(dsdp,drho), "Error Setting Dynamic Rho"); if (lpb<0.1) lpb=0.1; if(lpcone) DSDP_ERR( LPConeScaleBarrier(lpcone,lpb), "Error Setting LPCone Scale Barrier"); //Set Fixed Variables if(fixed != NULL) { if(nlhs > 4) { mxSetCell(plhs[4],indcell,mxCreateDoubleMatrix(nfix,1,mxREAL)); X = mxGetPr(mxGetCell(plhs[4],indcell++)); } else X = NULL; DSDP_ERR( DSDPSetFixedVariables(dsdp, fixed, &fixed[nfix], X, (int)nfix), "Error Setting Fixed Variables"); } //Print Header if(printLevel) { mexPrintf("\n------------------------------------------------------------------\n"); mexPrintf(" This is DSDP v%s\n",DSDP_VERSION); mexPrintf(" Authors: Steve Benson, Yinyu Ye and Xiong Zhang\n\n"); mexPrintf(" Problem Properties:\n"); mexPrintf(" # Decision Variables: %4d\n",ndec); mexPrintf(" # Linear Inequalities: %4d ",nlincon); if(nlincon) mexPrintf("[%d nz]\n",lincon_nz); else mexPrintf("\n"); mexPrintf(" # Semidefinite Cones: %4d\n",ncones); mexPrintf("------------------------------------------------------------------\n"); } //Start timer start = clock(); //Call DSDP Setup to initialize problem DSDP_ERR( DSDPSetup(dsdp), "Error setting up DSDP Problem, likely out of memory"); //Now Solve the Problem status = DSDPSolve(dsdp); //Stop Timer end = clock(); evaltime = ((double)(end-start))/CLOCKS_PER_SEC; //Determine Stop Reason if(status == 0) { DSDP_ERR( DSDPStopReason(dsdp,&reason), "Error retrieving post-solve stop reason"); } else if(status == DSDP_MAX_TIME || status == DSDP_USER_TERMINATION) reason = status; else { DSDP_ERR( status, "Error solving DSDP Problem!");} //Computer X and Get Solution Type if (reason!=DSDP_INFEASIBLE_START) DSDP_ERR( DSDPComputeX(dsdp), "Error computing post-solve x"); DSDP_ERR( DSDPGetSolutionType(dsdp,&pdfeasible), "Error collecting post-solve solution type"); //Copy Dual Solution DSDP_ERR( DSDPGetY(dsdp,x,(int)ndec), "Error returning Solution Vector"); //Collect Output Statistics DSDPGetIts(dsdp,&iters); DSDPGetDObjective(dsdp,dval); DSDPGetPObjective(dsdp,pval); DSDPGetR(dsdp,mxGetPr(mxGetField(plhs[3],0,"r"))); DSDPGetBarrierParameter(dsdp,mxGetPr(mxGetField(plhs[3],0,"mu"))); DSDPGetStepLengths(dsdp,mxGetPr(mxGetField(plhs[3],0,"pstep")),mxGetPr(mxGetField(plhs[3],0,"dstep"))); DSDPGetPnorm(dsdp,mxGetPr(mxGetField(plhs[3],0,"pnorm"))); DSDPGetYMaxNorm(dsdp,mxGetPr(mxGetField(plhs[3],0,"ynorm"))); DSDPGetTraceX(dsdp,mxGetPr(mxGetField(plhs[3],0,"tracex"))); DSDPGetPotentialParameter(dsdp,mxGetPr(mxGetField(plhs[3],0,"rho"))); *dreuse = (double)reuse; //Assign to MATLAB *iter = (double)iters; *exitflag = (double)reason; *pdflag = (double)pdfeasible; //Print Header if(printLevel){ //Detail termination reason switch(reason) { //Success case DSDP_CONVERGED: mexPrintf("\n *** DSDP CONVERGED ***\n"); break; case DSDP_UPPERBOUND: mexPrintf("\n *** DSDP CONVERGED: Dual Objective exceeds its bound***\n"); break; //Error case DSDP_SMALL_STEPS: mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: Terminated due to Small Steps ***\n"); break; case DSDP_MAX_IT: mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: Maximum Iterations Reached ***\n"); break; case DSDP_MAX_TIME: mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: Maximum Time Reached ***\n"); break; case DSDP_INFEASIBLE_START: mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: Infeasible Starting Point ***\n"); break; case DSDP_USER_TERMINATION: mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: User Exited ***\n"); break; //Here is ok too? default: mexPrintf("\n *** DSDP FINISHED ***\n"); break; } //Detail solution status if(reason == DSDP_CONVERGED || reason == DSDP_UPPERBOUND) { switch(pdfeasible) { //Success case DSDP_PDFEASIBLE: mexPrintf(" Solution Status: Both Primal and Dual are Feasible and Bounded\n"); break; //Error case DSDP_UNBOUNDED: mexPrintf(" Solution Status: Dual Unbounded, Primal Infeasible\n"); break; case DSDP_INFEASIBLE: mexPrintf(" Solution Status: Primal Unbounded, Dual Infeasible\n"); break; case DSDP_PDUNKNOWN: default: mexPrintf(" Solution Status: Unknown - Check Dual Bounds\n"); break; } } if(reason==DSDP_CONVERGED) mexPrintf("\n Final Primal Objective: %2.5g\n Final Dual Objective: %2.5g\n In %5d iterations\n %5.2f seconds\n",*pval,*dval,iters,evaltime); mexPrintf("------------------------------------------------------------------\n\n"); } //Free DSDP Problem DSDP_ERR( DSDPDestroy(dsdp), "Error Destroying DSDP Problem"); //Free Temporary memory if(temp_jc) {mxFree(temp_jc); temp_jc = NULL;} if(temp_ir) {mxFree(temp_ir); temp_ir = NULL;} if(temp_pr) {mxFree(temp_pr); temp_pr = NULL;} }
mxArray *sf_c23_CSE1_DP_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
mxArray *sf_c1_a3_updateBuildInfo_args_info(void) { mxArray *mxBIArgs = mxCreateCellMatrix(1,0); return mxBIArgs; }
// Export the whole network or a parametric description of preprocessors or algorithms int csimMexExport(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ( !TheNetwork ) mexErrMsgTxt("CSIM: No network initialized yet!\n"); if ( nrhs == 1 ) { // Export the whole network if ( nlhs > 0 ) plhs[0] = TheNetwork->exportNetwork(); } else if ( nrhs == 2 ) { // Export a preprocessor or an algorithm if ( nlhs > 0) { // Get identifiers of preprocessors or algorithms uint32 *idx; int nIdx; if ( getUint32Vector(prhs[1],&idx,&nIdx) ) mexErrMsgTxt("CSIM-Usage: csim('set',idx[,field,value]*); idx is not a uint32 vector.\n"); double **p=0; int *m; if ( TheNetwork->exportObject(idx,nIdx,&p,&m) < 0 ) { // Something went wrong clear all reserved memory if ( p ) { for (int i=0; i<nIdx; i++) { if (p[i]) { free(p[i]); p[i]=0; } } free(p); p=0; } if (m) { free(m); m=0; } return -1; } plhs[0] = mxCreateCellMatrix(1, nIdx); // Copy the export values to a cell array mxArray *representation; for (int i=0; i<nIdx; i++) { representation = mxCreateDoubleMatrix(1, m[i], mxREAL); memcpy(mxGetPr(representation),p[i],m[i]*sizeof(double)); mxSetCell(plhs[0], i, representation); } // Clear the memory if ( p ) { for (int i=0; i<nIdx; i++) { if (p[i]) { free(p[i]); p[i]=0; } } free(p); p=0; } if (m) { free(m); m=0; } return 0; } else mexErrMsgTxt("CSIM-Usage: values = csim('export', idx);\n"); } else mexErrMsgTxt("CSIM-Usage: net = csim('export'); or\n" " values = csim('export', idx);\n" ); return 0; }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *tstamp; /* spike timestamps (in 1/10000 sec) */ double *x_pos, *y_pos, *phi_pos; double *on_same_tet; double ***triplets_ts_ptr, ***triplets_x_ptr, ***triplets_y_ptr, ***triplets_phi_ptr; int **triplets_count; int **triplets_last_ts; int *idxs; int cidx[3]; int midx[2]; int n_spikes; /* total number of spike */ int n_triplets_true = 0, n_triplets_chk = 0; /* diagnostics */ int n_combs; /* number of combinations */ int i,j,k, i_last; int omit_double = 1; /* if TRUE, then a spike can't be member of more than one triplet of the same kind, this helps avoiding many doubles that would make the interpretation hard */ double *triplets_freq; double *triples_table; int *triples_lookup; /* direct lookup table */ double time_span; enum {TSTAMP=0, IDXS, X_POS, Y_POS, PHI_POS, NCELLS, TSPAN, ON_SAME_TET } in_arg_order; enum {TRIPLETS_FREQ, TRIPLES_TABLE, TRIPLETS_TS, TRIPLETS_X, TRIPLETS_Y, TRIPLETS_PHI } out_arg_order; if(nrhs != 8 ) mexErrMsgTxt("Eight inputs required"); if(nlhs != 6 ) mexErrMsgTxt("Six outputs required"); /* MEX related stuff, not really related with algorithms */ /* extracting timestamps */ mexPrintf("class of tstamp: %d\n", mxGetClassID(prhs[TSTAMP])); /* DEBUG */ n_spikes = mxGetM(prhs[TSTAMP]); if(mxGetN(prhs[TSTAMP]) != 1) mexErrMsgTxt("Timestamp must be a column vector"); tstamp = mxGetPr(prhs[TSTAMP]); /* extracting cell indices */ if(mxGetM(prhs[IDXS]) != n_spikes) mexErrMsgTxt("indices and timestamps must have same length"); { int i; double *dixs; dixs = mxGetPr(prhs[IDXS]); idxs = (int *) mxCalloc(n_spikes, sizeof(int)); for(i = 0; i < n_spikes; i++) idxs[i] = (int)(dixs[i])-1; } /* extracting location */ mexPrintf("class of x: %d\n", mxGetClassID(prhs[X_POS])); /* DEBUG */ if(mxGetN(prhs[X_POS]) != 1) mexErrMsgTxt("x_pos must be a column vector"); x_pos = mxGetPr(prhs[X_POS]); if(mxGetN(prhs[Y_POS]) != 1) mexErrMsgTxt("y_pos must be a column vector"); y_pos = mxGetPr(prhs[Y_POS]); if(mxGetN(prhs[PHI_POS]) != 1) mexErrMsgTxt("phi_pos must be a column vector"); phi_pos = mxGetPr(prhs[PHI_POS]); /* extracting n_cells */ if(mxGetM(prhs[NCELLS]) * mxGetN(prhs[NCELLS]) != 1) mexErrMsgTxt("n_cells must be a scalar"); n_cells = (int)mxGetScalar(prhs[NCELLS]); /* extracting time_span*/ if(mxGetM(prhs[TSPAN]) * mxGetN(prhs[TSPAN]) != 1) mexErrMsgTxt("time_span must be a scalar"); time_span = (int)mxGetScalar(prhs[TSPAN]); /* extracting on_same_tet */ if(mxGetM(prhs[ON_SAME_TET]) != n_cells || mxGetN(prhs[ON_SAME_TET]) != n_cells) mexErrMsgTxt("on_same_tet must be a n_cells X n_cells matrix"); on_same_tet = (int)mxGetPr(prhs[ON_SAME_TET]); /* create outputs */ n_combs = 0; for(i = 0; i < n_cells; i++) for(j = i+1; j < n_cells; j++) for(k = j+1; k < n_cells; k++) { /* int ix = lookup3[i] + (n_cells - i) *(j - i - 1) */ /* - (j - i - 1) * (j -i) /2 + (k-j-1); */ int i1, i2, i3; midx[0] = i; midx[1] = j; i1 = on_same_tet[mxCalcSingleSubscript(prhs[ON_SAME_TET], 2, midx)]; midx[0] = i; midx[1] = k; i2 = on_same_tet[mxCalcSingleSubscript(prhs[ON_SAME_TET], 2, midx)]; midx[0] = j; midx[1] = k; i3 = on_same_tet[mxCalcSingleSubscript(prhs[ON_SAME_TET], 2, midx)]; if(!(i1 || i2 || i3)) n_combs++; } mexPrintf("n_combs = %d\n", n_combs); plhs[TRIPLETS_FREQ] = mxCreateNumericMatrix(n_combs, 6, mxDOUBLE_CLASS, mxREAL); triplets_freq = mxGetPr(plhs[TRIPLETS_FREQ]); plhs[TRIPLES_TABLE] = mxCreateNumericMatrix(n_combs, 3, mxDOUBLE_CLASS, mxREAL); triples_table = mxGetPr(plhs[TRIPLES_TABLE]); plhs[TRIPLETS_TS] = mxCreateCellMatrix(n_combs, 6); plhs[TRIPLETS_X] = mxCreateCellMatrix(n_combs, 6); plhs[TRIPLETS_Y] = mxCreateCellMatrix(n_combs, 6); plhs[TRIPLETS_PHI] = mxCreateCellMatrix(n_combs, 6); /* create lookup tables direct and inverse */ triples_lookup = (int *) mxCalloc(n_cells*n_cells*n_cells, sizeof(int)); for(i = 0; i < n_cells*n_cells*n_cells; i++) triples_lookup[i] = -1; triplets_last_ts = (int **)mxCalloc(3, sizeof(int *)); for(i = 0; i < 3; i++) triplets_last_ts[i] = (int *)mxCalloc(n_combs, sizeof(int)); { int ix = 0; for(i = 0; i < n_cells; i++) for(j = i+1; j < n_cells; j++) for(k = j+1; k < n_cells; k++) { /* int ix = lookup3[i] + (n_cells - i) *(j - i - 1) */ /* - (j - i - 1) * (j -i) /2 + (k-j-1); */ int i1, i2, i3; midx[0] = i; midx[1] = j; i1 = on_same_tet[mxCalcSingleSubscript(prhs[ON_SAME_TET], 2, midx)]; midx[0] = i; midx[1] = k; i2 = on_same_tet[mxCalcSingleSubscript(prhs[ON_SAME_TET], 2, midx)]; midx[0] = j; midx[1] = k; i3 = on_same_tet[mxCalcSingleSubscript(prhs[ON_SAME_TET], 2, midx)]; if(!(i1 || i2 || i3)) { midx[0] = ix; midx[1] = 0; triples_table[mxCalcSingleSubscript(plhs[TRIPLES_TABLE], 2, midx)] = i+1; midx[1] = 1; triples_table[mxCalcSingleSubscript(plhs[TRIPLES_TABLE], 2, midx)] = j+1; midx[1] = 2; triples_table[mxCalcSingleSubscript(plhs[TRIPLES_TABLE], 2, midx)] = k+1; triples_lookup[lookup_idx(i,j,k)] = ix; ix++; } } } /* now complete the direct lookup table */ for(i = 0; i < n_cells; i++) for(j = 0; j < n_cells; j++) for(k = 0; k < n_cells; k++) { cidx[0] = i; cidx[1] = j; cidx[2] = k; order_tuple(cidx, 3); triples_lookup[lookup_idx(i,j,k)] = triples_lookup[lookup_idx(cidx[0], cidx[1], cidx[2])]; } /* and now compute the frequency table */ i_last = 0; for(i = 0; i < n_spikes-2; i++) { double t1 = tstamp[i]; double tl = t1 + time_span; int ix = idxs[i]; int jx, kx, cx, px; if(! (i % 10000)) mexPrintf("i: %d\n", i); while(i_last < n_spikes && tstamp[i_last] < tl) i_last++; for(j = i+1; j < i_last; j++) if(idxs[j] != ix) { jx = idxs[j]; for(k = j+1; k < i_last; k++) if(idxs[k] != ix && idxs[k] != jx) { kx = idxs[k]; cidx[0] = ix; cidx[1] = jx; cidx[2] = kx; px = order_code(cidx); order_tuple(cidx, 3); cx = triples_lookup[lookup_idx(cidx[0], cidx[1], cidx[2])]; if(cx >= 0 && (!omit_double || (triplets_last_ts[0][cx] != tstamp[i] && triplets_last_ts[1][cx] != tstamp[j] && triplets_last_ts[2][cx] != tstamp[k]))) { triplets_last_ts[0][cx] = tstamp[i]; triplets_last_ts[1][cx] = tstamp[j]; triplets_last_ts[2][cx] = tstamp[k]; n_triplets_true++; midx[0] = cx; midx[1] = px; triplets_freq[mxCalcSingleSubscript(plhs[TRIPLETS_FREQ], 2, midx)]++; } } } } /* now allocate memory for timestamps, x, y */ triplets_ts_ptr = (double ***)mxCalloc(6, sizeof(double **)); triplets_x_ptr = (double ***)mxCalloc(6, sizeof(double **)); triplets_y_ptr = (double ***)mxCalloc(6, sizeof(double **)); triplets_phi_ptr = (double ***)mxCalloc(6, sizeof(double **)); triplets_count = (int **)mxCalloc(6, sizeof(int *)); for(i = 0; i < 6; i++) { triplets_ts_ptr[i] = (double **)mxCalloc(n_combs, sizeof(double **)); triplets_x_ptr[i] = (double **)mxCalloc(n_combs, sizeof(double *)); triplets_y_ptr[i] = (double **)mxCalloc(n_combs, sizeof(double *)); triplets_phi_ptr[i] = (double **)mxCalloc(n_combs, sizeof(double *)); triplets_count[i] = (int *)mxCalloc(n_combs, sizeof(int)); } for(i = 0; i < n_combs; i++) for(j = 0; j < 6; j++) { int n_triplets; mxArray *tmp; midx[0] = i; midx[1] = j; n_triplets = triplets_freq[mxCalcSingleSubscript(plhs[TRIPLETS_FREQ], 2, midx)]; tmp = mxCreateNumericMatrix(n_triplets, 1, mxDOUBLE_CLASS, mxREAL); triplets_ts_ptr[j][i] = mxGetPr(tmp); mxSetCell(plhs[TRIPLETS_TS], mxCalcSingleSubscript(plhs[TRIPLETS_TS], 2, midx), tmp); n_triplets_chk += n_triplets; tmp = mxCreateNumericMatrix(n_triplets, 1, mxDOUBLE_CLASS, mxREAL); triplets_x_ptr[j][i] = mxGetPr(tmp); mxSetCell(plhs[TRIPLETS_X], mxCalcSingleSubscript(plhs[TRIPLETS_X], 2, midx), tmp); tmp = mxCreateNumericMatrix(n_triplets, 1, mxDOUBLE_CLASS, mxREAL); triplets_y_ptr[j][i] = mxGetPr(tmp); mxSetCell(plhs[TRIPLETS_Y], mxCalcSingleSubscript(plhs[TRIPLETS_Y], 2, midx), tmp); tmp = mxCreateNumericMatrix(n_triplets, 1, mxDOUBLE_CLASS, mxREAL); triplets_phi_ptr[j][i] = mxGetPr(tmp); mxSetCell(plhs[TRIPLETS_PHI], mxCalcSingleSubscript(plhs[TRIPLETS_PHI], 2, midx), tmp); } if (n_triplets_chk != n_triplets_true) { char errmsg[80]; sprintf(errmsg, "n_triplets = %d, n_triplets_chk = %d!!!", n_triplets_true, n_triplets_chk); mexErrMsgTxt(errmsg); } /* now fill timestamp and position arrays */ for (i = 0; i < 3; i++) for(j = 0; j < n_combs; j++) triplets_last_ts[i][j] = 0; i_last = 0; for(i = 0; i < n_spikes-2; i++) { double t1 = tstamp[i]; double tl = t1 + time_span; int ix = idxs[i]; int jx, kx, cx, px; if(! (i % 10000)) mexPrintf("i: %d\n", i); while(i_last < n_spikes && tstamp[i_last] < tl) i_last++; for(j = i+1; j < i_last; j++) if(idxs[j] != ix) { jx = idxs[j]; for(k = j+1; k < i_last; k++) if(idxs[k] != ix && idxs[k] != jx) { kx = idxs[k]; cidx[0] = ix; cidx[1] = jx; cidx[2] = kx; px = order_code(cidx); order_tuple(cidx, 3); cx = triples_lookup[lookup_idx(cidx[0], cidx[1], cidx[2])]; if(cx >= 0 && (!omit_double || (triplets_last_ts[0][cx] != tstamp[i] && triplets_last_ts[1][cx] != tstamp[j] && triplets_last_ts[2][cx] != tstamp[k]))) { triplets_last_ts[0][cx] = tstamp[i]; triplets_last_ts[1][cx] = tstamp[j]; triplets_last_ts[2][cx] = tstamp[k]; triplets_ts_ptr[px][cx][triplets_count[px][cx]] = tstamp[i]; triplets_x_ptr[px][cx][triplets_count[px][cx]] = x_pos[i]; triplets_y_ptr[px][cx][triplets_count[px][cx]] = y_pos[i]; triplets_phi_ptr[px][cx][triplets_count[px][cx]] = phi_pos[i]; triplets_count[px][cx]++; } } } } mxFree((void *)triples_lookup); for(i = 0; i < 6; i++) { mxFree((void *)triplets_ts_ptr[i]); mxFree((void *)triplets_x_ptr[i]); mxFree((void *)triplets_y_ptr[i]); mxFree((void *)triplets_phi_ptr[i]); mxFree((void *)triplets_count[i]); } for(i = 0; i < 3; i++) mxFree((void *)triplets_last_ts[i]); mxFree((void *)triplets_ts_ptr); mxFree((void *)triplets_x_ptr); mxFree((void *)triplets_y_ptr); mxFree((void *)triplets_phi_ptr); mxFree((void *)triplets_count); mxFree((void *)triplets_last_ts); /* mexCallMATLAB(0, NULL, 1, &plhs[TRIPLETS_PHI], "disp"); */ }
mxArray *sf_c14_ARP_02_RPSs_Bdr_GK_BIS5_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
mxArray *sf_c39_CSE1_Oculus_gesture_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
mxArray *sf_c14_ARP_02_RPSs_Bdr_GK_BIS5_updateBuildInfo_args_info(void) { mxArray *mxBIArgs = mxCreateCellMatrix(1,0); return mxBIArgs; }
void LTFAT_NAME(ltfatMexFnc)( int nlhs, mxArray *plhs[], int UNUSED(nrhs), const mxArray *prhs[]) { const mxArray* mxs = prhs[0]; const mxArray* mxtgrad = prhs[1]; const mxArray* mxfgrad = prhs[2]; const mxArray* mxa = prhs[3]; const mxArray* mxcfreq = prhs[4]; ltfatInt M = mxGetNumberOfElements(mxs); const LTFAT_REAL* sPtr[M]; const LTFAT_REAL* tgradPtr[M]; const LTFAT_REAL* fgradPtr[M]; double aPtr[M]; double cfreqPtr[M]; LTFAT_REAL* srPtr[M]; ltfatInt N[M]; mxArray* mxsr = mxCreateCellMatrix(M, 1); plhs[0] = mxsr; const double* a = mxGetPr(mxa); const double* cfreq = mxGetPr(mxcfreq); memcpy(aPtr, a, M * sizeof * a); memcpy(cfreqPtr, cfreq, M * sizeof * cfreq); for (ltfatInt m = 0; m < M; m++) { N[m] = mxGetM(mxGetCell(mxs, m)); sPtr[m] = mxGetData(mxGetCell(mxs, m)); tgradPtr[m] = mxGetData(mxGetCell(mxtgrad, m)); fgradPtr[m] = mxGetData(mxGetCell(mxfgrad, m)); mxSetCell(mxsr, m, ltfatCreateMatrix(N[m], 1, LTFAT_MX_CLASSID, mxREAL)); srPtr[m] = mxGetData(mxGetCell(mxsr, m)); } // This function uses optional output arguments fbreassOptOut* optout = NULL; mxArray* repos; ltfatInt sumN = 0; if (nlhs > 1) { for (ltfatInt ii = 0; ii < M; ii++) { sumN += N[ii]; } repos = mxCreateCellMatrix(sumN, 1); plhs[1] = repos; optout = fbreassOptOut_init(sumN, 16 ); } // Adjust a ltfatInt acols = mxGetN(mxa); if (acols > 1) { for (ltfatInt m = 0; m < M; m++) { aPtr[m] /= a[M + m]; } } // Run it LTFAT_NAME(filterbankreassign)(sPtr, tgradPtr, fgradPtr, N, a, cfreqPtr, M, srPtr, REASS_DEFAULT, optout); // Process the optional output if (optout != NULL) { for (ltfatInt ii = 0; ii < sumN; ii++) { ltfatInt l = optout->reposl[ii]; // Create an array of a proper length. even an empty one mxArray* cEl = mxCreateDoubleMatrix( l , l > 0 ? 1 : 0, mxREAL); mxSetCell(repos, ii, cEl); double* cElPtr = mxGetPr(cEl); // Convert to double and +1 to Matlab indexes... for (ltfatInt jj = 0; jj < optout->reposl[ii]; jj++) { cElPtr[jj] = (double) (optout->repos[ii][jj] + 1.0); } } fbreassOptOut_destroy(optout); } }
mxArray *sf_c9_CusakisME4901arcs2_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }
mxArray *sf_c39_Demo_KinectWaveWalkInvade_updateBuildInfo_args_info(void) { mxArray *mxBIArgs = mxCreateCellMatrix(1,0); return mxBIArgs; }
mxArray *sf_c1_varymultiswarm_third_party_uses_info(void) { mxArray * mxcell3p = mxCreateCellMatrix(1,0); return(mxcell3p); }