//-----------------------------------------------------------------------------------------
astra::CFloat32Data3DMemory *
allocateDataObject(const std::string & sDataType,
		const mxArray * const geometry, const mxArray * const data,
		const mxArray * const unshare, const mxArray * const zIndex)
{
	astra::CFloat32Data3DMemory* pDataObject3D = NULL;

	bool bUnshare = true;
	if (unshare)
	{
		if (!mexIsScalar(unshare))
		{
			mexErrMsgTxt("Argument 5 (read-only) must be scalar");
			return NULL;
		}
		// unshare the array if we're not linking read-only
		bUnshare = !(bool)mxGetScalar(unshare);
	}

	mwIndex iZ = 0;
	if (zIndex)
	{
		if (!mexIsScalar(zIndex))
		{
			mexErrMsgTxt("Argument 6 (Z) must be scalar");
			return NULL;
		}
		iZ = (mwSignedIndex)mxGetScalar(zIndex);
	}

	// SWITCH DataType
	if (sDataType == "-vol")
	{
		// Read geometry
		astra::Config* cfg = structToConfig("VolumeGeometry3D", geometry);
		astra::CVolumeGeometry3D* pGeometry = new astra::CVolumeGeometry3D();
		if (!pGeometry->initialize(*cfg))
		{
			mexErrMsgTxt("Geometry class not initialized. \n");
			delete pGeometry;
			delete cfg;
			return NULL;
		}
		delete cfg;

		// If data is specified, check dimensions
		if (data && !mexIsScalar(data))
		{
			if (! (zIndex
					? checkDataSize(data, pGeometry, iZ)
					: checkDataSize(data, pGeometry)) )
			{
				mexErrMsgTxt("The dimensions of the data do not match those specified in the geometry. \n");
				delete pGeometry;
				return NULL;
			}
		}

		// Initialize data object
#ifdef USE_MATLAB_UNDOCUMENTED
		if (unshare) {
			CFloat32CustomMemoryMatlab3D* pHandle =
					new CFloat32CustomMemoryMatlab3D(data, bUnshare, iZ);

			// Initialize data object
			pDataObject3D = new astra::CFloat32VolumeData3DMemory(pGeometry, pHandle);
		}
		else
		{
			pDataObject3D = new astra::CFloat32VolumeData3DMemory(pGeometry);
		}
#else
		pDataObject3D = new astra::CFloat32VolumeData3DMemory(pGeometry);
#endif
		delete pGeometry;
	}
	else if (sDataType == "-sino" || sDataType == "-proj3d" || sDataType == "-sinocone")
	{
		// Read geometry
		astra::Config* cfg = structToConfig("ProjectionGeometry3D", geometry);
		// FIXME: Change how the base class is created. (This is duplicated
		// in Projector3D.cpp.)
		std::string type = cfg->self->getAttribute("type");
		astra::CProjectionGeometry3D* pGeometry = 0;
		if (type == "parallel3d") {
			pGeometry = new astra::CParallelProjectionGeometry3D();
		} else if (type == "parallel3d_vec") {
			pGeometry = new astra::CParallelVecProjectionGeometry3D();
		} else if (type == "cone") {
			pGeometry = new astra::CConeProjectionGeometry3D();
		} else if (type == "cone_vec") {
			pGeometry = new astra::CConeVecProjectionGeometry3D();
		} else {
			mexErrMsgTxt("Invalid geometry type.\n");
			return NULL;
		}

		if (!pGeometry->initialize(*cfg)) {
			mexErrMsgTxt("Geometry class not initialized. \n");
			delete pGeometry;
			delete cfg;
			return NULL;
		}
		delete cfg;

		// If data is specified, check dimensions
		if (data && !mexIsScalar(data))
		{
			if (! (zIndex
					? checkDataSize(data, pGeometry, iZ)
					: checkDataSize(data, pGeometry)) )
			{
				mexErrMsgTxt("The dimensions of the data do not match those specified in the geometry. \n");
				delete pGeometry;
				return NULL;
			}
		}

		// Initialize data object
#ifdef USE_MATLAB_UNDOCUMENTED
		if (unshare)
		{
			CFloat32CustomMemoryMatlab3D* pHandle =
					new CFloat32CustomMemoryMatlab3D(data, bUnshare, iZ);

			// Initialize data object
			pDataObject3D = new astra::CFloat32ProjectionData3DMemory(pGeometry, pHandle);
		}
		else
		{
			pDataObject3D = new astra::CFloat32ProjectionData3DMemory(pGeometry);
		}
#else
		pDataObject3D = new astra::CFloat32ProjectionData3DMemory(pGeometry);
#endif
		delete pGeometry;
	}
	else
	{
		mexErrMsgTxt("Invalid datatype.  Please specify '-vol' or '-proj3d'. \n");
		return NULL;
	}

	// Check initialization
	if (!pDataObject3D->isInitialized())
	{
		mexErrMsgTxt("Couldn't initialize data object.\n");
		delete pDataObject3D;
		return NULL;
	}

	return pDataObject3D;
}
void mexFunction(int nlhs, mxArray *out[], int nrhs, const mxArray *input[])
{
    // Checking number of arguments
    if(nlhs > 3){
        mexErrMsgTxt("Function has three return values");
        return;
    }

    if(nrhs != 4){
        mexErrMsgTxt("Usage: mexFelzenSegment(UINT8 im, double sigma, double c, int minSize)");
        return;
    }

    if(!mxIsClass(input[0], "uint8")){
        mexErrMsgTxt("Only image arrays of the UINT8 class are allowed.");
        return;
    }

    // Load in arrays and parameters
    UInt8* matIm = (UInt8*) mxGetPr(input[0]);
    int nrDims = (int) mxGetNumberOfDimensions(input[0]);
    int* dims = (int*) mxGetDimensions(input[0]);
    double* sigma = mxGetPr(input[1]);
    double* c = mxGetPr(input[2]);
    double* minSize = mxGetPr(input[3]);
    int min_size = (int) *minSize;

    int height = dims[0];
    int width = dims[1];
    int imSize = height * width;
    
    // Convert to image. 
    int idx;
    image<rgb>* theIm = new image<rgb>(width, height);
    for (int x = 0; x < width; x++){
        for (int y = 0; y < height; y++){
            idx = x * height + y;
            imRef(theIm, x, y).r = matIm[idx];
            imRef(theIm, x, y).g = matIm[idx + imSize];
            imRef(theIm, x, y).b = matIm[idx + 2 * imSize];
        }
    }

    // KOEN: Disable randomness of the algorithm
    srand(12345);

    // Call Felzenswalb segmentation algorithm
    int num_css;
    //image<rgb>* segIm = segment_image(theIm, *sigma, *c, min_size, &num_css);
    double* segIndices = segment_image_index(theIm, *sigma, *c, min_size, &num_css);
    //mexPrintf("numCss: %d\n", num_css);

    // The segmentation index image
    out[0] = mxCreateDoubleMatrix(dims[0], dims[1], mxREAL);
    double* outSegInd = mxGetPr(out[0]);

    // Keep track of minimum and maximum of each blob
    out[1] = mxCreateDoubleMatrix(num_css, 4, mxREAL);
    double* minmax = mxGetPr(out[1]);
    for (int i=0; i < num_css; i++)
        minmax[i] = dims[0];
    for (int i= num_css; i < 2 * num_css; i++)
        minmax[i] = dims[1];

    // Keep track of neighbouring blobs using square matrix
    out[2] = mxCreateDoubleMatrix(num_css, num_css, mxREAL);
    double* nn = mxGetPr(out[2]);

    // Copy the contents of segIndices
    // Keep track of neighbours
    // Get minimum and maximum
    // These actually comprise of the bounding boxes
    double currDouble;
    int mprev, curr, prevHori, mcurr;
    for(int x = 0; x < width; x++){
        mprev = segIndices[x * height]-1;
        for(int y=0; y < height; y++){
            //mexPrintf("x: %d y: %d\n", x, y);
            idx = x * height + y;
            //mexPrintf("idx: %d\n", idx);
            //currDouble = segIndices[idx]; 
            //mexPrintf("currDouble: %d\n", currDouble);
            curr = segIndices[idx]; 
            //mexPrintf("curr: %d\n", curr);
            outSegInd[idx] = curr; // copy contents
            //mexPrintf("outSegInd: %f\n", outSegInd[idx]);
            mcurr = curr-1;

            // Get neighbours (vertical)
            //mexPrintf("idx: %d", curr * num_css + mprev);
            //mexPrintf(" %d\n", curr + num_css * mprev);
            //mexPrintf("mprev: %d\n", mprev);
            nn[(mcurr) * num_css + mprev] = 1;
            nn[(mcurr) + num_css * mprev] = 1;

            // Get horizontal neighbours
            //mexPrintf("Get horizontal neighbours\n");
            if (x > 0){
                prevHori = outSegInd[(x-1) * height + y] - 1;
                nn[mcurr * num_css + prevHori] = 1;
                nn[mcurr + num_css * prevHori] = 1;
            }

            // Keep track of min and maximum index of blobs
            //mexPrintf("Keep track of min and maximum index\n");
            if (minmax[mcurr] > y)
                minmax[mcurr] = y;
            if (minmax[mcurr + num_css] > x)
                minmax[mcurr + num_css] = x;
            if (minmax[mcurr + 2 * num_css] < y)
                minmax[mcurr + 2 * num_css] = y;
            if (minmax[mcurr + 3 * num_css] < x)
                minmax[mcurr + 3 * num_css] = x;

            //mexPrintf("Mprev = mcurr");
            mprev = mcurr;
        }
    }

    // Do minmax plus one for Matlab
    for (int i=0; i < 4 * num_css; i++)
        minmax[i] += 1;

    delete theIm;
    delete [] segIndices;

    return;
}
Ejemplo n.º 3
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

  // Check output argument
  if (nlhs != 1) {
    mexErrMsgTxt("Expecting one output argument.");
    return;
  }

  // Check input arguments
  if (nrhs < 2) {
    mexErrMsgTxt("Expecting at least two input arguments.");
    return;
  }

  // Check if input matrix and rhs are double precision
  if (!mxIsDouble(prhs[0]) || !mxIsSparse(prhs[0])) {
    mexErrMsgTxt("Expecting sparse matrix in double precision.");
    return;
  }

  if (!mxIsDouble(prhs[1])) {
    mexErrMsgTxt("Expecting rhs in double precision.");
    return;
  }

  double tol     = 1e-6;
  mwSize maxIter = 10000;

  if (nrhs > 2) tol     = mxGetScalar(prhs[2]);
  if (nrhs > 3) maxIter = mxGetScalar(prhs[3]);

  // Get matrix arrays
  mwIndex *mw_row     = mxGetIr(prhs[0]);
  mwIndex *mw_col_ptr = mxGetJc(prhs[0]);
  double  *mw_val     = mxGetPr(prhs[0]);

  // Get matrix sizes
  int nrow = int(mxGetN(prhs[0]));
  int ncol = int(mxGetM(prhs[0]));
  int nnz  = int(mw_col_ptr[nrow]);

  int *row = NULL;
  int *col_ptr = NULL;
  double *val = NULL;
  paralution::allocate_host(nnz, &val);
  paralution::allocate_host(nnz, &row);
  paralution::allocate_host(nrow+1, &col_ptr);

  // copy needed due to diff types
  for (int i=0; i<nnz; ++i) {
    row[i] = mw_row[i];
    val[i] = mw_val[i];
  }

  for (int i=0; i<nrow+1; ++i)
    col_ptr[i] = mw_col_ptr[i];

  // Get rhs
  double  *mw_rhs = mxGetPr(prhs[1]);
  double  *rhs = NULL;

  paralution::allocate_host(nrow, &rhs);

  for (int i=0; i<nrow; ++i)
    rhs[i] = mw_rhs[i];

  // Allocate output vector
  plhs[0] = mxCreateDoubleMatrix(nrow, 1, mxREAL);
  double  *sol = mxGetPr(plhs[0]);

  /*
  // Time measurement
  double tick, tack;
  tick = paralution::paralution_time();
  */

  // Initialize PARALUTION
  paralution::init_paralution();

  // Create PARALUTION data structures
  paralution::LocalMatrix<double> A;
  paralution::LocalVector<double> b;
  paralution::LocalVector<double> x;

  // Fill PARALUTION data
  // For symmetric matrices CSC == CSR
  A.SetDataPtrCSR(&col_ptr, &row, &val, "A", nnz, ncol, nrow);
  b.SetDataPtr(&rhs, "b", ncol);
  x.Allocate("x", nrow);

  // Solver
  paralution::CG<paralution::LocalMatrix<double>, paralution::LocalVector<double>, double> ls;
  // Preconditioner
  //  paralution::MultiColoredILU<paralution::LocalMatrix<double>, paralution::LocalVector<double>, double> p;
  paralution::Jacobi<paralution::LocalMatrix<double>, paralution::LocalVector<double>, double> p;

  ls.SetOperator(A);
  ls.SetPreconditioner(p);
  ls.Init(0.0, tol, 1e8, maxIter);

  // Build solver and preconditioner
  ls.Build();

  ls.MoveToAccelerator();
  A.MoveToAccelerator();
  b.MoveToAccelerator();
  x.MoveToAccelerator();

  x.Zeros();

  // Disable PARALUTION printing
  //ls.Verbose(0);

  // Verbose printing
  ls.Verbose(1);
  A.info();

  /*
  tack = paralution::paralution_time();
  std::cout << "PARALUTION::Building time: " << (tack-tick)/1000000. << "sec.\n";
  tick = paralution::paralution_time();
  */

  // Solve Ax=b
  ls.Solve(b, &x);

  /*
  tack = paralution::paralution_time();
  std::cout << "PARALUTION::Solving time: " << (tack-tick)/1000000. << "sec.\n";
  */

  ls.Clear();
  A.Clear();
  b.Clear();

  double *ptr_sol = NULL;
  x.MoveToHost();
  x.LeaveDataPtr(&ptr_sol);

  for (int i=0; i<nrow; ++i)
    sol[i] = ptr_sol[i];

  paralution::free_host(&ptr_sol);

  paralution::stop_paralution();

  return;

}
Ejemplo n.º 4
0
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
  double *x, *h,  *yl, *yh, *Lr;
  intptr_t m, n, mh, nh, h_col, h_row, lh, i, j, L;
  double mtest, ntest;

  /* check for correct # of input variables */
  if (nrhs>4){
    mexErrMsgTxt("There are at most 4 input parameters allowed!");
    return;
  }
  if (nrhs<3){
    mexErrMsgTxt("There are at least 3 input parameters required!");
    return;
  }
  yl = mxGetPr(prhs[0]);
  n = mxGetN(prhs[0]); 
  m = mxGetM(prhs[0]); 
  yh = mxGetPr(prhs[1]);
  nh = mxGetN(prhs[1]); 
  mh = mxGetM(prhs[1]); 
  h = mxGetPr(prhs[2]);
  h_col = mxGetN(prhs[2]); 
  h_row = mxGetM(prhs[2]); 
  if (h_col>h_row)
    lh = h_col;
  else  
    lh = h_row;
  if (nrhs == 4){
    L = (intptr_t) *mxGetPr(prhs[3]);
    if (L < 0)
      mexErrMsgTxt("The number of levels, L, must be a non-negative integer");
  }
  else /* Estimate L */ {
    i=n;j=0;
    while (even(i)){
      i=(i>>1);
      j++;
    }
    L=m;i=0;
    while (even(L)){
      L=(L>>1);
      i++;
    }
    if(min(m,n) == 1)
      L = max(i,j);
    else
      L = min(i,j);
    if (L==0){
      mexErrMsgTxt("Maximum number of levels is zero; no decomposition can be performed!");
      return;
    }
  }
  /* check for consistency of rows and columns of yl, yh */
  if (min(m,n) > 1){
    if((m != mh) | (3*n*L != nh)){
      mexErrMsgTxt("Dimensions of first two input matrices not consistent!");
      return;
    }
  }
  else{
    if((m != mh) | (n*L != nh)){
      mexErrMsgTxt("Dimensions of first two input vectors not consistent!");{
	return;
      }
    }
  }
  /* Check the ROW dimension of input */
  if(m > 1){
    mtest = (double) m/pow(2.0, (double) L);
    if (!isint(mtest))
      mexErrMsgTxt("The matrix row dimension must be of size m*2^(L)");
  }
  /* Check the COLUMN dimension of input */
  if(n > 1){
    ntest = (double) n/pow(2.0, (double) L);
    if (!isint(ntest))
      mexErrMsgTxt("The matrix column dimension must be of size n*2^(L)");
  }
  plhs[0] = mxCreateDoubleMatrix(m,n,mxREAL);
  x = mxGetPr(plhs[0]);
  if (nrhs < 4){
      plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
      Lr = mxGetPr(plhs[1]);
      *Lr = L;
  }
  MIRDWT(x, m, n, h, lh, L, yl, yh);
}
Ejemplo n.º 5
0
void compute(int nlhs, mxArray  *plhs[], int nrhs, const mxArray  *prhs[], const int atria_preprocessing_given,  METRIC dummy)
{ 
	long i,j,n,k;		/* loop variables */ 

	/* handle matrix I/O */
	
	const long N = mxGetM(prhs[0]);	
	const long dim = mxGetN(prhs[0]);
	const double* p  	= (double *)mxGetPr(prhs[0]);
	
	const long R = max(mxGetM(prhs[1]), mxGetN(prhs[1]));
	const double* ref 	= (double *)mxGetPr(prhs[1]);
	
	const double  relative_range = (double) *((double *)mxGetPr(prhs[2]));
	const long past	= (long) *((double *)mxGetPr(prhs[3]));
	
	if (N < 1) {
		mexErrMsgTxt("Data set must consist of at least two points (row vectors)");
		return;
	}		
	if (dim < 2) {
		mexErrMsgTxt("Data points must be at least of dimension two");
		return;
	}		
	if ((mxGetN(prhs[1]) == 0) || (mxGetM(prhs[1]) == 0)) {
		mexErrMsgTxt("Wrong reference indices given");
		return;
	}	
		
	if (R < 1) {
		mexErrMsgTxt("At least one reference index or point must be given");
		return;
	}	

	for (i=0; i < R; i++) {
		if ((ref[i] < 1) || (ref[i]>N)) {
			mexErrMsgTxt("Reference indices out of range");
			return;
		}	
	}
	
	point_set<METRIC> points(N,dim, p);	
	ATRIA< point_set<METRIC> >* searcher = 0;	

#ifdef MATLAB_MEX_FILE	
	if (atria_preprocessing_given) {
		searcher = new ATRIA< point_set<METRIC> >(points, prhs[-1]);	// this constructor used the data from the preprocessing 
		if (searcher->geterr()) {
			delete searcher;
			searcher = 0;
		}
	} 
#endif
	
	if (searcher == 0) {
		searcher = new ATRIA< point_set<METRIC> >(points);	
	}
	
	if (searcher->geterr()) {
		mexErrMsgTxt("Error preparing searcher");
		return;
	}	 		
	
	double range;
	
	if (relative_range > 0)	
		range = relative_range * searcher->data_set_radius();  // compute the maximal search radius using information about attractor size
	else
		range = fabs(relative_range); 	// if relative_range is negativ, use it's value (without sign) as maximal search radius  

	mexPrintf("Number of reference points            : %d\n", R);
	mexPrintf("Upper bound for attractor size        : %f\n", 2 * searcher->data_set_radius());	
	mexPrintf("Maximal search radius                 : %f\n", range);

	plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
	double* out = (double *) mxGetPr(plhs[0]);
	
	unsigned long counter = 0;	
	double sum = 0;

	for (n=0; n < R; n++) { 		/* iterate over all reference points */ 
		const long actual = ref[n]-1;		/* Matlab to C means indices change from 1 to 0, 2 to 1, 3 to 2 ...*/

		if (actual > past) {
			vector<neighbor> v;

			searcher->search_range(v, range, points.point_begin(actual), actual-past, N); // don't search points from [actual-past .. N-1]
			//overall_points += (actual-past);	// count the total number of points pairs that were at least theoretically tested

			if (v.size() > 0) {	
				vector<neighbor>::iterator i;
				
				for (i = v.begin(); i < v.end(); i++) { // v is unsorted
					const double dist = (*i).dist();
					if (dist > 0) {
						sum += log(dist/range);
						counter++;
					}
				}
			}
		}
	}

	if (counter > 0) *out = -((double)counter)/sum;
	else *out = 0;
		
	delete searcher;
}
Ejemplo n.º 6
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    
    /* declare variables */
    
     
    double *v1_val, *v2_val, *v1_id, *v2_id;
    
    double *dis = 0,
        sum_sqr = 0;
    
    double v1_n, v2_n;
            
    int64_T    i = 0, j = 0;

    /* check number of input and output arguments */

    if (nrhs != 4) {

        mexErrMsgTxt("Wrong number of input arguments.");

    } else if (nlhs > 1) {

        mexErrMsgTxt("Too many output arguments.");

    }

    /* get input arguments */
    
    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {

        mexErrMsgTxt("x1 must be a int64 matrix.");

    }
    
    v1_id = (double *)mxGetData(prhs[0]);

    if (!mxIsDouble(prhs[1]) || mxIsComplex(prhs[1])) {

        mexErrMsgTxt("x2 must be a double matrix.");

    }
    
    v1_val = mxGetPr(prhs[1]);    
    v1_n = mxGetNumberOfElements(prhs[1]);
    

    if (!mxIsDouble(prhs[2]) || mxIsComplex(prhs[2])) {

        mexErrMsgTxt("x3 must be a double matrix.");

    }
    
    v2_id = (double *)mxGetData(prhs[2]);

    if (!mxIsDouble(prhs[3]) || mxIsComplex(prhs[3])) {

        mexErrMsgTxt("x4 must be a double matrix.");

    }
    
    v2_val = mxGetPr(prhs[3]);
    v2_n = mxGetNumberOfElements(prhs[3]);
    
    /* allocate and initialise output matrix */

   plhs[0] = mxCreateDoubleScalar(0);

   dis = mxGetPr(plhs[0]);
   
   /* Calculate */
    
    while (i < v1_n && j < v2_n){
        if(v1_id[i] == v2_id[j]) {
            sum_sqr += (v1_val[i] - v2_val[j]) * (v1_val[i] - v2_val[j]);
            i++; j++;
        } else if (v1_id[i] < v2_id[j]) {
            sum_sqr += v1_val[i] * v1_val[i];
            i++;
        } else {
            sum_sqr += v2_val[j] * v2_val[j];
            j++;
        }
    }
    
    //Calculate the rest of array
    while(i < v1_n) {
        sum_sqr += v1_val[i] * v1_val[i];
        i++;
    }
    while (j < v2_n){
        sum_sqr += v2_val[j] * v2_val[j];
        j++;
    }
    
    *dis = sqrt(sum_sqr);
    
    
}
Ejemplo n.º 7
0
void mexFunction
(
    int nargout,
    mxArray *pargout [ ],
    int nargin,
    const mxArray *pargin [ ]
)
{
    Long *Ap, *Ai, *Zp, *Zi ;
    double *Ax, *Az, *Zx ;
    Long p, j, build_upper, zero_handling, nrow, ncol, mkind, skind, asize, znz,
        status ;
    int ok = TRUE ;
    char filename [LEN+1], title [73], key [9], mtype [4] ;

    SuiteSparse_config config ;
    config.malloc_memory = mxMalloc ;
    config.free_memory = mxFree ;

    /* ---------------------------------------------------------------------- */
    /* check inputs */
    /* ---------------------------------------------------------------------- */

    if (nargin != 1 || nargout > 5 || !mxIsChar (pargin [0]))
    {
        mexErrMsgTxt ("Usage: [A Z title key mtype] = RBread (filename)") ;
    }

    /* ---------------------------------------------------------------------- */
    /* get filename */
    /* ---------------------------------------------------------------------- */

    if (mxGetString (pargin [0], filename, LEN) != 0)
    {
        mexErrMsgTxt ("filename too long") ;
    }

    /* ---------------------------------------------------------------------- */
    /* read the matrix */
    /* ---------------------------------------------------------------------- */

    build_upper = TRUE ;                    /* always build upper tri. part */
    zero_handling = (nargout > 1) ? 2 : 1 ; /* prune or extract zeros */

    status = RBread (filename, build_upper, zero_handling, title, key, mtype,
        &nrow, &ncol, &mkind, &skind, &asize, &znz,
        &Ap, &Ai, &Ax, &Az, &Zp, &Zi, &config) ;

    if (status != RBIO_OK)
    {
        RBerror (status) ;
        mexErrMsgTxt ("error reading file") ;
    }

    /* ---------------------------------------------------------------------- */
    /* return A to MATLAB */
    /* ---------------------------------------------------------------------- */

    pargout [0] = mxCreateSparse (0, 0, 0, (mkind == 2) ? mxCOMPLEX : mxREAL) ;
    mxFree (mxGetJc (pargout [0])) ;
    mxFree (mxGetIr (pargout [0])) ;
    mxFree (mxGetPr (pargout [0])) ;
    if (mkind == 2) mxFree (mxGetPi (pargout [0])) ;
    mxSetM (pargout [0], nrow) ;
    mxSetN (pargout [0], ncol) ;
    mxSetNzmax (pargout [0], asize) ;
    mxSetJc (pargout [0], (mwIndex *) Ap) ;
    mxSetIr (pargout [0], (mwIndex *) Ai) ;
    mxSetPr (pargout [0], Ax) ;
    if (mkind == 2) mxSetPi (pargout [0], Az) ;

    /* ---------------------------------------------------------------------- */
    /* return Z to MATLAB */
    /* ---------------------------------------------------------------------- */

    if (nargout > 1)
    {
        Zx = (double *) SuiteSparse_malloc (znz, sizeof (double), &ok, &config);
        for (p = 0 ; p < znz ; p++)
        {
            Zx [p] = 1 ;
        }
        pargout [1] = mxCreateSparse (0, 0, 0, mxREAL) ;
        mxFree (mxGetJc (pargout [1])) ;
        mxFree (mxGetIr (pargout [1])) ;
        mxFree (mxGetPr (pargout [1])) ;
        mxSetM (pargout [1], nrow) ;
        mxSetN (pargout [1], ncol) ;
        mxSetNzmax (pargout [1], MAX (znz,1)) ;
        mxSetJc (pargout [1], (mwIndex *) Zp) ;
        mxSetIr (pargout [1], (mwIndex *) Zi) ;
        mxSetPr (pargout [1], Zx) ;
    }

    /* ---------------------------------------------------------------------- */
    /* return title */
    /* ---------------------------------------------------------------------- */

    if (nargout > 2)
    {
        pargout [2] = mxCreateString (title) ;
    }

    /* ---------------------------------------------------------------------- */
    /* return key */
    /* ---------------------------------------------------------------------- */

    if (nargout > 3)
    {
        pargout [3] = mxCreateString (key) ;
    }

    /* ---------------------------------------------------------------------- */
    /* return mtype */
    /* ---------------------------------------------------------------------- */

    if (nargout > 4)
    {
        pargout [4] = mxCreateString (mtype) ;
    }
}
void mexFunction
(
    int nargout,
    mxArray *pargout [ ],
    int nargin,
    const mxArray *pargin [ ]
)
{
    double xmin, xmax ;
    Long *Ap, *Ai ;
    double *Ax, *Az ;
    Long nrow, ncol, nnz, mkind, skind, mkind_in ;
    char mtype [4] ;

    /* ---------------------------------------------------------------------- */
    /* check inputs */
    /* ---------------------------------------------------------------------- */

    if (nargin != 1 || nargout > 3)
    {
        mexErrMsgTxt ("Usage: [mtype mkind skind] = RBtype (A)") ;
    }

    /* ---------------------------------------------------------------------- */
    /* get A */
    /* ---------------------------------------------------------------------- */

    if (!mxIsClass (pargin [0], "double") || !mxIsSparse (pargin [0]))
    {
        mexErrMsgTxt ("A must be sparse and double") ;
    }

    Ap = (Long *) mxGetJc (pargin [0]) ;
    Ai = (Long *) mxGetIr (pargin [0]) ;
    Ax = mxGetPr (pargin [0]) ;
    Az = mxGetPi (pargin [0]) ;
    nrow = mxGetM (pargin [0]) ;
    ncol = mxGetN (pargin [0]) ;

    /* ---------------------------------------------------------------------- */
    /* determine the mtype of A */
    /* ---------------------------------------------------------------------- */

    mkind_in = mxIsComplex (pargin [0]) ? 2 : 0 ;

    RBkind (nrow, ncol, Ap, Ai, Ax, Az, mkind_in, &mkind, &skind, mtype,
        &xmin, &xmax, NULL) ;

    /* ---------------------------------------------------------------------- */
    /* return the result */
    /* ---------------------------------------------------------------------- */

    pargout [0] = mxCreateString (mtype) ;
    if (nargout >= 2)
    {
        pargout [1] = mxCreateDoubleScalar ((double) mkind) ;
    }
    if (nargout >= 3)
    {
        pargout [2] = mxCreateDoubleScalar ((double) skind) ;
    }
}
Ejemplo n.º 9
0
void mexFunction( int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray*prhs[] )
     
{ 
  LSMLIB_REAL *phi_x, *phi_y;
  int ilo_grad_phi_gb, ihi_grad_phi_gb, jlo_grad_phi_gb, jhi_grad_phi_gb;
  LSMLIB_REAL *phi; 
  int ilo_phi_gb, ihi_phi_gb, jlo_phi_gb, jhi_phi_gb;
  LSMLIB_REAL *vel_x, *vel_y;
  int ilo_vel_gb, ihi_vel_gb, jlo_vel_gb, jhi_vel_gb;
  LSMLIB_REAL *D1;
  int ilo_D1_gb, ihi_D1_gb, jlo_D1_gb, jhi_D1_gb;
  LSMLIB_REAL *D2;
  int ilo_D2_gb, ihi_D2_gb, jlo_D2_gb, jhi_D2_gb;
  int ilo_fb, ihi_fb, jlo_fb, jhi_fb;
  double *dX;
  LSMLIB_REAL dX_meshgrid_order[2];
  int ghostcell_width;
  int num_data_array_dims;
  
  /* Check for proper number of arguments */
  if (nrhs != 5) { 
    mexErrMsgTxt("Five required input arguments."); 
  } else if (nlhs > 2) {
    mexErrMsgTxt("Too many output arguments."); 
  } 
    
  /* Parameter Checks */
  num_data_array_dims = mxGetNumberOfDimensions(PHI);
  if (num_data_array_dims != 2) {
    mexErrMsgTxt("phi should be a 2 dimensional array."); 
  }
  num_data_array_dims = mxGetNumberOfDimensions(VEL_X);
  if (num_data_array_dims != 2) {
    mexErrMsgTxt("vel_x should be a 2 dimensional array."); 
  }
  num_data_array_dims = mxGetNumberOfDimensions(VEL_Y);
  if (num_data_array_dims != 2) {
    mexErrMsgTxt("vel_y should be a 2 dimensional array."); 
  }

  /* Check that the inputs have the correct floating-point precision */
#ifdef LSMLIB_DOUBLE_PRECISION
    if (!mxIsDouble(PHI)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for double-precision but phi is single-precision");
    }
    if (!mxIsDouble(VEL_X)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for double-precision but vel_x is single-precision");
    }
    if (!mxIsDouble(VEL_Y)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for double-precision but vel_y is single-precision");
    }
#else
    if (!mxIsSingle(PHI)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for single-precision but phi is double-precision");
    }
    if (!mxIsSingle(VEL_X)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for single-precision but vel_x is double-precision");
    }
    if (!mxIsSingle(VEL_Y)) {
      mexErrMsgTxt("Incompatible precision: LSMLIB built for single-precision but vel_y is double-precision");
    }
#endif

  /* Get ghostcell_width */
  ghostcell_width = mxGetPr(GHOSTCELL_WIDTH)[0];

  /* Get dX */
  dX = mxGetPr(DX);

  /* Change order of dX to be match MATLAB meshgrid() order for grids. */
  dX_meshgrid_order[0] = dX[1];
  dX_meshgrid_order[1] = dX[0];

  /* Assign pointers for phi and velocities */
  phi = (LSMLIB_REAL*) mxGetPr(PHI);
  vel_x = (LSMLIB_REAL*) mxGetPr(VEL_X);
  vel_y = (LSMLIB_REAL*) mxGetPr(VEL_Y);
      
  /* Get size of phi data */
  ilo_phi_gb = 1;
  ihi_phi_gb = mxGetM(PHI);
  jlo_phi_gb = 1;
  jhi_phi_gb = mxGetN(PHI);

  /* Get size of velocity data (assume vel_x and vel_y have same size) */
  ilo_vel_gb = 1;
  ihi_vel_gb = mxGetM(VEL_X);
  jlo_vel_gb = 1;
  jhi_vel_gb = mxGetN(VEL_X);

  /* if necessary, shift ghostbox for velocity to be */
  /* centered with respect to the ghostbox for phi.  */
  if (ihi_vel_gb != ihi_phi_gb) {
    int shift = (ihi_phi_gb-ihi_vel_gb)/2;
    ilo_vel_gb += shift;
    ihi_vel_gb += shift;
  }
  if (jhi_vel_gb != jhi_phi_gb) {
    int shift = (jhi_phi_gb-jhi_vel_gb)/2;
    jlo_vel_gb += shift;
    jhi_vel_gb += shift;
  }

  /* Create matrices for upwind derivatives (i.e. phi_x and phi_y) */
  ilo_grad_phi_gb = ilo_phi_gb;
  ihi_grad_phi_gb = ihi_phi_gb;
  jlo_grad_phi_gb = ilo_phi_gb;
  jhi_grad_phi_gb = jhi_phi_gb;
#ifdef LSMLIB_DOUBLE_PRECISION
  PHI_X = mxCreateDoubleMatrix(ihi_grad_phi_gb-ilo_grad_phi_gb+1,
                               jhi_grad_phi_gb-jlo_grad_phi_gb+1,
                               mxREAL);
  PHI_Y = mxCreateDoubleMatrix(ihi_grad_phi_gb-ilo_grad_phi_gb+1,
                               jhi_grad_phi_gb-jlo_grad_phi_gb+1,
                               mxREAL);
#else
  PHI_X = mxCreateNumericMatrix(ihi_grad_phi_gb-ilo_grad_phi_gb+1,
                                jhi_grad_phi_gb-jlo_grad_phi_gb+1,
                                mxSINGLE_CLASS, mxREAL);
  PHI_Y = mxCreateNumericMatrix(ihi_grad_phi_gb-ilo_grad_phi_gb+1,
                                jhi_grad_phi_gb-jlo_grad_phi_gb+1,
                                mxSINGLE_CLASS, mxREAL);
#endif
  phi_x = (LSMLIB_REAL*) mxGetPr(PHI_X); 
  phi_y = (LSMLIB_REAL*) mxGetPr(PHI_Y); 


  /* Allocate scratch memory for undivided differences */
  ilo_D1_gb = ilo_phi_gb; 
  ihi_D1_gb = ihi_phi_gb;
  jlo_D1_gb = jlo_phi_gb; 
  jhi_D1_gb = jhi_phi_gb;
  D1 = (LSMLIB_REAL*) mxMalloc( sizeof(LSMLIB_REAL) 
                              * (ihi_D1_gb-ilo_D1_gb+1)
                              * (jhi_D1_gb-jlo_D1_gb+1) );

  ilo_D2_gb = ilo_phi_gb; 
  ihi_D2_gb = ihi_phi_gb;
  jlo_D2_gb = jlo_phi_gb; 
  jhi_D2_gb = jhi_phi_gb;
  D2 = (LSMLIB_REAL*) mxMalloc( sizeof(LSMLIB_REAL) 
                              * (ihi_D2_gb-ilo_D2_gb+1)
                              * (jhi_D2_gb-jlo_D2_gb+1) );

  if ( (!D1) || (!D2) ) {
    if (D1) mxFree(D1);
    if (D2) mxFree(D2);
    mexErrMsgTxt("Unable to allocate memory for scratch data...aborting....");
  }


  /* Do the actual computations in a Fortran 77 subroutine */
  ilo_fb = ilo_phi_gb+ghostcell_width;
  ihi_fb = ihi_phi_gb-ghostcell_width;
  jlo_fb = jlo_phi_gb+ghostcell_width;
  jhi_fb = jhi_phi_gb-ghostcell_width;

  /* 
   * NOTE: ordering of data arrays from meshgrid() is (y,x), so order
   * derivative and velocity data arrays need to be reversed.
   */
  LSM2D_UPWIND_HJ_ENO2(
    phi_y, phi_x, 
    &ilo_grad_phi_gb, &ihi_grad_phi_gb,
    &jlo_grad_phi_gb, &jhi_grad_phi_gb,
    phi, 
    &ilo_phi_gb, &ihi_phi_gb, &jlo_phi_gb, &jhi_phi_gb, 
    vel_y, vel_x, 
    &ilo_vel_gb, &ihi_vel_gb, &jlo_vel_gb, &jhi_vel_gb,
    D1,
    &ilo_D1_gb, &ihi_D1_gb, &jlo_D1_gb, &jhi_D1_gb, 
    D2,
    &ilo_D2_gb, &ihi_D2_gb, &jlo_D2_gb, &jhi_D2_gb, 
    &ilo_fb, &ihi_fb, &jlo_fb, &jhi_fb,
    &dX_meshgrid_order[0], &dX_meshgrid_order[1]);

  /* Deallocate scratch memory for undivided differences */
  mxFree(D1);
  mxFree(D2);

  return;
}
Ejemplo n.º 10
0
/* main function that interfaces with MATLAB */
void mexFunction(
				 int            nlhs,
				 mxArray       *plhs[],
				 int            nrhs,
				 const mxArray *prhs[] )
{

  /*initial states of m-sequence generators */
  /* PN register state of the first m-seqence   */
  unsigned char mseq_state0[31 + MAX_output_seq_length + NC_OFFSET];
  /* PN register state of the second m-seqence  */
  unsigned char mseq_state1[31 + MAX_output_seq_length + NC_OFFSET];
  unsigned char mseq_state1_temp[31];
  
  long seed1_dec; /* initial state expressed as decimal value   */
  
  mwSize output_seq_length;
  double NIDcell;
  double NIDue;
  double subframe;
  double codeword;
  unsigned char *gold_seq;

  int	deg;		/* order of the polynomials poly0 and poly1 */

  mwSize i, ji;     /* loop variables   */
  int help_convert; /* temporary variable for the dec to binary conversion  */
  int index_help_convert;	/* invert parameter for the bibary conversion	*/
  
  /* Check for proper number of arguments */
  if ((nrhs != 5 )||(nlhs  < 1)||(nlhs  > 2)) 
  {
	mexErrMsgTxt("Usage: s = LTE_common_scrambling(b, NIDcell, NIDue, subframe, codeword, mode)");
  } 
  else 
  {
	/* Get input parameters */
	output_seq_length = (mwSize) (*mxGetPr(INPUT_length));
	NIDcell           = *mxGetPr(INPUT_NIDcell);
	NIDue             = *mxGetPr(INPUT_NIDue);
	subframe          = *mxGetPr(INPUT_subframe);
	codeword          = *mxGetPr(INPUT_codeword);
    
    /* create the output vector */
    OUTPUT_gold_seq = mxCreateLogicalMatrix(1, output_seq_length);
    gold_seq = mxGetPr(OUTPUT_gold_seq);

  /*initial states of m-sequence generators */
  /*DEFINED IN STANDARD 3GPP TS 36.211 V8.2.0 (2008-03) Section 7.2. this initial state is also same with v8.8.0    */
	for(i = 0 ; i < 31 + output_seq_length + NC_OFFSET ; i++)
	{
		mseq_state0[i] = 0;
		mseq_state1[i] = 0;
	}
	mseq_state0[0] = 1;
	
    deg = 31;    
    seed1_dec = pow(2, 14) * NIDue + pow(2, 13) * codeword + pow(2, 9) * (subframe - 1) + NIDcell;
    
    /* Conversion of the seed into binary number for the second m-sequence that is calculated as decimal from input pars */
	index_help_convert = 0;
    for(help_convert = 30 ; help_convert >= 0; help_convert--) 
    {
        mseq_state1_temp[help_convert] = seed1_dec / (1 << help_convert);
        seed1_dec = seed1_dec - mseq_state1_temp[help_convert] * (1 << help_convert);
		mseq_state1[index_help_convert] = mseq_state1_temp[help_convert];
		index_help_convert++;
    }
    
    for (i = 0; i < output_seq_length + NC_OFFSET ; i++) 
    {
		if(i >= NC_OFFSET)
			gold_seq[i - NC_OFFSET] = mseq_state0[i] ^ mseq_state1[i];
		mseq_state0[i + deg] = mseq_state0[i] ^ mseq_state0[i + 3];
		mseq_state1[i + deg] = (mseq_state1[i] ^ mseq_state1[i + 1]) ^ (mseq_state1[i + 2] ^ mseq_state1[i + 3]);
    }
  }
  return;
}
Ejemplo n.º 11
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

  CUresult cudastatus = CUDA_SUCCESS;

  // no more than 2 arguments expected
  if (nrhs > 2)
    mexErrMsgTxt("Wrong number of arguments");

  if (init == 0) {
    // Initialize function
    //mexLock();

    // load GPUmat
    gm = gmGetGPUmat();

    // check gm
    gmCheckGPUmat(gm);

    // load module
    // NO MODULE REQUIRED

    // load float GPU function
    // NO FUNCTION REQUIRED

    init = 1;
  }

  // log
  gm->debug.log("> SIZE\n",0);
  gm->debug.logPush();

  if (gm->comp.getCompileMode() == 1) {
    mexWarnMsgTxt(WARNING_NUMERICS_COMPNOTIMPLEMENTED);
  }


  // mex parameters are:
  // IN: GPUtype variable

  GPUtype IN = gm->gputype.getGPUtype(prhs[0]);
  const int *in_size = gm->gputype.getSize(IN);
  int in_ndims = gm->gputype.getNdims(IN);
  // 2 cases
  // 1. s = size(A)
  // 2. s = size(A,dim)
  if (nrhs == 1) {
    // 2 cases:
    // 1. s = size(A)
    // 2. [a,b,c,...] = size(A)
    if (nlhs<=1) {
      // 1. s = size(A)
      // create output plhs[0]
      plhs[0] = mxCreateDoubleMatrix(1, in_ndims, mxREAL);
      // fill in plhs[0] with IN dimensions
      double *plhs_size = mxGetPr(plhs[0]);
      for (int i = 0; i < in_ndims; i++)
        plhs_size[i] = (double) in_size[i];
    } else {
      // 2. [a,b,c,...] = size(A)
      for (int i=0;i<nlhs;i++) {
        // create output
        // create output plhs[i]
        int r = 1;
        // if i is greater than IN dims return 1
        if (i>(in_ndims-1)) {
          // r = 1
        } else {
          r = in_size[i];
        }
        plhs[i] = mxCreateDoubleScalar(r);
      }
    }
  } else {
    // retrieve dim
    int dim  =  (int) mxGetScalar(prhs[1]);
    int r = 1;
    // if dim is greater than IN dims return 1
    if (dim>in_ndims) {
      // r = 1
    } else {
      r = in_size[dim-1];
    }
    // create output plhs[0]
    plhs[0] = mxCreateDoubleScalar(r);
  }



}
Ejemplo n.º 12
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{                                                                            
	try {                                                 
		char* conffile = mxArrayToString(prhs[0]);
		char* robotname = mxArrayToString(prhs[1]);
        
		//mexPrintf("conffile = %s", conffile);
		Robot robj(conffile, robotname);

		// Create link structure
		mxArray *links = mxCreateStructMatrix(robj.get_dof(), 1, NUM_LINK_FIELDS, link_field_names);
		double *ptr = NULL;
		Link *rlinks = robj.links;
		std::vector<double> immobileID;
		for (int i=1; i <= robj.get_dof(); ++i) 
		{
			// Return the joint type.
			mxSetField(links, i-1, "joint_type", mxCreateDoubleScalar( rlinks[i].get_joint_type() ));
            
			// Return theta.
			mxSetField(links, i-1, "theta", mxCreateDoubleScalar( rlinks[i].get_theta() ));
            
			//!< Return d.
			mxSetField(links, i-1, "d", mxCreateDoubleScalar( rlinks[i].get_d() ));
            
			// Return a.
			mxSetField(links, i-1, "a", mxCreateDoubleScalar( rlinks[i].get_a() ));
            
			// Return alpha.
			mxSetField(links, i-1, "alpha", mxCreateDoubleScalar( rlinks[i].get_alpha() ));
            
			//!< Return q
			mxSetField(links, i-1, "q", mxCreateDoubleScalar( rlinks[i].get_q() ));
            
			// Return theta_min.
			mxSetField(links, i-1, "theta_min", mxCreateDoubleScalar( rlinks[i].get_theta_min() ));
            
			// Return theta_max.
			mxSetField(links, i-1, "theta_max", mxCreateDoubleScalar( rlinks[i].get_theta_max() ));
            
			// Return joint_offset.
			mxSetField(links, i-1, "joint_offset", mxCreateDoubleScalar( rlinks[i].get_joint_offset() ));
            
			// Return r.
			mxArray *mr = mxArrayFromNMArray( rlinks[i].get_r() );
			//mxArray *mr = mxCreateDoubleMatrix(1,3,mxREAL); ptr = mxGetPr(mr);
			//ColumnVector r = rlinks[i].get_r();
			//for (int n=0; n < 3; ++n) ptr[n] = r(n+1);
			mxSetField(links, i-1, "r", mr);
            
			// Return p.
			mxArray *mp = mxArrayFromNMArray( rlinks[i].get_p() );
			//mxArray *mp = mxCreateDoubleMatrix(1,3,mxREAL); ptr = mxGetPr(mp);
			//ColumnVector p = rlinks[i].get_p();
			//for (int n=0; n < 3; ++n) ptr[n] = p(n+1);
			mxSetField(links, i-1, "p", mp);
            
			// Return m.
			mxSetField(links, i-1, "m", mxCreateDoubleScalar( rlinks[i].get_m() ));
            
			// Return Im.
			mxSetField(links, i-1, "Im", mxCreateDoubleScalar( rlinks[i].get_Im() ));
            
			// Return Gr.
			mxSetField(links, i-1, "Gr", mxCreateDoubleScalar( rlinks[i].get_Gr() ));
            
			// Return B.
			mxSetField(links, i-1, "B", mxCreateDoubleScalar( rlinks[i].get_B() ));
            
			// Return Cf.
			mxSetField(links, i-1, "Cf", mxCreateDoubleScalar( rlinks[i].get_Cf() ));
            
			// Return I.
			mxArray *mI = mxArrayFromNMArray( rlinks[i].get_I() );
			//mxArray *mI = mxCreateDoubleMatrix(3,3,mxREAL);
			//Matrix I = rlinks[i].get_I();
			//NMMatrixToMxArray(mxGetPr(mI), I, 3, 3);
			mxSetField(links, i-1, "I", mI);
            
			// Return immobile.
			mxSetField(links, i-1, "immobile", mxCreateLogicalScalar( rlinks[i].get_immobile() ));
			if ( rlinks[i].get_immobile() )
			{
				immobileID.push_back((double)i);
			}
		}
        
		// Create robot structure
		LHS_ARG_1 = mxCreateStructMatrix(1, 1, NUM_ROBOT_FIELDS, robot_field_names);
        
		// Set name
		mxSetField(LHS_ARG_1, 0, "name", mxCreateString(robotname) );
		
		// Set gravity
		mxSetField(LHS_ARG_1, 0, "gravity", mxArrayFromNMArray( robj.gravity ) );
		
		// Return DH type
		mxSetField(LHS_ARG_1, 0, "DH", mxCreateLogicalScalar( robj.get_DH() ));
        
		// Return DOF
		mxSetField(LHS_ARG_1, 0, "dof", mxCreateDoubleScalar( (double)robj.get_dof() ));
        
		// Return available DOF
		mxSetField(LHS_ARG_1, 0, "available_dof", mxCreateDoubleScalar( robj.get_available_dof() ));
        
		// Return IDs of immobile joints
		int nImmobileJnts = (int)immobileID.size();
		if ( nImmobileJnts > 0 )
		{
			mxArray *tempArray = mxCreateDoubleMatrix(1,nImmobileJnts,mxREAL);
			memcpy( mxGetPr(tempArray), &immobileID[0], nImmobileJnts*sizeof(double) );
			mxSetField(LHS_ARG_1, 0, "immobile_joints", tempArray);
		} else {
			mxSetField(LHS_ARG_1, 0, "immobile_joints", mxCreateDoubleMatrix(0,0, mxREAL));
		}
		
		// Return links
		mxSetField(LHS_ARG_1, 0, "links", links);
		
		// Free allocated stuff
		mxFree( conffile );
		mxFree( robotname );
	
	} catch(Exception) {
		std::ostringstream msg;
		msg << mexFunctionName() << ":: " << Exception::what();
		mexErrMsgTxt(msg.str().c_str());
	} catch (const std::runtime_error& e) {
		std::ostringstream msg;
		msg << mexFunctionName() << ":: " << e.what();
		mexErrMsgTxt(msg.str().c_str());
	} catch (...) {
		std::ostringstream msg;
		msg << mexFunctionName() << ":: Unknown failure during operation";
		mexErrMsgTxt(msg.str().c_str());
	}                                                                           
}
Ejemplo n.º 13
0
/* cs_qr: sparse QR factorization */
void mexFunction
(
    int nargout,
    mxArray *pargout [ ],
    int nargin,
    const mxArray *pargin [ ]
)
{
    CS_INT m, n, order, *p ;
    if (nargout > 5 || nargin != 1)
    {
        mexErrMsgTxt ("Usage: [V,beta,p,R,q] = cs_qr(A)") ;
    }
    order = (nargout == 5) ? 3 : 0 ;        /* determine ordering */
    m = mxGetM (pargin [0]) ;
    n = mxGetN (pargin [0]) ;
    if (m < n) mexErrMsgTxt ("A must have # rows >= # columns") ;
    if (mxIsComplex (pargin [0]))
    {
#ifndef NCOMPLEX
        cs_cls *S ;
        cs_cln *N ;
        cs_cl Amatrix, *A, *D ;
        A = cs_cl_mex_get_sparse (&Amatrix, 0, pargin [0]) ;    /* get A */
        S = cs_cl_sqr (order, A, 1) ;       /* symbolic QR ordering & analysis*/
        N = cs_cl_qr (A, S) ;               /* numeric QR factorization */
        cs_free (A->x) ;
        if (!N) mexErrMsgTxt ("qr failed") ;
        cs_cl_dropzeros (N->L) ;            /* drop zeros from V and sort */
        D = cs_cl_transpose (N->L, 1) ;
        cs_cl_spfree (N->L) ;
        N->L = cs_cl_transpose (D, 1) ;
        cs_cl_spfree (D) ;
        cs_cl_dropzeros (N->U) ;            /* drop zeros from R and sort */
        D = cs_cl_transpose (N->U, 1) ;
        cs_cl_spfree (N->U) ;
        N->U = cs_cl_transpose (D, 1) ;
        cs_cl_spfree (D) ;
        m = N->L->m ;                               /* m may be larger now */
        p = cs_cl_pinv (S->pinv, m) ;                   /* p = pinv' */
        pargout [0] = cs_cl_mex_put_sparse (&(N->L)) ;  /* return V */
        cs_dl_mex_put_double (n, N->B, &(pargout [1])) ;   /* return beta */
        pargout [2] = cs_dl_mex_put_int (p, m, 1, 1) ;  /* return p */
        pargout [3] = cs_cl_mex_put_sparse (&(N->U)) ;  /* return R */
        pargout [4] = cs_dl_mex_put_int (S->q, n, 1, 0) ;  /* return q */
        cs_cl_nfree (N) ;
        cs_cl_sfree (S) ;
#else
        mexErrMsgTxt ("complex matrices not supported") ;
#endif
    }
    else
    {
        cs_dls *S ;
        cs_dln *N ;
        cs_dl Amatrix, *A, *D ;
        A = cs_dl_mex_get_sparse (&Amatrix, 0, 1, pargin [0]) ; /* get A */
        S = cs_dl_sqr (order, A, 1) ;       /* symbolic QR ordering & analysis*/
        N = cs_dl_qr (A, S) ;               /* numeric QR factorization */
        if (!N) mexErrMsgTxt ("qr failed") ;
        cs_dl_dropzeros (N->L) ;            /* drop zeros from V and sort */
        D = cs_dl_transpose (N->L, 1) ;
        cs_dl_spfree (N->L) ;
        N->L = cs_dl_transpose (D, 1) ;
        cs_dl_spfree (D) ;
        cs_dl_dropzeros (N->U) ;            /* drop zeros from R and sort */
        D = cs_dl_transpose (N->U, 1) ;
        cs_dl_spfree (N->U) ;
        N->U = cs_dl_transpose (D, 1) ;
        cs_dl_spfree (D) ;
        m = N->L->m ;                               /* m may be larger now */
        p = cs_dl_pinv (S->pinv, m) ;                   /* p = pinv' */
        pargout [0] = cs_dl_mex_put_sparse (&(N->L)) ;  /* return V */
        cs_dl_mex_put_double (n, N->B, &(pargout [1])) ;   /* return beta */
        pargout [2] = cs_dl_mex_put_int (p, m, 1, 1) ;  /* return p */
        pargout [3] = cs_dl_mex_put_sparse (&(N->U)) ;  /* return R */
        pargout [4] = cs_dl_mex_put_int (S->q, n, 1, 0) ;  /* return q */
        cs_dl_nfree (N) ;
        cs_dl_sfree (S) ;
    }
}
Ejemplo n.º 14
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  int               i;
  mxClassID         category;
  int               total_num_of_elements, number_of_fields, index, field_index;
  const char        *field_name;

  const mxArray     *field_array_ptr;
  char              *buf, *sort1;
  int               number_of_dimensions;
  const int         *dims;
  int               buflen, d, page, total_number_of_pages, elements_per_page;
  double            *pr, *pr2, *pr3, *pr4;
  int               total_num_of_elements2, index2;

  int               mrows, mcols, mrows1, mcols1, toto;
  double            *sort2, sort3, *J1;
  int               sort3bis, *pr3bis;
  double            *sort4;
  double            *sort11, *sort22, *sort33;
  int               *sort55, *pr5, *ddl_n, *ddl_tt, *ddl_d;


  double            tol, k_lat;
  int               itermax, chat ;

  char              *mot1, *mot2, *mot3, *mot4, *mot5, *mot6, *mot7;
  method            meth_dfc_2D;
  double            *vec, *q, *z, *w, *info, *mu;
  int               n, *nr, *dim_tt, *dim_d;



  mot1 = "NLGS";
  mot2 = "Cfd_latin";
  mot3 = "Lemke";
  /*  mot4 = "CPG";
      mot5 = "Latin";
      mot6 = "QP";

  */
  mot7 = "NSQP";



  if (nlhs != 3)
  {
    mexErrMsgTxt("3 output required.");
  }


  if (nrhs != 5)
  {
    mexErrMsgTxt("5 input required.");
  }


  vec = mxGetPr(prhs[0]);
  q   = mxGetPr(prhs[1]);
  nr  = mxGetData(prhs[2]);
  mu  = mxGetPr(prhs[3]);



  meth_dfc_2D.dfc_2D.mu = *mu;



  n   = *nr;



  mrows1 = mxGetM(prhs[1]);
  mcols1 = mxGetN(prhs[1]);

  plhs[0] = mxCreateDoubleMatrix(mrows1, mcols1, mxREAL); /* z */
  plhs[1] = mxCreateDoubleMatrix(mrows1, mcols1, mxREAL); /* w */
  plhs[2] = mxCreateDoubleMatrix(mcols1, mcols1, mxREAL); /* info */


  z = mxGetPr(plhs[0]);
  w = mxGetPr(plhs[1]);
  info = mxGetPr(plhs[2]);

  category = mxGetClassID(prhs[4]);

  if (category != mxSTRUCT_CLASS)
  {
    mexPrintf("The thrid input must be a structure");
  }


  total_num_of_elements = mxGetNumberOfElements(prhs[4]);
  number_of_fields = mxGetNumberOfFields(prhs[4]);

  mexPrintf("\n\t\t");

  index = 0;
  field_index = 0;

  field_array_ptr = mxGetFieldByNumber(prhs[4],
                                       index,
                                       field_index);


  if (field_array_ptr == NULL)
    mexPrintf("\tEmpty Field\n");
  else
  {


    category = mxGetClassID(field_array_ptr);

    if (category != mxCHAR_CLASS)
    {
      mexPrintf("The first element of the structure must be a CHAR");
    }



    buflen = mxGetNumberOfElements(field_array_ptr) + 1;
    buf = mxCalloc(buflen, sizeof(char));

    /* Copy the string data from string_array_ptr and place it into buf. */
    if (mxGetString(field_array_ptr, buf, buflen) != 0)
      mexErrMsgTxt("Could not convert string data.");

    printf("\n");

    meth_dfc_2D.dfc_2D.name = buf;

    /*                        2nd element of the structure                     */

    if ((strcmp(buf, mot2) == 0))
    {

      field_index = 1;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }




      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 2 element of the structure must be an integer\n");
      }






      pr3bis = (int *) mxGetData(field_array_ptr);





      total_num_of_elements2 = 1;


      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {
        if (field_index == 1)
        {

          itermax = pr3bis[index2];

          meth_dfc_2D.dfc_2D.itermax =  itermax;





        }
      }

      /*                      End of  2nd element of the structure                     */

      /*                        3 element of the structure                     */
      field_index = 2;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 3 element of the structure must be a DOUBLE");
      }

      if (field_index == 2) pr2 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = 1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);

      sort2 = (double*) malloc(1 * 1 * sizeof(double));



      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 2)
        {


          sort2[index2] = pr2[index2];

          tol = sort2[index2];
          meth_dfc_2D.dfc_2D.tol = tol;



        }
      }


      /*                       End 3  element of the structure                     */
      /*                       4  element of the structure                     */

      field_index = 3;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 4 element of the structure must be a DOUBLE");
      }


      if (field_index == 3)  pr3 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = 1; /* mxGetNumberOfElements(field_array_ptr);*/


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      sort22 = (double*) malloc(1 * 1 * sizeof(double));



      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 3)
        {
          sort22[index2] = pr3[index2];

          k_lat = sort22[index2];
          meth_dfc_2D.dfc_2D.k_latin = k_lat;





        }
      }


      /*                      End of 4  element of the structure                     */

      /*                       5  element of the structure                     */



      field_index = 4;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 5 element of the structure must be an integer");
      }




      pr5 = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = 1; /*mxGetNumberOfElements(field_array_ptr);*/


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      sort55 = (int*) malloc(1 * 1 * sizeof(int));


      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 4)
        {
          sort55[index2] = pr5[index2];

          chat = sort55[index2];
          meth_dfc_2D.dfc_2D.chat = chat;




        }
      }


      /*                       End of 5 element of the structure                     */

      /*                       6  element of the structure                     */

      field_index = 5;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 6 element of the structure must be a DOUBLE");
      }


      if (field_index == 5)  J1 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = mrows1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      meth_dfc_2D.dfc_2D.J1 = (double *) malloc(mrows1 * sizeof(double));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 5)
        {
          meth_dfc_2D.dfc_2D.J1[index2] = J1[index2];


        }
      }


      /*                      End of 6  element of the structure                     */

      /*                       7  element of the structure                     */



      field_index = 6;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 7 element of the structure must be an integer");
      }




      dim_tt = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1; /*mxGetNumberOfElements(field_array_ptr);*/


      meth_dfc_2D.dfc_2D.dim_tt = *dim_tt;/* (int *) malloc(*dim_tt*sizeof(int));*/


      /*                       End of 7 element of the structure                     */
      /*                       8  element of the structure                     */



      field_index = 7;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 8 element of the structure must be an integer");
      }




      ddl_n = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt; /*mxGetNumberOfElements(field_array_ptr);*/





      meth_dfc_2D.dfc_2D.ddl_n = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 7)
        {
          meth_dfc_2D.dfc_2D.ddl_n[index2] = ddl_n[index2] - 1;

        }
      }


      /*                       End of 8 element of the structure                     */

      /*                       9  element of the structure                     */



      field_index = 8;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 9 element of the structure must be an integer");
      }




      ddl_tt = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt; /*mxGetNumberOfElements(field_array_ptr);*/



      meth_dfc_2D.dfc_2D.ddl_tt = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 8)
        {
          meth_dfc_2D.dfc_2D.ddl_tt[index2] = ddl_tt[index2] - 1;



        }
      }


      /*                       End of 9 element of the structure                     */

      /*                       10  element of the structure                     */



      field_index = 9;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 10 element of the structure must be an integer");
      }




      dim_d = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1; /*mxGetNumberOfElements(field_array_ptr);*/




      meth_dfc_2D.dfc_2D.dim_d = *dim_d;/* (int *) malloc(*dim_tt*sizeof(int));*/



      /*                       End of 10 element of the structure                     */
      /*                       11  element of the structure                     */



      field_index = 10;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 11 element of the structure must be an integer");
      }




      ddl_d = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_d;






      meth_dfc_2D.dfc_2D.ddl_d = (int *) malloc(*dim_d * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 10)
        {
          meth_dfc_2D.dfc_2D.ddl_d[index2] = ddl_d[index2] - 1;






        }
      }

      free(sort2);
      free(sort22);
      free(sort55);
    }

    /*                       End of 11 element of the structure                     */




    if ((strcmp(buf, mot1) == 0))
    {

      field_index = 1;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }




      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 2 element of the structure must be an integer\n");
      }






      pr3bis = (int *) mxGetData(field_array_ptr);





      total_num_of_elements2 = 1;


      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {
        if (field_index == 1)
        {

          itermax = pr3bis[index2];

          meth_dfc_2D.dfc_2D.itermax =  itermax;





        }
      }


      field_index = 2;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 3 element of the structure must be a DOUBLE");
      }

      if (field_index == 2) pr2 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = 1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);

      sort2 = (double*) malloc(1 * 1 * sizeof(double));



      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 2)
        {


          sort2[index2] = pr2[index2];

          tol = sort2[index2];
          meth_dfc_2D.dfc_2D.tol = tol;



        }
      }


      field_index = 3;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 4 element of the structure must be an integer");
      }




      pr5 = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      sort55 = (int*) malloc(1 * 1 * sizeof(int));


      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 3)
        {
          sort55[index2] = pr5[index2];

          chat = sort55[index2];
          meth_dfc_2D.dfc_2D.chat = chat;




        }
      }


      field_index = 4;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 5 element of the structure must be a DOUBLE");
      }


      if (field_index == 4)  J1 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = mrows1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      meth_dfc_2D.dfc_2D.J1 = (double *) malloc(mrows1 * sizeof(double));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 4)
        {
          meth_dfc_2D.dfc_2D.J1[index2] = J1[index2];


        }
      }



      field_index = 5;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 6 element of the structure must be an integer");
      }




      dim_tt = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;


      meth_dfc_2D.dfc_2D.dim_tt = *dim_tt;



      field_index = 6;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 7 element of the structure must be an integer");
      }




      ddl_n = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt;





      meth_dfc_2D.dfc_2D.ddl_n = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 6)
        {
          meth_dfc_2D.dfc_2D.ddl_n[index2] = ddl_n[index2] - 1;

        }
      }



      field_index = 7;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 8 element of the structure must be an integer");
      }




      ddl_tt = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt;



      meth_dfc_2D.dfc_2D.ddl_tt = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 7)
        {
          meth_dfc_2D.dfc_2D.ddl_tt[index2] = ddl_tt[index2] - 1;



        }
      }


      field_index = 8;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 9 element of the structure must be an integer");
      }




      dim_d = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;




      meth_dfc_2D.dfc_2D.dim_d = *dim_d;


      field_index = 9;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 10 element of the structure must be an integer");
      }




      ddl_d = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_d;






      meth_dfc_2D.dfc_2D.ddl_d = (int *) malloc(*dim_d * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 9)
        {
          meth_dfc_2D.dfc_2D.ddl_d[index2] = ddl_d[index2] - 1;
        }
      }

      free(sort2);
      free(sort55);
    }



    if ((strcmp(buf, mot3) == 0))
    {

      field_index = 1;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }




      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 2 element of the structure must be an integer\n");
      }






      pr3bis = (int *) mxGetData(field_array_ptr);





      total_num_of_elements2 = 1;


      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {
        if (field_index == 1)
        {

          itermax = pr3bis[index2];

          meth_dfc_2D.dfc_2D.itermax =  itermax;
        }
      }


      field_index = 2;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 3 element of the structure must be an integer");
      }




      pr5 = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      sort55 = (int*) malloc(1 * 1 * sizeof(int));


      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 2)
        {
          sort55[index2] = pr5[index2];

          chat = sort55[index2];
          meth_dfc_2D.dfc_2D.chat = chat;




        }
      }


      field_index = 3;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 4 element of the structure must be a DOUBLE");
      }


      if (field_index == 3)  J1 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = mrows1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      meth_dfc_2D.dfc_2D.J1 = (double *) malloc(mrows1 * sizeof(double));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 3)
        {
          meth_dfc_2D.dfc_2D.J1[index2] = J1[index2];


        }
      }



      field_index = 4;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 5 element of the structure must be an integer");
      }




      dim_tt = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;


      meth_dfc_2D.dfc_2D.dim_tt = *dim_tt;



      field_index = 5;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 6 element of the structure must be an integer");
      }




      ddl_n = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt;





      meth_dfc_2D.dfc_2D.ddl_n = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 5)
        {
          meth_dfc_2D.dfc_2D.ddl_n[index2] = ddl_n[index2] - 1;

        }
      }



      field_index = 6;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 7 element of the structure must be an integer");
      }




      ddl_tt = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt;



      meth_dfc_2D.dfc_2D.ddl_tt = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 6)
        {
          meth_dfc_2D.dfc_2D.ddl_tt[index2] = ddl_tt[index2] - 1;



        }
      }


      field_index = 7;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 8 element of the structure must be an integer");
      }




      dim_d = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;




      meth_dfc_2D.dfc_2D.dim_d = *dim_d;


      field_index = 8;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 9 element of the structure must be an integer");
      }




      ddl_d = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_d;






      meth_dfc_2D.dfc_2D.ddl_d = (int *) malloc(*dim_d * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 8)
        {
          meth_dfc_2D.dfc_2D.ddl_d[index2] = ddl_d[index2] - 1;
        }
      }

      free(sort55);
    }


    if ((strcmp(buf, mot7) == 0))
    {

      field_index = 1;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 2 element of the structure must be a DOUBLE");
      }

      if (field_index == 2) pr2 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = 1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);

      sort2 = (double*) malloc(1 * 1 * sizeof(double));



      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 2)
        {


          sort2[index2] = pr2[index2];

          tol = sort2[index2];
          meth_dfc_2D.dfc_2D.tol = tol;



        }
      }


      field_index = 2;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 3 element of the structure must be an integer");
      }




      pr5 = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      sort55 = (int*) malloc(1 * 1 * sizeof(int));


      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 2)
        {
          sort55[index2] = pr5[index2];

          chat = sort55[index2];
          meth_dfc_2D.dfc_2D.chat = chat;




        }
      }


      field_index = 3;

      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }

      if (category != mxDOUBLE_CLASS)
      {
        mexPrintf("The 4 element of the structure must be a DOUBLE");
      }


      if (field_index == 3)  J1 = mxGetPr(field_array_ptr);


      total_num_of_elements2 = mrows1;


      mrows = mxGetM(field_array_ptr);
      mcols = mxGetN(field_array_ptr);


      meth_dfc_2D.dfc_2D.J1 = (double *) malloc(mrows1 * sizeof(double));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 3)
        {
          meth_dfc_2D.dfc_2D.J1[index2] = J1[index2];


        }
      }



      field_index = 4;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 5 element of the structure must be an integer");
      }




      dim_tt = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;


      meth_dfc_2D.dfc_2D.dim_tt = *dim_tt;



      field_index = 5;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 6 element of the structure must be an integer");
      }




      ddl_n = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt;





      meth_dfc_2D.dfc_2D.ddl_n = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 5)
        {
          meth_dfc_2D.dfc_2D.ddl_n[index2] = ddl_n[index2] - 1;

        }
      }



      field_index = 6;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 7 element of the structure must be an integer");
      }




      ddl_tt = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_tt;



      meth_dfc_2D.dfc_2D.ddl_tt = (int *) malloc(*dim_tt * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 6)
        {
          meth_dfc_2D.dfc_2D.ddl_tt[index2] = ddl_tt[index2] - 1;



        }
      }


      field_index = 7;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 8 element of the structure must be an integer");
      }




      dim_d = mxGetData(field_array_ptr);


      total_num_of_elements2 = 1;




      meth_dfc_2D.dfc_2D.dim_d = *dim_d;


      field_index = 8;
      field_array_ptr = mxGetFieldByNumber(prhs[4],
                                           index,
                                           field_index);


      if (field_array_ptr == NULL)
        mexPrintf("\tEmpty Field\n");
      else
      {
        category = mxGetClassID(field_array_ptr);
      }


      if (category != mxINT32_CLASS)
      {
        mexPrintf("The 9 element of the structure must be an integer");
      }




      ddl_d = (int *) mxGetData(field_array_ptr);


      total_num_of_elements2 = *dim_d;






      meth_dfc_2D.dfc_2D.ddl_d = (int *) malloc(*dim_d * sizeof(int));

      for (index2 = 0; index2 < total_num_of_elements2; index2++)
      {

        if (field_index == 8)
        {
          meth_dfc_2D.dfc_2D.ddl_d[index2] = ddl_d[index2] - 1;
        }
      }

      free(sort55);
    }



    printf("we enter in dfc_2D_solver using the %s method \n\n", buf);

    if (strcmp(buf, mot1) == 0)
    {
      toto = dfc_2D_solver(vec, q, &mrows1, &meth_dfc_2D, z, w);
    }
    else if (strcmp(buf, mot2) == 0)
      toto = dfc_2D_solver(vec, q, &mrows1, &meth_dfc_2D, z, w);
    else if (strcmp(buf, mot3) == 0)
      toto = dfc_2D_solver(vec, q, &mrows1, &meth_dfc_2D, z, w);
    else if (strcmp(buf, mot7) == 0)
      toto = dfc_2D_solver(vec, q, &mrows1, &meth_dfc_2D, z, w);
    /*   else if (strcmp(buf, mot5) == 0)
     toto = dfc_2D_solver(vec, q, &mrows1, &meth_dfc_2D, z, w);*/
    else printf("Warning : Unknown solving method : %s\n", buf);

    *info = toto;





    free(meth_dfc_2D.dfc_2D.J1);
    free(meth_dfc_2D.dfc_2D.ddl_n);
    free(meth_dfc_2D.dfc_2D.ddl_tt);
    free(meth_dfc_2D.dfc_2D.ddl_d);


  }
}
Ejemplo n.º 15
0
void mexFunction(
        int nlhs,
        mxArray *plhs[],
        int nrhs,
        const mxArray *prhs[]
        ) {

    enum INPUTS {
        I_FACE = 0,
        I_NORMALF,
        I_NVERT,
        I_LAST
    };

    if (nrhs != I_LAST) {
        mexErrMsgTxt("Only 3 input arguments allowed.");
    } else if (nlhs != 1) {
        mexErrMsgTxt("Only 1 output arguments allowed.");
    } 

    if (mxGetM(prhs[I_FACE]) != 3){
        mexErrMsgTxt("Error with face array width");
    }

    if (mxGetM(prhs[I_NORMALF]) != 3){
        mexErrMsgTxt("Error with normal array width");
    }
    
    //mexPrintf("M = %d, N = %d",)
    
    if (mxGetM(prhs[I_NVERT]) != 1 || mxGetN(prhs[I_NVERT]) != 1 ){
        mexErrMsgTxt("nvert should be scalar");
    }

    
//    normal = zeros(3,nvert);
//for i=1:nface
//    f = face(:,i);
//    for j=1:3
//        normal(:,f(j)) = normal(:,f(j)) + normalf(:,i);
//    end
//end
    
    int nvert = mxGetScalar(prhs[I_NVERT]);
    int nface = mxGetN(prhs[I_FACE]);
    mxArray *normal = mxCreateDoubleMatrix(3, nvert, mxREAL);
    double *pNormal = mxGetPr(normal);
    double* pFaces = mxGetPr(prhs[I_FACE]);
    double* pNormalF = mxGetPr(prhs[I_NORMALF]);
    double f[3];
    
    for (int i = 0; i < nface; i++) {
        memcpy(&f, &pFaces[i*3],3*sizeof(double));
        //mexPrintf("f = %d %d %d\n", int(f[0]),int(f[1]),int(f[2]));
        for (int j = 0; j < 3; j++) {
            for (int l = 0; l < 3; l++) {
                int nIndex = floor(f[j]-1)*3 + l;
                char err[1000];
                if (nIndex > nvert*3) {
                    sprintf(err,"damn: nIndex = %d, f(j) = %d, i=%d, j=%d l=%d", nIndex, int(f[j]),i,j,l);
                    mexErrMsgTxt(err);
                }
                pNormal[nIndex] += pNormalF[i*3+l];
            }
        }
   }
    plhs[0] = normal;
}
/*============================================================*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  float *image, *tmp;
  int nX, nY;
  ccLabelStruct **label;
  int ixy;
  int numComp, t;
  double minTarget; /* 0.001 = boxes02-add.pgm */
  double *target;
  float debug = 0;

  /* for sparse array */
  mwIndex *rowPtr, *colInfo;
  double *data;
  int rows, cols;

  int sparseFlag = 0;

  RanTimeSeed;

  /*mexPrintf("nlhs:%d nrhs: %d\n",nlhs,nrhs);*/

  /* check for the required input arguments */
  if( nrhs < 2 )
    mexErrMsgTxt( "Input expected: <symmetric-positive-array-for-cca> <affty-threshold> <1-for-debug>" );

  /* get the symmetric matrix */
  /*mex2float( prhs[0], &target, &nX, &nY);*/
  nX = mxGetN(prhs[0]); /* cols */ 
  cols = nX;

  nY = mxGetM(prhs[0]); /* rows */
  rows = nY;
  
  mexPrintf("size: %d %d\n",nX,nY);

  if (mxIsSparse(prhs[0])) {
    sparseFlag = 1;
    mexPrintf("Affy matrix Sparse? : %d\n",sparseFlag);
  }

  if (sparseFlag) {
    mwIndex *jc;

    data    = mxGetPr(prhs[0]); /* pointer to real data */
    rowPtr  = mxGetIr(prhs[0]); /* pointer to row info */
    colInfo = mxGetJc(prhs[0]); /* pointer to col info */
    jc = mxGetJc(prhs[0]);

    /*
    for (ixy=0; ixy < mxGetN(prhs[0]); ixy++) {
      mexPrintf("rowBouMain %d (%d %d) \n",ixy,jc[ixy+1],colInfo[ixy+1]);    
    }

    analyze_sparse(prhs[0]);
    */
  } else {
    target = (double *)mxGetPr(prhs[0]);
  }


  /* get the threshold */
  minTarget = (double) mxGetScalar(prhs[1]);

  /* check for debug flag */
  if (nrhs == 3) {
    debug = mxGetScalar(prhs[2]);
  }

  if (debug)
    mexPrintf("Affty threshold: %2.3e\n",minTarget);

  /* set up empty labels */
  grabByteMemory((char **) &label,sizeof(ccLabelStruct *) * nX,"label");
  for (ixy=0;ixy < nX; ixy++)
    label[ixy] = NULL;

  if (debug) {
    mexPrintf("Computing connected components....");
  }

  if (sparseFlag) {
    connectSymmetricSparse(label,rowPtr,colInfo,data, minTarget, nX, nY);
  } else {
    connectSymmetricDbl(label, target, minTarget, nX, nY);
  }

  if (debug) {
    mexPrintf("done\n");
  }

  /* yalla edition */
  /*
  if (debug) {
    mexPrintf("Pruning small or weak connected components....");
  }
  pruneLabelComp(label, nX, 1, 1, 0);
  */

  if (debug) {
    mexPrintf("done\n");
  }

  /* component count */
  numComp = countLabelComp(label, nX, 1);
  if (debug) {
    mexPrintf("Found %d components.\n\n", numComp);
  }

  /*
  if (numComp > 0)
    printMarkovLabels(label,nX);
  */

  /* return the labels to matlab */
  if (nlhs > 0)
    labels2mex(label, &plhs[0], nX ); 
  if (nlhs > 1)
    {
      double *pout;
      plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
      pout = mxGetPr(plhs[1]);
      *pout = (double) numComp;
    }
  /* free up memory. */
  /* target is a pointer to prhs[0]. so no need to free. */
  /*utilFree( (void **)&target );*/
  utilFree((void **)label);
  /*
  for (ixy = 0; ixy < nX; ixy++)
    free(label[ixy]);
  */

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

{    mxArray  *blk_cell_pr;  
     double   *Avec, *idxstarttmp, *nzlistAtmp, *permAtmp, *U, *V, *schur;
     double   *blksizetmp, *Utmp, *Vtmp, *schurcol, *nzschur, *P;  
     mwIndex  *irP, *jcP, *irU, *jcU, *irV, *jcV;
     int      *idxstart, *colm, *permA, *nzlistAr, *nzlistAc;
     int      *nzlistAi, *nzlistAj, *blksize, *cumblksize, *blknnz, *blkidx; 

     mwIndex  subs[2];
     mwSize   nsubs=2; 
     int      index, colend, type, isspU, isspV, numblk, nzP, existP; 
     int      len, row, col, nU, nV, n, m, m1, idx1, idx2, l, k, nsub, n1, n2, opt, opt2;
     int      kstart, kend, rb, cb, cblk, colcb, count; 
     double   tmp; 

/* CHECK THE DIMENSIONS */

    if (nrhs < 10) {
       mexErrMsgTxt(" mexschur: must have at least 10 inputs"); }
    if (!mxIsCell(prhs[0])) {
       mexErrMsgTxt("mexschur: 1ST input must be the cell array blk"); }  
    if (mxGetM(prhs[0])>1) {
       mexErrMsgTxt("mexschur: blk can have only 1 row"); }  
    subs[0] = 0; 
    subs[1] = 1;
    index = mxCalcSingleSubscript(prhs[0],nsubs,subs); 
    blk_cell_pr = mxGetCell(prhs[0],index); 
    numblk  = mxGetN(blk_cell_pr);
    blksizetmp = mxGetPr(blk_cell_pr); 
    blksize = mxCalloc(numblk,sizeof(int)); 
    for (k=0; k<numblk; k++) { 
        blksize[k] = (int)blksizetmp[k];
    }
/**** get pointers ****/    

    Avec = mxGetPr(prhs[1]); 
    if (!mxIsSparse(prhs[1])) { 
       mexErrMsgTxt("mexschur: Avec must be sparse"); }
    idxstarttmp = mxGetPr(prhs[2]);  
    len = MAX(mxGetM(prhs[2]),mxGetN(prhs[2])); 
    idxstart = mxCalloc(len,sizeof(int)); 
    for (k=0; k<len; k++) { 
        idxstart[k] = (int)idxstarttmp[k]; 
    }
    nzlistAtmp = mxGetPr(prhs[3]); 
    len = mxGetM(prhs[3]);
    nzlistAi = mxCalloc(len,sizeof(int)); 
    nzlistAj = mxCalloc(len,sizeof(int)); 
    for (k=0; k<len; k++) { 
        nzlistAi[k] = (int)nzlistAtmp[k] -1; /* -1 to adjust for matlab index */
        nzlistAj[k] = (int)nzlistAtmp[k+len] -1; 
    }
    permAtmp = mxGetPr(prhs[4]); 
    m1 = mxGetN(prhs[4]); 
    permA = mxCalloc(m1,sizeof(int)); 
    for (k=0; k<m1; k++) {
        permA[k] = (int)permAtmp[k]-1; /* -1 to adjust for matlab index */
    }
    U = mxGetPr(prhs[5]);  nU = mxGetM(prhs[5]); 
    isspU = mxIsSparse(prhs[5]); 
    if (isspU) { irU = mxGetIr(prhs[5]); jcU = mxGetJc(prhs[5]); }
    V = mxGetPr(prhs[6]);  nV = mxGetM(prhs[6]); 
    isspV = mxIsSparse(prhs[6]);
    if (isspV) { irV = mxGetIr(prhs[6]); jcV = mxGetJc(prhs[6]); }
    if ((isspU & !isspV) || (!isspU & isspV)) { 
       mexErrMsgTxt("mexschur: U,V must be both dense or both sparse"); 
    }
    colend = (int)*mxGetPr(prhs[7]); 
    type   = (int)*mxGetPr(prhs[8]); 

    schur = mxGetPr(prhs[9]); 
    m = mxGetM(prhs[9]);    
    if (m!= m1) {
       mexErrMsgTxt("mexschur: schur and permA are not compatible"); }
    if (nrhs == 11) {
       P=mxGetPr(prhs[10]); irP=mxGetIr(prhs[10]); jcP=mxGetJc(prhs[10]);    
       existP = 1;
    } else {
       existP = 0; 
    }
/************************************
* output 
************************************/

    plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); 
    nzschur = mxGetPr(plhs[0]); 
    if (nlhs==2) {
       nzP = (int) (0.2*m*m+5); 
       plhs[1] = mxCreateSparse(m,colend,nzP,mxREAL); 
       P=mxGetPr(plhs[1]); irP=mxGetIr(plhs[1]); jcP=mxGetJc(plhs[1]); 
       jcP[0] = 0; 
    }
/************************************
* initialization 
************************************/
    if (isspU & isspV) { 
       cumblksize = mxCalloc(numblk+1,sizeof(int)); 
       blknnz = mxCalloc(numblk+1,sizeof(int)); 
       cumblksize[0] = 0; blknnz[0] = 0; 
       n1 = 0; n2 = 0; 
       for (k=0; k<numblk; ++k) {
           nsub = blksize[k];
           n1 += nsub;  
           n2 += nsub*nsub;  
           cumblksize[k+1] = n1; 
           blknnz[k+1] = n2;  }
       if (nU != n1 || nV != n1) { 
          mexErrMsgTxt("mexschur: blk and dimension of U not compatible"); }
       Utmp = mxCalloc(n2,sizeof(double)); 
       vec(numblk,cumblksize,blknnz,U,irU,jcU,Utmp); 
       Vtmp = mxCalloc(n2,sizeof(double)); 
       vec(numblk,cumblksize,blknnz,V,irV,jcV,Vtmp); 
       blkidx = mxCalloc(nU,sizeof(int));
       for (l=0; l<numblk; l++) {  
 	   kstart=cumblksize[l]; kend=cumblksize[l+1];
           for (k=kstart; k<kend; k++) { blkidx[k] = l; }           
       }
       nzlistAc = mxCalloc(len,sizeof(int)); 
       nzlistAr = mxCalloc(len,sizeof(int)); 
       for (k=0; k<len; k++) {
          rb = nzlistAi[k]; 
	  cb = nzlistAj[k]; 
	  cblk = blkidx[cb]; colcb = cumblksize[cblk];             
          nzlistAc[k] = blknnz[cblk]+(cb-colcb)*blksize[cblk]-colcb;
          nzlistAr[k] = blknnz[cblk]+(rb-colcb)*blksize[cblk]-colcb;  
       }
    }
/************************************
* compute schur(i,j)
************************************/

    colm = mxCalloc(colend,sizeof(int));     
    for (k=0; k<colend; k++) { colm[k] = permA[k]*m; } 

    n = nU; 
    if      (type==1 & !isspU)  { opt=1; }
    else if (type==0 & !isspU)  { opt=3; } 
    else if (type==1 &  isspU)  { opt=2; }
    else if (type==0 &  isspU)  { opt=4; }

    /*************************************/
    schurcol = mxCalloc(colend,sizeof(double)); 
    count = 0;
 
    for (col=0; col<colend; col++) { 
	if (existP) {
	   setvec(col,schurcol,0.0); 
           for (k=jcP[col]; k<jcP[col+1]; k++) { schurcol[irP[k]]=1.0;}
	} else {
	   setvec(col,schurcol,1.0); 
	}
        if (opt==1) { 
 	   schurij1(n,Avec,idxstart,nzlistAi,nzlistAj,U,col,schurcol); 
        } else if (opt==3) { 
           schurij3(n,Avec,idxstart,nzlistAi,nzlistAj,U,V,col,schurcol);
	} else if (opt==2) {
           schurij2(Avec,idxstart,nzlistAi,nzlistAj,Utmp, \
		    nzlistAr,nzlistAc,cumblksize,blkidx,col,schurcol); 
	} else if (opt==4) {
           schurij4(Avec,idxstart,nzlistAi,nzlistAj,Utmp,Vtmp, \
	            nzlistAr,nzlistAc,cumblksize,blkidx,col,schurcol);  
	}
        for (row=0; row<=col; row++) {
	    if (schurcol[row] != 0) {
	       if (count<nzP & nlhs==2) { jcP[col+1]=count+1; irP[count]=row; P[count]=1; }
	       count++; 
   	       idx1 = permA[row]+colm[col]; 
               idx2 = permA[col]+colm[row]; 
               schur[idx1] += schurcol[row];
               schur[idx2] = schur[idx1]; 
            }
	}
    }
    
    nzschur[0] = count;

    mxFree(blksize); mxFree(nzlistAi); mxFree(nzlistAj); 
    mxFree(permA);   mxFree(idxstart); mxFree(schurcol); 
    if (isspU) { 
       mxFree(Utmp);     mxFree(Vtmp); 
       mxFree(nzlistAc); mxFree(nzlistAr); 
       mxFree(blknnz); mxFree(cumblksize); mxFree(blkidx); 
    } 
return;
}
/*============================================================*/
void mexFunction_float( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  float *image, *tmp;
  int nX, nY;
  ccLabelStruct **label;
  int ixy;
  int numComp, t;
  float minTarget; /* 0.001 = boxes02-add.pgm */
  float *target;
  float debug = 0;

  RanTimeSeed;

  /*mexPrintf("nlhs:%d nrhs: %d\n",nlhs,nrhs);*/

  /* check for the required input arguments */
  if( nrhs < 2 )
    mexErrMsgTxt( "Input expected: <symmetric-positive-array-for-cca> <affty-threshold> <1-for-debug>" );

  /* get the symmetric matrix */
  mex2float( prhs[0], &target, &nX, &nY);
  /*mexPrintf("size: %d %d\n",nX,nY);*/

  /* get the threshold */
  minTarget = mxGetScalar(prhs[1]);
  if (nrhs == 3) {
    debug = mxGetScalar(prhs[2]);
  }

  if (debug)
    mexPrintf("Affty threshold: %2.3e\n",minTarget);

  /* set up empty labels */
  grabByteMemory((char **) &label,sizeof(ccLabelStruct *) * nX,"label");
  for (ixy=0;ixy < nX; ixy++)
    label[ixy] = NULL;

  if (debug) {
    mexPrintf("Computing connected components....");
  }
  connectSymmetric(label, target, minTarget, nX, nY);
  if (debug) {
    mexPrintf("done\n");
  }

  if (debug) {
    mexPrintf("Pruning small or weak connected components....");
  }
  pruneLabelComp(label, nX, 1, 1, 0);
  if (debug) {
    mexPrintf("done\n");
  }

  /* component count */
  numComp = countLabelComp(label, nX, 1);
  if (debug) {
    mexPrintf("Found %d components.\n\n", numComp);
  }

  /*
  if (numComp > 0)
    printMarkovLabels(label,nX);
  */

  /* return the labels to matlab */
  if (nlhs > 0)
    labels2mex(label, &plhs[0], nX ); 
  if (nlhs > 1)
    {
      double *pout;
      plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
      pout = mxGetPr(plhs[1]);
      *pout = (double) numComp;
    }
  /* free up memory */
  utilFree( (void **)&target );
  utilFree((void **)label);
  /*
  for (ixy = 0; ixy < nX; ixy++)
    free(label[ixy]);
  */

}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,const mxArray *prhs[])
{
	//lhs: left-hand-side, means outputs. rhs: right-hand-side, means inputs.
	const mwSize *dims1, *dims2;
	mwSize ndim1, ndim2;
	usb_dev_handle *hdl;
	int configuration, result;

	//check the number of input and output
	if (nrhs != 2)
	{
		mexErrMsgTxt("result = libusb_usb_set_configuration(usb_dev_hdl, configuration): need 2 inputs, no more no less.");
	}
	if (nlhs > 1)
	{
		mexErrMsgTxt("result = libusb_usb_set_configuration(usb_dev_hdl, configuration): only 1 output, no more no less.");
	}

	//check if the inputs are scalar
	ndim1 = mxGetNumberOfDimensions(prhs[0]);
	dims1 = mxGetDimensions(prhs[0]);
	ndim2 = mxGetNumberOfDimensions(prhs[1]);
	dims2 = mxGetDimensions(prhs[1]);
	if (ndim1 != 2 || ndim2 != 2 || dims1[0]*dims1[1] > 1 || dims2[0]*dims2[1] > 1)
	{
		mexErrMsgTxt("result = libusb_usb_set_configuration(usb_dev_hdl, configuration) input should be scalar");
	}
	if(mxGetClassID(prhs[0]) != mxUINT64_CLASS)
	{
		mexErrMsgTxt("Function first input should be unsigned 64 bit int: result = libusb_usb_set_configuration(usb_dev_hdl, configuration)");
	}
	if(mxGetClassID(prhs[1]) !=  mxINT32_CLASS)
	{
		mexErrMsgTxt("Function second input should be 32 bit int: result = libusb_usb_set_configuration(usb_dev_hdl, configuration)");
	}


	//usb_init(); /* initialize the library */
    //usb_find_busses(); /* find all busses */
    //usb_find_devices(); /* find all connected devices */

	hdl = (usb_dev_handle*)(*(U64*)(mxGetData(prhs[0])));
	configuration = *(int*)(mxGetData(prhs[1]));

	plhs[0] = mxCreateNumericArray(2, dims1, mxINT32_CLASS, mxREAL);

	if(hdl == NULL)
	{
		mexPrintf("Device handler is null and cannot set configuration.\r\n");
		*(int*)mxGetData(plhs[0]) = -1;
	}
	else
	{
		result = usb_set_configuration(hdl,configuration);
		if(result < 0)
			mexPrintf("Error when setting device 0x%x, configuration: %d,  return value: %d.\r\n Error string: %s\r\n",hdl, configuration, result, usb_strerror());
		else
			mexPrintf("Device 0x%x configuration %d set successfully. return value: %d.\r\n",hdl,configuration,result);

		*(int*)mxGetData(plhs[0]) = result;
	}
}
Ejemplo n.º 20
0
/* The matlab mex function */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
    HRESULT hr;
	
   	// Get pointer to Kinect handles
	unsigned __int64 *MXadress;
    if(nrhs==0) {
        mexErrMsgTxt("Give Pointer to Kinect as input");
    }
    MXadress = (unsigned __int64*)mxGetData(prhs[0]);
    int depthwidth=(int)MXadress[7];
	int depthheight=(int)MXadress[8];

	// Initialize Output Skeleton Array
    int Jdimsc[2];
    Jdimsc[0]=200; Jdimsc[1]=6;
    plhs[0] = mxCreateNumericArray(2, Jdimsc, mxDOUBLE_CLASS, mxREAL);
    double *Pos;
    Pos = mxGetPr(plhs[0]);
	
    NUI_SKELETON_FRAME SkeletonFrame;


	// Wait for a Skeleton_Frame to arrive	
	hr = NuiSkeletonGetNextFrame( 200, &SkeletonFrame );
    if( FAILED( hr ) )
	{ 
		printf("Failed to get Frame\r\n");
	} 
	else
	{
		// Check if there is a Skeleton found
        bool NoSkeletonFound = true;
        for( int i = 0 ; i < NUI_SKELETON_COUNT ; i++ )
        {
            if( SkeletonFrame.SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED )
            {
                NoSkeletonFound = false;
            }
        }
        if( NoSkeletonFound )  { return; }
      
        // Smooth the skeleton data
        NuiTransformSmooth(&SkeletonFrame,NULL);

		// Copy Skeleton points to output array
        int r=0;
        for( int i = 0 ; i < NUI_SKELETON_COUNT ; i++ )
        {
            if( SkeletonFrame.SkeletonData[i].eTrackingState == NUI_SKELETON_TRACKED )
            {
                NUI_SKELETON_DATA * pSkel = &SkeletonFrame.SkeletonData[i];
                int j;
                float fx=0,fy=0;
                for (j = 0; j < NUI_SKELETON_POSITION_COUNT; j++) 
                { 
                    Pos[j+r]=i+1;
                    Pos[j+r+Jdimsc[0]]=pSkel->SkeletonPositions[j].x;
                    Pos[j+r+Jdimsc[0]*2]=pSkel->SkeletonPositions[j].y;
                    Pos[j+r+Jdimsc[0]*3]=pSkel->SkeletonPositions[j].z;    
                    NuiTransformSkeletonToDepthImage( pSkel->SkeletonPositions[j], &fx, &fy ); 
                    Pos[j+r+Jdimsc[0]*4] = (double) ( fx * depthwidth + 0.5f ); 
                    Pos[j+r+Jdimsc[0]*5] = (double) ( fy * depthheight + 0.5f ); 

                }
                r+=NUI_SKELETON_POSITION_COUNT;
            }
        }
    }
}
Ejemplo n.º 21
0
void mexFunction( int nl, mxArray *pl[], int nr, const mxArray *pr[] )
{
  char action[1024]; if(!nr) mexErrMsgTxt("Inputs expected.");
  mxGetString(pr[0],action,1024); nr--; pr++;
  char *endptr; JsonValue val; JsonAllocator allocator;
  if( nl>1 ) mexErrMsgTxt("One output expected.");
  
  if(!strcmp(action,"convert")) {
    if( nr!=1 ) mexErrMsgTxt("One input expected.");
    if( mxGetClassID(pr[0])==mxCHAR_CLASS ) {
      // object = mexFunction( string )
      char *str = mxArrayToStringRobust(pr[0]);
      int status = jsonParse(str, &endptr, &val, allocator);
      if( status != JSON_OK) mexErrMsgTxt(jsonStrError(status));
      pl[0] = json(val); mxFree(str);
    } else {
      // string = mexFunction( object )
      ostrm S; S << std::setprecision(10); json(S,pr[0]);
      pl[0]=mxCreateStringRobust(S.str().c_str());
    }
    
  } else if(!strcmp(action,"split")) {
    // strings = mexFunction( string, k )
    if( nr!=2 ) mexErrMsgTxt("Two input expected.");
    char *str = mxArrayToStringRobust(pr[0]);
    int status = jsonParse(str, &endptr, &val, allocator);
    if( status != JSON_OK) mexErrMsgTxt(jsonStrError(status));
    if( val.getTag()!=JSON_ARRAY ) mexErrMsgTxt("Array expected");
    siz i=0, t=0, n=length(val), k=(siz) mxGetScalar(pr[1]);
    k=(k>n)?n:(k<1)?1:k; k=ceil(n/ceil(double(n)/k));
    pl[0]=mxCreateCellMatrix(1,k); ostrm S; S<<std::setprecision(10);
    for(auto o:val) {
      if(!t) { S.str(std::string()); S << "["; t=ceil(double(n)/k); }
      json(S,&o->value); t--; if(!o->next) t=0; S << (t ? "," : "]");
      if(!t) mxSetCell(pl[0],i++,mxCreateStringRobust(S.str().c_str()));
    }
    
  } else if(!strcmp(action,"merge")) {
    // string = mexFunction( strings )
    if( nr!=1 ) mexErrMsgTxt("One input expected.");
    if(!mxIsCell(pr[0])) mexErrMsgTxt("Cell array expected.");
    siz n = mxGetNumberOfElements(pr[0]);
    ostrm S; S << std::setprecision(10); S << "[";
    for( siz i=0; i<n; i++ ) {
      char *str = mxArrayToStringRobust(mxGetCell(pr[0],i));
      int status = jsonParse(str, &endptr, &val, allocator);
      if( status != JSON_OK) mexErrMsgTxt(jsonStrError(status));
      if( val.getTag()!=JSON_ARRAY ) mexErrMsgTxt("Array expected");
      for(auto j:val) json(S,&j->value) << (j->next ? "," : "");
      mxFree(str); if(i<n-1) S<<",";
    }
    S << "]"; pl[0]=mxCreateStringRobust(S.str().c_str());
    
  } else mexErrMsgTxt("Invalid action.");
}
Ejemplo n.º 22
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    tt_buf* buffer;
    int timetagger;
    uint64_t datapoints;

    
    uint64_t total;	//The total amount of data in the buffer
    uint64_t i;		//Temporary loop variable
    uint64_t j=0;
    double *channels=NULL, *timebins;
    
    if (nrhs == 2 && mxIsDouble(prhs[0]) && mxIsDouble(prhs[1])) {
        timetagger = (int)mxGetScalar(prhs[0]);
        datapoints = (uint64_t)mxGetScalar(prhs[1]);
    } else {
        mexErrMsgTxt("Inputs:\n\tTime tag buffer to dump from.\n\tNumber of datapoints to dump.\nOutputs:\n\tArray of time stamps\n\tArray of corresponding channels");
        return;
    }
    
    if (datapoints==0) {
        mexErrMsgTxt("No datapoints were specified!");
        return;
    }
    
    buffer = tt_open(timetagger);
    if (buffer) {
        total = tt_datapoints(buffer);
        
        if (datapoints > total) {
            mexPrintf("Warning: Not enough datapoints! Only reading saved datapoints!\n");
            datapoints = total;
        }
        if (datapoints > tt_maxdata(buffer)) {
            mexPrintf("Warning: There are not enough datapoints saved. Only reading to end of buffer!\n");
            datapoints = tt_maxdata(buffer);    //Only read up to the entire buffer
        }

        
        if (nlhs>=2) {
            plhs[0] = mxCreateDoubleMatrix(1,(int)datapoints,mxREAL);
            channels = mxGetPr(plhs[0]);
            plhs[1] = mxCreateDoubleMatrix(1,(int)datapoints,mxREAL);
            timebins = mxGetPr(plhs[1]);
        } else {
            plhs[0] = mxCreateDoubleMatrix(1,(int)datapoints,mxREAL);
            timebins = mxGetPr(plhs[0]);
        }
        
        //Read the array of data
        if (isnan(tt_resolution(buffer))) {
            mexPrintf("Warning: Resolution unset. Returning raw data.\n");
            if (channels) {
                for (i=total-datapoints;i<total;i++) {
                    channels[j] = (double)tt_channel(buffer,i)+1.0;	//Matlab has this weird off by one thing...
                    timebins[j] = (double)tt_tag(buffer,i);
                    j++;
                }
            } else {
                for (i=total-datapoints;i<total;i++) {
                    timebins[j] = (double)tt_tag(buffer,i);
                    j++;
                }
            }
        } else {
            if (channels) {
                for (i=total-datapoints;i<total;i++) {
                    channels[j] = (double)tt_channel(buffer,i)+1.0;	//Matlab has this weird off by one thing...
                    timebins[j] = (double)tt_tag(buffer,i)*tt_resolution(buffer);
                    j++;
                }
            } else {
                for (i=total-datapoints;i<total;i++) {
                    timebins[j] = (double)tt_tag(buffer,i)*tt_resolution(buffer);
                    j++;
                }
            }
        }
        
        
        tt_close(buffer);
        
    } else {
        mexErrMsgTxt("Unable to connect to time tag buffer! Is all necessary software running?");
    }

}
//Gateway routine
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//Read input arguments
	char outputFormat[10];
	char outputVarName[MAXVARNAMESIZE];
	int	outputVarSampsPerChan;
	double timeout;
	int numSampsPerChan;
	bool outputData; //Indicates whether to return an outputData argument
	mxClassID outputDataClass;
	uInt32 bufSize;
	bool writeDigitalLines;
	uInt32 bytesPerChan=0;
	TaskHandle taskID, *taskIDPtr;
	int32 status;

	//Get TaskHandle
	taskIDPtr = (TaskHandle*)mxGetData(mxGetProperty(prhs[0],0, "taskID"));
	taskID = *taskIDPtr;

	//Determine if this is a buffered read operation
	status = DAQmxGetBufInputBufSize(taskID, &bufSize);
	if (status)
		handleDAQmxError(status, "DAQmxGetBufInputBufSize");

	//Handle input arguments
	if ((nrhs < 2) || mxIsEmpty(prhs[1]) || mxIsInf(mxGetScalar(prhs[1])))
	{
		if (bufSize==0)
			numSampsPerChan = 1;
		else
			numSampsPerChan = DAQmx_Val_Auto;
	}
	else
		numSampsPerChan = (int) mxGetScalar(prhs[1]);
	
	if ((nrhs < 3) || mxIsEmpty(prhs[2]))
	{
		//Automatic determination of read type
		bool isLineBased = (bool) mxGetScalar(mxGetProperty(prhs[0],0,"isLineBasedDigital"));		

		if ((bufSize==0) && isLineBased) //This is a non-buffered, line-based Task: return data as a double array
			outputDataClass = mxDOUBLE_CLASS;
		else
		{
			status = DAQmxGetReadDigitalLinesBytesPerChan(taskID,&bytesPerChan); //This actually returns the number of bytes required to represent one sample of Channel data
			if (status)
				handleDAQmxError(status, "DAQmxGetReadDigitalLinesBytesPerChan");

			if (bytesPerChan <= 8)
				outputDataClass = mxUINT8_CLASS;
			else if (bytesPerChan <= 16)
				outputDataClass = mxUINT16_CLASS;
			else if (bytesPerChan <= 32)
				outputDataClass = mxUINT32_CLASS;
			else
				mexErrMsgTxt("It is not currently possible to read integer values from Task with greater than 32 lines per sample value");
		}
	}
	else
	{
		mxGetString(prhs[2], outputFormat, 10);		

		if (_strcmpi(outputFormat,"uint8"))
			outputDataClass = mxUINT8_CLASS;
		else if (_strcmpi(outputFormat,"uint16"))
			outputDataClass = mxUINT16_CLASS;
		else if (_strcmpi(outputFormat,"uint32"))
			outputDataClass = mxUINT32_CLASS;
		else if (_strcmpi(outputFormat,"double"))
			outputDataClass = mxDOUBLE_CLASS;
		else if (_strcmpi(outputFormat,"logical"))
			outputDataClass = mxLOGICAL_CLASS;
		else
			mexErrMsgTxt("The specified 'outputFormat' value (case-sensitive) is not recognized.");
	}

	if ((outputDataClass == mxDOUBLE_CLASS) || (outputDataClass == mxLOGICAL_CLASS))
	{
		writeDigitalLines = true;
		if (bytesPerChan == 0)
		{
			status = DAQmxGetReadDigitalLinesBytesPerChan(taskID,&bytesPerChan); //This actually returns the number of bytes required to represent one sample of Channel data
			if (status)
				handleDAQmxError(status, "DAQmxGetReadDigitalLinesBytesPerChan");
		}			
	}
	else
		writeDigitalLines = false;


	if ((nrhs < 4) || mxIsEmpty(prhs[3]) || mxIsInf(mxGetScalar(prhs[3])))
		timeout = DAQmx_Val_WaitInfinitely;
	else
		timeout = mxGetScalar(prhs[3]);


	if ((nrhs < 5) || mxIsEmpty(prhs[4])) //OutputVarSizeOrName argument
	{
		outputData = true;
		outputVarSampsPerChan = numSampsPerChan; //If value is DAQmx_Val_Auto, then the # of samples available will be queried before allocting array
	}
	else
	{
		outputData = mxIsNumeric(prhs[4]);
		if (outputData)
		{
			if (nlhs < 2)
				mexErrMsgTxt("There must be two output arguments specified if a preallocated MATLAB variable is not specified");
			outputVarSampsPerChan = (int) mxGetScalar(prhs[4]);
		}
		else
			mxGetString(prhs[4], outputVarName, MAXVARNAMESIZE);
	}

	//Determin # of output channels
	uInt32 numChannels; 
	DAQmxGetReadNumChans(taskID, &numChannels); //Reflects number of channels in Task, or the number of channels specified by 'ReadChannelsToRead' property
	
	//Determine output buffer/size (creating if needed)
	mxArray *outputDataBuf, *outputDataBufTrue;
	void *outputDataPtr;

	//float64 *outputDataPtr;
	if (outputData)
	{
		mwSize numRows;

		if (outputVarSampsPerChan == DAQmx_Val_Auto)
		{
			status = DAQmxGetReadAvailSampPerChan(taskID, (uInt32 *)&outputVarSampsPerChan);
			if (status)
			{
				handleDAQmxError(status, "DAQmxGetReadAvailSampPerChan");
				return;
			}
		}
		
		if (writeDigitalLines)
			numRows = (mwSize) (outputVarSampsPerChan * bytesPerChan);
		else
			numRows = (mwSize) outputVarSampsPerChan;
		
		if (outputDataClass == mxDOUBLE_CLASS)
		{
			outputDataBuf = mxCreateNumericMatrix(numRows,numChannels,mxUINT8_CLASS,mxREAL);
			outputDataBufTrue = mxCreateDoubleMatrix(numRows,numChannels,mxREAL);
		}
		else
			outputDataBuf = mxCreateNumericMatrix(numRows,numChannels,outputDataClass,mxREAL);
	}
	else //I don't believe this is working
	{
		outputDataBuf = mexGetVariable("caller", outputVarName);
		outputVarSampsPerChan = mxGetM(outputDataBuf);
		//TODO: Add check to ensure WS variable is of correct class
	}

	outputDataPtr = mxGetData(outputDataBuf);

	//Read data
	int32 numSampsRead;
	int32 numBytesPerSamp;

	switch (outputDataClass)
	{
	case mxUINT8_CLASS:
		status = DAQmxReadDigitalU8(taskID, numSampsPerChan, timeout, fillMode, (uInt8*) outputDataPtr, outputVarSampsPerChan * numChannels, &numSampsRead, NULL);
		break;
	case mxUINT16_CLASS:
		status = DAQmxReadDigitalU16(taskID, numSampsPerChan, timeout, fillMode, (uInt16*) outputDataPtr, outputVarSampsPerChan * numChannels, &numSampsRead, NULL);
		break;
	case mxUINT32_CLASS:
		status = DAQmxReadDigitalU32(taskID, numSampsPerChan, timeout, fillMode, (uInt32*) outputDataPtr, outputVarSampsPerChan * numChannels, &numSampsRead, NULL);
		break;
	case mxLOGICAL_CLASS:
	case mxDOUBLE_CLASS:
		status = DAQmxReadDigitalLines(taskID, numSampsPerChan, timeout, fillMode, (uInt8*) outputDataPtr, outputVarSampsPerChan * numChannels * bytesPerChan, &numSampsRead, &numBytesPerSamp, NULL);
		break;
	default:
		mexErrMsgTxt("There must be two output arguments specified if a preallocated MATLAB variable is not specified");

	}

	//Return output data
	if (!status)
	{
		//mexPrintf("Successfully read %d samples of data\n", numSampsRead);		

		if (outputData)
		{
			if (nlhs > 0)
			{
				if (outputDataClass == mxDOUBLE_CLASS)
				{
					//Convert logical data to double type
					double *outputDataTruePtr = mxGetPr(outputDataBufTrue);
					for (size_t i=0;i < mxGetNumberOfElements(outputDataBuf);i++)	
						*(outputDataTruePtr+i) = (double) *((uInt8 *)outputDataPtr+i);
						
					mxDestroyArray(outputDataBuf);

					plhs[0] = outputDataBufTrue;
				}
				else
					plhs[0] = outputDataBuf;
			}
			else
				mxDestroyArray(outputDataBuf); //If you don't read out, all the reading was done for naught
		}
		else //I don't believe this is working
		{
			mexErrMsgTxt("invalid branch");
			mexPutVariable("caller", outputVarName, outputDataBuf);
			
			if (nlhs > 0) //Return empty value for output data
				plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
		}			

		if (nlhs > 1) //Return number of samples actually read
		{
			double *sampsReadOutput;

			plhs[1] = mxCreateDoubleScalar(0);	
			sampsReadOutput = mxGetPr(plhs[1]);

			*sampsReadOutput = (double)numSampsRead;
		}
	}
	else //Read failed
		handleDAQmxError(status, mexFunctionName());

}
Ejemplo n.º 24
0
/*
 * function [ res ] = graphKernelDelta( edges1, edges2, nodes1, nodes2, lambda, epsilon );
 */
void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] )
{
  // check number of output params
  if( nlhs == 0 ) {
    printf( "%s\n", copyright );
    mexErrMsgTxt( syntax );
    return;
  }
  if( !( nlhs == 1 ) ) {
    int i;
    for( i = 1; i < nlhs; ++i ) {
      plhs[i] = mxCreateDoubleMatrix( 1, 1, mxREAL );
      double* const matPtr = mxGetPr( plhs[i] );
      *matPtr = mxGetNaN();
    }
  }

  // prepare for unsuccessful return
  plhs[0] = mxCreateDoubleMatrix( 1, 1, mxREAL );
  double* const resPtr = mxGetPr( plhs[0] );
  *resPtr = mxGetNaN();

  // check number of input params
  if( !( nrhs == 6 ) ) {
    printf( "found %d parameters\n", nrhs );
    mexErrMsgTxt( syntax );
    return;
  }

  // setup constants
  #define edges1_ ( prhs[ 0 ] )
  #define edges2_ ( prhs[ 1 ] )
  #define nodes1_ ( prhs[ 2 ] )
  #define nodes2_ ( prhs[ 3 ] )
  #define lambda_ ( prhs[ 4 ] )
  #define epsilon_ ( prhs[ 5 ] )
  const double* const edges1 = (double *) mxGetPr( edges1_ );
  const double* const edges2 = (double *) mxGetPr( edges2_ );
  const double* const nodes1 = (double *) mxGetPr( nodes1_ );
  const double* const nodes2 = (double *) mxGetPr( nodes2_ );
  const double lambda = *( (double *) mxGetPr( lambda_ ) );
  const double epsilon = *( (double *) mxGetPr( epsilon_ ) );
  const int n1 = (int)( mxGetM( nodes1_ ) );
  const int n2 = (int)( mxGetM( nodes2_ ) );

  // check input
  if( !( mxGetN( nodes1_ ) == 1 && mxGetN( nodes2_ ) == 1 ) ) {
    printf( "second dimension of nodes must be 1\n" );
    mexErrMsgTxt( syntax );
    return;
  }
  if( !( mxGetM( edges1_ ) == n1 && mxGetN( edges1_ ) == n1 ) ) {
    printf( "edges1 must be square\n" );
    mexErrMsgTxt( syntax );
    return;
  }
  if( !( mxGetM( edges2_ ) == n2 && mxGetN( edges2_ ) == n2 ) ) {
    printf( "edges2 must be square\n" );
    mexErrMsgTxt( syntax );
    return;
  }
  if( !( 0 <= lambda && lambda <= 1 ) ) {
    printf( "lambda must be between 0 and 1\n" );
    mexErrMsgTxt( syntax );
    return;
  }

  // setup variables
  double* probStart1s = new double[ n1 ];
  double* probStart2s = new double[ n2 ];
  double* probQuit1s = new double[ n1 ];
  double* probQuit2s = new double[ n2 ];
  double* probTrans1s = new double[ n1*n1 ];
  double* probTrans2s = new double[ n2*n2 ];

  // initialize probability distributions
  const double probStart1 = 1.0 / n1;
  const double probStart2 = 1.0 / n2;
  const double lambdaNeg = 1 - lambda;
  register int i;
  register int j;
  register int l;
  // - start and quit probabilities, graph 1
  for( i = 0; i < n1; ++i ) {
    probStart1s[ i ] = probStart1;
    probQuit1s[ i ] = lambda;
  }
  // - start and quit probabilities, graph 2
  for( i = 0; i < n2; ++i ) {
    probStart2s[ i ] = probStart2;
    probQuit2s[ i ] = lambda;
  }
  // - transition probabilities, graph 1
  l = 0;
  for( j = 0; j < n1; ++j ) {
    register int outDegree = 0;
    for( i = 0; i < n1; ++i ) {
      outDegree += ( edges1[l] != 0 );
      ++l;
    }
    l -= n1;
    register const double probTrans = lambdaNeg / outDegree;
    for( i = 0; i < n1; ++i ) {
      probTrans1s[l] = ( edges1[l] != 0 ) ? probTrans : 0;
      ++l;
    }
  }
  // - transition probabilities, graph 2
  l = 0;
  for( j = 0; j < n2; ++j ) {
    register int outDegree = 0;
    for( i = 0; i < n2; ++i ) {
      outDegree += ( edges2[l] != 0 );
      ++l;
    }
    l -= n2;
    register const double probTrans = lambdaNeg / outDegree;
    for( i = 0; i < n2; ++i ) {
      probTrans2s[l] = ( edges2[l] != 0 ) ? probTrans : 0;
      ++l;
    }
  }

  // compute
  const double result = graphKernel( n1, n2, edges1, edges2, nodes1, nodes2, probStart1s, probStart2s, probQuit1s, probQuit2s, probTrans1s, probTrans2s, epsilon );

  // return the final result
  *resPtr = result;
  delete[] probStart1s;
  delete[] probStart2s;
  delete[] probQuit1s;
  delete[] probQuit2s;
  delete[] probTrans1s;
  delete[] probTrans2s;
}
Ejemplo n.º 25
0
void mexFunction(int             nlhs,      /* No. of output arguments */
                 mxArray         *plhs[],   /* Output arguments. */ 
                 int             nrhs,      /* No. of input arguments. */
                 const mxArray   *prhs[])   /* Input arguments. */
{
   int            ndim, pm_ndim;
   int            n, i;
   const int      *cdim = NULL, *pm_cdim = NULL;
   unsigned int   dim[3];
   unsigned int   nnz = 0;
   double         *rima = NULL;
   double         *pm = NULL;
   double         *ii = NULL, *jj = NULL;
   double         *nn = NULL, *pp = NULL;
   double         *tmp = NULL;


   if (nrhs == 0) mexErrMsgTxt("usage: [i,j,n,p]=pm_create_connectogram_dtj(rima,pm)");
   if (nrhs != 2) mexErrMsgTxt("pm_create_connectogram_dtj: 2 input arguments required");
   if (nlhs != 4) mexErrMsgTxt("pm_create_connectogram_dtj: 4 output argument required");

   /* Get connected components map. */

   if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0]) || mxIsSparse(prhs[0]) || !mxIsDouble(prhs[0]))
   {
      mexErrMsgTxt("pm_bwlabel_dtj: rima must be numeric, real, full and double");
   }
   ndim = mxGetNumberOfDimensions(prhs[0]);
   if ((ndim < 2) | (ndim > 3))
   {
      mexErrMsgTxt("pm_bwlabel_dtj: rima must be 2 or 3-dimensional");
   }
   cdim = mxGetDimensions(prhs[0]);
   rima = mxGetPr(prhs[0]);

   /* Get phase-map. */

   if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1]) || mxIsSparse(prhs[1]) || !mxIsDouble(prhs[1]))
   {
      mexErrMsgTxt("pm_bwlabel_dtj: pm must be numeric, real, full and double");
   }
   pm_ndim = mxGetNumberOfDimensions(prhs[1]);
   if (pm_ndim != ndim)
   {
      mexErrMsgTxt("pm_bwlabel_dtj: rima and pm must have same dimensionality");
   }
   pm_cdim = mxGetDimensions(prhs[1]);
   for (i=0; i<ndim; i++)
   {
      if (cdim[i] != pm_cdim[i])
      {
         mexErrMsgTxt("pm_bwlabel_dtj: rima and pm must have same size");
      }
   }
   pm = mxGetPr(prhs[1]);

   /* Fix dimensions to allow for 2D and 3D data. */

   dim[0]=cdim[0]; dim[1]=cdim[1];
   if (ndim==2) {dim[2]=1; ndim=3;} else {dim[2]=cdim[2];} 
   for (i=0, n=1; i<ndim; i++)
   {
      n *= dim[i];
   }

   /* 
      Create ii, jj, and nn and pp vectors for subsequent
      use by the matlab sparse function such that
      N = sparse(ii,jj,nn,nnz) generates a matrix where
      each non-zero entry signifies the no. of voxels
      along the border of the corresponding regions.
   */

   nnz = make_vectors(rima,pm,dim,&ii,&jj,&nn,&pp);
 
   /* Allocate memory for output. */

   plhs[0] = mxCreateDoubleMatrix(nnz,1,mxREAL);
   tmp = mxGetPr(plhs[0]);
   memcpy(tmp,ii,nnz*sizeof(double));
   plhs[1] = mxCreateDoubleMatrix(nnz,1,mxREAL);
   tmp = mxGetPr(plhs[1]);
   memcpy(tmp,jj,nnz*sizeof(double));
   plhs[2] = mxCreateDoubleMatrix(nnz,1,mxREAL);
   tmp = mxGetPr(plhs[2]);
   memcpy(tmp,nn,nnz*sizeof(double));
   plhs[3] = mxCreateDoubleMatrix(nnz,1,mxREAL);
   tmp = mxGetPr(plhs[3]);
   memcpy(tmp,pp,nnz*sizeof(double));

   /* Clean up a bit. */

   mxFree(ii); mxFree(jj); mxFree(nn); mxFree(pp);
   
   return;
}
Ejemplo n.º 26
0
void read_input_parameters(int argc,char **argv,char *docfile,char *modelfile,
			   char *restartfile,long *verbosity,
			   LEARN_PARM *learn_parm,KERNEL_PARM *kernel_parm)
{
	long i;
	char type[100];
	char msg[512], msg1[255],msg2[255];


	/* set default */
	strcpy (modelfile, "svm_model");
	strcpy (learn_parm->predfile, "trans_predictions");
	strcpy (learn_parm->alphafile, "");
	strcpy (restartfile, "");
	(*verbosity)=1;

	learn_parm->biased_hyperplane=1;
	learn_parm->sharedslack=0;
	learn_parm->remove_inconsistent=0;
	learn_parm->skip_final_opt_check=0;
	learn_parm->svm_maxqpsize=10;
	learn_parm->svm_newvarsinqp=0;
	learn_parm->svm_iter_to_shrink=-9999;
	learn_parm->maxiter=100000;
	learn_parm->kernel_cache_size=40;
	learn_parm->svm_c=0.0;
	learn_parm->eps=0.1;
	learn_parm->transduction_posratio=-1.0;
	learn_parm->svm_costratio=1.0;
	learn_parm->svm_costratio_unlab=1.0;
	learn_parm->svm_unlabbound=1E-5;
	learn_parm->epsilon_crit=0.001;
	learn_parm->epsilon_a=1E-15;
	learn_parm->compute_loo=0;
	learn_parm->rho=1.0;
	learn_parm->xa_depth=0;
	kernel_parm->kernel_type=0;
	kernel_parm->poly_degree=3;
	kernel_parm->rbf_gamma=1.0;
	kernel_parm->coef_lin=1;
	kernel_parm->coef_const=1;
	strcpy(kernel_parm->custom,"empty");
	strcpy(type,"c");


	for(i=1;(i<argc) && ((argv[i])[0] == '-');i++) {

		switch ((argv[i])[1]) 
		{ 
		case 'z': i++; strcpy(type,argv[i]); break;
		case 'v': i++; (*verbosity)=atol(argv[i]); break;
		case 'b': i++; learn_parm->biased_hyperplane=atol(argv[i]); break;
		case 'i': i++; learn_parm->remove_inconsistent=atol(argv[i]); break;
		case 'f': i++; learn_parm->skip_final_opt_check=!atol(argv[i]); break;
		case 'q': i++; learn_parm->svm_maxqpsize=atol(argv[i]); break;
		case 'n': i++; learn_parm->svm_newvarsinqp=atol(argv[i]); break;
		case '#': i++; learn_parm->maxiter=atol(argv[i]); break;
		case 'h': i++; learn_parm->svm_iter_to_shrink=atol(argv[i]); break;
		case 'm': i++; learn_parm->kernel_cache_size=atol(argv[i]); break;
		case 'c': i++; learn_parm->svm_c=atof(argv[i]); break;
		case 'w': i++; learn_parm->eps=atof(argv[i]); break;
		case 'p': i++; learn_parm->transduction_posratio=atof(argv[i]); break;
		case 'j': i++; learn_parm->svm_costratio=atof(argv[i]); break;
		case 'e': i++; learn_parm->epsilon_crit=atof(argv[i]); break;
		case 'o': i++; learn_parm->rho=atof(argv[i]); break;
		case 'k': i++; learn_parm->xa_depth=atol(argv[i]); break;
		case 'x': i++; learn_parm->compute_loo=atol(argv[i]); break;
		case 't': i++; kernel_parm->kernel_type=atol(argv[i]); break;
		case 'd': i++; kernel_parm->poly_degree=atol(argv[i]); break;
		case 'g': i++; kernel_parm->rbf_gamma=atof(argv[i]); break;
		case 's': i++; kernel_parm->coef_lin=atof(argv[i]); break;
		case 'r': i++; kernel_parm->coef_const=atof(argv[i]); break;
		case 'l': i++; strcpy(learn_parm->predfile,argv[i]); break;
		case 'a': i++; strcpy(learn_parm->alphafile,argv[i]); break;
		case 'y': i++; strcpy(restartfile,argv[i]); break;
		default: 
			sprintf(msg,"\nUnrecognized option %s!\n\n",argv[i]);
			mexErrMsgTxt(msg);
		}
	}


	if ((i>1) && (i>argc)) {
		printf ("Errr?  i=%d, argc=%d\n", i, argc);
		mexErrMsgTxt("Not enough input parameters!\n\n");
	}

	/* don't read a docfile!!
	/*  strcpy (docfile, argv[i]);
	if((i+1)<argc) {
	strcpy (modelfile, argv[i+1]);
	}
	*/

	if(learn_parm->svm_iter_to_shrink == -9999) {
		if(kernel_parm->kernel_type == LINEAR) 
			learn_parm->svm_iter_to_shrink=2;
		else
			learn_parm->svm_iter_to_shrink=100;
	}
	if(strcmp(type,"c")==0) {
		learn_parm->type=CLASSIFICATION;
	}
	else if(strcmp(type,"r")==0) {
		learn_parm->type=REGRESSION;
	}
	else if(strcmp(type,"p")==0) {
		learn_parm->type=RANKING;
	}
	else if(strcmp(type,"o")==0) {
		learn_parm->type=OPTIMIZATION;
	}
	else if(strcmp(type,"s")==0) {
		learn_parm->type=OPTIMIZATION;
		learn_parm->sharedslack=1;
	}
	else {
		sprintf(msg,"\nUnknown type '%s': Valid types are 'c' (classification), 'r' regession, and 'p' preference ranking.\n",type);
		mexErrMsgTxt(msg);
	}    
	if((learn_parm->skip_final_opt_check) 
		&& (kernel_parm->kernel_type == LINEAR)) {
			printf("\nIt does not make sense to skip the final optimality check for linear kernels.\n\n");
			learn_parm->skip_final_opt_check=0;
		}    
		if((learn_parm->skip_final_opt_check) 
			&& (learn_parm->remove_inconsistent)) {
				mexErrMsgTxt("It is necessary to do the final optimality check when removing inconsistent \nexamples.\n");

			}    
			if((learn_parm->svm_maxqpsize<2)) {
				sprintf(msg,"\nMaximum size of QP-subproblems not in valid range: %ld [2..]\n",learn_parm->svm_maxqpsize); 
				mexErrMsgTxt(msg);
			}
			if((learn_parm->svm_maxqpsize<learn_parm->svm_newvarsinqp)) {
				sprintf(msg1,"Maximum size of QP-subproblems [%ld] must be larger than the number of\n",learn_parm->svm_maxqpsize); 
				sprintf(msg2,"new variables [%ld] entering the working set in each iteration.\n",learn_parm->svm_newvarsinqp); 
				sprintf(msg,"%s\n%s\n", msg1,msg2);
				mexErrMsgTxt(msg);
			}
			if(learn_parm->svm_iter_to_shrink<1) {
				sprintf(msg,"\nMaximum number of iterations for shrinking not in valid range: %ld [1,..]\n",learn_parm->svm_iter_to_shrink);
				mexErrMsgTxt(msg);
			}
			if(learn_parm->svm_c<0) {
				mexErrMsgTxt("\nThe C parameter must be greater than zero!\n\n");
			}
			if(learn_parm->transduction_posratio>1) {
				mexErrMsgTxt("\nThe fraction of unlabeled examples to classify as positives must be less than 1.0 !!!\n\n");
			}
			if(learn_parm->svm_costratio<=0) {
				mexErrMsgTxt("\nThe COSTRATIO parameter must be greater than zero!\n\n");
			}
			if(learn_parm->epsilon_crit<=0) {
				mexErrMsgTxt("\nThe epsilon parameter must be greater than zero!\n\n");
			}
			if(learn_parm->rho<0) {
				printf("\nThe parameter rho for xi/alpha-estimates and leave-one-out pruning must\n");
				printf("be greater than zero (typically 1.0 or 2.0, see T. Joachims, Estimating the\n");
				printf("Generalization Performance of an SVM Efficiently, ICML, 2000.)!\n\n");
				mexErrMsgTxt("ending.\n");
			}
			if((learn_parm->xa_depth<0) || (learn_parm->xa_depth>100)) {
				printf("\nThe parameter depth for ext. xi/alpha-estimates must be in [0..100] (zero\n");
				printf("for switching to the conventional xa/estimates described in T. Joachims,\n");
				printf("Estimating the Generalization Performance of an SVM Efficiently, ICML, 2000.)\n");
				mexErrMsgTxt("ending\n");
			}
}
void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray*prhs[] )
{        

    /* Check for proper number of arguments */
    if (!(nrhs == 2)) 
    {   
        mexErrMsgTxt("You have to give me two inputs"); 
    } 
    
    if (!mxIsStruct(prhs[1]))
    {
        mexErrMsgTxt("That second input has to be an image structure, you know.");
    }
    
    int error = 0;
    int BitsPerPixel = 8;
    HCAM hCam = *(HCAM *)mxGetPr(prhs[0]);
    
    //Freeze the video feed for frame grab to prevent split frames
    error = is_FreezeVideo( hCam, IS_WAIT );
    if (error !=IS_SUCCESS)
    {   
       mexErrMsgTxt("Error freezing video");  
    }  
    
    int image_field = mxGetFieldNumber(prhs[1],"image");
    int pointer_field = mxGetFieldNumber(prhs[1],"pointer");
    int ID_field = mxGetFieldNumber(prhs[1],"id");

    mxArray *p_output_image = mxGetFieldByNumber(prhs[1],0,image_field);
    char *p_output = (char *)mxGetPr(p_output_image);
    
    mxArray *ppointer_field = mxGetFieldByNumber(prhs[1],0,pointer_field);
    char *p_image = (char *)*(int *)mxGetPr(ppointer_field);
    
    mxArray *pID_field = mxGetFieldByNumber(prhs[1],0,ID_field);
    int *ID = (int *)mxGetPr(pID_field); 
           
    error =  is_CopyImageMem (hCam, p_image, *ID, p_output);
    if (error !=IS_SUCCESS)
    {   
       mexErrMsgTxt("Error copying image data to output");  
    }
    
    //If a variable is supplied on the LHS, use it to output image frame data
    if (nlhs == 1)
    {
    IS_RECT rectAOI;
    INT nX, nY;
    error = is_AOI(hCam, IS_AOI_IMAGE_GET_AOI, (void*)&rectAOI, sizeof(rectAOI));
    if (error == IS_SUCCESS)
    {
    nX = rectAOI.s32Width;
    nY = rectAOI.s32Height;
    }

        mxArray *p_output_image_new = mxCreateNumericMatrix(nX, nY, mxUINT8_CLASS, mxREAL);
        p_output = (char *)mxGetPr(p_output_image_new);           
        error =  is_CopyImageMem (hCam, p_image, *ID, p_output);
        if (error !=IS_SUCCESS)
        {   
           mexErrMsgTxt("Error copying image data to output");  
        }
        
        //Set mex function output
        plhs[0] = p_output_image_new;
    
    } 
    return;   
}
Ejemplo n.º 28
0
/* call as  model = mexsvmlearn(data,labels,options) */
void mexFunction(int nlhs, mxArray *plhs[],
				 int nrhs, const mxArray *prhs[])
{
	char **argv;
	int argc;
	DOC **docs;  /* training examples */
	long totwords,totdoc,i;
	double *target;
	double *alpha_in=NULL;
	KERNEL_CACHE *kernel_cache;
	LEARN_PARM learn_parm;
	KERNEL_PARM kernel_parm;
	MODEL model;

	/* check for valid calling format */
	if ((nrhs != 3)  || (nlhs != 1))
		mexErrMsgTxt(ERR001);

	if (mxGetM(prhs[0]) != mxGetM(prhs[1]))
		mexErrMsgTxt(ERR002);

	if (mxGetN(prhs[1]) != 1)
		mexErrMsgTxt(ERR003);

	/* reset static variables -- as a .DLL, static things are sticky  */
	global_init( );

	/* convert the parameters (given in prhs[2]) into an argv/argc combination */
	argv = make_argv((mxArray *)prhs[2],&argc); /* send the options */



	/* this was originally supposed to be argc, argv, re-written for MATLAB ...
	its cheesy - but it workss :: convert the options array into an argc, 
	argv pair  and let svm_lite handle it from there. */

	read_input_parameters(argc,argv,docfile,modelfile,restartfile,&verbosity, 
		&learn_parm,&kernel_parm);

	extract_user_opts((mxArray *)prhs[2], &kernel_parm);

	totdoc = mxGetM(prhs[0]);
	totwords = mxGetN(prhs[0]);

	/* prhs[0] = samples (mxn) array
	prhs[1] = labels (mx1) array */
	mexToDOC((mxArray *)prhs[0], (mxArray *)prhs[1], &docs, &target, NULL, NULL);

	/* TODO modify to accept this array 
	if(restartfile[0]) alpha_in=read_alphas(restartfile,totdoc); */

	if(kernel_parm.kernel_type == LINEAR) { /* don't need the cache */
		kernel_cache=NULL;
	}
	else {
		/* Always get a new kernel cache. It is not possible to use the
		same cache for two different training runs */
		kernel_cache=kernel_cache_init(totdoc,learn_parm.kernel_cache_size);
	}


	if(learn_parm.type == CLASSIFICATION) {
		svm_learn_classification(docs,target,totdoc,totwords,&learn_parm,
			&kernel_parm,kernel_cache,&model,alpha_in);

	}
	else if(learn_parm.type == REGRESSION) {
		svm_learn_regression(docs,target,totdoc,totwords,&learn_parm,
			&kernel_parm,&kernel_cache,&model);
	}
	else if(learn_parm.type == RANKING) {
		svm_learn_ranking(docs,target,totdoc,totwords,&learn_parm,
			&kernel_parm,&kernel_cache,&model);
	}
	else if(learn_parm.type == OPTIMIZATION) {
		svm_learn_optimization(docs,target,totdoc,totwords,&learn_parm,
			&kernel_parm,kernel_cache,&model,alpha_in);
	}
	else {
		mexErrMsgTxt(ERR004);
	}

	if(kernel_cache) {
		/* Free the memory used for the cache. */
		kernel_cache_cleanup(kernel_cache);
	}

	/* **********************************
	* After the training/learning portion has finished,
	* copy the model back to the output arrays for MATLAB 
	* ********************************** */
	store_model(&model, plhs);

	free_kernel();
	global_destroy( );	
}
Ejemplo n.º 29
0
void mexFunction(
    int nlhs, mxArray *plhs[],
    int nrhs, const mxArray *prhs[]
)
{
    int i, j;
    double *b=NULL, *A=NULL,
            *l=NULL, *u=NULL, *x=NULL, *lambda=NULL ;
    int *iA=NULL, *kA=NULL, nnz=0, neq=0, m=0, n=0, display=0;
    long *lpenv=NULL, *p_lp=NULL;
    char *Sense=NULL ;
    CPXENVptr     env = NULL;
    CPXLPptr      lp = NULL;
    int           status, lpstat;
    double        objval;
#ifndef MX_COMPAT_32
    long *iA_=NULL, *kA_=NULL ;
#endif

    if (nrhs > 6 || nrhs < 1) {
        mexErrMsgTxt("Usage: [how] "
                     "= lp_addrows(env,lp,A,b,neq,disp)");
        return;
    }
    switch (nrhs) {
    case 6:
        if (mxGetM(prhs[5]) != 0 || mxGetN(prhs[5]) != 0) {
            if (!mxIsNumeric(prhs[5]) || mxIsComplex(prhs[5])
                    ||  mxIsSparse(prhs[5])
                    || !(mxGetM(prhs[5])==1 && mxGetN(prhs[5])==1)) {
                mexErrMsgTxt("6th argument (display) must be "
                             "an integer scalar.");
                return;
            }
            display = *mxGetPr(prhs[5]);
        }
    case 5:
        if (mxGetM(prhs[4]) != 0 || mxGetN(prhs[4]) != 0) {
            if (!mxIsNumeric(prhs[4]) || mxIsComplex(prhs[4])
                    ||  mxIsSparse(prhs[4])
                    || !(mxGetM(prhs[4])==1 && mxGetN(prhs[4])==1)) {
                mexErrMsgTxt("5th argument (neq) must be "
                             "an integer scalar.");
                return;
            }
            neq = *mxGetPr(prhs[4]);
        }
    case 4:
        if (mxGetM(prhs[3]) != 0 || mxGetN(prhs[3]) != 0) {
            if (!mxIsNumeric(prhs[3]) || mxIsComplex(prhs[3])
                    ||  mxIsSparse(prhs[3])
                    || !mxIsDouble(prhs[3])
                    ||  mxGetN(prhs[3])!=1 ) {
                mexErrMsgTxt("4rd argument (b) must be "
                             "a column vector.");
                return;
            }
            if (m != 0 && m != mxGetM(prhs[3])) {
                mexErrMsgTxt("Dimension error (arg 4 and later).");
                return;
            }
            b = mxGetPr(prhs[3]);
            m = mxGetM(prhs[3]);
        }
    case 3:
        if (mxGetM(prhs[2]) != 0 || mxGetN(prhs[2]) != 0) {
            if (!mxIsNumeric(prhs[2]) || mxIsComplex(prhs[2])
                    || !mxIsSparse(prhs[2]) ) {
                mexErrMsgTxt("3n argument (A) must be "
                             "a sparse matrix.");
                return;
            }
            if (m != 0 && m != mxGetN(prhs[2])) {
                mexErrMsgTxt("Dimension error (arg 3 and later).");
                return;
            }
            if (n != 0 && n != mxGetM(prhs[2])) {
                mexErrMsgTxt("Dimension error (arg 3 and later).");
                return;
            }
            m = mxGetN(prhs[2]);
            n = mxGetM(prhs[2]);

            A = mxGetPr(prhs[2]);
#ifdef MX_COMPAT_32
            iA = mxGetIr(prhs[2]);
            kA = mxGetJc(prhs[2]);
#else
            iA_ = mxGetIr(prhs[2]);
            kA_ = mxGetJc(prhs[2]);

            iA = myMalloc(mxGetNzmax(prhs[2])*sizeof(int)) ;
            for (i=0; i<mxGetNzmax(prhs[2]); i++)
                iA[i]=iA_[i] ;

            kA = myMalloc((n+1)*sizeof(int)) ;
            for (i=0; i<n+1; i++)
                kA[i]=kA_[i] ;
#endif
            /*{
            int k=0 ;
            mxArray* a = mxCreateDoubleMatrix(1, 1, mxREAL);
            for (; k<28; k++)
              printf("%i,", iA[k]) ;
            printf("\n") ;
            for (k=0; k<28; k++)
              printf("%i,", kA[k]) ;
            printf("\n") ;
            for (k=0; k<28; k++)
              printf("%f,", A[k]) ;
            printf("\n") ;
            }*/
            /*nnz=mxGetNzmax(prhs[2]); */
            nnz=kA[m] ;
            if (display>3)
                fprintf(STD_OUT, "nnz=%i\n", nnz) ;

            Sense=myMalloc((m+1)*sizeof(char)) ;
            for (i=0; i<m; i++)
                if (i<neq) Sense[i]='E' ;
                else Sense[i]='L' ;
            Sense[m]=0 ;
            if (display>3)
                fprintf(STD_OUT, "Sense=%s\n", Sense) ;
        }
    case 2:
        if (mxGetM(prhs[1]) != 0 || mxGetN(prhs[1]) != 0) {
            if (!mxIsNumeric(prhs[1]) || mxIsComplex(prhs[1])
                    ||  mxIsSparse(prhs[1])
                    || !mxIsDouble(prhs[1])
                    ||  mxGetN(prhs[1])!=1 ) {
                mexErrMsgTxt("2nd argument (p_lp) must be "
                             "a column vector.");
                return;
            }
            if (1 != mxGetM(prhs[1])) {
                mexErrMsgTxt("Dimension error (arg 2).");
                return;
            }
            p_lp = (long*) mxGetPr(prhs[1]);
        }
    case 1:
        if (mxGetM(prhs[0]) != 0 || mxGetN(prhs[0]) != 0) {
            if (!mxIsNumeric(prhs[0]) || mxIsComplex(prhs[0])
                    ||  mxIsSparse(prhs[0])
                    || !mxIsDouble(prhs[0])
                    ||  mxGetN(prhs[0])!=1 ) {
                mexErrMsgTxt("1st argument (lpenv) must be "
                             "a column vector.");
                return;
            }
            if (1 != mxGetM(prhs[0])) {
                mexErrMsgTxt("Dimension error (arg 1).");
                return;
            }
            lpenv = (long*) mxGetPr(prhs[0]);
        }
    }

    if (nlhs > 1 || nlhs < 1) {
        mexErrMsgTxt("Usage: [how] "
                     "= lp_gen(lpenv,p_lp,A,b,neq,disp)");
        return;
    }
    if (display>3) fprintf(STD_OUT, "(m=%i, n=%i, neq=%i, nnz=%i) \n", m, n, neq, nnz) ;

    /* Initialize the CPLEX environment */
    env = (CPXENVptr) lpenv[0] ;
    lp=(CPXLPptr)p_lp[0] ;

    if (display>2)
        fprintf(STD_OUT, "calling CPXaddrows \n") ;
    status = CPXaddrows (env, lp, 0, m, nnz, b, Sense, kA, iA, A, NULL, NULL);
    if ( status ) {
        fprintf (STD_OUT,"CPXaddrows failed.\n");
        goto TERMINATE;
    }

TERMINATE:
    if (status) {
        char  errmsg[1024];
        CPXgeterrorstring (env, status, errmsg);
        fprintf (STD_OUT, "%s", errmsg);
        if (nlhs >= 1)
            plhs[0] = mxCreateString(errmsg) ;
    } else if (nlhs >= 1)
        plhs[0] = mxCreateString("OK") ;
    ;
    /*  if (Sense) myFree(Sense) ;*/
#ifndef MX_COMPAT_32
    if (iA) myFree(iA) ;
    if (kA) myFree(kA) ;
#endif

    return ;
}
Ejemplo n.º 30
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {		  

  if(nrhs < 5 || nrhs > 5) {
    mexErrMsgTxt("expected either 5 input arguments.\n");
		return;
  }
  
  if(nlhs != 3) {
    mexErrMsgTxt("expected 3 output arguments.\n");
    return;
  }
  
  // read input arguments
  int arg = 0;
  
  // amount of training examples == number of slacks
	const mxArray *params = prhs[arg];
	const int num_exm = (int) *mxGetPr(mxGetField(params,0, "num_examples"));
//	printf("Number of examples (new): %i\n",num_exm);
  ++arg;
	
	// this is the current solution
	const int M3 = mxGetM(prhs[arg]);
  const int D = mxGetN(prhs[arg]);
/*
  assert(M3 == 1);
*/
	double *w = mxGetPr(prhs[arg]);
	++arg;
	// get the delta_y_ybar [1 x t]-array
	const int M1 = mxGetM(prhs[arg]);
  const int N1 = mxGetN(prhs[arg]);
  assert(M1 == 1);
	double *delta_y_ybar = mxGetPr(prhs[arg]);
	++arg;

	const int DIM = mxGetM(prhs[arg]);
  const int N = mxGetN(prhs[arg]);
	double *delta_psis = mxGetPr(prhs[arg]);
	++arg;

	// get the delta_psis_idxs [1 x n]-array
	const int M2 = mxGetM(prhs[arg]);
  const int N2 = mxGetN(prhs[arg]);
  assert(M2 == 1);
	double *delta_psis_idxs = mxGetPr(prhs[arg]);
	++arg;

	 

  // these are the output values (already initialized)
	plhs[0] = mxCreateDoubleMatrix(1, num_exm, mxREAL);
  double *losses = mxGetPr(plhs[0]);

 	plhs[1] = mxCreateDoubleMatrix(1, num_exm, mxREAL);
  double *idxs = mxGetPr(plhs[1]);

	  // copy the parameter structure without making changes
	// to the elements
	plhs[2] = mxDuplicateArray(params);



	// for all dpsis
	for (int n=0; n<N; n++) {
		double loss = delta_y_ybar[n];
		const int ind = delta_psis_idxs[n];

		// for all dimensions in dpsis
		for (int d=0; d<DIM; d++) {
			loss -= w[d]*delta_psis[DIM*n+d];
		}
		
		// hinge 
		if (loss<0.0) {
			loss = 0.0;
		}

		//printf("t=%i n=%i loss=%f idxs=%i\n",num_exm,n,loss,ind);

		// store loss 
		if (loss>=losses[ind-1]) {
			losses[ind-1] = loss;
			idxs[ind-1] = n+1;
		}

	}

}