Esempio n. 1
0
void mexFunction(int nlhs, mxArray *plhs[],
  int nrhs, const mxArray *prhs[])
{
  char me[]="nrrdSave", *filename, *errPtr, errBuff[AIR_STRLEN_MED];
  int filenameLen, ntype;
  size_t sizeZ[NRRD_DIM_MAX];
  unsigned int dim, axIdx;
  Nrrd *nrrd;
  airArray *mop;
  const mxArray *filenameMx, *arrayMx;
  
  if (!(2 == nrhs && mxIsChar(prhs[0]) )) {
    sprintf(errBuff, "%s: requires two args: one string, one array", me);
    mexErrMsgTxt(errBuff);
  }
  filenameMx = prhs[0];
  arrayMx = prhs[1];

  if (mxIsComplex(arrayMx)) {
    sprintf(errBuff, "%s: sorry, array must be real", me);
    mexErrMsgTxt(errBuff);
  }
  ntype = typeMtoN(mxGetClassID(arrayMx));
  if (nrrdTypeUnknown == ntype) {
    sprintf(errBuff, "%s: sorry, can't handle type %s",
            me, mxGetClassName(arrayMx));
    mexErrMsgTxt(errBuff);
  }
  dim = mxGetNumberOfDimensions(arrayMx);
  if (!( 1 <= dim && dim <= NRRD_DIM_MAX )) {
    sprintf(errBuff, "%s: number of array dimensions %d outside range [1,%d]",
            me, dim, NRRD_DIM_MAX);
    mexErrMsgTxt(errBuff);
  }
  
  filenameLen = mxGetM(filenameMx)*mxGetN(filenameMx)+1;
  filename = mxCalloc(filenameLen, sizeof(mxChar));    /* managed by Matlab */
  mxGetString(filenameMx, filename, filenameLen);
  
  for (axIdx=0; axIdx<dim; axIdx++) {
    sizeZ[axIdx] = mxGetDimensions(arrayMx)[axIdx];
  }
  nrrd = nrrdNew();
  mop = airMopNew();
  airMopAdd(mop, nrrd, (airMopper)nrrdNix, airMopAlways);
  if (nrrdWrap_nva(nrrd, mxGetPr(arrayMx), ntype, dim, sizeZ)
      || nrrdSave(filename, nrrd, NULL)) {
    errPtr = biffGetDone(NRRD);
    airMopAdd(mop, errPtr, airFree, airMopAlways);
    sprintf(errBuff, "%s: error saving NRRD:\n%s", me, errPtr);
    airMopError(mop);
    mexErrMsgTxt(errBuff);
  }

  airMopOkay(mop);
  return;
}
Esempio n. 2
0
void TLA_mxa_to_dim_t(const mxArray* mxa, dim_t* val){
	double* data;
    mexPrintf("mxa class %s\n", mxGetClassName(mxa));
    if(!mxIsDouble(mxa)){
        mexErrMsgTxt("Mode multiplication must be double");
    }

    data = mxGetPr(mxa);
    (*val) = (dim_t)(*data);
}
Esempio n. 3
0
/* get_characteristics figures out the size, and category 
   of the input array_ptr, and then displays all this information. */ 
void
get_characteristics(const mxArray *array_ptr)
{
  const char    *name;
  const char    *class_name;
  const int     *dims;
        char    *shape_string;
	char    *temp_string;
        int      c;
        int      number_of_dimensions; 
        int      length_of_shape_string;

  /* Display the mxArray's Dimensions; for example, 5x7x3.  
     If the mxArray's Dimensions are too long to fit, then just
     display the number of dimensions; for example, 12-D. */ 
  number_of_dimensions = mxGetNumberOfDimensions(array_ptr);
  dims = mxGetDimensions(array_ptr);
  
  /* alloc memory for shape_string w.r.t thrice the number of dimensions */
  /* (so that we can also add the 'x')                                   */
  shape_string=(char *)mxCalloc(number_of_dimensions*3,sizeof(char));
  shape_string[0]='\0';
  temp_string=(char *)mxCalloc(64, sizeof(char));

  for (c=0; c<number_of_dimensions; c++) {
    sprintf(temp_string, "%dx", dims[c]);
    strcat(shape_string, temp_string);
  }

  length_of_shape_string = strlen(shape_string);
  /* replace the last 'x' with a space */
  shape_string[length_of_shape_string-1]='\0';
  if (length_of_shape_string > 16)
    sprintf(shape_string, "%d-D\0", number_of_dimensions); 
  
  mexPrintf("Dimensions: %s\n", shape_string);
  
  /* Display the mxArray's class (category). */
  class_name = mxGetClassName(array_ptr);
  mexPrintf("Class Name: %s%s\n", class_name,
	    mxIsSparse(array_ptr) ? " (sparse)" : "");
  
  /* Display a bottom banner. */
  mexPrintf("------------------------------------------------\n");
  
  /* free up memory for shape_string */
  mxFree(shape_string);
}
Esempio n. 4
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

	mexPrintf("mxInOut ... \n");

    mexPrintf("There are %d right-hand-side argument(s).\n", nrhs);
    for(int i = 0; i < nrhs; i++)  {
    	mexPrintf("\targument %i class name: %s\n", (i+1), mxGetClassName(prhs[i]));
    }


    mexPrintf("There are %d left-hand-side argument(s).\n", nlhs);
    if(nlhs > nrhs) {
      mexErrMsgTxt("Cannot specify more outputs than inputs.\n");
    }

    for (i=0; i < nlhs; i++)  {
    	plhs[i] = mxCreateDoubleMatrix(1, 1, mxREAL);
    	*mxGetPr(plhs[i]) = (double) mxGetNumberOfElements(prhs[i]);
    }
}
Esempio n. 5
0
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
    int        i;
       
    /* Examine input (right-hand-side) arguments. */
    mexPrintf("\nThere are %d right-hand-side argument(s).", nrhs);
    for (i=0; i<nrhs; i++)  {
	mexPrintf("\n\tInput Arg %i is of type:\t%s ",i,mxGetClassName(prhs[i]));
    }
    
    /* Examine output (left-hand-side) arguments. */
    mexPrintf("\n\nThere are %d left-hand-side argument(s).\n", nlhs);
    if (nlhs > nrhs)
      mexErrMsgTxt("Cannot specify more outputs than inputs.\n");
    for (i=0; i<nlhs; i++)  {
	plhs[i]=mxCreateDoubleMatrix(1,1,mxREAL);
	*mxGetPr(plhs[i])=(double)mxGetNumberOfElements(prhs[i]);
    }
}
Esempio n. 6
0
/**
 * restoreArray() - given a structure in mxStruct, retrieve a double
 * array from the field named "name".
 * TODO handle sparse arrays
 */
double *restoreArray(const mxArray *mxStruct, char *name)
{
  char msg[255];
  mxArray *mxValue;

  /* retrieve the array element from the struct */
  if (! mxIsStruct(mxStruct)) {
    sprintf(msg,"mxStruct is not a struct, it is a %s\n", 
	    mxGetClassName(mxStruct));
    mexErrMsgTxt(msg);
  }

  mxValue = mxGetField(mxStruct, 0, name);

  if (mxValue == NULL) {
    /*printf("Warning: could not retrieve %s from the given struct.\n", name); */
    return NULL;
  }

  return mxGetPr(mxValue); 
}
static void* calcSize(mxArray* data, uint64_t* size) {

    uint64_t numel = mxGetNumberOfElements(data);
    switch (mxGetClassID(data)) {
        case mxLOGICAL_CLASS: ;
        case mxINT8_CLASS:
        case mxUINT8_CLASS:
            *size = numel;
            return mxGetData(data);
        case mxCHAR_CLASS:
            *size = numel * sizeof(mxChar);
            return mxGetChars(data);
        case mxDOUBLE_CLASS:
            *size = numel * sizeof(double);
            return mxGetPr(data);
        case mxSINGLE_CLASS:
            *size = numel * sizeof(float);
            return mxGetData(data);
        case mxINT16_CLASS:
        case mxUINT16_CLASS:
            *size = numel * sizeof(short);
            return mxGetData(data);
        case mxINT32_CLASS:
        case mxUINT32_CLASS:
            *size = numel * sizeof(int);
            return mxGetData(data);
        case mxINT64_CLASS:
        case mxUINT64_CLASS:
            *size = numel * sizeof(int64_t);
            return mxGetData(data);
        default: {
            char s[256];
            sprintf(s, "GridFS - Unsupported type (%s)\n", mxGetClassName(data));
            mexErrMsgTxt(s);
            return 0;
        }
    }
}
Esempio n. 8
0
void parse(mxArray *ma, json_object **jo){

    int i = 0;
    size_t num_el = mxGetNumberOfElements(ma);
    size_t m = mxGetM(ma);
    size_t n = mxGetN(ma);

    json_object *lobj;
    json_object *tmpobj;
    mxArray *tmpma;

    /* was char - convert to string*/
    if(mxIsChar(ma)){
        char *str = mxArrayToString(ma);
        *jo = json_object_new_string(str);
    }
    /* was struct - convert to object */
    else if(mxIsStruct(ma)){
        if(num_el == 1){
            object(ma, 0, jo);
        }
        else{
            /* it was a list of objects! */
            *jo = json_object_new_array();

            if(n == 1){
                n = m;
                m = 1;
            }

            for(i = 0; i < num_el; i++){

                if(i % m == 0 && m > 1){
                    lobj = json_object_new_array();
                    json_object_array_add(*jo,lobj);
                }

                object(ma, i, &tmpobj);

                if(m > 1)
                    json_object_array_add(lobj, tmpobj);
                else
                    json_object_array_add(*jo, tmpobj);
            }
        }


    }
    /* was cell array - convert to list */
    else if(mxIsCell(ma)){

        *jo = json_object_new_array();

        if(n == 1){
            n = m;
            m = 1;
        }

        for(i = 0; i < num_el; i++){

            if(i % m == 0 && m > 1){
                lobj = json_object_new_array();
                json_object_array_add(*jo,lobj);
            }

            tmpma = mxGetCell(ma, i);

            if(tmpma){
                parse(tmpma, &tmpobj);

                if(m > 1)
                    json_object_array_add(lobj, tmpobj);
                else
                    json_object_array_add(*jo, tmpobj);
            }
        }
    }
    /* was numeric or bool - convert to number or list */
    else{

        /* single number or bool */
        if(num_el == 1){
            /* mxINT32_CLASS */

            if(mxIsComplex(ma)){
                mexErrMsgTxt("Data cannot be complex.");
            }

            if(mxIsNumeric(ma)){
                double dbl = mxGetScalar(ma);
                numeric(dbl, jo);
            }
            else if(mxIsLogical(ma)){
                *jo = json_object_new_boolean(mxIsLogicalScalarTrue(ma));
            }
            else{
                printf("Type is: %s\n", mxGetClassName(ma));
                mexErrMsgTxt("Encountered an unknown type.");
            }

        }
        else{

            double *dbl;
            int *intgr;
            mxLogical *bl;

            if(mxIsDouble(ma)){
                dbl = mxGetData(ma);
            }
            else if(mxIsClass(ma, "mxINT32_CLASS")){
                intgr = mxGetData(ma);
            }
            else if(mxIsLogical(ma)){
                bl = mxGetData(ma);
            }
            else{
                printf("Type is: %s\n", mxGetClassName(ma));
                mexErrMsgTxt("Encountered an unsupported type.");
            }

            *jo = json_object_new_array();

            /* vector - convert to list */
            if(n == 1){
                n = m;
                m = 1;
            }

            for(i = 0; i < num_el; i++){

                if(i % m == 0 && m > 1){
                    lobj = json_object_new_array();
                    json_object_array_add(*jo,lobj);
                }

                if(mxIsLogical(ma))
                    tmpobj = json_object_new_boolean(bl[i]);
                else if(mxIsDouble(ma))
                    numeric(dbl[i], &tmpobj);
                else
                    numeric((double)intgr[i], &tmpobj);

                if(m > 1)
                    json_object_array_add(lobj, tmpobj);
                else
                    json_object_array_add(*jo, tmpobj);

            }


        }

    }


}
Esempio n. 9
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
	OID ID;
	
	/* OMEIS data structures */
	omeis* is;
	pixHeader* head;
	
	/* MATLAB data structueres */
	mxArray *m_url, *m_sessionkey;
	mxArray *permute_inputs[2];
	mxArray *copy_input_array; /* we need a local copy so we can transpose it */
	
	char* url, *sessionkey;
	
	if (nrhs != 3)
		mexErrMsgTxt("\n [pix] = setPixels (is, ID, pixels)");
		
	if (!mxIsStruct(prhs[0]))
		mexErrMsgTxt("setPixels requires the first input to be the struct outputed"
					 " from openConnectionOMEIS\n");
					 
	if (!(m_url = mxGetField(prhs[0], 0, "url")))
		mexErrMsgTxt("setPixels requires the first input, OMEIS struct, to have field: url");
	if (!(m_sessionkey = mxGetField(prhs[0], 0, "sessionkey")))
		mexErrMsgTxt("setPixels requires the first input, OMEIS struct, to have field: sessionkey");
		
	if (!mxIsChar(m_url) || !mxIsChar(m_sessionkey))
		mexErrMsgTxt("OMEIS field aren't character array.\n");		
	
	if (!mxIsNumeric(prhs[1]))
		mexErrMsgTxt("setPixels requires the second input to be the PixelsID\n") ;
		
	ID = (OID) mxGetScalar(prhs[1]) ;
	
	url = mxArrayToString(m_url);
	sessionkey = mxArrayToString(m_sessionkey);

	is = openConnectionOMEIS (url, sessionkey);
	
	if (!(head = pixelsInfo (is, ID))){
		char err_str[128];
		sprintf(err_str, "PixelsID %llu or OMEIS URL '%s' is probably wrong\n", ID, is->url);		
		
		/* clean up */
		mxFree(url);
		mxFree(sessionkey);
		mxFree(is);
		
		mexErrMsgTxt(err_str);
	}
	
	/*
		In OMEIS Size_X corresponds to columns and Size_Y corresponds to rows.
		This is diametrically opposite to MATLAB's assumptions.
		hence we do
		"$matlab_var_name = permute($matlab_var_name, [2 1 3 4 5]);" 
		the hard way (groan)
	*/
	
	permute_inputs[0] = prhs[2]; /* permute_input isn't being modified so
									discarding the const qualifier is okay */
	permute_inputs[1] = mxCreateDoubleMatrix(1, 5, mxREAL);
 	mxGetPr(permute_inputs[1])[0] = 2;
 	mxGetPr(permute_inputs[1])[1] = 1;
 	mxGetPr(permute_inputs[1])[2] = 3;
 	mxGetPr(permute_inputs[1])[3] = 4;
 	mxGetPr(permute_inputs[1])[4] = 5;
 	
	/* mexCallMATLAB allocates memory for copy_input_array */
 	if (mexCallMATLAB(1, &copy_input_array, 2, permute_inputs, "permute")) {
		/* clean up */
		mxFree(url);
		mxFree(sessionkey);
		mxFree(head);
		mxFree(is);
		
 		char err_str[128];
		sprintf(err_str, "Couldn't permute the pixels to get them in MATLAB orientation");
		mexErrMsgTxt(err_str);
 	}
	
	
	/* check dimension and class check */
	const mwSize* dims = mxGetDimensions (copy_input_array);
	switch (mxGetNumberOfDimensions (copy_input_array)) {
		char err_str[128];
		case 5:
			if (head->dt != dims[4]) {
				sprintf (err_str, "5th Dimension (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[4], head->dt);
				mexErrMsgTxt(err_str);
			}
		case 4:
			if (head->dc != dims[3]) {
				sprintf (err_str, "4th Dimension (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[3], head->dc);
				mexErrMsgTxt(err_str);
			}
		case 3:
			if (head->dz != dims[2]){
				sprintf (err_str, "3th Dimension (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[2], head->dz);
				mexErrMsgTxt(err_str);
			}
		case 2:
			if (head->dy != dims[1]){
				sprintf (err_str, "Height (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[1], head->dy);
				mexErrMsgTxt(err_str);
			}
		case 1:
			if (head->dx != dims[0]){
				sprintf (err_str, "Width (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[0], head->dx);
				mexErrMsgTxt(err_str);
			}
			break;
		default:
			/* clean up */
			mxFree(url);
			mxFree(sessionkey);
			mxFree(head);
			mxFree(is);
			mxDestroyArray(copy_input_array);
					
			mexErrMsgTxt("Input Array must be 5D or less");
		break;
	}
	
	pixHeader tmp_head;
	CtoOMEISDatatype ((char*) mxGetClassName(copy_input_array), &tmp_head);
	
	if ( !samePixelType(&tmp_head, head)) {
		/* clean up */
		mxFree(url);
		mxFree(sessionkey);
		mxFree(head);
		mxFree(is);
		mxDestroyArray(copy_input_array);
		
		mexErrMsgTxt("Types of input array and Pixels don't match\n");
	}
	
	/* set the pixels */
	int pix = setPixels (is, ID, mxGetPr(copy_input_array));
	
	/* record number of pixels written */
	plhs[0] = mxCreateScalarDouble((double) pix);
	
	/* clean up */
	mxFree(url);
	mxFree(sessionkey);
	mxFree(head);
	mxFree(is);
	mxDestroyArray(copy_input_array);
}
Esempio n. 10
0
int main()

{
	Engine *ep;
	mxArray *T = NULL, *result = NULL;
	char buffer[BUFSIZE+1];
	double time[10] = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 };

	/*
	 * Call engOpen with a NULL string. This starts a MATLAB process 
     * on the current host using the command "matlab".
	 */
	if (!(ep = engOpen(""))) {
		fprintf(stderr, "\nCan't start MATLAB engine\n");
		return EXIT_FAILURE;
	}

	/*
	 * PART I
	 *
	 * For the first half of this demonstration, we will send data
	 * to MATLAB, analyze the data, and plot the result.
	 */

	/* 
	 * Create a variable for our data
	 */
	T = mxCreateDoubleMatrix(1, 10, mxREAL);
	memcpy((void *)mxGetPr(T), (void *)time, sizeof(time));
	/*
	 * Place the variable T into the MATLAB workspace
	 */
	engPutVariable(ep, "T", T);

	/*
	 * Evaluate a function of time, distance = (1/2)g.*t.^2
	 * (g is the acceleration due to gravity)
	 */
	engEvalString(ep, "D = .5.*(-9.8).*T.^2;");

	/*
	 * Plot the result
	 */
	engEvalString(ep, "plot(T,D);");
	engEvalString(ep, "title('Position vs. Time for a falling object');");
	engEvalString(ep, "xlabel('Time (seconds)');");
	engEvalString(ep, "ylabel('Position (meters)');");

	/*
	 * use fgetc() to make sure that we pause long enough to be
	 * able to see the plot
	 */
	printf("Hit return to continue\n\n");
	fgetc(stdin);
	/*
	 * We're done for Part I! Free memory, close MATLAB figure.
	 */
	printf("Done for Part I.\n");
	mxDestroyArray(T);
	engEvalString(ep, "close;");


	/*
	 * PART II
	 *
	 * For the second half of this demonstration, we will request
	 * a MATLAB string, which should define a variable X.  MATLAB
	 * will evaluate the string and create the variable.  We
	 * will then recover the variable, and determine its type.
	 */
	  
	/*
	 * Use engOutputBuffer to capture MATLAB output, so we can
	 * echo it back.  Ensure first that the buffer is always NULL
	 * terminated.
	 */

	buffer[BUFSIZE] = '\0';
	engOutputBuffer(ep, buffer, BUFSIZE);
	while (result == NULL) {
	    char str[BUFSIZE+1];
	    /*
	     * Get a string input from the user
	     */
	    printf("Enter a MATLAB command to evaluate.  This command should\n");
	    printf("create a variable X.  This program will then determine\n");
	    printf("what kind of variable you created.\n");
	    printf("For example: X = 1:5\n");
	    printf(">> ");

	    fgets(str, BUFSIZE, stdin);
	  
	    /*
	     * Evaluate input with engEvalString
	     */
	    engEvalString(ep, str);
	    
	    /*
	     * Echo the output from the command.  
	     */
	    printf("%s", buffer);
	    
	    /*
	     * Get result of computation
	     */
	    printf("\nRetrieving X...\n");
	    if ((result = engGetVariable(ep,"X")) == NULL)
	      printf("Oops! You didn't create a variable X.\n\n");
	    else {
		printf("X is class %s\t\n", mxGetClassName(result));
	    }
	}

	/*
	 * We're done! Free memory, close MATLAB engine and exit.
	 */
	printf("Done!\n");
	mxDestroyArray(result);
	engClose(ep);
	
	return EXIT_SUCCESS;
}
//Gateway routine
//sampsPerChanWritten = writeAnalogData(task, writeData, timeout, autoStart, numSampsPerChan)
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//General vars
	char errMsg[512];
	
	//Read input arguments
	float64 timeout;
	int numSampsPerChan;
	bool32 autoStart;
	TaskHandle taskID, *taskIDPtr;

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

	if ((nrhs < 3) || mxIsEmpty(prhs[2]))
		timeout = 10.0;
	else
	{
		timeout = (float64) mxGetScalar(prhs[2]);
		if (mxIsInf(timeout))
			timeout = DAQmx_Val_WaitInfinitely;
	}

	if ((nrhs < 4) || mxIsEmpty(prhs[3])) {
		int32 sampTimingType = 0;
		int32 status = DAQmxGetSampTimingType(taskID,&sampTimingType);
		if (status!=0) {
			mexErrMsgTxt("Failed to get sample timing type from DAQmx.");
		}
		autoStart = (sampTimingType==DAQmx_Val_OnDemand);
	}
	else
		autoStart = (bool32) mxGetScalar(prhs[3]);

	size_t numRows = mxGetM(prhs[1]);
	if ((nrhs < 5) || mxIsEmpty(prhs[4]))
		numSampsPerChan = numRows;
	else
		numSampsPerChan = (int) mxGetScalar(prhs[4]);

	//Verify correct input length

	//Write data
	int32 sampsWritten;
	int32 status;


	switch (mxGetClassID(prhs[1]))
	{	
		case mxUINT16_CLASS:
			status = DAQmxWriteBinaryU16(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt16*) mxGetData(prhs[1]), &sampsWritten, NULL);
		break;

		case mxINT16_CLASS:
			status = DAQmxWriteBinaryI16(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (int16*) mxGetData(prhs[1]), &sampsWritten, NULL);
		break;

		case mxDOUBLE_CLASS:
			status = DAQmxWriteAnalogF64(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (float64*) mxGetData(prhs[1]), &sampsWritten, NULL);
		break;

		default:
			sprintf_s(errMsg,"Class of supplied writeData argument (%s) is not valid", mxGetClassName(prhs[1]));
			mexErrMsgTxt(errMsg);
	}

	//Handle output arguments and errors
	if (!status)
	{
		if (nlhs > 0) {
			plhs[0] = mxCreateDoubleScalar(0);	
			double *sampsPerChanWritten = mxGetPr(plhs[0]);
		}

		//mexPrintf("Successfully wrote %d samples of data\n", sampsWritten);		
	}
	else //Write failed
		handleDAQmxError(status, mexFunctionName());
}
Esempio n. 12
0
//Gateway routine
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//General vars
	char errMsg[512];

	//Read input arguments
	float64 timeout;
	//bool dataIsLogicalOrDouble;  
	    // For unsigned int data (8, 16, or 32-bit) we call DAQmxWriteDigitalU<whatever>() to 
	    // write the data to the buffer.  For logical or double data, we call DAQmxWriteDigitalLines().
	    // For the first, the several channel settings have to be "packed" into a single unsigned int.
	    // For the second, each channel is set individually.
        // Note that a "channel" in this context is a thing you set up with a single call to the 
	    // DAQmxCreateDOChan() function.
	    // That is, a channel can consist of more than one TTL line.  
	    // This var is set to true iff the data is logical or double.
	uInt32 maxLinesPerChannel;
	int32 numSampsPerChan;  // The number of time points to output, aka the number of "scans"
	bool32 autoStart;
	int32 status;
	TaskHandle taskID, *taskIDPtr;

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

	// Get type and dimensions of data array
	mxClassID writeDataClassID = mxGetClassID(prhs[1]);
    bool dataIsLogicalOrDouble = ((writeDataClassID == mxLOGICAL_CLASS) || (writeDataClassID == mxDOUBLE_CLASS)) ;
	mwSize numRows = mxGetM(prhs[1]);
	mwSize numCols = mxGetN(prhs[1]);

	// Determine the timeout
	if ((nrhs < 3) || mxIsEmpty(prhs[2]))
		timeout = DAQmx_Val_WaitInfinitely;
	else
	{
		timeout = (float64) mxGetScalar(prhs[2]);
		if (mxIsInf(timeout) || (timeout < 0))
			timeout = DAQmx_Val_WaitInfinitely;
	}		

	// Determine whether to start automatically or not
	if ((nrhs < 4) || mxIsEmpty(prhs[3]))
	{
		int32 sampleTimingType;
		status = DAQmxGetSampTimingType(taskID, &sampleTimingType) ;
		if (status)
			handleDAQmxError(status,"DAQmxSetSampTimingType");
		if ( sampleTimingType == DAQmx_Val_OnDemand )
		{
			// The task is using on-demand timing, so we want the 
			// new values to be immediately output.  (And trying to call 
			// DAQmxWriteDigitalLines() for an on-demand task, with autoStart set to false, 
			// will error anyway.
			autoStart = (bool32) true;
		}
		else
		{
			autoStart = (bool32) false;
		}
	}
	else
	{
		autoStart = (bool32) mxGetScalar(prhs[3]);
	}

	// Determine the number of scans (time points) to write out
	if ((nrhs < 5) || mxIsEmpty(prhs[4]))
	{
		if (dataIsLogicalOrDouble)
		{
			status = DAQmxGetWriteDigitalLinesBytesPerChan(taskID,&maxLinesPerChannel); 
				// maxLinesPerChannel is maximum number of lines per channel.
				// Each DO "channel" can consist of multiple DO lines.  (A channel is the thing created with 
				// a call to DAQmxCreateDOChan().)  So this returns the maximum number of lines per channel, 
				// across all the channels in the task.  When you call DAQmxWriteDigitalLines(), the data must consist
				// of (number of scans) x (number of channels) x maxLinesPerChannel uint8 elements.  If a particular channel has fewer lines
				// than the max number, the extra ones are ignored.
			if (status)
				handleDAQmxError(status,"DAQmxGetWriteDigitalLinesBytesPerChan");
			numSampsPerChan = (int32) (numRows/maxLinesPerChannel);  // this will do an implicit floor
		}
		else
			numSampsPerChan = (int32) numRows;
	}
	else
	{
		numSampsPerChan = (int32) mxGetScalar(prhs[4]);
	}

	// Verify that the data contains the right number of columns
	uInt32 numberOfChannels;
	status = DAQmxGetTaskNumChans(taskID, &numberOfChannels) ;
	if (status)
		handleDAQmxError(status,"DAQmxGetTaskNumChans");
	if (numCols != numberOfChannels )
	{
		mexErrMsgTxt("Supplied writeData argument must have as many columns as there are channels in the task.");
	}

	// Verify that the data contains enough rows that we won't read off the end of it.
	// Note that for logical or double data, the different lines for each channel must be stored in the *rows*.
	// So for each time point, there's a maxLinesPerChannel x nChannels submatrix for that time point.
	int numberOfRowsNeededPerScan = (dataIsLogicalOrDouble ? maxLinesPerChannel : 1) ;
	int minNumberOfRowsNeeded = numberOfRowsNeededPerScan * numSampsPerChan ;
	if (numRows < minNumberOfRowsNeeded )
	{
		mexErrMsgTxt("Supplied writeData argument does not have enough rows.");
	}

	//Write data
	int32 scansWritten;

	switch (writeDataClassID)
	{	
		case mxUINT32_CLASS:
			status = DAQmxWriteDigitalU32(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt32*) mxGetData(prhs[1]), &scansWritten, NULL);
		break;

		case mxUINT16_CLASS:
			status = DAQmxWriteDigitalU16(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt16*) mxGetData(prhs[1]), &scansWritten, NULL);
		break;

		case mxUINT8_CLASS:
			status = DAQmxWriteDigitalU8(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt8*) mxGetData(prhs[1]), &scansWritten, NULL);
		break;

		case mxLOGICAL_CLASS:
			status = DAQmxWriteDigitalLines(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt8*) mxGetData(prhs[1]), &scansWritten, NULL);
		break;

		case mxDOUBLE_CLASS:
			{
				//Convert DOUBLE data to LOGICAL values
				double *writeDataRaw = mxGetPr(prhs[1]);
				mwSize numElements = mxGetNumberOfElements(prhs[1]);

				uInt8 *writeData = (uInt8 *)mxCalloc(numElements,sizeof(uInt8));					

				for (unsigned int i=0;i<numElements;i++)
				{
					if (writeDataRaw[i] != 0)
						writeData[i] = 1;
				}
				status = DAQmxWriteDigitalLines(taskID, numSampsPerChan, autoStart, timeout, dataLayout, writeData, &scansWritten, NULL);

				mxFree(writeData);
			}
		break;

		default:
			sprintf_s(errMsg,"Class of supplied writeData argument (%s) is not valid", mxGetClassName(prhs[1]));
			mexErrMsgTxt(errMsg);
	}

	// If an error occured at some point during writing, deal with that
	if (status)
		handleDAQmxError(status, mexFunctionName());

	// Handle output arguments, if needed
	if (nlhs > 0) 
	{
		plhs[0] = mxCreateDoubleScalar(0);	
		double * sampsPerChanWritten = mxGetPr(plhs[0]);
		*sampsPerChanWritten = (double)scansWritten ; 
	}
}
Esempio n. 13
0
/* Main mex gateway routine */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] )   { 
    
    integer iprint = (integer)1;
    integer task=(integer)START, csave=(integer)1;
    integer iterations = 0;
    integer total_iterations = 0;

    int  iterMax = 100;
    int  total_iterMax = 200;


    integer   n, m, *nbd=NULL, *iwa=NULL; 
    double  f=0, factr, pgtol, *x, *l, *u, *g, *wa=NULL;
    int     i;
    mxLogical FREE_nbd=false;

    int ndim = 2; /* for lcc compiler, must declare these here, not later ... */
    mwSize dims[2] = { LENGTH_ISAVE, 1 };

    logical lsave[LENGTH_LSAVE];
    integer isave[LENGTH_ISAVE];
    double  dsave[LENGTH_DSAVE];
    
    double *nbd_dbl=NULL;
    long long *nbd_long=NULL;
    
    mxArray *LHS[2];
    mxArray *RHS[3];
    double *tempX, *tempG, *tempIter;
    
    /* Parse inputs. Quite boring */
    
    if (nrhs < 5 ) mexErrMsgTxt("Needs at least 5 input arguments");
    m       = (int)*mxGetPr( prhs[N_m] );
    n       = (integer)mxGetM( prhs[N_x] );
    if ( mxGetN(prhs[N_x]) != 1 ) mexErrMsgTxt("x must be a column vector");
    if ( mxGetM(prhs[N_l]) != n ) mexErrMsgTxt("l must have same size as x");
    if ( mxGetM(prhs[N_u]) != n ) mexErrMsgTxt("u must have same size as x");
    if ( mxGetM(prhs[N_nbd]) != n ) mexErrMsgTxt("nbd must have same size as x");


    if (nlhs < 2 )  mexErrMsgTxt("Should have 2 or 3 output arguments");
    if (!mxIsDouble(prhs[N_x]))
            mexErrMsgTxt("x should be of type double!\n");
    plhs[1] = mxDuplicateArray( prhs[N_x] );
    x       = mxGetPr( plhs[1] );


    l       = mxGetPr( prhs[N_l] );
    u       = mxGetPr( prhs[N_u] );
    if ( isInt( prhs[N_nbd] ) ) {
        nbd     = (integer *)mxGetData( prhs[N_nbd] ); 
    } else {
        debugPrintf("Converting nbd array to integers\n" );
        if (!mxIsDouble(prhs[N_nbd])){
            if (mxIsInt64(prhs[N_nbd])){
                nbd_long = mxGetData( prhs[N_nbd] );
                nbd     = (integer *)mxMalloc( n * sizeof(integer) );
                assert( nbd != NULL );
                FREE_nbd = true;
                /* convert nbd_dbl (in double format) to integers */
                for (i=0;i<n;i++)
                    nbd[i]  = (integer)nbd_long[i];
            } else {
                debugPrintf("Sizeof(int) is %d bits, sizeof(integer) is %d bits\n",
                        CHAR_BIT*sizeof(int),CHAR_BIT*sizeof(integer) );
                /* integer is aliased to 'long int' and should be at least
                 * 32 bits. 'long long' should be at least 64 bits.
                 * On 64-bit Windows, it seems 'long int' is exactly 32 bits,
                 * while on 64-bit linux and Mac, it is 67 bits */
                debugPrintf("Nbd is of type %s\n", mxGetClassName( prhs[N_nbd] ) );
                mexErrMsgTxt("Nbd array not doubles or type int64!\n");
            }
        } else {
            nbd_dbl = mxGetPr( prhs[N_nbd] );
            nbd     = (integer *)mxMalloc( n * sizeof(integer) );
            assert( nbd != NULL );
            FREE_nbd = true;
            /* convert nbd_dbl (in double format) to integers */
            for (i=0;i<n;i++)
                nbd[i]  = (integer)nbd_dbl[i];
        }
    }


    /* some scalar parameters */
    if ( nrhs < N_factr+1 ) 
        factr   = 1.0e7;
    else if (mxGetNumberOfElements( prhs[N_factr] )!=1)
        factr   = 1.0e7;
    else {
        factr   = (double)mxGetScalar( prhs[N_factr] );
        if (factr < 0 )
            mexErrMsgTxt("factr must be >= 0\n");
    }

    if ( nrhs < N_pgtol+1 ) 
        pgtol   = 1.0e-5;
    else if (mxGetNumberOfElements( prhs[N_pgtol] )!=1)
        pgtol   = 1.0e-5;
    else {
        pgtol   = (double)mxGetScalar( prhs[N_pgtol] );
        if (pgtol < 0)
            mexErrMsgTxt("pgtol must be >= 0\n");
    }
    if ( nrhs < N_iprint+1 ) {
        iprint  = (integer)1;
    } else if (mxGetNumberOfElements( prhs[N_iprint] )!=1) {
        iprint  = (integer)1;
    } else {
        iprint = (integer)mxGetScalar( prhs[N_iprint] );
    }
    
    if ( nrhs >= N_iterMax+1 ) 
        iterMax = (int)mxGetScalar( prhs[N_iterMax] );
    if ( nrhs >= N_total_iterMax+1 ) 
        total_iterMax = (int)mxGetScalar( prhs[N_total_iterMax] );
    
    /* allocate memory for arrays */
    g   = (double *)mxMalloc( n * sizeof(double) );
    assert( g != NULL );
    wa      = (double *)mxMalloc( (2*m*n + 5*n + 11*m*m + 8*m ) * sizeof(double) );
    assert( wa != NULL );
    iwa     = (integer *)mxMalloc( (3*n)*sizeof(integer) );
    assert( iwa != NULL );
    

            
    /* -- Finally, done with parsing inputs. Now, call lbfgsb fortran routine */
    
    /* Be careful! This modifies many variables in-place! 
     * Basically, anything without a '&' before it will be changed in the Matlab
     * workspace */
    
    if ( nrhs < N_fcn - 1 )
        mexErrMsgTxt("For this f(x) feature, need more input aguments\n");
    RHS[0] = mxDuplicateArray( prhs[N_fcn] );
    RHS[1] = mxCreateDoubleMatrix(n,1,mxREAL);
    RHS[2] = mxCreateDoubleScalar( 0.0 ); /* The iterations counter */
    tempX = (double*)mxGetPr( RHS[1] );
    if (!mxIsDouble(RHS[2]))
        mexErrMsgTxt("Error trying to create RHS[2]\n");
    tempIter = (double*)mxGetPr( RHS[2] );

    while ( (iterations < iterMax) && (total_iterations < total_iterMax ) ){
        total_iterations++;

        setulb_auto(&n,&m,x,l,u,nbd,&f,g,&factr,&pgtol,wa,iwa,&task,&iprint,
                &csave,lsave,isave,dsave); /* (ftnlen) TASK_LEN, (ftnlen) CSAVE_LEN); */


        if ( IS_FG(task) ) {

            /* copy data from x to RHS[1] or just set pointer with mxSetPr */
            for (i=0;i<n;i++)
                tempX[i] = x[i];
            /*Try being bold: */
            /*mxSetPr( RHS[1], x ); */

            *tempIter = (double)iterations;
            mexCallMATLAB(2,LHS,3,RHS,"feval");
            f = mxGetScalar( LHS[0] );
            if (mxGetM(LHS[1]) != n )
                mexErrMsgTxt("Error with [f,g]=fcn(x) : g wrong size\n");
            if (mxGetN(LHS[1]) != 1 )
                mexErrMsgTxt("Error with [f,g]=fcn(x) : g wrong size (should be column vector)\n");

            /* could use memcpy, or just do it by hand... */
            if (!mxIsDouble(LHS[1]))
                mexErrMsgTxt("[f,g]=fcn(x) did not return g as type double\n");
            tempG = mxGetPr( LHS[1] );
            for (i=0;i<n;i++)
                g[i] = tempG[i];
            /* Or, be a bit bolder: */
            /*g = tempG; // Hmm, crashed */

            continue;
        }
        if ( task==NEW_X ) {
            iterations++;
            continue;
        } else
            break;

    }

    mxDestroyArray( LHS[0] );
    mxDestroyArray( LHS[1] );
    mxDestroyArray( RHS[0] );
    mxDestroyArray( RHS[1] );
            

    
    plhs[0] = mxCreateDoubleScalar( f );
    if ( nlhs >= 3 )
        plhs[2] = mxCreateDoubleScalar( task );
    if ( nlhs >= 4 )
        plhs[3] = mxCreateDoubleScalar( iterations );
    if ( nlhs >= 5 )
        plhs[4] = mxCreateDoubleScalar( total_iterations );
    if ( nlhs >= 6 )
        mexErrMsgTxt("Did not expect more than 5 outputs\n");

    if (FREE_nbd)
        mxFree(nbd);
    mxFree(g);
    mxFree(wa);
    mxFree(iwa);

    return;
}
Esempio n. 14
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  double *dp, *dend, dmax;
  float *fp, *fend, fmax;
  if (nrhs != 1)
      mexErrMsgIdAndTxt("cummax:one_input_required","This function has one input argument.");
  if (nlhs > 1)
      mexErrMsgIdAndTxt("cummax:one_output_required","This function has one output argument.");
  plhs[0] = mxDuplicateArray(prhs[0]);
  if (mxIsEmpty(plhs[0]))
    return;
  switch (mxGetClassID(plhs[0])) {
      case mxDOUBLE_CLASS:
          dp = mxGetData(plhs[0]);
          dend = dp + mxGetNumberOfElements(plhs[0]);
          dmax = *dp++;
          while (dp != dend)
              if (*dp < dmax)
                  *dp++ = dmax;
              else
                  dmax = *dp++;
          break;
      case mxSINGLE_CLASS:
          fp = mxGetData(plhs[0]);
          fend = fp + mxGetNumberOfElements(plhs[0]);
          fmax = *fp++;
          while (fp != fend)
              if (*fp < fmax)
                  *fp++ = fmax;
              else
                  fmax = *fp++;
          break;
      default:
          mexErrMsgIdAndTxt("cummax:unsuppored_class","Input array class not supported: %s",mxGetClassName(plhs[0]));
  }  
}
Esempio n. 15
0
EXPORT int  mongo_bson_buffer_append(struct bson_buffer* b, char* name, mxArray* value) {
    size_t numel = mxGetNumberOfElements(value);
    mxClassID cls = mxGetClassID(value);
    bson* _b = (bson*)b;
    mwSize i, j;
    mwSize dims[MAXDIM];
    mwSize ijk[MAXDIM];
    mwSize sizes[MAXDIM];
    mwSize ndims;
    const mwSize *odims;
    int depth = 0;
    int success;
    if (numel == 1) {
        /* Append a single element using the given name */
        switch (cls) {
        case mxLOGICAL_CLASS:
            return (bson_append_bool(_b, name, ((char*)mxGetData(value))[0]) == BSON_OK);
        case mxDOUBLE_CLASS:
            if (mxIsComplex(value))
                return mongo_bson_buffer_append_complex(b, name, mxGetPr(value)[0], mxGetPi(value)[0]);
            else
                return (bson_append_double(_b, name, mxGetPr(value)[0]) == BSON_OK);
        case mxSINGLE_CLASS:
            return (bson_append_double(_b, name, ((float*)mxGetData(value))[0]) == BSON_OK);
        case mxINT8_CLASS:
            return (bson_append_int(_b, name, ((signed char*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT8_CLASS:
            return (bson_append_int(_b, name, ((unsigned char*)mxGetData(value))[0]) == BSON_OK);
        case mxINT16_CLASS:
            return (bson_append_int(_b, name, ((short*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT16_CLASS:
            return (bson_append_int(_b, name, ((unsigned short*)mxGetData(value))[0]) == BSON_OK);
        case mxINT32_CLASS:
            return (bson_append_int(_b, name, ((int*)mxGetData(value))[0]) == BSON_OK);
        case mxUINT32_CLASS:
            return (bson_append_int(_b, name, ((unsigned int*)mxGetData(value))[0]) == BSON_OK);
        case mxINT64_CLASS: ;
        case mxUINT64_CLASS:
            return (bson_append_long(_b, name, ((int64_t*)mxGetData(value))[0]) == BSON_OK);
        default:
            mexPrintf("BsonBuffer:append - Unhandled type: %s\n", mxGetClassName(value));
            return 0;
        }
    }
    success = (bson_append_start_array(_b, name) == BSON_OK);
    odims = mxGetDimensions(value);
    ndims = mxGetNumberOfDimensions(value);
    memcpy(dims, odims, ndims*sizeof(mwSize));
    if (ndims > 1)
        reverse(dims, ndims);
    i = ndims;
    /* calculate offset to multiply each dimension's index by */
    j = 1;
    do {
        i--;
        sizes[i] = j;
        j *= dims[i];
    } while (i > 0);
    if (ndims == 2 && dims[1] == 1)
        ndims--;  /* 1 dimensional row vector */
    if (ndims > 1) {
        /* reverse row and columns */
        j = dims[ndims-1];
        dims[ndims-1] = dims[ndims-2];
        dims[ndims-2] = j;
        j = sizes[ndims-1];
        sizes[ndims-1] = sizes[ndims-2];
        sizes[ndims-2] = j;
    }
    memset(ijk, 0, ndims * sizeof(mwSize));
    while (success && depth >= 0) {
        if (ijk[depth] < dims[depth]) {
            const char* num = numstr((int)(ijk[depth]++));
            if (depth < (int)(ndims - 1)) {
                depth++;
                success = (bson_append_start_array(_b, num) == BSON_OK);
            }
            else {
                i = 0;
                for (j = 0; j < ndims; j++)
                    i += (ijk[j]-1) * sizes[j];
                switch (cls) {
                case mxLOGICAL_CLASS:
                    success = (bson_append_bool(_b, num, ((char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxDOUBLE_CLASS:
                    if (mxIsComplex(value))
                        success = mongo_bson_buffer_append_complex(b, num, mxGetPr(value)[i], mxGetPi(value)[i]);
                    else
                        success = (bson_append_double(_b, num, mxGetPr(value)[i]) == BSON_OK);
                    break;
                case mxSINGLE_CLASS:
                    success = (bson_append_double(_b, num, ((float*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT8_CLASS:
                    success = (bson_append_int(_b, num, ((signed char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT8_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned char*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT16_CLASS:
                    success = (bson_append_int(_b, num, ((short*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT16_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned short*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT32_CLASS:
                    success = (bson_append_int(_b, num, ((int*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxUINT32_CLASS:
                    success = (bson_append_int(_b, num, ((unsigned int*)mxGetData(value))[i]) == BSON_OK);
                    break;
                case mxINT64_CLASS: ;
                case mxUINT64_CLASS:
                    success = (bson_append_long(_b, num, ((int64_t*)mxGetData(value))[i]) == BSON_OK);
                    break;
                default:
                    mexPrintf("BsonBuffer:append - Unhandled type: %s\n", mxGetClassName(value));
                    return 0;
                }
            }
        }
        else {
            ijk[depth] = 0;
            success = (bson_append_finish_object(_b) == BSON_OK);
            depth--;
        }
    }
    return success;
}
Esempio n. 16
0
void putUnknown(const mxArray *var, MLINK link) {
    const char *classname = mxGetClassName(var);
    MLPutFunction(link, CONTEXT "matUnknown", 1);
    MLPutString(link, classname);
}
//Gateway routine
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//General vars
	char errMsg[512];

	//Read input arguments
	float64 timeout;
	bool writeDigitalLines;
	uInt32 bytesPerChan;
	int numSampsPerChan;
	bool32 autoStart;
	int32 status;
	TaskHandle taskID, *taskIDPtr;

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

	mxClassID writeDataClassID = mxGetClassID(prhs[1]);

	if ((writeDataClassID == mxLOGICAL_CLASS) || (writeDataClassID == mxDOUBLE_CLASS))
		writeDigitalLines = true;
	else
		writeDigitalLines = false;

	if (writeDigitalLines)
	{
		status = DAQmxGetWriteDigitalLinesBytesPerChan(taskID,&bytesPerChan); //This actually returns the number of bytes required to represent one sample of Channel data
		if (status)
			handleDAQmxError(status,"DAQmxGetWriteDigitalLinesBytesPerChan");
	}
	
	if ((nrhs < 3) || mxIsEmpty(prhs[2]))
		timeout = DAQmx_Val_WaitInfinitely;
	else
	{
		timeout = (float64) mxGetScalar(prhs[2]);
		if (mxIsInf(timeout) || (timeout < 0))
			timeout = DAQmx_Val_WaitInfinitely;
	}		

	if ((nrhs < 4) || mxIsEmpty(prhs[3]))
	{
		if (writeDigitalLines)
			autoStart = true;
		else
			autoStart = false;
	}
	else
		autoStart = (bool32) mxGetScalar(prhs[3]);


	mwSize numRows = mxGetM(prhs[1]);
	if ((nrhs < 5) || mxIsEmpty(prhs[4]))
		if (writeDigitalLines)
		{
			numSampsPerChan = numRows / bytesPerChan;
		}
		else 
			numSampsPerChan = numRows;
	else
		numSampsPerChan = (int) mxGetScalar(prhs[4]);


	//Verify correct input length

	//Write data
	int32 sampsWritten;


	switch (writeDataClassID)
	{	
		case mxUINT32_CLASS:
			status = DAQmxWriteDigitalU32(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt32*) mxGetData(prhs[1]), &sampsWritten, NULL);
		break;

		case mxUINT16_CLASS:
			status = DAQmxWriteDigitalU16(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt16*) mxGetData(prhs[1]), &sampsWritten, NULL);
		break;

		case mxUINT8_CLASS:
			status = DAQmxWriteDigitalU8(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt8*) mxGetData(prhs[1]), &sampsWritten, NULL);
		break;

		case mxDOUBLE_CLASS:
		case mxLOGICAL_CLASS:
			{
				if (numRows < (numSampsPerChan * bytesPerChan))
					mexErrMsgTxt("Supplied writeData argument must have at least (numSampsPerChan x numBytesPerChannel) rows.");
				else if (writeDataClassID == mxLOGICAL_CLASS)
					status = DAQmxWriteDigitalLines(taskID, numSampsPerChan, autoStart, timeout, dataLayout, (uInt8*) mxGetData(prhs[1]), &sampsWritten, NULL);
				else //mxDOUBLE_CLASS
				{
					//Convert DOUBLE data to LOGICAL values
					double *writeDataRaw = mxGetPr(prhs[1]);
					mwSize numElements = mxGetNumberOfElements(prhs[1]);

					uInt8 *writeData = (uInt8 *)mxCalloc(numElements,sizeof(uInt8));					

					for (unsigned int i=0;i<numElements;i++)
					{
						if (writeDataRaw[i] != 0)
							writeData[i] = 1;
					}
					status = DAQmxWriteDigitalLines(taskID, numSampsPerChan, autoStart, timeout, dataLayout, writeData, &sampsWritten, NULL);

					mxFree(writeData);
				}
			}

		break;

		default:
			sprintf_s(errMsg,"Class of supplied writeData argument (%s) is not valid", mxGetClassName(prhs[1]));
			mexErrMsgTxt(errMsg);
	}

	//Handle output arguments
	if (nlhs > 0) {
		plhs[0] = mxCreateDoubleScalar(0);	
		double *sampsPerChanWritten = mxGetPr(plhs[0]);

		if (!status)
		{
			//mexPrintf("Successfully wrote %d samples of data\n", sampsWritten);		
			*sampsPerChanWritten = (double)sampsWritten;
		}
		else //Write failed
			handleDAQmxError(status, mexFunctionName());
	}

}
Esempio n. 18
0
 const char* get_classname() const {
   safe_assert(array != NULL, "dereferenced null mxArray");
   return mxGetClassName(array);
 } // end of is class
Esempio n. 19
0
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{

  /* [R, [n]] = general_radon_c( theta, rho, M, dx, dy [, interpolation, method, constraint, valid, rho_x] ) */

  /* INPUTS: */
  /* theta: vector of angles */
  /* rho: vector of (local) rho values */
  /* M: data matrix */
  /* dx,dy: sample size in x (row) and y (column) dimension */
  /* interpolation: interpolation method (0=nearest or 1=linear) */
  /* method: 0=integral, 1=sum, 2=mean, 3=slice, 4=product, 5=logsum */
  /* constraint: 0=no constraint, 1=loop over rows only (i.e. only one element per row contributes to a line), 2=loop over columns only */
  /* valid: 0/1 (valid lines are those lines that span the whole width or height of the input matrix) */
  /* rho_x: 0/1 (if 1, indicates that rho is specified as the intercept with the horizontal center line,
     rather than the distance from the origin, this could be useful if you want rho to be in the same units as the x dimension.
     Notice however, that in this mode, rho will go to infinity if theta approaches +/- pi ) */

  /* OUTPUTS: */
  /* if method is one of integral, sum, mean, product
  /* R: radon transform matrix if method is one of integral, sum, mean, product */
  /* n: number of elements in original matrix contributing to each line*/ 
  /* if method is slice */
  /* R: cell array of projections along lines specified by theta and rho pairs */
  /* n: number of elements in original matrix contributing to each line*/ 

  /* variables */
  int T,R,M,N;
  int t,r,m,n;
  double *theta, *rho, *g;
  double delta_x, delta_y;
  mxArray *out, *tmp, *out2;
  double *pout;
  short *pout2;
  double alpha, beta, betap, costheta, sintheta, rhooffset;
  int mmin, mmax, nmin, nmax, amax;
  double xmin, ymin;
  int rstart, rend;
  double sum;
  int count, method, lininterp, valid, rho_x, constraint;
  double eps=1e-9;
  int indx;
  double nfloat, w;
  int dims[3];
  const char *mclass;
  mxArray *mcopy;

  /* check optional input parameters */
  if (nrhs>5 && mxGetScalar(prhs[5]) ) {
    lininterp=1;
  } else {
    lininterp=0; /* default interpolation is nearest */
  }
  if (nrhs>6 ) {
    method=mxGetScalar(prhs[6]);
  } else {
    method=0; /* default method is integral */
  }
  if (nrhs>7) {
    constraint = (int) mxGetScalar(prhs[7]);
    if (constraint!=1 && constraint!=2)
      constraint = 0;
  } else {
    constraint = 0; /* by default no constraint */
  }
  if (nrhs>8 && mxGetScalar(prhs[8]) ) {
    valid = 1;
  } else {
    valid = 0; /* by default compute all lines */
  }
  if (nrhs>9 && mxGetScalar(prhs[9]) ) {
    rho_x = 1;
  } else {
    rho_x = 0; /* by default rho specifies distance from origin */
  }


  mclass = mxGetClassName(prhs[2]);
  if (!mxIsDouble(prhs[2])) {
    if ( mexCallMATLAB(1, &mcopy, 1, (mxArray**)&prhs[2], "double") )
      mexErrMsgTxt("Could not convert matrix to double precision");
    
    g = mxGetPr( mcopy );
  } else {
    g = mxGetPr( prhs[2] );
  }

  /* get input arguments */
  T = mxGetNumberOfElements( prhs[0] ); /* length theta vector */
  R = mxGetNumberOfElements( prhs[1] ); /* length rho vector */
  M = mxGetM( prhs[2] ); /* number of rows matrix M */
  N = mxGetN( prhs[2] ); /* number of columns matrix M */

  theta = mxGetPr( prhs[0] ); /* pointer to theta vector */
  rho = mxGetPr( prhs[1] ); /* pointer to rho vector */

  delta_x = mxGetScalar( prhs[3] ); /* sample size in x (row) dimension */
  delta_y = mxGetScalar( prhs[4] ); /* sample size in y (column) dimension */

  xmin = -delta_x*(M-1)/2; /* x of lower left corner of matrix M (local coordinates) */
  ymin = -delta_y*(N-1)/2; /* y of lower left corner of matrix M (local coordinates) */


  /* create output matrices */
  if (method==3) {
    out = mxCreateCellMatrix(T,1);
  } else {
    out = mxCreateDoubleMatrix( T,R,mxREAL);
    pout = mxGetPr( out );
  }

  if (nlhs>1) {
    if (method==3) {
      out2 = mxCreateNumericMatrix(T,2,mxINT16_CLASS,mxREAL);
    } else {
      dims[0]=T;
      dims[1]=R;
      dims[2]=2;      
      out2 = mxCreateNumericArray(3,(const int*) &dims, mxINT16_CLASS,mxREAL);
    }
    pout2 = (short*) mxGetPr( out2 );
  }

  /* (minimal) error checking */
  if (method==3 && T!=R)
    mexErrMsgTxt("Theta and rho vectors have incompatible lengths");


  for (t=0;t<T;t++) { /* loop through all angles */

    costheta = cos( theta[t] );
    sintheta = sin( theta[t] );
      
    /* decide whether to loop over samples in x or y dimension */
    if (constraint==1 || (constraint==0 && ( fabs(sintheta)>(delta_x/sqrt(delta_x*delta_x+delta_y*delta_y)) ) ) ) { /* loop over rows */
	
      rhooffset = xmin*costheta + ymin*sintheta;
      alpha = -(delta_x/delta_y)*(costheta/sintheta); /* alpha parameter of line */
	
      /* initialize rho start and end */
      if (method==3) {
	rstart = t;
	rend = rstart+1;
      } else {
	rstart = 0;
	rend = R;
      }
	
      /* loop over all rho values */
      for (r=rstart;r<rend;r++ ) {
	  
	/* compute beta parameter of line */
	if (rho_x)
	  beta = (rho[r]*costheta-rhooffset)/(delta_y*sintheta);
	else
	  beta = (rho[r]-rhooffset)/(delta_y*sintheta);
	  
	/* compute rows to loop over */
	if (lininterp) { 
	  if (alpha>eps) {
	    mmin=(int)ceil(-(beta-eps)/alpha);
	    mmax=1+(int)floor((N-beta-1-eps)/alpha);
	  } else if (alpha<-eps) {
	    mmin=(int)ceil((N-beta-1-eps)/alpha);
	    mmax=1+(int)floor(-(beta-eps)/alpha);
	  } else if (((beta-eps)>0) && ((beta+eps)<(N-1))) {
	    mmin=0;
	    mmax=M;
	  } else {
	    mmin=0;
	    mmax=-1;
	  }
	} else {
	  betap=beta+0.5;
	  if (alpha>eps) {
	    mmin=(int)ceil(-(betap-eps)/alpha);
	    mmax=1+(int)floor((N-betap-eps)/alpha);
	  } else if (alpha<-eps) {
	    mmin=(int)ceil((N-betap-eps)/alpha);
	    mmax=1+(int)floor(-(betap-eps)/alpha);
	  } else if (((betap-eps)>0) && ((betap+eps)<N)) {
	    mmin=0;
	    mmax=M;
	  } else {
	    mmin=0;
	    mmax=-1;
	  }
	}
	if (mmin<0) mmin=0;
	if (mmax>M) mmax=M;
	count=MAX(0,mmax-mmin); /* number of rows to loop over */
	  
	/* check if line is valid */
	if ( ( (valid) && count<M && fabs(alpha*count)<(N-2) ) || (count<=0) ) {
	  if (method==3) {
	    if (nlhs>1) {
	      pout2[t] = 0;
	      pout2[t+T] = 0;
	    }
	  } else {
	    pout[ t+T*r] = mxGetNaN();
	    if (nlhs>1) {
	      pout2[ t+T*r ] = 0;
	      pout2[ t+T*r+T*R ] = 0;
	    }
	  }
	  continue;
	}
	  
	if (method==3) { /* process slice method */
	    
	  tmp = mxCreateDoubleMatrix(count, 1, mxREAL);
	  mxSetCell(out, t, tmp );
	    
/* 	  if (alpha<-eps) */
/* 	    pout = mxGetPr(tmp) + count - 1; */
/* 	  else */
	  pout = mxGetPr(tmp);
	    
	  if (lininterp) {

	    for (m=mmin; m<mmax; m++) {
		
	      nfloat = alpha*m+beta;
	      n = floor(nfloat);
	      w = nfloat-n;
		
	      if (fabs(w)<eps) {
		(*pout)=(g[m+M*n]);
	      } else {
		(*pout)=(g[m+M*n]*(1-w)+g[m+M*(n+1)]*w);
	      }
		
/* 	      if (alpha<-eps) */
/* 		pout--; */
/* 	      else */
	      pout++;
	      
	    }
	  } else {
	    for (m=mmin; m<mmax; m++) {
	      indx = round(alpha*m+beta); /* nearest neighbour */
	      (*pout)= g[m+M*indx];
/* 	      if (alpha<-eps) */
/* 		pout--; */
/* 	      else */
	      pout++;
	    }
	  }
	    
	} else if (method==4) { /* process product method */
	    
	  /* initialize sum to one */
	  sum=1;

	  if (lininterp) {	    

	    for (m=mmin; m<mmax; m++) {
		
	      nfloat = alpha*m+beta;
	      n = floor(nfloat);
	      w = nfloat-n;
		
	      if (fabs(w)<eps) {
		sum*=g[m+M*n];
	      } else {
		sum*=g[m+M*n]*(1-w)+g[m+M*(n+1)]*w;
	      }
		
	    } 

	  } else {

	    for (m=mmin; m<mmax; m++) {

	      indx = round(alpha*m+beta); /* nearest neighbour */
	      sum *= g[m+M*indx];

	    }

	  }
	    
	  pout[t+T*r] = sum;

	} else if (method==5) { /* process log sum method */
	    
	  /* initialize sum to one */
	  sum=0;

	  if (lininterp) {	    

	    for (m=mmin; m<mmax; m++) {
		
	      nfloat = alpha*m+beta;
	      n = floor(nfloat);
	      w = nfloat-n;
		
	      if (fabs(w)<eps) {
		sum+=log(g[m+M*n]);
	      } else {
		sum+=log(g[m+M*n]*(1-w)+g[m+M*(n+1)]*w);
	      }
		
	    } 

	  } else {

	    for (m=mmin; m<mmax; m++) {

	      indx = round(alpha*m+beta); /* nearest neighbour */
	      sum += log(g[m+M*indx]);

	    }

	  }
	    
	  pout[t+T*r] = sum;
	    
	} else { /* process integral, sum and mean methods */
	    
	  /* initialize sum to zero */
	  sum = 0;

	  if (lininterp) {
	    
	    for (m=mmin; m<mmax; m++) {
		
	      nfloat = alpha*m+beta;
	      n = floor(nfloat);
	      w = nfloat-n;
		
	      if (fabs(w)<eps) {
		sum+=g[m+M*n];
	      } else {
		sum+=g[m+M*n]*(1-w)+g[m+M*(n+1)]*w;
	      }
	      
	    }

	  } else {

	    for (m=mmin; m<mmax; m++) {

	      indx = round(alpha*m+beta); /* nearest neighbour */
	      sum += g[m+M*indx];

	    }

	  }
	    
	  if (method==0) /* integral */
	    pout[ t+T*r ] = delta_x*sum/fabs(sintheta);
	  else if (method==1) /* sum */
	    pout[ t+T*r ] = sum;
	  else if (method==2) /* mean */
	    pout[ t+T*r ] = sum/count;
	    
	} /* end conditional on method */
	  
	if (nlhs>1) {
	    
	  if (method==3) {
	    pout2[t] = mmin+1;
	    pout2[t+T] = mmax;
	  } else {
	    pout2[t+T*r] = mmin+1;
	    pout2[t+T*r+T*R] = mmax;
	  }
	    
	}	  
	  
      } /* end loop over rho values */	
	
    } else { /* loop over columns */
	
      alpha = -(delta_y/delta_x)*(sintheta/costheta);
      rhooffset = xmin*costheta + ymin*sintheta;
	
      /* initialize rho start and end */
      if (method==3) {
	rstart = t;
	rend = rstart+1;
      } else {
	rstart = 0;
	rend = R;
      }
	
      /* loop over all rho values */
      for ( r=rstart;r<rend;r++ ) {
	  
	if (rho_x)
	  beta = (rho[r]*costheta-rhooffset)/(delta_x*costheta);
	else
	  beta = (rho[r]-rhooffset)/(delta_x*costheta);
	  
	/* compute columns to loop over */
	if (lininterp) {
	  if (alpha>eps) {
	    nmin=(int)ceil(-(beta-eps)/alpha);
	    nmax=1+(int)floor((M-beta-1-eps)/alpha);
	  } else if (alpha<-eps) {
	    nmin=(int)ceil((M-beta-1-eps)/alpha);
	    nmax=1+(int)floor(-(beta-eps)/alpha);
	  } else if (((beta-eps)>0) && ((beta+eps)<(M-1))) {
	    nmin=0;
	    nmax=N;
	  } else {
	    nmin=0;
	    nmax=-1;
	  }
	} else {
	  betap=beta+0.5;
	  if (alpha>eps) {
	    nmin=(int)ceil(-(betap-eps)/alpha);
	    nmax=1+(int)floor((M-betap-eps)/alpha);
	  } else if (alpha<-eps) {
	    nmin=(int)ceil((M-betap-eps)/alpha);
	    nmax=1+(int)floor(-(betap-eps)/alpha);
	  } else if (((betap-eps)>0) && ((betap+eps)<M)) {
	    nmin=0;
	    nmax=N;
	  } else {
	    nmin=0;
	    nmax=-1;
	  }
	}
	if (nmin<0) nmin=0;
	if (nmax>N) nmax=N;
	count=MAX(0,nmax-nmin); /* number of columns to loop over */
	  
	/* check if line is valid */
	if ( ( (valid) && count<N && fabs(alpha*count)<(M-2) ) || (count<=0) ) {
	  if (method==3) {
	    if (nlhs>1) {
	      pout2[t] = 0;
	      pout2[t+T] = 0;
	    }
	  } else {
	    pout[ t+T*r] = mxGetNaN();
	    if (nlhs>1) {
	      pout2[ t+T*r ] = 0;
	      pout2[ t+T*r+T*R ] = 0;
	    }
	  }	    
	  continue;
	}
	  
	if (method==3) { /* process slice method */
	    
	  tmp = mxCreateDoubleMatrix(count, 1, mxREAL);
	  mxSetCell(out, t, tmp );
	    
	  pout = mxGetPr(tmp);

	  if (lininterp) {
	    
	    for (n=nmin;n<nmax;n++) {
		
	      nfloat = alpha*n+beta;
	      m = floor(nfloat);
	      w = nfloat-m;
		
	      if (fabs(w)<eps) {
		(*pout)=(g[m+M*n]);
	      } else {
		(*pout)=(g[m+M*n]*(1-w)+g[m+1+M*n]*w);
	      }

	      pout++;
		
	    }

	  } else {

	    for (n=nmin;n<nmax;n++) {
		
	      indx = round(alpha*n+beta); /* nearest neighbour */
	      *(pout)=g[n*M+indx];
	      pout++;
		
	    }
	      
	  }
	    
	} else if (method==4) { /* process product */
	    
	  /* initialize sum to one */
	  sum=1;

	  if (lininterp) {
	    
	    for (n=nmin; n<nmax; n++) {
		
	      nfloat = alpha*n+beta;
	      m = floor(nfloat);
	      w = nfloat-m;
		
	      if (fabs(w)<eps) {
		sum*=g[m+M*n];
	      } else {
		sum*=g[m+M*n]*(1-w)+g[m+M*(n+1)]*w;
	      }
		
	    } 

	  } else {

	    for (n=nmin; n<nmax; n++) {
	      indx = round(alpha*n+beta); /* nearest neighbour */
	      sum *= g[n*M+indx];
	    }

	  }
	    
	  pout[t+T*r] = sum;

	} else if (method==5) { /* process log sum */
	    
	  /* initialize sum to one */
	  sum=0;

	  if (lininterp) {
	    
	    for (n=nmin; n<nmax; n++) {
		
	      nfloat = alpha*n+beta;
	      m = floor(nfloat);
	      w = nfloat-m;
		
	      if (fabs(w)<eps) {
		sum+=log(g[m+M*n]);
	      } else {
		sum+=log(g[m+M*n]*(1-w)+g[m+M*(n+1)]*w);
	      }
		
	    } 

	  } else {

	    for (n=nmin; n<nmax; n++) {
	      indx = round(alpha*n+beta); /* nearest neighbour */
	      sum += log(g[n*M+indx]);
	    }

	  }
	    
	  pout[t+T*r] = sum;
	    
	} else { /* process integral, sum and mean methods */
	    
	  /* initialize sum to zero */
	  sum = 0;

	  if (lininterp) {
	    
	    for (n=nmin;n<nmax;n++) {
		
	      nfloat = alpha*n+beta;
	      m = floor(nfloat);
	      w = nfloat-m;
		
	      if (fabs(w)<eps) {
		sum+=g[m+M*n];
	      } else {
		sum+=g[m+M*n]*(1-w)+g[m+1+M*n]*w;
	      }
		
	    }

	  } else {
	      
	    for (n=nmin;n<nmax;n++) {
	      indx = round(alpha*n+beta); /* nearest neighbour */
	      sum+=g[n*M+indx];
	    }	      

	  }
	      
	  if (method==0) /* integral */
	    pout[ t+T*r ] = delta_y*sum/fabs(costheta);
	  else if (method==1) /* sum */
	    pout[ t+T*r ] = sum;
	  else if (method==2) /* mean */
	    pout[ t+T*r ] = sum/count;
	    
	} /* end conditional on method */

	if (nlhs>1) {
	    
	  if (method==3) {
	    pout2[t] = nmin+1;
	    pout2[t+T] = nmax;
	  } else {
	    pout2[t+T*r] = nmin+1;
	    pout2[t+T*r+T*R] = nmax;
	  }
	    
	}
	  
      } /* end loop over rho values */
	
    } /* end conditional rows/columns */

  } /* end loop over angles */

  /* set output arguments */
  plhs[0] = out;
  
  if (nlhs>1)
    plhs[1] = out2;


} /* end mexFunction */
Esempio n. 20
0
void error_unsupported_class(const mxArray *obj) {
  char str[256];
  sprintf(str,"Unsupported class: %s.",mxGetClassName(obj));
  mexErrMsgIdAndTxt("json_encode:UnsupportedClass",str);
}