Пример #1
0
unsigned int sf_Automat_process_check_sum_call( int nlhs, mxArray * plhs[], int
  nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3346104985U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2292149139U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(896709456U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3686958539U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2089999033U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(941296165U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3620454784U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(665239257U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 1:
        {
          extern void sf_c1_Automat_get_check_sum(mxArray *plhs[]);
          sf_c1_Automat_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3564696471U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(678668628U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1090454852U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3896867807U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3437021989U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1199552135U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2842795639U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(692071385U);
  }

  return 1;

#else

  return 0;

#endif

}
Пример #2
0
void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
    
    short   fh;
    WORD    chan;
    long    maxpoints;
    TSTime  sTime;
    TSTime  eTime;
    TpFilterMask    pFltMask=NULL;
    TFilterMask FilterMask;
    long npoints=0;
    TMarker Markers[32767];
    short levLow;
    unsigned char *ptr;
    int dim[2]={1,1};
    double *p;
    long *ret;
    int i,j;
    
    
    
    //Used for filter
    int m,n;
    const int *empty[2]={0,0};
    
    
    if (nrhs<5)
        mexErrMsgTxt("SONGetMarkData: Too few  arguments\n");
    
    //Get input arguments
    fh=mxGetScalar(prhs[0]);                   //File handle
    chan=mxGetScalar(prhs[1]);                 //Channel number
    maxpoints=mxGetScalar(prhs[2]);            //maxpoints
    if ((maxpoints>32767) || (maxpoints<=0))
        maxpoints=32767;
    sTime=mxGetScalar(prhs[3]);                //Start time for data search
    eTime=mxGetScalar(prhs[4]);                //End Time for data search
    
    
    
    //Get and set up the filter mask
    if (nrhs==6 && mxIsStruct(prhs[5])==1){
        GetFilterMask(prhs[5], &FilterMask);
        pFltMask=&FilterMask;
    }
    else
        pFltMask=NULL;
    
    
    //Load and get pointer to the library SON32.DLL//
    hinstLib = LoadLibrary(SON32);
    if (hinstLib == NULL){
        mexPrintf("%s not found",SON32);
        plhs[0]=mxCreateNumericArray(2, dim, mxINT32_CLASS, mxREAL);
        p=mxGetData(plhs[0]);
        p[0]=SON_BAD_PARAM;
        return;
    }
    
    
    
    //Call DLL
    npoints=_SONGetMarkData(fh, chan, &Markers, maxpoints, sTime, eTime, pFltMask);
    fFreeResult = FreeLibrary(hinstLib);
    
    
    //return results. This one goes in ans if no arguments
    dim[0]=1;
    dim[1]=1;
    plhs[0]=mxCreateNumericArray(2, dim, mxINT32_CLASS, mxREAL);
    ret=mxGetData(plhs[0]);
    *ret=npoints;
    
    
    if (nlhs>=2) {
        dim[0]=max(0,npoints);
        plhs[1]=mxCreateNumericArray(2, dim, mxINT32_CLASS, mxREAL);
        ret=mxGetData(plhs[1]);
        for (i=0; i<npoints; i++)
            *ret++=Markers[i].mark;
        
    }
    
    if (nlhs==3) {
        dim[1]=4;
        dim[0]=max(0,npoints);
        plhs[2]=mxCreateNumericArray(2, dim, mxUINT8_CLASS, mxREAL);
        ptr=mxGetData(plhs[2]);
            for (j=0; j<4; j++)
                for(i=0; i<npoints; i++)
                *ptr++=Markers[i].mvals[j];

        
        
    }
}
Пример #3
0
unsigned int sf_mainSim_process_check_sum_call( int nlhs, mxArray * plhs[], int
  nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(13515316U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(833989788U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2260018523U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(850705350U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(888113858U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2849162545U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(124305733U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1606849013U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 1:
        {
          extern void sf_c1_mainSim_get_check_sum(mxArray *plhs[]);
          sf_c1_mainSim_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3564696471U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(678668628U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1090454852U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3896867807U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3921995900U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2346178767U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2268642723U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2571770906U);
  }

  return 1;

#else

  return 0;

#endif

}
Пример #4
0
// [E,ind,segs] = mexFunction(model,I,chns,chnsSs) - helper for edgesDetect.m
void mexFunction( int nl, mxArray *pl[], int nr, const mxArray *pr[] )
{
  // get inputs
  mxArray *model = (mxArray*) pr[0];
  float *I = (float*) mxGetData(pr[1]);
  float *chns = (float*) mxGetData(pr[2]);
  float *chnsSs = (float*) mxGetData(pr[3]);

  // extract relevant fields from model and options
  float *thrs = (float*) mxGetData(mxGetField(model,0,"thrs"));
  uint32 *fids = (uint32*) mxGetData(mxGetField(model,0,"fids"));
  uint32 *child = (uint32*) mxGetData(mxGetField(model,0,"child"));
  uint8 *segs = (uint8*) mxGetData(mxGetField(pr[0],0,"segs"));
  uint8 *nSegs = (uint8*) mxGetData(mxGetField(pr[0],0,"nSegs"));
  uint16 *eBins = (uint16*) mxGetData(mxGetField(model,0,"eBins"));
  uint32 *eBnds = (uint32*) mxGetData(mxGetField(model,0,"eBnds"));
  mxArray *opts = mxGetField(model,0,"opts");
  const int shrink = (int) mxGetScalar(mxGetField(opts,0,"shrink"));
  const int imWidth = (int) mxGetScalar(mxGetField(opts,0,"imWidth"));
  const int gtWidth = (int) mxGetScalar(mxGetField(opts,0,"gtWidth"));
  const int nChns = (int) mxGetScalar(mxGetField(opts,0,"nChns"));
  const int nCells = (int) mxGetScalar(mxGetField(opts,0,"nCells"));
  const uint32 nChnFtrs = (uint32) mxGetScalar(mxGetField(opts,0,"nChnFtrs"));
  const int stride = (int) mxGetScalar(mxGetField(opts,0,"stride"));
  const int nTreesEval = (int) mxGetScalar(mxGetField(opts,0,"nTreesEval"));
  int sharpen = (int) mxGetScalar(mxGetField(opts,0,"sharpen"));
  int nThreads = (int) mxGetScalar(mxGetField(opts,0,"nThreads"));
  const int nBnds = int(mxGetNumberOfElements(mxGetField(model,0,"eBnds"))-1)/
    int(mxGetNumberOfElements(mxGetField(model,0,"thrs")));
  const char *msgSharpen="Model supports sharpening of at most %i pixels!\n";
  if( sharpen>nBnds-1 ) { sharpen=nBnds-1; mexPrintf(msgSharpen,sharpen); }

  // get dimensions and constants
  const mwSize *imgSize = mxGetDimensions(pr[1]);
  const int h = (int) imgSize[0];
  const int w = (int) imgSize[1];
  const int Z = mxGetNumberOfDimensions(pr[1])<=2 ? 1 : imgSize[2];
  const mwSize *fidsSize = mxGetDimensions(mxGetField(model,0,"fids"));
  const int nTreeNodes = (int) fidsSize[0];
  const int nTrees = (int) fidsSize[1];
  const int h1 = (int) ceil(double(h-imWidth)/stride);
  const int w1 = (int) ceil(double(w-imWidth)/stride);
  const int h2 = h1*stride+gtWidth;
  const int w2 = w1*stride+gtWidth;
  const int imgDims[3] = {h,w,Z};
  const int chnDims[3] = {h/shrink,w/shrink,nChns};
  const int indDims[3] = {h1,w1,nTreesEval};
  const int outDims[3] = {h2,w2,1};
  const int segDims[5] = {gtWidth,gtWidth,h1,w1,nTreesEval};

  // construct lookup tables
  uint32 *iids, *eids, *cids, *cids1, *cids2;
  iids = buildLookup( (int*)imgDims, gtWidth );
  eids = buildLookup( (int*)outDims, gtWidth );
  cids = buildLookup( (int*)chnDims, imWidth/shrink );
  buildLookupSs( cids1, cids2, (int*)chnDims, imWidth/shrink, nCells );

  // create outputs
  pl[0] = mxCreateNumericArray(3,outDims,mxSINGLE_CLASS,mxREAL);
  float *E = (float*) mxGetData(pl[0]);
  pl[1] = mxCreateNumericArray(3,indDims,mxUINT32_CLASS,mxREAL);
  uint32 *ind = (uint32*) mxGetData(pl[1]);
  if(nl>2) pl[2] = mxCreateNumericArray(5,segDims,mxUINT8_CLASS,mxREAL);
  uint8 *segsOut; if(nl>2) segsOut = (uint8*) mxGetData(pl[2]);

  // apply forest to all patches and store leaf inds
  #ifdef USEOMP
  nThreads = min(nThreads,omp_get_max_threads());
  #pragma omp parallel for num_threads(nThreads)
  #endif
  for( int c=0; c<w1; c++ ) for( int t=0; t<nTreesEval; t++ ) {
    for( int r0=0; r0<2; r0++ ) for( int r=r0; r<h1; r+=2 ) {
      int o = (r*stride/shrink) + (c*stride/shrink)*h/shrink;
      // select tree to evaluate
      int t1 = ((r+c)%2*nTreesEval+t)%nTrees; uint32 k = t1*nTreeNodes;
      while( child[k] ) {
        // compute feature (either channel or self-similarity feature)
        uint32 f = fids[k]; float ftr;
        if( f<nChnFtrs ) ftr = chns[cids[f]+o]; else
          ftr = chnsSs[cids1[f-nChnFtrs]+o]-chnsSs[cids2[f-nChnFtrs]+o];
        // compare ftr to threshold and move left or right accordingly
        if( ftr < thrs[k] ) k = child[k]-1; else k = child[k];
        k += t1*nTreeNodes;
      }
      // store leaf index and update edge maps
      ind[ r + c*h1 + t*h1*w1 ] = k;
    }
  }

  // compute edge maps (avoiding collisions from parallel executions)
  if( !sharpen ) for( int c0=0; c0<gtWidth/stride; c0++ ) {
    #ifdef USEOMP
    #pragma omp parallel for num_threads(nThreads)
    #endif
    for( int c=c0; c<w1; c+=gtWidth/stride ) {
      for( int r=0; r<h1; r++ ) for( int t=0; t<nTreesEval; t++ ) {
        uint32 k = ind[ r + c*h1 + t*h1*w1 ];
        float *E1 = E + (r*stride) + (c*stride)*h2;
        int b0=eBnds[k*nBnds], b1=eBnds[k*nBnds+1]; if(b0==b1) continue;
        for( int b=b0; b<b1; b++ ) E1[eids[eBins[b]]]++;
        if(nl>2) memcpy(segsOut+(r+c*h1+t*h1*w1)*gtWidth*gtWidth,
          segs+k*gtWidth*gtWidth,gtWidth*gtWidth*sizeof(uint8));
      }
    }
  }

  // computed sharpened edge maps, snapping to local color values
  if( sharpen ) {
    // compute neighbors array
    const int g=gtWidth; uint16 N[4096*4];
    for( int c=0; c<g; c++ ) for( int r=0; r<g; r++ ) {
      int i=c*g+r; uint16 *N1=N+i*4;
      N1[0] = c>0 ? i-g : i; N1[1] = c<g-1 ? i+g : i;
      N1[2] = r>0 ? i-1 : i; N1[3] = r<g-1 ? i+1 : i;
    }
    #ifdef USEOMP
    #pragma omp parallel for num_threads(nThreads)
    #endif
    for( int c=0; c<w1; c++ ) for( int r=0; r<h1; r++ ) {
      for( int t=0; t<nTreesEval; t++ ) {
        // get current segment and copy into S
        uint32 k = ind[ r + c*h1 + t*h1*w1 ];
        int m = nSegs[k]; if( m==1 ) continue;
        uint8 S0[4096], *S=(nl<=2) ? S0 : segsOut+(r+c*h1+t*h1*w1)*g*g;
        memcpy(S,segs+k*g*g, g*g*sizeof(uint8));
        // compute color model for each segment using every other pixel
        int ci, ri, s, z; float ns[100], mus[1000];
        const float *I1 = I+(c*stride+(imWidth-g)/2)*h+r*stride+(imWidth-g)/2;
        for( s=0; s<m; s++ ) { ns[s]=0; for( z=0; z<Z; z++ ) mus[s*Z+z]=0; }
        for( ci=0; ci<g; ci+=2 ) for( ri=0; ri<g; ri+=2 ) {
          s = S[ci*g+ri]; ns[s]++;
          for( z=0; z<Z; z++ ) mus[s*Z+z]+=I1[z*h*w+ci*h+ri];
        }
        for(s=0; s<m; s++) for( z=0; z<Z; z++ ) mus[s*Z+z]/=ns[s];
        // update segment S according to local color values
        int b0=eBnds[k*nBnds], b1=eBnds[k*nBnds+sharpen];
        for( int b=b0; b<b1; b++ ) {
          float vs[10], d, e, eBest=1e10f; int i, sBest=-1, ss[4];
          for( i=0; i<4; i++ ) ss[i]=S[N[eBins[b]*4+i]];
          for( z=0; z<Z; z++ ) vs[z]=I1[iids[eBins[b]]+z*h*w];
          for( i=0; i<4; i++ ) {
            s=ss[i]; if(s==sBest) continue;
            e=0; for( z=0; z<Z; z++ ) { d=mus[s*Z+z]-vs[z]; e+=d*d; }
            if( e<eBest ) { eBest=e; sBest=s; }
          }
          S[eBins[b]]=sBest;
        }
        // convert mask to edge maps (examining expanded set of pixels)
        float *E1 = E + c*stride*h2 + r*stride; b1=eBnds[k*nBnds+sharpen+1];
        for( int b=b0; b<b1; b++ ) {
          int i=eBins[b]; uint8 s=S[i]; uint16 *N1=N+i*4;
          if( s!=S[N1[0]] || s!=S[N1[1]] || s!=S[N1[2]] || s!=S[N1[3]] )
            E1[eids[i]]++;
        }
      }
    }
  }

  // free memory
  delete [] iids; delete [] eids;
  delete [] cids; delete [] cids1; delete [] cids2;
}
Пример #5
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
  // get inputs
  float *chns = (float*) mxGetData(prhs[0]);
  float *chnsSs = (float*) mxGetData(prhs[1]);
  float *thrs = (float*) mxGetData(prhs[2]);
  uint32 *fids = (uint32*) mxGetData(prhs[3]);
  uint32 *child = (uint32*) mxGetData(prhs[4]);
  float *distr = (float*) mxGetData(prhs[5]);//
  uint32 *cids1 =  (uint32*) mxGetData(prhs[6]);
  uint32 *cids2 =  (uint32*) mxGetData(prhs[7]);
  const int stride = (int) mxGetScalar(prhs[8]);// 2
  const int rad = (int) mxGetScalar(prhs[9]);//17
  const int nChnFtrs = (int) mxGetScalar(prhs[10]);//17150

  // get dimensions and constants
  const mwSize *chnsSize = mxGetDimensions(prhs[0]);
  const int height = (int) chnsSize[0];//634
  const int width = (int) chnsSize[1];//434
  const mwSize *distrSize = mxGetDimensions(prhs[5]);
  const int nTokens = (int) distrSize[0];//
  const int nTreeNodes = (int) distrSize[1];//
  const int nTrees = (int) distrSize[2];//
  const int heightOut = (int) ceil((height-rad*2.0)/stride);
  const int widthOut = (int) ceil((width-rad*2.0)/stride);

  // create output
  const int outDims[3]={nTokens,heightOut,widthOut};
  float *S = (float*) mxCalloc(nTokens*heightOut*widthOut,sizeof(float));
  plhs[0] = mxCreateNumericMatrix(0,0,mxSINGLE_CLASS,mxREAL);
  mxSetData(plhs[0],S);
  mxSetDimensions(plhs[0],outDims,3);

  // apply forest to each patch
  #pragma omp parallel for
  for( int c=0; c<widthOut; c++ ) {
      for( int r=0; r<heightOut; r++ ) {
        // classify a single patch using all trees
        float *chns1 = chns + (r*stride) + (c*stride)*height;
        float *chnsSs1 = chnsSs + (r*stride) + (c*stride)*height;
        
        for( int t = 0; t < nTrees; t++ ) {
            uint32 k = t*nTreeNodes, res;
            
            while( child[k] ) {
                // compute feature (either lookup in channel or self-similarity feature)
                uint32 f = fids[k], cid1 = cids1[f], cid2 = cids2[f];
                float ftr;
                
                if( f<nChnFtrs )
                    ftr = chns1[cid1];
                else
                    ftr = chnsSs1[cid1] - chnsSs1[cid2];
                
                // compare ftr to threshold and move left or right accordingly
                if( ftr < thrs[k] )
                    k = child[k]-1;
                else
                    k = child[k];
                
                res = k;
                k += t*nTreeNodes;
            }
            
            // lookup probability and store results
            for( int i = 0; i < nTokens; i++ ) {
                S[r*nTokens + c*heightOut*nTokens + i] += distr[t*nTreeNodes*nTokens + res*nTokens + i];
            }
        }
      }
  }
}
Пример #6
0
/* The gateway function */
void mexFunction(int nlhs, mxArray * plhs[],
				 int nrhs, const mxArray * prhs[])
{
	/* process input from matlab */
	/* format: id, r[M][N]; 
	   id = the order of the target agent in all input agents
	   In matrix r, each row: (px, py, vx, vy, prx, pry) */

	int id;
	double * arr;
    double * pr;
	int row, col;

	id = mxGetScalar(prhs[0]);
	row = mxGetM(prhs[1]);
	col = mxGetN(prhs[1]);
	arr = mxGetPr(prhs[1]);
    pr = mxGetPr(prhs[2]);
		
    //printf("row = %d\n", row);
	for (int r = 0; r < row; r ++)
	{
		int c = 0;

		pv elem;

		elem.x = arr[r + row*(c++)];
		elem.y = arr[r + row*(c++)];
		elem.vx = arr[r + row*(c++)];
		elem.vy = arr[r + row*(c++)];
		elem.prx = arr[r + row*(c++)];
		elem.pry = arr[r + row*(c++)];

		pvList.push_back(elem);
	}
	
    for (int i = 0; i < NUM_PARAM; i ++)
    {
        param[i] = pr[i];
    }
    
    init();

	float x, y, vx, vy;
	rvo_sim(); // Change name plz!
    
    // Get the simualtion results
    RVO::Vector2 pos, vel, prv;
    double * o;
    
    plhs[0] = mxCreateDoubleMatrix(1, 4*row, mxREAL);
    o = mxGetPr(plhs[0]);
    for (int r = 0; r < row; r ++)
    {
        // access RVO for results    
        pos = sim->getAgentPosition(r);
        vel = sim->getAgentVelocity(r);
        prv = sim->getAgentPrefVelocity(r);

        x = pos.x(); y = pos.y();
        vx = vel.x(); vy = vel.y();
        
        // load output arrays
        int baseInd = r * 4;
        o[baseInd] = x;
        o[baseInd+1] = y;
        o[baseInd+2] = vx;
        o[baseInd+3] = vy;
    }

//  // Previous code
// 	plhs[0] = mxCreateDoubleMatrix(1, 4, mxREAL);
// 	double * o;
// 	o = mxGetPr(plhs[0]);
// 	o[0] = x;
// 	o[1] = y;
// 	o[2] = vx;
// 	o[3] = vy;

	destroy();
}
Пример #7
0
unsigned int sf_test_process_check_sum_call( int nlhs, mxArray * plhs[], int
  nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2879395541U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3292577648U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3796445781U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3615203250U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2590014158U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3891542480U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2125734249U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1519912872U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 1:
        {
          extern void sf_c1_test_get_check_sum(mxArray *plhs[]);
          sf_c1_test_get_check_sum(plhs);
          break;
        }

       case 2:
        {
          extern void sf_c2_test_get_check_sum(mxArray *plhs[]);
          sf_c2_test_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3061339410U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1991824845U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3599338742U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2357874978U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(4167789182U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(252419955U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3494262876U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(711935334U);
  }

  return 1;

#else

  return 0;

#endif

}
unsigned int sf_IntelligentFlightSystem_process_check_sum_call( int nlhs,
  mxArray * plhs[], int nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1029893756U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1718458764U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2541882730U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2540130192U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1673257343U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(713078858U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1079295166U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3391332431U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 2:
        {
          extern void sf_c2_IntelligentFlightSystem_get_check_sum(mxArray *plhs[]);
          sf_c2_IntelligentFlightSystem_get_check_sum(plhs);
          break;
        }

       case 6:
        {
          extern void sf_c6_IntelligentFlightSystem_get_check_sum(mxArray *plhs[]);
          sf_c6_IntelligentFlightSystem_get_check_sum(plhs);
          break;
        }

       case 9:
        {
          extern void sf_c9_IntelligentFlightSystem_get_check_sum(mxArray *plhs[]);
          sf_c9_IntelligentFlightSystem_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2515920432U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3908508645U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2530489944U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2924353608U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(2793743795U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(2713150621U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(2962262553U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2433145717U);
  }

  return 1;

#else

  return 0;

#endif

}
Пример #9
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__ (__MAX_FILENAME_LENGTH__+1024)
    char s[__MAX_S__LENGTH__+1];

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

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

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

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





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

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

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


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


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

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

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

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

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


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


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

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


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

#ifdef MATLAB_MEX_FILE

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

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

  {
    unsigned int chartFileNumber;
    chartFileNumber = (unsigned int)mxGetScalar(prhs[1]);
    switch (chartFileNumber) {
     case 2:
      {
        if (strcmp(aiChksum, "mJv7tsD6gCcUKINP8Oy5aG") == 0) {
          extern mxArray *sf_c2_IntelligentFlightSystem_get_autoinheritance_info
            (void);
          plhs[0] = sf_c2_IntelligentFlightSystem_get_autoinheritance_info();
          break;
        }

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

     case 6:
      {
        if (strcmp(aiChksum, "VSxksOs1NLkvwAzXu95Kd") == 0) {
          extern mxArray *sf_c6_IntelligentFlightSystem_get_autoinheritance_info
            (void);
          plhs[0] = sf_c6_IntelligentFlightSystem_get_autoinheritance_info();
          break;
        }

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

     case 9:
      {
        if (strcmp(aiChksum, "fckvBmBjBT8XA7CcoasVNF") == 0) {
          extern mxArray *sf_c9_IntelligentFlightSystem_get_autoinheritance_info
            (void);
          plhs[0] = sf_c9_IntelligentFlightSystem_get_autoinheritance_info();
          break;
        }

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

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

  return 1;

#else

  return 0;

#endif

}
unsigned int sf_IntelligentFlightSystem_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 2:
      {
        extern const mxArray
          *sf_c2_IntelligentFlightSystem_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c2_IntelligentFlightSystem_get_eml_resolved_functions_info();
        plhs[0] = mxDuplicateArray(persistentMxArray);
        mxDestroyArray(persistentMxArray);
        break;
      }

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

     case 9:
      {
        extern const mxArray
          *sf_c9_IntelligentFlightSystem_get_eml_resolved_functions_info(void);
        mxArray *persistentMxArray = (mxArray *)
          sf_c9_IntelligentFlightSystem_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

}
Пример #12
0
/* the gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  int i; 
  srslte_cell_t cell; 
  srslte_pdsch_t pdsch;
  srslte_chest_dl_t chest; 
  srslte_ofdm_t fft; 
  cf_t *input_fft, *input_signal;
  int nof_re; 
  srslte_pdsch_cfg_t cfg;
  srslte_softbuffer_rx_t softbuffer; 
  uint32_t rnti32;
  uint32_t cfi; 

  if (nrhs < NOF_INPUTS) {
    help();
    return;
  }

  bzero(&cfg, sizeof(srslte_pdsch_cfg_t));

  if (mexutils_read_cell(ENBCFG, &cell)) {
    help();
    return;
  }
  
  if (mexutils_read_uint32_struct(PDSCHCFG, "RNTI", &rnti32)) {
    mexErrMsgTxt("Field RNTI not found in pdsch config\n");
    return;
  }
  
  if (mexutils_read_uint32_struct(ENBCFG, "CFI", &cfi)) {
    help();
    return;
  }
  if (mexutils_read_uint32_struct(ENBCFG, "NSubframe", &cfg.sf_idx)) {
    help();
    return;
  }

  if (srslte_pdsch_init(&pdsch, cell)) {
    mexErrMsgTxt("Error initiating PDSCH\n");
    return;
  }
  srslte_pdsch_set_rnti(&pdsch, (uint16_t) (rnti32 & 0xffff));

  if (srslte_softbuffer_rx_init(&softbuffer, cell)) {
    mexErrMsgTxt("Error initiating soft buffer\n");
    return;
  }
  
  if (srslte_chest_dl_init(&chest, cell)) {
    mexErrMsgTxt("Error initializing equalizer\n");
    return;
  }

  if (srslte_ofdm_rx_init(&fft, cell.cp, cell.nof_prb)) {
    mexErrMsgTxt("Error initializing FFT\n");
    return;
  }
  
  nof_re = 2 * SRSLTE_CP_NORM_NSYMB * cell.nof_prb * SRSLTE_NRE;

  cfg.grant.mcs.tbs = mxGetScalar(TBS);
  if (cfg.grant.mcs.tbs == 0) {
    mexErrMsgTxt("Error trblklen is zero\n");
    return;
  }
  if (srslte_cbsegm(&cfg.cb_segm, cfg.grant.mcs.tbs)) {
    mexErrMsgTxt("Error computing CB segmentation\n");
    return; 
  }

  if (mexutils_read_uint32_struct(PDSCHCFG, "RV", &cfg.rv)) {
    mexErrMsgTxt("Field RV not found in pdsch config\n");
    return;
  }
  
  char *mod_str = mexutils_get_char_struct(PDSCHCFG, "Modulation");
  
  if (!strcmp(mod_str, "QPSK")) {
    cfg.grant.mcs.mod = SRSLTE_MOD_QPSK;
  } else if (!strcmp(mod_str, "16QAM")) {
    cfg.grant.mcs.mod = SRSLTE_MOD_16QAM;
  } else if (!strcmp(mod_str, "64QAM")) {
    cfg.grant.mcs.mod = SRSLTE_MOD_64QAM;
  } else {
   mexErrMsgTxt("Unknown modulation\n");
   return;
  }

  mxFree(mod_str);
  
  float *prbset; 
  mxArray *p; 
  p = mxGetField(PDSCHCFG, 0, "PRBSet");
  if (!p) {
    mexErrMsgTxt("Error field PRBSet not found\n");
    return;
  } 
  
  // Only localized PRB supported 
  cfg.grant.nof_prb = mexutils_read_f(p, &prbset);

  for (i=0;i<cell.nof_prb;i++) {
    cfg.grant.prb_idx[0][i] = false; 
    for (int j=0;j<cfg.grant.nof_prb && !cfg.grant.prb_idx[0][i];j++) {
      if ((int) prbset[j] == i) {
        cfg.grant.prb_idx[0][i] = true;
      }
    }
  }
  memcpy(&cfg.grant.prb_idx[1], &cfg.grant.prb_idx[0], SRSLTE_MAX_PRB*sizeof(bool));

  free(prbset);
  
  srslte_dl_dci_to_grant_nof_re(&cfg.grant, cell, cfg.sf_idx, cell.nof_prb<10?(cfi+1):cfi);
  
  // Fill rest of grant structure 
  cfg.grant.lstart = cell.nof_prb<10?(cfi+1):cfi;
  cfg.grant.nof_symb = 2*SRSLTE_CP_NSYMB(cell.cp)-cfg.grant.lstart;
  cfg.grant.Qm = srslte_mod_bits_x_symbol(cfg.grant.mcs.mod);
  cfg.grant.nof_bits = cfg.grant.nof_re * cfg.grant.Qm;     
    
  /** Allocate input buffers */
  if (mexutils_read_cf(INPUT, &input_signal) < 0) {
    mexErrMsgTxt("Error reading input signal\n");
    return; 
  }
  input_fft = srslte_vec_malloc(SRSLTE_SF_LEN_RE(cell.nof_prb, cell.cp) * sizeof(cf_t));
  
  cf_t *ce[SRSLTE_MAX_PORTS];
  for (i=0;i<cell.nof_ports;i++) {
    ce[i] = srslte_vec_malloc(SRSLTE_SF_LEN_RE(cell.nof_prb, cell.cp) * sizeof(cf_t));
  }
  
  srslte_ofdm_rx_sf(&fft, input_signal, input_fft);

  if (nrhs > NOF_INPUTS) {
    cf_t *cearray = NULL; 
    nof_re = mexutils_read_cf(prhs[NOF_INPUTS], &cearray);
    cf_t *cearray_ptr = cearray; 
    for (i=0;i<cell.nof_ports;i++) {
      for (int j=0;j<nof_re/cell.nof_ports;j++) {
        ce[i][j] = *cearray;
        cearray++;
      }
    }    
    if (cearray_ptr)
      free(cearray_ptr);
  } else {
    srslte_chest_dl_estimate(&chest, input_fft, ce, cfg.sf_idx);    
  }
  float noise_power;
  if (nrhs > NOF_INPUTS + 1) {
    noise_power = mxGetScalar(prhs[NOF_INPUTS+1]);
  } else {
    noise_power = srslte_chest_dl_get_noise_estimate(&chest);
  }
  
  uint8_t *data = malloc(sizeof(uint8_t) * cfg.grant.mcs.tbs);
  if (!data) {
    return;
  }

  int r = srslte_pdsch_decode(&pdsch, &cfg, &softbuffer, input_fft, ce, noise_power, data);

  
  if (nlhs >= 1) { 
    plhs[0] = mxCreateLogicalScalar(r == 0);
  }
  if (nlhs >= 2) {
    mexutils_write_uint8(data, &plhs[1], cfg.grant.mcs.tbs, 1);  
  }
  if (nlhs >= 3) {
    mexutils_write_cf(pdsch.symbols[0], &plhs[2], cfg.grant.nof_re, 1);  
  }
  if (nlhs >= 4) {
    mexutils_write_cf(pdsch.d, &plhs[3], cfg.grant.nof_re, 1);  
  }
  if (nlhs >= 5) {
    mexutils_write_f(pdsch.e, &plhs[4], cfg.grant.nof_bits, 1);  
  }
  
  srslte_chest_dl_free(&chest);
  srslte_ofdm_rx_free(&fft);
  srslte_pdsch_free(&pdsch);
  
  for (i=0;i<cell.nof_ports;i++) {
    free(ce[i]);
  }
  free(data);
  free(input_signal);
  free(input_fft);
  
  return;
}
unsigned int sf_BJStateflow_process_check_sum_call( int nlhs, mxArray * plhs[],
  int nrhs, const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

  /* Possible call to get the checksum */
  mxGetString(prhs[0], commandName,sizeof(commandName)/sizeof(char));
  commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
  if (strcmp(commandName,"sf_get_check_sum"))
    return 0;
  plhs[0] = mxCreateDoubleMatrix( 1,4,mxREAL);
  if (nrhs>1 && mxIsChar(prhs[1])) {
    mxGetString(prhs[1], commandName,sizeof(commandName)/sizeof(char));
    commandName[(sizeof(commandName)/sizeof(char)-1)] = '\0';
    if (!strcmp(commandName,"machine")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(869586640U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(1378061590U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(3016396222U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(1356957673U);
    } else if (!strcmp(commandName,"exportedFcn")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0U);
    } else if (!strcmp(commandName,"makefile")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1998470075U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3347301001U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1007541166U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2568101299U);
    } else if (nrhs==3 && !strcmp(commandName,"chart")) {
      unsigned int chartFileNumber;
      chartFileNumber = (unsigned int)mxGetScalar(prhs[2]);
      switch (chartFileNumber) {
       case 1:
        {
          extern void sf_c1_BJStateflow_get_check_sum(mxArray *plhs[]);
          sf_c1_BJStateflow_get_check_sum(plhs);
          break;
        }

       default:
        ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(0.0);
        ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(0.0);
      }
    } else if (!strcmp(commandName,"target")) {
      ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(3564696471U);
      ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(678668628U);
      ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(1090454852U);
      ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(3896867807U);
    } else {
      return 0;
    }
  } else {
    ((real_T *)mxGetPr((plhs[0])))[0] = (real_T)(1811237150U);
    ((real_T *)mxGetPr((plhs[0])))[1] = (real_T)(3075248826U);
    ((real_T *)mxGetPr((plhs[0])))[2] = (real_T)(29541129U);
    ((real_T *)mxGetPr((plhs[0])))[3] = (real_T)(2528792612U);
  }

  return 1;

#else

  return 0;

#endif

}
Пример #14
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
	mxArray*    img;
	u_int8_t*   p_img;               /*The image from Matlab*/
	u_int8_t**  p_gray;              /*Image converted for texture calcs*/
	int         mrows;               /*Image height*/
	int         ncols;               /*Image width*/
	TEXTURE*    features ;           /*Returned struct of features*/
	int         i ;
	int         imgsize[2] ;              
	int         imgindex[2] ;
	long        offset ;                  
	int         outputsize[2] ;      /*Dimensions of TEXTURE struct*/
	int         outputindex[2] ;
	
	float*      output ;             /*Features to return*/
	int         distance, angle;     /*Parameters for texture calculations*/

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

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


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

	/*
	    Memory clean-up.
	*/
	for (i=0; i<mrows ; i++)
		mxFree(p_gray[i]) ;
	mxFree(p_gray) ;  
	
	/* features is calloc'd inside of Extract_Texture_Features */
	free(features) ;
}
Пример #15
0
void mexFunction(
  int nOUT, mxArray *pOUT[],
  int nINP, const mxArray *pINP[])
{
  
  double *t1;
  double binsize;
  double *C, *B;
  double rbound;
  
  mwSize nbins, nT;
  int i, nextEl, j, count;
  
  /* check number of arguments: expects 3 inputs, 1 or 2 outputs */
  if (nINP != 3)
    mexErrMsgTxt("Call with t1,  binsize and nbins  as inputs.");
  if (nOUT != 1 && nOUT != 2)
    mexErrMsgTxt("Requires one or two outputs.");

  /* check validity of inputs */
  if (mxGetM(pINP[0]) != 1 && mxGetN(pINP[0]) != 1)
    mexErrMsgTxt("t1 must be a row or column vector");
  if (mxGetM(pINP[1]) * mxGetN(pINP[1]) != 1)
    mexErrMsgTxt("binsize must be scalar");
  if (mxGetM(pINP[2]) * mxGetN(pINP[2]) != 1)
    mexErrMsgTxt("nbins must be scalar");
  if (!mxIsDouble(pINP[0]))
	  mexErrMsgTxt("T input is not a double!");
  
  /* unpack inputs */
  nT = mxGetM(pINP[0]) * mxGetN(pINP[0]);
  t1 = mxGetPr(pINP[0]);
  if (!t1)  mexErrMsgTxt("Memory allocation error t1");  // ADR 2014-11-25
  binsize = mxGetScalar(pINP[1]);
  nbins = (int)mxGetScalar(pINP[2]);
  
  pOUT[0] = mxCreateDoubleMatrix(nbins, 1, mxREAL); // inits all C to 0
  C = mxGetPr(pOUT[0]);
  if (!C)  mexErrMsgTxt("Memory allocation error C");  // ADR 2014-11-25
  if(nOUT == 2)
  {
      double m;
      
      pOUT[1] = mxCreateDoubleMatrix(nbins, 1, mxREAL);
      B =  mxGetPr(pOUT[1]);
      if (!B)  mexErrMsgTxt("Memory allocation error B");  // ADR 2014-11-25
      m = binsize/2.0;
      for(j = 0; j < nbins; j++)	B[j] = m + j * binsize;

  }
  
  /* cross correlations */
    
  for(i = 0; i < nT; i++)
  {
      nextEl = i+1;
      rbound = t1[i];
        
      for(j = 0; j < nbins; j++)
	  {
		  count = 0; // nothing in this bin yet
		  rbound += binsize;  // rbound of this bin
		  while((t1[nextEl] < rbound) && (nextEl < (nT-1)))
              {nextEl++; count++;}
		  C[j] += count;
	  }
  }
  
  for(j = 0; j < nbins; j++)  C[j] /= nT * binsize;
  
      
}
Пример #16
0
void homogToInds(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  /* [rs,cs,is]=homogToInds(H,m,n,r0,r1,c0,c1,flag); */
  int m, n, flag; double *H, r0, r1, c0, c1;
  int *is, m1, n1, ind=0, i, j, fr, fc; double *rs, *cs, r, c, m2, n2, z;

  /* extract inputs */
  H  = (double*) mxGetData(prhs[0]);
  m  = (int) mxGetScalar(prhs[1]);
  n  = (int) mxGetScalar(prhs[2]);
  r0 = mxGetScalar(prhs[3]);
  r1 = mxGetScalar(prhs[4]);
  c0 = mxGetScalar(prhs[5]);
  c1 = mxGetScalar(prhs[6]);
  flag = (int) mxGetScalar(prhs[7]);

  /* initialize memory */
  m1  = (int) (r1-r0+1); m2 = (m+1.0)/2.0;
  n1  = (int) (c1-c0+1); n2 = (n+1.0)/2.0;
  rs  = mxMalloc(sizeof(double)*m1*n1);
  cs  = mxMalloc(sizeof(double)*m1*n1);
  is  = mxMalloc(sizeof(int)*m1*n1);

  /* Compute rs an cs */
  if( H[2]==0 && H[5]==0 ) {
    for( i=0; i<n1; i++ ) {
      r = H[0]*r0 + H[3]*(c0+i) + H[6] + m2;
      c = H[1]*r0 + H[4]*(c0+i) + H[7] + n2;
      for(j=0; j<m1; j++) {
        rs[ind]=r; cs[ind]=c;
        r+=H[0]; c+=H[1]; ind++;
      }
    }
  } else {
    for( i=0; i<n1; i++ ) {
      r = H[0]*r0 + H[3]*(c0+i) + H[6];
      c = H[1]*r0 + H[4]*(c0+i) + H[7];
      z = H[2]*r0 + H[5]*(c0+i) + 1;
      for(j=0; j<m1; j++) {
        rs[ind]=r/z+m2; cs[ind]=c/z+n2;
        r+=H[0]; c+=H[1]; z+=H[2]; ind++;
      }
    }
  }

  /* clamp and compute ids according to flag */
  if( flag==1 ) { /* nearest neighbor */
    for(i=0; i<n1*m1; i++) {
      r = rs[i]<1 ? 1 : (rs[i]>m ? m : rs[i]);
      c = cs[i]<1 ? 1 : (cs[i]>n ? n : cs[i]);
      is[i] = ((int) (r-.5)) + ((int) (c-.5)) * m;
    }
  } else if(flag==2) { /* bilinear */
    for(i=0; i<n1*m1; i++) {
      r = rs[i]<2 ? 2 : (rs[i]>m-1 ? m-1 : rs[i]);
      c = cs[i]<2 ? 2 : (cs[i]>n-1 ? n-1 : cs[i]);
      fr = (int) r; fc = (int) c;
      rs[i]=r-fr; cs[i]=c-fc; is[i]=(fr-1)+(fc-1)*m;
    }
  } else { /* other cases - clamp only */
    for(i=0; i<n1*m1; i++) {
      rs[i] = rs[i]<2 ? 2 : (rs[i]>m-1 ? m-1 : rs[i]);
      cs[i] = cs[i]<2 ? 2 : (cs[i]>n-1 ? n-1 : cs[i]);
    }
  }

  /* create output array */
  plhs[0] = mxCreateNumericMatrix(0,0,mxDOUBLE_CLASS,mxREAL);
  plhs[1] = mxCreateNumericMatrix(0,0,mxDOUBLE_CLASS,mxREAL);
  plhs[2] = mxCreateNumericMatrix(0,0,mxINT32_CLASS,mxREAL);
  mxSetData(plhs[0],rs); mxSetM(plhs[0],m1); mxSetN(plhs[0],n1);
  mxSetData(plhs[1],cs); mxSetM(plhs[1],m1); mxSetN(plhs[1],n1);
  mxSetData(plhs[2],is); mxSetM(plhs[2],m1); mxSetN(plhs[2],n1);
}
Пример #17
0
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{

  /* Check for proper number of input and output arguments */
  if (nrhs < 5 || nrhs > 6)
    mexErrMsgTxt("5 or 6 input arguments required.");
  
  /* Check data type of input argument */
  for (int i = 0; i < nrhs; i++)
    {
      if (!mxIsDouble(prhs[i]))
	{
	  std::ostringstream s;
	  s << "Input " << i + 1 << " must be of type double.";
	  mexErrMsgTxt(s.str().c_str());
	}
      if (mxIsComplex(prhs[i]))
	{
	  std::ostringstream s;
	  s << "Input " << i + 1 << " may not be complex.";
	  mexErrMsgTxt(s.str().c_str());
	}
      if (mxGetNumberOfDimensions(prhs[i]) > 2)
	{
	  std::ostringstream s;
	  s << "Input " << i + 1 << " may not have more than 2 dimensions.";
	  mexErrMsgTxt(s.str().c_str());
	}
    }

  for (int i = 2; i < 5; i++)
    if (mxGetM(prhs[i]) != 1 || mxGetN(prhs[i]) != 1)
      {
	std::ostringstream s;
	s << "Input " << i + 1 << " must be scalar.";
	mexErrMsgTxt(s.str().c_str());
      }

  
  mwSize ai = mxGetM(prhs[0]);
  mwSize aj = mxGetN(prhs[0]);
  mwSize bi = mxGetM(prhs[1]);
  mwSize bj = mxGetN(prhs[1]);

  if (ai <= 0 || aj <= 0)
    mexErrMsgTxt("First argument may not be empty.");
  if (bi <= 0 || bj <= 0)
    mexErrMsgTxt("Second argument may not be empty.");
  if (ai != aj)
    mexErrMsgTxt("Coefficient matrix must be square.");    
  if (ai != bi)
    mexErrMsgTxt("Argument sizes incompatible.");
  if (bj > 1)
    mexErrMsgTxt("Right-hand side vector may only have one column.");

  if (nrhs > 5)
    {
      mwSize xi = mxGetM(prhs[5]);
      mwSize xj = mxGetN(prhs[5]);

      if (ai != xi)
	mexErrMsgTxt("Argument sizes incompatible.");
      if (xj > 1)
	mexErrMsgTxt("Initialization vector may only have one column.");
    }
  
  if (!mxIsSparse(prhs[0]))
    mexErrMsgTxt("Coefficient matrix must be sparse.");    
  if (mxIsSparse(prhs[1]))
    mexErrMsgTxt("Right hand size may not be sparse.");    
  

  double*  APr = mxGetPr(prhs[0]);
  mwIndex* AJc = mxGetJc(prhs[0]);
  mwIndex* AIr = mxGetIr(prhs[0]);
  double*  bPr = mxGetPr(prhs[1]);

  double w      = mxGetScalar(prhs[2]);
  int    niters = (int) mxGetScalar(prhs[3]);
  double tol    = mxGetScalar(prhs[4]);


  // -----------------------------------------------------------------
  // Construct output
  // -----------------------------------------------------------------
  
  plhs[0] = mxCreateDoubleMatrix(bi, 1, mxREAL);
  double* xPr  = mxGetPr(plhs[0]);

  if (nrhs > 5)
    memcpy(xPr, mxGetPr(prhs[5]), bi * sizeof(double));
  
  // -----------------------------------------------------------------
  // Perform SOR 
  // -----------------------------------------------------------------

  for (int n = 0; n < niters; n++)
    {
      if ((n % 5) == 0)
	{
	  // Terminate if residual treshold reached
	  double res = residual(prhs[0], plhs[0], prhs[1]);
	  if (res < tol)
	    {
	      if (nlhs > 1)
		plhs[1] = mxCreateLogicalScalar(true);
	      if (nlhs > 2)
		plhs[2] = mxCreateDoubleScalar(res);
	      if (nlhs > 3)
		plhs[3] = mxCreateDoubleScalar(n);
	      return;
	    }
	}
      
      double* A = APr;
      
      // Iterate over all the columns of A
      for (mwSize col = 0; col < ai; col++)
	{
	  mwIndex row_start = AJc[col];
	  mwIndex nrows = AJc[col+1] - row_start;
	  mwIndex* row = AIr + row_start;
	  
	  double sigma = 0.0;	    
	  double diag  = 0.0;

	  // Iterate over all non-zero row indices
	  for (mwSize row_idx = nrows; row_idx > 0; row_idx--)
	    {
	      double  tmp = *A;
	      mwIndex r = *row;

	      if (r == col)
		diag = tmp;
	      else
		sigma += tmp * xPr[r];

	      A++;	
	      row++;
	    }
	  
	  sigma = (bPr[col] - sigma) / diag;
	  xPr[col] += w * (sigma - xPr[col]);
	}
    }
  
  if (nlhs > 1)
    plhs[1] = mxCreateLogicalScalar(false);
  if (nlhs > 2)
    plhs[2] = mxCreateDoubleScalar(residual(prhs[0], plhs[0], prhs[1]));
  if (nlhs > 3)
    plhs[3] = mxCreateDoubleScalar(niters);
}
Пример #18
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *Prhs[])
{
register int i;
register double *pdbl;
mxArray **prhs=(mxArray **)&Prhs[0], *At, *Ct;
struct mexdata mdata;
int len, status;
double *p, *p0, *ret, *x;
int m, n, havejac, Arows, Crows, itmax, nopts, mintype, nextra;
double opts[LM_OPTS_SZ]={LM_INIT_MU, LM_STOP_THRESH, LM_STOP_THRESH, LM_STOP_THRESH, LM_DIFF_DELTA};
double info[LM_INFO_SZ];
double *lb=NULL, *ub=NULL, *A=NULL, *b=NULL, *wghts=NULL, *C=NULL, *d=NULL, *covar=NULL;

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

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

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

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

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

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

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

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

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

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

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

    mxFree(minhowto);

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

  if(mintype==MIN_UNCONSTRAINED) goto extraargs;

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

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

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

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

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

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

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

        ++prhs;
        --nrhs;
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  if(status==LM_ERROR)
    mexWarnMsgTxt("levmar: optimization returned with an error!");
}
Пример #19
0
unsigned int sf_test_autoinheritance_info( int nlhs, mxArray * plhs[], int nrhs,
  const mxArray * prhs[] )
{

#ifdef MATLAB_MEX_FILE

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

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

  {
    unsigned int chartFileNumber;
    chartFileNumber = (unsigned int)mxGetScalar(prhs[1]);
    switch (chartFileNumber) {
     case 1:
      {
        if (strcmp(aiChksum, "iXoCUCWCdn5v10UYXcgv7C") == 0) {
          extern mxArray *sf_c1_test_get_autoinheritance_info(void);
          plhs[0] = sf_c1_test_get_autoinheritance_info();
          break;
        }

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

     case 2:
      {
        if (strcmp(aiChksum, "0KcEh7HNN3ZxPFcKkBpYp") == 0) {
          extern mxArray *sf_c2_test_get_autoinheritance_info(void);
          plhs[0] = sf_c2_test_get_autoinheritance_info();
          break;
        }

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

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

  return 1;

#else

  return 0;

#endif

}
Пример #20
0
/* The gateway routine */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
/* ----------------- Variables ----------------- */
/* input variables */
/* mandatory input */
  int startIdx;
  int endIdx;
  double * inReal;
/* optional input */
  int	 optInTimePeriod;
  int	 optInFastKPeriod;
  int	 optInFastDPeriod;
  double	 optInFastDMA;
/* output variables */ 
  int outBegIdx;
  int outNbElement;
  double*	 outFastK;
  double*	 outFastD;
/* input dimentions */ 
  int inSeriesRows;
  int inSeriesCols;
/* error handling */
  TA_RetCode retCode;

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

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

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

	retCode = TA_STOCHRSI(
                   startIdx, endIdx,
                   inReal,
                   optInTimePeriod,
                   optInFastKPeriod,
                   optInFastDPeriod,
                   optInFastDMA,
                   &outBegIdx, &outNbElement,
                   outFastK,                   outFastD);
/* -------------- Errors ---------------- */
   if (retCode) {
   	   mxFree(outFastK);
   	   mxFree(outFastD);
       mexPrintf("%s%i","Return code=",retCode);
       mexErrMsgTxt(" Error!");
   }
  
   // Populate Output
  plhs[0] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL);
  memcpy(((double *) mxGetData(plhs[0]))+outBegIdx, outFastK, outNbElement*mxGetElementSize(plhs[0]));
  mxFree(outFastK);  
  plhs[1] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL);
  memcpy(((double *) mxGetData(plhs[1]))+outBegIdx, outFastD, outNbElement*mxGetElementSize(plhs[1]));
  mxFree(outFastD);  
} /* END mexFunction */
Пример #21
0
void mexFunction( int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray *prhs[] )
/*        left hand side              right hand side
/* function [z,kz] = mandelbrot_step(z,kz,z0,d);
 * Take one step of the Mandelbrot iteration.
 * Complex arithmetic:
 *    z = z.^2 + z0
 *    kz(abs(z) < 2) == d
 * Real arithmetic:
 *    x <-> real(z);
 *    y <-> imag(z);
 *    u <-> real(z0);
 *    v <-> imag(z0);
 *    [x,y] = [x.^2-y.^2+u, 2*x.*y+v];
 *    kz(x.^2+y.^2 < 4) = d;
 */
     
{ 
    double *x,*y,*u,*v,t; 
    unsigned short *kz, *num, d;
    int j ,n, m;
    int dim[] = {1, 1};
    
    x = mxGetPr(prhs[0]); 
    y = mxGetPi(prhs[0]);
    kz = (unsigned short *) mxGetData(prhs[1]); 
    u = mxGetPr(prhs[2]); 
    v = mxGetPi(prhs[2]);
    d = (unsigned short) mxGetScalar(prhs[3]);
    plhs[0] = prhs[0];
    plhs[1] = prhs[1];
    plhs[2] = mxCreateNumericArray(2,dim,mxUINT32_CLASS,mxREAL);
    num = mxGetData(plhs[2]);
    *num = 0;
    
    n = mxGetN(prhs[0]);

	m = mxGetM(prhs[0]);

    if(1){
    for (j=n*m; j--; ) {
        if (kz[j] == d-1) {
            t = x[j];
            x[j] = x[j]*x[j] - y[j]*y[j] + u[j];
            y[j] = (t+t)*y[j] + v[j];
            if (x[j]*x[j] + y[j]*y[j] < 4) {
                kz[j] = d;
            } else {
                *num = *num+1;
            }
        }
    }
    } else {
        for (j=0; j<n*m; j++) {
        if (kz[j] == d-1) {
            t = x[j];
            x[j] = x[j]*x[j] - y[j]*y[j] + u[j];
            y[j] = 2*t*y[j] + v[j];
            if (x[j]*x[j] + y[j]*y[j] < 4) {
                kz[j] = d;
            }
        }
    }
    }
    
    return;
}
Пример #22
0
void mexFunction
(
    int nargout,
    mxArray *pargout [ ],
    int nargin,
    const mxArray *pargin [ ]
)
{
    Int *P, *Q, *Rp, *Pinv ;
    double *Ax, dummy, tol ;
    Int m, n, anz, is_complex, n1rows, n1cols, i, k ;
    cholmod_sparse *A, Amatrix, *Y ;
    cholmod_common Common, *cc ;

    // -------------------------------------------------------------------------
    // start CHOLMOD and set parameters
    // -------------------------------------------------------------------------

    cc = &Common ;
    cholmod_l_start (cc) ;
    spqr_mx_config (SPUMONI, cc) ;

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

    if (nargout > 5)
    {
        mexErrMsgIdAndTxt ("MATLAB:maxlhs", "Too many output arguments") ;
    }
    if (nargin < 1)
    {
        mexErrMsgIdAndTxt ("MATLAB:minrhs", "Not enough input arguments") ;
    }
    if (nargin > 2)
    {
        mexErrMsgIdAndTxt ("MATLAB:maxrhs", "Too many input arguments") ;
    }

    // -------------------------------------------------------------------------
    // get the input matrix A and convert to merged-complex if needed
    // -------------------------------------------------------------------------

    if (!mxIsSparse (pargin [0]))
    {
        mexErrMsgIdAndTxt ("QR:invalidInput", "A must be sparse") ;
    }

    A = spqr_mx_get_sparse (pargin [0], &Amatrix, &dummy) ;
    m = A->nrow ;
    n = A->ncol ;
    is_complex = mxIsComplex (pargin [0]) ;
    Ax = spqr_mx_merge_if_complex (pargin [0], is_complex, &anz, cc) ; 
    if (is_complex)
    {
        // A has been converted from real or zomplex to complex
        A->x = Ax ;
        A->z = NULL ;
        A->xtype = CHOLMOD_COMPLEX ;
    }

    // -------------------------------------------------------------------------
    // get the tolerance
    // -------------------------------------------------------------------------

    if (nargin < 2)
    {
        tol = is_complex ? spqr_tol <Complex> (A,cc) : spqr_tol <double> (A,cc);
    }
    else
    {
        tol = mxGetScalar (pargin [1]) ;
    }

    // -------------------------------------------------------------------------
    // find the singletons
    // -------------------------------------------------------------------------

    if (is_complex)
    {
        spqr_1colamd <Complex> (SPQR_ORDERING_NATURAL, tol, 0, A,
            &Q, &Rp, &Pinv, &Y, &n1cols, &n1rows, cc) ;
    }
    else
    {
        spqr_1colamd <double> (SPQR_ORDERING_NATURAL, tol, 0, A,
            &Q, &Rp, &Pinv, &Y, &n1cols, &n1rows, cc) ;
    }

    // -------------------------------------------------------------------------
    // free unused outputs from spqr_1colamd, and the merged-complex copy of A
    // -------------------------------------------------------------------------

    cholmod_l_free (n1rows+1, sizeof (Int), Rp, cc) ;
    cholmod_l_free_sparse (&Y, cc) ;
    if (is_complex)
    {
        // this was allocated by merge_if_complex
        cholmod_l_free (anz, sizeof (Complex), Ax, cc) ;
    }

    // -------------------------------------------------------------------------
    // find P from Pinv
    // -------------------------------------------------------------------------

    P = (Int *) cholmod_l_malloc (m, sizeof (Int), cc) ;
    for (i = 0 ; i < m ; i++)
    {
        k = Pinv ? Pinv [i] : i ;
        P [k] = i ;
    }
    cholmod_l_free (m, sizeof (Int), Pinv, cc) ;

    // -------------------------------------------------------------------------
    // return results
    // -------------------------------------------------------------------------

    pargout [0] = spqr_mx_put_permutation (P, m, TRUE, cc) ;
    cholmod_l_free (m, sizeof (Int), P, cc) ;
    if (nargout > 1) pargout [1] = spqr_mx_put_permutation (Q, n, TRUE, cc) ;
    cholmod_l_free (n, sizeof (Int), Q, cc) ;
    if (nargout > 2) pargout [2] = mxCreateDoubleScalar ((double) n1rows) ;
    if (nargout > 3) pargout [3] = mxCreateDoubleScalar ((double) n1cols) ;
    if (nargout > 4) pargout [4] = mxCreateDoubleScalar (tol) ;

    cholmod_l_finish (cc) ;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	/****************************************************************************/
/* Input arguments                                                          */
/****************************************************************************/
#define IN_spike_matrix     prhs[0]	//ST1
#define IN_spike_vector     prhs[1]	//ST2
#define IN_Time_Length		prhs[2]	//T
#define IN_Max_Num_Spikes	prhs[3]	//MaxSpike                       //Don't need this??!!!

/****************************************************************************/
/* Output arguments                                                         */
/****************************************************************************/
#define OUT					plhs[0]

	
	//int M, N, m, n;

	/* Since this is a custome C code, I will not checks for data type, assume user knows the valid type */

	double TimeLength, MaxSpike;
	int i,j, M, N, Total_ROW, Num_rows_single_spike;
	int col, row, left_i, right_i;
	double *output, *spike_matrix, *spike_vector;
	double *Sorted_SpikeTimings, *spiketime_label;  
    double sum, squaredCount;

	TimeLength = mxGetScalar(IN_Time_Length);
	MaxSpike = mxGetScalar(IN_Max_Num_Spikes);
	
	spike_matrix = mxGetPr(IN_spike_matrix);
	spike_vector = mxGetPr(IN_spike_vector);
	
	M = mxGetM(IN_spike_matrix);
	N = mxGetN(IN_spike_matrix);
	Num_rows_single_spike = mxGetM(IN_spike_vector);

	Total_ROW = M + Num_rows_single_spike;

	OUT = mxCreateDoubleMatrix(1, N, mxREAL); /* Create the output matrix */
	output = mxGetPr(OUT);
	//=================================SORTING=================================Merge=================================
	
    //Sorted_SpikeTimings = (double**) malloc(Total_ROW * sizeof(double*));
    //for (i = 0; i < Total_ROW; i++)  
    //Sorted_SpikeTimings[i] = (double*) malloc(N * sizeof(double));
    Sorted_SpikeTimings = (double*) malloc(Total_ROW * sizeof(double));
    

	// Can be cut down to 1D array
    spiketime_label = (double*) malloc(Total_ROW * sizeof(double)); 

	for(col = 0; col < N; col++)
	{
		left_i = 0; right_i = 0; row = 0;

        if(spike_matrix[col*M+left_i] == -1 && spike_vector[right_i] == -1)
            output[col] = 0.0;
        else{
			while(left_i < M || right_i < Num_rows_single_spike){
                //Check for empty spike trains
				if(spike_matrix[col*M+left_i] == -1)
					left_i = M;
                if(spike_vector[right_i] == -1)
					right_i = Num_rows_single_spike;

				if (left_i < M && right_i < Num_rows_single_spike){
					if(spike_matrix[col*M+left_i] <= spike_vector[right_i]){
						Sorted_SpikeTimings[row] = spike_matrix[col*M+left_i];
						spiketime_label[row] = 1;
						left_i++;
						row++;
					}
					else{
						Sorted_SpikeTimings[row] = spike_vector[right_i];
						spiketime_label[row] = -1;
						right_i++;
						row++;
					}
				}

				else if (left_i < M){
                    while(left_i < M && spike_matrix[col*M+left_i] != -1){
						Sorted_SpikeTimings[row] = spike_matrix[col*M+left_i];
						spiketime_label[row] = 1;                        
                        left_i++;
						row++;
                    }
                    break;
				}
				
				else if (right_i < Num_rows_single_spike){
                    while(right_i < Num_rows_single_spike && spike_vector[right_i] != -1){
						Sorted_SpikeTimings[row] = spike_vector[right_i];
						spiketime_label[row] = -1;                        
                        right_i++;
						row++;
                    }
                    break;
				}
			}
            
            //what happens when ROW is < 2 (i.e., = 1)?
            sum = 0.0; squaredCount = spiketime_label[0];
            for(i = 0; i<row-1; i++)
            {
                sum += (Sorted_SpikeTimings[i+1]-Sorted_SpikeTimings[i])*squaredCount*squaredCount;
                squaredCount += spiketime_label[i+1];
            }
            sum += (TimeLength-Sorted_SpikeTimings[row-1])*squaredCount*squaredCount;
            //mexPrintf("Value We Need: %f\n\n",sum);         
            output[col] = sum;
        }
	}
    
    //for (i = 0; i < Total_ROW; i++)      
    //    free(Sorted_SpikeTimings[i]);
    free(Sorted_SpikeTimings);
    
    free(spiketime_label);
    return;
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
          float          *pOutputImage32f;
          unsigned short *pInputRowMap16u,  *pInputColMap16u;
          unsigned short *pTopLeftOrg, *pBotRightMarg, *pKernelSize;
          unsigned char  *pInputRefImage8u, *pInputTargetImage8u;
          
          unsigned short nPropRow16u, nPropCol16u;  // Indices of propagation
          
          int nErrorAccum, nElementSqrDiff;
          
          mxArray *pMxArray[1];
          
          int i, j, iRoi, jRoi;
          int m, n, mTarget, nTarget;
          int mOutput, nOutput;
          int nSingleChannelColNum,  nSingleChannelColNumTarget;// Number of columns in single channel
          int nNumOfChannelElements, nNumOfChannelElementsTarget;
          int nNumOfROIElements;
          int nFirstRow, nLastRow; // Matlab indices
          int nFirstCol, nLastCol; // Matlab indices
          int nCurIterStep, nCurIterOffset, nCurIterStepTarget, nCurIterOffsetTarget;
          int nRoiOffset, nRoiOffsetTarget;
          int pChannelStep[2], pChannelStepTarget[2];
          
          if (nrhs < 7 || nrhs > 8 || nlhs!=1)
                    mexErrMsgTxt("Usage: outputImage=GetANNError_C3(inputRefImage8u_C3, inputTargetImage8u_C3, rowMapping16u, colMapping16u, TLboundary16u, BRboundary16u, nWidth16u, debugFlag(opt));\n");
          
          if (mxGetClassID(prhs[0]) != mxUINT8_CLASS || mxGetClassID(prhs[1]) != mxUINT8_CLASS ||
                  mxGetClassID(prhs[2]) != mxUINT16_CLASS || mxGetClassID(prhs[3]) != mxUINT16_CLASS ||
                  mxGetClassID(prhs[4]) != mxUINT16_CLASS|| mxGetClassID(prhs[5]) != mxUINT16_CLASS ||
                  mxGetClassID(prhs[6]) != mxUINT16_CLASS)
                    mexErrMsgTxt("input and target images must be uint8 matrices, row and column mapping images must be a uint16 matrices, top-left and bottom-right of ROI must be a uint16 scalars and kernel size must be a uint16 scalar!");
          
          if (nrhs == 8) {
                    debugEnable = (int)mxGetScalar(prhs[7]);
          }
          else
                    debugEnable = 0;
          
          // Get inputs
          pInputRefImage8u    = (unsigned char*)mxGetPr(prhs[0]);
          pInputTargetImage8u = (unsigned char*)mxGetPr(prhs[1]);
          pInputRowMap16u     = (unsigned short*)mxGetPr(prhs[2]);
          pInputColMap16u     = (unsigned short*)mxGetPr(prhs[3]);
          pTopLeftOrg         = (unsigned short*)mxGetPr(prhs[4]);
          pBotRightMarg       = (unsigned short*)mxGetPr(prhs[5]);
          pKernelSize         = (unsigned short*)mxGetPr(prhs[6]);
          
          
          // Get sizes of variables (Opposite on purpose)//
          m = mxGetM(prhs[0]); // Width
          n = mxGetN(prhs[0]); // Height
          nSingleChannelColNum = n/3;
          
          mTarget = mxGetM(prhs[1]); // Width target
          nTarget = mxGetN(prhs[1]); // Height target
          nSingleChannelColNumTarget = nTarget/3;
          
          nNumOfChannelElements       = nSingleChannelColNum * m;
          nNumOfChannelElementsTarget = nSingleChannelColNumTarget * mTarget;
          
          // Calc steps
          pChannelStep[0]       = nNumOfChannelElements;       pChannelStep[1]       = 2*nNumOfChannelElements;
          pChannelStepTarget[0] = nNumOfChannelElementsTarget; pChannelStepTarget[1] = 2*nNumOfChannelElementsTarget;
          
          // Create output matrix
          mOutput = m-(*pBotRightMarg)-(*pTopLeftOrg);
          nOutput = nSingleChannelColNum-(*pBotRightMarg)-(*pTopLeftOrg);
          mOutput = m;
          nOutput = nSingleChannelColNum;
          plhs[0] = mxCreateNumericMatrix(mOutput, nOutput, mxSINGLE_CLASS, false);
          pOutputImage32f = (float*)mxGetPr(plhs[0]);
          
          // Initialize filter parameters
          nFirstRow = (int)(*pTopLeftOrg);
          nLastRow  = (int)m-(*pBotRightMarg);
          nFirstCol = (int)(*pTopLeftOrg);
          nLastCol  = (int)nSingleChannelColNum-(*pBotRightMarg);
          
          nNumOfROIElements = (*pKernelSize)*(*pKernelSize)*3;
          
          for (j=nFirstCol; j<nLastCol; j++) {
                    nCurIterStep       = j*m;
                    nCurIterStepTarget = j*mTarget;
                    
                    for (i=nFirstRow; i<nLastRow; i++) {
                              nCurIterOffset = nCurIterStep+i;
                              nPropCol16u = pInputColMap16u[nCurIterOffset];
                              nPropRow16u = pInputRowMap16u[nCurIterOffset];
                              
                              nCurIterOffsetTarget = (int)((nPropRow16u-1) + (nPropCol16u-1)*mTarget); // Translating matlab to C
                              
                              nErrorAccum = 0;
                              for (jRoi = 0; jRoi<(*pKernelSize); jRoi++) {
                                        nRoiOffset       = nCurIterOffset + jRoi*m;
                                        nRoiOffsetTarget = nCurIterOffsetTarget + jRoi*mTarget;
                                        for (iRoi = 0; iRoi<(*pKernelSize); iRoi++) {
                                                  nElementSqrDiff = (int)pInputRefImage8u[nRoiOffset] - (int)pInputTargetImage8u[nRoiOffsetTarget];
                                                  nErrorAccum += nElementSqrDiff*nElementSqrDiff;
                                                  nElementSqrDiff = (int)pInputRefImage8u[nRoiOffset+pChannelStep[0]] - (int)pInputTargetImage8u[nRoiOffsetTarget+pChannelStepTarget[0]];
                                                  nErrorAccum += nElementSqrDiff*nElementSqrDiff;
                                                          
                                                  nElementSqrDiff = (int)pInputRefImage8u[nRoiOffset+pChannelStep[1]] - (int)pInputTargetImage8u[nRoiOffsetTarget+pChannelStepTarget[1]];
                                                  nErrorAccum += nElementSqrDiff*nElementSqrDiff;
                                                  nRoiOffset++;
                                                  nRoiOffsetTarget++;
                                        }
                              }
                              
                              pOutputImage32f[nCurIterOffset] = sqrt(nErrorAccum );// / (float)nNumOfROIElements;
                    }
          }
          
}
/* Function: mdlInitializeSampleTimes =========================================
 * Abstract:
 *    This function is used to specify the sample time(s) for your
 *    S-function. You must register the same number of sample times as
 *    specified in ssSetNumSampleTimes.
 */
static void mdlInitializeSampleTimes(SimStruct *S)
{
    ssSetSampleTime(S, 0, mxGetScalar(ssGetSFcnParam(S, 0)));	// tiempo de muestreo?
    ssSetOffsetTime(S, 0, 0.0);
}
Пример #26
0
void mexFunction(int nlhs, mxArray *plhs[ ],int nrhs, const mxArray *prhs[ ]) 
{
    double *vol,*img;
    double *n,*n_z,*n_x,*n_y;
    double mask_r;
    double img_c_x,img_c_y;
    double vol_c_x,vol_c_y,vol_c_z;
    double img_r,z_lim;
    double z;
    double v_x,v_y,v_z;
    int i_v_x,i_v_y,i_v_z;
    int i1,j1,k1;
    double wt;
    double a_v_x,a_v_y,a_v_z;
    int v_size;
    int i,j;
    mwSignedIndex dims[3];
    
    
    /**********************************************/
       /*Retrieve the input data */
       /* The volume */
       img=mxGetPr(prhs[0]);
       v_size=mxGetM(prhs[0]);
       /* The coordinate system */
       n=mxGetPr(prhs[1]);
       n_x=n;
       n_y=n+3;
       n_z=n+6;
       /* The radius */
       mask_r=mxGetScalar(prhs[2]);
       
   /************************************************/
       
       /* Create the output volume */
       dims[0] = v_size;
       dims[1] = v_size;
       dims[2]= v_size;
       plhs[0] = mxCreateNumericArray(3, dims, mxDOUBLE_CLASS, mxREAL);
       vol=mxGetPr(plhs[0]);
       for (i=0;i<v_size*v_size*v_size;i++) *(vol+i)=0;
        
   /*************************************************/
        /* Create constants */
        img_c_x=v_size/2-0.0;
        img_c_y=v_size/2-0.0;
        
        vol_c_x=v_size/2-0.0;
        vol_c_y=v_size/2-0.0;
        vol_c_z=v_size/2-0.5;
        
    /**************************************************/
        /* Back_project onto the image */
        for (i=0;i<v_size;i++)
            for (j=0;j<v_size;j++)
        {
            /* Calculate the radius in the image */
            img_r=sqrt((i-img_c_x)*(i-img_c_x)+(j-img_c_y)*(j-img_c_y));
            /* If the radius is less than mask_r */
            if (img_r < mask_r)
            { /* Radius is small, get the z limits */
                z_lim=sqrt(mask_r*mask_r-img_r*img_r);
         
                
                for (z=-z_lim;z<=z_lim;z++)
                {
                    /* Calculate an index into the volume */
                    /* Double indices */
               /*   v_x=((i-img_c_x)+vol_c_x);
                    v_y=((j-img_c_y)+vol_c_y);
                    v_z=(z+vol_c_z);
                */
                    v_x=(i-img_c_x)*(*n_x)+(j-img_c_y)*(*n_y)+z*(*n_z)+vol_c_x;
                    v_y=(i-img_c_x)*(*(n_x+1))+(j-img_c_y)*(*(n_y+1))+z*(*(n_z+1))+vol_c_y;
                    v_z=(i-img_c_x)*(*(n_x+2))+(j-img_c_y)*(*(n_y+2))+z*(*(n_z+2))+vol_c_z;
                    
                    /*Integer indices and fractional offsets */
                    i_v_x=(int)floor(v_x);
                    i_v_y=(int)floor(v_y);
                    i_v_z=(int)floor(v_z);
                    
                    a_v_x=v_x-(double)i_v_x;
                    a_v_y=v_y-(double)i_v_y;
                    a_v_z=v_z-(double)i_v_z;

                    /* Multi-linear interpolation */
                    for (i1=0;i1<=1;i1++)
                        for (j1=0;j1<=1;j1++)
                            for (k1=0;k1<=1;k1++) 
                            {
                                wt=((1-a_v_x)*(1-i1)+a_v_x*i1)
                                     *((1-a_v_y)*(1-j1)+a_v_y*j1)
                                     *((1-a_v_z)*(1-k1)+a_v_z*k1);
                        *(vol+(i_v_x+i1)+(i_v_y+j1)*v_size+(i_v_z+k1)*v_size*v_size) += 
                              (*(img+i+j*v_size))*wt;
                            } /* End k1 loop */
                    
                } /* End z loop */
         
                
            } /* End img_r < mask_r condition */
        } /* End j loop */
        
}
/* entry point */
void mexFunction(int nlhs, mxArray *plhs[], 
                 int nrhs, const mxArray *prhs[])                
{
    int ind, i, x, y, o, dataDim, j, bytes_to_copy, nGaborFilter;
    const mxArray *f;
    const mxArray *pAS1Map;
    mxArray *outPA;
    mwSize ndim;
    const mwSize* dims;
    mwSize dimsOutput[2];
    void* start_of_pr;
    mxClassID datatype;

	/*
	 * input variable 0: nGaborOri
	 */
	nGaborOri = (int)mxGetScalar(prhs[0]);
 
    /*
	 * input variable 1: S1 maps
	 */
    pAS1Map = prhs[1];
    dims = mxGetDimensions(pAS1Map);
    nGaborFilter = dims[0] * dims[1];
    nGaborScale = nGaborFilter / nGaborOri;
 
    S1Map = (const float**)mxCalloc( nGaborFilter, sizeof(*S1Map) );   /* SUM1 maps */
    for (i=0; i<nGaborFilter; ++i)
    {
        f = mxGetCell(pAS1Map, i);
        datatype = mxGetClassID(f);
        if (datatype != mxSINGLE_CLASS)
            mexErrMsgTxt("warning !! single precision required.");
        S1Map[i] = (const float*)mxGetPr(f);    /* get the pointer to cell content */
        height = mxGetM(f);    /* overwriting is ok, since it is constant */
        width = mxGetN(f);
    }
    
    /*
     * input variable 2: location shift radius
     */
    locationPerturb = (int)mxGetScalar(prhs[2]);
    
    /*
     * input variable 3: orientation shift radius
     */
    orientationPerturb = (int)mxGetScalar(prhs[3]);
    
    /*
     * input variable 4: sub sample step length
     */
    subsample = (int)mxGetScalar(prhs[4]);

    StoreShift();
    Compute();
    
    /* =============================================
     * Handle output variables.
     * ============================================= 
     */
    
    /*
     * output variable 0: M1 map
     */
    dimsOutput[0] = 1; dimsOutput[1] = nGaborScale * nGaborOri;
	plhs[0] = mxCreateCellArray( 2, dimsOutput );
    dimsOutput[0] = sizexSubsample; dimsOutput[1] = sizeySubsample;
    for( i = 0; i < nGaborOri * nGaborScale; ++i )
    {
        outPA = mxCreateNumericArray( 2, dimsOutput, mxSINGLE_CLASS, mxREAL );
        /* populate the real part of the created array */
        start_of_pr = (float*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, M1Map[i], bytes_to_copy );
        mxSetCell( plhs[0], i, outPA );
    }
    
    /*
     * output variable 1: M1 trace
     */
    dimsOutput[0] = 1; dimsOutput[1] = nGaborScale * nGaborOri;
	plhs[1] = mxCreateCellArray( 2, dimsOutput );
    dimsOutput[0] = sizexSubsample; dimsOutput[1] = sizeySubsample;
    for( i = 0; i < nGaborOri * nGaborScale; ++i )
    {
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        /* populate the real part of the created array */
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, M1Trace[i], bytes_to_copy );
        mxSetCell( plhs[1], i, outPA );
    }
    
    /*
     * output variable 2: stored Gabor shifts : row shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[2] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, rowShift[i], bytes_to_copy );
        mxSetCell( plhs[2], i, outPA );
    }
    
    /*
     * output variable 3: stored Gabor shifts : col shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[3] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, colShift[i], bytes_to_copy );
        mxSetCell( plhs[3], i, outPA );
    }
    
    /*
     * output variable 4: stored Gabor shifts : orientation shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[4] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, orientShift[i], bytes_to_copy );
        mxSetCell( plhs[4], i, outPA );
    }
}
Пример #28
0
void mexFunction(int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[]) {
  char            command[STRLEN];
  char            matlabcmd[STRLEN];
  char            cmd[STRLEN];
  char           *ptr;
  int             poolsize, retval, block, num, i, status;
  #ifndef USE_PTHREADS
          HANDLE TName;
  InitializeCriticalSection(&enginemutex);
  #endif
          
          initFun();
  mexAtExit(exitFun);
  
  /* the first argument is always the command string */
  if (nrhs < 1)
    mexErrMsgTxt("invalid number of input arguments");
  
  if (!mxIsChar(prhs[0]))
    mexErrMsgTxt("invalid input argument #1");
  if (mxGetString(prhs[0], command, STRLEN - 1))
    mexErrMsgTxt("invalid input argument #1");
  
  /* convert to lower case */
  ptr = command;
  while (*ptr) {
    *ptr = tolower(*ptr);
    ptr++;
  }
  
  /****************************************************************************/
  if (strcmp(command, "open") == 0) {
    /* engine open num cmd */
    
    if (nrhs < 2)
      mexErrMsgTxt("Invalid number of input arguments");
    
    if (nrhs > 1) {
      if (!mxIsNumeric(prhs[1]))
        mexErrMsgTxt("Invalid input argument #2, should be numeric");
      poolsize = mxGetScalar(prhs[1]);
    }
    if (nrhs > 2) {
      if (!mxIsChar(prhs[2]))
        mexErrMsgTxt("Invalid input argument #3, should be a string");
      mxGetString(prhs[2], matlabcmd, STRLEN - 1);
    } else {
      sprintf(matlabcmd, "matlab");
    }
    
    if (poolsize < 1)
      mexErrMsgTxt("The number of engines in the pool should be positive");
    
    ENGINEMUTEX_LOCK;
    engine = engOpenSingleUse(NULL, NULL, &retval);	/* returns NULL on failure */
    ENGINEMUTEX_UNLOCK;
    
    if (!engine) {
      exitFun();	/* this cleans up all engines */
      mexErrMsgTxt("failed to open MATLAB engine");
    }
  }
  /****************************************************************************/
  else if (strcmp(command, "close") == 0) {
    /* engine close */
    
    exitFun();
    
    retval = 0;
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    mxGetPr(plhs[0])[0] = retval;
    
  }
  /****************************************************************************/
  else if (strcmp(command, "put") == 0) {
    /* engine put num name val */
    
    if (nrhs != 4)
      mexErrMsgTxt("Exactly four input arguments needed");
    
    if (!mxIsNumeric(prhs[1]))
      mexErrMsgTxt("Argument #2 should be numeric");
    num = mxGetScalar(prhs[1]);
    
    if (num < 1 || num > poolsize)
      mexErrMsgTxt("Invalid engine number");
    
    if (!mxIsChar(prhs[2]))
      mexErrMsgTxt("Argument #3 should be a string");
    
    ENGINEMUTEX_LOCK;
    
    retval = engPutVariable(engine, mxArrayToString(prhs[2]), prhs[3]);
    
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    mxGetPr(plhs[0])[0] = retval;
    
    ENGINEMUTEX_UNLOCK;
  }
  /****************************************************************************/
  else if (strcmp(command, "get") == 0) {
    /* engine get num name */
    
    if (nrhs != 3)
      mexErrMsgTxt("Exactly three input arguments needed");
    
    if (!mxIsNumeric(prhs[1]))
      mexErrMsgTxt("Argument #2 should be numeric");
    
    if (!mxIsChar(prhs[2]))
      mexErrMsgTxt("Argument #3 should be a string");
    
    num = mxGetScalar(prhs[1]);
    
    ENGINEMUTEX_LOCK;
    
    plhs[0] = engGetVariable(engine, mxArrayToString(prhs[2]));
    
    ENGINEMUTEX_UNLOCK;
    
  }
  /****************************************************************************/
  else if (strcmp(command, "isbusy") == 0) {
    /* engine isbusy num */
    
    if (nrhs != 2)
      mexErrMsgTxt("Exactly two input arguments needed");
    
    if (!mxIsNumeric(prhs[1]))
      mexErrMsgTxt("Argument #2 should be numeric");
    num = mxGetScalar(prhs[1]);
    
    ENGINEMUTEX_LOCK;
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    mxGetPr(plhs[0])[0] = 1;
    ENGINEMUTEX_UNLOCK;
  }
  /****************************************************************************/
  else if (strcmp(command, "eval") == 0) {
    /* engine eval num str block */
    
    if (nrhs < 3)
      mexErrMsgTxt("At least three input arguments needed");
    
    if (!mxIsNumeric(prhs[1]))
      mexErrMsgTxt("Argument #2 should be numeric");
    num = mxGetScalar(prhs[1]);
    
    if (!mxIsChar(prhs[2]))
      mexErrMsgTxt("Invalid input argument #3, should be a string");
    mxGetString(prhs[2], cmd, STRLEN - 1);
    
    if (nrhs > 3) {
      if (!mxIsNumeric(prhs[3]))
        mexErrMsgTxt("Invalid input argument #4, should be numeric");
      block = mxGetScalar(prhs[3]);
    } else {
      block = 0;
    }
    
    ENGINEMUTEX_LOCK;
    
    if (!block) {
      
#ifdef USE_PTHREADS
      retval = pthread_create(&(enginepool[num - 1].tid), NULL, (void *) &evalString, (void *) (enginepool + num - 1));
#else
      TName = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) evalString, (void *) (cmd), 0, NULL);
#endif

    } else {
      retval = engEvalString(engine, cmd);
    }
    mexPrintf("Finished executing command, retval = %d\n", retval);
    ENGINEMUTEX_UNLOCK;
    
    WaitForSingleObject(TName, INFINITE);
    
    /* wait for the thread to become busy */
    mexPrintf("Waiting for engine to become busy\n");
    BUSYCOND_WAIT;
    mexPrintf("The engine has become busy\n");
    
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    mxGetPr(plhs[0])[0] = retval;
  }
  /****************************************************************************/
  else if (strcmp(command, "poolsize") == 0) {
    /* engine poolsize */
    
    ENGINEMUTEX_LOCK;
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    mxGetPr(plhs[0])[0] = (engine!=0);
    ENGINEMUTEX_UNLOCK;
  }
  /****************************************************************************/
  else if (strcmp(command, "info") == 0) {
    /* engine info */
    
    ENGINEMUTEX_LOCK;
    mexPrintf("engine = %d\n",   engine);
    ENGINEMUTEX_UNLOCK;
  }
  /****************************************************************************/
  else {
    mexErrMsgTxt("unknown command");
    return;
  }
  
  return;
}
Пример #29
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
		int i;

    if(nrhs!=1){
			mexPrintf("\nwriteFileNifti(niftiStruct)\n\n");
			mexPrintf("Writes a NIFTI image based on fields of a structure that resembles\n");
			mexPrintf("the NIFTI 1 standard (see http://nifti.nimh.nih.gov/nifti-1/ ).\n");
 		  mexPrintf("See readFileNifti for details about the expected niftiStruct.\n\n");
			return;
    }else if(nlhs>0) { mexPrintf("Too many output arguments"); return; }

    /* The first arg must be a nifti struct. */
		if(!mxIsStruct(prhs[0])) mexErrMsgTxt("First arg must be a nifti struct.");
    const mxArray *mxnim = prhs[0];
		// Sanity check that this is a complete NIFTI struct
		if(mxGetField(mxnim,0,"fname")==NULL || mxGetField(mxnim,0,"data")==NULL)
			myErrMsg("First argument must be a proper NIFTI struct (see readFileNifti).\n\n");

    /* Create an empty NIFTI C struct */
		nifti_image *nim = (nifti_image *)mxCalloc(1, sizeof(nifti_image));
		if(!nim) myErrMsg("failed to allocate nifti image");

		nim->nifti_type = 1; // We only support single-file NIFTI format

		/* Load the C-struct with fields from the matlab struct */
		mxArray *fname =  mxGetField(mxnim,0,"fname");
		mxArray *data = mxGetField(mxnim,0,"data");
    // fname field needs to be allocated
    int buflen = (mxGetN(fname)) + 1;
    nim->fname = (char *)mxCalloc(buflen, sizeof(char));
    if(mxGetString(fname, nim->fname, buflen))
      mexWarnMsgTxt("Not enough space- fname string is truncated.");
		nim->iname = NULL;
		nim->data = mxGetData(data); 
		nim->ndim = mxGetNumberOfDimensions(data);
		nim->dim[0] = nim->ndim;
		const int *dims = mxGetDimensions(data);
		for(i=0; i<nim->ndim; i++) nim->dim[i+1] = dims[i];
		for(i=nim->ndim+1; i<8; i++) nim->dim[i] = 1;
		// Why do I have to assign these explicitly? 
		nim->nx = nim->dim[1];
		nim->ny = nim->dim[2];
		nim->nz = nim->dim[3];
		nim->nt = nim->dim[4];
		nim->nu = nim->dim[5];
		nim->nv = nim->dim[6];
		nim->nw = nim->dim[7];
		//for(i=0; i<8; i++) mexPrintf("%d ",nim->dim[i]); mexPrintf("\n\n");

		nim->nvox = mxGetNumberOfElements(data);
		// *** TO DO: we should support DT_RGB24 type (triplet of uint8)
		if(mxIsComplex(data)){
			switch(mxGetClassID(data)){
			case mxSINGLE_CLASS: nim->datatype=DT_COMPLEX64; nim->nbyper=8; break;
			case mxDOUBLE_CLASS: nim->datatype=DT_COMPLEX128; nim->nbyper=16; break;
			default: myErrMsg("Unknown data type!");
			}
		}else{
			switch(mxGetClassID(data)){
			case mxUINT8_CLASS: nim->datatype=DT_UINT8; nim->nbyper=1; break;
			case mxINT8_CLASS: nim->datatype=DT_INT8; nim->nbyper=1; break;
			case mxUINT16_CLASS: nim->datatype=DT_UINT16; nim->nbyper=2; break;
			case mxINT16_CLASS: nim->datatype=DT_INT16; nim->nbyper=2; break;
			case mxUINT32_CLASS: nim->datatype=DT_UINT32; nim->nbyper=4; break;
			case mxINT32_CLASS: nim->datatype=DT_INT32; nim->nbyper=4; break;
			case mxUINT64_CLASS: nim->datatype=DT_UINT64; nim->nbyper=8; break;
			case mxINT64_CLASS: nim->datatype=DT_INT64; nim->nbyper=8; break;
			case mxSINGLE_CLASS: nim->datatype=DT_FLOAT32; nim->nbyper=4; break;
			case mxDOUBLE_CLASS: nim->datatype=DT_FLOAT64; nim->nbyper=8; break;
			default: mexErrMsgTxt("Unknown data type!");
			}
		}

		double *pdPtr = (double *)mxGetData(mxGetField(mxnim,0,"pixdim"));
		int nPixDim = mxGetM(mxGetField(mxnim,0,"pixdim"))*mxGetN(mxGetField(mxnim,0,"pixdim"));
		if(nPixDim>8) nPixDim=8;
		for(i=0; i<nPixDim; i++) nim->pixdim[i+1] = (float)pdPtr[i];
		// xxx dla fixed bug below (i was not being assigned).
		//  for(nPixDim+1; i<8; i++) nim->pixdim[i] = (float)1.0;
		for(i = nPixDim+1; i<8; i++) nim->pixdim[i] = (float)1.0;
		nim->dx = nim->pixdim[1]; 
		nim->dy = nim->pixdim[2];
		nim->dz = nim->pixdim[3];
		nim->dt = nim->pixdim[4];
		nim->du = nim->pixdim[5];
		nim->dv = nim->pixdim[6];
		nim->dw = nim->pixdim[7];

		nim->scl_slope = mxGetScalar(mxGetField(mxnim,0,"scl_slope"));
		nim->scl_inter = mxGetScalar(mxGetField(mxnim,0,"scl_inter"));
		nim->cal_min = mxGetScalar(mxGetField(mxnim,0,"cal_min"));
		nim->cal_max = mxGetScalar(mxGetField(mxnim,0,"cal_max"));
		nim->qform_code = (int)mxGetScalar(mxGetField(mxnim,0,"qform_code"));
		nim->sform_code = (int)mxGetScalar(mxGetField(mxnim,0,"sform_code"));
		nim->freq_dim = (int)mxGetScalar(mxGetField(mxnim,0,"freq_dim"));
		nim->phase_dim = (int)mxGetScalar(mxGetField(mxnim,0,"phase_dim"));
		nim->slice_dim = (int)mxGetScalar(mxGetField(mxnim,0,"slice_dim"));
		nim->slice_code = (int)mxGetScalar(mxGetField(mxnim,0,"slice_code"));
		nim->slice_start = (int)mxGetScalar(mxGetField(mxnim,0,"slice_start"));
		nim->slice_end = (int)mxGetScalar(mxGetField(mxnim,0,"slice_end"));
		nim->slice_duration = mxGetScalar(mxGetField(mxnim,0,"slice_duration"));
    /* if qform_code > 0, the quatern_*, qoffset_*, and qfac fields determine
     * the qform output, NOT the qto_xyz matrix; if you want to compute these
     * fields from the qto_xyz matrix, you can use the utility function
     * nifti_mat44_to_quatern() */
		nim->quatern_b = mxGetScalar(mxGetField(mxnim,0,"quatern_b"));
		nim->quatern_c = mxGetScalar(mxGetField(mxnim,0,"quatern_c"));
		nim->quatern_d = mxGetScalar(mxGetField(mxnim,0,"quatern_d"));
		nim->qoffset_x = mxGetScalar(mxGetField(mxnim,0,"qoffset_x"));
		nim->qoffset_y = mxGetScalar(mxGetField(mxnim,0,"qoffset_y"));
		nim->qoffset_z = mxGetScalar(mxGetField(mxnim,0,"qoffset_z"));
		nim->qfac = mxGetScalar(mxGetField(mxnim,0,"qfac"));
		nim->pixdim[0] = nim->qfac; // pixdim[0] is the same as qfac (again- why duplicate the field?)

		double *sxPtr = (double *)mxGetData(mxGetField(mxnim,0,"sto_xyz"));
		for(i=0; i<16; i++) nim->sto_xyz.m[i%4][i/4] = (float)sxPtr[i];

		nim->toffset = mxGetScalar(mxGetField(mxnim,0,"toffset"));
		// Allow units to be specified as a string
		char str[16]; 
		mxGetString(mxGetField(mxnim,0,"xyz_units"),str,16);
		nim->xyz_units = getNiftiUnitCode(str);
		mxGetString(mxGetField(mxnim,0,"time_units"),str,16);
		nim->time_units = getNiftiUnitCode(str);
		nim->intent_code = (int)mxGetScalar(mxGetField(mxnim,0,"intent_code"));
		nim->intent_p1 = mxGetScalar(mxGetField(mxnim,0,"intent_p1"));
		nim->intent_p2 = mxGetScalar(mxGetField(mxnim,0,"intent_p2"));
		nim->intent_p3 = mxGetScalar(mxGetField(mxnim,0,"intent_p3"));
		mxGetString(mxGetField(mxnim,0,"intent_name"), nim->intent_name, 16);
		mxGetString(mxGetField(mxnim,0,"descrip"), nim->descrip, 80);
		mxGetString(mxGetField(mxnim,0,"aux_file"), nim->aux_file, 24);
		// *** TO DO: support extended header fileds!
		nim->num_ext = 0;

		/* I assume that we can rely on the nifti routine to byte-swap for us? */
		nifti_image_write(nim);
}
Пример #30
0
void 
LTFAT_NAME(ltfatMexFnc)( int nlhs, mxArray *plhs[],
                      int nrhs, const mxArray *prhs[] )
{
  // Register exit function only once
    static int atExitFncRegistered = 0;
    if(!atExitFncRegistered)
    {
        LTFAT_NAME(ltfatMexAtExit)(LTFAT_NAME(dctMexAtExitFnc));
        atExitFncRegistered = 1;
    }

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

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

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

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

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



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



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


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


  return;
}