int get_LinSolvOptions(const mxArray *options, cvmPbData thisPb, booleantype fwd,
                       long int *mupper, long int *mlower,
                       long int *mudq, long int *mldq, double *dqrely,
                       int *ptype, int *gstype, int *maxl)
{
  mxArray *opt;
  char *bufval;
  int buflen, status;
  char *fctName;
  char *fwd_fctName = "CVodeInit/CVodeReInit";
  char *bck_fctName = "CVodeInitB/CVodeReInitB";

  if (fwd) fctName = fwd_fctName;
  else     fctName = bck_fctName;

  *mupper = 0;
  *mlower = 0;

  *mudq = 0;
  *mldq = 0;
  *dqrely = 0.0;

  *ptype = PREC_NONE;
  *gstype = MODIFIED_GS;
  *maxl = 0;

  /* Return now if options was empty */

  if (mxIsEmpty(options)) return(0);

  /* Linear solver type */

  opt = mxGetField(options,0,"LinearSolver");
  if ( !mxIsEmpty(opt) ) {
    buflen = mxGetM(opt) * mxGetN(opt) + 1;
    bufval = mxCalloc(buflen, sizeof(char));
    status = mxGetString(opt, bufval, buflen);
    if(status != 0) {
      cvmErrHandler(-999, "CVODES", fctName, "Cannot parse LinearSolver.", NULL);
      return(-1);
    }
    if(!strcmp(bufval,"Diag"))          ls = LS_DIAG;
    else if(!strcmp(bufval,"Band"))     ls = LS_BAND;
    else if(!strcmp(bufval,"GMRES"))    ls = LS_SPGMR;
    else if(!strcmp(bufval,"BiCGStab")) ls = LS_SPBCG;
    else if(!strcmp(bufval,"TFQMR"))    ls = LS_SPTFQMR;
    else if(!strcmp(bufval,"Dense"))    ls = LS_DENSE;
    else {
      cvmErrHandler(-999, "CVODES", fctName, "LinearSolver has an illegal value.", NULL);
      return(-1);
    }
  }
  
  /* Jacobian function */

  opt = mxGetField(options,0,"JacobianFn");
  if ( !mxIsEmpty(opt) ) {
    mxDestroyArray(mtlb_JACfct);
    mtlb_JACfct  = mxDuplicateArray(opt);
  }

  /* Band linear solver */

  if (ls==LS_BAND) {

    opt = mxGetField(options,0,"UpperBwidth");
    if ( !mxIsEmpty(opt) )
      *mupper = (long int)*mxGetPr(opt);
    
    opt = mxGetField(options,0,"LowerBwidth");
    if ( !mxIsEmpty(opt) )
      *mlower = (long int)*mxGetPr(opt);

  }

  /* SPGMR linear solver options */
  
  if (ls==LS_SPGMR) {

    /* Type of Gram-Schmidt procedure */

    opt = mxGetField(options,0,"GramSchmidtType");
    if ( !mxIsEmpty(opt) ) {
      buflen = mxGetM(opt) * mxGetN(opt) + 1;
      bufval = mxCalloc(buflen, sizeof(char));
      status = mxGetString(opt, bufval, buflen);
      if(status != 0) {
        cvmErrHandler(-999, "CVODES", fctName, "Cannot parse GramSchmidtType.", NULL);
        return(-1);
      }
      if(!strcmp(bufval,"Classical"))     *gstype = CLASSICAL_GS;
      else if(!strcmp(bufval,"Modified")) *gstype = MODIFIED_GS;
      else {
        cvmErrHandler(-999, "CVODES", fctName, "GramSchmidtType has an illegal value.", NULL);
        return(-1);
      }
    }

  }

  /* SPILS linear solver options */

  if ( (ls==LS_SPGMR) || (ls==LS_SPBCG) || (ls==LS_SPTFQMR) ) {

    /* Max. dimension of Krylov subspace */

    opt = mxGetField(options,0,"KrylovMaxDim");
    if ( !mxIsEmpty(opt) ) {
      *maxl = (int)*mxGetPr(opt);
      if (*maxl < 0) {
        cvmErrHandler(-999, "CVODES", fctName, "KrylovMaxDim is negative.", NULL);
        return(-1);
      }
    }

    /* Preconditioning type */

    opt = mxGetField(options,0,"PrecType");
    if ( !mxIsEmpty(opt) ) {
      buflen = mxGetM(opt) * mxGetN(opt) + 1;
      bufval = mxCalloc(buflen, sizeof(char));
      status = mxGetString(opt, bufval, buflen);
      if(status != 0) {
        cvmErrHandler(-999, "CVODES", fctName, "Cannot parse PrecType.", NULL);
        return(-1);
      }
      if(!strcmp(bufval,"Left")) *ptype = PREC_LEFT;
      else if(!strcmp(bufval,"Right")) *ptype = PREC_RIGHT;
      else if(!strcmp(bufval,"Both"))  *ptype = PREC_BOTH;
      else if(!strcmp(bufval,"None"))  *ptype = PREC_NONE;
      else {
        cvmErrHandler(-999, "CVODES", fctName, "PrecType has an illegal value.", NULL);
        return(-1);
      }
    }

    /* User defined precoditioning */

    opt = mxGetField(options,0,"PrecSetupFn");
    if ( !mxIsEmpty(opt) ) {
      mxDestroyArray(mtlb_PSETfct);
      mtlb_PSETfct  = mxDuplicateArray(opt);
    }

    opt = mxGetField(options,0,"PrecSolveFn");
    if ( !mxIsEmpty(opt) ) {
      mxDestroyArray(mtlb_PSOLfct);
      mtlb_PSOLfct  = mxDuplicateArray(opt);
    }

    /* Preconditioner module */
  
    opt = mxGetField(options,0,"PrecModule");
    if ( !mxIsEmpty(opt) ) {
      buflen = mxGetM(opt) * mxGetN(opt) + 1;
      bufval = mxCalloc(buflen, sizeof(char));
      status = mxGetString(opt, bufval, buflen);
      if(status != 0) {
        cvmErrHandler(-999, "CVODES", fctName, "Cannot parse PrecModule.", NULL);
        return(-1);
      }
      if(!strcmp(bufval,"BandPre"))          pm = PM_BANDPRE;
      else if(!strcmp(bufval,"BBDPre"))      pm = PM_BBDPRE;
      else if(!strcmp(bufval,"UserDefined")) pm = PM_NONE;
      else {
        cvmErrHandler(-999, "CVODES", fctName, "PrecModule has an illegal value.", NULL);
        return(-1);
      }
    }

    if (pm != PM_NONE) {
    
      opt = mxGetField(options,0,"UpperBwidth");
      if ( !mxIsEmpty(opt) )
        *mupper = (long int)*mxGetPr(opt);
      
      opt = mxGetField(options,0,"LowerBwidth");
      if ( !mxIsEmpty(opt) )
        *mlower = (long int)*mxGetPr(opt);
      
    }

    if (pm == PM_BBDPRE) {
      
      opt = mxGetField(options,0,"UpperBwidthDQ");
      if ( !mxIsEmpty(opt) )
        *mudq = (long int)*mxGetPr(opt);

      opt = mxGetField(options,0,"LowerBwidthDQ");
      if ( !mxIsEmpty(opt) )
        *mldq = (long int)*mxGetPr(opt);

      opt = mxGetField(options,0,"GlocalFn");
      if ( !mxIsEmpty(opt) ) {
        mxDestroyArray(mtlb_GLOCfct);
        mtlb_GLOCfct  = mxDuplicateArray(opt);
      } else { 
        cvmErrHandler(-999, "CVODES", fctName, "GlocalFn required for BBD preconditioner.", NULL);
        return(-1);
      }      

      opt = mxGetField(options,0,"GcommFn");
      if ( !mxIsEmpty(opt) ) {
        mxDestroyArray(mtlb_GCOMfct);
        mtlb_GCOMfct  = mxDuplicateArray(opt);
      }

    }

  }

  
  /* We made it here without problems */

  return(0);

}
Beispiel #2
0
void build_source(double *nodes_reg, double *inreg, long nnod, long nnod_reg, mxArray *omega,
double D, double *source, long reg, mxArray *q) {

	mxArray *source_strength, *Gns, *zz;
	mxArray *temp_result;
	double xi, yi, zi; 
	long inod, i;
	double rq;
	
	double *q_real, *q_img;
	double *zz_real, *zz_img, *omega_real, *omega_img, *gns_real, *gns_img;
	double *s_strength_real, *s_strength_img, *temp_real, *temp_img, temp_var;

	source_strength = mxCreateDoubleMatrix(1, 1, mxCOMPLEX);
	assert(source_strength != NULL);

	(*(mxGetPr(source_strength))) = 12.4253;
	(*(mxGetPi(source_strength))) = 1.8779;

	zz = mxCreateDoubleMatrix(1,1,mxCOMPLEX);
	Gns = mxCreateDoubleMatrix(1,1,mxCOMPLEX);
	temp_result = mxCreateDoubleMatrix(1,1,mxCOMPLEX);
	
q_real = mxGetPr(q);
	q_img = mxGetPi(q);

	for(i=0; i<nnod; i++)
		*(q_real+i) = *(q_img+i) = 0.0;	

	zz_real = mxGetPr(zz);
	zz_img = mxGetPi(zz);
	omega_real = mxGetPr(omega);
	omega_img = mxGetPi(omega);

	s_strength_real = mxGetPr(source_strength);
	s_strength_img = mxGetPi(source_strength);
	temp_real = mxGetPr(temp_result);
	temp_img = mxGetPi(temp_result);




	for(i = 0; i < nnod_reg; ++i) {
		inod = (long) inreg[i];

		xi =    nodes_reg(i,0);
		yi =    nodes_reg(i,1);
		zi =    nodes_reg(i,2);
		
		if(reg == 1) {
			rq = sqrt(pow(source[0]-xi,2) + pow(source[1]-yi,2) 
				+ pow(source[2]-zi,2));
			
			*zz_real = (*omega_real) * rq;
			*zz_img = (*omega_img) * rq;
			
			temp_var = 4*PI*rq*D;
			gns_real = mxGetPr(Gns);
			gns_img = mxGetPi(Gns);
			cis((*zz_real * -1.0), (*zz_img * -1.0), *gns_real, *gns_img);
			(*gns_real) /= temp_var;
			(*gns_img) /= temp_var; 

			mult_complex(*gns_real, *gns_img, *s_strength_real, *s_strength_img,
					*temp_real, *temp_img); 
			
			(*(q_real+(inod-1))) += *temp_real;
			(*(q_img+(inod-1))) += *temp_img;
		}

	}
	
		mxDestroyArray(zz); 
		mxDestroyArray(temp_result);
		mxDestroyArray(Gns);
		mxDestroyArray(source_strength);
}
MatlabFunctionHandle::~MatlabFunctionHandle() {
  if (f) mxDestroyArray(f);
}
// [outputData, sampsPerChanRead] = readAnalogData(task, numSampsPerChan, outputFormat, timeout, outputVarSizeOrName)
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//Read input arguments

	// Get the task handle
	mxArray *mxTaskID = mxGetProperty(prhs[0],0,"taskID");
	mxClassID clsID = mxGetClassID(mxTaskID);
	localAssert(clsID==TASKHANDLE_MXCLASS);
	TaskHandle *taskIDPtr = (TaskHandle*)mxGetData(mxTaskID);
	TaskHandle taskID = *taskIDPtr;

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

	// Handle input arguments

	int32 numSampsPerChan = 0; // this does take negative vals in the case of DAQmx_Val_Auto
	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]);
	}
	
	char outputFormat[10];
	if ((nrhs < 3) || mxIsEmpty(prhs[2]))
		strcpy_s(outputFormat,"scaled");
	else
		mxGetString(prhs[2], outputFormat, 10);

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

	bool outputData; //Indicates whether to return an outputData argument
	int outputVarSampsPerChan = 0; // this CAN take negative values in case of DAQmx_Val_Auto
	char outputVarName[MAXVARNAMESIZE];	
	if ((nrhs < 5) || mxIsEmpty(prhs[4])) {
		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);
		}
	}

	//Determine output data type
	mxClassID outputDataClass;
	mxArray *mxRawDataArrayAI = mxGetProperty(prhs[0],0,"rawDataArrayAI"); //Stored in MCOS Task object as an empty array of the desired class!
	mxClassID rawDataClass = mxGetClassID(mxRawDataArrayAI); 

	char errorMessage[30];
	if (!_strcmpi(outputFormat,"scaled"))
		outputDataClass = mxDOUBLE_CLASS;
	else if (!_strcmpi(outputFormat,"native"))
		outputDataClass = rawDataClass;
	else {
		sprintf_s(errorMessage,"Unrecognized output format: %s\n",outputFormat);
		mexErrMsgTxt(errorMessage);
	}		

	//Determine # 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 *mxOutputDataBuf = NULL;
	if (outputData)	{
		if (outputVarSampsPerChan == DAQmx_Val_Auto) {
			uInt32 buf = 0;
			status = DAQmxGetReadAvailSampPerChan(taskID,&buf);
			if (status) {
				handleDAQmxError(status, mexFunctionName());
			}
			outputVarSampsPerChan = buf;
		}

		localAssert(outputVarSampsPerChan >= 0);
		mxOutputDataBuf = mxCreateNumericMatrix(outputVarSampsPerChan,numChannels,outputDataClass,mxREAL);
	} else {
		localAssert(false);
		////I don't believe this is working
		//mxOutputDataBuf = mexGetVariable("caller", outputVarName);
		//outputVarSampsPerChan = mxGetM(mxOutputDataBuf);
		////TODO: Add check to ensure WS variable is of correct class
	}

	void* outputDataPtr = mxGetData(mxOutputDataBuf);
	localAssert(outputDataPtr!=NULL);

	uInt32 arraySizeInSamps = outputVarSampsPerChan * numChannels;
	localAssert(mxGetNumberOfElements(mxOutputDataBuf)==(size_t)arraySizeInSamps);
	int32 numSampsPerChanRead;

	
	if (outputDataClass == mxDOUBLE_CLASS) //'scaled' 
		// float64 should be double
		status = DAQmxReadAnalogF64(taskID,numSampsPerChan,timeout,fillMode,
				(float64*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
	else { //'raw'
		switch (outputDataClass)
		{
			case mxINT16_CLASS:
				status = DAQmxReadBinaryI16(taskID, numSampsPerChan, timeout, fillMode, (int16*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
			case mxINT32_CLASS:
				status = DAQmxReadBinaryI32(taskID, numSampsPerChan, timeout, fillMode, (int32*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
			case mxUINT16_CLASS:
				status = DAQmxReadBinaryU16(taskID, numSampsPerChan, timeout, fillMode, (uInt16*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
			case mxUINT32_CLASS:
				status = DAQmxReadBinaryU32(taskID, numSampsPerChan, timeout, fillMode, (uInt32*) outputDataPtr, arraySizeInSamps, &numSampsPerChanRead, NULL);
				break;
		}
	}

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

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

		if (nlhs>1) { //Return number of samples actually read
			plhs[1] = mxCreateDoubleScalar(0.0);	
			double *sampsReadOutput = mxGetPr(plhs[1]);
			*sampsReadOutput = (double)numSampsPerChanRead;
		}
	} else { //Read failed
		handleDAQmxError(status, mexFunctionName());
	}

}
Beispiel #5
0
mxArray * toMx(GPUtype *r, int isscalar=0) {
	// garbage collector
	//MyGCObj<GPUtype> mgc;
	//mgc.setPtr(r);

	mxArray *plhs[1];
	mwSize dims[2] = {1,1};

	if ((r->getNumel() == 1)||(isscalar==1)) {
		if (r->isComplex()) {
			if (r->getType()==gpuCFLOAT) {
				Complex tmpr;
				try {

					GPUopCudaMemcpy(&tmpr, r->getGPUptr(), GPU_SIZE_OF_CFLOAT * 1,
							cudaMemcpyDeviceToHost, r->getGPUmanager());

				} catch (GPUexception ex) {
					mexErrMsgTxt(ex.getError());
				}
				//plhs[0] = mxCreateDoubleMatrix(1, 1, mxCOMPLEX);
				plhs[0] = mxCreateNumericArray(2, dims, mxSINGLE_CLASS, mxCOMPLEX);
				memcpy (mxGetPr(plhs[0]), &tmpr.x, sizeof(float) );
				memcpy (mxGetPi(plhs[0]), &tmpr.y, sizeof(float) );
				//*mxGetPr(plhs[0]) = tmpr.x;
				//*mxGetPi(plhs[0]) = tmpr.y;
			} else if (r->getType()==gpuCDOUBLE){
				DoubleComplex tmpr;
				try {

					GPUopCudaMemcpy(&tmpr, r->getGPUptr(), GPU_SIZE_OF_CDOUBLE * 1,
							cudaMemcpyDeviceToHost, r->getGPUmanager());

				} catch (GPUexception ex) {
					mexErrMsgTxt(ex.getError());
				}
				//plhs[0] = mxCreateDoubleMatrix(1, 1, mxCOMPLEX);
				plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxCOMPLEX);
				memcpy (mxGetPr(plhs[0]), &tmpr.x, sizeof(double) );
				memcpy (mxGetPi(plhs[0]), &tmpr.y, sizeof(double) );

				//*mxGetPr(plhs[0]) = tmpr.x;
				//*mxGetPi(plhs[0]) = tmpr.y;
			}
		} else {
			if (r->getType()==gpuFLOAT) {
				float tmpr = 0.0;
				try {

					GPUopCudaMemcpy(&tmpr, r->getGPUptr(), GPU_SIZE_OF_FLOAT * 1,
							cudaMemcpyDeviceToHost, r->getGPUmanager());

				} catch (GPUexception ex) {
					mexErrMsgTxt(ex.getError());
				}
				//plhs[0] = mxCreateDoubleScalar(tmpr);
				plhs[0] = mxCreateNumericArray(2, dims, mxSINGLE_CLASS, mxREAL);
				memcpy (mxGetPr(plhs[0]), &tmpr, sizeof(float) );
				//*mxGetPr(plhs[0]) = tmpr;
			} else if (r->getType()==gpuDOUBLE) {
				double tmpr = 0.0;
				try {

					GPUopCudaMemcpy(&tmpr, r->getGPUptr(), GPU_SIZE_OF_DOUBLE * 1,
							cudaMemcpyDeviceToHost, r->getGPUmanager());

				} catch (GPUexception ex) {
					mexErrMsgTxt(ex.getError());
				}
				//plhs[0] = mxCreateDoubleScalar(tmpr);
				plhs[0] = mxCreateNumericArray(2, dims, mxDOUBLE_CLASS, mxREAL);
				memcpy (mxGetPr(plhs[0]), &tmpr, sizeof(double) );
				//*mxGetPr(plhs[0]) = tmpr;
			}
		}

		// remove first from Garbage collector
		//mgc.remPtr(r);

		// must delete r
		delete r;
	} else {
	  GPUmanager *gman = r->getGPUmanager();
	  int slot = 0;
	  // request a free slot in cache
		gpuTYPE_t mxtype = gpuNOTDEF;
		
		// first I search for a cached element. mxtype is the tyep of cached
		// element I am looking for. 
		// If the cached element is not found, I have to create a new GPUsingle/GPUdouble
		// which is not registered to the cache. 

		if (r->isFloat())
			mxtype = gpuFLOAT; // complex as well
		if (r->isDouble())
			mxtype = gpuDOUBLE; // complex as well

		// NPN yet implemented
	  //void *mxtmp = gman->extCacheGetFreeSlot(&slot, mxtype);
	  void *mxtmp = gman->extCacheGetFreeSlot(&slot, gpuNOTDEF);

	  if (slot<0) {
	    // internal error
	    mexErrMsgTxt(ERROR_MXID_CACHEINTERNAL);
	  }

	  if (mxtmp==NULL) {
	    // the mxArray is not in cache
      mxArray *prhs[2];
      prhs[0] = mxCreateDoubleScalar(slot);
      prhs[1] = prhs[0];

      //mxArray *tmpr = toMxStruct(r);

      if (r->getType()==gpuCFLOAT) {
        mexCallMATLAB(1, plhs, 2, prhs, "GPUsingle");
      } else if (r->getType()==gpuFLOAT){
        mexCallMATLAB(1, plhs, 2, prhs, "GPUsingle");
      } else if (r->getType()==gpuCDOUBLE){
        mexCallMATLAB(1, plhs, 2, prhs, "GPUdouble");
      } else if (r->getType()==gpuDOUBLE){
        mexCallMATLAB(1, plhs, 2, prhs, "GPUdouble");
      }

      gman->extCacheRegisterPtrBySlot(slot, mxID(plhs[0]), plhs[0], r, gpuNOTDEF);

      //mexPrintf("%p -> %p\n", plhs[0], r);

      // clean up
      mxDestroyArray(prhs[0]);

	  } else {
	    // shoud no be here, not impl.
	    mexErrMsgTxt(ERROR_MXID_CACHEINTERNAL);
	    plhs[0] = (mxArray *) mxtmp;
	    gman->extCacheRegisterPtrBySlot(slot, mxID(plhs[0]), NULL, r, mxtype);
	  }
	  //mexPrintf("************** begin return mx ****************\n");
	  //gman->extCachePrint();

	}

	// remove from gc
	//mgc.remPtr(r);
	mxArray * tmp = plhs[0];
	//printMx1(tmp, 0);
	//mexPrintf("************** end return mx ****************\n");
	//mexPrintf("<- %p\n",tmp->reserved2);
  //mexPrintf("<- %p\n",tmp->data.number_array.pdata);

  return plhs[0];

}
MatlabTemplateComponent::~MatlabTemplateComponent()
{
  mxDestroyArray(matlabInput_);
  mxDestroyArray(matlabOutput_);
}
Beispiel #7
0
PyObject * mlabraw_put(PyObject *, PyObject *args)
{
  char *lName;
  PyObject *lHandle;
  PyObject *lSource;
  PyObject *encoded_source;
  mxArray *lArray = NULL;
  //FIXME should make these objects const
  if (! PyArg_ParseTuple(args, "OsO:put", &lHandle, &lName, &lSource)) return NULL;
  if (! PyCapsule_CheckExact(lHandle)) {
    PyErr_SetString(PyExc_TypeError, "Invalid object passed as mlabraw session handle");
    return NULL;
  }
  Py_INCREF(lSource);

#ifdef PY3K
  if (PyUnicode_Check(lSource)) {
      encoded_source = PyUnicode_AsUTF8String(lSource);
    lArray = char2mx(encoded_source);
    Py_DECREF(encoded_source);
#else
  if (PyString_Check(lSource)) {
    lArray = char2mx(lSource);
#endif
  } else {
    lArray = numeric2mx(lSource);
  }
  Py_DECREF(lSource);

  if (lArray == NULL) {
    return NULL;   // Above converter already set error message
  }


// for matlab version >= 6.5 (FIXME UNTESTED)
#ifdef _V6_5_OR_LATER
  if (engPutVariable((Engine *)PyCapsule_GetPointer(lHandle, NULL), lName, lArray) != 0) {
#else
  mxSetName(lArray, lName);
  if (engPutArray((Engine *)PyCapsule_GetPointer(lHandle, NULL), lArray) != 0) {
#endif
    PyErr_SetString(mlabraw_error,
                   "Unable to put matrix into MATLAB(TM) workspace");
    mxDestroyArray(lArray);
    return NULL;
  }
  mxDestroyArray(lArray);
  Py_INCREF(Py_None);
  return Py_None;
}

static const char * DOC = 
    "Mlabraw -- Low-level MATLAB(tm) Engine Interface\n"
    "\n"
    "  open  - Open a MATLAB(tm) engine session\n"
    "  close - Close a MATLAB(tm) engine session\n"
    "  eval  - Evaluates a string in the MATLAB(tm) session\n"
    "  get   - Gets a matrix from the MATLAB(tm) session\n"
    "  put   - Places a matrix into the MATLAB(tm) session\n"
    "\n"
    "The Numeric package must be installed for this module to be used.\n"
    "\n"
    "Copyright & Disclaimer\n"
    "======================\n"
    "Copyright (c) 2002-2007 Alexander Schmolck <*****@*****.**>\n"
    "\n"
    "Copyright (c) 1998,1999 Andrew Sterian. All Rights Reserved. mailto: [email protected]\n"
    "\n"
    "Copyright (c) 1998,1999 THE REGENTS OF THE UNIVERSITY OF MICHIGAN. ALL RIGHTS RESERVED \n"
    "\n"
    "Permission to use, copy, modify, and distribute this software and its\n"
    "documentation for any purpose and without fee is hereby granted, provided\n"
    "that the above copyright notices appear in all copies and that both these\n"
    "copyright notices and this permission notice appear in supporting\n"
    "documentation, and that the name of The University of Michigan not be used\n"
    "in advertising or publicity pertaining to distribution of the software\n"
    "without specific, written prior permission.\n"
    "\n"
    "THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION AS TO ITS FITNESS\n"
    "FOR ANY PURPOSE, AND WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR\n"
    "IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF\n"
    "MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE REGENTS OF THE\n"
    "UNIVERSITY OF MICHIGAN SHALL NOT BE LIABLE FOR ANY DAMAGES, INCLUDING\n"
    "SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY\n"
    "CLAIM ARISING OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN IF\n"
    "IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.\n"
    "\n";

static PyMethodDef MlabrawMethods[] = {
  { "open",       mlabraw_open,       METH_VARARGS, open_doc },
  { "close",      mlabraw_close,      METH_VARARGS, close_doc },
  { "oldeval",    mlabraw_oldeval,    METH_VARARGS, ""       },
  { "eval",       mlabraw_eval,       METH_VARARGS, eval_doc },  //FIXME doc
  { "get",        mlabraw_get,        METH_VARARGS, get_doc },
  { "put",        mlabraw_put,        METH_VARARGS, put_doc },
  { NULL,         NULL,               0           , NULL}, // sentinel
};

struct module_state {
    PyObject *error;
};

#ifdef PY3K
    #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
#else
    #define GETSTATE(m) (&_state)
    static struct module_state _state;
#endif

#ifdef PY3K
    static int myextension_traverse(PyObject *m, visitproc visit, void *arg) {
        Py_VISIT(GETSTATE(m)->error);
        return 0;
    }
    static int myextension_clear(PyObject *m) {
        Py_CLEAR(GETSTATE(m)->error);
        return 0;
    }
Beispiel #8
0
// Interface function of matlab
// now assume prhs[0]: label prhs[1]: features
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    const char *error_msg;

    // fix random seed to have same results for each run
    // (for cross validation and probability estimation)
    srand(1);

    // Transform the input Matrix to libsvm format
    if(nrhs > 1 && nrhs < 4)
    {
        int err;

        if(!mxIsDouble(prhs[0]) || !mxIsDouble(prhs[1])) {
            mexPrintf("Error: label vector and instance matrix must be double\n");
            fake_answer(plhs);
            return;
        }

        if(parse_command_line(nrhs, prhs, NULL))
        {
            exit_with_help();
            svm_destroy_param(&param);
            fake_answer(plhs);
            return;
        }

        if(mxIsSparse(prhs[1]))
        {
            if(param.kernel_type == PRECOMPUTED)
            {
                // precomputed kernel requires dense matrix, so we make one
                mxArray *rhs[1], *lhs[1];

                rhs[0] = mxDuplicateArray(prhs[1]);
                if(mexCallMATLAB(1, lhs, 1, rhs, "full"))
                {
                    mexPrintf("Error: cannot generate a full training instance matrix\n");
                    svm_destroy_param(&param);
                    fake_answer(plhs);
                    return;
                }
                err = read_problem_dense(prhs[0], lhs[0]);
                mxDestroyArray(lhs[0]);
                mxDestroyArray(rhs[0]);
            }
            else
                err = read_problem_sparse(prhs[0], prhs[1]);
        }
        else
            err = read_problem_dense(prhs[0], prhs[1]);

        // svmtrain's original code
        error_msg = svm_check_parameter(&prob, &param);

        if(err || error_msg)
        {
            if (error_msg != NULL)
                mexPrintf("Error: %s\n", error_msg);
            svm_destroy_param(&param);
            free(prob.y);
            free(prob.x);
            free(x_space);
            fake_answer(plhs);
            return;
        }

        if(cross_validation)
        {
            double *ptr;
            plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
            ptr = mxGetPr(plhs[0]);
            ptr[0] = do_cross_validation();
        }
        else
        {
            int nr_feat = (int)mxGetN(prhs[1]);
            const char *error_msg;
            model = svm_train(&prob, &param);
            error_msg = model_to_matlab_structure(plhs, nr_feat, model);
            if(error_msg)
                mexPrintf("Error: can't convert libsvm model to matrix structure: %s\n", error_msg);
            svm_free_and_destroy_model(&model);
        }
        svm_destroy_param(&param);
        free(prob.y);
        free(prob.x);
        free(x_space);
    }
    else
    {
        exit_with_help();
        fake_answer(plhs);
        return;
    }
}
void
mexFunction(int nout, mxArray *out[], 
            int nin, const mxArray *in[])
{
  enum {IN_GRAD=0,IN_FRAMES,IN_END} ;
  enum {OUT_DESCRIPTORS} ;

  int                verbose = 0 ;
  int                opt ;
  int                next = IN_END ;
  mxArray const     *optarg ;
     
  mxArray           *grad_array ;
  vl_sift_pix       *grad ;
  int                M, N ;

  double             magnif = -1 ;
  double            *ikeys = 0 ;
  int                nikeys = 0 ;

  int i,j ;
  
  VL_USE_MATLAB_ENV ;
  
  /* -----------------------------------------------------------------
   *                                               Check the arguments
   * -------------------------------------------------------------- */

  if (nin < 2) {
    mexErrMsgTxt("Two arguments required.") ;
  } else if (nout > 1) {
    mexErrMsgTxt("Too many output arguments.");
  }
  
  if (mxGetNumberOfDimensions (in[IN_GRAD])    != 3              ||
      mxGetClassID            (in[IN_GRAD])    != mxSINGLE_CLASS ||
      mxGetDimensions         (in[IN_GRAD])[0] != 2              ) {
    mexErrMsgTxt("GRAD must be a 2xMxN matrix of class SINGLE.") ;
  }

  if (!uIsRealMatrix(in[IN_FRAMES], 4, -1)) {
    mexErrMsgTxt("FRAMES must be a 4xN matrix.") ;
  }
  nikeys = mxGetN (in[IN_FRAMES]) ;
  ikeys  = mxGetPr(in[IN_FRAMES]) ;
  
  while ((opt = uNextOption(in, nin, options, &next, &optarg)) >= 0) {
    switch (opt) {
        
      case opt_verbose :
        ++ verbose ;
        break ;
        
      case opt_magnif :
        if (!uIsRealScalar(optarg) || (magnif = *mxGetPr(optarg)) < 0) {
          mexErrMsgTxt("MAGNIF must be a non-negative scalar.") ;
        }
        break ;
        
      default :
        assert(0) ;
        break ;
    }
  }
  
  grad_array = mxDuplicateArray(in[IN_GRAD]) ;  
  grad = (vl_sift_pix*) mxGetData (grad_array) ;
  M    = mxGetDimensions(in[IN_GRAD])[1] ;
  N    = mxGetDimensions(in[IN_GRAD])[2] ;

  /* transpose angles */
  for (i = 1 ; i < 2*M*N ; i+=2) {
    grad [i] = VL_PI/2 - grad [i] ;
  }

  /* -----------------------------------------------------------------
   *                                                            Do job
   * -------------------------------------------------------------- */
  {
    VlSiftFilt *filt = 0 ;    
    vl_uint8   *descr = 0 ;

    /* create a filter to process the image */
    filt = vl_sift_new (M, N, -1, -1, 0) ;
    
    if (magnif >= 0) vl_sift_set_magnif (filt, magnif) ;
    
    if (verbose) {    
      mexPrintf("siftdescriptor: filter settings:\n") ;
      mexPrintf("siftdescriptor:   magnif                = %g\n",
                vl_sift_get_magnif (filt)) ;
      mexPrintf("siftdescriptor:   num of frames         = %d\n",
                nikeys) ;
    }

    {
      mwSize dims [2] ;
      dims [0] = 128 ;
      dims [1] = nikeys ;
      out[OUT_DESCRIPTORS]= mxCreateNumericArray 
        (2, dims, mxUINT8_CLASS,  mxREAL) ;
      descr = mxGetData(out[OUT_DESCRIPTORS]) ;
    }
    
    /* ...............................................................
     *                                             Process each octave
     * ............................................................ */
    for (i = 0 ; i < nikeys ; ++i) {
      vl_sift_pix  buf [128], rbuf [128] ;

      double y  = *ikeys++ - 1 ;
      double x  = *ikeys++ - 1 ;
      double s  = *ikeys++ ;
      double th = VL_PI / 2 - *ikeys++ ;

      vl_sift_calc_raw_descriptor (filt, 
                                   grad, 
                                   buf,
                                   M, N,
                                   x, y, s, th) ;
      
      transpose_descriptor (rbuf, buf) ;
      
      for (j = 0 ; j < 128 ; ++j) {
        double x = 512.0 * rbuf [j] ;
        x = (x < 255.0) ? x : 255.0 ;
        *descr++ = (vl_uint8) (x) ;
      }
    }    
    /* cleanup */
    mxDestroyArray (grad_array) ;
    vl_sift_delete (filt) ;
  } /* job done */    
}
void mexFunction(
          int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray* prhs[] )
{
    mwIndex i, j, k;
    mwSize m, n, r;
    mxArray *Ri;
    double *Rivals, *Ctvals, *Uvals;
    char *uplo = "U";
    char *TRANS = "T";
    char *NOTRANS = "N";
    ptrdiff_t N, NB, M, RR, info = 0;
    double lambdaval;
    mwIndex *CtIr, *CtJc;
    mxArray *scaledUi;
    double *scaledUivals;
    double one = 1.0;
    double zero = 0.0;
    mwSize nb;
    mwIndex *Ctcol;
    double coeff;
    
    if(nrhs != 3 || nlhs != 1)
        mexErrMsgTxt("Invalid number of input/output parameter. Need 3 inputs and 1 output.");
    
    m = mxGetM(Ct);
    n = mxGetN(Ct);
    r = mxGetN(U);
    if(mxGetM(U) != m)
        mexErrMsgTxt("Dimensions mismatch in input arguments.");
    
    if(!mxIsSparse(Ct))
        mexErrMsgTxt("Ct ought to be a sparse matrix.");
    
    lambdaval = mxGetScalar(lambda);
    
    CtIr = mxGetIr(Ct);
    CtJc = mxGetJc(Ct);
    Ctvals = mxGetPr(Ct);
    Uvals = mxGetPr(U);
    
    N  = (ptrdiff_t) n;
    M  = (ptrdiff_t) m;
    RR = (ptrdiff_t) r;
    
    /* dummy matrix, for memory allocation */
    scaledUi = mxCreateDoubleMatrix(m, r, mxREAL);
    scaledUivals = mxGetPr(scaledUi);
    
    /* Create a suitable cell */
    R = mxCreateCellMatrix(n, 1);
    for(i = 0; i < n; ++i)
        mxSetCell(R, i, NULL);
    
    for(i = 0; i < n; ++i)
    {
        /* allocate space for an r-by-r matrix in each cell entry */
        mxSetCell(R, i, mxCreateDoubleMatrix(r, r, mxREAL));
        Ri = mxGetCell(R, i);
        Rivals = mxGetPr(Ri);
        
        /* compute the entries of the matrix R{i}
           nb is the number of nonzero entries in the i-th column of Ct
           Ctcol is a pointer to an array of nb elements: the indices of
           rows where a nonzero element exists on column i of Ct. */
        nb = CtJc[i+1]-CtJc[i];
        /* mexPrintf("%d ", nb); */
        Ctcol = CtIr+CtJc[i];
        if(nb > 0)
        {
            for(j = 0; j < nb; ++j)
            {
                /* coeff = Ct(Ctcol[j], i) */
                /* Correction on Oct. 15, 2014 */
                coeff = Ctvals[CtJc[i]+j];
                /* mexPrintf("%g ", coeff); */
                for(k = 0; k < r; ++k)
                {
                    /* scaledUi(j, k) = coeff * U(Ctcol[j], k) */
                    scaledUivals[j+k*m] = coeff * Uvals[Ctcol[j]+k*m];
                }
            }
            /*   mexPrintf("\n"); */
            /* compute the matrix product of the interesting part of
               scaledUi with itself (transposed): Ri = scaledUi.'*scaledUi */
            NB = (ptrdiff_t) nb;
            dgemm(TRANS, NOTRANS, &RR, &RR, &NB, &one,
                  scaledUivals, &M, scaledUivals, &M, &zero, Rivals, &RR);
        }
        else
        {
            for(j = 0; j < r*r; ++j)
                Rivals[j] = 0.0;
        }
        
        /* add lambda*eye(r) to Ri */
        for(j = 0; j < r; ++j)
            Rivals[j*(r+1)] += lambdaval;
        
        /* remplace R{i} by its Cholesky factor by calling Lapack's dpotrf. */
        dpotrf(uplo, &RR, Rivals, &RR, &info);
        /* write zeroes on the lower triangular parts of Ri */
        for(j = 1; j < r; ++j)
            for(k = 0; k < j; ++k)
                Rivals[j+r*k] = 0.0;
        
        if(info < 0)
            mexErrMsgTxt("dpotrf (in spbuildmatrix): invalid argument.");
        if(info > 0)
            mexErrMsgTxt("dpotrf (in spbuildmatrix): a leading minor is not positive definite.");
    }
    
    mxDestroyArray(scaledUi);
    
    return;
}
Beispiel #11
0
int read_problem_sparse(const mxArray *label_vec, const mxArray *instance_mat)
{
    int i, j, k, low, high;
    mwIndex *ir, *jc;
    int elements, max_index, num_samples, label_vector_row_num;
    double *samples, *labels;
    mxArray *instance_mat_col; // transposed instance sparse matrix

    prob.x = NULL;
    prob.y = NULL;
    x_space = NULL;

    // transpose instance matrix
    {
        mxArray *prhs[1], *plhs[1];
        prhs[0] = mxDuplicateArray(instance_mat);
        if(mexCallMATLAB(1, plhs, 1, prhs, "transpose"))
        {
            mexPrintf("Error: cannot transpose training instance matrix\n");
            return -1;
        }
        instance_mat_col = plhs[0];
        mxDestroyArray(prhs[0]);
    }

    // each column is one instance
    labels = mxGetPr(label_vec);
    samples = mxGetPr(instance_mat_col);
    ir = mxGetIr(instance_mat_col);
    jc = mxGetJc(instance_mat_col);

    num_samples = (int)mxGetNzmax(instance_mat_col);

    // the number of instance
    prob.l = (int)mxGetN(instance_mat_col);
    label_vector_row_num = (int)mxGetM(label_vec);

    if(label_vector_row_num!=prob.l)
    {
        mexPrintf("Length of label vector does not match # of instances.\n");
        return -1;
    }

    elements = num_samples + prob.l;
    max_index = (int)mxGetM(instance_mat_col);

    prob.y = Malloc(double,prob.l);
    prob.x = Malloc(struct svm_node *,prob.l);
    x_space = Malloc(struct svm_node, elements);

    j = 0;
    for(i=0; i<prob.l; i++)
    {
        prob.x[i] = &x_space[j];
        prob.y[i] = labels[i];
        low = (int)jc[i], high = (int)jc[i+1];
        for(k=low; k<high; k++)
        {
            x_space[j].index = (int)ir[k] + 1;
            x_space[j].value = samples[k];
            j++;
        }
        x_space[j++].index = -1;
    }

    if(param.gamma == 0 && max_index > 0)
        param.gamma = 1.0/max_index;

    return 0;
}
void ttCallBlockSystem(int nOutp, double *outp, int nInp, double *inp, const char *blockName) {
  
  mxArray *simsetRHS[8];
  mxArray *simRHS[4];
  mxArray *simLHS[3];
  mxArray *options[1];
  mxArray *states;
  double *values;
  double *state_values;
  int i, j, n;

  DataNode* dn;
  Blockdata *bd;

  // Make sure that the Simulink block exists in Matlab path
  mxArray *lhs[1];
  mxArray *rhs[1];
  rhs[0] = mxCreateString(blockName);
  mexCallMATLAB(1, lhs, 1, rhs, "exist");
  int number = (int) *mxGetPr(lhs[0]);
  if (number == 0) {
    TT_MEX_ERROR("ttCallBlockSystem: Simulink block not in path!");
    for (j=0; j < nOutp; j++) {
      outp[j] = 0.0;
    }
    return;
  }

  Task* task = rtsys->running;
  dn = (DataNode*) getNode(blockName, task->blockList);

  if (dn==NULL) {
    // Not found, create options mxArray (Matlab struct) 

    bd = new Blockdata(blockName);
    
    simsetRHS[0] = mxCreateString("Solver");
    simsetRHS[1] = mxCreateString("FixedStepDiscrete");
    simsetRHS[2] = mxCreateString("FixedStep");
	simsetRHS[3] = mxCreateDoubleScalar(1.0);
    simsetRHS[4] = mxCreateString("MaxDataPoints");
	simsetRHS[5] = mxCreateDoubleScalar(2.0);
    simsetRHS[6] = mxCreateString("OutputVariables");
    simsetRHS[7] = mxCreateString("xy");
    
    mexCallMATLAB(1, options, 8, simsetRHS, "simset");
    
    bd->options = options[0];
    mexMakeArrayPersistent(bd->options);
    
    for (i=0; i<8; i++) {
      mxDestroyArray(simsetRHS[i]);
    }
    task->blockList->appendNode(new DataNode(bd, bd->blockName));
  } else {
    bd = (Blockdata*) dn->data;
  }

  // [t,x,outp] = sim(blockName,1,options,[0 inp]) 

  simRHS[0] = mxCreateString(blockName);
  simRHS[1] = mxCreateDoubleScalar(1.0);
  simRHS[2] = bd->options;
  simRHS[3] = mxCreateDoubleMatrix(1, nInp+1, mxREAL);
  values = mxGetPr(simRHS[3]);
  values[0] = 0.0;
  for (j=0; j < nInp; j++) {
    values[j+1] = inp[j];
  }

  i = mexCallMATLAB(3, simLHS, 4, simRHS, "sim");

  mxDestroyArray(simRHS[0]);
  mxDestroyArray(simRHS[1]);
  mxDestroyArray(simRHS[3]);

  if (i==0) { // Successful
    // Update options mxArray with last row of returned state matrix 
    n = mxGetN(simLHS[1]); // Number of cols of state matrix 
    
    states = mxCreateDoubleMatrix(1, n, mxREAL);

    values = mxGetPr(simLHS[1]);
    state_values = mxGetPr(states);
    
    // Transfer values 
    for (j=0; j < n; j++) {
      state_values[j] = values[2*j+1]; // second row elements
    }

    mxArray* oldstates = mxGetField(bd->options, 0, "InitialState");
    mxDestroyArray(oldstates);
    mxSetField(bd->options, 0, "InitialState", states);
    
    // Return the output of the simulation, first row of returned output matrix 
    values = mxGetPr(simLHS[2]);
    for (j=0; j < nOutp; j++) {
      outp[j] = values[2*j];          // first row elements
    }

    mxDestroyArray(simLHS[0]);
    mxDestroyArray(simLHS[1]);
    mxDestroyArray(simLHS[2]);

  } else {

    TT_MEX_ERROR("ttCallBlockSystem: Simulation failed!");
    for (j=0; j < nOutp; j++) {
      outp[j] = 0.0;
    }
  }
}
Beispiel #13
0
void mexFunction
(
    int	nargout,
    mxArray *pargout [ ],
    int	nargin,
    const mxArray *pargin [ ]
    )
{
  double dummy = 0, beta [2], *px, *C, *Ct, *C2, *fil, *Zt, *zt, done=1.0, *zz, dzero=0.0;
  cholmod_sparse Amatrix, *A, *Lsparse ;
  cholmod_factor *L ;
  cholmod_common Common, *cm ;
  Int minor, *It2, *Jt2 ;
  mwIndex l, k2, h, k, i, j, ik, *I, *J, *Jt, *It, *I2, *J2, lfi, *w, *w2, *r;
  mwSize nnz, nnzlow, m, n;
  int nz = 0;
  mwSignedIndex one=1, lfi_si;
  mxArray *Am, *Bm;
  char *uplo="L", *trans="N";
  

  /* ---------------------------------------------------------------------- */
  /* Only one input. We have to find first the Cholesky factorization.      */ 
  /* start CHOLMOD and set parameters */ 
  /* ---------------------------------------------------------------------- */

  if (nargin == 1) {
    cm = &Common ;
    cholmod_l_start (cm) ;
    sputil_config (SPUMONI, cm) ;
    
    /* convert to packed LDL' when done */
    cm->final_asis = FALSE ;
    cm->final_super = FALSE ;
    cm->final_ll = FALSE ;
    cm->final_pack = TRUE ;
    cm->final_monotonic = TRUE ;

    /* since numerically zero entries are NOT dropped from the symbolic
     * pattern, we DO need to drop entries that result from supernodal
     * amalgamation. */
    cm->final_resymbol = TRUE ;

    cm->quick_return_if_not_posdef = (nargout < 2) ;
  }

  /* This will disable the supernodal LL', which will be slow. */
  /* cm->supernodal = CHOLMOD_SIMPLICIAL ; */
  
  /* ---------------------------------------------------------------------- */
  /* get inputs */
  /* ---------------------------------------------------------------------- */
  
  if (nargin > 3)
    {
      mexErrMsgTxt ("usage: Z = sinv(A), or Z = sinv(LD, 1)") ;
    }
  
  n = mxGetM (pargin [0]) ;
  m = mxGetM (pargin [0]) ;
  
  if (!mxIsSparse (pargin [0]))
    {
      mexErrMsgTxt ("A must be sparse") ;
    }
  if (n != mxGetN (pargin [0]))
    {
      mexErrMsgTxt ("A must be square") ;
    }

  /* Only one input. We have to find first the Cholesky factorization.      */
  if (nargin == 1) {
    /* get sparse matrix A, use tril(A)  */
    A = sputil_get_sparse (pargin [0], &Amatrix, &dummy, -1) ; 
    
    A->stype = -1 ;	    /* use lower part of A */
    beta [0] = 0 ;
    beta [1] = 0 ;
    
    /* ---------------------------------------------------------------------- */
    /* analyze and factorize */
    /* ---------------------------------------------------------------------- */
    
    L = cholmod_l_analyze (A, cm) ;
    cholmod_l_factorize_p (A, beta, NULL, 0, L, cm) ;
    
    if (cm->status != CHOLMOD_OK)
      {
	mexErrMsgTxt ("matrix is not positive definite") ;
      }
    
    /* ---------------------------------------------------------------------- */
    /* convert L to a sparse matrix */
    /* ---------------------------------------------------------------------- */

    Lsparse = cholmod_l_factor_to_sparse (L, cm) ;
    if (Lsparse->xtype == CHOLMOD_COMPLEX)
      {
	mexErrMsgTxt ("matrix is complex") ;
      }
    
    /* ---------------------------------------------------------------------- */
    /* Set the sparse Cholesky factorization in Matlab format */
    /* ---------------------------------------------------------------------- */
    /*Am = sputil_put_sparse (&Lsparse, cm) ;
      I = mxGetIr(Am);
      J = mxGetJc(Am);
      C = mxGetPr(Am);
      nnz = mxGetNzmax(Am); */

    It2 = Lsparse->i;
    Jt2 = Lsparse->p;
    Ct = Lsparse->x;
    nnz = (mwSize) Lsparse->nzmax;

    Am = mxCreateSparse(m, m, nnz, mxREAL) ;
    I = mxGetIr(Am);
    J = mxGetJc(Am);
    C = mxGetPr(Am);
    for (j = 0 ;  j < n+1 ; j++)  J[j] = (mwIndex) Jt2[j];
    for ( i = 0 ; i < nnz ; i++) {
	I[i] = (mwIndex) It2[i];
	C[i] = Ct[i];
    }
    
    cholmod_l_free_sparse (&Lsparse, cm) ;

    /*FILE *out1 = fopen( "output1.txt", "w" );
    if( out1 != NULL )
      fprintf( out1, "Hello %d\n", nnz );
      fclose (out1);*/
    
  } else {
    /* The cholesky factorization is given as an input.      */
    /* We have to copy it into workspace                     */
    It = mxGetIr(pargin [0]);
    Jt = mxGetJc(pargin [0]);
    Ct = mxGetPr(pargin [0]);
    nnz = mxGetNzmax(pargin [0]);
    
    Am = mxCreateSparse(m, m, nnz, mxREAL) ;
    I = mxGetIr(Am);
    J = mxGetJc(Am);
    C = mxGetPr(Am);
    for (j = 0 ;  j < n+1 ; j++)  J[j] = Jt[j];
    for ( i = 0 ; i < nnz ; i++) {
	I[i] = It[i];
	C[i] = Ct[i];
    }    
  }

  /* Evaluate the sparse inverse */
  C[nnz-1] = 1.0/C[J[m-1]];               /* set the last element of sparse inverse */
  fil = mxCalloc((mwSize)1,sizeof(double));
  zt = mxCalloc((mwSize)1,sizeof(double));
  Zt = mxCalloc((mwSize)1,sizeof(double));
  zz = mxCalloc((mwSize)1,sizeof(double));
  for (j=m-2;j!=-1;j--){
    lfi = J[j+1]-(J[j]+1);
    
    /* if (lfi > 0) */
    if ( J[j+1] > (J[j]+1) )
      {
	/*	printf("lfi = %u \n ", lfi);
	printf("lfi*double = %u \n", (mwSize)lfi*sizeof(double));
	printf("lfi*lfi*double = %u \n", (mwSize)lfi*(mwSize)lfi*sizeof(double));
	printf("\n \n");
	*/
	
	fil = mxRealloc(fil,(mwSize)lfi*sizeof(double));
	for (i=0;i<lfi;i++) fil[i] = C[J[j]+i+1];                   /* take the j'th lower triangular column of the Cholesky */
	
	zt = mxRealloc(zt,(mwSize)lfi*sizeof(double));              /* memory for the sparse inverse elements to be evaluated */
	Zt = mxRealloc(Zt,(mwSize)lfi*(mwSize)lfi*sizeof(double));  /* memory for the needed sparse inverse elements */
	
	/* Set the lower triangular for Zt */
	k2 = 0;
	for (k=J[j]+1;k<J[j+1];k++){
	  ik = I[k];
	  h = k2;
	  for (l=J[ik];l<=J[ik+1];l++){
	    if (I[l] == I[ J[j]+h+1 ]){
	      Zt[h+lfi*k2] = C[l];
	      h++;
	    }
	  }
	  k2++;
	}
	
	
	/* evaluate zt = fil*Zt */
	lfi_si = (mwSignedIndex) lfi;
	dsymv_(uplo, &lfi_si, &done, Zt, &lfi_si, fil, &one, &dzero, zt, &one);
	
	/* Set the evaluated sparse inverse elements, zt, into C */
	k=lfi-1;
	for (i = J[j+1]-1; i!=J[j] ; i--){
	  C[i] = -zt[k];
	  k--;
	}
	/* evaluate the j'th diagonal of sparse inverse */
	dgemv_(trans, &one, &lfi_si, &done, fil, &one, zt, &one, &dzero, zz, &one); 
	C[J[j]] = 1.0/C[J[j]] + zz[0];
      }
    else
      {
	/* evaluate the j'th diagonal of sparse inverse */
	C[J[j]] = 1.0/C[J[j]];	
      }
  }
    
  /* Free the temporary variables */
  mxFree(fil);
  mxFree(zt);
  mxFree(Zt);
  mxFree(zz);

  /* ---------------------------------------------------------------------- */
  /* Permute the elements according to r(q) = 1:n                           */
  /* Done only if the Cholesky was evaluated here                           */
  /* ---------------------------------------------------------------------- */
  if (nargin == 1) {
   
    Bm = mxCreateSparse(m, m, nnz, mxREAL) ;     
    It = mxGetIr(Bm);
    Jt = mxGetJc(Bm);
    Ct = mxGetPr(Bm);                            /* Ct = C(r,r) */ 
    
    r = (mwIndex *) L->Perm;                         /* fill reducing ordering */
    w = mxCalloc(m,sizeof(mwIndex));                 /* column counts of Am */
    
    /* count entries in each column of Bm */
    for (j=0; j<m; j++){
      k = r ? r[j] : j ;       /* column j of Bm is column k of Am */
      for (l=J[j] ; l<J[j+1] ; l++){
	i = I[l];
	ik = r ? r[i] : i ;    /* row i of Bm is row ik of Am */
	w[ max(ik,k) ]++;
      }
    }
    cumsum2(Jt, w, m);
    for (j=0; j<m; j++){
      k = r ? r[j] : j ;             /* column j of Bm is column k of Am */
      for (l=J[j] ; l<J[j+1] ; l++){
	i= I[l];
	ik = r ? r[i] : i ;          /* row i of Bm is row ik of Am */
	It [k2 = w[max(ik,k)]++ ] = min(ik,k);
	Ct[k2] = C[l];
      }
    }
    mxFree(w);
    
    /* ---------------------------------------------------------------------- */
    /* Transpose the permuted (upper triangular) matrix Bm into Am */
    /* (this way we get sorted columns)                            */
    /* ---------------------------------------------------------------------- */
    w = mxCalloc(m,sizeof(mwIndex));                 
    for (i=0 ; i<Jt[m] ; i++) w[It[i]]++;        /* row counts of Bm */
    cumsum2(J, w, m);                            /* row pointers */
    for (j=0 ; j<m ; j++){
      for (i=Jt[j] ; i<Jt[j+1] ; i++){
	I[ l=w[ It[i] ]++ ] = j;
	C[l] = Ct[i];
      }
    }
    mxFree(w);
    mxDestroyArray(Bm);
  }
  
  /* ---------------------------------------------------------------------- */
  /* Fill the upper triangle of the sparse inverse */
  /* ---------------------------------------------------------------------- */
  
  w = mxCalloc(m,sizeof(mwIndex));        /* workspace */
  w2 = mxCalloc(m,sizeof(mwIndex));       /* workspace */
  for (k=0;k<J[m];k++) w[I[k]]++;     /* row counts of the lower triangular */
  for (k=0;k<m;k++) w2[k] = w[k] + J[k+1] - J[k] - 1;   /* column counts of the sparse inverse */
  
  nnz = (mwSize)2*nnz - m;                       /* The number of nonzeros in Z */
  pargout[0] = mxCreateSparse(m,m,nnz,mxREAL);   /* The sparse matrix */
  It = mxGetIr(pargout[0]);
  Jt = mxGetJc(pargout[0]);
  Ct = mxGetPr(pargout[0]);
  
  cumsum2(Jt, w2, m);               /* column starting points */
  for (j = 0 ; j < m ; j++){           /* fill the upper triangular */
    for (k = J[j] ; k < J[j+1] ; k++){
      It[l = w2[ I[k]]++] = j ;	 /* place C(i,j) as entry Ct(j,i) */
      if (Ct) Ct[l] = C[k] ;
    }
  }
  for (j = 0 ; j < m ; j++){           /* fill the lower triangular */
    for (k = J[j]+1 ; k < J[j+1] ; k++){
      It[l = w2[j]++] = I[k] ;         /* place C(j,i) as entry Ct(j,i) */
      if (Ct) Ct[l] = C[k] ;
    }
  }
  
  mxFree(w2);
  mxFree(w);
  
  /* ---------------------------------------------------------------------- */
  /* return to MATLAB */
  /* ---------------------------------------------------------------------- */
  
  /* ---------------------------------------------------------------------- */
  /* free workspace and the CHOLMOD L, except for what is copied to MATLAB */
  /* ---------------------------------------------------------------------- */
  if (nargin == 1) {
    cholmod_l_free_factor (&L, cm) ;
    cholmod_l_finish (cm) ;
    cholmod_l_print_common (" ", cm) ;
  }
  mxDestroyArray(Am);
  
}
int get_IntgrOptions(const mxArray *options, cvmPbData thisPb, booleantype fwd, int lmm,
                     int *maxord, booleantype *sld, booleantype *errmsg,
                     long int *mxsteps,
                     int *itol, realtype *reltol, double *Sabstol, double **Vabstol,
                     double *hin, double *hmax, double *hmin, double *tstop,
                     booleantype *rhs_s)
{
  mxArray *opt;
  int q;
  long int i, m, n;
  double *tmp;
  char *fctName;
  char *fwd_fctName = "CVodeInit/CVodeReInit";
  char *bck_fctName = "CVodeInitB/CVodeReInitB";

  if (fwd) fctName = fwd_fctName;
  else     fctName = bck_fctName;
  
  /* Set default values */
  
  *maxord = (lmm == CV_ADAMS) ? 12 : 5;
  
  *sld = FALSE;

  *mxsteps = 0;

  *itol = CV_SS;
  *reltol = 1.0e-3;
  *Sabstol = 1.0e-6;
  *Vabstol = NULL;

  *hin = 0.0;
  *hmax = 0.0;
  *hmin = 0.0;

  *rhs_s = FALSE;

  Ng = 0;
  tstopSet = FALSE;
  mon = FALSE;

  *errmsg = TRUE;


  /* Return now if options was empty */

  if (mxIsEmpty(options)) return(0);

  /* User data */

  opt = mxGetField(options,0,"UserData");
  if ( !mxIsEmpty(opt) ) {
    mxDestroyArray(mtlb_data);
    mtlb_data = mxDuplicateArray(opt);
  }
  
  /* Tolerances */

  opt = mxGetField(options,0,"RelTol");
  if ( !mxIsEmpty(opt) ) {
    *reltol = *mxGetPr(opt);
    if (*reltol < 0.0 ) {
      cvmErrHandler(-999, "CVODES", fctName, "RelTol is negative.", NULL);
      return(-1);
    }
  }
    
  opt = mxGetField(options,0,"AbsTol");
  if ( !mxIsEmpty(opt) ) {
    m = mxGetM(opt);
    n = mxGetN(opt);
    if ( (n != 1) && (m != 1) ) {
      cvmErrHandler(-999, "CVODES", fctName, "AbsTol is not a scalar or a vector.", NULL);
      return(-1);
    }
    if ( m > n ) n = m;
    tmp = mxGetPr(opt);
    if (n == 1) {
      *itol = CV_SS;
      *Sabstol = *tmp;
      if (*Sabstol < 0.0) {
        cvmErrHandler(-999, "CVODES", fctName, "AbsTol is negative.", NULL);
      return(-1);
      }
    } else if (n == N) {
      *itol = CV_SV;
      *Vabstol = (double *) malloc(N*sizeof(double));
      for(i=0;i<N;i++) {
        (*Vabstol)[i] = tmp[i];
        if (tmp[i] < 0.0) {
          cvmErrHandler(-999, "CVODES", fctName, "AbsTol has a negative component.", NULL);
          return(-1);
        }
      }
    } else {
      cvmErrHandler(-999, "CVODES", fctName, "AbsTol does not contain N elements.", NULL);
      return(-1);
    }
  }

  /* Maximum number of steps */

  opt = mxGetField(options,0,"MaxNumSteps");
  if ( !mxIsEmpty(opt) ) {
    *mxsteps = (int)*mxGetPr(opt);
    if (*mxsteps < 0) {
      cvmErrHandler(-999, "CVODES", fctName, "MaxNumSteps is negative.", NULL);
      return(-1);
    }
  }

  /* Maximum order */

  opt = mxGetField(options,0,"MaxOrder");
  if ( !mxIsEmpty(opt) ) {
    q = (int)*mxGetPr(opt);
    if (q <= 0) {
      cvmErrHandler(-999, "CVODES", fctName, "MaxOrder must be positive.", NULL);
      return(-1);
    }
    if (q > *maxord) {
      cvmErrHandler(-999, "CVODES", fctName, "MaxOrder is too large for the Method specified.", NULL);
      return(-1);
    }
    *maxord = q;
  }

  /* Initial step size */

  opt = mxGetField(options,0,"InitialStep");
  if ( !mxIsEmpty(opt) ) {
    *hin = *mxGetPr(opt);
  }

  /* Maximum step size */

  opt = mxGetField(options,0,"MaxStep");
  if ( !mxIsEmpty(opt) ) {
    tmp = mxGetPr(opt);
    if (*tmp < 0.0) {
      cvmErrHandler(-999, "CVODES", fctName, "MaxStep is negative.", NULL);
      return(-1);
    }
    if ( mxIsInf(*tmp) ) *hmax = 0.0;
    else                 *hmax = *tmp;
  }

  /* Minimum step size */

  opt = mxGetField(options,0,"MinStep");
  if ( !mxIsEmpty(opt) ) {
    *hmin = *mxGetPr(opt);
    if (*hmin < 0.0) {
      cvmErrHandler(-999, "CVODES", fctName, "MinStep is negative.", NULL);
      return(-1);
    }
  }

  /* Stability Limit Detection */

  opt = mxGetField(options,0,"StabilityLimDet");
  if ( !mxIsEmpty(opt) ) {
    if (!mxIsLogical(opt)) {
      cvmErrHandler(-999, "CVODES", fctName, "StabilityLimDet is not a logical scalar.", NULL);
      return(-1);
    }
    if (mxIsLogicalScalarTrue(opt)) *sld = TRUE;
    else                            *sld = FALSE;
  }

  /* Monitor? */

  opt = mxGetField(options,0,"MonitorFn");
  if ( !mxIsEmpty(opt) ) {
    mon = TRUE;
    mxDestroyArray(mtlb_MONfct);
    mtlb_MONfct = mxDuplicateArray(opt);
    opt = mxGetField(options,0,"MonitorData");
    if ( !mxIsEmpty(opt) ) {
      mxDestroyArray(mtlb_MONdata);
      mtlb_MONdata  = mxDuplicateArray(opt);
    }
  }

  /* The remaining options are interpreted either for 
   * forward problems only or backward problems only */

  if (fwd) {   /* FORWARD PROBLEM ONLY */

    /* Disable error/warning messages? */

    opt = mxGetField(options,0,"ErrorMessages");
    if ( !mxIsEmpty(opt) ) {
      if (!mxIsLogical(opt)) {
        cvmErrHandler(-999, "CVODES", fctName, "ErrorMessages is not a logical scalar.", NULL);
        return(-1);
      }
      if (mxIsLogicalScalarTrue(opt)) *errmsg = TRUE;
      else                            *errmsg = FALSE;
    }

    /* Stopping time */
    opt = mxGetField(options,0,"StopTime");
    if ( !mxIsEmpty(opt) ) {
      *tstop = *mxGetPr(opt);
      tstopSet = TRUE;
    }

    /* Number of root functions */
    opt = mxGetField(options,0,"NumRoots");
    if ( !mxIsEmpty(opt) ) {

      Ng = (int)*mxGetPr(opt);
      if (Ng < 0) {
        cvmErrHandler(-999, "CVODES", fctName, "NumRoots is negative.", NULL);
        return(-1);
      }
      if (Ng > 0) {
        /* Roots function */
        opt = mxGetField(options,0,"RootsFn");
        if ( !mxIsEmpty(opt) ) {
          mxDestroyArray(mtlb_Gfct);
          mtlb_Gfct = mxDuplicateArray(opt);
        } else {
          cvmErrHandler(-999, "CVODES", fctName, "RootsFn required for NumRoots > 0", NULL);
          return(-1);
        }
      }
      
    }

  } else {   /* BACKWARD PROBLEM ONLY */

    /* Dependency on forward sensitivities */

    opt = mxGetField(options,0,"SensDependent");
    if ( !mxIsEmpty(opt) ) {
      if (!mxIsLogical(opt)) {
        cvmErrHandler(-999, "CVODES", fctName, "SensDependent is not a logical scalar.", NULL);
        return(-1);
      }
      if (mxIsLogicalScalarTrue(opt)) *rhs_s = TRUE;
      else                            *rhs_s = FALSE;
    }

  }

  /* We made it here without problems */

  return(0);
}
Beispiel #15
0
SmartPointerMxArray::~SmartPointerMxArray() 
{
	if(m_mx) 
		mxDestroyArray(m_mx);
}
Beispiel #16
0
    void MatlabAdapter::initJoints()
    {
        engEvalString(mEngine, "joints = {Model.Joint.Name, Model.Joint.Bodies}");

        QString query = "jointParentIds = reshape([Model.Joint.BodiesNr],2," +
                QString::number(tree.jointNodes.size()) +  ")";
        engEvalString(mEngine, query.toStdString().c_str());

        engEvalString(mEngine, "jointDofs = [Model.Joint.nq]");
        engEvalString(mEngine, "cjoint = {Model.Joint.qNr}");
        // array of size 1 x dof, contains the degrees of freedom in correct order
        engEvalString(mEngine, "jointIds = cell2mat(cjoint(:))");

        mxArray *mxJoints = engGetVariable(mEngine, "joints");
        //mxArray *mxJointParentIds = engGetVariable(mEngine, "jointParentIds");
        mxArray *mxJointDofs = engGetVariable(mEngine, "jointDofs");
        mxArray *mxJointIds = engGetVariable(mEngine, "jointIds");
        mxArray *mxCell = 0;

        // double *jointParentIds = mxGetPr(mxJointParentIds);
        // TODO: use jointParentIds

        double *jointDofs = mxGetPr(mxJointDofs);
        double *jointIds = mxGetPr(mxJointIds);
        int count=0;

        for(unsigned i=0; i < tree.jointNodes.size(); i++)
        {
            tree.jointNodes.at(i).parent = 0;

            mxCell = mxGetCell(mxJoints,i);
            char* name = mxArrayToString(mxCell);
            tree.jointNodes.at(i).name = name;

            //  find parents
            mxCell = mxGetCell(mxJoints,i+tree.jointNodes.size());
            char* jointDeps = mxArrayToString(mxCell);
            std::string jd = jointDeps;
            std::vector<std::string> names =  splitString(jd, " ");

            BodyPartNode* pre = findBodyPart(tree.partNodes, names[0]);
            BodyPartNode* post = findBodyPart(tree.partNodes, names[1]);

            if(pre)
            {
                tree.jointNodes.at(i).parent = pre;
                pre->children.push_back(&(tree.jointNodes.at(i)));
            } else
            {
                std::cout << name << "has no parent";
            }

            if(post)
            {
                tree.jointNodes.at(i).children.push_back(post);
                post->parent = &(tree.jointNodes.at(i));
            } else
            {
                std::cout << name << "has no childs";
            }


            tree.jointNodes.at(i).indices.resize(jointDofs[i]);

            for(unsigned k=0; k < tree.jointNodes.at(i).indices.size(); k++)
            {
                unsigned dof = jointIds[count++];
                tree.jointNodes.at(i).indices.at(k) = dof-1; // Matlab indices start at 1 !!!
            }
        } // end for

        tree.findRoot();
        mxDestroyArray(mxJoints);
        //mxDestroyArray(mxJointParentIds);
        mxDestroyArray(mxJointDofs);
        mxDestroyArray(mxJointIds);
//        mxDestroyArray(mxCell);
    }
void MatlabTemplateComponentImpl<Tin,Tout>::process()
{
  //Get the input buffer
  inBuf_->getReadData(readDataSet_);

  //Check dimensions of our matlab matrix
  const mwSize* dims = mxGetDimensions(matlabInput_);
  size_t s = readDataSet_->data.size();
  if(s != dims[0])
  {
    mxDestroyArray(matlabInput_);
    if(TypeInfo<T>::isComplex)
    {
      matlabInput_ = mxCreateDoubleMatrix(1, s, mxCOMPLEX);
    }
    else
    {
      matlabInput_ = mxCreateDoubleMatrix(1, s, mxREAL);
    }
  }

  //Copy data into our matlab matrix
  copyInData(readDataSet_->data, matlabInput_);

//bug in matlab windows - has to be reopened every time
#ifdef _WIN32 // _WIN32 is defined by all Windows 32 compilers, but not by others.
  if(!matlab_.open(""))
  {
    throw ResourceNotFoundException("Failed to start Matlab engine");
  }
#endif

  //Send data to matlab
  matlab_.putVariable("matlab_input", matlabInput_);

  //Use OutputBuffer to capture MATLAB output
  memset(buffer_, 0, 256 * sizeof(char));
  matlab_.outputBuffer(buffer_, 256);

  //Process in Matlab
  matlab_.evalString(command_.c_str());

  //The evaluate string returns the result into the output buffer
  if (buffer_[0] != 0)
  {
    LOG(LWARNING) << buffer_;
  }

  //Output data if required
  if(hasOutput_x || passThrough_x)
  {
    if(passThrough_x)
    {
      //Get a write data set
      outBuf_->getWriteData(writeDataSet_, readDataSet_->data.size());
      //Copy data through
      copy(readDataSet_->data.begin(), readDataSet_->data.end(), writeDataSet_->data.begin());
      writeDataSet_->sampleRate = readDataSet_->sampleRate;
      writeDataSet_->timeStamp = readDataSet_->timeStamp;
    }
    else
    {
      //Get the matlab output
      mxArray* matlab_output = matlab_.getVariable("matlab_output");
      size_t m = mxGetM(matlab_output);
      size_t n = mxGetN(matlab_output);
      //Get a write data set of the correct size and copy data
      outBuf_->getWriteData(writeDataSet_, m>n?m:n);
      copyOutData(matlab_output, writeDataSet_->data);
    }

    //Release write data set
    outBuf_->releaseWriteData(writeDataSet_);
  }

  //Release read data set
  inBuf_->releaseReadData(readDataSet_);
}
Beispiel #18
0
/* ************************************************************
   PROCEDURE mexFunction - Entry for Matlab
   [qdetx,ux,ispos,perm] = factorK(x,K);
   ************************************************************ */
void mexFunction(const int nlhs, mxArray *plhs[],
  const int nrhs, const mxArray *prhs[])
{
  mxArray *myplhs[NPAROUT];
  coneK cK;
  int i,k,nk,nksqr, sdplen,sdpdim,lenfull, fwsiz, ispos;
  const double *x;
  double *ux, *fwork, *permPr, *qdetx, *up, *uppi;
  int *iwork, *perm;
  double uxk;
  char use_pivot;
/* ------------------------------------------------------------
   Check for proper number of arguments
   ------------------------------------------------------------ */
  mxAssert(nrhs >= NPARIN, "factorK requires more input arguments");
  mxAssert(nlhs <= NPAROUT, "factorK produces less output arguments");
  use_pivot = (nlhs == NPAROUT);
/* ------------------------------------------------------------
   Disassemble cone K structure
   ------------------------------------------------------------ */
  conepars(K_IN, &cK);
/* ------------------------------------------------------------
   Compute statistics: sdpdim = rdim+hdim, sdplen = sum(K.s).
   ------------------------------------------------------------ */
  lenfull = cK.lpN +  cK.qDim + cK.rDim + cK.hDim;
  sdpdim = cK.rDim + cK.hDim;
  sdplen = cK.rLen + cK.hLen;
/* ------------------------------------------------------------
   Get input vector x, skip LP part
   ------------------------------------------------------------ */
  mxAssert(mxGetM(X_IN) * mxGetN(X_IN) == lenfull, "x size mismatch.");
  x = mxGetPr(X_IN) + cK.lpN;
/* ------------------------------------------------------------
   Allocate output qdetx(lorN), UX(sdpdim), perm(sdplen), ispos(1).
   ------------------------------------------------------------ */
  QDETX_OUT = mxCreateDoubleMatrix(cK.lorN, 1, mxREAL);
  qdetx = mxGetPr(QDETX_OUT);
  UX_OUT = mxCreateDoubleMatrix(sdpdim, 1, mxREAL);
  ux = mxGetPr(UX_OUT);
  ISPOS_OUT = mxCreateDoubleMatrix(1,1,mxREAL);
  PERM_OUT =  mxCreateDoubleMatrix(sdplen, 1, mxREAL);
  permPr = mxGetPr(PERM_OUT);
/* ------------------------------------------------------------
   Allocate working arrays iwork(sdplen),
   fwork(MAX(rmaxn^2,2*hmaxn^2) + MAX(rmaxn,hmaxn))
   ------------------------------------------------------------ */
  iwork = (int *) mxCalloc(sdplen, sizeof(int));
  perm = iwork;
  fwsiz = MAX(cK.rMaxn,cK.hMaxn);
  fwork = (double *) mxCalloc(fwsiz + MAX(SQR(cK.rMaxn),2*SQR(cK.hMaxn)),
                              sizeof(double));
  up = fwork + fwsiz;
  uppi = up + SQR(cK.hMaxn);
/* ------------------------------------------------------------
   LORENTZ:  qdetx = sqrt(qdet(x))
   ------------------------------------------------------------ */
  ispos = 1;
  for(k = 0; k < cK.lorN; k++){
    nk = cK.lorNL[k];
    if( (uxk = qdet(x,nk)) < 0.0){
      ispos = 0;
      break;
    }
    else
      qdetx[k] = sqrt(uxk);
    x += nk;
  }
/* ------------------------------------------------------------
   PSD: Cholesky factorization. If use_pivot, then do pivoting.
   ------------------------------------------------------------ */
  if(use_pivot){
    if(ispos)
      for(k = 0; k < cK.rsdpN; k++){                /* real symmetric */
        nk = cK.sdpNL[k];
        if(cholpivot(up,perm, x,nk, fwork)){
          ispos = 0;
          break;
        }
        uperm(ux, up, perm, nk);
        triu2sym(ux,nk);
        nksqr = SQR(nk);
        x += nksqr; ux += nksqr;
        perm += nk;
      }
/* ------------------------------------------------------------
   Complex Hermitian PSD pivoted Cholesky factorization
   ------------------------------------------------------------ */
    if(ispos)
      for(; k < cK.sdpN; k++){                    /* complex Hermitian */
        nk = cK.sdpNL[k];
        nksqr = SQR(nk);
        if(prpicholpivot(up,uppi,perm, x,x+nksqr,nk, fwork)){
          ispos = 0;
          break;
        }
        uperm(ux, up, perm, nk);                  /* real part */
        uperm(ux+nksqr, uppi, perm, nk);          /* imaginary part */
        triu2herm(ux,ux+nksqr,nk);
        nksqr += nksqr;                           /* 2*n^2 for real+imag */
        x += nksqr; ux += nksqr;
        perm += nk;
      }
/* ------------------------------------------------------------
   Convert "perm" to Fortran-index in doubles.
   ------------------------------------------------------------ */
    for(i = 0; i < sdplen; i++)
      permPr[i] = 1.0 + iwork[i];
  }
/* ------------------------------------------------------------
   PSD, !use_pivot: Cholesky without pivoting.
   First let ux = x, then ux=chol(ux).
   ------------------------------------------------------------ */
  else{           /* Cholesky real sym PSD without pivoting */
    if(ispos){
      memcpy(ux, x, sdpdim * sizeof(double));       /* copy real + complex */
      for(k = 0; k < cK.rsdpN; k++){                /* real symmetric */
        nk = cK.sdpNL[k];
        if(cholnopiv(ux,nk)){
          ispos = 0;
          break;
        }
        triu2sym(ux,nk);
        ux += SQR(nk);
      }
    }
/* ------------------------------------------------------------
   Complex Hermitian PSD Cholesky factorization, no pivoting.
   ------------------------------------------------------------ */
    if(ispos)
      for(; k < cK.sdpN; k++){                    /* complex Hermitian */
        nk = cK.sdpNL[k];
        nksqr = SQR(nk);
        if(prpicholnopiv(ux,ux+nksqr,nk)){
          ispos = 0;
         break;
        }
        triu2herm(ux,ux+nksqr,nk);
        ux += 2 * nksqr;
      }
  } /* !use_pivot */
/* ------------------------------------------------------------
   Return parameter ispos
   ------------------------------------------------------------ */
  *mxGetPr(ISPOS_OUT) = ispos;
/* ------------------------------------------------------------
   Release working arrays
   ------------------------------------------------------------ */
  mxFree(iwork);
  mxFree(fwork);
/* ------------------------------------------------------------
   Copy requested output parameters (at least 1), release others.
   ------------------------------------------------------------ */
  i = MAX(nlhs, 1);
  memcpy(plhs,myplhs, i * sizeof(mxArray *));
  for(; i < NPAROUT; i++)
    mxDestroyArray(myplhs[i]);
}
Beispiel #19
0
PyObject * mlabraw_eval(PyObject *, PyObject *args)
{
  //XXX how large should this be? used to be 10000, but looks like matlab
  // hangs when it gets bigger than ~9000 I'm not aware of some actual limit
  // being documented anywhere; I don't want to make it too small since the
  // high overhead of engine calls means that it can be potentially useful to
  // eval large chunks.
  const int  BUFSIZE=4096;
  char* fmt = "try, %s; MLABRAW_ERROR_=0; catch, MLABRAW_ERROR_=1; end;";
  char buffer[BUFSIZE];
  char cmd[BUFSIZE];
  char *lStr;
  char *retStr = buffer;
  PyObject *ret;
  PyObject *lHandle;
  PyObject *u_ret_str;
  PyObject *encoded_ret_str;

  if (! PyArg_ParseTuple(args, "Os:eval", &lHandle, &lStr)) return NULL;
  if (! PyCapsule_CheckExact(lHandle)) {
    PyErr_SetString(PyExc_TypeError, "Invalid object passed as mlabraw session handle");
	return NULL;
  }

  bool ok = my_snprintf(cmd, BUFSIZE, fmt, lStr);
  if (!ok) {
	  PyErr_SetString(mlabraw_error,
					  "String too long to evaluate.");
	  return NULL;
  }
  // std::cout << "DEBUG: CMD " << cmd << std::endl << std::flush;
  engOutputBuffer((Engine *)PyCapsule_GetPointer(lHandle, NULL), retStr, BUFSIZE-1);
  if (engEvalString((Engine *)PyCapsule_GetPointer(lHandle, NULL), cmd) != 0) {
    //std::cout << "DEBUG: RETURN " << retStr << std::endl << std::flush;
#ifdef PY3K
    u_ret_str = PyUnicode_DecodeFSDefault(retStr);
    encoded_ret_str = PyUnicode_AsUTF8String(u_ret_str);
    PyErr_SetString(mlabraw_error, PyBytes_AsString(encoded_ret_str));
    Py_DECREF(encoded_ret_str);
    Py_DECREF(u_ret_str);
#else
    PyErr_SetString(mlabraw_error, retStr);
#endif
    return NULL;
  }
  {
    mxArray *lArray = NULL;
    char buffer2[BUFSIZE];
    char *retStr2 = buffer2;
    bool __mlabraw_error;
    if (NULL == (lArray = _getMatlabVar(lHandle, "MLABRAW_ERROR_")) ) {
      PyErr_SetString(mlabraw_error,
                      "Something VERY BAD happened whilst trying to evaluate string "
                      "in MATLAB(TM) workspace.");
      return NULL;
    }
    __mlabraw_error = (bool)*mxGetPr(lArray);
    mxDestroyArray(lArray);
    if (__mlabraw_error) {
      engOutputBuffer((Engine *)PyCapsule_GetPointer(lHandle, NULL), retStr2, BUFSIZE-1);
      if (engEvalString((Engine *)PyCapsule_GetPointer(lHandle, NULL),
                        "disp(subsref(lasterror(),struct('type','.','subs','message')))") != 0) {
        PyErr_SetString(mlabraw_error, "THIS SHOULD NOT HAVE HAPPENED!!!");
        return NULL;
      }
#ifdef PY3K
    u_ret_str = PyUnicode_DecodeFSDefault(retStr2 + ((strncmp(">> ", retStr2, 3) == 0) ?  3 : 0));
    encoded_ret_str = PyUnicode_AsUTF8String(u_ret_str);
    PyErr_SetString(mlabraw_error, PyBytes_AsString(encoded_ret_str));
    Py_DECREF(encoded_ret_str);
    Py_DECREF(u_ret_str);
#else
      PyErr_SetString(mlabraw_error, retStr2 + ((strncmp(">> ", retStr2, 3) == 0) ?  3 : 0));
#endif
      return NULL;
    }
  }
  if (strncmp(">> ", retStr, 3) == 0) { retStr += 3; } //FIXME
#ifdef PY3K
  //ret = PyUnicode_FromString(retStr);
    ret = PyUnicode_DecodeFSDefault(retStr);
#else
  ret = (PyObject *)PyString_FromString(retStr);
#endif
  return ret;
}
Beispiel #20
0
void TerminateModule_myrot(void) {
    mxDestroyArray(_mxarray0_);
}
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
    
    mwSize maxepoch;
    double epsilon;
    double momentumweight;
    mwSize nGroup;
    mwSize nDiscriminantPerGroup;
    double *initial_discriminants;
    double *xtrain;
    double *ytrain;
    
    double *discriminants;
    double *totalerror;
    double *totalerrorvalid;
    double *n_epochs;
    mwSize tM, tN, dM, dN;
            
    mwIndex x, ii, i, j, k;    
    mwIndex *ptr_to_rnd;    

    /* cross validation variables */
    
    double *xvalid, *yvalid;   
    double *voutputs;
    double  vmul_d_pts, vAND_c_muls, voutput, verro, CV;
    mwSize vN;
    mxArray *discreserve, *discold;
    double *discreservep, *discoldp;
    double cv_count;
    double cv_flg;
    
    /* end of validation variables */    

    double *outputs, *outputsAND_c;
    double *outputsAND, *outputs_c, *term2;

    mxArray *prevupdates, *updates;
    double *prevupdates_p, *updates_p;
    
    double sum_d_pts, mul_d_pts, AND_c_muls, output, erro, mp;
    
    xtrain = mxGetPr(prhs[0]);
    ytrain = mxGetPr(prhs[1]);
    initial_discriminants = mxGetPr(prhs[2]);
    
    maxepoch = mxGetScalar(prhs[3]);
    nDiscriminantPerGroup = mxGetScalar(prhs[4]);
    nGroup = mxGetScalar(prhs[5]);
    epsilon = mxGetScalar(prhs[6]);
    momentumweight = mxGetScalar(prhs[7]);    
    
    dM = mxGetM(prhs[2]);
    dN = mxGetN(prhs[2]);
    
    tM = mxGetM(prhs[0]);
    tN = mxGetN(prhs[0]);
    
    plhs[0] = mxCreateDoubleMatrix(dM, dN, mxREAL);            
    plhs[1] = mxCreateDoubleMatrix(maxepoch, 1, mxREAL); 
    plhs[2] = mxCreateDoubleMatrix(maxepoch, 1, mxREAL);
    plhs[3] = mxCreateDoubleMatrix(1, 1, mxREAL);
    
    discriminants = mxGetPr(plhs[0]);
    totalerror = mxGetPr(plhs[1]);
    totalerrorvalid = mxGetPr(plhs[2]);
    n_epochs = mxGetPr(plhs[3]);
    *n_epochs = (double)maxepoch;
    
    /* cross validation initialization */

    xvalid = mxGetPr(prhs[8]);
    yvalid = mxGetPr(prhs[9]);
    
    vN = mxGetN(prhs[8]);
    
    voutputs = (double*)mxCalloc(dN,sizeof(double));
    
    CV = 0;
    discreserve = mxCreateDoubleMatrix(dM, dN, mxREAL);
    discold = mxCreateDoubleMatrix(dM, dN, mxREAL);
    
    discreservep = mxGetPr(discreserve);
    discoldp = mxGetPr(discold);

    cv_count = mxGetScalar(prhs[10]);
    cv_flg = mxGetScalar(prhs[11]);

    /* end of validation initialization */
    
    outputs = (double*)mxCalloc(dN,sizeof(double));
    term2 = (double*)mxCalloc(dN,sizeof(double));
    outputs_c = (double*)mxCalloc(dN,sizeof(double));
    outputsAND = (double*)mxCalloc(nGroup,sizeof(double));
    outputsAND_c = (double*)mxCalloc(nGroup,sizeof(double));
           
    prevupdates = mxCreateDoubleMatrix(dM, dN, mxREAL);
    updates = mxCreateDoubleMatrix(dM, dN, mxREAL);    
    
    prevupdates_p = mxGetPr(prevupdates);
    updates_p = mxGetPr(updates);
    
   
    /* MATFile *pmat;
    const char *file = "Outputs.mat";
    int s; */
    
    
    for (i=0;i<dM*dN;i++){
        discriminants[i] = initial_discriminants[i];
    } 
    
    ptr_to_rnd = (mwIndex*)mxCalloc(tN,sizeof(mwIndex));
    
    for (i=0; i<tN; ptr_to_rnd[i] = i++);
    
    for (x=0;x<maxepoch;x++){
        
/*    cross validation */
        if (cv_flg == 1){
            
            for (i=0; i<vN; i++){

                for (j=0; j<dN; j++){

                    sum_d_pts = 0;
                    for (k=0; k<dM; k++){
                        sum_d_pts = sum_d_pts + discriminants[j*dM+k]*xvalid[i*tM+k];                  
                    }
                    voutputs[j] = 1/(1+exp(-sum_d_pts));
                }            


                vAND_c_muls = 1;
                for (j=0; j<nGroup; j++){
                    vmul_d_pts = 1;
                    for (k=0; k<nDiscriminantPerGroup; k++){
                        vmul_d_pts = vmul_d_pts * voutputs[j*nDiscriminantPerGroup+k];
                    }
                    vAND_c_muls = vAND_c_muls * (1 - vmul_d_pts);
                }

                voutput = 1 - vAND_c_muls;
                verro = 0.1 + 0.8*yvalid[i] - voutput; 
                totalerrorvalid[x] = totalerrorvalid[x] + verro*verro;
            }
            totalerrorvalid[x] = sqrt(totalerrorvalid[x]/vN);
            
        }
 /* end of computing validation outputs  */
        
        shuffle(ptr_to_rnd, tN); 
        for (i=0; i<tN; i++){
            ii = ptr_to_rnd[i];
            
            for (j=0; j<dN; j++){

                sum_d_pts = 0;
                for (k=0; k<dM; k++){
                    sum_d_pts = sum_d_pts + discriminants[j*dM+k]*xtrain[ii*tM+k];                  
                }
                outputs[j] = 1/(1+exp(-sum_d_pts));
                outputs[j] = outputs[j] - DBL_EPSILON*(outputs[j]==1);
                outputs_c[j] = 1 - outputs[j];
            }
            
            AND_c_muls = 1;
            for (j=0; j<nGroup; j++){
                mul_d_pts = 1;
                for (k=0; k<nDiscriminantPerGroup; k++){
                    mul_d_pts = mul_d_pts * outputs[j*nDiscriminantPerGroup+k];
                }
                outputsAND[j] = mul_d_pts;
                outputsAND_c[j] = 1-mul_d_pts;
                AND_c_muls = AND_c_muls * outputsAND_c[j];
            }
            
            output = 1 - AND_c_muls;
            erro = 0.1 + 0.8*ytrain[ii] - output;                       
            totalerror[x] = totalerror[x] + erro*erro;                    
          
            for (j=0; j<nGroup; j++){
                    mp = ((AND_c_muls/outputsAND_c[j])*outputsAND[j])*erro;              
                for (k=0; k<nDiscriminantPerGroup; k++){
                    term2[j*nDiscriminantPerGroup+k] = mp * outputs_c[j*nDiscriminantPerGroup+k];
                }                
            }
            
            for (j=0; j<dN; j++){
                for (k=0; k<tM; k++){
                    updates_p[j*tM+k] = xtrain[ii*tM+k] * term2[j] + momentumweight * prevupdates_p[j*tM+k];
                    discriminants[j*tM+k] = discriminants[j*tM+k] + epsilon * updates_p[j*tM+k];
                    prevupdates_p[j*tM+k] = updates_p[j*tM+k];
                            
                }
            }
            
        }
        totalerror[x] = sqrt(totalerror[x]/tN);
        
        mexPrintf("Epoch No. %d ... error = %f \n",x+1,totalerror[x]); 
        
        if (cv_flg == 1){
                        
            mexPrintf("Epoch No. %d ... error = %f (validation set)\n",x+1,totalerrorvalid[x]);      
            if(x>0){
                if(totalerrorvalid[x] > totalerrorvalid[x-1]){
                    CV = CV + 1;
                    if (CV==1){
                        mxDestroyArray(discreserve);
                        discreserve = mxDuplicateArray(discold);
                        discreservep = mxGetPr(discreserve);
                    }
                    if (CV==cv_count){
                        mxDestroyArray(plhs[0]);
                        plhs[0] = mxDuplicateArray(discreserve);
                        discriminants = mxGetPr(plhs[0]);
                        *n_epochs = (double)x+1;
                        break;
                    }
                }
                else{
                    CV = 0;
                }
            } 
            mxDestroyArray(discold);
            discold = mxDuplicateArray(plhs[0]);
            discoldp = mxGetPr(discold);
        /*
         pmat = matOpen(file,"w");
            s = matPutVariable(pmat,"discriminants",plhs[0]);
            s = matPutVariable(pmat,"totalerror",plhs[1]);
            s = matPutVariable(pmat,"totalerrorvalid",plhs[2]);
            s = matClose(pmat); */
        }   
    }
    
    mxDestroyArray(discreserve);
    mxDestroyArray(discold);
    mxDestroyArray(prevupdates);
    mxDestroyArray(updates); 

}
Beispiel #22
0
/* Call matlab's fmincon */
int matlab_fmincon(
	       double* x,		    /* result: optimum point */
	       double* fval,		    /* result: optimum function value */
               int ndim,		    /* number of dimensions (variables) */
               double (*objfun)(double *),  /* objective function */
	       double* x0,                  /* starting point */
	       int nIneq,		    /* number of linear inequalities */
	       double* A,		    /* linear inequalities A*X <= B*/
	       double* B,		    
	       int nEq,			    /* number of linear equalities */
	       double* Aeq,		    /* linear equalities Aeq*X = B*/
	       double* Beq,
	       bool hasBounds,              /* are there any bounds */ 
	       double* LB,		    /* lower bounds */
	       double* UB,		    /* upper bounds */
	       int nC,			    /* number of constraints */
	       double* (*C)(double *),      /* non linear constraints */
	       int nCeq,		    /* number of equality constraints */
	       double* (*Ceq)(double *)     /* non linear equality constraints */
	      ){

    /** Intialize MCR and library **/
    const char* ops = "-nodesktop";
    /*const char* ops = "";*/
    if (!mclInitializeApplication(&ops, 1)) {
        printf("Error Initializing Application\n");
        return -1;
    }
    if (!liboptimizeInitialize()) {
        printf("Error Initializing Library\n");
        return -1;
    }

    printf("Setting up matlab optimizer for a %i var problem\n",ndim);
    
    /** The objective function **/
    /* Create a numeric datatype large enough to hold a pointer */
    mxArray *of = mxCreateNumericMatrix(1,1,mxUINT64_CLASS,mxREAL);
    
    /* Save the pointer to the objective function as numeric */
    *((mwSize*)mxGetData(of)) = (mwSize) objfun;
    printf("  Objective function set\n");
    
    /** The starting point **/
    mxArray *x0arr = makeArray(x0,ndim,1);
    printf("  Starting point set x0[0]=%f x0[1]=%f\n",x0[0],x0[1]);

    /** linear constraints **/
    mxArray *Aarr = makeArray(A,nIneq,ndim);
    mxArray *Barr = makeArray(B,nIneq,1);
    printf("  %i inequality constraints set\n",nIneq);

    /** linear equality constraints **/
    mxArray *Aeqarr = makeArray(Aeq,nEq,ndim);
    mxArray *Beqarr = makeArray(Beq,nEq,1);
    printf("  %i equality constraints set\n",nEq);
    
    /** variable bounds **/
    int nb = ndim;
    if (!hasBounds) nb = 0;
    mxArray *LBarr = makeArray(LB,nb,1);
    mxArray *UBarr = makeArray(UB,nb,1);
    printf("  %i variable bounds set\n",nb);
    
    /** nonlinear constraints **/
    mxArray *cf;
    mxArray *ncf = makeScalar(nC);
    if (nC > 0) {
	cf = mxCreateNumericMatrix(1,1,mxUINT64_CLASS,mxREAL);
        *((mwSize*)mxGetData(cf)) = (mwSize) C;
    }else{
        cf = mxCreateNumericMatrix(0, 1, mxDOUBLE_CLASS, mxREAL);
    }
    printf("  %i nonlinear constraints set\n",nC);

    /** nonlinear equality constraints **/
    mxArray *ecf;
    mxArray *necf = makeScalar(nCeq);
    if (nCeq > 0) {
	ecf = mxCreateNumericMatrix(1,1,mxUINT64_CLASS,mxREAL);
        *((mwSize*)mxGetData(ecf)) = (mwSize) Ceq;
    }else{
        ecf = mxCreateNumericMatrix(0, 1, mxDOUBLE_CLASS, mxREAL);
    }
    printf("  %i nonlinear equality constraints set\n",nCeq);

    /** Call the matlab function **/
    mxArray *xarr=NULL;
    mxArray *fvalarr=NULL;

    printf("Calling the matlab library\n");
    
    mlfDoOptim(2,&xarr,&fvalarr,of,x0arr,Aarr,Barr,Aeqarr,Beqarr,LBarr,UBarr,ncf,cf,necf,ecf);
    
    printf("Returning results\n");
    
    /** Get/display the results **/
    double* xa = mxGetPr(xarr);
    double* fvala = mxGetPr(fvalarr);
    int i;
    for(i=0;i<ndim;++i) x[i] = xa[i];
    for(i=0;i<1;++i) fval[i] = fvala[i];
    
    printf("Cleaning up\n");

    /** Cleanup **/
    mxDestroyArray(of);
    mxDestroyArray(x0arr);
    mxDestroyArray(Aarr);
    mxDestroyArray(Barr);
    mxDestroyArray(Aeqarr);
    mxDestroyArray(Beqarr);
    mxDestroyArray(LBarr);
    mxDestroyArray(UBarr);
    mxDestroyArray(cf);
    mxDestroyArray(ecf);
    mxDestroyArray(ncf);
    mxDestroyArray(necf);
    mxDestroyArray(xarr);
    mxDestroyArray(fvalarr);
    
    liboptimizeTerminate();
    mclTerminateApplication();
    
    return 0;
}
Beispiel #23
0
/***********************************************************************//**
 * \brief mexFunction to append a stack to an existing em-file.
 **************************************************************************/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[]) {


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

    #define __MAX_S__LENGTH__ (4096)
    char s[__MAX_S__LENGTH__+1];

    #define __BUFFERLENGTH_SYNOPSIS__ 1024
    char synopsis[__BUFFERLENGTH_SYNOPSIS__];

    size_t i, j, k;

    const void *w_data;
    int w_iotype;

    uint32_t subregion_start[3] = { 0,0,0 };
    uint32_t reverse_sampling[3] = { 0,0,0 };
    tom_io_em_header header;
    int allow_conversion = 1;
    mxArray *plhs_tmp[5] = { NULL, NULL, NULL, NULL, NULL };
    void *complexCopy = NULL;

    uint32_t w_sizex, w_sizey, w_sizez;
    size_t w_stridex=0, w_stridey=0, w_stridez=0;




    snprintf(synopsis, __BUFFERLENGTH_SYNOPSIS__, "[size, magic, comment, emdata, userdata] = %s(filename, volume, [subregion_start, reverse_sampling, allow_conversion])", mexFunctionName());
    if (nrhs==0 && nlhs==0) {
        /* Print help */
        mexPrintf("SYNOPSIS: %s\n", synopsis);
        mexPrintf("mex-file compiled from file \"" __FILE__ "\" at " __DATE__ ", " __TIME__ ".\n");
        return;
    }

    if (nlhs>5 || nrhs<2 || nrhs>5) {
        snprintf(s, __MAX_S__LENGTH__, "%s: Wrong number of in/output arguments: %s.", mexFunctionName(), synopsis);
        mexErrMsgTxt(s);
    }

    {
        #define __MAX_UINT32_T__ 0xFFFFFFFF
        const mxArray *arg;
        mxArray *tmpArray = NULL;
        const mwSize *size;
        double *pdouble;
        mxClassID type;

        /* filename */
        arg = prhs[0];
        if (!mxIsChar(arg) || mxGetNumberOfDimensions(arg)!=2 || mxGetM(arg)!=1 || (filename_length=mxGetN(arg))<1 || filename_length>=__MAX_FILENAME_LENGTH__) {
            snprintf(s, __MAX_S__LENGTH__, "%s: needs file name as first parameter: %s.", mexFunctionName(), synopsis);
            mexErrMsgTxt(s);
        }
        mxGetString(arg, filename, __MAX_FILENAME_LENGTH__);


        /* subregion_start */
        if (nrhs >= 3) {
            arg = prhs[2];
            i = mxGetM(arg); j = mxGetN(arg);
            if (!mxIsNumeric(arg) || mxIsComplex(arg) || mxGetNumberOfDimensions(arg)!=2 || !((i==0&&j==0) || (i==1&&j==3) || (i==3&&j==1))) {
                snprintf(s, __MAX_S__LENGTH__, "%s: The subregion_start must be either [] or a 1x3 vector: %s", mexFunctionName(), synopsis);
                mexErrMsgTxt(s);
            }
            if (i!=0) {
                if (!(tmpArray=getDoubleArray(arg))) {
                    snprintf(s, __MAX_S__LENGTH__, "%s: Error creating a copy of the subregion_start. Maybe out of memory.", mexFunctionName());
                    mexErrMsgTxt(s);
                }
                pdouble = mxGetPr(tmpArray);
                for (k=0; k<3; k++) {
                    subregion_start[k] = (uint32_t)pdouble[k];
                    if (pdouble[k] != subregion_start[k]) {
                        snprintf(s, __MAX_S__LENGTH__, "%s: subregion_start must contain integer values: %s", mexFunctionName(), synopsis);
                        mexErrMsgTxt(s);
                    }
                }
                mxDestroyArray(tmpArray);
            }
        }

        /* reverse_sampling */
        if (nrhs >= 4) {
            arg = prhs[3];
            i = mxGetM(arg); j = mxGetN(arg);
            if (!mxIsNumeric(arg) || mxIsComplex(arg) || mxGetNumberOfDimensions(arg)!=2 || !((i==0&&j==0) || (i==1&&j==3) || (i==3&&j==1))) {
                snprintf(s, __MAX_S__LENGTH__, "%s: The reverse_sampling must be either [] or a 1x3 vector: %s", mexFunctionName(), synopsis);
                mexErrMsgTxt(s);
            }
            if (i!=0) {
                if (!(tmpArray=getDoubleArray(arg))) {
                    snprintf(s, __MAX_S__LENGTH__, "%s: Error creating a copy of the reverse_sampling. Maybe out of memory.", mexFunctionName());
                    mexErrMsgTxt(s);
                }
                pdouble = mxGetPr(tmpArray);
                for (k=0; k<3; k++) {
                    reverse_sampling[k] = (uint32_t)pdouble[k];
                    if (pdouble[k] != reverse_sampling[k]) {
                        snprintf(s, __MAX_S__LENGTH__, "%s: reverse_sampling must contain integer values: %s", mexFunctionName(), synopsis);
                        mexErrMsgTxt(s);
                    }
                }
                mxDestroyArray(tmpArray);
            }
        }
        if (reverse_sampling[0] < 1) { reverse_sampling[0] = 1; }
        if (reverse_sampling[1] < 1) { reverse_sampling[1] = 1; }
        if (reverse_sampling[2] < 1) { reverse_sampling[2] = 1; }


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


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


        /* data */
        arg = prhs[1];
        if (!mxIsNumeric(arg) || mxGetNumberOfDimensions(arg)>3) {
            snprintf(s, __MAX_S__LENGTH__, "%s: needs a numerical volume as second parameter: %s", mexFunctionName(), synopsis);
            mexErrMsgTxt(s);
        }
        type = mxGetClassID(arg);
        size = mxGetDimensions(arg);
        w_sizex = size[0];
        w_sizey = size[1];
        w_sizez = mxGetNumberOfDimensions(arg)==3 ? size[2] : 1;
        if (w_sizex!=size[0] || w_sizey!=size[1] || w_sizez!=(mxGetNumberOfDimensions(arg)==3?size[2]:1)) {
            snprintf(s, __MAX_S__LENGTH__, "%s: The volume is too large to save it as EM.", mexFunctionName(), synopsis);
            mexErrMsgTxt(s);
        }

        if (mxIsComplex(arg)) {
            const size_t numel = w_sizex * w_sizey * w_sizez;
            float *pdst;
            if (!allow_conversion && type!=mxSINGLE_CLASS) {
                snprintf(s, __MAX_S__LENGTH__, "%s: Can not convert complex volume to single (not allow_conversion).", mexFunctionName());
                mexErrMsgTxt(s);
            }
            if (!(complexCopy = malloc(numel*2*sizeof(float)))) {
                snprintf(s, __MAX_S__LENGTH__, "%s: Error allocating memory for temporary copy of complex data.", mexFunctionName());
                mexErrMsgTxt(s);
            }
            pdst = complexCopy;
            if (type == mxSINGLE_CLASS) {
                const float *psrc_re;
                const float *psrc_im;
                psrc_re = (float *)mxGetData(arg);
                psrc_im = (float *)mxGetData(arg);
                for (i=0; i<numel; i++) {
                    *pdst++ = psrc_re[i];
                    *pdst++ = psrc_im[i];
                }
            } else if (type == mxDOUBLE_CLASS) {
                const double *psrc_re, *psrc_im;
                psrc_re = mxGetPr(arg);
                psrc_im = mxGetPi(arg);
                for (i=0; i<numel; i++) {
                    *pdst++ = psrc_re[i];
                    *pdst++ = psrc_im[i];
                }
            } else {
                free(complexCopy); complexCopy = NULL;
                snprintf(s, __MAX_S__LENGTH__, "%s: EM supports only floating point complex data (single).", mexFunctionName(), type);
                mexErrMsgTxt(s);
            }
            w_data = complexCopy;
            w_iotype = TOM_IO_TYPE_COMPLEX4;
        } else {
            w_data = mxGetData(arg);
            w_iotype = getIOTypeFromMxClassID(type, false);
        }
    }

    {
        int header_read;
        int fcn_res = tom_io_em_write_paste(filename, w_data, w_iotype, w_sizex, w_sizey, w_sizez, w_stridex, w_stridey, w_stridez, &header, &header_read, allow_conversion, subregion_start, reverse_sampling);
        if (fcn_res != TOM_ERR_OK) {
            if (complexCopy) { free(complexCopy); complexCopy = NULL; }
            switch (fcn_res) {
                case TOM_ERR_VOLUME_TOO_LARGE:
                    snprintf(s, __MAX_S__LENGTH__, "%s: The %lux%lux%lu-volume is to large to paste it into the %lux%lux%lu-EM-file (start at %lux%lux%lu, sample %lux%lux%lu).", mexFunctionName(), (unsigned long)w_sizex, (unsigned long)w_sizey, (unsigned long)w_sizez, (unsigned long)header.dims[0], (unsigned long)header.dims[1], (unsigned long)header.dims[2], (unsigned long)subregion_start[0], (unsigned long)subregion_start[1], (unsigned long)subregion_start[2], (unsigned long)reverse_sampling[0], (unsigned long)reverse_sampling[1], (unsigned long)reverse_sampling[2]);
                    break;
                case TOM_ERR_WRONG_IOTYPE_CONVERSION:
                    snprintf(s, __MAX_S__LENGTH__, "%s: Error converting the volume from type %d to type %d (allow conversion = %s).", mexFunctionName(), (int)w_iotype, (int)tom_io_em_get_iotype(&header), allow_conversion ? "yes" : "no");
                    break;
                default:
                    snprintf(s, __MAX_S__LENGTH__, "%s: Unspecified error pasting the volume to file (%d).", mexFunctionName(), fcn_res);
                    break;
            }
            mexErrMsgTxt(s);
        }
        if (complexCopy) { free(complexCopy); complexCopy = NULL;}
    }


    {
        /* Construct the output. */
        void *pdata;
        switch (nlhs) {
            case 5:
                pdata = mxGetData(plhs[4] = plhs_tmp[4]);
                for (i=0; i<256; i++) { ((int8_t *)pdata)[i] = header.userdata[i]; }
            case 4:
                pdata = mxGetData(plhs[3] = plhs_tmp[3]);
                for (i=0; i<40; i++) { ((int32_t *)pdata)[i] = header.emdata[i]; }
            case 3:
                pdata = mxGetData(plhs[2] = plhs_tmp[2]);
                for (i=0; i<80; i++) { ((int8_t *)pdata)[i] = header.comment[i]; }
            case 2:
                pdata = mxGetData(plhs[1] = plhs_tmp[1]);
                ((int8_t *)pdata)[0] = header.machine;
                ((int8_t *)pdata)[1] = header.byte2;
                ((int8_t *)pdata)[2] = header.byte3;
                ((int8_t *)pdata)[3] = header.type;
            case 1:
                pdata = mxGetData(plhs[0] = plhs_tmp[0]);
                ((uint32_t *)pdata)[0] = header.dims[0];
                ((uint32_t *)pdata)[1] = header.dims[1];
                ((uint32_t *)pdata)[2] = header.dims[2];
                break;
            case 0:
            default:
                break;
        }
    }


}
Beispiel #24
0
void mexFunction(int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[]){
    double *lnQ,*lnH,*iEnd; /* inputparameters */
    int *s;          /* output parameter */
    int T,t,Mends,Nends,n,tStart,tEnd;                       /* temporary variables */
    int ss,N,j,k;
    double Z;
    double *lnp0, *lnp1,*lnpp;
    int *MaxPrev;
    mxArray *mxMaxPrev,*mxpp, *mxp1, *mxp0; /* temporary arrays */
    
    /* check number of input/output arguments */
    if (nlhs != 1)
        mexErrMsgTxt("One output argument required.");
    if (nrhs != 3)
        mexErrMsgTxt("Three input arguments required.");
    
    /* size of input variables */
    T = mxGetM(LNH_IN); /* number of rows = number of time points*/
    N = mxGetN(LNH_IN); /* number of columns = number of states*/
    
    /* check that the other variables have consistent sizes */
    if ( mxGetM(LNQ_IN) != N || mxGetN(LNQ_IN) != N)
        mexErrMsgTxt("Q is not an N by N matrix (N = # columns in lnH).");
    
    /* require iEnd to be a 1 x N matrix */
    Mends = mxGetM(IEND_IN); /* number of rows */
    Nends = mxGetN(IEND_IN); /* number of rows */
    /* printf("input iEnds is [ %d %d ] \n",Mends,Nends); */
    if( (Mends==1) && (Nends >=1) ){ /* then do nothing */
    }else if( (Nends == 1) && (Mends >=1) ){ /* a N x 1 is also OK */
        Nends=Mends;
        Mends=1;
    }else{ /*something weird going on */
        mexErrMsgTxt("iEnds must be a 1-by-N or N-by-1 matrix.");
    }

    /* retrieve input data */
    lnQ=mxGetPr(LNQ_IN);
    lnH=mxGetPr(LNH_IN);
    iEnd=mxGetPr(IEND_IN);
    
    /* Create an mxArray for the output data */
    S_OUT = mxCreateNumericMatrix(T,1,mxINT32_CLASS, mxREAL);
    s= (int*) mxGetPr(S_OUT); /* pointer to output array*/
    
    /* allocate temporary arrays */
    mxp0=mxCreateDoubleMatrix(1,N, mxREAL);
    mxp1=mxCreateDoubleMatrix(1,N, mxREAL);
    lnp0=mxGetPr(mxp0);
    lnp1=mxGetPr(mxp1);
    
    mxMaxPrev=mxCreateNumericMatrix(T,N,mxINT32_CLASS,mxREAL);
    MaxPrev=(int*)mxGetPr(mxMaxPrev);
    mxpp=mxCreateDoubleMatrix(N,1, mxREAL);
    lnpp=mxGetPr(mxpp);
    
    /* start of actual algorithm */
    tStart=0;
    for(n=0;n<Nends;n++){
        tEnd=(int)(iEnd[n]);   

        /*lnP1=lnH(tStart,:); % initial probability, not normalized*/
        for(k=0;k<N;k++){
            lnp1[k]=lnH[tStart+k*T];}
        
        /*for tV=(tStart+1):tEnd  */
        for(t=tStart+1;t<tEnd;t++){
            Z=0.0;
            for(k=0;k<N;k++){/*lnP0=lnP1-mean(lnP1); lnP1=zeros(1,N);*/
                lnp0[k]=lnp1[k];
                Z=Z+lnp0[k]/N;
                lnp1[k]=0.0;
            }
            for(k=0;k<N;k++){
                lnp0[k]=lnp0[k]-Z;
            }
                    
            for(j=0;j<N;j++){
                for(k=0;k<N;k++){
                    /* lnPP(kV)=lnP0(kV)+lnQ(kV,jV)+lnH(tV,jV); */
                    lnpp[k]=lnp0[k]+lnQ[k+j*N]+lnH[t+j*T];
                }
                /* probability of previous state before ending up at jV.
                 * [lnP1(jV),         MaxPrev(tV,jV)]=max(lnPP); */
                lnp1[j]=lnpp[0];
                MaxPrev[t+j*T]=0;
                for(k=1;k<N;k++){
                    if(lnpp[k]>lnp1[j]){
                        lnp1[j]=lnpp[k];
                        MaxPrev[t+j*T]=k;
                    }
                }
            }
        }
        /* [~,S(tEnd)]=max(lnP1);*/
        s[tEnd-1]=0;
        Z=lnp1[0];
        for(k=1;k<N;k++){
            if(lnp1[k]>Z){
                Z=lnp1[k];
                s[tEnd-1]=k;
            }
        }
        /*  for tV=tEnd-1:-1:tStart*/
        /*      S(tV)=MaxPrev(tV+1,S(tV+1)); end*/
        for(t=tEnd-2;t>=tStart;t--){
            ss=s[t+1];
            s[t]=MaxPrev[t+1+T*ss];
        }
        tStart=tEnd;
    }
    
    /* finished actual algorithm */
    /* transform back to matlab's index convention */
    for(t=0;t<T;t++){
        s[t]=s[t]+1;
    }
    /* destroy temporary arrays */
    mxDestroyArray(mxp0);
    mxDestroyArray(mxp1);
    mxDestroyArray(mxpp);
    mxDestroyArray(mxMaxPrev);
}
Beispiel #25
0
int main()

{
   Engine *ep;
   mxArray *T = NULL, *result = NULL;
   char buffer[BUFSIZE];
   double time[10] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 
                       8.0, 9.0};
   /*
    * Start the MATLAB engine locally by executing the string
    * "matlab".
    *
    * To start the session on a remote host, use the name of
    * the host as the string rather than \0.
    *
    * For more complicated cases, use any string with whitespace,
    * and that string will be executed literally to start MATLAB.
    */
   if (!(ep = engOpen("\0"))) {
      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 engine.
    */
   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.
    */

   engOutputBuffer(ep, buffer, BUFSIZE);
   while (result == NULL) {
      char str[BUFSIZE];

      /*
       * 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-1, stdin);
	  
      /*
       * Evaluate input with engEvalString.
       */
      engEvalString(ep, str);
	    
      /*
       * Echo the output from the command.  First two characters
       * are always the double prompt (>>).
       */
      printf("%s", buffer+2);

      /*
       * 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;
}
Beispiel #26
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){

  int dims [2];
  int i, j, k, m, n;
  long index;
  double * G_pr;
  double * stage_pr;
  double * answer_G_pr, * fill_ins_pr;
  double * matlab_clique_pr;
  mxArray * matlab_clique;
  Elimination e;
  float ** adj_mat;
  int ** order = (int **) NULL;
  Iterator iter, iter2;
  word w, w2;
  int ** fill_ins;
  Map cliques;
  Map clique;
  mxArray * fill_ins_mat;
  int * nodes;
  mxArray * full;

  full = mlfFull((mxArray *) prhs[0]);
  /* Obtain graph matrix information. */
  m = mxGetM(full);
  n = mxGetN(full);
  G_pr = mxGetPr(full);

  if(n < 1 || m < 1){
    return;
  }

  /* Allocate and populate the log weight adjacency matrix corresponding
     to the input graph. */
  adj_mat = (float **) malloc(sizeof(float *) * m);
  adj_mat[0] = (float *) malloc(sizeof(float) * m * n);
  for(i = 1; i < m; i++){
    adj_mat[i] = adj_mat[i - 1] + n;
  }
  /* We no longer have log weight info, but we have a (total) ordering on
     the nodes already, so we do not need this information. */
  for(i = 0; i < m; i++){
    for(j = 0; j < n; j++){
      index = j * m + i;
      if(G_pr[index] > 0){
        adj_mat[i][j] = 1;
      } else {
        adj_mat[i][j] = 0;
      }
    }
  }

  /* Convert the total elimination ordering into a partial order argument
     for the elimination routine.  The elimination routine's purpose in this
     mode of operation is to return cliques and fill-in edges. */
  if(nrhs > 1){
    order = (int **) malloc(sizeof(int *) * m);
    order[0] = (int *) malloc(sizeof(int) * m * n);
    for(i = 1; i < m; i++){
      order[i] = order[i - 1] + n;
    }
    for(i = 0; i < m; i++){
      for(j = 0; j < n; j++){
        order[i][j] = 0;
      }
    }
    stage_pr = mxGetPr(prhs[1]);
    for(i = 0; i < mxGetN(prhs[1]) - 1; i++){
      order[(int) stage_pr[i] - 1][(int) stage_pr[i + 1] - 1] = 1;
    }
  }

  /* Find the elimination ordering. */
  e = find_elim(n, adj_mat, order, -1);

  /* Allocate memory for the answer, and set the answer. */
  plhs[0] = mxCreateDoubleMatrix(m, n, mxREAL);
  answer_G_pr = mxGetPr(plhs[0]);
  cliques = get_cliques(e);
/* 
  dims[0] = 1;
  dims[1] = get_size_Map(cliques);
  plhs[1] = mxCreateCellArray(2, (const int *) dims);*/
  plhs[1] = mxCreateCellMatrix(get_size_Map(cliques), 1);
  fill_ins = get_fill_ins(e);
  fill_ins_mat = mxCreateDoubleMatrix(m, n, mxREAL);
  fill_ins_pr = mxGetPr(fill_ins_mat);

  for(i = 0; i < n; i++){
    for(j = 0; j < m; j++){
      index = j * m + i;
      answer_G_pr[index] = G_pr[index];
      if(fill_ins[i][j] > 0){
        answer_G_pr[index] = 1;
        fill_ins_pr[index] = 1;
      }
    }
  }
  mxDestroyArray(full);
  plhs[2] = mlfSparse(fill_ins_mat, NULL, NULL, NULL, NULL, NULL);
  mxDestroyArray(fill_ins_mat);
  nodes = (int *) malloc(sizeof(int) * n);
  k = 0;
  iter = get_Iterator(cliques);
  while(!is_empty(iter)){
    w = next_key(iter);
    clique = (Map) w.v;
    matlab_clique = mxCreateDoubleMatrix(1, get_size_Map(clique), mxREAL);
    matlab_clique_pr = mxGetPr(matlab_clique);
    for(i = 0; i < n; i++){
      nodes[i] = 0;
    }
    iter2 = get_Iterator(clique);
    while(!is_empty(iter2)){
      w2 = next_key(iter2);
      nodes[w2.i] = w2.i + 1;
    }
    j = 0;
    for(i = 0; i < n; i++){
      if(nodes[i] > 0){
        matlab_clique_pr[j++] = nodes[i];
      }
    }
    mxSetCell(plhs[1], k++, matlab_clique);
  }
  free(nodes);

  /* Finally, free the allocated memory. */
  destroy_Elimination(e);
  if(adj_mat){
    if(adj_mat[0]){
      free(adj_mat[0]);
    }
    free(adj_mat);
  }
  if(order){
    if(order[0]){
      free(order[0]);
    }
    free(order);
  }
}
unsigned int sf_sensor_block_complete_get_eml_resolved_functions_info( int nlhs,
  mxArray * plhs[], int nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

  char commandName[64];
  if (nrhs<2 || !mxIsChar(prhs[0]))
    return 0;

  /* Possible call to get the get_eml_resolved_functions_info */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"get_eml_resolved_functions_info"))
    return 0;

  {
    unsigned int chartFileNumber;
    chartFileNumber = (unsigned int)mxGetScalar(prhs[1]);
    switch (chartFileNumber) {
     case 1:
      {
        extern const mxArray
          *sf_c1_sensor_block_complete_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c1_sensor_block_complete_get_eml_resolved_functions_info();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

     case 2:
      {
        extern const mxArray
          *sf_c2_sensor_block_complete_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c2_sensor_block_complete_get_eml_resolved_functions_info();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

     case 3:
      {
        extern const mxArray
          *sf_c3_sensor_block_complete_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c3_sensor_block_complete_get_eml_resolved_functions_info();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

     case 4:
      {
        extern const mxArray
          *sf_c4_sensor_block_complete_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c4_sensor_block_complete_get_eml_resolved_functions_info();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

     case 5:
      {
        extern const mxArray
          *sf_c5_sensor_block_complete_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c5_sensor_block_complete_get_eml_resolved_functions_info();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

     case 6:
      {
        extern const mxArray
          *sf_c6_sensor_block_complete_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c6_sensor_block_complete_get_eml_resolved_functions_info();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

     default:
      plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
    }
  }

  return 1;

#else

  return 0;

#endif

}
Beispiel #28
0
INT64 read_problem_sparse(const mxArray *label_vec, const mxArray *instance_mat)
{
	INT64 i, j, k, low, high;
	mwIndex *ir, *jc;
	INT64 elements, max_index, num_samples, label_vector_row_num;
	double *samples, *labels;
	mxArray *instance_mat_col; // instance sparse matrix in column format

	prob.x = NULL;
	prob.y = NULL;
	x_space = NULL;

	if(col_format_flag)
		instance_mat_col = (mxArray *)instance_mat;
	else
	{
		// transpose instance matrix
		mxArray *prhs[1], *plhs[1];
		prhs[0] = mxDuplicateArray(instance_mat);
		if(mexCallMATLAB(1, plhs, 1, prhs, "transpose"))
		{
			mexPrintf("Error: cannot transpose training instance matrix\n");
			return -1;
		}
		instance_mat_col = plhs[0];
		mxDestroyArray(prhs[0]);
	}

	// the number of instance
	prob.l = (INT64) mxGetN(instance_mat_col);
	label_vector_row_num = (INT64) mxGetM(label_vec);

	if(label_vector_row_num!=prob.l)
	{
		mexPrintf("Length of label vector does not match # of instances.\n");
		return -1;
	}
	
	// each column is one instance
	labels = mxGetPr(label_vec);
	samples = mxGetPr(instance_mat_col);
	ir = mxGetIr(instance_mat_col);
	jc = mxGetJc(instance_mat_col);

	num_samples = (INT64) mxGetNzmax(instance_mat_col);

	elements = num_samples + prob.l*2;
	max_index = (INT64) mxGetM(instance_mat_col);

	prob.y = Malloc(double, prob.l);
	prob.x = Malloc(struct feature_node*, prob.l);
	x_space = Malloc(struct feature_node, elements);

	prob.bias=bias;

	j = 0;
	for(i=0;i<prob.l;i++)
	{
		prob.x[i] = &x_space[j];
		prob.y[i] = labels[i];
		low = (INT64) jc[i], high = (INT64) jc[i+1];
		for(k=low;k<high;k++)
		{
			x_space[j].index = (INT64) ir[k]+1;
			x_space[j].value = samples[k];
			j++;
	 	}
		if(prob.bias>=0)
		{
			x_space[j].index = max_index+1;
			x_space[j].value = prob.bias;
			j++;
		}
		x_space[j++].index = -1;
	}

	if(prob.bias>=0)
		prob.n = max_index+1;
	else
		prob.n = max_index;

	return 0;
}
Beispiel #29
0
/*
 * JS Changed coord arguments to double as external function API changed
 */
int matlab_demo_(float *data,
		 double *xcoords, int *xsize,
		 double *ycoords, int *ysize,
		 float *bad_flag) {
  mxArray *T = NULL, *result = NULL;
  mxArray *mX = NULL, *mY = NULL;
  char buffer[BUFSIZE], cbuffer[BUFSIZE];
  double *ddata = 0, *mxData = 0, *myData = 0;;

				/* Open MATLAB engine */
  if (ep == 0){
    if (!(ep = engOpen("\0"))) {
      fprintf(stderr, "\nCan't start MATLAB engine\n");
      return EXIT_FAILURE;
    }
  }

  engOutputBuffer(ep, buffer, BUFSIZE);
				/* Convert from float->double */
  T = mxCreateDoubleMatrix(*xsize, *ysize, mxREAL);
  mxSetName(T, "FERRET_DATA");
  ddata = mxGetPr(T);

  mX = mxCreateDoubleMatrix(*xsize, 1, mxREAL);
  mxSetName(mX, "FERRET_XDATA");
  mxData = mxGetPr(mX);
  mY = mxCreateDoubleMatrix(*ysize, 1, mxREAL);
  mxSetName(mY, "FERRET_YDATA");
  myData = mxGetPr(mY);
  
  {
    int i;
    for (i=0; i < *xsize * *ysize; ++i){
      float theData = data[i];
      if (theData == *bad_flag){
	ddata[i] = NaN;
      } else {
	ddata[i] = data[i];
      }
    }

    memcpy(mxData, xcoords, sizeof(double)* *xsize);
    memcpy(myData, ycoords, sizeof(double)* *ysize);
  }

  /* Place the variables into the MATLAB workspace */
  engPutArray(ep, T);
  engPutArray(ep, mX);
  engPutArray(ep, mY);

  
  sprintf(cbuffer, "ferretdemo(FERRET_DATA', FERRET_XDATA', FERRET_YDATA');");
  engEvalString(ep, cbuffer);
  /*
   * Echo the output from the command.  First two characters are
   * always the double prompt (>>).
   */
  printf("%s", buffer+2);

  mxDestroyArray(T);
/*   engEvalString(ep, "close;"); */
/*   engClose(ep); */
	
  return EXIT_SUCCESS;
}
Beispiel #30
0
/* ************************************************************
   PROCEDURE mexFunction - Entry for Matlab
   ************************************************************ */
void mexFunction(const int nlhs, mxArray *plhs[],
  const int nrhs, const mxArray *prhs[])
{
 mxArray *output_array[3], *Xk, *hXk;
 coneK cK;
 int k, nk, nkp1, nksqr, lendiag,lenud, lenfull, i,ii;
 double *lab,*q,*labk,*xwork;
 const double *x;

/* ------------------------------------------------------------
   Check for proper number of arguments
   ------------------------------------------------------------ */
  mxAssert(nrhs >= NPARIN, "psdeig requires more input arguments");
  mxAssert(nlhs <= NPAROUT, "psdeig produces less output arguments");
/* ------------------------------------------------------------
   Disassemble cone K structure
   ------------------------------------------------------------ */
  conepars(K_IN, &cK);
/* ------------------------------------------------------------
   Compute statistics based on cone K structure
   ------------------------------------------------------------ */
  lendiag = cK.rLen + cK.hLen;
  lenud = cK.rDim + cK.hDim;
  lenfull = cK.lpN + cK.qDim + lenud;
/* ------------------------------------------------------------
   Get input vector x
   ------------------------------------------------------------ */
  mxAssert(!mxIsSparse(X_IN), "x must be full (not sparse).");
  x = mxGetPr(X_IN);
  if(mxGetM(X_IN) * mxGetN(X_IN) != lenud){
    mxAssert(mxGetM(X_IN) * mxGetN(X_IN) == lenfull, "Size mismatch x");
    x += cK.lpN + cK.qDim;       /* point to PSD part */
  }

/* ------------------------------------------------------------
   Allocate output LAB(diag), eigvec Q(full for psd)
   ------------------------------------------------------------ */
  LAB_OUT = mxCreateDoubleMatrix(lendiag, 1, mxREAL);
  lab = mxGetPr(LAB_OUT);
  if(nlhs > 1){
    Q_OUT = mxCreateDoubleMatrix(lenud, 1, mxREAL);
    q = mxGetPr(Q_OUT);
  }
/* ------------------------------------------------------------
   Allocate working arrays:
   ------------------------------------------------------------ */
  Xk = mxCreateDoubleMatrix(0,0,mxREAL);
  hXk = mxCreateDoubleMatrix(0,0,mxCOMPLEX);
  xwork =(double *) mxCalloc(MAX(1,SQR(cK.rMaxn)+2*SQR(cK.hMaxn)),
                             sizeof(double));
/* ------------------------------------------------------------
   PSD: (I) LAB = eig(X)
   ------------------------------------------------------------ */
  if(nlhs < 2){
    for(k=0; k < cK.rsdpN; k++){                /* real symmetric */
      nk = cK.sdpNL[k];
      symproj(xwork,x,nk);              /* make it symmetric */
      mxSetM(Xk, nk);
      mxSetN(Xk, nk);
      mxSetPr(Xk, xwork);
      mexCallMATLAB(1, output_array, 1, &Xk, "eig");
      memcpy(lab, mxGetPr(output_array[0]), nk * sizeof(double));
/* ------------------------------------------------------------
   With mexCallMATLAB, we invoked the mexFunction "eig", which
   allocates a matrix struct *output_array[0], AND a block for the
   float data of that matrix.
   ==> mxDestroyArray() does not only free the float data, it
   also releases the matrix struct (and this is what we want).
   ------------------------------------------------------------ */
      mxDestroyArray(output_array[0]);
      lab += nk;  x += SQR(nk);
    }
/* ------------------------------------------------------------
   WARNING: Matlab's eig doesn't recognize Hermitian, hence VERY slow
   ------------------------------------------------------------ */
    for(; k < cK.sdpN; k++){                    /* complex Hermitian */
      nk = cK.sdpNL[k]; nksqr = SQR(nk);
      symproj(xwork,x,nk);              /* make it Hermitian */
      skewproj(xwork + nksqr,x+nksqr,nk);
      mxSetM(hXk, nk);
      mxSetN(hXk, nk);
      mxSetPr(hXk, xwork);
      mxSetPi(hXk, xwork + nksqr);     
      mexCallMATLAB(1, output_array, 1, &hXk, "eig");
      memcpy(lab, mxGetPr(output_array[0]), nk * sizeof(double));
      mxDestroyArray(output_array[0]);
      lab += nk;  x += 2 * nksqr;
    }
  } /* nlhs < 2 */
  else{
/* ------------------------------------------------------------
   SDP: (II) (Q,LAB) = eig(X)
   ------------------------------------------------------------ */
    for(k=0; k < cK.rsdpN; k++){                /* real symmetric */
      nk = cK.sdpNL[k];
      symproj(xwork,x,nk);                      /* make it symmetric */
      mxSetM(Xk, nk);
      mxSetN(Xk, nk);
      mxSetPr(Xk, xwork);
      mexCallMATLAB(2, output_array, 1, &Xk, "eig");
      nksqr = SQR(nk);                                  /* copy Q-matrix */
      memcpy(q, mxGetPr(output_array[0]), nksqr * sizeof(double));
      nkp1 = nk + 1;                                   /* copy diag(Lab) */
      labk = mxGetPr(output_array[1]);
      for(i = 0, ii = 0; i < nk; i++, ii += nkp1)
        lab[i] = labk[ii];
      mxDestroyArray(output_array[0]);
      mxDestroyArray(output_array[1]);
      lab += nk;  x += nksqr; q += nksqr;
    }
    for(; k < cK.sdpN; k++){                    /* complex Hermitian */
      nk = cK.sdpNL[k]; nksqr = SQR(nk);
      symproj(xwork,x,nk);                      /* make it Hermitian */
      skewproj(xwork + nksqr,x+nksqr,nk);
      mxSetM(hXk, nk);
      mxSetN(hXk, nk);
      mxSetPr(hXk, xwork);
      mxSetPi(hXk, xwork+nksqr);
#ifdef USE_SVD
      mexCallMATLAB(3, output_array, 1, &hXk, "svd");
#else
      mexCallMATLAB(2, output_array, 1, &hXk, "eig");
#endif
      memcpy(q, mxGetPr(output_array[0]), nksqr * sizeof(double));
      q += nksqr;
      if(mxIsComplex(output_array[0]))     /* if any imaginary part */
        memcpy(q, mxGetPi(output_array[0]), nksqr * sizeof(double));
      nkp1 = nk + 1;                              /* copy diag(Lab) */
      labk = mxGetPr(output_array[1]);
      for(i = 0, ii = 0; i < nk; i++, ii += nkp1)
        lab[i] = labk[ii];
      mxDestroyArray(output_array[0]);
      mxDestroyArray(output_array[1]);
#ifdef USE_SVD
      mxDestroyArray(output_array[2]);
#endif
      lab += nk;  x += 2 * nksqr; q += nksqr;
    }
  } /* [lab,q] = eigK */
/* ------------------------------------------------------------
   Release PSD-working arrays.
   ------------------------------------------------------------ */
  mxSetM(Xk,0); mxSetN(Xk,0); 
  mxSetPr(Xk, (double *) NULL);
  mxDestroyArray(Xk);
  mxSetM(hXk,0); mxSetN(hXk,0); 
  mxSetPr(hXk, (double *) NULL);   mxSetPi(hXk, (double *) NULL);
  mxDestroyArray(hXk);
  mxFree(xwork);
}