示例#1
0
/// get type of current argument (does not increment argument counter)
IFType CMatlabInterface::get_argument_type()
{
	const mxArray* arg=m_rhs[m_rhs_counter];
	ASSERT(arg);

	if (mxIsSparse(arg))
	{
		if (mxIsUint8(arg))
			return SPARSE_BYTE;
		if (mxIsChar(arg))
			return SPARSE_CHAR;
		if (mxIsInt32(arg))
			return SPARSE_INT;
		if (mxIsDouble(arg))
			return SPARSE_REAL;
		if (mxIsInt16(arg))
			return SPARSE_SHORT;
		if (mxIsSingle(arg))
			return SPARSE_SHORTREAL;
		if (mxIsUint16(arg))
			return SPARSE_WORD;

		return UNDEFINED;
	}

	if (mxIsInt32(arg))
		return DENSE_INT;
	if (mxIsDouble(arg))
		return DENSE_REAL;
	if (mxIsInt16(arg))
		return DENSE_SHORT;
	if (mxIsSingle(arg))
		return DENSE_SHORTREAL;
	if (mxIsUint16(arg))
		return DENSE_WORD;

	if (mxIsChar(arg))
		return STRING_CHAR;
	if (mxIsUint8(arg))
		return STRING_BYTE;

	if (mxIsCell(arg))
	{
		const mxArray* cell=mxGetCell(arg, 0);
		if (cell && mxGetM(cell)==1)
		{
			if (mxIsUint8(cell))
				return STRING_BYTE;
			if (mxIsChar(cell))
				return STRING_CHAR;
			if (mxIsInt32(cell))
				return STRING_INT;
			if (mxIsInt16(cell))
				return STRING_SHORT;
			if (mxIsUint16(cell))
				return STRING_WORD;
		}
	}

	return UNDEFINED;
}
/***********************************************************************//**
 * \brief mexFunction to append a stack to an existing em-file.
 **************************************************************************/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) {


    size_t filename_length = 0;
#define __MAX_FILENAME_LENGTH__ ((int)2048)
    char filename[__MAX_FILENAME_LENGTH__+1];
#define __MAX_S__LENGTH__ (__MAX_FILENAME_LENGTH__+1024)
    char s[__MAX_S__LENGTH__+1];

    tom_io_em_header header;
#define __BUFFERLENGTH_SYNOPSIS__ 1024
    char synopsis[__BUFFERLENGTH_SYNOPSIS__];
    void *data;

    mxArray *mxData;
    size_t sizex, sizey, sizez;
    mxClassID mxType;
    mxComplexity mxIsComplexVolume;

    size_t i;
    int res;
    int header_read;
    int allow_conversion = 1;

    mxArray *plhs_tmp[5] = { NULL, NULL, NULL, NULL, NULL };





    snprintf(synopsis, __BUFFERLENGTH_SYNOPSIS__, "[size, magic, comment, emdata, userdata] = %s(filename, volume, [allow_conversion])", mexFunctionName());

    if (nrhs==0 && nlhs==0) {
        /* Print help */
        mexPrintf("SYNOPSIS: %s\n", synopsis);
        mexPrintf("mex-file compiled from file \"" __FILE__ "\" at " __DATE__ ", " __TIME__ ".\n");
        return;
    }

    if (nrhs < 2 || nrhs > 3) {
        snprintf(s, __MAX_S__LENGTH__, "%s: call function with up to 3 parameters: %s.", mexFunctionName(), synopsis);
        mexErrMsgTxt(s);
    }
    if (nlhs>5) {
        snprintf(s, __MAX_S__LENGTH__, "%s: Too many output parameters: %s.", mexFunctionName(), synopsis);
        mexErrMsgTxt(s);
    }


    {
        const mxArray *PRHS_FILENAME = prhs[0];
        const mxArray *PRHS_VOLUME = prhs[1];
        const mwSize *size;


        /* Check input parameters! */
        if (!mxIsChar(PRHS_FILENAME) || mxGetNumberOfDimensions(PRHS_FILENAME)!=2 || mxGetM(PRHS_FILENAME)!=1 || (filename_length=mxGetN(PRHS_FILENAME))<1) {
            snprintf(s, __MAX_S__LENGTH__, "%s: needs the file name as first parameter: %s.", mexFunctionName(), synopsis);
            mexErrMsgTxt(s);
        }
        if (filename_length >= __MAX_FILENAME_LENGTH__) {
            snprintf(s, __MAX_S__LENGTH__, "%s: Maximal length of file name exceeded. (Recompile with larger buffer :)", mexFunctionName());
            mexErrMsgTxt(s);
        }
        mxGetString(PRHS_FILENAME, filename, __MAX_FILENAME_LENGTH__);

        if (!mxIsNumeric(PRHS_VOLUME) || mxGetNumberOfDimensions(PRHS_VOLUME)>3) {
            snprintf(s, __MAX_S__LENGTH__, "%s: needs a numerical volume as second parameter: %s", mexFunctionName(), synopsis);
            mexErrMsgTxt(s);
        }
        data = mxGetData(PRHS_VOLUME);
        size = mxGetDimensions(PRHS_VOLUME);
        mxType = mxGetClassID(PRHS_VOLUME);
        mxIsComplexVolume = mxIsComplex(PRHS_VOLUME);
        sizex = size[0];
        sizey = size[1];
        sizez = mxGetNumberOfDimensions(PRHS_VOLUME)==3 ? size[2] : 1;

        if (mxIsComplexVolume) {
            if (mxType==mxSINGLE_CLASS || mxType==mxDOUBLE_CLASS) {
                mwSize size[3];
                size_t x, y, z;

                size[0] = sizex*2;
                size[1] = sizey;
                size[2] = sizez;
                if (!(mxData = mxCreateNumericArray(sizez==1 ? 2 : 3, size, mxType, mxREAL))) {
                    mexErrMsgTxt("%s: Error allocating temporary buffer for complex data.");
                }
                data = mxGetData(mxData);
                if (mxType == mxSINGLE_CLASS) {
                    float *data_as_real = (float *)data;
                    const float *data_real = (const float *)mxGetData(PRHS_VOLUME);
                    const float *data_complex = (const float *)mxGetImagData(PRHS_VOLUME);
                    for (z=0; z<sizez; z++) {
                        for (y=0; y<sizey; y++) {
                            for (x=0; x<sizex; x++) {
                                *data_as_real++ = *data_real++;
                                *data_as_real++ = *data_complex++;
                            }
                        }
                    }
                } else {
                    double *data_as_real = (double *)data;
                    const double *data_real = (const double *)mxGetData(PRHS_VOLUME);
                    const double *data_complex = (const double *)mxGetImagData(PRHS_VOLUME);
                    for (z=0; z<sizez; z++) {
                        for (y=0; y<sizey; y++) {
                            for (x=0; x<sizex; x++) {
                                *data_as_real++ = *data_real++;
                                *data_as_real++ = *data_complex++;
                            }
                        }
                    }
                }
            } else {
                snprintf(s, __MAX_S__LENGTH__, "%s: Complex data for this type not supported (currently only for single and double).", mexFunctionName());
                mexErrMsgTxt(s);
            }
        }

        if (nrhs >= 3) {
            mwSize numel;
            numel = mxGetM(prhs[2]) * mxGetN(prhs[2]);
            if (!(mxIsNumeric(prhs[2]) || mxIsLogical(prhs[2])) || numel>1) {
                snprintf(s, __MAX_S__LENGTH__, "%s: allow_conversion must be one of true, false or [].", mexFunctionName(), synopsis);
                mexErrMsgTxt(s);
            }
            if (numel == 1) {
                allow_conversion = mxGetScalar(prhs[2]) != 0.;
            }
        }
    }


    {
        /* Allocate the memory for the ouput, so that in case of successfully writing, no
           error can happen afterwards in the mexfunction. */
        switch (nlhs) {
        case 5:
            if (!(plhs_tmp[4] = mxCreateNumericMatrix(1, 256, mxINT8_CLASS, mxREAL))) {
                mexErrMsgTxt("Error allocating memory");
            }
        case 4:
            if (!(plhs_tmp[3] = mxCreateNumericMatrix(1, 40, mxINT32_CLASS, mxREAL))) {
                mexErrMsgTxt("Error allocating memory");
            }
        case 3:
            if (!(plhs_tmp[2] = mxCreateNumericMatrix(1, 80, mxINT8_CLASS, mxREAL))) {
                mexErrMsgTxt("Error allocating memory");
            }
        case 2:
            if (!(plhs_tmp[1] = mxCreateNumericMatrix(1, 4, mxINT8_CLASS, mxREAL))) {
                mexErrMsgTxt("Error allocating memory");
            }
        case 1:
            if (!(plhs_tmp[0] = mxCreateNumericMatrix(3, 1, mxUINT32_CLASS, mxREAL))) {
                mexErrMsgTxt("Error allocating memory");
            }
        }
    }


    res = tom_io_em_write_append_stack(filename, data, getIOTypeFromMxClassID(mxType, mxIsComplexVolume), sizex, sizey, sizez, 0, 0, 0, &header, &header_read, allow_conversion);

    if (res != TOM_ERR_OK) {
        if (res ==TOM_ERR_WRITE_FILE) {
            snprintf(s, __MAX_S__LENGTH__, "%s: IO-error occured. The em-file may now be damaged :(", mexFunctionName());
            mexErrMsgTxt(s);
        } else if (res==TOM_ERR_OPEN_FILE) {
            snprintf(s, __MAX_S__LENGTH__, "%s: Error opening the file \"%s\" for writing.", mexFunctionName(), filename);
            mexErrMsgTxt(s);
        } else if (header_read && res==TOM_ERR_WRONG_IOTYPE_CONVERSION) {
            snprintf(s, __MAX_S__LENGTH__, "%s: Wrong typeconversion: can not convert volume of type %d to type %d as in the em-file.", mexFunctionName(), getIOTypeFromMxClassID(mxType, mxIsComplexVolume), tom_io_em_get_iotype_header(&header));
            mexErrMsgTxt(s);
        } else if (res == TOM_ERR_IOTYPE_NOT_SUPPORTED) {
            snprintf(s, __MAX_S__LENGTH__, "%s: Saving data of type %d to em-file is (currently) not supported.", mexFunctionName(), getIOTypeFromMxClassID(mxType, mxIsComplexVolume));
            mexErrMsgTxt(s);
        } else if (header_read && TOM_ERR_WRONG_DATA_SIZE && (sizex!=header.dims[0] || sizey!=header.dims[1])) {
            snprintf(s, __MAX_S__LENGTH__, "%s: Size mismatch: The volume has dimension %dx%dx%d, but the em-file has size %dx%dx%d.", mexFunctionName(), sizex, sizey, sizez, header.dims[0], header.dims[1], header.dims[2]);
            mexErrMsgTxt(s);
        } else {
            snprintf(s, __MAX_S__LENGTH__, "%s: Unexpected error. Is the \"%s\" a valid em-file? (%d)", mexFunctionName(), filename, res);
            mexErrMsgTxt(s);
        }
    }


    {
        /* Construct the output. */
        void *pdata;
        switch (nlhs) {
        case 5:
            pdata = mxGetData(plhs[4] = plhs_tmp[4]);
            for (i=0; i<256; i++) {
                ((int8_t *)pdata)[i] = header.userdata[i];
            }
        case 4:
            pdata = mxGetData(plhs[3] = plhs_tmp[3]);
            for (i=0; i<40; i++) {
                ((int32_t *)pdata)[i] = header.emdata[i];
            }
        case 3:
            pdata = mxGetData(plhs[2] = plhs_tmp[2]);
            for (i=0; i<80; i++) {
                ((int8_t *)pdata)[i] = header.comment[i];
            }
        case 2:
            pdata = mxGetData(plhs[1] = plhs_tmp[1]);
            ((int8_t *)pdata)[0] = header.machine;
            ((int8_t *)pdata)[1] = header.byte2;
            ((int8_t *)pdata)[2] = header.byte3;
            ((int8_t *)pdata)[3] = header.type;
        case 1:
            pdata = mxGetData(plhs[0] = plhs_tmp[0]);
            ((uint32_t *)pdata)[0] = header.dims[0];
            ((uint32_t *)pdata)[1] = header.dims[1];
            ((uint32_t *)pdata)[2] = header.dims[2];
            break;
        case 0:
        default:
            break;
        }
    }
}
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
	DOUBLE	*hpf,*lpf;
	DOUBLE	*sig,*wcp,*wcp1,*wcp2;
/*	unsigned int	m,n;  */
	int nr,nc,nn,mm,kk,J,lenfil,dee;
	mxArray *temp, *hpfmat, *WP_OUT1, *WP_OUT2;



	/* Check for proper number of arguments */

	if (nrhs != 3) {
		mexErrMsgTxt("rec_wp_decomp1 requires three input arguments.");
	} else if (nlhs != 1) {
		mexErrMsgTxt("rec_wp_decomp1 requires one output argument.");
	}


	/* Check the dimensions of signal.  signal can be n X 1 or 1 X n. */

	nr  = mxGetM(Sig_IN);
	nc = mxGetN(Sig_IN);
	
    J = 0;
	for( nn = 1; nn < nc;  nn *= 2 )  
		 J ++;
	if(  nn  !=  nc){
		mexErrMsgTxt("rec_wp_decomp1 requires dyadic length");
	}
    J = 0;
	for( nn = 1; nn < nr;  nn *= 2 )  
		 J ++;
	if(  nn  !=  nr){
		mexErrMsgTxt("rec_wp_decomp1 requires dyadic length");
	}
    WP_OUT = mxCreateDoubleMatrix(nr, nc, mxREAL);
    sig = mxGetPr(Sig_IN);
    wcp = mxGetPr(WP_OUT);
    lenfil =  (int) (mxGetM(LPF_IN) * mxGetN(LPF_IN));   /* should check this */
    
    lpf = mxGetPr(LPF_IN);
    hpfmat = mxCreateDoubleMatrix((unsigned int) lenfil,  1, mxREAL);
    hpf    = mxGetPr(hpfmat);
    mirrorfilt(lpf,hpf,lenfil);

    for( kk = 0; kk < mxGetN(LLL_IN); kk++) {
        dee =  floor ((mxGetPr(LLL_IN))[kk] + .5);   /* should check whether this is in range */
	    /* Create a matrix for the return argument */
	    if( dee > J ){
	    	mexErrMsgTxt("rec_wp_decomp1 requires D < log_2(n)");
         }
        if( dee < 0){
	        mexErrMsgTxt("rec_wp_decomp1 requires D >= 0");
	     }
    	nn = dee+1;
        for( mm = nc/2; mm < nc; mm++){  
            WP_OUT1 = mxCreateDoubleMatrix(nr, nn, mxREAL);
            WP_OUT2 = mxCreateDoubleMatrix(nr, 1, mxREAL);
            temp   = mxCreateDoubleMatrix(nr, 6, mxREAL);
        	/* Assign pointers to the various parameters */
        	wcp1 = mxGetPr(WP_OUT1);
            wcp2 = mxGetPr(WP_OUT2);
            copydouble(&sig[mm*nr],wcp2,nr);
            /* Do the actual computations in a subroutine */
        	wpd(wcp2,nr,dee,hpf,lpf,lenfil,wcp1,mxGetPr(temp));
            copydouble(&wcp1[0],&wcp[mm*nr],nr);
         	mxDestroyArray(temp);
        }
        nc = nc/2;
    }
    mxDestroyArray(hpfmat);
}
示例#4
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
	mxArray*    img;
	u_int8_t*   p_img;               /*The image from Matlab*/
	u_int8_t**  p_gray;              /*Image converted for texture calcs*/
	int         mrows;               /*Image height*/
	int         ncols;               /*Image width*/
	TEXTURE*    features ;           /*Returned struct of features*/
	int         i ;
	int         imgsize[2] ;              
	int         imgindex[2] ;
	long        offset ;                  
	int         outputsize[2] ;      /*Dimensions of TEXTURE struct*/
	int         outputindex[2] ;
	
	float*      output ;             /*Features to return*/
	int         distance, angle;     /*Parameters for texture calculations*/

	if (nrhs != 3)
		mexErrMsgTxt("\n mb_texture (im, distance, angle),\n\n"
		 "This function returns the 14 image texture statistics described by R. Haralick.\n"
		 "The statistics are calculated from the image's co-occurence matrix specified\n"
		 "for a particular distance and angle. Distance is measured in pixels and\n"
		 "the angle is measured in degrees.\n");
    
    else if (nlhs != 1)
		mexErrMsgTxt("mb_texture returns a single output.\n") ;
	
	if (!mxIsNumeric(prhs[0]))
		mexErrMsgTxt("mb_texture requires the first input to be numeric\n") ;
	
	if (!mxIsUint8(prhs[0]))
		mexCallMATLAB(1, &img, 1, prhs, "im2uint8_dynamic_range");
	else
		img = prhs[0];
	
	mrows = mxGetM(img) ;
	ncols = mxGetN(img) ;
	
	if (!(mrows > 1) || !(ncols > 1))
		mexErrMsgTxt("mb_texture requires an input image, not a scalar.\n") ;
	
	if ( !mxIsNumeric(prhs[1]) || (mxIsComplex(prhs[1])) )
		mexErrMsgTxt("The second argument (distance) should be numeric and not complex.");

	if ( !mxIsNumeric(prhs[2]) || (mxIsComplex(prhs[2])) )
		mexErrMsgTxt("The third argument (angle) should be numeric and not complex.");


	p_img = (u_int8_t*) mxGetData(img) ;
	distance = (double) mxGetScalar(prhs[1]) ;
	angle = (double) mxGetScalar(prhs[2]) ;
	
	imgsize[col] = ncols ;
	imgsize[row] = mrows ;
	
	p_gray = mxCalloc(mrows, sizeof(u_int8_t*)) ;
	if(p_gray) {
		for(i=0; i<mrows ; i++) {
			p_gray[i] = mxCalloc(ncols, sizeof(u_int8_t)) ;
			if(!p_gray[i])
				mexErrMsgTxt("mb_texture : error allocating p_gray[i]") ;
		}
	} else mexErrMsgTxt("mb_texture : error allocating p_gray") ;
	
	
	for(imgindex[row] = 0 ; imgindex[row] < imgsize[row] ; imgindex[row]++) 
		for(imgindex[col]=0; imgindex[col] < imgsize[col]; imgindex[col]++) {
			offset = mxCalcSingleSubscript(prhs[0], 2, imgindex) ;
			p_gray[imgindex[row]][imgindex[col]] = p_img[offset] ;
		}
	
	if (! (features=Extract_Texture_Features(distance, angle, p_gray,mrows, ncols, 255))) 
		mexErrMsgTxt("ERROR: Could not compute Haralick Features.");
		
	outputsize[row] = 14;
	outputsize[col] = 1;
	
	plhs[0] = mxCreateNumericArray(2, outputsize, mxSINGLE_CLASS, mxREAL) ;
	if (!plhs[0]) 
		mexErrMsgTxt("mb_texture: error allocating return variable.") ;
	
	output = (float*)mxGetData(plhs[0]) ;
	
	/* Copy the features into the return variable */
	outputindex[row]=0 ;
	outputindex[col]=0 ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->ASM;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->contrast;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->correlation;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->variance;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->IDM;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->sum_avg;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->sum_var;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->sum_entropy;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->entropy;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->diff_var;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->diff_entropy;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->meas_corr1;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->meas_corr2;
	
	outputindex[row]++ ;
	offset =  mxCalcSingleSubscript(plhs[0], 2, outputindex) ;
	output[offset] = features->max_corr_coef;

	/*
	    Memory clean-up.
	*/
	for (i=0; i<mrows ; i++)
		mxFree(p_gray[i]) ;
	mxFree(p_gray) ;  
	
	/* features is calloc'd inside of Extract_Texture_Features */
	free(features) ;
}
示例#5
0
  double *v;		// Vertices
  unsigned int *f;	// Faces
  
  /* ************** Others ******************* */
  unsigned int nV, nF, i, j;

  // Initialize vtk variables
  vtkPolyData *surf = vtkPolyData::New();
  vtkPoints *sverts = vtkPoints::New();
  vtkCellArray *sfaces = vtkCellArray::New();

  /* Inputs */
  v = mxGetPr(prhs[0]);
  f = (unsigned int*)mxGetPr(prhs[1]);
  
  nV = mxGetM(prhs[0]);
  nF = mxGetM(prhs[1]);
  
  // Load the point, cell, and data attributes.
  for (i=0; i<nV; i++) sverts->InsertPoint(i,v[i],v[nV+i],v[2*nV+i]);
  for (i=0; i<nF; i++) 
    {
      sfaces->InsertNextCell(3);
      for(j=0;j<3;j++)
	sfaces->InsertCellPoint((vtkIdType(f[j*nF+i]-1)));
    }
	
  // We now assign the pieces to the vtkPolyData.
  surf->SetPoints(sverts);
  surf->SetPolys(sfaces);
  sverts->Delete();
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    
    // Macros for output
    #define RNGI        plhs[0]
    #define WIDTH       plhs[1]
    #define H_OUT       plhs[2]
    #define S_OUT       plhs[3]
    #define TNM         plhs[4]
    
    // Macros for input
    #define NRNG        prhs[0]
    #define IRNG        prhs[1]
    #define RNGVEC      prhs[2]
    #define JMAX        prhs[3]
    #define NREP1       prhs[4]
    #define NREP2       prhs[5]
    #define FDOBJ1      prhs[6]
    #define FDOBJ2      prhs[7]
    #define LFDOBJ1     prhs[8]
    #define LFDOBJ2     prhs[9]
    #define WTFD        prhs[10]
    
    double *rngi, *width, *rngvec, *h, *s, *tnm, *fx1, *fx2;
    int *iter, jmaxp, irng, nrng, nrep1, nrep2, j, k, M, index;
    
    // retrieve irng and nrng
    irng    = (int)mxGetPr(IRNG)[0];
    nrng    = (int)mxGetPr(NRNG)[0];
    // retrieve rngvec
    rngvec  = mxGetPr(RNGVEC);
    
    // initialize and assign rngi
    RNGI    = mxCreateDoubleMatrix(1, 2, mxREAL);
    rngi    = mxGetPr(RNGI);
    rngi[0] = rngvec[irng-2];
    rngi[1] = rngvec[irng-1];
    
    // adjust rngi
    if (irng > 2) {
        rngi[0] += 1e-10;
    }
    if (irng < nrng){
        rngi[1] -= 1e-10;
    }
    
    // initialize ans calculate width
    WIDTH       = mxCreateDoubleMatrix(1, 1, mxREAL);
    width       = mxGetPr(WIDTH);
    width[0]    = rngi[1] - rngi[0];
    
    // initialize and calculate JMAXP
    jmaxp    = (int)mxGetPr(JMAX)[0] + 1;
    
    
    // retrieve JMAXP, nrep1, nrep2
    nrep1   = (int)mxGetPr(NREP1)[0];
    nrep2   = (int)mxGetPr(NREP2)[0];
    
    // create uninitialized h array
    H_OUT = mxCreateDoubleMatrix(jmaxp, 1, mxREAL);
    //mxSetM(H_OUT, jmaxp_i);
    //mxSetN(H_OUT, 1);
    //mxSetData(H_OUT, mxMalloc(sizeof(double)*jmaxp_i));
    h = mxGetPr(H_OUT);
    
    // assign values to h
    h[0] = 1;
    h[1] = 0.25;
    for (j = 2; j < jmaxp; j++) {
        h[j] = 1;
    }
    
    //initialize solution matrix s
    mwSize D[3]  = {jmaxp, nrep1, nrep2};
    S_OUT           = mxCreateNumericArray(3, D, mxDOUBLE_CLASS, mxREAL);
    s               = mxGetPr(S_OUT);
    
    mxArray *FX1, *FX2;
    
    // evaluate estimated solutions fx1 and fx2 of inner product
    eval_fds(&FX1, &FX2, FDOBJ1, FDOBJ2, LFDOBJ1, LFDOBJ2, WTFD, RNGI);
    
    // initialize tnm
    TNM     = mxCreateDoubleMatrix(1, 1, mxREAL);
    tnm     = mxGetPr(TNM);
    tnm[0]  = 0.5;
    
    // get contents of fx1 and fx2
    fx1     = mxGetPr(FX1);
    fx2     = mxGetPr(FX2);
    
    // assign first set of solutions
    M       = mxGetM(FX1);
    for (j = 0; j < nrep1; j++) {
        for (k = 0; k < nrep2; k++) {
            int m;
            double n = 0;
            // multiply fx1^T and fx2
            for (m = 0; m < M; m++){
                n += fx1[m + M*j] * fx2[m + M*k];
            }
            index = jmaxp*j + jmaxp*nrep1*k;
            s[index] = n*width[0]/2;
            mexPrintf("%f ", s[index]);
        }
        mexPrintf("\n");
    }
    mexPrintf("\n");
    
    return;
}
示例#7
0
void 
LTFAT_NAME(ltfatMexFnc)( int nlhs, mxArray *plhs[],
                      int nrhs, const mxArray *prhs[] )
{
  // Register exit function only once
    static int atExitFncRegistered = 0;
    if(!atExitFncRegistered)
    {
        LTFAT_NAME(ltfatMexAtExit)(LTFAT_NAME(dctMexAtExitFnc));
        atExitFncRegistered = 1;
    }

  LTFAT_REAL *c_r, *c_i;
  const LTFAT_REAL *f_r, *f_i;
  dct_kind kind;

  mwIndex L = mxGetM(prhs[0]);
  mwIndex W = mxGetN(prhs[0]);
  mwIndex type = (mwIndex) mxGetScalar(prhs[1]);

 // Copy inputs and get pointers
  if( mxIsComplex(prhs[0]))
  {
     f_i =  mxGetImagData(prhs[0]); 
     plhs[0] = ltfatCreateMatrix(L, W, LTFAT_MX_CLASSID, mxCOMPLEX);
     c_i = mxGetImagData(plhs[0]);
  }
  else
  {
     plhs[0] = ltfatCreateMatrix(L, W, LTFAT_MX_CLASSID, mxREAL);
  }

  f_r = mxGetData(prhs[0]);
  c_r = mxGetData(plhs[0]);

  switch(type)
  {
	 case 1:
        kind = DSTI;
     break;
	 case 2:
        kind = DSTII;
     break;
	 case 3:
        kind = DSTIII;
     break;
	 case 4:
        kind = DSTIV;
     break;
     default:
		 mexErrMsgTxt("Unknown type.");
  }



  LTFAT_FFTW(plan) p = LTFAT_NAME(dst_init)( L, W, c_r, kind);



  LTFAT_NAME(dctMexAtExitFnc)();
  LTFAT_NAME(p_old) = p;


  LTFAT_NAME(dst_execute)(p,f_r,L,W,c_r,kind);
  if( mxIsComplex(prhs[0]))
  {
      LTFAT_NAME(dst_execute)(p,f_i,L,W,c_i,kind);
  }


  return;
}
void mexFunction(int nlhs, mxArray *plhs[],
		 int nrhs, const mxArray *prhs[]) {
  // Test number of parameters.
  if (nrhs != 6 || nlhs != 4) {
    mexWarnMsgTxt("Usage: [X,rval,Obj,iter]=solveInnerProblem(W,Y,rval,MAXITER,EPS,FourTimesMaxSumSquaredWeights)");
    return;
  }
  
  // get important parameters
  int rows = (int)mxGetM(prhs[0]); // number of rows of W
  int cols = (int)mxGetN(prhs[0]); // number of columns of W (should be the same)
  int len  = (int)mxGetM(prhs[1]); // the desired output
  int lenrval = (int)mxGetM(prhs[2]); // rval

  if(!mxIsSparse(prhs[0])) { mexWarnMsgTxt("Matrix is not sparse");}
  
  if(rows!=cols){
    mexWarnMsgTxt("Sparse matrix is not square");
    return;
  }

  if(rows!=len){
    mexWarnMsgTxt("Length of the vector is not the same as the number of the rows of the sparse matrix");
    return;
  }
    
  // Create output array and compute values
  double* sr = mxGetPr(prhs[0]);     // get values
  mwIndex* irs = mxGetIr(prhs[0]);   // get row
  mwIndex* jcs = mxGetJc(prhs[0]);   // get columns
  
  double* Xobs = mxGetPr(prhs[1]);
  double* rval = mxGetPr(prhs[2]);     // get values

  int MAXITER = (int) mxGetScalar(prhs[3]); 
  double EPS = mxGetScalar(prhs[4]); 
  double MaxSumSquaredWeights = mxGetScalar(prhs[5]); 
  //mexPrintf("Elements: %f\n",MaxSumSquaredWeights);

  if(MaxSumSquaredWeights<=0){
	  mexWarnMsgTxt("Lipschitz constant has to be positive");
    return;
  }

  double *X;      /* output matrix */
  plhs[0] = mxCreateDoubleMatrix(len,1,mxREAL); /* create the output vector */
  plhs[1] = mxCreateDoubleMatrix(lenrval,1,mxREAL); /* create the output dual variable */
  plhs[2] = mxCreateDoubleMatrix(1,1,mxREAL); /* create the output objective value */
  plhs[3] = mxCreateDoubleMatrix(1,1,mxREAL); /* create the final iteration value */
  
  //plhs[1]= (mxArray *)prhs[2];
  //plhs[2]= (mxArray *)prhs[3];

  X = mxGetPr(plhs[0]);
  double* Z = mxGetPr(plhs[1]);
  double* OutputObj = mxGetPr(plhs[2]);
  double* FinalIter = mxGetPr(plhs[3]);

  int counter=0,i,j,start,mid,end,iter=0;
  double tnew=1; double told=1,alpha,beta,factor;
  double dummy,normD,normDiff,relativeChange,Fval;
  double* dummyPointer;

  double* D =new double[len];
  double* Dold =new double[len];
  for(i=0; i<len; i++) { D[i]=0; Dold[i]=0;}

  double* pval    = new double[lenrval];
  double* pvalold = new double[lenrval];
  for(i=0; i<lenrval; i++) { pval[i]=0; }
  for(i=0; i<lenrval; i++) { pvalold[i]=0; }

  
  //MaxSumSquaredWeights=max(sum(W.^2,2));
  /*double MaxSumSquaredWeights=0;  
  for(j=0; j<cols; j++) 
  {   
	dummy=0;
	for(i=0; i<jcs[j+1]-jcs[j]; i++) {  dummy+=sr[j]*sr[j]; }
	if(dummy>MaxSumSquaredWeights) { MaxSumSquaredWeights=dummy; }
  }
  MaxSumSquaredWeights=4*MaxSumSquaredWeights;*/
  Fval=EPS+1;
  while(iter<MAXITER && Fval > EPS)
  {
     //if (iter % 100 == 0){ mexPrintf("iter=%d tnew = %.5g\n",iter,tnew);}
    // exchange D and Dold
	dummyPointer=D; D=Dold; Dold=dummyPointer;

	//mexPrintf("Exchanged D \n");

	// exchange pval and pvalold
	dummyPointer=pval; pval=pvalold; pvalold=dummyPointer;

	//mexPrintf("Exchanged Pointer \n");

	// exchange tnew and told
	told=tnew;
    
	// initialize X with zeros 
    for(i=0; i<len; i++) { X[i]=0; }

	//mexPrintf("Initialized X, %i \n",X[0]);
  
    //sval = lambda*wval.*rval;
    //X = -sparse(jx,1,sval);
    dummy=0; counter=0;
    for(j=0; j<cols; j++) 
    {   
	   for(i=0; i<jcs[j+1]-jcs[j]; i++)
	   {  
         dummy = sr[counter]*rval[counter];
		 //mexPrintf("Computed dummy, %f\n",dummy);
         X[j] -= dummy;
	     X[irs[counter]] += dummy;
         counter++;
	   }
	} 
	//mexPrintf("Computed X, %f %f %f %f %f \n",X[0],X[1],X[2],X[3],X[4]);
    //D = Xobs-X; 
    normD = 0;  normDiff=0;
    for(i=0; i<len; i++) { D[i]=Xobs[i]-X[i]; normD+=D[i]*D[i]; normDiff+=(D[i]-Dold[i])*(D[i]-Dold[i]);}
  
    //pval = rval + uval.*(D(ix)-D(jx));
	 // pval=pval./max(abs(pval),1);
    counter=0;
	tnew = (1 + sqrt(1+4*told*told))/2;
    factor = (told-1)/tnew;
    for(j=0; j<cols; j++) 
    {   
       alpha=D[j];
	   for(i=0; i<jcs[j+1]-jcs[j]; i++)
	   {  
	      // update of pval
		  beta=rval[counter] + sr[counter]*( D[irs[counter]] - alpha)/MaxSumSquaredWeights;
		  // projection onto l_inf-cube 
		  if(beta>1) beta=1;
	      else if(beta<-1) beta=-1;
		  pval[counter]=beta;
		  // update of rval
          rval[counter] = beta + factor*(beta-pvalold[counter]);
		  counter++;
	   }	  
    }

    //tkp1=(1+sqrt(1+4*tk^2))/2;
    //rval = pval + (tk-1)/(tkp1)*(pval-pvalold);
	/*tnew = (1 + sqrt(1+4*told*told))/2;
    for(j=0; j<jcs[len]; j++) 
    {
	  alpha=pval[j];
	  if(alpha>1) { pval[j]=1; alpha=1;  }
	  else if(alpha<-1) { pval[j]=-1; alpha=-1;}
      rval[j] = alpha + (told-1)/tnew*(alpha-pvalold[j]);
    }*/
	//mexPrintf("Comp pval: %f %f %f\n",pval[0],pval[1],pval[len-1]);
	//mexPrintf("Comp rval: %f %f %f\n",rval[0],rval[1],rval[len-1]);
  
    relativeChange = sqrt(normDiff/normD);

    Fval = sqrt(normD);

    //mexPrintf("Iteration: %i, Fval: %1.15f, RelativeChange %1.15f\n",iter,Fval,relativeChange);
	//if(iter<10 || iter % 10==0)
	// mexPrintf("Iteration: %i, Fval: %1.15f, RelativeChange %1.15f\n",iter,Fval,relativeChange);
	iter++;
 }
 //mexPrintf("FINAL: Iterations %i, Fval: %1.15f, RelativeChange %1.15f\n",iter,Fval,relativeChange);
 for(i=0; i<len; i++) { X[i]=D[i];}
 for(i=0; i<lenrval; i++) { Z[i]=rval[i];}
 OutputObj[0]=Fval;
 FinalIter[0]=iter;
   //mexPrintf("iter=%d tnew = %.5g\n",iter,tnew);
 delete D; delete Dold; delete pvalold; delete pval;
	  
	

    // loop over columns
    /*for(i=0; i<jcs[j+1]-jcs[j]; i++) {     // loop over rows
      if(irs[counter]==j)
	  {
        sr[counter]+=vecvals[j];
	  }
	  counter++;
    }*/
    /*start=counter;  
	end=counter+jcs[j+1]-jcs[j]; 
	mid = floor(0.5*(start+end));
    while(irs[mid]!=j)
	{
		if(irs[mid]>j) { end=mid; mid = floor(0.5*(start+end)); }
		else           {start=mid; mid = floor(0.5*(start+end)); }
		//mexPrintf("Start: %i, Mid: %i, End %i \n",start,mid,end);
	}
	sr[mid]+=vecvals[j];
	counter=counter+jcs[j+1]-jcs[j];
  }*/
}
示例#9
0
void mexFunction(
  int nOutputs, mxArray *pointerOutputs[],
  int nInputs, const mxArray *pointerInputs[])
{
  
  double *tX;
  double *tY;
  double binSize;
  double *C;
  double lBound,uBound, minLag;
  int nX,nY;
  int nBins;
  int iBin,iX,jY,yStartIndx;
  double d,t1;
  int binNum;
  int c;
          
  nX = mxGetM(pointerInputs[0]) * mxGetN(pointerInputs[0]);
  nY = mxGetM(pointerInputs[1]) * mxGetN(pointerInputs[1]);

  tX = mxGetPr(pointerInputs[0]);
  tY = mxGetPr(pointerInputs[1]);
  
  binSize = mxGetScalar(pointerInputs[2]);
  nBins   = (int)mxGetScalar(pointerInputs[3]);
  double bins[nBins];
  
  /* create the pointer to the first output matrix */
  pointerOutputs[0] = mxCreateDoubleMatrix(nBins, 1, mxREAL);
  C                 = mxGetPr(pointerOutputs[0]);  
  minLag = -binSize*(nBins-1.0)/2.0;
              
  for(iBin = 0; iBin < nBins; iBin++)
  {  
    bins[iBin] = minLag + ((double)(iBin))*binSize;
  }
   
  /* compute the actual cross-correlations */
  minLag = -(nBins-1)*binSize/2.0;
  yStartIndx = 0;
  for(iX=0; iX<nX; iX++)
  {
      if (tX[iX]<(tY[yStartIndx]+minLag))
        continue;
      
      /* first determine where to start */
      t1 = tX[iX];
      lBound = t1 + minLag; 
      uBound = t1 - minLag;
      while(tY[yStartIndx] < lBound && yStartIndx < (nY-1))
        yStartIndx++;
      
      if (tY[yStartIndx]>uBound || tY[yStartIndx]<lBound )
      {
        continue;
      }
      for(jY = yStartIndx; jY < nY; jY++)
      {
        /* find the binnumber associated with the distance */
        d      = tY[jY] - t1;
        binNum =  (int)(floor((d - minLag)/binSize));              
        if (binNum<0)
        {
          binNum = 0;
        }                
        if (binNum>(nBins-2))
        {
          break;
        }
        C[binNum]++;
      }
  }     
}
示例#10
0
void mexFunction(
   int nlhs, mxArray *plhs[],
   int nrhs, const mxArray *prhs[])
{
  double *a, *b, *x, *c, *y; /*mxGetPr, mxGetPr, mxGetPr, mCalloc(double), mxGetPr*/
  double *cptr, *ccol, *xptr, *yptr, *cin, *cend, *cp, *cstart; /*ccol, cend, x, cptr, mxGetPr, c, ccol, cend*/
  double z, z2, dd, di, temp; /*2.0, 2.0, 0.0, 0.0, di*/
  mwSize *cind, *n; /*p, (mwSize)*/
  mwSize d, m, p, N, i, j, nj, xrows, csize; /**/

  /* Error checking on inputs */  
  if (nrhs<5) mexErrMsgTxt("Not enough input arguments.");
  if (nrhs>5) mexErrMsgTxt("Too many input arguments.");
  if (nlhs>1) mexErrMsgTxt("Too many output arguments.");
  for (i=0; i<nrhs; i++) {
    if (!mxIsDouble(prhs[i]) || mxIsSparse(prhs[i]))
      mexErrMsgTxt("Function not defined for variables of input class");
    if (mxIsComplex(prhs[i]))
      mexErrMsgTxt("Arguments must be real.");
  }

  p=mxGetN(prhs[0]);

  m=mxGetM(prhs[1]);
  d=mxGetN(prhs[1]);
  x=mxGetPr(prhs[1]);

  if (mxGetNumberOfElements(prhs[2])!=d)
    mexErrMsgTxt("n has improper dimension");
  a=mxGetPr(prhs[2]);
  n=mxCalloc(d,sizeof(mwSize));
  for (i=0;i<d;i++) n[i]=(mwSize)a[i];

  if (mxGetNumberOfElements(prhs[3])!=d)
    mexErrMsgTxt("a has improper dimension");
  a=mxGetPr(prhs[3]);

  if (mxGetNumberOfElements(prhs[4])!=d)
    mexErrMsgTxt("b has improper dimension");
  b=mxGetPr(prhs[4]);

  N=1; for(i=0;i<d; i++) N *= n[i];
  if (mxGetM(prhs[0])!=N)
    mexErrMsgTxt("c has improper number of rows");

  plhs[0]=mxCreateDoubleMatrix(m,p,mxREAL);

  cind=mxCalloc(d,sizeof(mwSize));  
  cind[d-1]=p; for (i=d-1;i>0;i--) cind[i-1]=cind[i]*n[i];
  c=mxCalloc(N*p,sizeof(double));
  y=mxGetPr(plhs[0]);

  cin=mxGetPr(prhs[0]);
  csize=N*p*sizeof(double);
  cend=c+N*p;
  for (xrows=0;xrows<m; xrows++)
  {  
    memcpy(c,cin,csize);
    xptr=x+xrows;
    for (j=0; j<d; j++, xptr+=m)
    {
      z=(2.0**xptr-a[j]-b[j])/(b[j]-a[j]);
      z2=z*2.0;
      nj=n[j];
      ccol=cend-1;
      cptr=ccol;
      cstart=cend;
      for (cp=ccol-cind[j]; ccol>cp;)
      {
        di=0.0; 
        dd=0.0;
        for (cstart-=nj;cptr>cstart;)
        {
          temp=di;
          di=z2*di-dd+*cptr--;
          dd=temp;
        }
        *ccol--=z*di-dd+*cptr--;
      }
    }
    for (cptr=cend-p, yptr=y+xrows; cptr<cend; yptr+=m) 
       *yptr=*cptr++;
  }
  mxFree(c);
  mxFree(cind);
  mxFree(n);
}
示例#11
0
void
mexFunction (int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
  char str[256];
  mxArray *sa;
  double *v1, *v2, *v3, p1[3], p2[3], p3[3], *pnt, *tri, *sa_p;
  int i1, i2, i3, npnt, ntri, i, on_triangle;

  if (nrhs==2)
  {
    /* the input consists of a vertex array and a triangle array */
    if (mxGetN(prhs[0])!=3)
      mexErrMsgTxt ("Invalid dimension for input argument 1");
    if (mxGetN(prhs[1])!=3)
      mexErrMsgTxt ("Invalid dimension for input argument 2");
    npnt = mxGetM(prhs[0]);
    ntri = mxGetM(prhs[1]);
    pnt = mxGetData (prhs[0]);
    tri = mxGetData (prhs[1]);
    sa = mxCreateDoubleMatrix (ntri, 1, mxREAL);
    sa_p = mxGetData (sa);
    /* compute the solid angle for all triangles */
    for (i=0; i<ntri; i++)
    {
      i1 = (int)(tri[i]) - 1;
      i2 = (int)(tri[i+ntri]) - 1;
      i3 = (int)(tri[i+ntri+ntri]) - 1;
      p1[0] = pnt[i1]; p1[1] = pnt[i1+npnt]; p1[2] = pnt[i1+npnt+npnt];
      p2[0] = pnt[i2]; p2[1] = pnt[i2+npnt]; p2[2] = pnt[i2+npnt+npnt];
      p3[0] = pnt[i3]; p3[1] = pnt[i3+npnt]; p3[2] = pnt[i3+npnt+npnt];
      *(sa_p+i) = solang(p1, p2, p3, &on_triangle);
      if (on_triangle)
        *(sa_p+i) = mxGetNaN();
    }
    /* assign the output parameter */
    plhs[0] = sa;
  }
  else if (nrhs==3)
  {
    /* the input consists of three vertices */
    if (mxGetM(prhs[0])!=1 || mxGetN(prhs[0])!=3)
      mexErrMsgTxt ("Invalid dimension for input argument 1");
    if (mxGetM(prhs[1])!=1 || mxGetN(prhs[1])!=3)
      mexErrMsgTxt ("Invalid dimension for input argument 2");
    if (mxGetM(prhs[2])!=1 || mxGetN(prhs[2])!=3)
      mexErrMsgTxt ("Invalid dimension for input argument 3");
    v1 = mxGetData (prhs[0]);
    v2 = mxGetData (prhs[1]);
    v3 = mxGetData (prhs[2]);
    sa = mxCreateDoubleMatrix (1, 1, mxREAL);
    sa_p = mxGetData (sa);
    /* compute the solid angle for a single triangle */
    *(sa_p) = solang(v1, v2, v3, &on_triangle);
    if (on_triangle)
      *(sa_p) = mxGetNaN();
    /* assign the output parameter */
    plhs[0] = sa;
  }
  else
    mexErrMsgTxt ("Invalid number of input arguments");

  return;
}
示例#12
0
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{

  enum {IN_I=0,IN_END} ;
  enum {OUT_FRAMES=0, OUT_DESCRIPTORS} ;

  int                verbose = 0 ;
  int                opt ;
  int                next = IN_END ;
  mxArray const     *optarg ;

  vl_sift_pix const *data ;
  int                M, N ;

  int                O     = - 1 ;
  int                S     =   3 ;
  int                o_min =   0 ;

  double             edge_thresh = -1 ;
  double             peak_thresh = -1 ;
  double             norm_thresh = -1 ;
  double             magnif      = -1 ;
  double             window_size = -1 ;

  mxArray           *ikeys_array = 0 ;
  double            *ikeys = 0 ;
  int                nikeys = -1 ;
  vl_bool            force_orientations = 0 ;
  vl_bool            floatDescriptors = 0 ;

  VL_USE_MATLAB_ENV ;

  /* -----------------------------------------------------------------
   *                                               Check the arguments
   * -------------------------------------------------------------- */

  if (nin < 1) {
    mexErrMsgTxt("One argument required.") ;
  } else if (nout > 2) {
    mexErrMsgTxt("Too many output arguments.");
  }

  if (mxGetNumberOfDimensions (in[IN_I]) != 2              ||
      mxGetClassID            (in[IN_I]) != mxSINGLE_CLASS  ) {
    mexErrMsgTxt("I must be a matrix of class SINGLE") ;
  }

  data = (vl_sift_pix*) mxGetData (in[IN_I]) ;
  M    = mxGetM (in[IN_I]) ;
  N    = mxGetN (in[IN_I]) ;

  while ((opt = vlmxNextOption (in, nin, options, &next, &optarg)) >= 0) {
    switch (opt) {

    case opt_verbose :
      ++ verbose ;
      break ;

    case opt_frames :
      if (!vlmxIsMatrix(optarg, 4, -1)) {
        mexErrMsgTxt("'Frames' must be a 4 x N matrix.") ;
      }
      ikeys_array = mxDuplicateArray (optarg) ;
      nikeys      = mxGetN (optarg) ;
      ikeys       = mxGetPr (ikeys_array) ;
      if (! check_sorted (ikeys, nikeys)) {
        qsort (ikeys, nikeys, 4 * sizeof(double), korder) ;
      }
      break ;

    default :
		mexPrintf("Something is wrong!");
      abort() ;
    }
  }
  
  /* -----------------------------------------------------------------
   *                                                            Do job
   * -------------------------------------------------------------- */
  {
    VlSiftFilt        *filt ;
    vl_bool            first ;
    double            *frames = 0 ;
    void              *descr  = 0 ;
    int                nframes = 0, reserved = 0, i,j,q ;

    /* create a filter to process the image */
    filt = vl_sift_new (M, N, O, S, o_min) ;

	//mexPrintf("%f %f %f \n%f %f %f %f %f\n",(float)O,(float)S,(float)o_min,(float)peak_thresh
	//	,(float)edge_thresh,(float)norm_thresh,(float)magnif,(float)window_size);


    /* ...............................................................
     *                                             Process each octave
     * ............................................................ */
    i     = 0 ;
    first = 1 ;
    while (first == 1) {
      int                   err ;
      VlSiftKeypoint const *keys  = 0 ;
      int                   nkeys = 0 ;


        err   = vl_sift_process_first_octave (filt, data) ;
        first = 0 ;

      if (err) break ;

      /* Run detector ............................................. */
        nkeys = nikeys ;

	  //mexPrintf("Zhu: entering sweeping nkeys, nkeys = %d, i = %d \n", nkeys, i);

      /* For each keypoint ........................................ */
		for (; i < nkeys ; ++i) {
			int h;
			vl_sift_pix  buf[128];
			vl_sift_pix rbuf[128];
        double                angle;
        VlSiftKeypoint        ik ;
        VlSiftKeypoint const *k ;

        /* Obtain keypoint orientations ........................... */
          vl_sift_keypoint_init (filt, &ik,
                                 ikeys [4 * i + 1] - 1,
                                 ikeys [4 * i + 0] - 1,
                                 ikeys [4 * i + 2]) ;
		  //mexPrintf("ikeys: [%f, %f, %f]\n", (float)(ikeys [4 * i + 1] - 1), (float)(ikeys [4 * i + 0] - 1), (float)(ikeys [4 * i + 2]) );

          k = &ik ;

          /* optionally compute orientations too */
            angle = VL_PI / 2 - ikeys [4 * i + 3] ;
			q = 0;

		  
		  /* compute descriptor (if necessary) */
		  //int h;
		  //mexPrintf("M = %d, N = %d.\n",M,N);
		  //for (h = 0; h < 300; h++) 
		  //{
			//  mexPrintf("%f ",data[h]);
			//  if (h % 8 == 7) mexPrintf("\n");
		  //}
          if (nout > 1) {
			  //mexPrintf("angles = %f, x = %f(%d), y = %f(%d), s = %f(%d), o = %d, sigma = %f.\n buf = [", 
				  //angle,k->x,k->ix,k->y,k->iy,k->s,k->is,k->o,k->sigma);
			  vl_sift_calc_keypoint_descriptor (filt, buf, k, angle) ;
			  //for (h = 0; h < 128; h++) 
			  //{
				//  mexPrintf("%f ",(float)buf[h]);
				//  if (h % 8 == 7) mexPrintf("\n");
			  //}
			  //mexPrintf("...].\nrbuf = [");
			  transpose_descriptor (rbuf, buf) ;
			  //for (h = 0; h < 128; h++) 
			  //{
				//  mexPrintf("%f ",(float)rbuf[h]);
				//  if (h % 8 == 7) mexPrintf("\n");
			  //}
			  //mexPrintf("...].\n");
          }

          /* make enough room for all these keypoints and more */
          if (reserved < nframes + 1) {
            reserved += 2 * nkeys ;
            frames = mxRealloc (frames, 4 * sizeof(double) * reserved) ;
            if (nout > 1) {
              if (! floatDescriptors) {
                descr  = mxRealloc (descr,  128 * sizeof(vl_uint8) * reserved) ;
              } else {
                descr  = mxRealloc (descr,  128 * sizeof(float) * reserved) ;
              }
            }
          }

          /* Save back with MATLAB conventions. Notice tha the input
           * image was the transpose of the actual image. */
          frames [4 * nframes + 0] = k -> y + 1 ;
          frames [4 * nframes + 1] = k -> x + 1 ;
          frames [4 * nframes + 2] = k -> sigma ;
          frames [4 * nframes + 3] = VL_PI / 2 - angle;

		  //mexPrintf("Zhu: %d\n", nframes);
          if (nout > 1) {
            if (! floatDescriptors) {
              for (j = 0 ; j < 128 ; ++j) {
                float x = 512.0F * rbuf [j] ;
                x = (x < 255.0F) ? x : 255.0F ;
                ((vl_uint8*)descr) [128 * nframes + j] = (vl_uint8) x ;
              }
            } else {
              for (j = 0 ; j < 128 ; ++j) {
                float x = 512.0F * rbuf [j] ;
                ((float*)descr) [128 * nframes + j] = x ;
              }
            }
          }

          ++ nframes ;
         /* next orientation */
      } /* next keypoint */
	  //break;
	  //mexPrintf("Zhu: skip subsequent octave\n");
    } /* next octave */

	//mexPrintf("nframes_tot = %d\n",nframes);

    /* ...............................................................
     *                                                       Save back
     * ............................................................ */

    {
      mwSize dims [2] ;

      /* create an empty array */
      dims [0] = 0 ;
      dims [1] = 0 ;
      out[OUT_FRAMES] = mxCreateNumericArray
        (2, dims, mxDOUBLE_CLASS, mxREAL) ;

      /* set array content to be the frames buffer */
      dims [0] = 4 ;
      dims [1] = nframes ;
      mxSetPr         (out[OUT_FRAMES], frames) ;
      mxSetDimensions (out[OUT_FRAMES], dims, 2) ;

      if (nout > 1) {

        /* create an empty array */
        dims [0] = 0 ;
        dims [1] = 0 ;
        out[OUT_DESCRIPTORS]= mxCreateNumericArray
          (2, dims,
           floatDescriptors ? mxSINGLE_CLASS : mxUINT8_CLASS,
           mxREAL) ;

        /* set array content to be the descriptors buffer */
        dims [0] = 128 ;
        dims [1] = nframes ;
        mxSetData       (out[OUT_DESCRIPTORS], descr) ;
        mxSetDimensions (out[OUT_DESCRIPTORS], dims, 2) ;
      }
    }

    /* cleanup */
    vl_sift_delete (filt) ;

    if (ikeys_array)
      mxDestroyArray(ikeys_array) ;

  } /* end: do job */
}
示例#13
0
/*
 * static bool fbct_proj_all( ... )
 * forward projection call function
 */
static bool cbct_proj_all
        (
        mxArray *plhs[],
        Cmx mx_nxyz,
        Cmx mx_dxyz,
        Cmx mx_cxyz,
        Cmx mx_nuv,
        Cmx mx_duv,
        Cmx mx_cuv,
        Cmx mx_sad,
        Cmx mx_add,
        Cmx mx_sdd,
        Cmx mx_noviews,
        Cmx mx_betas,
        Cmx mx_couchz,
        Cmx mx_detector_type,
        Cmx mx_image,
        Cmx mx_map,
        GEOM_TYPE geom_type){
    
    bool sof = false;
    
    int nx = mxGetPr_cint32(mx_nxyz)[0];
    int ny = mxGetPr_cint32(mx_nxyz)[1];
    int nz = mxGetPr_cint32(mx_nxyz)[2];
    float dx = mxGetPr_cfloat(mx_dxyz)[0];
    float dy = mxGetPr_cfloat(mx_dxyz)[1];
    float dz = mxGetPr_cfloat(mx_dxyz)[2];
    float offset_x = mxGetPr_cfloat(mx_cxyz)[0];
    float offset_y = mxGetPr_cfloat(mx_cxyz)[1];
    float offset_z = mxGetPr_cfloat(mx_cxyz)[2];
    
    int nu = mxGetPr_cint32(mx_nuv)[0];
    int nv = mxGetPr_cint32(mx_nuv)[1];
    float du = mxGetPr_cfloat(mx_duv)[0];
    float dv = mxGetPr_cfloat(mx_duv)[1];
    float offset_u = mxGetPr_cfloat(mx_cuv)[0];
    float offset_v = mxGetPr_cfloat(mx_cuv)[1];
    
    float sad = mxGetPr_cfloat(mx_sad)[0];
    float add = mxGetPr_cfloat(mx_add)[0];
    float sdd = mxGetPr_cfloat(mx_sdd)[0];
    int noviews = mxGetPr_cint32(mx_noviews)[0];
    int detector_type = mxGetPr_cint32(mx_detector_type)[0];
    
    double *betas;
    float *couchz;
    float *image;
    float *proj;
    bool *map;
    const unsigned long* dim_image = mxGetDimensions( mx_image );
    const unsigned long* dim_map = mxGetDimensions( mx_map );
    mwSize dim_proj[3];
    
    /* get parameters for projection angle */
    if (noviews != mxGetM(mx_betas) * mxGetN(mx_betas) || !mxIsRealDouble(mx_betas)){
        mexErrMsgTxt("Error: mx_betas must have noviews X 1 double array.\n");
        return false;
    }
    
    betas = (double *) mxGetData(mx_betas);
    
    /* get parameters for couch position */
    if (noviews != mxGetM(mx_couchz) * mxGetN(mx_couchz) || !mxIsSingle(mx_couchz)){
        mexErrMsgTxt("Error: mx_couchz must have noviews X 1 double array.\n");
        return false;
    }
    
    couchz = (float *) mxGetData(mx_couchz);
    
    
    /* get image data */
    if ( nz != dim_image[2] || nx != dim_image[0] || ny != dim_image[1] ||  !mxIsSingle(mx_image) ){
        mexErrMsgTxt("Error: mx_image must have [nx ny nz] float array.\n");
        return false;
    }
    
    image = mxGetPr_cfloat(mx_image);
    
    
    /* get image map */
    if ( nx != dim_map[0] || ny != dim_map[1] ||  !mxIsLogical(mx_map) ){
        mexErrMsgTxt("Error: mx_map must have [nx ny] bool array.\n");
        return false;
    }
    
    map = mxGetPr_cbool(mx_map);
    
    
    /* create memory space for proj */
    dim_proj[0] = nv;
    dim_proj[1] = nu;
    dim_proj[2] = noviews;
    
    plhs[0] = mxCreateNumericArray( 3 , dim_proj, mxSINGLE_CLASS, mxREAL);
    proj = ((float *) mxGetData(plhs[0]));
    
    
    if (geom_type == PROJ_DD ) {
        sof = cbct_proj_dd(  nx, ny, nz, dx, dy, dz, offset_x, offset_y, offset_z, nu, nv, du, dv, offset_u, offset_v, sad, add, sdd, noviews, betas, couchz, detector_type, image, proj, map  );
    } else if (geom_type == PROJ_TF ) {
        sof = cbct_proj_tf(  nx, ny, nz, dx, dy, dz, offset_x, offset_y, offset_z, nu, nv, du, dv, offset_u, offset_v, sad, add, sdd, noviews, betas, couchz, detector_type, image, proj, map  );
    }
    
    return sof;
}
示例#14
0
void mexFunction(int			nlhs, 		/* number of expected outputs */
				 mxArray		*plhs[],	/* mxArray output pointer array */
				 int			nrhs, 		/* number of inputs */
				 const mxArray	*prhs[]		/* mxArray input pointer array */)
{
	// input checks
	if (nrhs != 2 || !mxIsSparse(prhs[0]) || !mxIsSparse(prhs[1]))
	{
		mexErrMsgTxt ("USAGE: [flow,labels] = maxflowmex(A,T)");
	}
	const mxArray *A = prhs[0];
	const mxArray *T = prhs[1];
	if (mxIsComplex(A) || mxIsComplex(T))
	{
		mexErrMsgTxt ("Complex entries are not supported!");
	}
	// fetch its dimensions
	// actually, we must have m=n
	mwSize m = mxGetM(A);
	mwSize n = mxGetN(A);
	mwSize nzmax = mxGetNzmax(A);
	if (m != n)
	{
		mexErrMsgTxt ("Matrix A should be square!");
	}
	if (n != mxGetM(T) || mxGetN(T) != 2)
	{
		mexErrMsgTxt ("T should be of size Nx2");
	}

	// sparse matrices have a different storage convention from that of full matrices in MATLAB. 
	// The parameters pr and pi are still arrays of double-precision numbers, but these arrays 
	// contain only nonzero data elements. There are three additional parameters: nzmax, ir, and jc.
	// nzmax - is an integer that contains the length of ir, pr, and, if it exists, pi. It is the maximum 
	// possible number of nonzero elements in the sparse matrix.
	// ir - points to an integer array of length nzmax containing the row indices of the corresponding 
	// elements in pr and pi.
	// jc - points to an integer array of length n+1, where n is the number of columns in the sparse matrix. 
	// The jc array contains column index information. If the jth column of the sparse matrix has any nonzero
	// elements, jc[j] is the index in ir and pr (and pi if it exists) of the first nonzero element in the jth
	// column, and jc[j+1] - 1 is the index of the last nonzero element in that column. For the jth column of 
	// the sparse matrix, jc[j] is the total number of nonzero elements in all preceding columns. The last 
	// element of the jc array, jc[n], is equal to nnz, the number of nonzero elements in the entire sparse matrix. 
	// If nnz is less than nzmax, more nonzero entries can be inserted into the array without allocating additional 
	// storage.

	double *pr = mxGetPr(A);
	mwIndex *ir = mxGetIr(A);
	mwIndex *jc = mxGetJc(A);

	// create graph
	typedef Graph<float,float,float> GraphType;
	// estimations for number of nodes and edges - we know these exactly!
	GraphType *g = new GraphType(/*estimated # of nodes*/ n, /*estimated # of edges*/ jc[n]); 
	
	// add the nodes
	// NOTE: their indices are 0-based
    g->add_node(n);

	// traverse the adjacency matrix and add n-links
	unsigned int i, j, k;
	float v;
	for (j = 0; j < n; j++)
	{
		// this is a simple check whether there are non zero
		// entries in the j'th column
		if (jc[j] == jc[j+1])
		{
			continue; // nothing in this column
		}
		for (k = jc[j]; k <= jc[j+1]-1; k++)
		{
			i = ir[k];
			v = (float)pr[k];
			//mexPrintf("non zero entry: (%d,%d) = %.2f\n", i+1, j+1, v);
			g->add_edge(i, j, v, 0.0f);
		}
	}

	// traverse the terminal matrix and add t-links
	pr = mxGetPr(T);
	ir = mxGetIr(T);
	jc = mxGetJc(T);
	for (j = 0; j <= 1; j++)
	{
		if (jc[j] == jc[j+1])
		{
			continue;
		}
		for (k = jc[j]; k <= jc[j+1]-1; k++)
		{
			i = ir[k];
			v = (float)pr[k];

			if (j == 0) // source weight
			{
				g->add_tweights(i, v, 0.0f);
			}
			else if (j == 1) // sink weight
			{
				g->add_tweights(i, 0.0f, v);
			}
		}
	}

	plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
	double* flow = mxGetPr(plhs[0]);
	*flow = g->maxflow();

	// figure out segmentation
	plhs[1] = mxCreateNumericMatrix(n, 1, mxINT32_CLASS, mxREAL);
	int* labels = (int*)mxGetData(plhs[1]);
	for (i = 0; i < n; i++)
	{
		labels[i] = g->what_segment(i);
	}

	// cleanup
	delete g;
}
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
	// declare variables
    double *Xs,*Xi,*Y,*N;
    double *m_infty, *l_infty, *parents_labels;
	double *F;
	double *feature_costs;
    
	// check inputs from matlab
	// TODO verify that there are 7 inputs and that each is of the correct size,
	// e.g. size(Xs) == size(Xi) == size(y) == size(n) == [N,1]
	// and size(m_infty)==size(l_infty)==[1,w]
	
	// get data from matlab
    Xs = mxGetPr(prhs[0]);//Sorted Features
    Xi = mxGetPr(prhs[1]);//Indices for Sorted Features
    Y = mxGetPr(prhs[2]);//Labels or Residuals
    N = mxGetPr(prhs[3]);//Nodes
	F = mxGetPr(prhs[4]);//Feature indices
	
	// get additional args from matlab
    m_infty = mxGetPr(mxGetCell(prhs[5],0));
    l_infty = mxGetPr(mxGetCell(prhs[5],1));
	parents_labels = mxGetPr(mxGetCell(prhs[5],2));
	feature_costs = mxGetPr(mxGetCell(prhs[5],3));
			// added when returning loss for each node
	
	// get dimensions
	int numinstances = mxGetM(prhs[0]);
	int numnodes = mxGetN(mxGetCell(prhs[5],0));
	int numfeatures = mxGetM(prhs[4]);
	
	// instantiate parent and child layers of nodes
	StaticNode** parents = new StaticNode*[numnodes];
	StaticNode** children = new StaticNode*[2*numnodes];
	for (int i=0; i<numnodes; i++) {
		parents[i] = new StaticNode((int)m_infty[i], l_infty[i]);
		children[2*i] = new StaticNode(0, 0.0);
		children[2*i]->label = parents_labels[i];
		children[2*i+1] = new StaticNode(0, 0.0);
		children[2*i+1]->label = parents_labels[i];
	}
	
	// instantiate outputs
	plhs[0]=mxCreateDoubleMatrix(numfeatures,numnodes,mxREAL); // splits
    plhs[1]=mxCreateDoubleMatrix(numfeatures,numnodes,mxREAL); // losses
    plhs[2]=mxCreateDoubleMatrix(numfeatures,2*numnodes,mxREAL); // labels
	
    double* splits = mxGetPr(plhs[0]);
    double* losses = mxGetPr(plhs[1]);
    double* labels = mxGetPr(plhs[2]);
	
    // iterate over features
	for (int f=0; f<numfeatures; f++) {
		// consider feature f
		double feature = F[f];
	    for (int j=f*numinstances; j<(f+1)*numinstances; j++) {
	        // get current value
	        double v = Xs[j]; // feature value from training set
	        int i = (int) Xi[j] - 1; // feature index that corresponds to the unsorted feature
	        double l = Y[i]; // target output label for the instance
			int n = (int) N[i] - 1; // node index on the parent layer for the instance
	        StaticNode *node = parents[n]; // node on the parent layer for the instance
		
	        // if not first instance at node and greater than split point, consider new split at v
	        if (node->m_s > 0 && v > node->pxs) {
				// compute split impurity
	            double loss_i =
					- pow(node->l_s,2.0) / (double) node->m_s 
					- pow(node->l_infty - node->l_s,2.0) / (double) (node->m_infty - node->m_s)
					+ feature_costs[(int)feature-1];
				// compare with best and record if better
	            if (node->loss > 0 || loss_i < node->loss) {
	                node->loss = loss_i;
	                node->split = (node->pxs + v) / 2.0;
	                StaticNode* child1 = children[2*n];
	                child1->label = node->l_s / (double) node->m_s;
	                StaticNode* child2 = children[2*n+1];
	                child2->label = (node->l_infty - node->l_s) / (double) (node->m_infty - node->m_s);
	            }
	        }
		
	        // update variables
	        node->m_s += 1; // m_s is the number of data points encountered so far at that node
	        node->l_s += l; // l_s is the total residual encountered so far at that node.
	        node->pxs = v; // the previous feature value at that node
	    }
		
		// record output values for feature f
	    for (int i=0; i<numnodes; i++) {
			splits[i*numfeatures + f] = parents[i]->split;
			losses[i*numfeatures + f] = parents[i]->loss; // add feature cost
			labels[2*i*numfeatures + f] = children[2*i]->label;
			labels[(2*i+1)*numfeatures + f] = children[2*i+1]->label;
		}
		
		// clear nodes
		for (int i=0; i<numnodes; i++) {
			parents[i]->clear();
			children[2*i]->clear();
			children[2*i+1]->clear();
		}
	}
	
	// delete nodes
	for (int i=0; i<numnodes; i++) {
		delete parents[i];
		parents[i] = NULL;
		delete children[2*i];
		children[2*i] = NULL;
		delete children[2*i+1];
		children[2*i+1] = NULL;
	}
	delete[] parents;
	delete[] children;
}
示例#16
0
Hkms<T>* importMatlab(const mxArray* in, T dummy)
{

  //get the options
  HkmOptions opt;
  importHkmOptions(opt, mxGetField(in, 0, "opt"));
  
  //allocate
  Hkms<T>* hkms = new Hkms<T>(opt);
  
  
  //get the nodes
  mxArray* nodes = mxGetField(in, 0, "nodes");

  //size of array
//   uint nnodes = mxGetNumberOfElements(nodes);
  uint nnodes = mxGetN(nodes);
  uint ntrees = mxGetM(nodes);
    
  //resize hkms
  hkms->resize(ntrees);
  
  //loop on trees
  for (uint t=0; t<ntrees; ++t)
  {
    //get hkm
    Hkm<T>& hkm = hkms->hkms[t];
    //resize
    hkm.resize(nnodes);
    //set opt
    hkm.opt = opt;
//     cout << "opt.nlevels:" << hkm.opt.nlevels << ", orig:" << opt.nlevels << endl;

    mxArray* a;

    //now loop and build
    for (uint i=0; i<nnodes; ++i)
    {
      //node id
      mwSize nid = i*ntrees + t;

      //get the node
      HkmNode<T> &node = hkm.at(i+1);

      //get the means
      fillData(node.means, mxGetField(nodes, nid, "means"), true);
      
      //mean stds
      importMeanStds(node.meanStds, mxGetField(nodes, nid, "meanstd"));

      //get the lists
      importHkmPointList(node.plist, mxGetField(nodes, nid, "plist"));    
      importHkmClassIds(node.classIds, mxGetField(nodes, nid, "classids"));

      //visited
      node.visited = (bool) *((uint8_t*)mxGetData(mxGetField(nodes, nid, "visited")));
    }
  //  uint8_t* popt = (uint8_t*) &hkm->opt;
  //  cout << "hkmopt:" << endl;
  //  for (uint i=0; i<sizeof(opt); ++i) cout << " | " << (int)popt[i];
  //  cout << endl;
  //  popt = (uint8_t*) &opt;
  //  cout << "opt:" << endl;
  //  for (uint i=0; i<sizeof(opt); ++i) cout << " | " << (int)popt[i];
  //  cout << endl;
  }
  
  return hkms;
}
示例#17
0
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{

/*Input output boilerplate*/
    if(nlhs != 1 || nrhs != 6)
        mexErrMsgTxt("Function must be called with 6 arguments and has 1 return values");

    const mxArray *x_ptr = prhs[0];
    mexmetypecheck(x_ptr,mxDOUBLE_CLASS,"Argument x (#1) is expected to be of type double");
    const mwSize   x_m = mxGetM(x_ptr);
    const mwSize   x_n = mxGetN(x_ptr);
    const mwSize   x_length = x_m == 1 ? x_n : x_m;
    const mwSize   x_numel = mxGetNumberOfElements(x_ptr);
    const int      x_ndims = mxGetNumberOfDimensions(x_ptr);
    const mwSize  *x_size = mxGetDimensions(x_ptr);
    const double  *x = (double *) mxGetData(x_ptr);
    const mxArray *firstknot_ptr = prhs[1];
    mexmetypecheck(firstknot_ptr,mxDOUBLE_CLASS,"Argument firstknot (#2) is expected to be of type double");
    const mwSize   firstknot_m = mxGetM(firstknot_ptr);
    const mwSize   firstknot_n = mxGetN(firstknot_ptr);
    const mwSize   firstknot_length = firstknot_m == 1 ? firstknot_n : firstknot_m;
    const mwSize   firstknot_numel = mxGetNumberOfElements(firstknot_ptr);
    const int      firstknot_ndims = mxGetNumberOfDimensions(firstknot_ptr);
    const mwSize  *firstknot_size = mxGetDimensions(firstknot_ptr);
    const double  *firstknot = (double *) mxGetData(firstknot_ptr);
    const mxArray *lastknot_ptr = prhs[2];
    mexmetypecheck(lastknot_ptr,mxDOUBLE_CLASS,"Argument lastknot (#3) is expected to be of type double");
    const mwSize   lastknot_m = mxGetM(lastknot_ptr);
    const mwSize   lastknot_n = mxGetN(lastknot_ptr);
    const mwSize   lastknot_length = lastknot_m == 1 ? lastknot_n : lastknot_m;
    const mwSize   lastknot_numel = mxGetNumberOfElements(lastknot_ptr);
    const int      lastknot_ndims = mxGetNumberOfDimensions(lastknot_ptr);
    const mwSize  *lastknot_size = mxGetDimensions(lastknot_ptr);
    const double  *lastknot = (double *) mxGetData(lastknot_ptr);
    const mxArray *knots_ptr = prhs[3];
    mexmetypecheck(knots_ptr,mxDOUBLE_CLASS,"Argument knots (#4) is expected to be of type double");
    const mwSize   knots_m = mxGetM(knots_ptr);
    const mwSize   knots_n = mxGetN(knots_ptr);
    const mwSize   knots_length = knots_m == 1 ? knots_n : knots_m;
    const mwSize   knots_numel = mxGetNumberOfElements(knots_ptr);
    const int      knots_ndims = mxGetNumberOfDimensions(knots_ptr);
    const mwSize  *knots_size = mxGetDimensions(knots_ptr);
    const double  *knots = (double *) mxGetData(knots_ptr);
    const mxArray *weights_ptr = prhs[4];
    mexmetypecheck(weights_ptr,mxDOUBLE_CLASS,"Argument weights (#5) is expected to be of type double");
    const mwSize   weights_m = mxGetM(weights_ptr);
    const mwSize   weights_n = mxGetN(weights_ptr);
    const mwSize   weights_length = weights_m == 1 ? weights_n : weights_m;
    const mwSize   weights_numel = mxGetNumberOfElements(weights_ptr);
    const int      weights_ndims = mxGetNumberOfDimensions(weights_ptr);
    const mwSize  *weights_size = mxGetDimensions(weights_ptr);
    const double  *weights = (double *) mxGetData(weights_ptr);
    const mxArray *order_ptr = prhs[5];
    mexmetypecheck(order_ptr,mxDOUBLE_CLASS,"Argument order (#6) is expected to be of type double");
    if(mxGetNumberOfElements(order_ptr) != 1)
        mexErrMsgTxt("Argument order (#6) must be scalar");
    const double   order = (double) mxGetScalar(order_ptr);
    
    mwSize Sx_dims[] = {x_length,1};
    plhs[0] = mxCreateNumericArray(2,Sx_dims,mxDOUBLE_CLASS,mxREAL);
    mxArray **Sx_ptr = &plhs[0];
    double   *Sx = (double *) mxGetData(*Sx_ptr);
    

    /*
     * Actual function
     */

    int orderint = (int) order;
    int jj,ii;
        
    for(jj = 0; jj < x_length; jj++) {
       double s = 0;
       for(ii = firstknot[jj]; ii < lastknot[jj]; ii++) {
	  s += weights[ii-1]*bin(&(knots[-1]),ii,orderint,x[jj]);
       }
       Sx[jj] = s;
    }


}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{
	double *MUIN, *phi, *theta, *mu, *sr;
	double ALPHA, BETA;
	int W, J, D, NN, SEED, OUTPUT, nzmax, i, j, startcond;
	mwIndex *jc, *ir;

	/* Check for proper number of arguments. */
	if (nrhs < 7) {
		mexErrMsgTxt("At least 7 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");
	sr = mxGetPr(prhs[0]);
	ir = mxGetIr(prhs[0]);
	jc = mxGetJc(prhs[0]);
	nzmax = (int) mxGetNzmax(prhs[0]);
	W = (int) mxGetM(prhs[0]);
	D = (int) mxGetN(prhs[0]);

	phi = mxGetPr(prhs[1]);
	J = (int) mxGetM(prhs[1]);
	if (J<=0) mexErrMsgTxt("Number of topics must be greater than zero");
	if ((int) mxGetN(prhs[1]) != W) mexErrMsgTxt("Vocabulary mismatches");

	NN = (int) mxGetScalar(prhs[2]);
	if (NN<0) mexErrMsgTxt("Number of iterations must be positive");

	ALPHA = (double) mxGetScalar(prhs[3]);
	if (ALPHA<0) mexErrMsgTxt("ALPHA must be greater than zero");

	BETA = (double) mxGetScalar(prhs[4]);
	if (BETA<0) mexErrMsgTxt("BETA must be greater than zero");

	SEED = (int) mxGetScalar(prhs[5]);

	OUTPUT = (int) mxGetScalar(prhs[6]);

	if (startcond == 1) {
		MUIN = mxGetPr(prhs[7]);
		if (nzmax != (mxGetN(prhs[7]))) mexErrMsgTxt("WD and MUIN mismatch");
		if (J != (mxGetM(prhs[7]))) mexErrMsgTxt("J and MUIN mismatch");
	}

	// seeding
	seedMT(1 + SEED*2); // seeding only works on uneven numbers

	/* allocate memory */
	mu  = dvec(J*nzmax);

	if (startcond == 1) {
		for (i=0; i<nzmax; i++) mu[i] = (double) MUIN[i];   
	} 

	theta = dvec(J*D);

	/* run the learning algorithm */
	asiBP(ALPHA, BETA, W, J, D, NN, OUTPUT, jc, ir, sr, phi, theta, mu, startcond);

	/* output */
	plhs[0] = mxCreateDoubleMatrix(J, D, mxREAL);
	mxSetPr(plhs[0], theta);

	plhs[1] = mxCreateDoubleMatrix(J, nzmax, mxREAL);
	mxSetPr(plhs[1], mu);
}
示例#19
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

#ifdef MATLAB_VERBOSE
    //Allows my DBGM macro to redirect output to matlab console
    mystream mout; //defined in utils.h
    std::streambuf *outbuf = std::cout.rdbuf(&mout); //buffer redirection
#endif//MATLAB_VERBOSE  

    //=======================================================================
    // *** User error handling and initialization ***
    // Check the number of input and output parameters
    // This is more important than in regular m-files, as an error at this
    // stage may cause the Matlab instance to crash
    //=======================================================================
    if(nrhs>3)
        mexErrMsgTxt("Too many inputs: Should be an in signal vector followed by (optional) parameter structures");
    if(nrhs<1)
        mexErrMsgTxt("Too few inputs: At minimum, a signal vector must be supplied.");
    if(nlhs > 1)
        mexErrMsgTxt("Too many output arguments:\n"
                     "You are attempting to run the mex version of the algorithm.\n"
                     "Inspection of parameters is disabled.");

    bool isUniqueParsSupplied = (nrhs>1); //alias for readability
    bool isSharedParsSupplied = (nrhs>2); //alias for readability

    if (isUniqueParsSupplied)
        if(!mxIsStruct(UNIQUE_PARS_IN))
            mexErrMsgTxt("(optional) second input argument must be a parameter structure");

    if (isSharedParsSupplied)
        if(!mxIsStruct(SHARED_PARS_IN))
            mexErrMsgTxt("(optional) third input argument must be a parameter structure");

    int xM = mxGetM(AUDIO_DATA_IN); //columns (NxM)=Matlab
    int xN = mxGetN(AUDIO_DATA_IN); //rows (NxM)=Matlab

    if ((xN>2) || (xN<1))
        mexErrMsgTxt("Input must be a single or double channel column matrix i.e. (n,1) or (n,2)");
    bool isStereo = (xN==2); //alias for readability

    if(mxIsChar(AUDIO_DATA_IN) ||
            !mxIsNumeric(AUDIO_DATA_IN) ||
            mxIsSparse(AUDIO_DATA_IN) ||
            mxIsComplex(AUDIO_DATA_IN)   )
        mexErrMsgTxt("Audio data must be non-complex, non-sparse, and numeric");

    int numUniqueParSets =0;
    int numUniqueParFields =0;
    if (isUniqueParsSupplied)
    {
        numUniqueParSets   = mxGetNumberOfElements(UNIQUE_PARS_IN);
        numUniqueParFields = mxGetNumberOfFields(UNIQUE_PARS_IN);
    }

    int numSharedParFields =0;
    if (isSharedParsSupplied)
    {
        if(  mxGetNumberOfElements(SHARED_PARS_IN)   >   1  )
            mexErrMsgTxt("Parameter structure for pars shared between stereo channels should only have one element");
        numSharedParFields = mxGetNumberOfFields(SHARED_PARS_IN);
    }

    bool isStereoPars = (numUniqueParSets == 2); //alias for readability

    if (numUniqueParSets > 2)
        mexErrMsgTxt("Too many parameter sets supplied (parameter struct has more than 2 elements).\n"
                     "Algorithm only functions in mono or stereo - please supply 1x1 or 1x2 element struct.");

    if (isStereoPars && !isStereo)
        mexErrMsgTxt("Ambiguous parameters: Stereo parameters supplied for a mono signal.\n"
                     "Please supply a 1x1 element struct for a mono input, or convert input to stereo" );


    int totalNumElements = xM*xN; /* this is elements for all channels combined */


    //=======================================================================
    // *** Instantiate and modify parameter class(es) ***
    // Set parameter object values according to the supplied structures
    //=======================================================================

    //Create 2: We might waste one, but they are cheap and it saves dynamic allocation
    cUniqueStereoParams uniquePars[2];
    cSharedStereoParams sharedPars; // We only need one of these

    mxArray* tmpData;
    const char* tmpName;

    //============= UNIQUE ================
    for (int structIdx=0; structIdx<numUniqueParSets; ++structIdx)
    {
        for (int fieldIdx=0; fieldIdx<numUniqueParFields; ++fieldIdx)
        {
            tmpData = mxGetFieldByNumber(UNIQUE_PARS_IN, structIdx, fieldIdx);
            tmpName = mxGetFieldNameByNumber(UNIQUE_PARS_IN, fieldIdx);

            checkParamValidity(tmpName, tmpData);

            if(  uniquePars[structIdx].setParam(tmpName, (float)mxGetScalar(tmpData))  ) //The actual setting occurs here (returns TRUE on error)
            {
                std::string errMsg = std::string("Field named \"") + std::string(tmpName)
                                     + std::string("\" is not an existing field name in \"UNIQUE\" parameters");
                mexErrMsgTxt(errMsg.c_str());
            }
        }
    }

    //============= SHARED ================
    for (int fieldIdx=0; fieldIdx<numSharedParFields; ++fieldIdx)
    {
        tmpData = mxGetFieldByNumber(SHARED_PARS_IN, 0, fieldIdx);
        tmpName = mxGetFieldNameByNumber(SHARED_PARS_IN, fieldIdx);

        checkParamValidity(tmpName, tmpData);

        if(  sharedPars.setParam(tmpName, (float)mxGetScalar(tmpData))  ) //The actual setting occurs here (returns TRUE on error)
        {
            std::string errMsg = std::string("Field named \"") + std::string(tmpName)
                                 + std::string("\" is not an existing field name in \"SHARED\" parameters");
            mexErrMsgTxt(errMsg.c_str());
        }
    }


    //=======================================================================
    // *** Signal processing ***
    //=======================================================================
    AUDIO_DATA_OUT = mxCreateDoubleMatrix(xM,xN,mxREAL);

    double* out  = mxGetPr(AUDIO_DATA_OUT);
    double* in   = mxGetPr(AUDIO_DATA_IN);

    float*  in32  =  (float*)mxCalloc(totalNumElements, sizeof(float));
    float*  out32 =  (float*)mxCalloc(totalNumElements, sizeof(float));


    // ---------> DOWNCAST <---------
    for (int mm = 0; mm < totalNumElements; ++mm)
        in32[mm] = (float)in[mm];
    // ---------- DOWNCAST ----------

    // Make the data look like 2D C-style arrays
    //(this fits with other audio APIs [like VST] nicely)
    float* in2D[] =  {in32,  &in32[xM]};
    float* out2D[] = {out32, &out32[xM]};

    if(!isStereo) {
        cAidAlgo myAlgo(uniquePars[0], sharedPars);
        myAlgo.processSampleBlock ((const float**) in2D,  1,  (float**) out2D,   1,   xM);

    } else {
        if (isStereoPars) {
            cAidAlgo myAlgo(uniquePars[0], uniquePars[1], sharedPars);
            myAlgo.processSampleBlock ((const float**) in2D,  2,  (float**) out2D,   2,   xM);
        } else {
            cAidAlgo myAlgo(uniquePars[0], uniquePars[0], sharedPars);
            myAlgo.processSampleBlock ((const float**) in2D,  2,  (float**) out2D,   2,   xM);
        }
    }

    // ---------> UPCAST <---------
    for (int mm = 0; mm < totalNumElements; ++mm)
        out[mm] = (double)out32[mm];
    // ---------- UPCAST ----------


    mxFree(in32);
    mxFree(out32);

#ifdef MATLAB_VERBOSE
    // Play nice and restore the std stream buffer (not strictly necessary)
    std::cout.rdbuf(outbuf);
#endif//MATLAB_VERBOSE
}
/* driver */
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum {IN_X=0,IN_C,IN_END} ;
  enum {OUT_ASGN=0} ;
  vl_uint*     asgn ;
  vl_ikm_acc*  centers ;
  vl_uint8* data ;

  int M,N,j,K=0 ;

  int             opt ;
  int             next = IN_END ;
  mxArray const  *optarg ;

  int method_type = VL_IKM_LLOYD ;
  int verb = 0 ;

  VlIKMFilt *ikmf ;

  VL_USE_MATLAB_ENV ;

  /** -----------------------------------------------------------------
   **                                               Check the arguments
   ** -------------------------------------------------------------- */
  
  if (nin < 2) {
    mexErrMsgTxt("At least two arguments required.") ;
  } else if (nout > 2) {
    mexErrMsgTxt("Too many output arguments.") ;
  }
  
  if(mxGetClassID(in[IN_X]) != mxUINT8_CLASS) {
    mexErrMsgTxt("X must be of class UINT8") ;
  }
  
  if(mxGetClassID(in[IN_C]) != mxINT32_CLASS) {
    mexErrMsgTxt("C must be of class INT32") ;
  }
  
  M = mxGetM(in[IN_X]) ;  /* n of components */
  N = mxGetN(in[IN_X]) ;  /* n of elements */
  K = mxGetN(in[IN_C]) ;  /* n of centers */
  
  if( mxGetM(in[IN_C]) != M ) {
    mexErrMsgTxt("DATA and CENTERS must have the same number of columns.") ;
  }
  
  while ((opt = uNextOption(in, nin, options, &next, &optarg)) >= 0) {
    char buf [1024] ;
    
    switch (opt) {
      
    case opt_verbose :
      ++ verb ;
      break ;
            
    case opt_method :
      if (!uIsString (optarg, -1)) {
        mexErrMsgTxt("'Method' must be a string.") ;        
      }
      if (mxGetString (optarg, buf, sizeof(buf))) {
        mexErrMsgTxt("Option argument too long.") ;
      }
      if (strcmp("lloyd", buf) == 0) {
        method_type = VL_IKM_LLOYD ;
      } else if (strcmp("elkan", buf) == 0) {
        method_type = VL_IKM_ELKAN ;
      } else {
        mexErrMsgTxt("Unknown cost type.") ;
      }
      
      break ;
      
    default :
      assert(0) ;
      break ;
    }
  }
  
  /** -----------------------------------------------------------------
   **                                               Check the arguments
   ** -------------------------------------------------------------- */
  
  if (verb) {
    char const * method_name = 0 ;
    switch (method_type) {
    case VL_IKM_LLOYD: method_name = "Lloyd" ; break ;
    case VL_IKM_ELKAN: method_name = "Elkan" ; break ;
    default :
      assert (0) ;
    }
    mexPrintf("ikmeanspush: Method = %s\n", method_name) ;
    mexPrintf("ikmeanspush: ndata  = %d\n", N) ;
  }

  out[OUT_ASGN] = mxCreateNumericMatrix (1, N, mxUINT32_CLASS, mxREAL) ;

  data    = (vl_uint8*) mxGetData (in[IN_X]) ;
  centers = (vl_ikm_acc*)  mxGetData (in[IN_C]) ;
  asgn    = (vl_uint*)     mxGetData (out[OUT_ASGN]) ;
  ikmf    = vl_ikm_new (method_type) ;
  
  vl_ikm_set_verbosity  (ikmf, verb) ;
  vl_ikm_init           (ikmf, centers, M, K) ;
  vl_ikm_push           (ikmf, asgn, data, N) ;
  
  /* adjust for MATLAB indexing */
  for(j = 0 ; j < N ; ++j) ++ asgn[j] ;

  vl_ikm_delete (ikmf) ;
}
示例#21
0
void mexFunction(
      int nlhs,   mxArray  *plhs[], 
      int nrhs,   const mxArray  *prhs[] )

{    double   *A, *U, *V, *VT, *S, *flag, *work, *AA;  

     mwIndex  *irS, *jcS, *iwork; 
     mwSize   M, N, lwork, info, options, minMN, maxMN, k, j; 
     mwSize   LDA, LDU, LDVT, nU, mVT, mS, nS; 
     char     *jobz;

/* CHECK FOR PROPER NUMBER OF ARGUMENTS */

   if (nrhs > 2){
      mexErrMsgTxt("mexsvd: requires at most 2 input arguments."); }
   if (nlhs > 4){ 
      mexErrMsgTxt("mexsvd: requires at most 4 output argument."); }   

/* CHECK THE DIMENSIONS */

    M = mxGetM(prhs[0]); 
    N = mxGetN(prhs[0]); 
    if (mxIsSparse(prhs[0])) {
       mexErrMsgTxt("mexeig: sparse matrix not allowed."); }   
    A = mxGetPr(prhs[0]); 
    LDA = M; 
    minMN = MIN(M,N); 
    maxMN = MAX(M,N); 
    options = 0; 
    if (nrhs==2) { options = (int)*mxGetPr(prhs[1]); } 
    if (options==0) { 
        /***** economical SVD ******/
       jobz="S"; nU = minMN; mVT = minMN; mS = minMN; nS = minMN; 
    } else {
        /***** full SVD ******/
       jobz="A"; nU = M; mVT = N; mS = M; nS = N; 
    }   
    LDU  = M; 
    LDVT = mVT; 
    /***** create return argument *****/
    if (nlhs >=3) {
       /***** compute singular values and vectors ******/
       plhs[0] = mxCreateDoubleMatrix(M,nU,mxREAL); 
       U = mxGetPr(plhs[0]);  
       plhs[1] = mxCreateSparse(mS,nS,minMN,mxREAL); 
       S   = mxGetPr(plhs[1]); 
       irS = mxGetIr(plhs[1]); 
       jcS = mxGetJc(plhs[1]);
       plhs[2] = mxCreateDoubleMatrix(N,mVT,mxREAL);     
       V = mxGetPr(plhs[2]); 
       plhs[3] = mxCreateDoubleMatrix(1,1,mxREAL);     
       flag = mxGetPr(plhs[3]); 
    } else { 
       /***** compute only singular values ******/
       plhs[0]= mxCreateDoubleMatrix(minMN,1,mxREAL); 
       S = mxGetPr(plhs[0]); 
       plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);     
       flag = mxGetPr(plhs[1]); 
       U = mxCalloc(M*nU,sizeof(double)); 
       V = mxCalloc(N*mVT,sizeof(double)); 
       jobz="N";
    }
    /***** Do the computations in a subroutine *****/   
    lwork = 4*minMN*minMN + MAX(maxMN,5*minMN*minMN+4*minMN);  
    work  = mxCalloc(lwork,sizeof(double)); 
    iwork = mxCalloc(8*minMN,sizeof(int)); 
    VT = mxCalloc(mVT*N,sizeof(double)); 
    AA = mxCalloc(M*N,sizeof(double)); 
    memcpy(AA,mxGetPr(prhs[0]),(M*N)*sizeof(double));

    dgesdd_(jobz,&M,&N, AA,&LDA,S,U,&LDU,VT,&LDVT,work,&lwork,iwork, &info); 

    flag[0] = (double)info; 
    if (nlhs >= 3) { 
       for (k=0; k<minMN; k++) { irS[k] = k; }
       jcS[0] = 0;
       for (k=1; k<=nS; k++) { 
          if (k<minMN) { jcS[k] = k; } else { jcS[k] = minMN; }
       }  
       for (k=0; k<mVT; k++) { 
          for (j=0; j<N; j++) { V[j+k*N] = VT[k+j*mVT]; }
       }
    }
    return;
 }
示例#22
0
文件: smlr_mex.c 项目: Zubeen/CIS520
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

    /* Check for invalid usage */
    if (nrhs < 15)
        mexErrMsgTxt("Not enough input arguments.");
    if (nrhs > 15)
        mexErrMsgTxt("Too many input arguments.");
    if (nlhs < 5)
        mexErrMsgTxt("Not enough output arguments.");
    if (nlhs > 5)
        mexErrMsgTxt("Too many output arguments.");

    /* --------------------------------------------------------------------- */
    /* Grab all the input arguments */

    const mxArray *w_in = prhs[0];
    const mxArray *X = prhs[1];
    const mxArray *XY = prhs[2];
    const mxArray *Xw_in = prhs[3];
    const mxArray *E_in = prhs[4];
    const mxArray *S_in = prhs[5];
    const mxArray *B = prhs[6];
    const mxArray *delta = prhs[7];
    const mxArray *w_resamp_in = prhs[8];

    double maxiter = *mxGetPr(prhs[9]);
    double tol = *mxGetPr(prhs[10]);
    double decay_rate = *mxGetPr(prhs[11]);
    double decay_min = *mxGetPr(prhs[12]);
    int seed = (int)*mxGetPr(prhs[13]);
    int verbose = (int)*mxGetPr(prhs[14]);

    /* --------------------------------------------------------------------- */
    // Allocate extra memory to return modified copies of several inputs

    mxArray *w = copyMxArray(w_in);
    mxArray *Xw = copyMxArray(Xw_in);
    mxArray *E = copyMxArray(E_in);
    mxArray *S = copyMxArray(S_in);
    mxArray *w_resamp = copyMxArrayFloat(w_resamp_in);

    /* --------------------------------------------------------------------- */
    // Run the SMLR iterative optimization loop
    int N = mxGetM(X);
    int D = mxGetN(X);
    int M = mxGetN(w);

    int iter = stepwise_regression(N, D, M,
                                   mxGetData(w), mxGetData(w_resamp),
                                   mxGetData(X), mxGetData(Xw), mxGetData(E),
                                   mxGetData(S),
                                   mxGetData(XY), mxGetData(B), mxGetData(delta),
                                   maxiter, tol, decay_rate, decay_min,
                                   seed, verbose);

    // Return the modified inputs
    plhs[0] = w;
    plhs[1] = Xw;
    plhs[2] = E;
    plhs[3] = S;
    plhs[4] = mxCreateDoubleScalar(iter); //
}
示例#23
0
/* Matlab Gateway routine */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	char	*pszSRS_WKT = NULL;
	GDALDatasetH	hSrcDS, hDstDS;
	GDALDriverH	hDriver;
	GDALRasterBandH hBand;
	OGRSpatialReference oSrcSRS, oDstSRS; 
	GDALResampleAlg	interpMethod = GRA_NearestNeighbour;
	GDALTransformerFunc pfnTransformer = NULL;
	CPLErr		eErr;
	GDAL_GCP	*pasGCPs = NULL;
	void		*hTransformArg;
	static int runed_once = FALSE;	/* It will be set to true if reaches end of main */

	int	nx, ny, i, j, m, n, c = 0, n_pts, n_fields;
	char	*pszSrcSRS = NULL, *pszSrcWKT = NULL;
	char	*pszDstSRS = NULL, *pszDstWKT = NULL;
	double	*in_data, *ptr_d, *x, *y, *z;
	mxArray	*mx_ptr;

	int	nGCPCount = 0, nOrder = 0;
	char	**papszMetadataOptions = NULL;
	char	*tmp, *txt;
	int	bInverse = FALSE;
	int	*bSuccess;
	char	**papszTO = NULL;


	if (nrhs == 2 && mxIsStruct(prhs[1])) {

		/* -------------------------------------------------- */

		/* -------- See for projection stuff ---------------- */
		mx_ptr = mxGetField(prhs[1], 0, "SrcProjSRS");
		if (mx_ptr != NULL)
			pszSrcSRS = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "SrcProjWKT");
		if (mx_ptr != NULL)
			pszSrcWKT = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "DstProjSRS");
		if (mx_ptr != NULL)
			pszDstSRS = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "DstProjWKT");
		if (mx_ptr != NULL)
			pszDstWKT = (char *)mxArrayToString(mx_ptr);
		/* -------------------------------------------------- */

		/* -------- Do we have GCPs? ----------------------- */
		mx_ptr = mxGetField(prhs[1], 0, "gcp");
		if (mx_ptr != NULL) {
			nGCPCount = mxGetM(mx_ptr);
			if (mxGetN(mx_ptr) != 4)
				mexErrMsgTxt("GDALWARP: GCPs must be a Mx4 array");
			ptr_d = mxGetPr(mx_ptr);
			pasGCPs = (GDAL_GCP *) mxCalloc( nGCPCount, sizeof(GDAL_GCP) );
			GDALInitGCPs( 1, pasGCPs + nGCPCount - 1 );
			for (i = 0; i < nGCPCount; i++) {
				pasGCPs[i].dfGCPPixel = ptr_d[i];
				pasGCPs[i].dfGCPLine = ptr_d[i+nGCPCount];
				pasGCPs[i].dfGCPX = ptr_d[i+2*nGCPCount];
				pasGCPs[i].dfGCPY = ptr_d[i+3*nGCPCount];
				pasGCPs[i].dfGCPZ = 0;
			}
		}
			/* ---- Have we an order request? --- */
		mx_ptr = mxGetField(prhs[1], 0, "order");
		if (mx_ptr != NULL) {
			ptr_d = mxGetPr(mx_ptr);
			nOrder = (int)*ptr_d;
			if (nOrder != -1 || nOrder != 0 || nOrder != 1 ||
				nOrder != 2 || nOrder != 3)
				nOrder = 0;
		}
		/* -------------------------------------------------- */
		mx_ptr = mxGetField(prhs[1], 0, "inverse");
		if (mx_ptr != NULL)
			bInverse = TRUE;

		mx_ptr = mxGetField(prhs[1], 0, "ResampleAlg");
		if (mx_ptr != NULL) {
			txt = (char *)mxArrayToString(mx_ptr);
			if (!strcmp(txt,"nearest"))
				interpMethod = GRA_NearestNeighbour;
			else if (!strcmp(txt,"bilinear"))
				interpMethod = GRA_Bilinear;
			else if (!strcmp(txt,"cubic") || !strcmp(txt,"bicubic"))
				interpMethod = GRA_Cubic;
			else if (!strcmp(txt,"spline"))
				interpMethod = GRA_CubicSpline;
		}

	}
	else {
		mexPrintf("Usage: out = gdaltransform_mex(IN,PAR_STRUCT)\n\n");
		mexPrintf("      IN is a Mx2 or Mx3 array of doubles with X, Y (,Z)\n");
		mexPrintf("      PAR_STRUCT is a structure with at most two of the next fields:\n");
		mexPrintf("\t\t'SrcProjSRS', 'SrcProjWKT' -> Source projection string\n");
		mexPrintf("\t\t'DstProjSRS', 'DstProjWKT' -> Target projection string\n");
		mexPrintf("\t\t\tSRS stands for a string of the type used by proj4\n");
		mexPrintf("\t\t\tWKT stands for a string on the 'Well Known Text' format\n\n");
		mexPrintf("\t\t\tIf one of the Src or Dst fields is absent a GEOGRAPHIC WGS84 is assumed\n");
		mexPrintf("\nOPTIONS\n");
		mexPrintf("\t\t'gcp' a [Mx4] array with Ground Control Points\n");
		mexPrintf("\t\t'inverse' reverse transformation. e.g from georef to rows-columns\n");

		if (!runed_once)		/* Do next call only at first time this MEX is loaded */
			GDALAllRegister();

        	mexPrintf( "The following format drivers are configured and support Create() method:\n" );
        	for( i = 0; i < GDALGetDriverCount(); i++ ) {
			hDriver = GDALGetDriver(i);
			if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL)
				mexPrintf("%s: %s\n", GDALGetDriverShortName(hDriver), 
							GDALGetDriverLongName(hDriver));
		}
		return;
	}


	if (!runed_once) 		/* Do next call only at first time this MEX is loaded */
		GDALAllRegister();


	/* ----- Check that first argument contains at least a mx2 table */
	n_pts = mxGetM (prhs[0]);
	n_fields = mxGetN(prhs[0]);
	if (!mxIsNumeric(prhs[0]) || (n_fields < 2)) {
		mexPrintf("GDALTRANSFORM ERROR: first argument must contain a mx2 (or mx3) table\n");
		mexErrMsgTxt("               with the x,y (,z) positions to convert.\n");
	}

DEBUGA(1);
	/* ---------- Set the Source projection ---------------------------- */
	/* If it was not provided assume it is Geog WGS84 */
	if (pszSrcSRS == NULL && pszSrcWKT == NULL)
		oSrcSRS.SetWellKnownGeogCS( "WGS84" ); 
	else if (pszSrcWKT != NULL)
		oSrcSRS.importFromWkt( &pszSrcWKT );

	else {
		if( oSrcSRS.SetFromUserInput( pszSrcSRS ) != OGRERR_NONE )
			mexErrMsgTxt("GDALTRANSFORM: Translating source SRS failed.");
	}
	if (pszSrcWKT == NULL)
		oSrcSRS.exportToWkt( &pszSrcWKT );

	/* ------------------------------------------------------------------ */


DEBUGA(2);
	/* ---------- Set up the Target coordinate system ------------------- */
	/* If it was not provided assume it is Geog WGS84 */
	CPLErrorReset();
	if (pszDstSRS == NULL && pszDstWKT == NULL)
		oDstSRS.SetWellKnownGeogCS( "WGS84" ); 
	else if (pszDstWKT != NULL)
		oDstSRS.importFromWkt( &pszDstWKT );
	else {
		if( oDstSRS.SetFromUserInput( pszDstSRS ) != OGRERR_NONE )
			mexErrMsgTxt("GDALTRANSFORM: Translating target SRS failed.");
	}
	if (pszDstWKT == NULL)
		oDstSRS.exportToWkt( &pszDstWKT );
	/* ------------------------------------------------------------------ */



	/* -------------------------------------------------------------------- */
	/*      Create a transformation object from the source to               */
	/*      destination coordinate system.                                  */
	/* -------------------------------------------------------------------- */
	if( nGCPCount != 0 && nOrder == -1 ) {
		pfnTransformer = GDALTPSTransform;
		hTransformArg = GDALCreateTPSTransformer( nGCPCount, pasGCPs, FALSE );
	}
	else if( nGCPCount != 0 ) {
DEBUGA(3);
		pfnTransformer = GDALGCPTransform;
		hTransformArg = GDALCreateGCPTransformer( nGCPCount, pasGCPs, nOrder, FALSE );
	}
	else {
		pfnTransformer = GDALGenImgProjTransform;
		//hTransformArg = GDALCreateGenImgProjTransformer2( hSrcDS, hDstDS, papszTO );
		hTransformArg = 
    			GDALCreateGenImgProjTransformer( NULL, pszSrcWKT, NULL, pszDstWKT, 
						 nGCPCount == 0 ? FALSE : TRUE, 0, nOrder );
	}

	//CSLDestroy( papszTO );
DEBUGA(4);

	if( hTransformArg == NULL )
		mexErrMsgTxt("GDALTRANSFORM: Generating transformer failed.");

	in_data = (double *)mxGetData(prhs[0]);

	if (n_pts == 1) {
		x = &in_data[0];
		y = &in_data[1];
		bSuccess = &c;
	}
	else {
		x = (double *)mxCalloc(n_pts, sizeof(double));
		y = (double *)mxCalloc(n_pts, sizeof(double));
		bSuccess = (int *)mxCalloc(n_pts, sizeof(int));

		for (j = 0; j < n_pts; j++) {
			x[j] = in_data[j];
			y[j] = in_data[j+n_pts];
		}
	}
DEBUGA(5);

	z = (double *)mxCalloc(n_pts, sizeof(double));
	if (n_fields == 3)
		for (j = 0; j < n_pts; j++)
			z[j] = in_data[j+2*n_pts];

	if ( !pfnTransformer( hTransformArg, bInverse, n_pts, x, y, z, bSuccess ) )
		mexPrintf( "Transformation failed.\n" );


DEBUGA(6);
	if( nGCPCount != 0 && nOrder == -1 )
		GDALDestroyTPSTransformer(hTransformArg);
	else if( nGCPCount != 0 )
		GDALDestroyGCPTransformer(hTransformArg);
	else
		GDALDestroyGenImgProjTransformer(hTransformArg);


	/* -------------- Copy the result into plhs  --------------------------------- */
	plhs[0] = mxCreateDoubleMatrix (n_pts,n_fields, mxREAL);
	ptr_d = mxGetPr(plhs[0]);

	for (j = 0; j < n_pts; j++) {
		ptr_d[j] = x[j];
		ptr_d[j+n_pts] = y[j];
	}

	if (n_pts > 1) {
		mxFree((void *)x);	mxFree((void *)y);	mxFree((void *)bSuccess);
	}

	if (n_fields == 3) {
		for (j = 0; j < n_pts; j++)
			ptr_d[j+2*n_pts] = z[j];
	}
	mxFree((void *)z);


	if (pszDstWKT && strlen(pszDstWKT) > 1 ) OGRFree(pszDstWKT);	
	if (pszSrcWKT && strlen(pszSrcWKT) > 1 ) OGRFree(pszSrcWKT);
	//OGRFree(pszSrcWKT);
	//OGRFree(pszDstWKT);
	if (nGCPCount > 0) {
		GDALDeinitGCPs( nGCPCount, pasGCPs );	// makes this mex crash in the next call
		mxFree((void *) pasGCPs );
	}

	runed_once = TRUE;	/* Signals that next call won't need to call GDALAllRegister() again */

}
示例#24
0
文件: vl_aib.c 项目: ledduy/kaori-ins
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  enum {IN_PCX = 0, IN_END} ;
  enum {OUT_PARENTS = 0, OUT_COST} ;
  enum {INFORMATION, EC} ;

  int            verbose = 0 ;
  int            opt ;
  int            next = IN_END ;
  mxArray const *optarg ;
  int            cluster_null = 0 ;

  double   *Pcx     ;
  vl_uint32    nlabels ;
  vl_uint32    nvalues ;

  mxArray *Pcx_cpy ;

  VL_USE_MATLAB_ENV ;

  /* -----------------------------------------------------------------
   *                                               Check the arguments
   * -------------------------------------------------------------- */

  if (nin < 1) {
    mexErrMsgTxt("One argument required.") ;
  } else if (nout > 2) {
    mexErrMsgTxt("Too many output arguments.");
  }

  if (!vlmxIsMatrix(in[IN_PCX], -1, -1)) {
    mexErrMsgTxt("PCX must be a real matrix.") ;
  }

  Pcx_cpy = mxDuplicateArray(in[IN_PCX]);
  Pcx     = mxGetPr (Pcx_cpy) ;
  nlabels = mxGetM  (in[IN_PCX]) ;
  nvalues = mxGetN  (in[IN_PCX]) ;

  while ((opt = vlmxNextOption (in, nin, options, &next, &optarg)) >= 0) {

    switch (opt) {

    case opt_verbose :
      ++ verbose ;
      break ;

    case opt_cluster_null :
      cluster_null = 1 ;
      break ;

    }
  }

  if (verbose) {
    mexPrintf("aib: cluster null:    %d", cluster_null) ;
  }

  /* -----------------------------------------------------------------
   *                                                            Do job
   * -------------------------------------------------------------- */

  {
    VlAIB   *aib;
    double* acost = 0, *cost = 0 ;
    vl_uint32 *aparents = 0, *parents = 0 ;
    vl_uint32 n ;

    out[OUT_PARENTS] = mxCreateNumericMatrix(1, 2*nvalues - 1, mxUINT32_CLASS, mxREAL);
    parents = mxGetData(out[OUT_PARENTS]);

    if (nout > 1) {
      out[OUT_COST] = mxCreateNumericMatrix(1, nvalues, mxDOUBLE_CLASS, mxREAL);
      cost = mxGetPr(out[OUT_COST]);
    }

    aib = vl_aib_new (Pcx, nvalues, nlabels) ;
    vl_aib_process (aib);

    aparents = vl_aib_get_parents (aib);
    acost    = vl_aib_get_costs (aib);
    memcpy(parents, aparents, sizeof(vl_uint32)*(2*nvalues-1));
    if (nout > 1)
      memcpy(cost, acost, sizeof(double)*nvalues);

    vl_aib_delete(aib);

    if (cluster_null) {
      cluster_null_nodes (parents, nvalues, (nout == 0) ? 0 : cost) ;
    }

    /* save back parents */
    for (n = 0 ; n < 2 * nvalues - 1 ; ++n) {
      if (parents [n] > 2 * nvalues - 1) {
        /* map ingored nodes to zero */
        parents [n] = 0 ;
      } else {
        /* MATLAB starts counting from 1 */
        ++ parents [n]  ;
      }
    }

  }
  mxDestroyArray(Pcx_cpy);
}
示例#25
0
/*!
	\param nlhs number of left-hand-side output arguments
	\param plhs mxArray of output arguments
	\param nrhs number of right-hand-side input arguments
	\param prhs mxArray of input arguments
*/
void mexFunction( int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray*prhs[] )
     
{ 
	int p, nStage, L, flag;
	int i, j, m, n, N, J, K, M;
	double *v_in, *v_out, *v_ext, *v_final, *temp;

	/* Check for proper number of arguments */    
    if (nrhs != 1) { 
		mexErrMsgTxt("Only one input arguments required."); 
	} 
	else if (nlhs > 1) {
		mexErrMsgTxt("Too many output arguments."); 
    }

	/* Get the size and pointers to input data. */
	m  = mxGetM(prhs[0]);
	n  = mxGetN(prhs[0]);


	if (MIN(m,n) != 1) {
		mexErrMsgTxt("Only vectors accepted as input right now."); 
	}

	/* flag == 1, row vector; flag == 0, column vector. */
	flag = 1;
	if ( m != 1) {
		flag = 0;
	}

    /* Make sure that both input and output vectors have the length with 2^p where p is some integer. */ 
	n = MAX(m,n);
	p = ceil(log2(n));
    N = pow(2,p);	
    // sqrtN = sqrt(N);
	if ( flag == 1) {
		plhs[0] = mxCreateDoubleMatrix(1, N, mxREAL);
	}
	else {
		plhs[0] = mxCreateDoubleMatrix(N, 1, mxREAL);
	}
	v_final = mxGetPr(plhs[0]);
	v_in = mxGetPr(prhs[0]);
	
	/* Extend the input vector if necessary. */
	v_ext = (double*) mxCalloc (N,sizeof(double));
	v_out = (double*) mxCalloc (N,sizeof(double));
	for (j = 0; j <n; j++){
		v_ext[j] = v_in[j];
	}
	// mxDestroyArray(prhs[0]);

	
	for (i=0; i<N-1; i = i+2) {
		v_ext[i] = v_ext[i] + v_ext[i+1];
		v_ext[i+1] = v_ext[i] - v_ext[i+1] * 2;
	}
	L = 1;
    
	/* main loop */
	for (nStage = 2; nStage<=p; ++nStage){
		M = pow(2,L);
		J = 0;
		K = 0; // difference between Matlab and C++
		while (K<N-1){
			for (j = J;j < J+M-1; j = j+2){
				/* sequency order  */
				v_out[K] = v_ext[j] + v_ext[j+M];
				v_out[K+1] = v_ext[j] - v_ext[j+M];
				v_out[K+2] = v_ext[j+1] - v_ext[j+1+M];
				v_out[K+3] = v_ext[j+1] + v_ext[j+1+M];

				K = K+4;
			}

			J = J+2*M;
		}

		// for ( i =0; i<N; ++i){
		// 	v_ext[i] = v_out[i];
		// }

		// mxFree(v_ext);
		temp = v_ext;
		v_ext = v_out;
		v_out = temp;
		// v_out = (double*) mxMalloc (N,sizeof(double));

		L = L+1;
	}

	/* Perform scaling of coefficients. */
	for ( i =0; i<N; ++i){
			v_final[i] = v_ext[i]/N;
	}
	
	/* Set free the memory. */
	mxFree(v_out);
	mxFree(v_ext);

	return;
}
示例#26
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
                 const mxArray *prhs[])
{
  int len;  
  double rs, cs, re, ce;
  int *rr, *cc;
  double *p;
  int i;
  int row, col;
    
  /* Check for proper number of arguments. */
  if (nrhs != 5 || nlhs > 1) {
    mexErrMsgTxt("SegInMat::Invalid calling method...please type help LineTwoPntsInMat in"                  "command for help\n");
  } 
  rs = mxGetScalar(prhs[1]);
  cs = mxGetScalar(prhs[2]);
  re = mxGetScalar(prhs[3]);
  ce = mxGetScalar(prhs[4]);
  /* 获取所得线段的长度 */
  len = bresenham_len((int)rs, (int)cs, (int)re, (int)ce);
  rr = (int*)mxCalloc(len, sizeof(int));
  cc = (int*)mxCalloc(len, sizeof(int));
  
  
  /* 求线段上所有点 */
  bresenham((int)rs, (int)cs, (int)re, (int)ce, rr, cc);
  
  /* 
   * 将对应点上的值填入输出.
   * 注意!!Matlab中矩阵按列存储,下标从1开始。C中下标从0开始
   */
  
  int nrow = mxGetM(prhs[0]);
  int ncol = mxGetN(prhs[0]);

  // 注意:检查行列是否在范围内
  if ( rs > nrow || rs < 1
    || re > nrow || re < 1
    || cs > ncol || cs < 1
    || ce > ncol || ce < 1) 
  {
    mexErrMsgTxt("SegInMat::Input point out of range...\n");
  }
  else 
  {
    plhs[0] = mxCreateDoubleMatrix(1, len, mxREAL);
    p = mxGetPr(plhs[0]);
  }

  
  if (mxIsDouble(prhs[0])) {
    double* pmat = (double* )mxGetPr(prhs[0]);
    for (i = 0; i < len; ++i) {
      row = *(rr+i);
      col = *(cc+i);
      *(p+i) = (double)(*(pmat + (col-1)*nrow + row - 1));
    }
    return;
  }
  else {
    mexErrMsgTxt("SegInMat::Only supports double matrix\n" 
      "Try forced casting:\n"
      "SegInMat(double(mat),rs,cs, re,ce)\n"
      "Or use:\n"
      "  [rr,cc] = LineTwoPnts(rs,ce, re,ce);\n"
      "  idx     = sub2ind(rr,cc);\n"
      "  elems   = mat(idx);\n"
      "as alternative.");
  }
  
  

}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

	/*variables*/
	char *buffer; /*array for input string*/
	int32_t levels; /*number of levels*/
	int64_t w, h; /*width, height of each level*/
	double *dims, *ds; /*pointers to outputs - for convenience*/
	const char *objective, *mppx, *mppy;
	openslide_t *slide; /*openslide struct*/
	int i; /*loop iterator*/
	
	/*check input arguments*/
	if(nrhs != 1) {
		mexErrMsgTxt("'openslide_check_levels.m' requires one input argument.");
	}
	if(nlhs > 5) {
		mexErrMsgTxt("'openslide_check_levels.m' produces two outputs.");
	}
	
	/*check input type*/
	if(!mxIsChar(prhs[0]) || (mxGetM(prhs[0]) != 1)) {
		mexErrMsgTxt("Input must be character array.");
	}
	
	/*copy*/
	buffer = mxArrayToString(prhs[0]);
	
	/*copy input*/
	if(openslide_can_open(buffer) == 1) {
			
		/*open*/	
		slide = openslide_open(buffer);

		/*check for error*/
		if(openslide_get_error(slide) != NULL) {
			mexErrMsgTxt("'openslide_check_levels.m' cannot open slide.");
		}
		else {
			
			/*get # of levels*/
			levels = openslide_get_layer_count(slide);
			
			/*allocate arrays*/
			plhs[0] = mxCreateDoubleMatrix((mwSize)levels, 2, mxREAL);
			plhs[1] = mxCreateDoubleMatrix((mwSize)levels, 1, mxREAL);
			
			/*get output addresses*/
			dims = mxGetPr(plhs[0]);
			ds = mxGetPr(plhs[1]);
			
			/*loop through levels, get dimensions/downsample factor of each*/
			for(i = 0; i < levels; i++) {
			
				/*get level info*/
				openslide_get_layer_dimensions(slide, (int32_t)i, &w, &h);
				*ds = openslide_get_layer_downsample(slide, (int32_t)i);
				ds = ds + 1;
				
				/*copy dimensions to outputs*/
				*dims = (double)h;
				*(dims+levels) = (double)w;
				dims = dims + 1;
				
			}

			/*get properties*/
			objective = openslide_get_property_value(slide, OPENSLIDE_PROPERTY_NAME_OBJECTIVE_POWER);
			mppx = openslide_get_property_value(slide, OPENSLIDE_PROPERTY_NAME_MPP_X);
			mppy = openslide_get_property_value(slide, OPENSLIDE_PROPERTY_NAME_MPP_Y);
			
			/*assign properties to outputs*/
			plhs[2] = mxCreateString(objective);
			plhs[3] = mxCreateString(mppx);
			plhs[4] = mxCreateString(mppy);
			
		}
	}
	else{ /*can't open slide*/
		mexErrMsgTxt("'openslide_check_levels.m' cannot open slide.");
	}
	
	/*free input buffer copy*/
	mxFree(buffer);
	
}
示例#28
0
/* The gateway routine */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
/* ----------------- Variables ----------------- */
/* input variables */
/* mandatory input */
  int startIdx;
  int endIdx;
  double * high;
  double * low;
  double * close;
/* optional input */
  int	 optInTimePeriod;
/* output variables */ 
  int outBegIdx;
  int outNbElement;
  double*	 outReal;
/* input dimentions */ 
  int inSeriesRows;
  int inSeriesCols;
/* error handling */
  TA_RetCode retCode;

/* ----------------- input/output count ----------------- */  
  /*  Check for proper number of arguments. */
  if (nrhs < 3 || nrhs > 4) mexErrMsgTxt("#4 inputs possible #1 optional.");
  if (nlhs != 1) mexErrMsgTxt("#1 output required.");
/* ----------------- INPUT ----------------- */ 
  /* Create a pointer to the input matrix high. */
  high = mxGetPr(prhs[0]);
  /* Get the dimensions of the matrix input high. */
  inSeriesCols = mxGetN(prhs[0]);
  if (inSeriesCols != 1) mexErrMsgTxt("high only vector alowed.");
  /* Create a pointer to the input matrix low. */
  low = mxGetPr(prhs[1]);
  /* Get the dimensions of the matrix input low. */
  inSeriesCols = mxGetN(prhs[1]);
  if (inSeriesCols != 1) mexErrMsgTxt("low only vector alowed.");
  /* Create a pointer to the input matrix close. */
  close = mxGetPr(prhs[2]);
  /* Get the dimensions of the matrix input close. */
  inSeriesCols = mxGetN(prhs[2]);
  if (inSeriesCols != 1) mexErrMsgTxt("close only vector alowed.");
  inSeriesRows = mxGetM(prhs[2]);  
  endIdx = inSeriesRows - 1;  
  startIdx = 0;

 /* Process optional arguments */ 
  if (nrhs >= 3+1) {
	if (!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) ||
      mxGetN(prhs[3])*mxGetM(prhs[3]) != 1) 
    	mexErrMsgTxt("Input optInTimePeriod must be a scalar.");
   	/* Get the scalar input optInTimePeriod. */
   	optInTimePeriod = (int)  mxGetScalar(prhs[3]);
  } else {
  	optInTimePeriod = 14;
  }

/* ----------------- OUTPUT ----------------- */
  outReal = mxCalloc(inSeriesRows, sizeof(double));
/* -------------- Invocation ---------------- */

	retCode = TA_DX(
                   startIdx, endIdx,
                   high,
                   low,
                   close,
                   optInTimePeriod,
                   &outBegIdx, &outNbElement,
                   outReal);
/* -------------- Errors ---------------- */
   if (retCode) {
   	   mxFree(outReal);
       mexPrintf("%s%i","Return code=",retCode);
       mexErrMsgTxt(" Error!");
   }
  
   // Populate Output
  plhs[0] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL);
  memcpy(((double *) mxGetData(plhs[0]))+outBegIdx, outReal, outNbElement*mxGetElementSize(plhs[0]));
  mxFree(outReal);  
} /* END mexFunction */
示例#29
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *Prhs[])
{
register int i;
register double *pdbl;
mxArray **prhs=(mxArray **)&Prhs[0], *At, *Ct;
struct mexdata mdata;
int len, status;
double *p, *p0, *ret, *x;
int m, n, havejac, Arows, Crows, itmax, nopts, mintype, nextra;
double opts[LM_OPTS_SZ]={LM_INIT_MU, LM_STOP_THRESH, LM_STOP_THRESH, LM_STOP_THRESH, LM_DIFF_DELTA};
double info[LM_INFO_SZ];
double *lb=NULL, *ub=NULL, *A=NULL, *b=NULL, *wghts=NULL, *C=NULL, *d=NULL, *covar=NULL;

  /* parse input args; start by checking their number */
  if((nrhs<5))
    matlabFmtdErrMsgTxt("levmar: at least 5 input arguments required (got %d).", nrhs);
  if(nlhs>4)
    matlabFmtdErrMsgTxt("levmar: too many output arguments (max. 4, got %d).", nlhs);
  else if(nlhs<2)
    matlabFmtdErrMsgTxt("levmar: too few output arguments (min. 2, got %d).", nlhs);
    
  /* note that in order to accommodate optional args, prhs & nrhs are adjusted accordingly below */

  /** func **/
  /* first argument must be a string , i.e. a char row vector */
  if(mxIsChar(prhs[0])!=1)
    mexErrMsgTxt("levmar: first argument must be a string.");
  if(mxGetM(prhs[0])!=1)
    mexErrMsgTxt("levmar: first argument must be a string (i.e. char row vector).");
  /* store supplied name */
  len=mxGetN(prhs[0])+1;
  mdata.fname=mxCalloc(len, sizeof(char));
  status=mxGetString(prhs[0], mdata.fname, len);
  if(status!=0)
    mexErrMsgTxt("levmar: not enough space. String is truncated.");

  /** jac (optional) **/
  /* check whether second argument is a string */
  if(mxIsChar(prhs[1])==1){
    if(mxGetM(prhs[1])!=1)
      mexErrMsgTxt("levmar: second argument must be a string (i.e. row vector).");
    /* store supplied name */
    len=mxGetN(prhs[1])+1;
    mdata.jacname=mxCalloc(len, sizeof(char));
    status=mxGetString(prhs[1], mdata.jacname, len);
    if(status!=0)
      mexErrMsgTxt("levmar: not enough space. String is truncated.");
    havejac=1;

    ++prhs;
    --nrhs;
  }
  else{
    mdata.jacname=NULL;
    havejac=0;
  }

#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: %s analytic Jacobian\n", havejac? "with" : "no");
#endif /* DEBUG */

/* CHECK 
if(!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || !(mxGetM(prhs[1])==1 && mxGetN(prhs[1])==1))
*/

  /** p0 **/
  /* the second required argument must be a real row or column vector */
  if(!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1]) || !(mxGetM(prhs[1])==1 || mxGetN(prhs[1])==1))
    mexErrMsgTxt("levmar: p0 must be a real vector.");
  p0=mxGetPr(prhs[1]);
  /* determine if we have a row or column vector and retrieve its 
   * size, i.e. the number of parameters
   */
  if(mxGetM(prhs[1])==1){
    m=mxGetN(prhs[1]);
    mdata.isrow_p0=1;
  }
  else{
    m=mxGetM(prhs[1]);
    mdata.isrow_p0=0;
  }
  /* copy input parameter vector to avoid destroying it */
  p=mxMalloc(m*sizeof(double));
  for(i=0; i<m; ++i)
    p[i]=p0[i];
    
  /** x **/
  /* the third required argument must be a real row or column vector */
  if(!mxIsDouble(prhs[2]) || mxIsComplex(prhs[2]) || !(mxGetM(prhs[2])==1 || mxGetN(prhs[2])==1))
    mexErrMsgTxt("levmar: x must be a real vector.");
  x=mxGetPr(prhs[2]);
  n=__MAX__(mxGetM(prhs[2]), mxGetN(prhs[2]));

  /** itmax **/
  /* the fourth required argument must be a scalar */
  if(!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3]) || mxGetM(prhs[3])!=1 || mxGetN(prhs[3])!=1)
    mexErrMsgTxt("levmar: itmax must be a scalar.");
  itmax=(int)mxGetScalar(prhs[3]);
    
  /** opts **/
  /* the fifth required argument must be a real row or column vector */
  if(!mxIsDouble(prhs[4]) || mxIsComplex(prhs[4]) || (!(mxGetM(prhs[4])==1 || mxGetN(prhs[4])==1) &&
                                                      !(mxGetM(prhs[4])==0 && mxGetN(prhs[4])==0)))
    mexErrMsgTxt("levmar: opts must be a real vector.");
  pdbl=mxGetPr(prhs[4]);
  nopts=__MAX__(mxGetM(prhs[4]), mxGetN(prhs[4]));
  if(nopts!=0){ /* if opts==[], nothing needs to be done and the defaults are used */
    if(nopts>LM_OPTS_SZ)
      matlabFmtdErrMsgTxt("levmar: opts must have at most %d elements, got %d.", LM_OPTS_SZ, nopts);
    else if(nopts<((havejac)? LM_OPTS_SZ-1 : LM_OPTS_SZ))
      matlabFmtdWarnMsgTxt("levmar: only the %d first elements of opts specified, remaining set to defaults.", nopts);
    for(i=0; i<nopts; ++i)
      opts[i]=pdbl[i];
  }
#ifdef DEBUG
  else{
    fflush(stderr);
    fprintf(stderr, "LEVMAR: empty options vector, using defaults\n");
  }
#endif /* DEBUG */

  /** mintype (optional) **/
  /* check whether sixth argument is a string */
  if(nrhs>=6 && mxIsChar(prhs[5])==1 && mxGetM(prhs[5])==1){
    char *minhowto;

    /* examine supplied name */
    len=mxGetN(prhs[5])+1;
    minhowto=mxCalloc(len, sizeof(char));
    status=mxGetString(prhs[5], minhowto, len);
    if(status!=0)
      mexErrMsgTxt("levmar: not enough space. String is truncated.");

    for(i=0; minhowto[i]; ++i)
      minhowto[i]=tolower(minhowto[i]);
    if(!strncmp(minhowto, "unc", 3)) mintype=MIN_UNCONSTRAINED;
    else if(!strncmp(minhowto, "bc", 2)) mintype=MIN_CONSTRAINED_BC;
    else if(!strncmp(minhowto, "lec", 3)) mintype=MIN_CONSTRAINED_LEC;
    else if(!strncmp(minhowto, "blec", 4)) mintype=MIN_CONSTRAINED_BLEC;
    else if(!strncmp(minhowto, "bleic", 5)) mintype=MIN_CONSTRAINED_BLEIC;
    else if(!strncmp(minhowto, "blic", 4)) mintype=MIN_CONSTRAINED_BLIC;
    else if(!strncmp(minhowto, "leic", 4)) mintype=MIN_CONSTRAINED_LEIC;
    else if(!strncmp(minhowto, "lic", 3)) mintype=MIN_CONSTRAINED_BLIC;
    else matlabFmtdErrMsgTxt("levmar: unknown minimization type '%s'.", minhowto);

    mxFree(minhowto);

    ++prhs;
    --nrhs;
  }
  else
    mintype=MIN_UNCONSTRAINED;

  if(mintype==MIN_UNCONSTRAINED) goto extraargs;

  /* arguments below this point are optional and their presence depends
   * upon the minimization type determined above
   */
  /** lb, ub **/
  if(nrhs>=7 && (mintype==MIN_CONSTRAINED_BC || mintype==MIN_CONSTRAINED_BLEC || mintype==MIN_CONSTRAINED_BLIC || mintype==MIN_CONSTRAINED_BLEIC)){
    /* check if the next two arguments are real row or column vectors */
    if(mxIsDouble(prhs[5]) && !mxIsComplex(prhs[5]) && (mxGetM(prhs[5])==1 || mxGetN(prhs[5])==1)){
      if(mxIsDouble(prhs[6]) && !mxIsComplex(prhs[6]) && (mxGetM(prhs[6])==1 || mxGetN(prhs[6])==1)){
        if((i=__MAX__(mxGetM(prhs[5]), mxGetN(prhs[5])))!=m)
          matlabFmtdErrMsgTxt("levmar: lb must have %d elements, got %d.", m, i);
        if((i=__MAX__(mxGetM(prhs[6]), mxGetN(prhs[6])))!=m)
          matlabFmtdErrMsgTxt("levmar: ub must have %d elements, got %d.", m, i);

        lb=mxGetPr(prhs[5]);
        ub=mxGetPr(prhs[6]);

        prhs+=2;
        nrhs-=2;
      }
    }
  }

  /** A, b **/
  if(nrhs>=7 && (mintype==MIN_CONSTRAINED_LEC || mintype==MIN_CONSTRAINED_BLEC || mintype==MIN_CONSTRAINED_LEIC || mintype==MIN_CONSTRAINED_BLEIC)){
    /* check if the next two arguments are a real matrix and a real row or column vector */
    if(mxIsDouble(prhs[5]) && !mxIsComplex(prhs[5]) && mxGetM(prhs[5])>=1 && mxGetN(prhs[5])>=1){
      if(mxIsDouble(prhs[6]) && !mxIsComplex(prhs[6]) && (mxGetM(prhs[6])==1 || mxGetN(prhs[6])==1)){
        if((i=mxGetN(prhs[5]))!=m)
          matlabFmtdErrMsgTxt("levmar: A must have %d columns, got %d.", m, i);
        if((i=__MAX__(mxGetM(prhs[6]), mxGetN(prhs[6])))!=(Arows=mxGetM(prhs[5])))
          matlabFmtdErrMsgTxt("levmar: b must have %d elements, got %d.", Arows, i);

        At=prhs[5];
        b=mxGetPr(prhs[6]);
        A=getTranspose(At);

        prhs+=2;
        nrhs-=2;
      }
    }
  }

  /* wghts */
  /* check if we have a weights vector */
  if(nrhs>=6 && mintype==MIN_CONSTRAINED_BLEC){ /* only check if we have seen both box & linear constraints */
    if(mxIsDouble(prhs[5]) && !mxIsComplex(prhs[5]) && (mxGetM(prhs[5])==1 || mxGetN(prhs[5])==1)){
      if(__MAX__(mxGetM(prhs[5]), mxGetN(prhs[5]))==m){
        wghts=mxGetPr(prhs[5]);

        ++prhs;
        --nrhs;
      }
    }
  }

  /** C, d **/
  if(nrhs>=7 && (mintype==MIN_CONSTRAINED_BLEIC || mintype==MIN_CONSTRAINED_BLIC || mintype==MIN_CONSTRAINED_LEIC || mintype==MIN_CONSTRAINED_LIC)){
    /* check if the next two arguments are a real matrix and a real row or column vector */
    if(mxIsDouble(prhs[5]) && !mxIsComplex(prhs[5]) && mxGetM(prhs[5])>=1 && mxGetN(prhs[5])>=1){
      if(mxIsDouble(prhs[6]) && !mxIsComplex(prhs[6]) && (mxGetM(prhs[6])==1 || mxGetN(prhs[6])==1)){
        if((i=mxGetN(prhs[5]))!=m)
          matlabFmtdErrMsgTxt("levmar: C must have %d columns, got %d.", m, i);
        if((i=__MAX__(mxGetM(prhs[6]), mxGetN(prhs[6])))!=(Crows=mxGetM(prhs[5])))
          matlabFmtdErrMsgTxt("levmar: d must have %d elements, got %d.", Crows, i);

        Ct=prhs[5];
        d=mxGetPr(prhs[6]);
        C=getTranspose(Ct);

        prhs+=2;
        nrhs-=2;
      }
    }
  }

  /* arguments below this point are assumed to be extra arguments passed
   * to every invocation of the fitting function and its Jacobian
   */

extraargs:
  /* handle any extra args and allocate memory for
   * passing the current parameter estimate to matlab
   */
  nextra=nrhs-5;
  mdata.nrhs=nextra+1;
  mdata.rhs=(mxArray **)mxMalloc(mdata.nrhs*sizeof(mxArray *));
  for(i=0; i<nextra; ++i)
    mdata.rhs[i+1]=(mxArray *)prhs[nrhs-nextra+i]; /* discard 'const' modifier */
#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: %d extra args\n", nextra);
#endif /* DEBUG */

  if(mdata.isrow_p0){ /* row vector */
    mdata.rhs[0]=mxCreateDoubleMatrix(1, m, mxREAL);
    /*
    mxSetM(mdata.rhs[0], 1);
    mxSetN(mdata.rhs[0], m);
    */
  }
  else{ /* column vector */
    mdata.rhs[0]=mxCreateDoubleMatrix(m, 1, mxREAL);
    /*
    mxSetM(mdata.rhs[0], m);
    mxSetN(mdata.rhs[0], 1);
    */
  }

  /* ensure that the supplied function & Jacobian are as expected */
  if(checkFuncAndJacobian(p, m, n, havejac, &mdata)){
    status=LM_ERROR;
    goto cleanup;
  }

  if(nlhs>3) /* covariance output required */
    covar=mxMalloc(m*m*sizeof(double));

  /* invoke levmar */
  switch(mintype){
    case MIN_UNCONSTRAINED: /* no constraints */
      if(havejac)
        status=dlevmar_der(func, jacfunc, p, x, m, n, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_dif(func,          p, x, m, n, itmax, opts, info, NULL, covar, (void *)&mdata);
#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_der()/dlevmar_dif()\n");
#endif /* DEBUG */
    break;
    case MIN_CONSTRAINED_BC: /* box constraints */
      if(havejac)
        status=dlevmar_bc_der(func, jacfunc, p, x, m, n, lb, ub, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_bc_dif(func,          p, x, m, n, lb, ub, itmax, opts, info, NULL, covar, (void *)&mdata);
#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_bc_der()/dlevmar_bc_dif()\n");
#endif /* DEBUG */
    break;
    case MIN_CONSTRAINED_LEC:  /* linear equation constraints */
#ifdef HAVE_LAPACK
      if(havejac)
        status=dlevmar_lec_der(func, jacfunc, p, x, m, n, A, b, Arows, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_lec_dif(func,          p, x, m, n, A, b, Arows, itmax, opts, info, NULL, covar, (void *)&mdata);
#else
      mexErrMsgTxt("levmar: no linear constraints support, HAVE_LAPACK was not defined during MEX-file compilation.");
#endif /* HAVE_LAPACK */

#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_lec_der()/dlevmar_lec_dif()\n");
#endif /* DEBUG */
    break;
    case MIN_CONSTRAINED_BLEC: /* box & linear equation constraints */
#ifdef HAVE_LAPACK
      if(havejac)
        status=dlevmar_blec_der(func, jacfunc, p, x, m, n, lb, ub, A, b, Arows, wghts, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_blec_dif(func,          p, x, m, n, lb, ub, A, b, Arows, wghts, itmax, opts, info, NULL, covar, (void *)&mdata);
#else
      mexErrMsgTxt("levmar: no box & linear constraints support, HAVE_LAPACK was not defined during MEX-file compilation.");
#endif /* HAVE_LAPACK */

#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_blec_der()/dlevmar_blec_dif()\n");
#endif /* DEBUG */
    break;
    case MIN_CONSTRAINED_BLEIC: /* box, linear equation & inequalities constraints */
#ifdef HAVE_LAPACK
      if(havejac)
        status=dlevmar_bleic_der(func, jacfunc, p, x, m, n, lb, ub, A, b, Arows, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_bleic_dif(func, p, x, m, n, lb, ub, A, b, Arows, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
#else
      mexErrMsgTxt("levmar: no box, linear equation & inequality constraints support, HAVE_LAPACK was not defined during MEX-file compilation.");
#endif /* HAVE_LAPACK */

#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_bleic_der()/dlevmar_bleic_dif()\n");
#endif /* DEBUG */
    break;
    case MIN_CONSTRAINED_BLIC: /* box, linear inequalities constraints */
#ifdef HAVE_LAPACK
      if(havejac)
        status=dlevmar_bleic_der(func, jacfunc, p, x, m, n, lb, ub, NULL, NULL, 0, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_bleic_dif(func, p, x, m, n, lb, ub, NULL, NULL, 0, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
#else
      mexErrMsgTxt("levmar: no box & linear inequality constraints support, HAVE_LAPACK was not defined during MEX-file compilation.");
#endif /* HAVE_LAPACK */

#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_blic_der()/dlevmar_blic_dif()\n");
#endif /* DEBUG */
    break;
    case MIN_CONSTRAINED_LEIC: /* linear equation & inequalities constraints */
#ifdef HAVE_LAPACK
      if(havejac)
        status=dlevmar_bleic_der(func, jacfunc, p, x, m, n, NULL, NULL, A, b, Arows, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_bleic_dif(func, p, x, m, n, NULL, NULL, A, b, Arows, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
#else
      mexErrMsgTxt("levmar: no linear equation & inequality constraints support, HAVE_LAPACK was not defined during MEX-file compilation.");
#endif /* HAVE_LAPACK */

#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_leic_der()/dlevmar_leic_dif()\n");
#endif /* DEBUG */
    break;
    case MIN_CONSTRAINED_LIC: /* linear inequalities constraints */
#ifdef HAVE_LAPACK
      if(havejac)
        status=dlevmar_bleic_der(func, jacfunc, p, x, m, n, NULL, NULL, NULL, NULL, 0, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
      else
        status=dlevmar_bleic_dif(func, p, x, m, n, NULL, NULL, NULL, NULL, 0, C, d, Crows, itmax, opts, info, NULL, covar, (void *)&mdata);
#else
      mexErrMsgTxt("levmar: no linear equation & inequality constraints support, HAVE_LAPACK was not defined during MEX-file compilation.");
#endif /* HAVE_LAPACK */

#ifdef DEBUG
  fflush(stderr);
  fprintf(stderr, "LEVMAR: calling dlevmar_lic_der()/dlevmar_lic_dif()\n");
#endif /* DEBUG */
    break;
    default:
      mexErrMsgTxt("levmar: unexpected internal error.");
  }

#ifdef DEBUG
  fflush(stderr);
  printf("LEVMAR: minimization returned %d in %g iter, reason %g\n\tSolution: ", status, info[5], info[6]);
  for(i=0; i<m; ++i)
    printf("%.7g ", p[i]);
  printf("\n\n\tMinimization info:\n\t");
  for(i=0; i<LM_INFO_SZ; ++i)
    printf("%g ", info[i]);
  printf("\n");
#endif /* DEBUG */

  /* copy back return results */
  /** ret **/
  plhs[0]=mxCreateDoubleMatrix(1, 1, mxREAL);
  ret=mxGetPr(plhs[0]);
  ret[0]=(double)status;

  /** popt **/
  plhs[1]=(mdata.isrow_p0==1)? mxCreateDoubleMatrix(1, m, mxREAL) : mxCreateDoubleMatrix(m, 1, mxREAL);
  pdbl=mxGetPr(plhs[1]);
  for(i=0; i<m; ++i)
    pdbl[i]=p[i];

  /** info **/
  if(nlhs>2){
    plhs[2]=mxCreateDoubleMatrix(1, LM_INFO_SZ, mxREAL);
    pdbl=mxGetPr(plhs[2]);
    for(i=0; i<LM_INFO_SZ; ++i)
      pdbl[i]=info[i];
  }

  /** covar **/
  if(nlhs>3){
    plhs[3]=mxCreateDoubleMatrix(m, m, mxREAL);
    pdbl=mxGetPr(plhs[3]);
    for(i=0; i<m*m; ++i) /* covariance matrices are symmetric, thus no need to transpose! */
      pdbl[i]=covar[i];
  }

cleanup:
  /* cleanup */
  mxDestroyArray(mdata.rhs[0]);
  if(A) mxFree(A);
  if(C) mxFree(C);

  mxFree(mdata.fname);
  if(havejac) mxFree(mdata.jacname);
  mxFree(p);
  mxFree(mdata.rhs);
  if(covar) mxFree(covar);

  if(status==LM_ERROR)
    mexWarnMsgTxt("levmar: optimization returned with an error!");
}
示例#30
0
void
mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    MatlabCPPInitialize(false);

    // Check for proper number of arguments
    if ( (nrhs < NR_IN) || (nrhs > NR_IN + NR_IN_OPT) || \
            (nlhs < NR_OUT) || (nlhs > NR_OUT + NR_OUT_OPT) ) {
        mexErrMsgTxt("Wrong number of arguments.");
    }

    // fetch the input (we support matrices and cell arrays)
    std::vector< Eigen::VectorXd > theta_unary;
    std::vector< Eigen::VectorXd > theta_pair;

    if (!mxIsCell(THETA_UNARY_IN)) {
        GetMatlabPotentialFromMatrix(THETA_UNARY_IN, theta_unary);
        GetMatlabPotentialFromMatrix(THETA_PAIR_IN, theta_pair);
    }
    else {
        GetMatlabPotential(THETA_UNARY_IN, theta_unary);
        GetMatlabPotential(THETA_PAIR_IN, theta_pair);
    }
    
    Eigen::MatrixXi edges;
    GetMatlabMatrix(EDGES_IN, edges);

    // decomposition: cell array of edge index vectors
    std::vector< std::vector<size_t> > decomposition;
    if (nrhs >= 5) {
        size_t num = mxGetNumberOfElements(DECOMPOSITION_IN);
        decomposition.resize(num);
        for (size_t d_idx=0; d_idx<num; d_idx++) {
            const mxArray* v = mxGetCell(DECOMPOSITION_IN, d_idx);
            size_t num_edges = mxGetM(v);
            decomposition[d_idx].resize(num_edges);
	        const double* ptr = mxGetPr(v);
            for (size_t e_idx=0; e_idx<num_edges; e_idx++) {
                decomposition[d_idx][e_idx] = static_cast<size_t>(ptr[e_idx]);
            }
        }
    }
    
    // parse options
    MexLPQPOptions options;
    if (nrhs >= 4) {
        bool opts_parsed = options.parse(OPTIONS_IN);
        if (!opts_parsed) {
            MatlabCPPExit();
            return;
        }
    }

    LPQP* lpqp;
    if (nrhs < 5) {
        lpqp = new LPQPNPBP(theta_unary, theta_pair, edges);
    }
    else {
        lpqp = new LPQPSDD(theta_unary, theta_pair, edges, decomposition, options.solver_sdd);
    }

    lpqp->setRhoStart(options.rho_start);
    lpqp->setRhoEnd(options.rho_end);
    lpqp->setEpsilonEntropy(options.eps_entropy);
    lpqp->setEpsilonKullbackLeibler(options.eps_dkl);
    lpqp->setEpsilonObjective(options.eps_obj);
    lpqp->setEpsilonMP(options.eps_mp);
    lpqp->setMaximumNumberOfIterationsDC(options.num_max_iter_dc);
    lpqp->setMaximumNumberOfIterationsMP(options.num_max_iter_mp);
    lpqp->setRhoScheduleConstant(options.rho_schedule_constant);
    lpqp->setInitialLPActive(options.initial_lp_active);
    lpqp->setInitialLPImprovmentRatio(options.initial_lp_improvement_ratio);
    lpqp->setInitialLPRhoStart(options.initial_lp_rho_start);
    lpqp->setInitialRhoSimilarValues(options.initial_rho_similar_values);
    lpqp->setInitialRhoFactorKLSmaller(options.initial_rho_factor_kl_smaller);
    lpqp->setSkipIfIncrease(options.skip_if_increase);

    lpqp->run();
    
    if (options.do_round) {
        double curr_qp_obj = lpqp->computeQPValue();

        lpqp->roundSolution();

        double qp_obj_after_rounding = lpqp->computeQPValue();
        printf("QP objective before rounding: %f after rounding: %f\n",curr_qp_obj, qp_obj_after_rounding);
    }

    // return marginals (if input was provided as a matrix, also return
    // marginals in a matrix)
    std::vector< Eigen::VectorXd >& mu_unary = lpqp->getUnaryMarginals();
    if (!mxIsCell(THETA_UNARY_IN)) {
        size_t num_states = mxGetM(THETA_UNARY_IN);
        size_t num_vars = mxGetN(THETA_UNARY_IN);
        MARGINALS_UNARY_OUT = mxCreateNumericMatrix(
                                num_states, 
                                num_vars,
                                mxDOUBLE_CLASS, mxREAL);
        double* mu_res_p = mxGetPr(MARGINALS_UNARY_OUT);
        for (size_t v_idx=0; v_idx<mu_unary.size(); v_idx++) {
            for (size_t idx=0; idx<mu_unary[v_idx].size(); idx++) {
                mu_res_p[v_idx*num_states+idx] = mu_unary[v_idx](idx);
            }
        }
    }
    else {
        mwSize dim_0 = static_cast<mwSize>(mu_unary.size());
        MARGINALS_UNARY_OUT = mxCreateCellArray(1, &dim_0);
        for (size_t v_idx=0; v_idx<mu_unary.size(); v_idx++) {
            mxArray* m = mxCreateNumericMatrix(
                            static_cast<int>(mu_unary[v_idx].size()),
                            1,
                            mxDOUBLE_CLASS, mxREAL);
            double* mu_res_p = mxGetPr(m);
            for (size_t idx=0; idx<mu_unary[v_idx].size(); idx++) {
                mu_res_p[idx] = mu_unary[v_idx](idx);
            }

            mxSetCell(MARGINALS_UNARY_OUT, v_idx, m);
        }
    }
    
    // return history
    if (nlhs > 1) {
        std::vector<double>& history_obj = lpqp->getHistoryObjective();
        std::vector<double>& history_obj_qp = lpqp->getHistoryObjectiveQP();
        std::vector<double>& history_obj_lp = lpqp->getHistoryObjectiveLP();
        std::vector<double>& history_obj_decoded = lpqp->getHistoryObjectiveDecoded();
        std::vector<size_t>& history_iteration = lpqp->getHistoryIteration();
        std::vector<double>& history_rho = lpqp->getHistoryRho();
        //std::vector< Eigen::VectorXi > history_decoded = lpqp.getHistoryDecoded();

        //const char *field_names[] = {"obj", "obj_qp", "obj_lp", "obj_decoded", "iteration", "beta", "decoded"};
        const char *field_names[] = {"obj", "obj_qp", "obj_lp", "obj_decoded", "iteration", "rho"};
        mwSize dims[2];
        dims[0] = 1;
        dims[1] = history_obj.size();
        HISTORY_OUT = mxCreateStructArray(2, dims, sizeof(field_names)/sizeof(*field_names), field_names);

        int field_obj, field_obj_qp, field_obj_lp, field_obj_decoded, field_iteration, field_rho;
        //int field_decoded;
        field_obj = mxGetFieldNumber(HISTORY_OUT, "obj");
        field_obj_qp = mxGetFieldNumber(HISTORY_OUT, "obj_qp");
        field_obj_lp = mxGetFieldNumber(HISTORY_OUT, "obj_lp");
        field_obj_decoded = mxGetFieldNumber(HISTORY_OUT, "obj_decoded");
        field_iteration = mxGetFieldNumber(HISTORY_OUT, "iteration");
        field_rho = mxGetFieldNumber(HISTORY_OUT, "rho");
        //field_decoded = mxGetFieldNumber(HISTORY_OUT, "decoded");

        for (size_t i=0; i<history_obj.size(); i++) {
            mxArray *field_value;

            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj_qp[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj_qp, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj_lp[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj_lp, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_obj_decoded[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_obj_decoded, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = static_cast<double>(history_iteration[i]);
            mxSetFieldByNumber(HISTORY_OUT, i, field_iteration, field_value);
            
            field_value = mxCreateDoubleMatrix(1,1,mxREAL);
            *mxGetPr(field_value) = history_rho[i];
            mxSetFieldByNumber(HISTORY_OUT, i, field_rho, field_value);
            
            //if (options.with_decoded_history) {
            //    field_value = mxCreateDoubleMatrix(history_decoded[i].size(),1,mxREAL);
            //    double* decoded_res_p = mxGetPr(field_value);
            //    for (size_t idx=0; idx<history_decoded[i].size(); idx++) {
            //        decoded_res_p[idx] = static_cast<double>(history_decoded[i][idx]);
            //    }
            //    mxSetFieldByNumber(HISTORY_OUT, i, field_decoded, field_value);
            //}
        }
    }

    delete lpqp;

    MatlabCPPExit();
}