示例#1
0
void IHCAN(double *px, double cf, int nrep, double tdres, int totalstim,
                double cohc, double cihc, double *ihcout)
{	
    
    /*variables for middle-ear model */
	double megainmax=43;
    double *mey1, *mey2, *mey3, meout,c1filterouttmp,c2filterouttmp,c1vihctmp,c2vihctmp;
    double fp,C,m11,m12,m21,m22,m23,m24,m25,m26,m31,m32,m33,m34,m35,m36;
	
	/*variables for the signal-path, control-path and onward */
	double *ihcouttmp,*tmpgain;
	int    grd;

    double bmplace,centerfreq,gain,taubm,ratiowb,bmTaubm,fcohc,TauWBMax,TauWBMin,tauwb;
    double Taumin[1],Taumax[1],bmTaumin[1],bmTaumax[1],ratiobm[1],lasttmpgain,wbgain,ohcasym,ihcasym,delay;
	int    i,n,delaypoint,grdelay[1],bmorder,wborder;
	double wbout1,wbout,ohcnonlinout,ohcout,tmptauc1,tauc1,rsigma,wb_gain;
            
    /* Declarations of the functions used in the program */
	double C1ChirpFilt(double, double,double, int, double, double);
	double C2ChirpFilt(double, double,double, int, double, double);
    double WbGammaTone(double, double, double, int, double, double, int);

    double Get_tauwb(double, int, double *, double *);
	double Get_taubm(double, double, double *, double *, double *);
    double gain_groupdelay(double, double, double, double, int *);
    double delay_cat(double cf);

    double OhcLowPass(double, double, double, int, double, int);
    double IhcLowPass(double, double, double, int, double, int);
	double Boltzman(double, double, double, double, double);
    double NLafterohc(double, double, double, double);
	double ControlSignal(double, double, double, double, double);

    double NLogarithm(double, double, double, double);
    
    /* Allocate dynamic memory for the temporary variables */
	ihcouttmp  = (double*)mxCalloc(totalstim*nrep,sizeof(double));
	    
	mey1 = (double*)mxCalloc(totalstim,sizeof(double));
	mey2 = (double*)mxCalloc(totalstim,sizeof(double));
	mey3 = (double*)mxCalloc(totalstim,sizeof(double));

	tmpgain = (double*)mxCalloc(totalstim,sizeof(double));
    
	/** Calculate the location on basilar membrane from CF */	
    
	bmplace = 11.9 * log10(0.80 + cf / 456.0); 
    
	/** Calculate the center frequency for the control-path wideband filter
	    from the location on basilar membrane */
	
	centerfreq = 456.0*(pow(10,(bmplace+1.2)/11.9)-0.80); /* shift the center freq */
    
	/*==================================================================*/
	/*====== Parameters for the gain ===========*/
	gain = 52/2*(tanh(2.2*log10(cf/0.6e3)+0.15)+1);
    /*gain = 52/2*(tanh(2.2*log10(cf/1e3)+0.15)+1);*/
    if(gain>60) gain = 60;  
    if(gain<15) gain = 15;
	/*====== Parameters for the control-path wideband filter =======*/
	bmorder = 3;
	Get_tauwb(cf,bmorder,Taumax,Taumin);
	taubm   = cohc*(Taumax[0]-Taumin[0])+Taumin[0];
	ratiowb = Taumin[0]/Taumax[0];
	/*====== Parameters for the signal-path C1 filter ======*/
	Get_taubm(cf,Taumax[0],bmTaumax,bmTaumin,ratiobm);
	bmTaubm  = cohc*(bmTaumax[0]-bmTaumin[0])+bmTaumin[0];
	fcohc    = bmTaumax[0]/bmTaubm;
    /*====== Parameters for the control-path wideband filter =======*/
	wborder  = 3;
    TauWBMax = Taumin[0]+0.2*(Taumax[0]-Taumin[0]);
	TauWBMin = TauWBMax/Taumax[0]*Taumin[0];
    tauwb    = TauWBMax+(bmTaubm-bmTaumax[0])*(TauWBMax-TauWBMin)/(bmTaumax[0]-bmTaumin[0]);
	
	wbgain = gain_groupdelay(tdres,centerfreq,cf,tauwb,grdelay);
	tmpgain[0]   = wbgain; 
	lasttmpgain  = wbgain;
  	/*===============================================================*/
    /* Nonlinear asymmetry of OHC function and IHC C1 transduction function*/
	ohcasym  = 7.0;    
	ihcasym  = 3.0;
  	/*===============================================================*/
    /*===============================================================*/
    /* Prewarping and related constants for the middle ear */
     fp = 1e3;  /* prewarping frequency 1 kHz */
     C  = TWOPI*fp/tan(TWOPI/2*fp*tdres);
	 m11 = C/(C + 693.48);                    m12 = (693.48 - C)/C;
	 m21 = 1/(pow(C,2) + 11053*C + 1.163e8);  m22 = -2*pow(C,2) + 2.326e8;    m23 = pow(C,2) - 11053*C + 1.163e8; 
	 m24 = pow(C,2) + 1356.3*C + 7.4417e8;    m25 = -2*pow(C,2) + 14.8834e8;  m26 = pow(C,2) - 1356.3*C + 7.4417e8;
	 m31 = 1/(pow(C,2) + 4620*C + 909059944); m32 = -2*pow(C,2) + 2*909059944; m33 = pow(C,2) - 4620*C + 909059944;
	 m34 = 5.7585e5*C + 7.1665e7;             m35 = 14.333e7;                 m36 = 7.1665e7 - 5.7585e5*C;
	 
  	for (n=0;n<totalstim;n++) /* Start of the loop */
    {    
        if (n==0)  /* Start of the middle-ear filtering section  */
		{
	    	mey1[0]  = m11*px[0];
            mey2[0]  = mey1[0]*m24*m21;
            mey3[0]  = mey2[0]*m34*m31;
            meout = mey3[0]/megainmax ;
        }
            
        else if (n==1)
		{
            mey1[1]  = m11*(-m12*mey1[0] + px[1]       - px[0]);
			mey2[1]  = m21*(-m22*mey2[0] + m24*mey1[1] + m25*mey1[0]);
            mey3[1]  = m31*(-m32*mey3[0] + m34*mey2[1] + m35*mey2[0]);
            meout = mey3[1]/megainmax;
		}
	    else 
		{
            mey1[n]  = m11*(-m12*mey1[n-1]  + px[n]         - px[n-1]);
            mey2[n]  = m21*(-m22*mey2[n-1] - m23*mey2[n-2] + m24*mey1[n] + m25*mey1[n-1] + m26*mey1[n-2]);
            mey3[n]  = m31*(-m32*mey3[n-1] - m33*mey3[n-2] + m34*mey2[n] + m35*mey2[n-1] + m36*mey2[n-2]);
            meout = mey3[n]/megainmax;
		}; 	/* End of the middle-ear filtering section */   
     
		/* Control-path filter */

        wbout1 = WbGammaTone(meout,tdres,centerfreq,n,tauwb,wbgain,wborder);
        wbout  = pow((tauwb/TauWBMax),wborder)*wbout1*10e3*__max(1,cf/5e3);
  
        ohcnonlinout = Boltzman(wbout,ohcasym,12.0,5.0,5.0); /* pass the control signal through OHC Nonlinear Function */
		ohcout = OhcLowPass(ohcnonlinout,tdres,600,n,1.0,2);/* lowpass filtering after the OHC nonlinearity */
        
		tmptauc1 = NLafterohc(ohcout,bmTaumin[0],bmTaumax[0],ohcasym); /* nonlinear function after OHC low-pass filter */
		tauc1    = cohc*(tmptauc1-bmTaumin[0])+bmTaumin[0];  /* time -constant for the signal-path C1 filter */
		rsigma   = 1/tauc1-1/bmTaumax[0]; /* shift of the location of poles of the C1 filter from the initial positions */

		if (1/tauc1<0.0) mexErrMsgTxt("The poles are in the right-half plane; system is unstable.\n");

		tauwb = TauWBMax+(tauc1-bmTaumax[0])*(TauWBMax-TauWBMin)/(bmTaumax[0]-bmTaumin[0]);

	    wb_gain = gain_groupdelay(tdres,centerfreq,cf,tauwb,grdelay);
		
		grd = grdelay[0]; 

        if ((grd+n)<totalstim)
	         tmpgain[grd+n] = wb_gain;

        if (tmpgain[n] == 0)
			tmpgain[n] = lasttmpgain;	
		
		wbgain      = tmpgain[n];
		lasttmpgain = wbgain;
	 		        
        /*====== Signal-path C1 filter ======*/
         
		 c1filterouttmp = C1ChirpFilt(meout, tdres, cf, n, bmTaumax[0], rsigma); /* C1 filter output */

	 
        /*====== Parallel-path C2 filter ======*/

		 c2filterouttmp  = C2ChirpFilt(meout, tdres, cf, n, bmTaumax[0], 1/ratiobm[0]); /* parallel-filter output*/

	    /*=== Run the inner hair cell (IHC) section: NL function and then lowpass filtering ===*/

        c1vihctmp  = NLogarithm(cihc*c1filterouttmp,0.1,ihcasym,cf);
	     
		c2vihctmp = -NLogarithm(c2filterouttmp*fabs(c2filterouttmp)*cf/10*cf/2e3,0.2,1.0,cf); /* C2 transduction output */

        ihcouttmp[n] = IhcLowPass(c1vihctmp+c2vihctmp,tdres,3000,n,1.0,7);
   };  /* End of the loop */
   
    /* Stretched out the IHC output according to nrep (number of repetitions) */
   
    for(i=0;i<totalstim*nrep;i++)
	{
		ihcouttmp[i] = ihcouttmp[(int) (fmod(i,totalstim))];
  	};   
   	/* Adjust total path delay to IHC output signal */
	delay      = delay_cat(cf);
	delaypoint =__max(0,(int) ceil(delay/tdres));    
         
    for(i=delaypoint;i<totalstim*nrep;i++)
	{        
		ihcout[i] = ihcouttmp[i - delaypoint];
  	};   

    /* Freeing dynamic memory allocated earlier */

    mxFree(ihcouttmp);
    mxFree(mey1); mxFree(mey2); mxFree(mey3);	
    mxFree(tmpgain);

} /* End of the SingleAN function */
示例#2
0
mxArray *sfmult_AN_XN_YT    // y = (A*x)'
(
    const mxArray *A,
    const mxArray *X,
    int ac,		// if true: conj(A)   if false: A. ignored if A real
    int xc,		// if true: conj(x)   if false: x. ignored if x real
    int yc		// if true: conj(y)   if false: y. ignored if y real
)
{
    mxArray *Y ;
    double *Ax, *Az, *Xx, *Xz, *Yx, *Yz, *Wx, *Wz ;
    Int *Ap, *Ai ;
    Int m, n, k, k1, i ;
    int Acomplex, Xcomplex, Ycomplex ;

    //--------------------------------------------------------------------------
    // get inputs
    //--------------------------------------------------------------------------

    m = mxGetM (A) ;
    n = mxGetN (A) ;
    k = mxGetN (X) ;
    if (n != mxGetM (X)) sfmult_invalid ( ) ;
    Acomplex = mxIsComplex (A) ;
    Xcomplex = mxIsComplex (X) ;
    Ap = mxGetJc (A) ;
    Ai = mxGetIr (A) ;
    Ax = mxGetPr (A) ;
    Az = mxGetPi (A) ;
    Xx = mxGetPr (X) ;
    Xz = mxGetPi (X) ;

    //--------------------------------------------------------------------------
    // allocate result
    //--------------------------------------------------------------------------

    Ycomplex = Acomplex || Xcomplex ;
    Y = sfmult_yalloc (k, m, Ycomplex) ;
    Yx = mxGetPr (Y) ;
    Yz = mxGetPi (Y) ;

    //--------------------------------------------------------------------------
    // special cases
    //--------------------------------------------------------------------------

    if (k == 0 || m == 0 || n == 0 || Ap [n] == 0)
    {
	// Y = 0
	return (sfmult_yzero (Y)) ;
    }
    if (k == 1)
    {
	// Y = A*X
	sfmult_AN_x_1 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
	return (Y) ;
    }
    if (k == 2)
    {
	// Y = (A * X)'
	sfmult_AN_XN_YT_2 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
	return (Y) ;
    }
    if (k == 4)
    {
	// Y = (A * X)'
	sfmult_AN_XN_YT_4 (Yx, Yz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
	return (Y) ;
    }

    //--------------------------------------------------------------------------
    // allocate workspace
    //--------------------------------------------------------------------------

    sfmult_walloc (4, m, &Wx, &Wz) ;

    //--------------------------------------------------------------------------
    // Y = (A*X)', in blocks of up to 4 columns of X, using sfmult_anxnyt
    //--------------------------------------------------------------------------

    k1 = k % 4 ;
    if (k1 == 1)
    {
	// W = A * X(:,1)
	sfmult_AN_x_1 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
	// Y (1,:) = W
	for (i = 0 ; i < m ; i++)
	{
	    Yx [k*i] = Wx [i] ;
	}
	Yx += 1 ;
	Yz += 1 ;
	Xx += n ;
	Xz += n ;
    }
    else if (k1 == 2)
    {
	// W = (A * X(:,1:2))'
	sfmult_AN_XN_YT_2 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
	// Y (1:2,:) = W
	for (i = 0 ; i < m ; i++)
	{
	    Yx [k*i  ] = Wx [2*i  ] ;
	    Yx [k*i+1] = Wx [2*i+1] ;
	}
	Yx += 2 ;
	Yz += 2 ;
	Xx += 2*n ;
	Xz += 2*n ;
    }
    else if (k1 == 3)
    {
	// W = (A * X(:,1:3))'
	sfmult_AN_XN_YT_3 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
	// Y (1:3,:) = W
	for (i = 0 ; i < m ; i++)
	{
	    Yx [k*i  ] = Wx [4*i  ] ;
	    Yx [k*i+1] = Wx [4*i+1] ;
	    Yx [k*i+2] = Wx [4*i+2] ;
	}
	Yx += 3 ;
	Yz += 3 ;
	Xx += 3*n ;
	Xz += 3*n ;
    }
    for ( ; k1 < k ; k1 += 4)
    {
	// W = (A*X(:,1:4))'
	sfmult_AN_XN_YT_4 (Wx, Wz, Ap, Ai, Ax, Az, m, n, Xx, Xz, ac, xc, yc) ;
	// Y (k1+(1:4),:) = W
	for (i = 0 ; i < m ; i++)
	{
	    Yx [k*i  ] = Wx [4*i  ] ;
	    Yx [k*i+1] = Wx [4*i+1] ;
	    Yx [k*i+2] = Wx [4*i+2] ;
	    Yx [k*i+3] = Wx [4*i+3] ;
	}
	Yx += 4 ;
	Yz += 4 ;
	Xx += 4*n ;
	Xz += 4*n ;
    }

    //--------------------------------------------------------------------------
    // free workspace and return result
    //--------------------------------------------------------------------------

    mxFree (Wx) ;
    return (Y) ;
}
示例#3
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;
/* output variables */ 
  int outBegIdx;
  int outNbElement;
  double*	 outReal;
/* input dimentions */ 
  int inSeriesRows;
  int inSeriesCols;
/* error handling */
  TA_RetCode retCode;

/* ----------------- input/output count ----------------- */  
  /*  Check for proper number of arguments. */
  if (nrhs < 1 || nrhs > 2) mexErrMsgTxt("#2 inputs possible #1 optional.");
  if (nlhs != 1) mexErrMsgTxt("#1 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;
  }

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

	retCode = TA_RSI(
                   startIdx, endIdx,
                   inReal,
                   optInTimePeriod,
                   &outBegIdx, &outNbElement,
                   outReal);
/* -------------- Errors ---------------- */
   if (retCode) {
   	   mxFree(outReal);
       mexPrintf("%s%i","Return code=",retCode);
       mexErrMsgTxt(" Error!");
   }
  
   // Populate Output
  plhs[0] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL);
  memcpy(((double *) mxGetData(plhs[0]))+outBegIdx, outReal, outNbElement*mxGetElementSize(plhs[0]));
  mxFree(outReal);  
} /* END mexFunction */
/*  the gateway routine.  */
void mexFunction( int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[] )
{
    
    /* create a pointer to the real data in the input matrix  */
    int nfields = mxGetNumberOfFields(prhs[0]); // number of fields in each constraint
    mwSize NStructElems = mxGetNumberOfElements(prhs[0]); // number of constraints
    const char **fnames = (const char **)mxCalloc(nfields, sizeof(*fnames)); /* pointers to field names */
    double *sw = mxGetPr(prhs[1]); /* switch vector */ 
    double *xs = mxGetPr(prhs[2]); /* linearisation point */
    long unsigned int nrow = mxGetM(prhs[2]);
    double *ptr = mxGetPr(prhs[3]); /* number of cameras */
    int ncams = ptr[0];
    
    /* initialise a PwgOptimiser object */
    PwgOptimiser *Object; // pointer initialisation
    Object = new PwgOptimiser (ncams, nrow-6*ncams) ; // pointer initialisation
    
    /* get constraints from Matlab to C++ and initialise a constraint */
    double *pr;
    mxArray *tmp;
    int cam, kpt;
    std::vector<double> p1(2), z(2), R(4,0.0);//, Y(49,0.0), y(7,0.0);
    std::string str1 ("cam");
    std::string str2 ("kpt");
    std::string str3 ("p1");
    std::string str4 ("z");
    std::string str5 ("R");
    std::string str6 ("y");
    std::string str7 ("Y");
    Eigen::MatrixXd yz = Eigen::MatrixXd::Zero(7,1);
    Eigen::VectorXd Yz = Eigen::MatrixXd::Zero(7,7);
    for (mwIndex jstruct = 0; jstruct < NStructElems; jstruct++) { /* loop the constraints */
        for (int ifield = 0; ifield < nfields; ifield++) {  /* loop the fields */
            fnames[ifield] = mxGetFieldNameByNumber(prhs[0],ifield); // get field name
            tmp = mxGetFieldByNumber(prhs[0], jstruct, ifield); // get field
            pr = (double *)mxGetData(tmp); // get the field data pointer
            if (str1.compare(fnames[ifield]) == 0) // cam
                cam = pr[0];
            if (str2.compare(fnames[ifield]) == 0) // kpt
                kpt = pr[0];
            if (str3.compare(fnames[ifield]) == 0){ // p1
                p1[0] = pr[0]; p1[1] = pr[1];}
            if (str4.compare(fnames[ifield]) == 0){ // z
                z[0] = pr[0]; z[1] = pr[1];}
            if (str5.compare(fnames[ifield]) == 0){ // R
                R[0] = pr[0]; R[3] = pr[3];}
        } // end of nfields loop
        Object->initialise_a_constraint(cam, kpt, p1, z, R, Yz, yz, (int)sw[jstruct]) ; // using pointer to object
    } // end of NStructElems loop
    
    // optimise constraints information
    Object->optimise_constraints_image_inverse_depth_Mviews( xs ) ;
            
    /* get output state vector */
    int ncol = (Object->xhat).size();
    plhs[0] = mxCreateDoubleMatrix(ncol, 1, mxREAL);
    double *vec_out = mxGetPr(plhs[0]);
    for (int i=0; i<ncol; i++)
        vec_out[i] = (Object->xhat).coeffRef(i);
    
    /* get output sparse covariance matrix */
    ncol = (Object->Phat).outerSize();
    long unsigned int nzmax = (Object->Phat).nonZeros();
    plhs[1] = mxCreateSparse(ncol, ncol, nzmax, mxREAL);
    double *mat_out = mxGetPr(plhs[1]);
    long unsigned int *ir2 = mxGetIr(plhs[1]);
    long unsigned int *jc2 = mxGetJc(plhs[1]);
    int index=0;
    for (int k=0; k < (Object->Phat).outerSize(); ++k)
    {
        jc2[k] = index;
        for (Eigen::SparseMatrix<double>::InnerIterator it(Object->Phat,k); it; ++it)
        {
            ir2[index] = it.row();
            mat_out[index] = it.value();
            index++;
        }
    }
    jc2[(Object->Phat).outerSize()] = index;
    
    /* Free memory */
    mxFree((void *)fnames);
    delete Object; // delete class pointer
    //mxFree(tmp);
}
示例#5
0
/**
 * @brief Interfaces C and Matlab data.
 * This function is the MEX-file gateway routine. Please see the Matlab
 * MEX-file documentation (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f43721.html)
 * for more information.
 */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{

  /* allocate variables */
  struct input *X;
  struct options_direct *opts;
  int m,p,n,z;
  int p_total,P_total;
  int W;
  int *P_vec;
  mxArray *mxbinned;
  int **binned,*binned_temp;
  int cur_P;
  int status;
  int temp_N;

  /* check number of inputs (nargin) and outputs (nargout) */
  if((nrhs<1) | (nrhs>2))
    mexErrMsgIdAndTxt("STAToolkit:directbin:numArgs","1 or 2 input arguments required.");
  if((nlhs<1) | (nlhs>2))
    mexErrMsgIdAndTxt("STAToolkit:directbin:numArgs","1 or 2 output arguments required.");

  X = ReadInput(prhs[0]);

  /* get or set options */
  if(nrhs<2)
    opts = ReadOptionsDirect(mxCreateEmptyStruct());
  else if(mxIsEmpty(prhs[1]))
    opts = ReadOptionsDirect(mxCreateEmptyStruct());
  else
    opts = ReadOptionsDirect(prhs[1]);

  /* Read in time range */
  ReadOptionsDirectTimeRange(opts,X);
  
  /* check options */
  if(opts->Delta_flag==0)
    {
      opts[0].Delta = (*opts).t_end-(*opts).t_start;
      opts[0].Delta_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter counting_bin_size. Using default value end_time-start_time=%f.\n",opts[0].Delta);
    }
  
  if(opts->Delta <= 0)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","counting_bin_size must be positive. It is currently set to %f.\n",opts[0].Delta);
    }

  if(opts->words_per_train_flag==0)
    {
      opts[0].words_per_train = (int)DEFAULT_WORDS_PER_TRAIN;
      opts[0].words_per_train_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter words_per_train. Using default value %d.\n",opts[0].words_per_train);
    }

  if(opts->words_per_train <= 0)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","words_per_train must be positive. It is currently set to %d.\n",opts[0].words_per_train);
    }

 if(opts->legacy_binning_flag==0)
    {
      opts[0].legacy_binning = (int)DEFAULT_LEGACY_BINNING;
      opts[0].legacy_binning_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter legacy_binning. Using default value %d.\n",opts[0].legacy_binning);
    }

  if((opts->legacy_binning!=0) & (opts->legacy_binning!=1))
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option legacy_binning set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",opts[0].legacy_binning);
    }

 if(opts->letter_cap_flag==0)
    {
      opts[0].letter_cap = (int)DEFAULT_LETTER_CAP;
      opts[0].letter_cap_flag=1;
      mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter letter_cap. Using default value %d.\n",opts[0].letter_cap);
    }

  if(opts->letter_cap<0)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option letter_cap set to an invalid value. Must be a positive integer or Inf. It is currently set to %d.\n",opts[0].letter_cap);
    }

  if((*X).N>1)
    {
      if(opts->sum_spike_trains_flag==0)
	{
	  opts[0].sum_spike_trains = (int)DEFAULT_SUM_SPIKE_TRAINS;
	  opts[0].sum_spike_trains_flag=1;
	  mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter sum_spike_trains. Using default value %d.\n",opts[0].sum_spike_trains);
	}

      if((opts->sum_spike_trains!=0) & (opts->sum_spike_trains!=1))
        {
          mxFree(opts);
          mxFreeInput(X); 
	  mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option sum_spike_trains set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",(*opts).sum_spike_trains);
        }
      
      if(opts->permute_spike_trains_flag==0)
	{
	  opts[0].permute_spike_trains = (int)DEFAULT_PERMUTE_SPIKE_TRAINS;
	  opts[0].permute_spike_trains_flag=1;
	  mexWarnMsgIdAndTxt("STAToolkit:directbin:missingParameter","Missing parameter permute_spike_trains. Using default value %d.\n",opts[0].permute_spike_trains);
	}

      if((opts->permute_spike_trains!=0) & (opts->permute_spike_trains!=1))
        {
          mxFree(opts);
          mxFreeInput(X); 
	  mexErrMsgIdAndTxt("STAToolkit:directbin:invalidValue","Option permute_spike_trains set to an invalid value. Must be 0 or 1. It is currently set to %d.\n",(*opts).permute_spike_trains);
        }
    }

  P_total = GetNumTrials(X);
  /* W is the number of letters in a word */
  W=GetWindowSize(opts);

  /* Allocate memory for pointers to pointers */
  if(opts[0].sum_spike_trains)
    temp_N = 1;
  else
    temp_N = X[0].N;
  binned = mxMatrixInt((*opts).words_per_train*P_total,temp_N*W);

  /* Allocate memory for P_vec */
  P_vec = (int *)mxMalloc((*X).M*sizeof(int));

  /* Do computation */
  status = DirectBinComp(X,opts,(*opts).words_per_train*P_total,W,P_vec,binned);
  if(status==EXIT_FAILURE)
    {
      mxFree(opts);
      mxFreeInput(X); 
      mxFreeMatrixInt(binned);
      mxFree(P_vec);
      mexErrMsgIdAndTxt("STAToolkit:directbin:failure","directbin failed.");
    }

  /* Create binned cell array */
  plhs[0] = mxCreateCellMatrix((*X).M,(*opts).words_per_train);
  p_total = 0;

  for(m=0;m<(*X).M;m++)
    {
      cur_P = (*X).categories[m].P;
      for(z=0;z<(*opts).words_per_train;z++)
	{
	  /* vectorize and transpose this matrix */
	  binned_temp = (int *)mxMalloc(W*temp_N*cur_P*sizeof(int));
	  
	  for(p=0;p<cur_P;p++)
	    for(n=0;n<temp_N*W;n++)
	      binned_temp[n*cur_P + p]=binned[p_total+p][n];
	  
	  p_total += cur_P;
      
	  mxbinned = mxCreateNumericMatrix(cur_P,temp_N*W,mxINT32_CLASS,mxREAL);
	  memcpy(mxGetData(mxbinned),binned_temp,cur_P*temp_N*W*sizeof(int));

	  mxSetCell(plhs[0],z*(*X).M+m,mxbinned);
	  
	  mxFree(binned_temp);
	}
    }

  /* output options used */
  if(nrhs<2)
    plhs[1] = WriteOptionsDirect(mxCreateEmptyStruct(),opts);
  else if(mxIsEmpty(prhs[1]))
    plhs[1] = WriteOptionsDirect(mxCreateEmptyStruct(),opts);
  else
    plhs[1] = WriteOptionsDirect(prhs[1],opts);

  /* free memory */
  mxFreeInput(X); 
  mxFreeMatrixInt(binned);
  mxFree(P_vec);

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

{    
     mxArray  *rhs[2]; 
     mxArray  *blk_cell_pr, *A_cell_pr;
     double   *A,  *B,  *blksize;
     int      *irA, *jcA, *irB, *jcB;
     int      *cumblksize, *blknnz;
     int      iscellA, mblk, mA, nA, m1, n1, rowidx, colidx, isspA, isspB;

     int   subs[2];
     int   nsubs=2; 
     int   n, n2, k, nsub, index, numblk, NZmax;
     double  ir2=1/sqrt(2); 

/* CHECK FOR PROPER NUMBER OF ARGUMENTS */

     if (nrhs < 2){
         mexErrMsgTxt("mexsmat: requires at least 2 input arguments."); }
     else if (nlhs>1){ 
         mexErrMsgTxt("mexsmat: requires 1 output argument."); }

/* CHECK THE DIMENSIONS */

     iscellA = mxIsCell(prhs[1]); 
     if (iscellA) { mA = mxGetM(prhs[1]); nA = mxGetN(prhs[1]); }
     else         { mA = 1; nA = 1; }
     if (mxGetM(prhs[0]) != mA) {
         mexErrMsgTxt("mexsmat: blk and Avec not compatible"); }

/***** main body *****/ 
       
     if (nrhs > 3) {rowidx = (int)*mxGetPr(prhs[3]); } else {rowidx = 1;}  
     if (rowidx > mA) {
         mexErrMsgTxt("mexsmat: rowidx exceeds size(Avec,1)."); }
     subs[0] = rowidx-1;  /* subtract 1 to adjust for Matlab index */
     subs[1] = 1;
     index = mxCalcSingleSubscript(prhs[0],nsubs,subs); 
     blk_cell_pr = mxGetCell(prhs[0],index);
     if (blk_cell_pr == NULL) { 
        mexErrMsgTxt("mexsmat: blk not properly specified"); }    
     numblk  = mxGetN(blk_cell_pr);            
     blksize = mxGetPr(blk_cell_pr);
     cumblksize = mxCalloc(numblk+1,sizeof(int)); 
     blknnz = mxCalloc(numblk+1,sizeof(int)); 
     cumblksize[0] = 0; blknnz[0] = 0; 
     n = 0;  n2 = 0; 
     for (k=0; k<numblk; ++k) {
          nsub = (int) blksize[k];
          n  += nsub; 
          n2 += nsub*(nsub+1)/2;  
          cumblksize[k+1] = n; 
          blknnz[k+1] = n2;
     }
     /***** assign pointers *****/
     if (iscellA) { 
         subs[0] = rowidx-1; 
         subs[1] = 0;
         index = mxCalcSingleSubscript(prhs[1],nsubs,subs); 
         A_cell_pr = mxGetCell(prhs[1],index); 
         A  = mxGetPr(A_cell_pr); 
         m1 = mxGetM(A_cell_pr); 
         n1 = mxGetN(A_cell_pr);
         isspA = mxIsSparse(A_cell_pr);
         if (isspA) { irA = mxGetIr(A_cell_pr);
                      jcA = mxGetJc(A_cell_pr); } 
     }
     else { 
         A  = mxGetPr(prhs[1]); 
         m1 = mxGetM(prhs[1]); 
         n1 = mxGetN(prhs[1]); 
         isspA = mxIsSparse(prhs[1]); 
         if (isspA) {  irA = mxGetIr(prhs[1]); 
                       jcA = mxGetJc(prhs[1]); }
     }
     if (numblk > 1) 
        { isspB = 1; }
     else { 
        if (nrhs > 2) {isspB = (int)*mxGetPr(prhs[2]);} else {isspB = isspA;} 
     }
     if (nrhs > 4) {colidx = (int)*mxGetPr(prhs[4]) -1;} else {colidx = 0;} 
     if (colidx > n1) { 
         mexErrMsgTxt("mexsmat: colidx exceeds size(Avec,2)."); 
     }    
     /***** create return argument *****/
     if (isspB) {
	 if (isspA) { NZmax = jcA[colidx+1]-jcA[colidx]; } 
         else       { NZmax = blknnz[numblk]; } 
	 rhs[0] = mxCreateSparse(n,n,2*NZmax,mxREAL); 
	 B = mxGetPr(rhs[0]); irB = mxGetIr(rhs[0]); jcB = mxGetJc(rhs[0]);
     }
     else {
         plhs[0] = mxCreateDoubleMatrix(n,n,mxREAL); 
         B = mxGetPr(plhs[0]); 
     }
     /***** Do the computations in a subroutine *****/
     if (numblk == 1) { 
         smat1(n,ir2,A,irA,jcA,isspA,m1,colidx,B,irB,jcB,isspB);  }
     else { 
         smat2(n,numblk,cumblksize,blknnz,ir2,A,irA,jcA,isspA,m1,colidx,B,irB,jcB,isspB);  
     }
     if (isspB) {
        /*** if isspB, (actual B) = B+B' ****/ 
        mexCallMATLAB(1, &rhs[1], 1, &rhs[0], "transpose"); 
        mexCallMATLAB(1, &plhs[0],2, rhs, "+");  
        mxDestroyArray(*rhs); 
     }
     mxFree(blknnz); 
     mxFree(cumblksize);
 return;
 }
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
   /* Variables */
    int n, s,e,e2,n1,n2,neigh,Vind,Vind2,s1,s2,
    nNodes, nEdges, maxState,
    iter,maxIter,nNbrs,
    *edgeEnds, *nStates, *V, *E,*y;
    
    double *nodePot, *edgePot, *nodeBel,
    z,*prodMsgs,*oldMsgs,*newMsgs,*tmp;
    
   /* Input */
    
    nodePot = mxGetPr(prhs[0]);
    edgePot = mxGetPr(prhs[1]);
    edgeEnds = (int*)mxGetPr(prhs[2]);
    nStates = (int*)mxGetPr(prhs[3]);
    V = (int*)mxGetPr(prhs[4]);
    E = (int*)mxGetPr(prhs[5]);
    maxIter = ((int*)mxGetPr(prhs[6]))[0];
    
	if (!mxIsClass(prhs[2],"int32")||!mxIsClass(prhs[3],"int32")||!mxIsClass(prhs[4],"int32")||!mxIsClass(prhs[5],"int32")||!mxIsClass(prhs[6],"int32"))
		mexErrMsgTxt("edgeEnds, nStates, V, E, maxIter must be int32");
	
   /* Compute Sizes */
    
    nNodes = mxGetDimensions(prhs[0])[0];
    maxState = mxGetDimensions(prhs[0])[1];
    nEdges = mxGetDimensions(prhs[2])[0];    
    
   /* Output */
    plhs[0] = mxCreateDoubleMatrix(nNodes,maxState,mxREAL);
    nodeBel = mxGetPr(plhs[0]);
        
    prodMsgs = mxCalloc(maxState*nNodes,sizeof(double));
    oldMsgs = mxCalloc(maxState*nEdges*2,sizeof(double));
    newMsgs = mxCalloc(maxState*nEdges*2,sizeof(double));
    tmp = mxCalloc(maxState,sizeof(double));
    
    /* Initialize */
    for(e = 0; e < nEdges; e++)
    {
        n1 = edgeEnds[e]-1;
        n2 = edgeEnds[e+nEdges]-1;
        for(s = 0; s < nStates[n2]; s++)
            newMsgs[s+maxState*e] = 1./nStates[n2];
        for(s = 0; s < nStates[n1]; s++)
            newMsgs[s+maxState*(e+nEdges)] = 1./nStates[n1];
    }
    
    
    for(iter = 0; iter < maxIter; iter++)
    {
        
        for(n=0;n<nNodes;n++)
        {
            
            /* Update Messages */
            for(Vind = V[n]-1; Vind < V[n+1]-1; Vind++)
            {
                e = E[Vind]-1;
                n1 = edgeEnds[e]-1;
                n2 = edgeEnds[e+nEdges]-1;
                
                /* First part of message is nodePot*/
                for(s = 0; s < nStates[n]; s++)
                    tmp[s] = nodePot[n + nNodes*s];
                
                /* Multiply by messages from neighbors except j */
                for(Vind2 = V[n]-1; Vind2 < V[n+1]-1; Vind2++)
                {
                    e2 = E[Vind2]-1;
                    if (e != e2)
                    {
                        if (n == edgeEnds[e2+nEdges]-1)
                        {
                            for(s = 0; s < nStates[n]; s++)
                            {
                                tmp[s] *= newMsgs[s+maxState*e2];
                            }
                        }
                        else
                        {
                            for(s = 0; s < nStates[n]; s++)
                            {
                                tmp[s] *= newMsgs[s+maxState*(e2+nEdges)];
                            }
                        }
                    }
                }
                
                /* Now multiply by edge potential to get new message */
                
                if (n == n2)
                {
                    for(s1 = 0; s1 < nStates[n1]; s1++)
                    {
                        newMsgs[s1+maxState*(e+nEdges)] = tmp[0]*edgePot[s1+maxState*(0+maxState*e)];
                        for(s2 = 1; s2 < nStates[n2]; s2++)
                        {
							if(tmp[s2]*edgePot[s1+maxState*(s2+maxState*e)] > newMsgs[s1+maxState*(e+nEdges)])
									newMsgs[s1+maxState*(e+nEdges)] = tmp[s2]*edgePot[s1+maxState*(s2+maxState*e)];
                        }
                    }
                    
                    z = 0.0;
                    for(s = 0; s < nStates[n1]; s++)
                        z += newMsgs[s+maxState*(e+nEdges)];
                    for(s = 0; s < nStates[n1]; s++)
                        newMsgs[s+maxState*(e+nEdges)] /= z;
                }
                else
                {
                    for(s2 = 0; s2 < nStates[n2]; s2++)
                    {
						newMsgs[s2+maxState*e] = tmp[0]*edgePot[0+maxState*(s2+maxState*e)];
                        for(s1 = 1; s1 < nStates[n1]; s1++)
                        {
							if(tmp[s1]*edgePot[s1+maxState*(s2+maxState*e)] > newMsgs[s2+maxState*e])
									newMsgs[s2+maxState*e] = tmp[s1]*edgePot[s1+maxState*(s2+maxState*e)];
                        }
                    }
                    
                    z = 0.0;
                    for(s = 0; s < nStates[n2]; s++)
                        z += newMsgs[s+maxState*e];
                    for(s = 0; s < nStates[n2]; s++)
                        newMsgs[s+maxState*e] /= z;
                }
            }
            
            
            
            
        }
        
        
        /* oldMsgs = newMsgs */
        z = 0;
        for(s=0;s<maxState;s++)
        {
            for(e=0;e<nEdges*2;e++)
            {
                z += absDif(newMsgs[s+maxState*e],oldMsgs[s+maxState*e]);
                oldMsgs[s+maxState*e] = newMsgs[s+maxState*e];
            }
        }
        
        /* if sum(abs(newMsgs(:)-oldMsgs(:))) < 1e-4; break; */
		/*printf("z = %f\n",z);*/
        if(z < 1e-4)
        {
            break;
        }
        
    }
    
    /*if(iter == maxIter)
    {
        printf("LBP reached maxIter of %d iterations\n",maxIter);
    }
     printf("Stopped after %d iterations\n",iter); */
    
    /* compute nodeBel */
    for(n = 0; n < nNodes; n++)
    {
        for(s = 0; s < nStates[n]; s++)
            prodMsgs[s+maxState*n] = nodePot[n+nNodes*s];
        
        for(Vind = V[n]-1; Vind < V[n+1]-1; Vind++)
        {
            e = E[Vind]-1;
            n1 = edgeEnds[e]-1;
            n2 = edgeEnds[e+nEdges]-1;
            
            if (n == n2)
            {
                for(s = 0; s < nStates[n]; s++)
                {
                    prodMsgs[s+maxState*n] *= newMsgs[s+maxState*e];
                }
            }
            else
            {
                for(s = 0; s < nStates[n]; s++)
                {
                    prodMsgs[s+maxState*n] *= newMsgs[s+maxState*(e+nEdges)];
                }
            }
        }
        
        z = 0;
        for(s = 0; s < nStates[n]; s++)
        {
            nodeBel[n + nNodes*s] = prodMsgs[s+maxState*n];
            z = z + nodeBel[n+nNodes*s];
        }
        for(s = 0; s < nStates[n]; s++)
            nodeBel[n + nNodes*s] /= z;
    }
    
    
   /* Free memory */
    mxFree(prodMsgs);
    mxFree(oldMsgs);
    mxFree(newMsgs);
    mxFree(tmp);
}
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
    int     nsubs, index, x; 
    double  *temp;
    int     *subs;
      
    /* Check for proper number of input and output arguments */    
    if (nrhs != 2) {
	mexErrMsgTxt("Two input arguments required.");
    } 
    if (nlhs > 1) {
	mexErrMsgTxt("Too many output arguments.");
    }
        
    /* Check data type of first input argument */
    if (!mxIsDouble(prhs[0])) {
	mexErrMsgTxt("First input argument must be a double.");
    }
    /* Check data type of first second argument */
    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0])) {
	mexErrMsgTxt("Second input argument must be a real double.");
    }
    /* Get the number of dimensions in array */
    nsubs=mxGetNumberOfDimensions(prhs[0]);
      
    /* Check for the correct number of indices  */
    if (mxGetNumberOfElements(prhs[1]) != nsubs){
	mexErrMsgTxt("You must specify an index for each dimension.");
    }

    /* Allocate memory for the subs array on the fly */
    subs=mxCalloc(nsubs,sizeof(int));
      
    /* Get the indices and account for the fact that MATLAB is 1
       based and C is zero based.  While doing this, check to make
       sure that an index was not specified that is larger than size
       of input array */

    temp=mxGetPr(prhs[1]);
       
    for (x=0;x<nsubs;x++){
	subs[x]=(int)temp[x]-1;
	if (temp[x]> ((mxGetDimensions(prhs[0]))[x]) ){
	    mxFree(subs);
	    mexErrMsgTxt("You indexed above the size of the array.");
	}
    }

    /* Find the index of location selected.  Note, for example, that
       (3,4) in MATLAB corresponds to (2,3) in C. */
    index = mxCalcSingleSubscript(prhs[0], nsubs, subs);
      
    /* Create the output array */
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxIsComplex(prhs[0]) ? mxCOMPLEX : mxREAL);
      
    /* Free allocated memory*/
    mxFree(subs);
      
    /* Assign value in C based array to plhs. */
    mxGetPr(plhs[0])[0]= mxGetPr(prhs[0])[index];
    if (mxIsComplex(prhs[0])) {
	mxGetPi(plhs[0])[0]= mxGetPi(prhs[0])[index];
    }
}
示例#9
0
/* ************************************************************
   PROCEDURE mexFunction - Entry for Matlab
   ************************************************************ */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
  const mxArray *L_FIELD;
  mwIndex i,j, nsuper,m, cachesiz;
  const mwIndex *ljc,*lir;
  mwIndex *xsuper, *split;
  const double *xsuperPr;
  double *splitPr;
/* ------------------------------------------------------------
   Check for proper number of arguments
   ------------------------------------------------------------ */
  mxAssert(nrhs >= NPARIN, "cholsplit requires more input arguments.");
  mxAssert(nlhs <= NPAROUT, "cholsplit produces less output arguments.");
/* ------------------------------------------------------------
   Get cachesiz, and transform from KBs into 90% of FLOATS.
   ------------------------------------------------------------ */
  cachesiz = (mwIndex) floor(0.9 * (1024 / sizeof(double)) * mxGetScalar(CACHESIZ_IN));
/* ------------------------------------------------------------
   Disassemble block Cholesky structure L
   ------------------------------------------------------------ */
  mxAssert(mxIsStruct(L_IN), "Parameter `L' should be a structure.");
  L_FIELD = mxGetField(L_IN,(mwIndex)0,"L");        /* L.L */
  mxAssert( L_FIELD != NULL, "Missing field L.L.");
  m = mxGetM(L_FIELD);
  mxAssert(m == mxGetN(L_FIELD), "L.L must be square.");
  mxAssert(mxIsSparse(L_FIELD), "L.L should be sparse.");
  ljc = mxGetJc(L_FIELD);
  lir = mxGetIr(L_FIELD);
  L_FIELD = mxGetField(L_IN,(mwIndex)0,"xsuper");          /* L.xsuper */
  mxAssert( L_FIELD != NULL, "Missing field L.xsuper.");
  nsuper = mxGetM(L_FIELD) * mxGetN(L_FIELD) - 1;
  mxAssert( nsuper <= m, "Size L.xsuper mismatch.");
  xsuperPr = mxGetPr(L_FIELD);
/* ------------------------------------------------------------
   Allocate working arrays:
   ------------------------------------------------------------ */
  xsuper    = (mwIndex *) mxCalloc(nsuper+1,sizeof(mwIndex));
  split     = (mwIndex *) mxCalloc(m,sizeof(mwIndex));
/* ------------------------------------------------------------
   Convert XSUPER to integer and C-Style
   ------------------------------------------------------------ */
  for(i = 0; i <= nsuper; i++){
    j =  (mwIndex) xsuperPr[i];
    mxAssert(j>0,"");
    xsuper[i] = --j;
  }
/* ------------------------------------------------------------
   The main job: compute (upper bound on) blkchol-split.
   ------------------------------------------------------------ */
  getsplit(split, ljc,lir,xsuper,nsuper, cachesiz);
/* ------------------------------------------------------------
   create OUTPUT variable SPLIT(m)
   ------------------------------------------------------------ */
  SPLIT_OUT = mxCreateDoubleMatrix(m, (mwSize)1, mxREAL);          /* L.split */
  splitPr = mxGetPr(SPLIT_OUT);
  for(i = 0; i < m; i += j){
    j = split[i];
    splitPr[i] = (double) j;
  }
/* ------------------------------------------------------------
   Release working arrays.
   ------------------------------------------------------------ */
  mxFree(split);
  mxFree(xsuper);
}
PsychError EyelinkMessage(void)
{
   int i, numInArgs;
   int status = -1;
   void **args_ptr = NULL; /* argument list, used as a va_list */
   char s[256];
   char *formatString;
   PsychArgFormatType format;
   double tempValue;
   char *tempString = NULL;
   
   //all sub functions should have these two lines
   PsychPushHelp(useString, synopsisString, seeAlsoString);
   if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};

   //check to see if the user supplied superfluous arguments
   // PsychErrorExit(PsychCapNumInputArgs(1));
   PsychErrorExit(PsychRequireNumInputArgs(1));
   PsychErrorExit(PsychCapNumOutputArgs(1));
   
   	// Verify eyelink is up and running
	EyelinkSystemIsConnected();
	EyelinkSystemIsInitialized();
   
   PsychAllocInCharArg(1, TRUE, &formatString);
   numInArgs = PsychGetNumInputArgs();   

   if (numInArgs > 1)
   {
      args_ptr = (void **)mxMalloc((numInArgs-1) * sizeof(char *));
      //iterate over each of the supplied inputs.  
      for(i=2;i<=numInArgs;i++){
         format = PsychGetArgType(i);
         switch(format){
            case PsychArgType_double:
               if(PsychGetArgM(i)==1 && PsychGetArgN(i)==1){
                  PsychCopyInDoubleArg(i, TRUE, &tempValue);
                  args_ptr[i-2] = (void *) (int) tempValue;
               }
               else
               {
                  PsychGiveHelp();
                  return(PsychError_user);
               }
               break;
            case PsychArgType_char:
               args_ptr[i-2] = NULL;
               PsychAllocInCharArg(i, TRUE, &tempString); 
               args_ptr[i-2] = tempString;
               break;
            default:
               PsychGiveHelp();
               return(PsychError_user);
               break;
         }
      }
   }

   vsprintf(s, formatString, (va_list)args_ptr);

   status = eyemsg_printf(s);

   if (args_ptr != NULL)
      mxFree(args_ptr);

   /* if there is an output variable available, assign eyecmd_printf status to it.   */
   PsychCopyOutDoubleArg(1, FALSE, status);
   
   return(PsychError_none);
}
示例#11
0
void mexFunction ( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
	Dbptr	db;
	mxArray	*array_ptr;
	char	errmsg[STRSZ];
	char	*dbstring_code;
	int	dbcode;
	int	retcode;
	char	*string;
	Tbl	*tbl;
	long	n;
	int	i;

	if( nrhs != 2  )
	{
		antelope_mexUsageMsgTxt ( USAGE );
		return;
	}
        else if( ! get_dbptr( prhs[0], &db ) )
        {
                antelope_mexUsageMsgTxt ( USAGE );
		return;
        }
        else if( ! mtlb_get_string( prhs[1], &dbstring_code ) )
        {
                antelope_mexUsageMsgTxt ( USAGE );
		return;
        }

	dbcode = xlatname( dbstring_code, Dbxlat, NDbxlat );

	switch( dbcode )
	{
	case dbSCHEMA_DEFAULT:
	case dbDATABASE_FILENAME:
	case dbIDSERVER:
	case dbLOCKS:
        case dbSCHEMA_DESCRIPTION:
        case dbTIMEDATE_NAME:
        case dbDATABASE_DESCRIPTION:
        case dbTABLE_DESCRIPTION:
        case dbFIELD_DESCRIPTION:
        case dbSCHEMA_DETAIL:
        case dbDATABASE_DETAIL:
        case dbTABLE_DETAIL:
        case dbFIELD_DETAIL:
        case dbSCHEMA_NAME:
        case dbDATABASE_NAME:
        case dbTABLE_NAME:
        case dbFIELD_NAME:
        case dbTABLE_FILENAME:
        case dbTABLE_DIRNAME:
        case dbFIELD_RANGE:
        case dbFIELD_FORMAT:
        case dbDBPATH:
        case dbFORMAT:
        case dbFIELD_UNITS:
        case dbFIELD_BASE_TABLE:
        case dbUNIQUE_ID_NAME:
		if( ( retcode = dbquery(db, dbcode, &string) ) >= 0 )
		{
			plhs[0] = mxCreateString( string );
		}
		antelope_mex_clear_register( 1 );
		break;

        case dbDATABASE_COUNT:
        case dbTABLE_COUNT:
        case dbFIELD_COUNT:
        case dbRECORD_COUNT:
        case dbTABLE_SIZE:
        case dbFIELD_SIZE:
        case dbFIELD_INDEX:
        case dbVIEW_TABLE_COUNT:
        case dbRECORD_SIZE:
        case dbTABLE_IS_WRITEABLE:
        case dbTABLE_IS_VIEW:
	case dbDATABASE_IS_WRITABLE:
	case dbTABLE_PRESENT:
	case dbTABLE_IS_TRANSIENT:
		if( ( retcode = dbquery(db, dbcode, &n) ) >= 0 )
		{
			antelope_mex_clear_register( 1 );
			plhs[0] = CreateDouble( (double) n );
			if( plhs[0] == NULL )
			{
				mxFree( dbstring_code );
				mexErrMsgTxt( 
				   "dbquery: failed to create return value" );
			}
		}
		else
		{
			antelope_mex_clear_register( 1 );
		}
                break;  

        case dbFIELD_TYPE:
		if( ( retcode = dbquery(db, dbcode, &n) ) >= 0 )
		{
			antelope_mex_clear_register( 1 );
			plhs[0] = mxCreateString( xlatnum( n, Dbxlat, NDbxlat ) );
		}
		else
		{
			antelope_mex_clear_register( 1 );
		}
                break;  
 
        case dbLINK_FIELDS:
        case dbSCHEMA_FIELDS:
	case dbSCHEMA_TABLES:
        case dbFIELD_TABLES:
        case dbVIEW_TABLES:
        case dbTABLE_FIELDS:
        case dbPRIMARY_KEY:
        case dbALTERNATE_KEY:
        case dbFOREIGN_KEYS:
		if( ( retcode = dbquery(db, dbcode, &tbl) ) >= 0 )
		{
			antelope_mex_clear_register( 1 );
			plhs[0] = stringtbl2cellstr( tbl );
		}
		else
		{
			antelope_mex_clear_register( 1 );
		}
                break;  
 
        default:
		sprintf( errmsg, "dbquery: bad code '%s'", dbstring_code );
		mxFree( dbstring_code );
		mexErrMsgTxt( errmsg );
		break ;
	}

	mxFree( dbstring_code );
}
示例#12
0
void mexFunction( int nlhs, mxArray *plhs[] , int nrhs, const mxArray *prhs[] )

{
	
	
	double *x , *w;
	
	double sigma = 1.0 , e = 10.0;
	
	int p = 8 , K = 30;
	
	
	double *xc , *A_k;
	
	
	const int  *dimsx ;
	
	int numdimsx  ;
	
	int i , d , Nx ;
	
	int pd;
	
	double *dist_C , *C_k , *dx , *prods;
	
	int *indxc , *indx , *xhead , *xboxsz , *heads , *cinds;
	
	
	
	/*--------------------------------------------------------------------------------*/
	/*--------------------------------------------------------------------------------*/
	/* -------------------------- Parse INPUT  -------------------------------------- */
	/*--------------------------------------------------------------------------------*/	
	/*--------------------------------------------------------------------------------*/
	
	if ((nrhs < 1))
		
	{
		
		mexErrMsgTxt("Usage : v = fgt_model(x  , [w] , [sigma] , [p] , [K] , [e] );"); 
		
	}
	
	
	/* ----- Input 1 ----- */
	
	
	x           = mxGetPr(prhs[0]);
	
	numdimsx    = mxGetNumberOfDimensions(prhs[0]);
	
	dimsx       = mxGetDimensions(prhs[0]);
	
	
	d           = dimsx[0];
	
	Nx          = dimsx[1];
	
	
    K           = min(Nx , K);
	
	
	
	/* ----- Input 2 ----- */
	
	
	if ((nrhs < 2) || mxIsEmpty(prhs[1]))
	{
		
		w            = (double *)mxMalloc(Nx*sizeof(double));
		
		for (i = 0 ; i < Nx ; i++)
		{
			
			w[i] = 1.0;
			
		}
	}
	
	else
		
	{
		
		w           = mxGetPr(prhs[1]);
		
	}
	
	
	/* ----- Input 3 ----- */
	
	
	
	if (nrhs > 2)
	{
		
		sigma       = (double)mxGetScalar(prhs[2]);
		
	}
	
	
	/* ----- Input 4 ----- */
	
	if (nrhs > 3)
	{
		
		e       = (double)mxGetScalar(prhs[3]);
		
	}
	
	
	/* ----- Input 5 ----- */
	
	
	if (nrhs > 4)
	{
		
		K         = (int)mxGetScalar(prhs[4]);
		
		if(K > Nx)
			
		{
			
			mexErrMsgTxt("K must be <= Nx"); 
			
		}
		
	}
	
	else
		
	{
		
		K = (int) sqrt(Nx);
		
	}
	
	/* ----- Input 6 ----- */
	
	
	if (nrhs > 5)
	{
		
		p          = (int)mxGetScalar(prhs[5]);
		
	}
	
	
	/*--------------------------------------------------------------------------------*/
	/*---------------------------------------,----------------------------------------*/
	/* -------------------------- Parse OUTPUT  ------------------------------------- */
	/*--------------------------------------------------------------------------------*/
	/*--------------------------------------------------------------------------------*/
	
	
	pd             = nchoosek(p + d - 1 , d); 
	
	
	/* ----- output 1 ----- */
	
	
	
	
	plhs[0]        = mxCreateDoubleMatrix(d , K , mxREAL); 
	
	xc             = mxGetPr(plhs[0]);
	
	
	plhs[1]        = mxCreateDoubleMatrix(pd , K , mxREAL); 
	
	A_k            = mxGetPr(plhs[1]);
	
	
	
    C_k            = (double *)mxMalloc(pd*sizeof(double));
	
    dist_C         = (double *)mxMalloc(Nx*sizeof(double));
	
    dx             = (double *)mxMalloc(d*sizeof(double));
	
    prods          = (double *)mxMalloc(pd*sizeof(double));
	
	
    indxc          = (int *)mxMalloc(K*sizeof(int));
	
    indx           = (int *)mxMalloc(Nx*sizeof(int));
	
    xhead          = (int *)mxMalloc(K*sizeof(int));
	
    xboxsz         = (int *)mxMalloc(K*sizeof(int));
	
    heads          = (int *)mxMalloc((d + 1)*sizeof(int));
	
    cinds          = (int *)mxMalloc(pd*sizeof(int));
	
	
	/*---------------------------------------------------------------------------------*/
	/*---------------------------------------------------------------------------------*/
	/* ----------------------- MAIN CALL  -------------------------------------------- */
	/*---------------------------------------------------------------------------------*/
	/*---------------------------------------------------------------------------------*/	
	/*---------------------------------------------------------------------------------*/
	
	
	fgt_model(x ,  w , sigma , p , K , e , 
		      xc , A_k , 
			  d , Nx ,
			  indxc , indx , xhead , xboxsz , 
			  dist_C , C_k , heads , cinds , dx , prods ,  
			  pd);
	
	
	/*-----------------------------------------------*/
	/*-----------------------------------------------*/
	/* ------------ END of Mex File ---------------- */
	/*-----------------------------------------------*/
	/*-----------------------------------------------*/
	
	
	mxFree(indxc);
	
	mxFree(indx);
	
	mxFree(xhead);
	
	mxFree(xboxsz);
	
	mxFree(dist_C);
	
	mxFree(C_k);
	
	mxFree(heads);
	
	mxFree(cinds);
	
	mxFree(dx);
	
	mxFree(prods);
	
	if ((nrhs < 3) || mxIsEmpty(prhs[2]) )
	{
		
		mxFree(w);
		
	}
	
	
}
示例#13
0
/** @brief MATLAB Driver.
 **/
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  int M,N,S=0,smin=0,K,num_levels=0 ;
  const int* dimensions ;
  const double* P_pt ;
  const double* G_pt ;
  float* descr_pt ;
  float* buffer_pt ;
  float sigma0 ;
  float magnif = 3.0f ; /* Spatial bin extension factor. */
  int NBP = 4 ;         /* Number of bins for one spatial direction (even). */
  int NBO = 8 ;         /* Number of bins for the ortientation. */
  int mode = NOSCALESPACE ;
  int buffer_size=0;

  enum {IN_G=0,IN_P,IN_SIGMA0,IN_S,IN_SMIN} ;
  enum {OUT_L=0} ;

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

  if (nin < 3) {
    mexErrMsgTxt("At least three arguments are required") ;
  } else if (nout > 1) {
    mexErrMsgTxt("Too many output arguments.");
  }

  if( !uIsRealScalar(in[IN_SIGMA0]) ) {
    mexErrMsgTxt("SIGMA0 should be a real scalar") ;
  }

  if(!mxIsDouble(in[IN_G]) ||
     mxGetNumberOfDimensions(in[IN_G]) > 3) {
    mexErrMsgTxt("G should be a real matrix or 3-D array") ;
  }

  sigma0 = (float) *mxGetPr(in[IN_SIGMA0]) ;

  dimensions = mxGetDimensions(in[IN_G]) ;
  M = dimensions[0] ;
  N = dimensions[1] ;
  G_pt = mxGetPr(in[IN_G]) ;

  P_pt = mxGetPr(in[IN_P]) ;
  K = mxGetN(in[IN_P]) ;

  if( !uIsRealMatrix(in[IN_P],-1,-1)) {
    mexErrMsgTxt("P should be a real matrix") ;
  }

  if ( mxGetM(in[IN_P])  == 4) {
    /* Standard (scale space) mode */
    mode = SCALESPACE ;
    num_levels = dimensions[2] ;

    if(nin < 5) {
      mexErrMsgTxt("Five arguments are required in standard mode") ;
    }

    if( !uIsRealScalar(in[IN_S]) ) {
      mexErrMsgTxt("S should be a real scalar") ;
    }

    if( !uIsRealScalar(in[IN_SMIN]) ) {
      mexErrMsgTxt("SMIN should be a real scalar") ;
    }

    if( !uIsRealMatrix(in[IN_P],4,-1)) {
      mexErrMsgTxt("When the e mode P should be a 4xK matrix.") ;
    }

    S = (int)(*mxGetPr(in[IN_S])) ;
    smin = (int)(*mxGetPr(in[IN_SMIN])) ;

  } else if (  mxGetM(in[IN_P])  == 3 ) {
    mode = NOSCALESPACE ;
    num_levels = 1 ;
    S      = 1 ;
    smin   = 0 ;
  } else {
    mexErrMsgTxt("P should be either a 3xK or a 4xK matrix.") ;
  }

  /* Parse the property-value pairs */
  {
    char str [80] ;
    int arg = (mode == SCALESPACE) ? IN_SMIN + 1 : IN_SIGMA0 + 1 ;

    while(arg < nin) {
      int k ;

      if( !uIsString(in[arg],-1) ) {
        mexErrMsgTxt("The first argument in a property-value pair"
                     " should be a string") ;
      }
      mxGetString(in[arg], str, 80) ;

#ifdef WINDOWS
      for(k = 0 ; properties[k] && strcmpi(str, properties[k]) ; ++k) ;
#else
      for(k = 0 ; properties[k] && strcasecmp(str, properties[k]) ; ++k) ;
#endif

      switch (k) {
      case PROP_NBP:
        if( !uIsRealScalar(in[arg+1]) ) {
          mexErrMsgTxt("'NumSpatialBins' should be real scalar") ;
        }
        NBP = (int) *mxGetPr(in[arg+1]) ;
        if( NBP <= 0 || (NBP & 0x1) ) {
          mexErrMsgTxt("'NumSpatialBins' must be positive and even") ;
        }
        break ;

      case PROP_NBO:
        if( !uIsRealScalar(in[arg+1]) ) {
          mexErrMsgTxt("'NumOrientBins' should be a real scalar") ;
        }
        NBO = (int) *mxGetPr(in[arg+1]) ;
        if( NBO <= 0 ) {
          mexErrMsgTxt("'NumOrientlBins' must be positive") ;
        }
        break ;

      case PROP_MAGNIF:
        if( !uIsRealScalar(in[arg+1]) ) {
          mexErrMsgTxt("'Magnif' should be a real scalar") ;
        }
        magnif = (float) *mxGetPr(in[arg+1]) ;
        if( magnif <= 0 ) {
          mexErrMsgTxt("'Magnif' must be positive") ;
        }
        break ;

      case PROP_UNKNOWN:
        mexErrMsgTxt("Property unknown.") ;
        break ;
      }
      arg += 2 ;
    }
  }

  /* -----------------------------------------------------------------
   *                                   Pre-compute gradient and angles
   * -------------------------------------------------------------- */
  /* Alloc two buffers and make sure their size is multiple of 128 for
   * better alignment (used also by the Altivec code below.)
   */
  buffer_size = (M*N*num_levels + 0x7f) & (~ 0x7f) ;
  buffer_pt = (float*) mxMalloc( sizeof(float) * 2 * buffer_size ) ;
  descr_pt  = (float*) mxCalloc( NBP*NBP*NBO*K,  sizeof(float)  ) ;

  {
    /* Offsets to move in the scale space. */
    const int yo = 1 ;
    const int xo = M ;
    const int so = M*N ;
    int x,y,s ;

#define at(x,y) (*(pt + (x)*xo + (y)*yo))

    /* Compute the gradient */
    for(s = 0 ; s < num_levels ; ++s) {
      const double* pt = G_pt + s*so ;
      for(x = 1 ; x < N-1 ; ++x) {
        for(y = 1 ; y < M-1 ; ++y) {
          float Dx = 0.5 * ( at(x+1,y) - at(x-1,y) ) ;
          float Dy = 0.5 * ( at(x,y+1) - at(x,y-1) ) ;
          buffer_pt[(x*xo+y*yo+s*so) + 0          ] = Dx ;
          buffer_pt[(x*xo+y*yo+s*so) + buffer_size] = Dy ;
        }
      }
    }

    /* Compute angles and modules */
    {
      float* pt = buffer_pt ;
      int j = 0 ;
      while (j < N*M*num_levels) {

#if defined( MACOSX ) && defined( __ALTIVEC__ )
        if( ((unsigned int)pt & 0x7) == 0 && j+3 < N*M*num_levels ) {
          /* If aligned to 128 bit and there are at least 4 pixels left */
          float4 a, b, c, d ;
          a.vec = vec_ld(0,(vector float*)(pt              )) ;
          b.vec = vec_ld(0,(vector float*)(pt + buffer_size)) ;
          c.vec = vatan2f(b.vec,a.vec) ;
          a.x[0] = a.x[0]*a.x[0]+b.x[0]*b.x[0] ;
          a.x[1] = a.x[1]*a.x[1]+b.x[1]*b.x[1] ;
          a.x[2] = a.x[2]*a.x[2]+b.x[2]*b.x[2] ;
          a.x[3] = a.x[3]*a.x[3]+b.x[3]*b.x[3] ;
          d.vec = vsqrtf(a.vec) ;
          vec_st(c.vec,0,(vector float*)(pt + buffer_size)) ;
          vec_st(d.vec,0,(vector float*)(pt              )) ;
          j += 4 ;
          pt += 4 ;
        } else {
#endif
          float Dx = *(pt              ) ;
          float Dy = *(pt + buffer_size) ;
          *(pt              ) = sqrtf(Dx*Dx + Dy*Dy) ;
          if (*pt > 0)
            *(pt + buffer_size) = atan2f(Dy, Dx) ;
          else
            *(pt + buffer_size) = 0 ;
          j += 1 ;
          pt += 1 ;
#if defined( MACOSX ) && defined( __ALTIVEC__ )
        }
#endif

      }
    }
  }

  /* -----------------------------------------------------------------
   *                                                        Do the job
   * -------------------------------------------------------------- */
  if(K > 0) {
    int p ;

    /* Offsets to move in the buffer */
    const int yo = 1 ;
    const int xo = M ;
    const int so = M*N ;

    /* Offsets to move in the descriptor. */
    /* Use Lowe's convention. */
    const int binto = 1 ;
    const int binyo = NBO * NBP ;
    const int binxo = NBO ;
    const int bino  = NBO * NBP * NBP ;

    for(p = 0 ; p < K ; ++p, descr_pt += bino) {
      /* The SIFT descriptor is a  three dimensional histogram of the position
       * and orientation of the gradient.  There are NBP bins for each spatial
       * dimesions and NBO  bins for the orientation dimesion,  for a total of
       * NBP x NBP x NBO bins.
       *
       * The support  of each  spatial bin  has an extension  of SBP  = 3sigma
       * pixels, where sigma is the scale  of the keypoint.  Thus all the bins
       * together have a  support SBP x NBP pixels wide  . Since weighting and
       * interpolation of  pixel is used, another  half bin is  needed at both
       * ends of  the extension. Therefore, we  need a square window  of SBP x
       * (NBP + 1) pixels. Finally, since the patch can be arbitrarly rotated,
       * we need to consider  a window 2W += sqrt(2) x SBP  x (NBP + 1) pixels
       * wide.
       */
      const float x = (float) *P_pt++ ;
      const float y = (float) *P_pt++ ;
      const float s = (float) (mode == SCALESPACE) ? (*P_pt++) : 0.0 ;
      const float theta0 = (float) *P_pt++ ;

      const float st0 = sinf(theta0) ;
      const float ct0 = cosf(theta0) ;
      const int xi = (int) floor(x+0.5) ; /* Round-off */
      const int yi = (int) floor(y+0.5) ;
      const int si = (int) floor(s+0.5) - smin ;
      const float sigma = sigma0 * powf(2, s / S) ;
      const float SBP = magnif * sigma ;
      const int W = (int) floor( sqrt(2.0) * SBP * (NBP + 1) / 2.0 + 0.5) ;
      int bin ;
      int dxi ;
      int dyi ;
      const float* pt ;
      float* dpt ;

      /* Check that keypoints are within bounds . */

      if(xi < 0   ||
         xi > N-1 ||
         yi < 0   ||
         yi > M-1 ||
         ((mode==SCALESPACE) &&
          (si < 0   ||
           si > dimensions[2]-1) ) )
        continue ;

      /* Center the scale space and the descriptor on the current keypoint.
       * Note that dpt is pointing to the bin of center (SBP/2,SBP/2,0).
       */
      pt  = buffer_pt + xi*xo + yi*yo + si*so ;
      dpt = descr_pt + (NBP/2) * binyo + (NBP/2) * binxo ;

#define atd(dbinx,dbiny,dbint) (*(dpt + (dbint)*binto + (dbiny)*binyo + (dbinx)*binxo))

      /*
       * Process each pixel in the window and in the (1,1)-(M-1,N-1)
       * rectangle.
       */
      for(dxi = max(-W, 1-xi) ; dxi <= min(+W, N-2-xi) ; ++dxi) {
        for(dyi = max(-W, 1-yi) ; dyi <= min(+W, M-2-yi) ; ++dyi) {

          /* Compute the gradient. */
          float mod   = *(pt + dxi*xo + dyi*yo + 0           ) ;
          float angle = *(pt + dxi*xo + dyi*yo + buffer_size ) ;
#ifdef LOWE_COMPATIBLE
          float theta = fast_mod(-angle + theta0) ;
#else
          float theta = fast_mod(angle - theta0) ;
#endif
          /* Get the fractional displacement. */
          float dx = ((float)(xi+dxi)) - x;
          float dy = ((float)(yi+dyi)) - y;

          /* Get the displacement normalized w.r.t. the keypoint orientation
           * and extension. */
          float nx = ( ct0 * dx + st0 * dy) / SBP ;
          float ny = (-st0 * dx + ct0 * dy) / SBP ;
          float nt = NBO * theta / (2*M_PI) ;

          /* Get the gaussian weight of the sample. The gaussian window
           * has a standard deviation of NBP/2. Note that dx and dy are in
           * the normalized frame, so that -NBP/2 <= dx <= NBP/2. */
          const float wsigma = NBP/2 ;
          float win =  expf(-(nx*nx + ny*ny)/(2.0 * wsigma * wsigma)) ;

          /* The sample will be distributed in 8 adijacient bins.
           * Now we get the ``lower-left'' bin. */
          int binx = fast_floor( nx - 0.5 ) ;
          int biny = fast_floor( ny - 0.5 ) ;
          int bint = fast_floor( nt ) ;
          float rbinx = nx - (binx+0.5) ;
          float rbiny = ny - (biny+0.5) ;
          float rbint = nt - bint ;
          int dbinx ;
          int dbiny ;
          int dbint ;

          /* Distribute the current sample into the 8 adijacient bins. */
          for(dbinx = 0 ; dbinx < 2 ; ++dbinx) {
            for(dbiny = 0 ; dbiny < 2 ; ++dbiny) {
              for(dbint = 0 ; dbint < 2 ; ++dbint) {

                if( binx+dbinx >= -(NBP/2) &&
                    binx+dbinx <   (NBP/2) &&
                    biny+dbiny >= -(NBP/2) &&
                    biny+dbiny <   (NBP/2) ) {
                  float weight = win
                    * mod
                    * fabsf(1 - dbinx - rbinx)
                    * fabsf(1 - dbiny - rbiny)
                    * fabsf(1 - dbint - rbint) ;

                      atd(binx+dbinx, biny+dbiny, (bint+dbint) % NBO) += weight ;
                }
              }
            }
          }
        }
      }


      {
        /* Normalize the histogram to L2 unit length. */
        normalize_histogram(descr_pt, descr_pt + NBO*NBP*NBP) ;

        /* Truncate at 0.2. */
        for(bin = 0; bin < NBO*NBP*NBP ; ++bin) {
          if (descr_pt[bin] > 0.2) descr_pt[bin] = 0.2;
        }

        /* Normalize again. */
        normalize_histogram(descr_pt, descr_pt + NBO*NBP*NBP) ;
      }
    }
  }

  /* Restore pointer to the beginning of the descriptors. */
  descr_pt -= NBO*NBP*NBP*K ;

  {
    int k ;
    double* L_pt ;
    out[OUT_L] = mxCreateDoubleMatrix(NBP*NBP*NBO, K, mxREAL) ;
    L_pt = mxGetPr(out[OUT_L]) ;
    for(k = 0 ; k < NBP*NBP*NBO*K ; ++k) {
      L_pt[k] = descr_pt[k] ;
    }
  }

  mxFree(descr_pt) ;
  mxFree(buffer_pt) ;
}
示例#14
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	
	double *px, cf, tdres, reptime, cohc, cihc;
	int    nrep, pxbins, lp, outsize[2], totalstim;

	double *pxtmp, *cftmp, *nreptmp, *tdrestmp, *reptimetmp, *cohctmp, *cihctmp;
	
    double *ihcout;
   
	void   IHCAN(double *, double, int, double, int, double, double, double *);
	
	/* Check for proper number of arguments */
	
	if (nrhs != 7) 
	{
		mexErrMsgTxt("catmodel_IHC requires 7 input arguments.");
	}; 

	if (nlhs !=1)  
	{
		mexErrMsgTxt("catmodel_IHC requires 1 output argument.");
	};
	
	/* Assign pointers to the inputs */

	pxtmp		= mxGetPr(prhs[0]);
	cftmp		= mxGetPr(prhs[1]);
	nreptmp		= mxGetPr(prhs[2]);
	tdrestmp	= mxGetPr(prhs[3]);
	reptimetmp	= mxGetPr(prhs[4]);
    cohctmp		= mxGetPr(prhs[5]);
    cihctmp		= mxGetPr(prhs[6]);
		
	/* Check with individual input arguments */

	pxbins = mxGetN(prhs[0]);
	if (pxbins==1)
		mexErrMsgTxt("px must be a row vector\n");
	
	cf = cftmp[0];
	if ((cf<80)|(cf>40e3))
	{
		mexPrintf("cf (= %1.1f Hz) must be between 80 Hz and 40 kHz\n",cf);
		mexErrMsgTxt("\n");
    }
	
	nrep = (int) nreptmp[0];
	if (nreptmp[0]!=nrep)
		mexErrMsgTxt("nrep must an integer.\n");
	if (nrep<1)
		mexErrMsgTxt("nrep must be greater that 0.\n");

    tdres = tdrestmp[0];
	
	reptime = reptimetmp[0];
	if (reptime<pxbins*tdres)  /* duration of stimulus = pxbins*tdres */
		mexErrMsgTxt("reptime should be equal to or longer than the stimulus duration.\n");

    cohc = cohctmp[0]; /* impairment in the OHC  */
	if ((cohc<0)|(cohc>1))
	{
		mexPrintf("cohc (= %1.1f) must be between 0 and 1\n",cohc);
		mexErrMsgTxt("\n");
	}

	cihc = cihctmp[0]; /* impairment in the IHC  */
	if ((cihc<0)|(cihc>1))
	{
		mexPrintf("cihc (= %1.1f) must be between 0 and 1\n",cihc);
		mexErrMsgTxt("\n");
	}
	
	/* Calculate number of samples for total repetition time */

	totalstim = (int)floor((reptime*1e3)/(tdres*1e3));    

    px = (double*)mxCalloc(totalstim,sizeof(double)); 

	/* Put stimulus waveform into pressure waveform */

	for (lp=0; lp<pxbins; lp++)
			px[lp] = pxtmp[lp];
	
	/* Create an array for the return argument */
	
	outsize[0] = 1;
	outsize[1] = totalstim*nrep;
    
	plhs[0] = mxCreateNumericArray(2, outsize, mxDOUBLE_CLASS, mxREAL);
	
	/* Assign pointers to the outputs */
	
	ihcout  = mxGetPr(plhs[0]);
		
	/* run the model */

	IHCAN(px,cf,nrep,tdres,totalstim,cohc,cihc,ihcout);

	mxFree(px);

}
示例#15
0
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  int unsigned K1, K2, ND ;
  void* L1_pt ;
  void* L2_pt ;
  double thresh = 1.5 ;
  mxClassID data_class ;
  enum {L1=0,L2,THRESH} ;
  enum {MATCHES=0,D} ;

  /* ------------------------------------------------------------------
  **                                                Check the arguments
  ** --------------------------------------------------------------- */
  if (nin < 2) {
    mexErrMsgTxt("At least two input arguments required");
  } else if (nout > 2) {
    mexErrMsgTxt("Too many output arguments");
  }

  if(!mxIsNumeric(in[L1]) ||
     !mxIsNumeric(in[L2]) ||
     mxGetNumberOfDimensions(in[L1]) > 2 ||
     mxGetNumberOfDimensions(in[L2]) > 2) {
    mexErrMsgTxt("L1 and L2 must be two dimensional numeric arrays") ;
  }

  K1 = mxGetN(in[L1]) ;
  K2 = mxGetN(in[L2]) ;
  ND = mxGetM(in[L1]) ;

  if(mxGetM(in[L2]) != ND) {
    mexErrMsgTxt("L1 and L2 must have the same number of rows") ;
  }

  data_class = mxGetClassID(in[L1]) ;
  if(mxGetClassID(in[L2]) != data_class) {
    mexErrMsgTxt("L1 and L2 must be of the same class") ;
  }

  L1_pt = mxGetData(in[L1]) ;
  L2_pt = mxGetData(in[L2]) ;

  if(nin == 3) {
    if(!vlmxIsPlainScalar(in[THRESH])) {
      mexErrMsgTxt("THRESH should be a real scalar") ;
    }
    thresh = *mxGetPr(in[THRESH]) ;
  } else if(nin > 3) {
    mexErrMsgTxt("At most three arguments are allowed") ;
  }

  /* ------------------------------------------------------------------
  **                                                         Do the job
  ** --------------------------------------------------------------- */
  {
    Pair* pairs_begin = (Pair*) mxMalloc(sizeof(Pair) * (K1+K2)) ;
    Pair* pairs_iterator = pairs_begin ;


#define _DISPATCH_COMPARE( MXC )                                        \
    case MXC :                                                          \
      pairs_iterator = compare_##MXC(pairs_iterator,                    \
                                     (const TYPEOF_##MXC*) L1_pt,       \
                                     (const TYPEOF_##MXC*) L2_pt,       \
                                     K1,K2,ND,thresh) ;                 \
    break ;                                                             \

    switch (data_class) {
    _DISPATCH_COMPARE( mxDOUBLE_CLASS ) ;
    _DISPATCH_COMPARE( mxSINGLE_CLASS ) ;
    _DISPATCH_COMPARE( mxINT8_CLASS   ) ;
    _DISPATCH_COMPARE( mxUINT8_CLASS  ) ;
    default :
      mexErrMsgTxt("Unsupported numeric class") ;
      break ;
    }

    /* ---------------------------------------------------------------
     *                                                        Finalize
     * ------------------------------------------------------------ */
    {
      Pair* pairs_end = pairs_iterator ;
      double* M_pt ;
      double* D_pt = NULL ;

      out[MATCHES] = mxCreateDoubleMatrix
        (2, pairs_end-pairs_begin, mxREAL) ;

      M_pt = mxGetPr(out[MATCHES]) ;

      if(nout > 1) {
        out[D] = mxCreateDoubleMatrix(1,
                                      pairs_end-pairs_begin,
                                      mxREAL) ;
        D_pt = mxGetPr(out[D]) ;
      }

      for(pairs_iterator = pairs_begin ;
          pairs_iterator < pairs_end  ;
          ++pairs_iterator) {
        *M_pt++ = pairs_iterator->k1 + 1 ;
        *M_pt++ = pairs_iterator->k2 + 1 ;
        if(nout > 1) {
          *D_pt++ = pairs_iterator->score ;
        }
      }
    }
    mxFree(pairs_begin) ;
  }
}
示例#16
0
int buffer_puthdr(int server, mxArray * plhs[], const mxArray * prhs[])
{
	int fieldnumber;
	mxArray *field;
	int result;
  
	message_t     request;
	messagedef_t  request_def;
	message_t    *response = NULL;
	headerdef_t   header_def;
	
	ft_chunkdef_t chunk_def;
  
  /* allocate the request message */
	request.def = &request_def;
	request.buf = NULL;
	request_def.version = VERSION;
	request_def.command = PUT_HDR;
	request_def.bufsize = 0;
  
  /* define the header, it has the fields "nchans", "nsamples", "nevents", "fsample", "data_type" */
  	if (mxGetNumberOfElements(prhs[0])!=1)
		mexErrMsgTxt("Only one header can be put into the buffer at a time.");

	fieldnumber = mxGetFieldNumber(prhs[0], "nchans");
	if (fieldnumber<0) 
		mexErrMsgTxt("field 'nchans' is missing");
	field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
	if (!mxIsNumeric(field) || mxIsEmpty(field)) 
		mexErrMsgTxt("invalid data type for 'nchans'");
	header_def.nchans    = (UINT32_T)mxGetScalar(field) ;
	
	fieldnumber = mxGetFieldNumber(prhs[0], "nsamples");
	if (fieldnumber<0) 
		mexErrMsgTxt("field 'nsamples' is missing");
    field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
    if (!mxIsNumeric(field) || mxIsEmpty(field)) 
		mexErrMsgTxt("invalid data type for 'nsamples'");
	header_def.nsamples    = (UINT32_T)mxGetScalar(field) ;
  
	fieldnumber = mxGetFieldNumber(prhs[0], "nevents");
	if (fieldnumber<0) 
		mexErrMsgTxt("field is missing 'nevents'");
	field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
	if (!mxIsNumeric(field) || mxIsEmpty(field)) 
		mexErrMsgTxt("invalid data type for 'nevents'");
	header_def.nevents    = (UINT32_T)mxGetScalar(field) ;
  
	fieldnumber = mxGetFieldNumber(prhs[0], "fsample");
	if (fieldnumber<0) 
		mexErrMsgTxt("field is missing 'fsample'");
    field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
    if (!mxIsNumeric(field) || mxIsEmpty(field)) 
		mexErrMsgTxt("invalid data type for 'fsample'");
	header_def.fsample    = (float)mxGetScalar(field) ;
  
	fieldnumber = mxGetFieldNumber(prhs[0], "data_type");
	if (fieldnumber<0) 
		mexErrMsgTxt("field 'data_type' is missing");
	field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
	if (!mxIsNumeric(field) || mxIsEmpty(field)) 
		mexErrMsgTxt("invalid data type for 'data_type'");
	header_def.data_type    = (UINT32_T)mxGetScalar(field) ;
	
	/* construct a PUT_HDR request */
	request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, &header_def, sizeof(headerdef_t));
	
	/* append existing chunks to request.buf, set correct header_def.bufsize at the end */
	fieldnumber = mxGetFieldNumber(prhs[0], "nifti_1");
	if (fieldnumber>=0) {
		field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
		if (!mxIsUint8(field) || mxGetNumberOfElements(field)!=SIZE_NIFTI_1) {
			mexWarnMsgTxt("invalid data type for field 'nifti_1' -- ignoring");
		} else {
			chunk_def.size = SIZE_NIFTI_1;
			chunk_def.type = FT_CHUNK_NIFTI1;
		
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, &chunk_def, sizeof(chunk_def));
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, mxGetData(field), chunk_def.size);
		}
	}
	
	fieldnumber = mxGetFieldNumber(prhs[0], "siemensap");
	if (fieldnumber>=0) {
		field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
		if (!mxIsUint8(field)) {
			mexWarnMsgTxt("invalid data type for field 'siemensap' -- ignoring");
		} else {
			chunk_def.size = mxGetNumberOfElements(field);
			chunk_def.type = FT_CHUNK_SIEMENS_AP;
		
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, &chunk_def, sizeof(chunk_def));
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, mxGetData(field), chunk_def.size);
		}
	}
	
	fieldnumber = mxGetFieldNumber(prhs[0], "ctf_res4");
	if (fieldnumber>=0) {
		field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
		if (!mxIsUint8(field)) {
			mexWarnMsgTxt("invalid data type for field 'ctf_res4' -- ignoring");
		} else {
			chunk_def.size = mxGetNumberOfElements(field);
			chunk_def.type = FT_CHUNK_CTF_RES4;
		
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, &chunk_def, sizeof(chunk_def));
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, mxGetData(field), chunk_def.size);
		}
	}	
	
	fieldnumber = mxGetFieldNumber(prhs[0], "channel_names");
	if (fieldnumber>=0) {
		ft_chunk_t *chunk = NULL;
		field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
		chunk = encodeChannelNames(field, header_def.nchans);
		if (chunk == NULL) {
			mexWarnMsgTxt("invalid data type for field 'channel_names' -- ignoring.");
		} else {
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, chunk, sizeof(ft_chunkdef_t) + chunk->def.size);
			mxFree(chunk);
		}
	}
	
	fieldnumber = mxGetFieldNumber(prhs[0], "resolutions");
	if (fieldnumber>=0) {
		ft_chunk_t *chunk = NULL;
		field = mxGetFieldByNumber(prhs[0], 0, fieldnumber);
		chunk = encodeResolutions(field, header_def.nchans);
		if (chunk == NULL) {
			mexWarnMsgTxt("invalid data type for field 'resolutions' -- ignoring.");
		} else {
			request_def.bufsize = ft_mx_append(&request.buf, request_def.bufsize, chunk, sizeof(ft_chunkdef_t) + chunk->def.size);
			mxFree(chunk);
		}
	}		
	
	/* header->def->bufsize is the request->def->bufsize - sizeof(header->def) */
	((headerdef_t *) request.buf)->bufsize = request_def.bufsize - sizeof(headerdef_t);
	
	/* write the request, read the response */
	result = clientrequest(server, &request, &response);
  
	/* the request structure is not needed any more, but only .buf needs to be free'd */
    if (request.buf != NULL) mxFree(request.buf);
	
	if (result == 0) {
		/* check that the response is PUT_OK */
		if (!response)
			mexErrMsgTxt("unknown error in response\n");
		if (!response->def) {
			FREE(response->buf);
			FREE(response);
			mexErrMsgTxt("unknown error in response\n");
		}
		if (response->def->command!=PUT_OK) {
			result = response->def->command;
		}
	}
	/* the response structure is not needed any more */
	if (response) {
		FREE(response->def);
		FREE(response->buf);
		FREE(response);
	}
	return result;
}
示例#17
0
/* ************************************************************
   PROCEDURE mexFunction - Entry for Matlab
   ************************************************************ */
void mexFunction(int nlhs, mxArray *plhs[],
                int nrhs, const mxArray *prhs[])
{
  jcir At;
  mwIndex i,j, nblk,m, L, iwsize;
  mwIndex *iwork, *Ablkjc, *blkstart;
  const mwIndex *rowj;
  double *AblkjcPr;
  const double *blkstartPr;
  bool *cwork;
/* ------------------------------------------------------------
   Check for proper number of arguments
   ------------------------------------------------------------ */
  mxAssert(nrhs >= NPARIN, "partitA requires more input arguments.");
  mxAssert(nlhs <= NPAROUT, "partitA produces less output arguments.");
/* --------------------------------------------------
   GET inputs At, blkstart
   -------------------------------------------------- */
  mxAssert(mxIsSparse(AT_IN), "At must be a sparse matrix.");
  At.jc = mxGetJc(AT_IN);
  At.ir = mxGetIr(AT_IN);
  m = mxGetN(AT_IN);
  nblk = mxGetM(BLKSTART_IN) * mxGetN(BLKSTART_IN);
  blkstartPr = mxGetPr(BLKSTART_IN);
/* ------------------------------------------------------------
   Allocate working array Ablkjc((nblk+2) * m), iwork(log_2(1+nblk)),
   blkstart(nblk)
   ------------------------------------------------------------ */
  iwsize = (mwIndex) floor(log(1.0+nblk)/log(2.0));
  iwork = (mwIndex *) mxCalloc(MAX(iwsize,1), sizeof(mwIndex));
  Ablkjc = (mwIndex *) mxCalloc(MAX((nblk+2)*m,1), sizeof(mwIndex));
  blkstart = (mwIndex *) mxCalloc(MAX(nblk,1), sizeof(mwIndex));
  cwork = (bool *) mxCalloc(MAX(nblk,1), sizeof(bool));
/* ------------------------------------------------------------
   Translate blkstart from Fortran-double to C-mwIndex
   ------------------------------------------------------------ */
  for(i = 0; i < nblk; i++){                         /* to integers */
    j = (mwIndex) blkstartPr[i];
    mxAssert(j>0,"");
    blkstart[i] = --j;
  }
/* ------------------------------------------------------------
   The real job:
   ------------------------------------------------------------ */
  partitA(Ablkjc, At.jc,At.ir, blkstart, m,nblk, iwsize,cwork,iwork);
/* ------------------------------------------------------------
   Create output Ablkjc m x nblk.
   ------------------------------------------------------------ */
  ABLKJC_OUT = mxCreateDoubleMatrix(m, nblk, mxREAL);
  AblkjcPr = mxGetPr(ABLKJC_OUT);
  rowj = Ablkjc;
  L = nblk+2;
  for(j = 0; j < nblk; j++){
    ++rowj;
    for(i = 0; i < m; i++)
      AblkjcPr[i] = (double) rowj[i*L];      /* convert mwIndex to double */
    AblkjcPr += m;
  }
/* ------------------------------------------------------------
   Release working arrays
   ------------------------------------------------------------ */
  mxFree(cwork);
  mxFree(iwork);
  mxFree(Ablkjc);
  mxFree(blkstart);
}
// Function definitions. 
// -----------------------------------------------------------------
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{
    //Input Args
    user_function_data fun;
    double *x0, *ydata = NULL, *lb = NULL, *ub = NULL, *A = NULL, *b = NULL, *Aeq = NULL, *beq = NULL;
    //Options
    int maxIter = 500;
    double info[LM_INFO_SZ];
    double opts[LM_OPTS_SZ]={J_INIT_MU, J_STOP_THRESH, J_STOP_THRESH, J_STOP_THRESH, LM_DIFF_DELTA};
    
    //Outputs Args
    double *x, *fval, *exitflag, *iter, *feval;
    double *pcovar = NULL;
    
    //Internal Vars
    size_t ndec, ndat;   
    int i, status, havJac = 0, conMode = 0;
    int nineq=0, neq=0;
    double *covar = NULL;
    double *Apr, *bpr;
    double *llb, *lub;
    citer = 1;
    iterF.enabled = false;
    
    if (nrhs < 1) {
        if(nlhs < 1)
            printSolverInfo();
        else
            plhs[0] = mxCreateString(LM_VERSION);   
        return;
    }

    //Check user inputs & get constraint information
    checkInputs(prhs,nrhs,&conMode);

    //Get Sizes
    ndec = mxGetNumberOfElements(prhs[2]);
    ndat = mxGetNumberOfElements(prhs[3]);
    //Get Objective Function Handle
    if (mxIsChar(prhs[0])) {
        CHECK(mxGetString(prhs[0], fun.f, FLEN) == 0,"error reading objective name string");
        fun.nrhs = 1;
        fun.xrhs = 0;
    } else {
        fun.prhs[0] = (mxArray*)prhs[0];
        strcpy(fun.f, "feval");
        fun.nrhs = 2;
        fun.xrhs = 1;
    }
    fun.prhs[fun.xrhs] = mxCreateDoubleMatrix(ndec, 1, mxREAL); //x0
    fun.print = 0;
    //Check and Get Gradient Function Handle
    if(!mxIsEmpty(prhs[1])) {  
        havJac = 1;
        if (mxIsChar(prhs[1])) {
            CHECK(mxGetString(prhs[1], fun.g, FLEN) == 0,"error reading gradient name string");
            fun.nrhs_g = 1;
            fun.xrhs_g = 0;
        } else {
            fun.prhs_g[0] = (mxArray*)prhs[1];
            strcpy(fun.g, "feval");
            fun.nrhs_g = 2;
            fun.xrhs_g = 1;
        }   
        fun.prhs_g[fun.xrhs_g] = mxCreateDoubleMatrix(ndec, 1, mxREAL); //x0
    }

    //Get x0 + data
    x0 = mxGetPr(prhs[2]);
    ydata = mxGetPr(prhs[3]);
    fun.ydata = ydata;
    
    //Get Bounds
    if(conMode & 1) {
        //LB
        if(!mxIsEmpty(prhs[4])){
            llb = mxGetPr(prhs[4]);
            lb = mxCalloc(ndec,sizeof(double));
            memcpy(lb,llb,ndec*sizeof(double));
            for(i=0;i<ndec;i++) {
                if(mxIsInf(lb[i]))
                    lb[i] = -DBL_MAX;
            }
        }
        else {
            lb = mxCalloc(ndec,sizeof(double));
            for(i=0;i<ndec;i++)
                lb[i] = -DBL_MAX;
        }
        //UB
        if(nrhs > 5 && !mxIsEmpty(prhs[5])){
            lub = mxGetPr(prhs[5]);
            ub = mxCalloc(ndec,sizeof(double));
            memcpy(ub,lub,ndec*sizeof(double));
            for(i=0;i<ndec;i++) {
                if(mxIsInf(ub[i]))
                    ub[i] = DBL_MAX;
            }
        }
        else {
            ub = mxCalloc(ndec,sizeof(double));
            for(i=0;i<ndec;i++)
                ub[i] = DBL_MAX;
        }
    }
    //Get Linear Inequality Constraints
    if(conMode & 2) {
        nineq = (int)mxGetM(prhs[7]);
        Apr = mxGetPr(prhs[6]);
        bpr = mxGetPr(prhs[7]);
        //Need to flip >= to <=
        A = mxCalloc(ndec*nineq,sizeof(double));
        b = mxCalloc(nineq,sizeof(double));
        for(i=0;i<ndec*nineq;i++)
            A[i] = -Apr[i];
        for(i=0;i<nineq;i++)
            b[i] = -bpr[i];
    }
    //Get Linear Equality Constraints
    if(conMode & 4) {
        Aeq = mxGetPr(prhs[8]);
        beq = mxGetPr(prhs[9]);
        neq = (int)mxGetM(prhs[9]);
    }
    
    //Get Options if specified
    if(nrhs > 10) {
        if(mxGetField(prhs[10],0,"maxiter"))
            maxIter = (int)*mxGetPr(mxGetField(prhs[10],0,"maxiter"));
        if(mxGetField(prhs[10],0,"display"))
            fun.print = (int)*mxGetPr(mxGetField(prhs[10],0,"display"));
        if(mxGetField(prhs[10],0,"iterfun") && !mxIsEmpty(mxGetField(prhs[10],0,"iterfun")))
        {
            iterF.prhs[0] = (mxArray*)mxGetField(prhs[10],0,"iterfun");
            strcpy(iterF.f, "feval");
            iterF.enabled = true;  
            iterF.prhs[1] = mxCreateNumericMatrix(1,1,mxINT32_CLASS,mxREAL);
            iterF.prhs[2] = mxCreateDoubleMatrix(1,1,mxREAL);
            iterF.prhs[3] = mxCreateDoubleMatrix(ndec,1,mxREAL);
        }
    }                       

    //Create Outputs
    plhs[0] = mxCreateDoubleMatrix(ndec,1, mxREAL);
    plhs[1] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[2] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[3] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[4] = mxCreateDoubleMatrix(1,1, mxREAL);
    x = mxGetPr(plhs[0]); 
    fval = mxGetPr(plhs[1]); 
    exitflag = mxGetPr(plhs[2]);    
    iter = mxGetPr(plhs[3]);
    feval = mxGetPr(plhs[4]);
    
    //Copy initial guess to x
    memcpy(x,x0,ndec*sizeof(double));
    //Create Covariance Matrix if Required
    if(nlhs>4)
        covar=mxCalloc(ndec*ndec,sizeof(double));
    
    //Print Header
    if(fun.print) {
        mexPrintf("\n------------------------------------------------------------------\n");
        
        mexPrintf(" This is LEVMAR v2.5\n");
            
        mexPrintf(" Author: Manolis Lourakis\n MEX Interface J. Currie 2011\n\n");
        mexPrintf(" Problem Properties:\n");
        mexPrintf(" # Decision Variables:     %4d\n",ndec);
        mexPrintf(" # Data Points:            %4d\n",ndat);

        mexPrintf("------------------------------------------------------------------\n");
    }
  
    //Solve based on constraints
    switch(conMode)
    {
        case MIN_UNCONSTRAINED:
            //mexPrintf("Unc Problem\n");
            if(havJac)
                status = dlevmar_der(func, jac, x, ydata, (int)ndec, (int)ndat, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_dif(func, x, ydata, (int)ndec, (int)ndat, maxIter, opts, info, NULL, covar, &fun);            
            break;
        case MIN_CONSTRAINED_BC:
            //mexPrintf("Box Constrained Problem\n");
            if(havJac)
                status = dlevmar_bc_der(func, jac, x, ydata, (int)ndec, (int)ndat, lb, ub, NULL, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_bc_dif(func, x, ydata, (int)ndec, (int)ndat, lb, ub, NULL, maxIter, opts, info, NULL, covar, &fun);
            break;
        case MIN_CONSTRAINED_LIC:
            //mexPrintf("Linear Inequality Problem\n");
            if(havJac)
                status = dlevmar_lic_der(func, jac, x, ydata, (int)ndec, (int)ndat, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_lic_dif(func, x, ydata, (int)ndec, (int)ndat, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            break;
        case MIN_CONSTRAINED_BLIC:
            //mexPrintf("Boxed Linear Inequality Problem\n");
            if(havJac)
                status = dlevmar_blic_der(func, jac, x, ydata, (int)ndec, (int)ndat, lb, ub, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_blic_dif(func, x, ydata, (int)ndec, (int)ndat, lb, ub, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            break;
        case MIN_CONSTRAINED_LEC:
            //mexPrintf("Linear Equality Problem\n");
            if(havJac)
                status = dlevmar_lec_der(func, jac, x, ydata, (int)ndec, (int)ndat, Aeq, beq, neq, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_lec_dif(func, x, ydata, (int)ndec, (int)ndat, Aeq, beq, neq, maxIter, opts, info, NULL, covar, &fun);
            break;
        case MIN_CONSTRAINED_BLEC:
            //mexPrintf("Boxed Linear Equality Problem\n");
            if(havJac)
                status = dlevmar_blec_der(func, jac, x, ydata, (int)ndec, (int)ndat, lb, ub, Aeq, beq, neq, NULL, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_blec_dif(func, x, ydata, (int)ndec, (int)ndat, lb, ub, Aeq, beq, neq, NULL, maxIter, opts, info, NULL, covar, &fun);
            break;
        case MIN_CONSTRAINED_LEIC:
            //mexPrintf("Linear Inequality + Equality Problem\n");
            if(havJac)
                status = dlevmar_leic_der(func, jac, x, ydata, (int)ndec, (int)ndat, Aeq, beq, neq, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_leic_dif(func, x, ydata, (int)ndec, (int)ndat, Aeq, beq, neq, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            break;
        case MIN_CONSTRAINED_BLEIC:
            //mexPrintf("Boxed Linear Inequality + Equality Problem\n");
            if(havJac)
                status = dlevmar_bleic_der(func, jac, x, ydata, (int)ndec, (int)ndat, lb, ub, Aeq, beq, neq, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            else
                status = dlevmar_bleic_dif(func, x, ydata, (int)ndec, (int)ndat, lb, ub, Aeq, beq, neq, A, b, nineq, maxIter, opts, info, NULL, covar, &fun);
            break;
        default:
            mexErrMsgTxt("Unknown constraint configuration");
    }
       
    //Save Status & Iterations
    *fval = info[1];
    *exitflag = getStatus(info[6]);
    *iter = (double)status;
    *feval = (double)citer;
    
    //Save Covariance if Required
    if(nlhs > 5) {
        plhs[5] = mxCreateDoubleMatrix(ndec, ndec, mxREAL);
        pcovar = mxGetPr(plhs[5]);
        memcpy(pcovar,covar,ndec*ndec*sizeof(double));
    }
    
    //Print Header
    if(fun.print){            
        //Termination Detected
        if(*exitflag == 1)
            mexPrintf("\n *** SUCCESSFUL TERMINATION ***\n");
        else if(*exitflag == 0)
            mexPrintf("\n *** MAXIMUM ITERATIONS REACHED ***\n");
        else if(*exitflag == -1)
            mexPrintf("\n *** TERMINATION: TOLERANCE TOO SMALL ***\n");
        else if(*exitflag == -2)
            mexPrintf("\n *** TERMINATION: ROUTINE ERROR ***\n");     

        if(*exitflag==1)
            mexPrintf(" Final SSE: %12.5g\n In %3.0f iterations\n",*fval,*iter);

        mexPrintf("------------------------------------------------------------------\n\n");
    }
    
    //Clean Up
    if(lb) mxFree(lb);
    if(ub) mxFree(ub);
    if(covar) mxFree(covar);
    if(A) mxFree(A);
    if(b) mxFree(b);
}
示例#19
0
void mexFunction
(
    /* === Parameters ======================================================= */

    int nlhs,			/* number of left-hand sides */
    mxArray *plhs [],		/* left-hand side matrices */
    int nrhs,			/* number of right--hand sides */
    const mxArray *prhs []	/* right-hand side matrices */
)
{
    ZAMGlevelmat *PRE;
    CAMGlevelmat *SPRE;
    ZILUPACKparam *param;
    integer n;

    const char **fnames;

    mxArray    *PRE_input, *b_input, *x_output, *tmp, *fout;
    int        i,j,k,l,m, ifield,nfields;
    char       *pdata;
    double     *pr, *pi;
    doublecomplex *dbuff, *sol, *rhs;

    if (nrhs != 2)
       mexErrMsgTxt("Two input arguments required.");
    else if (nlhs !=1)
       mexErrMsgTxt("One output argument is required.");



    /* import pointer to the preconditioner */
    PRE_input = (mxArray*) prhs [0] ;
    /* get number of levels of input preconditioner structure `PREC' */
    /* nlev=mxGetN(PRE_input); */


    nfields = mxGetNumberOfFields(PRE_input);
    /* allocate memory  for storing pointers */
    fnames = mxCalloc((size_t)nfields, (size_t)sizeof(*fnames));
    for (ifield = 0; ifield < nfields; ifield++) {
        fnames[ifield] = mxGetFieldNameByNumber(PRE_input,ifield);
	/* check whether `PREC.ptr' exists */
	if (!strcmp("ptr",fnames[ifield])) {
	   /* field `ptr' */
	   tmp = mxGetFieldByNumber(PRE_input,0,ifield);
	   pdata = mxGetData(tmp);
	   memcpy(&PRE, pdata, (size_t)sizeof(size_t));
	}
	else if (!strcmp("param",fnames[ifield])) {
	   /* field `param' */
	   tmp = mxGetFieldByNumber(PRE_input,0,ifield);
	   pdata = mxGetData(tmp);
	   memcpy(&param, pdata, (size_t)sizeof(size_t));
	}
    }
    mxFree(fnames);



    /* copy right hand side `b' */
    b_input = (mxArray *) prhs [1] ;
    pr=mxGetPr(b_input);
    n=mxGetM(b_input);

    /* make sure that enough buffer memory is available */
    param->ndbuff=MAX(param->ndbuff,5*(size_t)n);
    param->dbuff=(doublecomplex*)ReAlloc(param->dbuff,
					 (size_t)param->ndbuff*sizeof(doublecomplex),
					 "ZSYMilupacksol:rhs");

    rhs=param->dbuff;
    if (!mxIsComplex(b_input)) {
       for (i=0; i<n; i++) {
	   rhs[i].r=pr[i];
	   rhs[i].i=0;
       }
    }
    else {
       pi=mxGetPi(b_input);
       for (i=0; i<n; i++) {
	   rhs[i].r=pr[i];
	   rhs[i].i=pi[i];
       }
    }


    /* rescale right hand side */
    if (PRE->issingle) {
       SPRE=(CAMGlevelmat *)PRE;
       for (i=0; i <n; i++) {
	   rhs[i].r=rhs[i].r*(double)SPRE->rowscal[i].r;
	   rhs[i].i=rhs[i].i*(double)SPRE->rowscal[i].r;
       }
    }
    else {
       for (i=0; i <n; i++) {
	   rhs[i].r=rhs[i].r*PRE->rowscal[i].r;
	   rhs[i].i=rhs[i].i*PRE->rowscal[i].r;
       }
    }


    /* provide memory for the approximate solution */
    sol=param->dbuff+n;
    /* 3n spaces as buffer */
    dbuff=param->dbuff+2*n;
  
    ZSYMAMGsol_internal(PRE,param, rhs,sol, dbuff);

    /* Create a struct matrices for output */
    nlhs=1;

    plhs[0] = mxCreateDoubleMatrix((mwSize)n, (mwSize)1, mxCOMPLEX);
    x_output=plhs[0];
    pr=mxGetPr(x_output);
    pi=mxGetPi(x_output);
    /* rescale approximate solution */
    if (PRE->issingle) {
       for (i=0; i <n; i++) {
	   pr[i]=sol[i].r*SPRE->colscal[i].r;
	   pi[i]=sol[i].i*SPRE->colscal[i].r;
       }
    }
    else {
       for (i=0; i <n; i++) {
	   pr[i]=sol[i].r*PRE->colscal[i].r;
	   pi[i]=sol[i].i*PRE->colscal[i].r;
       }
    }

    return;
}
void mexFunction( int nlhs, mxArray *plhs[] , int nrhs, const mxArray *prhs[] )
{
    float *X ;
	int Tcascade = 0;
	int *dimsyest;
	double  param_default[400]      = {4608.000000,240.000000, 0.698196, 0.000000,8396.000000, 6.000000,-0.632038, 0.000000,4717.000000,13.000000,-0.475997, 0.000000,4776.000000,128.000000,-0.417231, 0.000000,986.000000,240.000000, 0.371072, 0.000000,2431.000000,192.000000, 0.365243, 0.000000,6463.000000,62.000000,-0.300767, 0.000000,2399.000000,192.000000, 0.283725, 0.000000,4630.000000,40.000000,-0.272978, 0.000000,4215.000000,161.000000, 0.277569, 0.000000,3030.000000,120.000000, 0.280558, 0.000000,655.000000,28.000000,-0.273113, 0.000000,604.000000,240.000000, 0.257744, 0.000000,185.000000,32.000000, 0.244766, 0.000000,2274.000000,195.000000, 0.224438, 0.000000,5389.000000,221.000000, 0.234751, 0.000000,4100.000000,156.000000, 0.224505, 0.000000,95.000000,191.000000, 0.214761, 0.000000,570.000000,62.000000,-0.207912, 0.000000,303.000000,113.000000, 0.224903, 0.000000,7335.000000,88.000000,-0.225694, 0.000000,268.000000,128.000000, 0.212380, 0.000000,5580.000000,193.000000, 0.184738, 0.000000,7362.000000,62.000000,-0.215452, 0.000000,3290.000000,206.000000, 0.189538, 0.000000,3065.000000,225.000000,-0.187511, 0.000000,996.000000,31.000000,-0.202382, 0.000000,3175.000000,245.000000, 0.186089, 0.000000,446.000000,26.000000, 0.197077, 0.000000,5027.000000, 1.000000,-0.189798, 0.000000,1611.000000,56.000000, 0.185341, 0.000000,2553.000000,241.000000, 0.194732, 0.000000,2595.000000,143.000000,-0.179444, 0.000000,4151.000000,60.000000,-0.141295, 0.000000,74.000000,192.000000, 0.181271, 0.000000,350.000000,56.000000, 0.179354, 0.000000,5575.000000,63.000000,-0.188858, 0.000000,8417.000000,223.000000, 0.184274, 0.000000,2726.000000,215.000000,-0.205059, 0.000000,8090.000000, 3.000000,-0.188663, 0.000000,619.000000,159.000000,-0.184901, 0.000000,273.000000,221.000000, 0.177643, 0.000000,1299.000000,96.000000,-0.153172, 0.000000,7658.000000,193.000000, 0.182067, 0.000000,3161.000000,36.000000, 0.179439, 0.000000,5600.000000,14.000000,-0.192280, 0.000000,6205.000000,119.000000,-0.131479, 0.000000,2318.000000,223.000000, 0.156541, 0.000000,184.000000,31.000000, 0.173775, 0.000000,193.000000,240.000000, 0.178032, 0.000000,5782.000000,64.000000,-0.151024, 0.000000,3539.000000,226.000000,-0.187696, 0.000000,1139.000000,227.000000, 0.179310, 0.000000,2447.000000,156.000000, 0.170499, 0.000000,822.000000,212.000000,-0.178263, 0.000000,6274.000000,68.000000,-0.181376, 0.000000,4037.000000,193.000000, 0.167209, 0.000000,2422.000000,192.000000, 0.167217, 0.000000,1309.000000,192.000000, 0.168216, 0.000000,3801.000000,63.000000,-0.170634, 0.000000,67.000000,215.000000,-0.171848, 0.000000,5999.000000,248.000000, 0.172926, 0.000000,207.000000,32.000000, 0.158846, 0.000000,4362.000000, 4.000000,-0.172901, 0.000000,163.000000,56.000000, 0.180091, 0.000000,910.000000,223.000000, 0.179276, 0.000000,394.000000,219.000000,-0.157030, 0.000000,315.000000,240.000000, 0.167899, 0.000000,302.000000,111.000000, 0.168984, 0.000000,8144.000000,62.000000,-0.130941, 0.000000,352.000000,196.000000,-0.160475, 0.000000,6015.000000,248.000000, 0.163526, 0.000000,327.000000,56.000000, 0.159658, 0.000000,3343.000000,100.000000,-0.159380, 0.000000,2770.000000,28.000000, 0.155594, 0.000000,3418.000000, 8.000000,-0.171566, 0.000000,1031.000000,152.000000,-0.158116, 0.000000,1224.000000,191.000000, 0.173054, 0.000000,5586.000000,62.000000,-0.144778, 0.000000,4734.000000,163.000000, 0.163755, 0.000000,306.000000,60.000000, 0.158639, 0.000000,3168.000000,39.000000,-0.163906, 0.000000,4161.000000,193.000000, 0.155211, 0.000000,6779.000000,39.000000, 0.161238, 0.000000,2617.000000,107.000000,-0.162070, 0.000000,2218.000000,224.000000, 0.160180, 0.000000,774.000000,120.000000, 0.158661, 0.000000,3834.000000,60.000000,-0.147024, 0.000000,2130.000000,207.000000, 0.169375, 0.000000,3082.000000,226.000000,-0.167427, 0.000000,406.000000,192.000000, 0.158246, 0.000000,295.000000,205.000000, 0.153665, 0.000000,330.000000,201.000000,-0.159461, 0.000000,173.000000,224.000000, 0.169945, 0.000000,1157.000000,140.000000,-0.147730, 0.000000,5520.000000,32.000000,-0.146256, 0.000000,2092.000000,63.000000,-0.160068, 0.000000,792.000000,120.000000, 0.156527, 0.000000,117.000000,239.000000, 0.129437, 0.000000,2402.000000,26.000000, 0.154331, 0.000000};
	struct opts options;
    char *yest;
	double *fx;
	int i , d , N;
	mxArray *mxtemp;
	double *tmp;
	int tempint;
	
	options.weaklearner  = 2; 
	options.cascade_type = 0;
	options.Ncascade     = 1;
	options.T            = 100;
	options.transpose    = 0;
	
    /* Input 1  */
	
	if( (mxGetNumberOfDimensions(prhs[0]) !=2) || !mxIsSingle(prhs[0]) )
	{	
		mexErrMsgTxt("X must be (d x N) or (N x d) in SINGLE format");	
	}
	X           = (float *)mxGetData(prhs[0]);
	d           = mxGetM(prhs[0]);
	N           = mxGetN(prhs[0]);
	
	/* Input 2  */

	if ((nrhs > 1) && !mxIsEmpty(prhs[1]) )
	{
		mxtemp                             = mxGetField( prhs[1] , 0, "param" );
		if(mxtemp != NULL)
		{
			if (mxGetM(mxtemp) != 4)
			{	
				mexErrMsgTxt("model must be (4 x T) matrix");	
			}
			options.param                     = mxGetPr(mxtemp);
			options.T                         = mxGetN(mxtemp);
		}
		else
		{
			options.param                 = (double *)mxMalloc(400*sizeof(double));	
			for(i = 0 ; i < 400 ; i++)
			{
				options.param[i]          = param_default[i];	
			}	
			options.T                     = 100;
		}

		mxtemp                            = mxGetField( prhs[1] , 0, "weaklearner" );
		if(mxtemp != NULL)
		{
			tmp                           = mxGetPr(mxtemp);			
			tempint                       = (int) tmp[0];

			if((tempint < 0) || (tempint > 3))
			{
				mexPrintf("weaklearner = {0,1,2}, force to 2");		
				options.weaklearner       = 2;
			}
			else
			{
				options.weaklearner       = tempint;	
			}			
		}

		mxtemp                            = mxGetField( prhs[1] , 0, "cascade_type" );
		if(mxtemp != NULL)
		{
			tmp                           = mxGetPr(mxtemp);	
			tempint                       = (int) tmp[0];
			
			if((tempint < 0) || (tempint > 1))
			{
				options.cascade_type      = 0;	
			}
			else
			{
				options.cascade_type      = tempint;	
			}			
		}

		mxtemp                            = mxGetField( prhs[1] , 0, "transpose" );
		if(mxtemp != NULL)
		{
			tmp                           = mxGetPr(mxtemp);			
			tempint                       = (int) tmp[0];

			if((tempint < 0) || (tempint > 1))
			{
				mexPrintf("transpose = {0,1}, force to 0");		
				options.transpose         = 0;
			}
			else
			{
				options.transpose         = tempint;	
			}			
		}

		mxtemp                            = mxGetField( prhs[1] , 0, "cascade" );
		if(mxtemp != NULL)
		{
			if(mxGetM(mxtemp) != 2)
			{
				mexErrMsgTxt("cascade must be (2 x Ncascade)");		
			}

			options.cascade               = mxGetPr(mxtemp );
			options.Ncascade              = mxGetN(mxtemp);
			for(i = 0 ; i < 2*options.Ncascade ; i=i+2)
			{
				Tcascade         += (int) options.cascade[i];
			}

			if(Tcascade > options.T)
			{
				mexErrMsgTxt("sum(cascade(1 , :)) <= T");
			}
		}
		else
		{
			options.cascade                           = (double *)mxMalloc(2*sizeof(double));
			options.cascade[0]                        = (double) options.T;
			options.cascade[1]                        = 0.0;		
		}	
	}
	else
	{
		options.param                                 = (double *)mxMalloc(400*sizeof(double));	
		for(i = 0 ; i < 400 ; i++)
		{
			options.param[i]                          = param_default[i];	
		}	
		options.T                                     = 100;

		options.cascade               = (double *)mxMalloc(2*sizeof(double));
		options.cascade[0]            = (double) options.T;
		options.cascade[1]            = 0.0;		
	}
	
  /*----------------------- Outputs -------------------------------*/	

	/* Output 1  */

	if(options.transpose)
	{

		dimsyest                              = (int *)mxMalloc(2*sizeof(int));	
		dimsyest[0]                           = 1;
		dimsyest[1]                           = d;
		plhs[0]                               = mxCreateNumericArray(2 , dimsyest , mxINT8_CLASS , mxREAL);
		yest                                  = (char *)mxGetPr(plhs[0]);

		/* Output 2  */

		plhs[1]                               =  mxCreateNumericMatrix(1 , d, mxDOUBLE_CLASS, mxREAL);
		fx                                    =  mxGetPr(plhs[1]);

		/*------------------------ Main Call ----------------------------*/

		adaboost_binary_model_cascade(X , N , d , options , yest , fx );

	}
	else
	{
		dimsyest                              = (int *)mxMalloc(2*sizeof(int));	
		dimsyest[0]                           = 1;
		dimsyest[1]                           = N;
		plhs[0]                               = mxCreateNumericArray(2 , dimsyest , mxINT8_CLASS , mxREAL);
		yest                                  = (char *)mxGetPr(plhs[0]);


		/* Output 2  */


		plhs[1]                               =  mxCreateNumericMatrix(1 , N, mxDOUBLE_CLASS, mxREAL);
		fx                                    =  mxGetPr(plhs[1]);


		/*------------------------ Main Call ----------------------------*/

		adaboost_binary_model_cascade(X , d , N , options , yest , fx );

	}
		
   /*--------------------------- Free memory -----------------------*/
	
	if ((nrhs > 1) && !mxIsEmpty(prhs[1]) )
	{
		if ( mxGetField( prhs[1] , 0 , "param" ) == NULL )	
		{
			mxFree(options.param);
		}

		if ( mxGetField( prhs[1] , 0 , "cascade" ) == NULL )	
		{
			mxFree(options.cascade);
		}
	}
	else
	{
		mxFree(options.param);
		mxFree(options.cascade);
	}	
	
	mxFree(dimsyest);	
}
示例#21
0
/* Main mex gateway routine */
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] )   { 
    
    integer iprint = (integer)1;
    integer task=(integer)START, csave=(integer)1;
    integer iterations = 0;
    integer total_iterations = 0;

    int  iterMax = 100;
    int  total_iterMax = 200;


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

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

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


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


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


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

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

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

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

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


        if ( IS_FG(task) ) {

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

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

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

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

    }

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

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

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

    return;
}
示例#22
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
	{

//	mexPrintf("\nin sim_create\n");

	// sizeof(long long) == sizeof(void *) = 64 !!!
	long long *ptr;
	int ii;



	/* RHS */

	// model

	bool
		set_nu = false,
		set_nx = false,
		set_T = false,
		set_x = false,
		set_u = false;

	int nu, nx;
	double T;
	double *x, *u;

	if(mxGetField( prhs[0], 0, "dim_nx" )!=NULL)
		{
		set_nx = true;
		nx = mxGetScalar( mxGetField( prhs[0], 0, "dim_nx" ) );
		}
	if(mxGetField( prhs[0], 0, "dim_nu" )!=NULL)
		{
		set_nu = true;
		nu = mxGetScalar( mxGetField( prhs[0], 0, "dim_nu" ) );
		}
	if(mxGetField( prhs[0], 0, "T" )!=NULL)
		{
		set_T = true;
		T = mxGetScalar( mxGetField( prhs[0], 0, "T" ) );
		}
	if(mxGetField( prhs[0], 0, "x" )!=NULL)
		{
		set_x = true;
		x = mxGetPr( mxGetField( prhs[0], 0, "x" ) );
		}
	if(mxGetField( prhs[0], 0, "u" )!=NULL)
		{
		set_u = true;
		u = mxGetPr( mxGetField( prhs[0], 0, "u" ) );
		}


	// opts_struct

	//
	int num_stages = mxGetScalar( mxGetField( prhs[1], 0, "num_stages" ) );
	//
	int num_steps = mxGetScalar( mxGetField( prhs[1], 0, "num_steps" ) );
	//
	bool sens_forw;
	char *c_ptr = mxArrayToString( mxGetField( prhs[1], 0, "sens_forw" ) );
	if (!strcmp(c_ptr, "true"))
		sens_forw = true;
	else
		sens_forw = false;
//	mexPrintf("\n%d\n", sens_forw);
	//
	char *method = mxArrayToString( mxGetField( prhs[1], 0, "method" ) );
//	mexPrintf("\n%s\n", method);



	/* LHS */

	// field names of output struct
	char *fieldnames[6];
	fieldnames[0] = (char*)mxMalloc(50);
	fieldnames[1] = (char*)mxMalloc(50);
	fieldnames[2] = (char*)mxMalloc(50);
	fieldnames[3] = (char*)mxMalloc(50);
	fieldnames[4] = (char*)mxMalloc(50);
	fieldnames[5] = (char*)mxMalloc(50);

	memcpy(fieldnames[0],"config",sizeof("config"));
	memcpy(fieldnames[1],"dims",sizeof("dims"));
	memcpy(fieldnames[2],"opts",sizeof("opts"));
	memcpy(fieldnames[3],"in",sizeof("in"));
	memcpy(fieldnames[4],"out",sizeof("out"));
	memcpy(fieldnames[5],"solver",sizeof("solver"));

	// create output struct
	plhs[0] = mxCreateStructMatrix(1, 1, 6, (const char **) fieldnames);

	mxFree( fieldnames[0] );
	mxFree( fieldnames[1] );
	mxFree( fieldnames[2] );
	mxFree( fieldnames[3] );
	mxFree( fieldnames[4] );
	mxFree( fieldnames[5] );



	/* plan & config */
	sim_solver_plan plan;

	if(!strcmp(method, "erk"))
		{
//		mexPrintf("\n%s\n", method);
		plan.sim_solver = ERK;
		}
	else if(!strcmp(method, "irk"))
		{
//		mexPrintf("\n%s\n", method);
		plan.sim_solver = IRK;
		}
	else
		{
		mexPrintf("\nmethod not supported %s\n", method);
		return;
		}

	sim_config *config = sim_config_create(plan);


	/* dims */
	void *dims = sim_dims_create(config);
	if(set_nx)
		sim_dims_set(config, dims, "nx", &nx);
	if(set_nu)
		sim_dims_set(config, dims, "nu", &nu);


	/* opts */
	sim_opts *opts = sim_opts_create(config, dims);
	sim_opts_set(config, opts, "num_stages", &num_stages);
	sim_opts_set(config, opts, "num_steps", &num_steps);
	sim_opts_set(config, opts, "sens_forw", &sens_forw);

	/* in */
	sim_in *in = sim_in_create(config, dims);
	if(sens_forw==true)
		{
//		mexPrintf("\nsens forw true!\n");
		double *Sx = calloc(nx*nx, sizeof(double));
		for(ii=0; ii<nx; ii++)
			Sx[ii*(nx+1)] = 1.0;
		double *Su = calloc(nx*nu, sizeof(double));
//		d_print_mat(nx, nx, Sx, nx);
//		d_print_mat(nx, nu, Su, nx);
		sim_in_set(config, dims, in, "Sx", Sx);
		sim_in_set(config, dims, in, "Su", Su);
		free(Sx);
		free(Su);
		}
	if(set_T)
		{
		sim_in_set(config, dims, in, "T", &T);
		}
	if(set_x)
		{
		sim_in_set(config, dims, in, "x", x);
		}
	if(set_u)
		{
		sim_in_set(config, dims, in, "u", u);
		}


	/* out */
	sim_out *out = sim_out_create(config, dims);


	/* solver */
	sim_solver *solver = sim_solver_create(config, dims, opts);



	/* populate output struct */

	// config
	mxArray *config_mat  = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
	ptr = mxGetData(config_mat);
	ptr[0] = (long long) config;
	mxSetField(plhs[0], 0, "config", config_mat);

	// dims
	mxArray *dims_mat  = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
	ptr = mxGetData(dims_mat);
	ptr[0] = (long long) dims;
	mxSetField(plhs[0], 0, "dims", dims_mat);

	// opts
	mxArray *opts_mat  = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
	ptr = mxGetData(opts_mat);
	ptr[0] = (long long) opts;
	mxSetField(plhs[0], 0, "opts", opts_mat);

	// in
	mxArray *in_mat  = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
	ptr = mxGetData(in_mat);
	ptr[0] = (long long) in;
	mxSetField(plhs[0], 0, "in", in_mat);

	// out
	mxArray *out_mat  = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
	ptr = mxGetData(out_mat);
	ptr[0] = (long long) out;
	mxSetField(plhs[0], 0, "out", out_mat);

	// solver
	mxArray *solver_mat  = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
	ptr = mxGetData(solver_mat);
	ptr[0] = (long long) solver;
	mxSetField(plhs[0], 0, "solver", solver_mat);



	/* return */
	return;

	}
示例#23
0
void TaylormapPass3(double *r_in, double le, int no, int nv,
                        double *x, int nx, double *px, int npx,
                        double *y, int ny, double *py, int npy,
                        double *delta, int ndelta, double *t, int nt,
                        double *T1, double *T2,
                        double *R1, double *R2, int num_particles)
/*
   r_in -- 6-by-N matrix of initial conditions reshaped into 
           1-d array of 6*N elements 
   le -- physical length
   no -- order of the Taylor map
   nv -- number of variables in the input
   x -- Taylor map of final x
   nx -- number of monomials in the map x
   px -- Taylor map of final px
   npx -- number of monomials in the map px
   y -- Taylor map of final y
   ny -- number of monomials in the map y
   py -- Taylor map of final py
   npy -- number of monomials in the map py
   delta -- Taylor map of final delta p / p
   ndelta -- number of monomials in the map delta
   t -- Taylor map of final t
   nt -- number of monomials in the map t
   T1 -- 6 x 1 translation at entrance
   T2 -- 6 x 1 translation at exit
   R1 -- 6 x 6 rotation matrix at the entrance
   R2 -- 6 x 6 rotation matrix at the exit
   num_particles -- number of particles
*/
#define NUM_COLUMNS 9
{
 int c,i,j,itmp;
 int *ptmpx;
 int *ptmppx;
 int *ptmpy;
 int *ptmppy;
 int *ptmpdelta;
 int *ptmpt;
 double *r6; 
 double *rtmp;
 double tmp;
 double *product;

 rtmp = (double*)mxCalloc(6,sizeof(double));
 ptmpx = (int*)mxCalloc(nx,sizeof(int));
 ptmppx = (int*)mxCalloc(npx,sizeof(int));
 ptmpy = (int*)mxCalloc(ny,sizeof(int));
 ptmppy = (int*)mxCalloc(npy,sizeof(int));
 ptmpdelta = (int*)mxCalloc(ndelta,sizeof(int));
 ptmpt = (int*)mxCalloc(nt,sizeof(int));
 product = (double*)mxCalloc( (int)pow(no+1,nv),sizeof(double));

 for(c = 0;c<num_particles;c++) {
  r6 = r_in+c*6;
  for(i=0;i<6;i++) {
   rtmp[i] = r6[i];
   r6[i] = 0;
  }

  /* linearized misalignment transformation at the entrance */
  ATaddvv(rtmp,T1);
  ATmultmv(rtmp,R1);

  /* Taylor map */

  for(i=0;i<((int)pow(no+1,nv));i++) {
   product[i] = 0;
  }

  product[0] = 1;
  itmp = 1;
  for(i=0;i<nv;i++) {
   tmp = 1;
   for(j=0;j<no;j++) {
    tmp *= rtmp[i];
    product[(j+1)*itmp] = tmp;
   }
   itmp *= no+1;
  }

  /* x */
  for(i=0;i<nx;i++) {
   itmp = 1;
   ptmpx[i] = 0;
   for(j=0;j<nv;j++) {
    ptmpx[i] += (int)x[i+(j+3)*nx]*itmp;
    itmp *= no+1;
   }
   if (product[ptmpx[i]]==0) {
    itmp = 1;
    tmp = 1;
    for(j=0;j<nv;j++) {
     if ((int)x[i+(j+3)*nx]>0) {
      tmp *= product[(int)x[i+(j+3)*nx]*itmp];
     }
     itmp *= no+1;
    }
    product[ptmpx[i]] = tmp;
   }
  }
  /* px */
  for(i=0;i<npx;i++) {
   itmp = 1;
   ptmppx[i] = 0;
   for(j=0;j<nv;j++) {
    ptmppx[i] += (int)px[i+(j+3)*npx]*itmp;
    itmp *= no+1;
   }
   if (product[ptmppx[i]]==0) {
    itmp = 1;
    tmp = 1;
    for(j=0;j<nv;j++) {
     if ((int)px[i+(j+3)*npx]>0) {
      tmp *= product[(int)px[i+(j+3)*npx]*itmp];
     }
     itmp *= no+1;
    }
    product[ptmppx[i]] = tmp;
   }
  }
  /* y */
  for(i=0;i<ny;i++) {
   itmp = 1;
   ptmpy[i] = 0;
   for(j=0;j<nv;j++) {
    ptmpy[i] += (int)y[i+(j+3)*ny]*itmp;
    itmp *= no+1;
   }
   if (product[ptmpy[i]]==0) {
    itmp = 1;
    tmp = 1;
    for(j=0;j<nv;j++) {
     if ((int)y[i+(j+3)*ny]>0) {
      tmp *= product[(int)y[i+(j+3)*ny]*itmp];
     }
     itmp *= no+1;
    }
    product[ptmpy[i]] = tmp;
   }
  }
  /* py */
  for(i=0;i<npy;i++) {
   itmp = 1;
   ptmppy[i] = 0;
   for(j=0;j<nv;j++) {
    ptmppy[i] += (int)py[i+(j+3)*npy]*itmp;
    itmp *= no+1;
   }
   if (product[ptmppy[i]]==0) {
    itmp = 1;
    tmp = 1;
    for(j=0;j<nv;j++) {
     if ((int)py[i+(j+3)*npy]>0) {
      tmp *= product[(int)py[i+(j+3)*npy]*itmp];
     }
     itmp *= no+1;
    }
    product[ptmppy[i]] = tmp;
   }
  }
  /* delta */
  for(i=0;i<ndelta;i++) {
   itmp = 1;
   ptmpdelta[i] = 0;
   for(j=0;j<nv;j++) {
    ptmpdelta[i] += (int)delta[i+(j+3)*ndelta]*itmp;
    itmp *= no+1;
   }
   if (product[ptmpdelta[i]]==0) {
    itmp = 1;
    tmp = 1;
    for(j=0;j<nv;j++) {
     if ((int)delta[i+(j+3)*ndelta]>0) {
      tmp *= product[(int)delta[i+(j+3)*ndelta]*itmp];
     }
     itmp *= no+1;
    }
    product[ptmpdelta[i]] = tmp;
   }
  }
  /* t */
  for(i=0;i<nt;i++) {
   itmp = 1;
   ptmpt[i] = 0;
   for(j=0;j<nv;j++) {
    ptmpt[i] += (int)t[i+(j+3)*nt]*itmp;
    itmp *= no+1;
   }
   if (product[ptmpt[i]]==0) {
    itmp = 1;
    tmp = 1;
    for(j=0;j<nv;j++) {
     if ((int)t[i+(j+3)*nt]>0) {
      tmp *= product[(int)t[i+(j+3)*nt]*itmp];
     }
     itmp *= no+1;
    }
    product[ptmpt[i]] = tmp;
   }
  }


  /* x final */
  for(i=0;i<nx;i++) {
   tmp = x[i+1*nx]*product[ptmpx[i]];
   r6[0] += tmp;
  }

  /* px final */
  for(i=0;i<npx;i++) {
   tmp = px[i+1*npx]*product[ptmppx[i]];
   r6[1] += tmp;
  }

  /* y final */
  for(i=0;i<ny;i++) {
   tmp = y[i+1*ny]*product[ptmpy[i]];
   r6[2] += tmp;
  }

  /* py final */
  for(i=0;i<npy;i++) {
   tmp = py[i+1*npy]*product[ptmppy[i]];
   r6[3] += tmp;
  }

  /* delta final */
  for(i=0;i<ndelta;i++) {
   tmp = delta[i+1*ndelta]*product[ptmpdelta[i]];
   r6[4] += tmp;
  }

  /* t final */
  for(i=0;i<nt;i++) {
   tmp = t[i+1*nt]*product[ptmpt[i]];
   r6[5] += tmp;
  }

  /* linearized misalignment transformation at the exit */
  ATmultmv(r6,R2);
  ATaddvv(r6,T2);
 }
 mxFree(rtmp);
 mxFree(ptmpx);
 mxFree(ptmppx);
 mxFree(ptmpy);
 mxFree(ptmppy);
 mxFree(ptmpdelta);
 mxFree(ptmpt);
 mxFree(product);
}
示例#24
0
void mexFunction(int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[])
{
    double *V;
    mwSize V_ndims;
    mwSize *V_dims;
    double *SRC;
    mwSize SRC_ndims;
    mwSize *SRC_dims;
    double *H;
    mwSize H_ndims;
    mwSize *H_dims;
    double EPS, MAX_ITER;
    double *U;
    char *LSM_UNLOCKED;
    int max_iter_int, it, converged;
    size_t NI, NJ, NK;
    double SRCI, SRCJ, SRCK, HI, HJ, HK;
    
    OPENST_MEX_CHECK((nrhs < 5), "Not enough input arguments.");
    OPENST_MEX_CHECK((nrhs > 5), "Too many input arguments.");
    OPENST_MEX_CHECK((nlhs < 3), "Not enough output arguments.");
    OPENST_MEX_CHECK((nlhs > 3), "Too many output arguments.");
    
    OPENST_MEX_CHECK((OPENST_MEX_GetDoubleArray(prhs[0], &V,
            &V_ndims, &V_dims)), NULL);
    OPENST_MEX_CHECK((V_ndims != 3), "V must be 3D.");
    
    OPENST_MEX_CHECK((OPENST_MEX_GetDoubleArray(prhs[1], &SRC, &SRC_ndims,
            &SRC_dims)), NULL);
    OPENST_MEX_CHECK((OPENST_MEX_GetNumel(SRC_ndims, SRC_dims) != 3),
            "numel(SRC) must be 3.");
    
    OPENST_MEX_CHECK((OPENST_MEX_GetDoubleArray(prhs[2], &H, &H_ndims,
            &H_dims)), NULL);
    OPENST_MEX_CHECK((OPENST_MEX_GetNumel(H_ndims, H_dims) != 3),
            "numel(H) must be 3.");
    
    OPENST_MEX_CHECK((OPENST_MEX_GetDoubleScalar(prhs[3], &EPS)),
            NULL);
    
    OPENST_MEX_CHECK((OPENST_MEX_GetDoubleScalar(prhs[4], &MAX_ITER)),
            NULL);
    OPENST_MEX_CHECK(!OPENST_MEX_ValueIsInteger(MAX_ITER),
            "MAX_ITER must be an integer value.");
    
    NI = V_dims[2];
    NJ = V_dims[1];
    NK = V_dims[0];
    HI = H[0];
    HJ = H[1];
    HK = H[2];
    SRCI = SRC[0];
    SRCJ = SRC[1];
    SRCK = SRC[2];
    
    OPENST_MEX_CHECK(((plhs[0] =
            mxCreateNumericArray(3, V_dims, mxDOUBLE_CLASS,
            mxREAL)) == NULL), NULL);
    OPENST_MEX_CHECK(((U = mxGetPr(plhs[0])) == NULL), NULL);
    
    OPENST_MEX_CHECK(((LSM_UNLOCKED = mxMalloc(NI * NJ * NK *
            sizeof(double))) == NULL), NULL);
    
    OPENST_MEX_CHECK(((OpenST_LSM3D(U, LSM_UNLOCKED, V,
            NI, NJ, NK,
            HI, HJ, HK,
            SRCI, SRCJ, SRCK,
            EPS, (int) MAX_ITER,
            &it, &converged)
            != OPENST_ERR_SUCCESS)), "OpenST_LSM3D Error");
    
    OPENST_MEX_CHECK(((plhs[1] =
            mxCreateDoubleScalar((double) converged)) == NULL), NULL);
    
    OPENST_MEX_CHECK(((plhs[2] =
            mxCreateDoubleScalar((double) it)) == NULL), NULL);
    
    mxFree(LSM_UNLOCKED);
    
}
/* The gateway routine */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
/* ----------------- Variables ----------------- */
/* input variables */
/* mandatory input */
  int startIdx;
  int endIdx;
  double * open;
  double * high;
  double * low;
  double * close;
/* optional input */
  double	 optInPenetration;
/* output variables */ 
  int outBegIdx;
  int outNbElement;
  int*	 outInteger;
/* input dimentions */ 
  int inSeriesRows;
  int inSeriesCols;
/* error handling */
  TA_RetCode retCode;

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

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

/* ----------------- OUTPUT ----------------- */
  outInteger = mxCalloc(inSeriesRows, sizeof(int));
/* -------------- Invocation ---------------- */

	retCode = TA_CDLEVENINGSTAR(
                   startIdx, endIdx,
                   open,
                   high,
                   low,
                   close,
                   optInPenetration,
                   &outBegIdx, &outNbElement,
                   outInteger);
/* -------------- Errors ---------------- */
   if (retCode) {
   	   mxFree(outInteger);
       mexPrintf("%s%i","Return code=",retCode);
       mexErrMsgTxt(" Error!");
   }
  
   // Populate Output
  plhs[0] = mxCreateNumericMatrix(outBegIdx+outNbElement,1, mxINT32_CLASS, mxREAL);
  memcpy(((int *) mxGetData(plhs[0]))+outBegIdx, outInteger, outNbElement*mxGetElementSize(plhs[0]));
  mxFree(outInteger);  
} /* END mexFunction */
示例#26
0
/* Function: mdlJacobian ======================================================
 * Abstract: populate the model's Jacobian data.
 * See the on-line documentation for mxCreateSparse for
 * information regarding the format of Ir, Jc, and Pr data.
 *
 *        [ A | B ]    
 *  J =   [ --+-- ]  (= D here)
 *        [ C | D ]  
 *                 
 */
static void mdlJacobian(SimStruct *S)
{
    #if defined(MATLAB_MEX_FILE)
    real_T      *Pr     = ssGetJacobianPr(S);
	real_T		*out;
	real_T		*temp;
    uint_T      nr      = (uint_T) mxGetScalar(NUMREG(S));
    ParStruc    *Par    = ssGetUserData(S);
    const real_T      *Reg    = ssGetInputPortRealSignal(S,0); /* input signals are contiguous */
    int_T		k;
    mxArray *plhs;
    mxArray *prhs[3];
    mxArray *ParStruct, *TreeParStruct;
    mxArray *TypeStr;
    const char **fnamesPar;
    const char **fnamesTree;
    
    /* plhs            = mxCreateDoubleMatrix(1,nr,mxREAL); */
    TypeStr         = mxCreateString("treepartition");
    fnamesPar       = mxCalloc(8, sizeof(*fnamesPar));
    fnamesTree      = mxCalloc(5, sizeof(*fnamesTree));
       
     /* memory error check */
    if ( (fnamesPar==NULL) || (fnamesTree==NULL) || (TypeStr==NULL) || (prhs==NULL)){
        ssSetErrorStatus(S, "Could not allocate memory for Jacobian computation.");
        return;
    }
    
    /* Tree struct field names */
    fnamesTree[0] = "TreeLevelPntr";
    fnamesTree[1] = "AncestorDescendantPntr";
    fnamesTree[2] = "LocalizingVectors";
    fnamesTree[3] = "LocalCovMatrix";
    fnamesTree[4] = "LocalParVector";
    
    /* Parameter struct field names */
    fnamesPar[0] = "NumberOfUnits";
    fnamesPar[1] = "Threshold";
    fnamesPar[2] = "RegressorMean";
    fnamesPar[3] = "OutputOffset";
    fnamesPar[4] = "LinearCoef";
    fnamesPar[5] = "SampleLength";
    fnamesPar[6] = "NoiseVariance";
    fnamesPar[7] = "Tree";
    
    TreeParStruct   = mxCreateStructMatrix(1,1,5,fnamesTree);
    ParStruct       = mxCreateStructMatrix(1,1,8,fnamesPar);
    
    /* do memory error check */
    if ((TreeParStruct==NULL) || (ParStruct==NULL)){
        ssSetErrorStatus(S, "Could not allocate memory for Jacobian computation.");
        return;
    }
    
    /* set fields of Parameters.Tree struct */
    mxSetFieldByNumber(TreeParStruct, 0, 0, mxDuplicateArray(TREE_TREELEVELPNTR(S)));
    mxSetFieldByNumber(TreeParStruct, 0, 1, mxDuplicateArray(TREE_ANCESTORDESCENDANTPNTR(S)));
    mxSetFieldByNumber(TreeParStruct, 0, 2, mxDuplicateArray(TREE_LOCALIZINGVECTORS(S)));
    mxSetFieldByNumber(TreeParStruct, 0, 3, mxDuplicateArray(TREE_LOCALCOVMATRIX(S)));
    mxSetFieldByNumber(TreeParStruct, 0, 4, mxDuplicateArray(TREE_LOCALPARVECTOR(S)));
    
    /* set fields of Paramater struct */
    mxSetFieldByNumber(ParStruct, 0, 0, mxDuplicateArray(NUMUNITS(S)));
    mxSetFieldByNumber(ParStruct, 0, 1, mxDuplicateArray(OPT_THRESHOLD(S)));
    mxSetFieldByNumber(ParStruct, 0, 2, mxDuplicateArray(PAR_REGRESSORMEAN(S)));
    mxSetFieldByNumber(ParStruct, 0, 3, mxDuplicateArray(PAR_OUTPUTOFFSET(S)));
    mxSetFieldByNumber(ParStruct, 0, 4, mxDuplicateArray(PAR_LINEARCOEF(S)));
    mxSetFieldByNumber(ParStruct, 0, 5, mxDuplicateArray(PAR_SAMPLELENGTH(S)));
    mxSetFieldByNumber(ParStruct, 0, 6, mxDuplicateArray(PAR_NOISEVARIANCE(S)));
    mxSetFieldByNumber(ParStruct, 0, 7, TreeParStruct);
	
	prhs[0] = mxCreateDoubleMatrix(1,nr,mxREAL);
    temp = mxGetPr(prhs[0]);
	for (k=0; k<nr; k++){
		temp[k] = Reg[k];
	}

	/* mxSetPr(prhs[0],Reg); */
    prhs[1] = ParStruct;
    prhs[2] = TypeStr;
    
    /* 
     * Call utEvalStateJacobian to compute the regressors 
     * M file: dydx = utEvalStateJacobian(x,par,type) 
     */
    
    mexCallMATLAB(1,&plhs,3,prhs,"utEvalStateJacobian");

    out = mxGetPr(plhs);
	for(k=0; k<nr; k++){
		Pr[k] = out[k];
	}
    
    mxFree((void *)fnamesTree);
    mxFree((void *)fnamesPar);
    mxDestroyArray(plhs);
    
	mxDestroyArray(prhs[0]);
	mxDestroyArray(TypeStr);
	mxDestroyArray(ParStruct);
    #endif
    
}
示例#27
0
//___________________________________________________________________________________
void mexFunction(int nOUT, mxArray *pOUT[],
				 int nINP, const mxArray *pINP[])
{
	
	int i;
	double *records_to_get, *range_to_get,*t,*wv, *all_timestamps;
	int n_records_to_get = 0;
	int record_units = 0;
	int nSpikesInFile = 0;
	int length_records_to_get = 0;	
	int start_idx=0;
	int end_idx = 0;
	int idx = 0;	
	/* check number of arguments: expects 1 input */
	if (nINP != 3 && nINP != 1)
				mexErrMsgTxt("Call with fn or fn and array of recs to load(vector), and 1(timestamp) or 2(record number	) as inputs.");
	if (nOUT > 2)
				mexErrMsgTxt("Requires two outputs (t, wv).");

	/* read inputs */
	int fnlen = (mxGetM(pINP[0]) * mxGetN(pINP[0])) + 1;
	char *fn = (char *) mxCalloc(fnlen, sizeof(char)); 
	if (!fn)
		mexErrMsgTxt("Not enough heap space to hold converted string.");
	int errorstatus = mxGetString(pINP[0], fn,fnlen);    
	if (errorstatus)
		mexErrMsgTxt("Could not convert string data.");


	nSpikesInFile = GetNumberOfSpikes(fn);
	////////////////////////////////////////////////////////
	// If only one input is passed, assume the whole file is
	// to be loaded. If only one output is present, assume it is
	// only timestamps.
	////////////////////////////////////////////////////////

	if(nINP == 1 && nOUT == 1)
	{
		/* Return the timestamps of all of the records */
			// create outputs 
		pOUT[0] = mxCreateDoubleMatrix(nSpikesInFile, 1, mxREAL);
		t = mxGetPr(pOUT[0]);

		// load tt file fn into t and wv arrays 
		ReadTT_timestamps(fn,nSpikesInFile,t);

		// cleanup
		mxFree(fn);
		return;

	}else if(nINP == 1 && nOUT == 2)
	{
		////////////////////////////////////////////////////////
		// create outputs 
		////////////////////////////////////////////////////////
		mexPrintf("Getting %i records.\n",nSpikesInFile);
		pOUT[0] = mxCreateDoubleMatrix(nSpikesInFile , 1, mxREAL);
		t = mxGetPr(pOUT[0]);
		int wvDims[] = {nSpikesInFile , 4, 32};    // wv = nSpikes x 4 x 32   FORTRAN (column major) array
		pOUT[1] = mxCreateNumericArray(3, wvDims, mxDOUBLE_CLASS, mxREAL);
		wv = mxGetPr(pOUT[1]);

		////////////////////////////////////////////////////////
		// load tt file fn into t and wv arrays 
		////////////////////////////////////////////////////////

		ReadTT(fn,nSpikesInFile ,t,wv);

		////////////////////////////////////////////////////////
		// cleanup
		////////////////////////////////////////////////////////

		mxFree(fn);
		return;
	}
	////////////////////////////////////////////////////////
	// unpack inputs 
	////////////////////////////////////////////////////////
	length_records_to_get = mxGetM(pINP[1]) * mxGetN(pINP[1]);
	records_to_get = mxGetPr(pINP[1]);
	record_units = (int) mxGetScalar(pINP[2]);

	switch(record_units)
	{
		case BY_TIMESTAMP:
			////////////////////////////////////////////////////////
			// Convert the timestamps into record numbers. This will
			// make loading these records easy.
			////////////////////////////////////////////////////////
			////////////////////////////////////////////////////////
			// Create a very large array of all of the timestamps
			////////////////////////////////////////////////////////
			n_records_to_get = length_records_to_get;
			all_timestamps = (double *)calloc( nSpikesInFile, sizeof( double ) );
			if (all_timestamps == NULL)
				mexErrMsgTxt("NOT ENOUGH MEMORY");
			range_to_get = (double *) calloc( n_records_to_get, sizeof( double ) );
			if (range_to_get == NULL)
				mexErrMsgTxt("NOT ENOUGH MEMORY");

			ReadTT_timestamps(fn,nSpikesInFile,all_timestamps);

			for (i = 0;i<n_records_to_get;i++)
			{
				idx = binsearch(nSpikesInFile, all_timestamps, &records_to_get[i]);
				range_to_get[i] = idx + 1; // Add one since records are assumed
											 // to be from 1 to end.
			}

			free(all_timestamps);
			break;

		case BY_RECORD:
			////////////////////////////////////////////////////////
			// Get records asked for. First, subract one since matlab
			// users typically think records as being ordered from 
			// 1 to ....
			////////////////////////////////////////////////////////

			n_records_to_get = length_records_to_get;
			range_to_get = records_to_get;
			break;

		case BY_TIMESTAMP_RANGE:

			////////////////////////////////////////////////////////
			// Error checking
			////////////////////////////////////////////////////////

			if(length_records_to_get != 2)
			{
				mexErrMsgTxt("Must pass in two arguements for parameter 2.");
				return;
			}

			////////////////////////////////////////////////////////
			// Create a very large array of all of the timestamps
			////////////////////////////////////////////////////////
			all_timestamps = (double *)calloc( nSpikesInFile, sizeof( double ) );
			if (all_timestamps == NULL)
				mexErrMsgTxt("NOT ENOUGH MEMORY");

			ReadTT_timestamps(fn,nSpikesInFile,all_timestamps);
			////////////////////////////////////////////////////////
			// Find the index in all_timestamps of the start record.
			////////////////////////////////////////////////////////

			start_idx = binsearch(nSpikesInFile, all_timestamps, &records_to_get[0]) + 1; // Add one since records are assumed
																					  	  // to be from 1 to end.

			////////////////////////////////////////////////////////
			// Find the index in all_timestamps of the end record.
			////////////////////////////////////////////////////////
			end_idx = binsearch(nSpikesInFile, all_timestamps, &records_to_get[1]) + 1;  // Add one since records are assumed
																				  	 // to be from 1 to end.


			free(all_timestamps);
			
			n_records_to_get = end_idx - start_idx + 1;
			////////////////////////////////////////////////////////
			// Allocate the space
			// Using ints would be much more efficient, but it would make it necessary
			// to rewrite the ReadTT program. I don't want to do that.
			////////////////////////////////////////////////////////

			range_to_get = (double *) calloc( n_records_to_get, sizeof( double ) );
			if (range_to_get == NULL)
			{
				mexErrMsgTxt("NOT ENOUGH MEMORY");
				return;
			}

			for (i = 0; i<n_records_to_get;i++)
				range_to_get[i] = start_idx + i;

			break;

		case BY_RECORD_RANGE:
			////////////////////////////////////////////////////////
			// This is easy. First check to make sure the user passed in
			// the proper number of arguements.
			////////////////////////////////////////////////////////
			if(length_records_to_get != 2)
			{
				mexErrMsgTxt("Must pass in a start and end record number for argument 2.");
				return;
			}
			start_idx = (int) records_to_get[0] ;
			end_idx   = (int) records_to_get[1] ;

			////////////////////////////////////////////////////////
			n_records_to_get = end_idx - start_idx + 1;
			////////////////////////////////////////////////////////
			// Allocate the space
			////////////////////////////////////////////////////////
			range_to_get = (double  *)calloc( n_records_to_get, sizeof( double  ) );
			if (range_to_get == NULL)
			{
				mexErrMsgTxt("NOT ENOUGH MEMORY");
				return;
			}
			for (i = 0; i<n_records_to_get;i++)
			{
				range_to_get[i] = start_idx + i;
			}
			break;
			
		case COUNTSPIKES: // ADR/NCST
			printf("Counting spikes.\n");
			pOUT[0] = mxCreateDoubleMatrix(1,1,mxREAL);
			t = mxGetPr(pOUT[0]);
			t[0] = nSpikesInFile;		
			break;

		default:
			mexErrMsgTxt("Incorrect parameter 3.");
	}
	if (!(record_units==COUNTSPIKES))
	{
		////////////////////////////////////////////////////////
		// Allocate the space
		////////////////////////////////////////////////////////
		printf("Getting %i records.\n",n_records_to_get);
		pOUT[0] = mxCreateDoubleMatrix(n_records_to_get, 1, mxREAL);
		t = mxGetPr(pOUT[0]);
		int wvDims[] = {n_records_to_get, 4, 32};    // wv = nSpikes x 4 x 32   FORTRAN (column major) array
		pOUT[1] = mxCreateNumericArray(3, wvDims, mxDOUBLE_CLASS, mxREAL);
		wv = mxGetPr(pOUT[1]);
		////////////////////////////////////////////////////////
		// Get the data. Record_units will whether to get by 
		// timestamp or by record number.
		////////////////////////////////////////////////////////
		ReadTTByRecord(fn,range_to_get,n_records_to_get,t,wv);

		// Free this variable only if it was not a matlab variable.
		if (record_units == BY_TIMESTAMP_RANGE || record_units == BY_RECORD_RANGE )
			free(range_to_get);
	}
	// cleanup
	mxFree(fn);

}
示例#28
0
文件: pswarmmex.c 项目: ZiiCee/OPTI
// Function definitions. 
// -----------------------------------------------------------------
void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{
    //Input Args         
    double *x0 = NULL, *lb = NULL, *ub = NULL, *A = NULL, *b = NULL;  
    
    //Outputs Args
    double *x, *fval, *exitflag, *iter, *feval;
    
    //Internal Vars
    double *llb, *lub;
    size_t ndec;   
    int i, exit_code;    
    
    //PSwarm Vars
    double *sol = NULL;
    int lincon = 0;

    if (nrhs < 1) {
        if(nlhs < 1)
            printSolverInfo();
        else
            plhs[0] = mxCreateString(PSWARM_VERSION);
        return;
    }
    
    //Check user inputs
    checkInputs(prhs,nrhs,&lincon);
    
    //Set Defaults    
    printLevel = 0;
    maxtime = 1000;
    noFeval = 0;
    ctrlCExit = false;
    iterF.enabled = false;
    //Reset Stats
    stats.solveriters = 0;
    stats.objfunctions = 0;
    stats.pollsteps = 0;
    stats.sucpollsteps = 0;
    //Set PSwarm Defaults
    opt.s = 42;
    opt.mu = 0.5; opt.nu = 0.5;
    opt.maxvfactor = 0.5; opt.maxiter = 1500;
    opt.maxf = 10000;       
    opt.iweight = 0.9; opt.fweight = 0.4;
    opt.n2grd = 0.5;
    opt.blim = 10;
    opt.tol = 1e-5;
    opt.delta = Inf; opt.fdelta = 5.0; opt.idelta = 2.0; opt.ddelta = 0.5;
    opt.pollbasis = 0; opt.EpsilonActive = 0.1;
    opt.IPrint = 10;    
    opt.vectorized = 0;     //important, otherwise will pass whole swarm
    opt.outfcn = &iterfcn;  //iteration + ctrl c

    //Get Sizes
    ndec = mxGetNumberOfElements(prhs[1]);
    //Get Objective Function Handle
    if (mxIsChar(prhs[0])) {
        CHECK(mxGetString(prhs[0], fun.f, FLEN) == 0,"error reading objective name string");
        fun.nrhs = 1;
        fun.xrhs = 0;
    } else {
        fun.prhs[0] = (mxArray*)prhs[0];
        strcpy(fun.f, "feval");
        fun.nrhs = 2;
        fun.xrhs = 1;
    }    

    //Get x0
    x0 = mxGetPr(prhs[1]);   
    
    //Get Bounds
    //LB
    if(!mxIsEmpty(prhs[2])){
        llb = mxGetPr(prhs[2]);
        lb = mxCalloc(ndec,sizeof(double));
        memcpy(lb,llb,ndec*sizeof(double));
        for(i=0;i<ndec;i++) {
            if(mxIsInf(lb[i]))
                lb[i] = -1e19;
        }
    }
    else {
        lb = mxCalloc(ndec,sizeof(double));
        for(i=0;i<ndec;i++)
            lb[i] = -1e19;
    }
    //UB
    if(nrhs > 3 && !mxIsEmpty(prhs[3])){
        lub = mxGetPr(prhs[3]);
        ub = mxCalloc(ndec,sizeof(double));
        memcpy(ub,lub,ndec*sizeof(double));
        for(i=0;i<ndec;i++) {
            if(mxIsInf(ub[i]))
                ub[i] = 1e19;
        }
    }
    else {
        ub = mxCalloc(ndec,sizeof(double));
        for(i=0;i<ndec;i++)
            ub[i] = 1e19;
    }
    
    //Get Linear Inequality Constraints
    if(nrhs > 4) {
        if(!mxIsEmpty(prhs[4]) && !mxIsEmpty(prhs[5])) {
            A = mxGetPr(prhs[4]);
            b = mxGetPr(prhs[5]);
        }
    }
    
    //Get Options if specified
    if(nrhs > 6) {
        if(mxGetField(prhs[6],0,"display"))
            printLevel = (int)*mxGetPr(mxGetField(prhs[6],0,"display"));
        if(mxGetField(prhs[6],0,"maxiter"))
            opt.maxiter = (int)*mxGetPr(mxGetField(prhs[6],0,"maxiter"));
        if(mxGetField(prhs[6],0,"maxtime"))
            maxtime = *mxGetPr(mxGetField(prhs[6],0,"maxtime"));
        if(mxGetField(prhs[6],0,"tolfun"))
            opt.tol = *mxGetPr(mxGetField(prhs[6],0,"tolfun"));
        if(mxGetField(prhs[6],0,"maxfeval"))
            opt.maxf = (int)*mxGetPr(mxGetField(prhs[6],0,"maxfeval"));
        if(mxGetField(prhs[6],0,"swarm_size"))
            opt.s = (int)*mxGetPr(mxGetField(prhs[6],0,"swarm_size"));
        if(mxGetField(prhs[6],0,"vectorized"))
            opt.vectorized = (int)*mxGetPr(mxGetField(prhs[6],0,"vectorized"));
        if(mxGetField(prhs[6],0,"mu"))
            opt.mu = *mxGetPr(mxGetField(prhs[6],0,"mu"));
        if(mxGetField(prhs[6],0,"nu"))
            opt.nu = *mxGetPr(mxGetField(prhs[6],0,"nu"));
        if(mxGetField(prhs[6],0,"iweight"))
            opt.iweight = *mxGetPr(mxGetField(prhs[6],0,"iweight"));
        if(mxGetField(prhs[6],0,"fweight"))
            opt.fweight = *mxGetPr(mxGetField(prhs[6],0,"fweight"));
        if(mxGetField(prhs[6],0,"delta"))
            opt.delta = *mxGetPr(mxGetField(prhs[6],0,"delta"));
        if(mxGetField(prhs[6],0,"idelta"))
            opt.idelta = *mxGetPr(mxGetField(prhs[6],0,"idelta"));
        if(mxGetField(prhs[6],0,"ddelta"))
            opt.ddelta = *mxGetPr(mxGetField(prhs[6],0,"ddelta"));
        if(mxGetField(prhs[6],0,"iterfun") && !mxIsEmpty(mxGetField(prhs[6],0,"iterfun")))
        {
            iterF.prhs[0] = (mxArray*)mxGetField(prhs[6],0,"iterfun");
            strcpy(iterF.f, "feval");
            iterF.enabled = true;  
            iterF.prhs[1] = mxCreateNumericMatrix(1,1,mxINT32_CLASS,mxREAL);
            iterF.prhs[2] = mxCreateDoubleMatrix(1,1,mxREAL);
            iterF.prhs[3] = mxCreateDoubleMatrix(ndec,1,mxREAL);
        }
    }       
    
    //If not vectorized, we can create x now, otherwise must be done in callback
    if(!opt.vectorized)
        fun.prhs[fun.xrhs] = mxCreateDoubleMatrix(ndec, 1, mxREAL);
    
    //Create Outputs
    plhs[0] = mxCreateDoubleMatrix(ndec,1, mxREAL);
    plhs[1] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[2] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[3] = mxCreateDoubleMatrix(1,1, mxREAL);
    plhs[4] = mxCreateDoubleMatrix(1,1, mxREAL);
    x = mxGetPr(plhs[0]); 
    fval = mxGetPr(plhs[1]); 
    exitflag = mxGetPr(plhs[2]);    
    iter = mxGetPr(plhs[3]);
    feval = mxGetPr(plhs[4]);

    //Print Header
    if(printLevel) {
        mexPrintf("\n------------------------------------------------------------------\n");
        mexPrintf(" This is PSwarm v1.5\n");
            
        mexPrintf(" Authors: A.I.F Vaz and L.N. Vicente\n\n");
        mexPrintf(" Problem Properties:\n");
        mexPrintf(" # Decision Variables:     %4d\n",ndec);
        mexPrintf(" # Linear Constraints:     %4d\n",lincon);

        mexPrintf("------------------------------------------------------------------\n");
    }
    
    //Run PSwarm
    start = clock();
    exit_code = PSwarm((int)ndec, &func, lb, ub, lincon, A, b, &sol, fval, x0);
    
    if(exit_code == 0) {
        //Copy Solution
        memcpy(x,sol,ndec*sizeof(double));
        free(sol);
        *iter = (double)stats.solveriters;
        *feval = (double)stats.objfunctions;
    }

    //Save Status & Iterations
    *exitflag = getStatus(exit_code,stats.solveriters,stats.objfunctions); 
    
    //Print Header
    if(printLevel){            
        //Termination Detected
        switch((int)*exitflag)
        {
            //Success
            case 1:
                mexPrintf("\n *** SUCCESSFUL TERMINATION ***\n *** Normal Exit ***\n"); break;
            //Error
            case -1:
                mexPrintf("\n *** ERROR: Abnormal Exit ***\n"); break;
            case 0:
                if(stats.solveriters >= (opt.maxiter-5))
                    mexPrintf("\n *** MAXIMUM ITERATIONS REACHED ***\n"); 
                else if(((double)(end-start))/CLOCKS_PER_SEC > maxtime)
                    mexPrintf("\n *** MAXIMUM TIME EXCEEDED ***\n");
                else
                    mexPrintf("\n *** MAXIMUM FUNCTION EVALUATIONS REACHED ***\n"); 
                
                break;
            //Early Exit
            case -2:
                mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: Failed to allocate memory ***\n"); break;
            case -3:
                mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: Unable to initialize population - check constraints are feasible ***\n"); break;
            case -5:
                mexPrintf("\n *** TERMINATION: EARLY EXIT ***\n *** CAUSE: User Exit (Ctrl C) ***\n"); break;
        }

        if(*exitflag==1)
            mexPrintf("\n Final Objective: %12.5g\n In %3d iterations and\n   %4d function evaluations\n",*fval,stats.solveriters,stats.objfunctions);

        mexPrintf("------------------------------------------------------------------\n\n");
    }
    
    //Free Memory
    if(lb) mxFree(lb);
    if(ub) mxFree(ub);    
}
//usage:feature = feaGen( training,depth,ndim);
//state:finishing
//version:v1
//notation: maximum size of buffer is 1024
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, mxArray * prhs[])
{
	// check the input parameter
	if (nlhs != 1)
		mexErrMsgTxt(" error in using feaGen, one output is needed");
	if (nrhs != 3)
		mexErrMsgTxt(" error in using feaGen, three input are needed");
	if (!mxIsCell(prhs[0]))
	{
		mexErrMsgTxt(" input type error");
	}

	mxArray * pp, *ptemp;
	mwSize M;
	mwSize depth, ndim;
	int i, j, k, m, n, intTemp;
	double *pointer;

	//get parameter
	depth = mxGetScalar(prhs[1]);
	ndim = mxGetScalar(prhs[2]);
	M = mxGetM(prhs[0]);
	//alloc the space

	char *buf = (char*) mxMalloc((unsigned int) (MAXSIZE) * sizeof(char));

	char ** fea;
	fea = (char**) mxMalloc((unsigned int) ndim * sizeof(char*));
	for (i = 0; i < ndim; i++)
	{
		fea[i] = (char*) mxMalloc((unsigned int) (MAXSIZE) * sizeof(char));
	}

	feature fv(ndim, depth, M);

	for (i = 0; i < M; i++)
	{
		fv.addLine();
		ptemp = mxGetCell(prhs[0], i);
		if (mxGetString(ptemp, buf, (unsigned int) MAXSIZE))
			mexErrMsgTxt("error in the buffer of this function:line53");
#ifdef debug
		mexPrintf("%s",buf);
#endif
		for (j = 0; buf[j] != '\0'; j++)
		{
			intTemp = char2num(buf[j]);
			for (int l = 0; l < ndim; l++)
			{

				fea[l][j] = (int)(intTemp & 0x1) + '0';
				intTemp >>= 1;
			}
		}

		int len = j;
#ifdef debug
		mexPrintf("%s",len);
#endif
		char *temp;
		temp = (char*) mxMalloc((ndim * depth + 1) * sizeof(char));
		for (j = 0; j <= len - depth; j++)
		{
			intTemp = 0;
			int mm, nn;
			for (nn = 0; nn < ndim; nn++)
			{
				for (mm = 0; mm < depth; mm++)
				{
					temp[intTemp++] = fea[nn][mm + j];
				}
			}
			*(temp + ndim * depth) = '\0';
			intTemp = ndim * depth;
			int index = to2num(temp, intTemp);
			if( index < 0 || index > power2(ndim,depth))
			{
				mexErrMsgTxt("error in input format line:90");
			}
			fv.store(index);
		}
		mxFree(temp);

	}

	mxFree(buf);
	for (i = 0; i < ndim; i++)
	{
		mxFree(fea[i]);
	}
	mxFree(fea);

	int lineSize = fv.getLineSize();
	plhs[0] = mxCreateDoubleMatrix(fv.getLen(), lineSize, mxREAL);
	pointer = mxGetPr(plhs[0]);
	fv.transaction(pointer);

}
const char *model_to_matlab_structure(mxArray *plhs[], struct model *model_)
{
	int i;
	int nr_w;
	double *ptr;
	mxArray *return_model, **rhs;
	int out_id = 0;
	int n, w_size;

	rhs = (mxArray **)mxMalloc(sizeof(mxArray *)*NUM_OF_RETURN_FIELD);

	// Parameters
	// for now, only solver_type is needed
	rhs[out_id] = mxCreateDoubleMatrix(1, 1, mxREAL);
	ptr = mxGetPr(rhs[out_id]);
	ptr[0] = model_->param.solver_type;
	out_id++;

	// nr_class
	rhs[out_id] = mxCreateDoubleMatrix(1, 1, mxREAL);
	ptr = mxGetPr(rhs[out_id]);
	ptr[0] = model_->nr_class;
	out_id++;

	if(model_->nr_class==2 && model_->param.solver_type != MCSVM_CS)
		nr_w=1;
	else
		nr_w=model_->nr_class;

	// nr_feature
	rhs[out_id] = mxCreateDoubleMatrix(1, 1, mxREAL);
	ptr = mxGetPr(rhs[out_id]);
	ptr[0] = model_->nr_feature;
	out_id++;

	// bias
	rhs[out_id] = mxCreateDoubleMatrix(1, 1, mxREAL);
	ptr = mxGetPr(rhs[out_id]);
	ptr[0] = model_->bias;
	out_id++;

	if(model_->bias>=0)
		n=model_->nr_feature+1;
	else
		n=model_->nr_feature;

	w_size = n;
	// Label
	if(model_->label)
	{
		rhs[out_id] = mxCreateDoubleMatrix(model_->nr_class, 1, mxREAL);
		ptr = mxGetPr(rhs[out_id]);
		for(i = 0; i < model_->nr_class; i++)
			ptr[i] = model_->label[i];
	}
	else
		rhs[out_id] = mxCreateDoubleMatrix(0, 0, mxREAL);
	out_id++;

	// w
	rhs[out_id] = mxCreateDoubleMatrix(nr_w, w_size, mxREAL);
	ptr = mxGetPr(rhs[out_id]);
	for(i = 0; i < w_size*nr_w; i++)
		ptr[i]=model_->w[i];
	out_id++;

	/* Create a struct matrix contains NUM_OF_RETURN_FIELD fields */
	return_model = mxCreateStructMatrix(1, 1, NUM_OF_RETURN_FIELD, field_names);

	/* Fill struct matrix with input arguments */
	for(i = 0; i < NUM_OF_RETURN_FIELD; i++)
		mxSetField(return_model,0,field_names[i],mxDuplicateArray(rhs[i]));
	/* return */
	plhs[0] = return_model;
	mxFree(rhs);

	return NULL;
}