/* 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 */
/* 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 > 4) mexErrMsgTxt("#4 inputs possible #0 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 */ 

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

	retCode = TA_CDLLONGLINE(
                   startIdx, endIdx,
                   open,
                   high,
                   low,
                   close,
                   &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 */
/* store all the shifts or perturbations in local maximum pooling */
void StoreShift()
{
    int orient, i, j, shift, ci, cj, si, sj, os, iS;
    float alpha;

    /* store all the possible shifts for all orientations */
    numShift = (locationPerturb * 2 + 1) * (orientationPerturb*2+1);
    rowShift = (int**)mxCalloc( nGaborScale * nGaborOri, sizeof(*rowShift) );
    colShift = (int**)mxCalloc( nGaborScale * nGaborOri, sizeof(*colShift) );
    orientShift = (int**)mxCalloc( nGaborScale * nGaborOri, sizeof(*orientShift) );

    for( iS = 0; iS < nGaborScale; ++iS ) /* for each scale */
    {
        for (orient=0; orient<nGaborOri; orient++)  /* for each orientation */
        {
            rowShift[orient+nGaborOri*iS] = (int*)mxCalloc( numShift, sizeof(**rowShift) );
            colShift[orient+nGaborOri*iS] = (int*)mxCalloc( numShift, sizeof(**colShift) );
            orientShift[orient+nGaborOri*iS] = (int*)mxCalloc( numShift, sizeof(**orientShift) );
            
            /* order the shifts from small to large */
            alpha = (float)PI*orient/nGaborOri;
            ci = 0;
            for( i=0; i<=locationPerturb; ++i ) // location shifts
            {
                for (si=0; si<=1; si++) /* sign of i */
                {
                    double location_shift = i;

                    cj = 0;
                    for( j = 0; j<=orientationPerturb; j++ ) // orientation shifts
                    {
                        for (sj=0; sj<=1; sj++) /* sign of j */
                        {
                            shift = ci*(2*orientationPerturb+1) + cj; /* hybrid counter for location and orientation */

                            //mexPrintf("locationshift=%.3f\n", location_shift);
                            //mexErrMsgTxt("for debug");
                            
                            rowShift[iS*nGaborOri+orient][shift] = (int)floor(.5+location_shift*(si*2-1)*cos(alpha));
                            colShift[iS*nGaborOri+orient][shift] = (int)floor(.5+location_shift*(si*2-1)*sin(alpha));
                            os = orient + j*(sj*2-1);
                            if (os<0)
                            {
                                os += nGaborOri;
                            }
                            else if (os>=nGaborOri)
                            {
                                os -= nGaborOri;
                            }
                            orientShift[iS*nGaborOri+orient][shift] = os;
                            if (j>0 || sj==1) /* triggers the orientation counter */
                            {
                                cj++;
                            }
                        }
                    }
                    if (i>0 || si==1)
                    {
                        ci++;
                    }
                }
            }
        }
        
    }
}
Exemple #3
0
void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] )
     
{ 

	/* 
	 * Construct error and warning messages using this buffer.  
	 * */
	char error_msg[500];



	int nShapeType, nEntities, i, j;


	int buflen;            /* length of input shapefile name */
	char *shapefile;       /* holder for input shapefile name */
	int status;            /* success or failure */

	/*
	 * Not used.
	 * */
	double adfMinBound[4], adfMaxBound[4];

	/*
	 * pointer to the shapefile
	 * */
	SHPHandle	hSHP;
	SHPObject	*psShape;



	/*
	 * handle for DBF file
	 * */
	DBFHandle     dbh;

	/*
	 * number of DBF attributes, records
	 * */
	int num_dbf_fields, num_dbf_records;


	/*
	 * This structure will hold a description of each field in the DBF file.
	 * */
	typedef struct DBF_Field_Descriptor {
		char          pszFieldName[12];
		DBFFieldType  field_type;
	} DBF_Field_Descriptor;


	DBF_Field_Descriptor *dbf_field;


	/*
	 * stores individual values from the DBF.
	 * */
	double dbf_double_val;
	int dbf_integer_val;
	char *dbf_char_val;

	char error_buffer[500];


	char **att_fnames;             /* holds name of fie */

	/* holds name of fields for the shape structure */
	char *shape_fnames[2] = { "x", "y" };      

	/* holds name of fields for the shape structure */
	char *outstruct_fnames[3]
		= { "Shape", "Attribute", "Type" };  


	/*
	 * Matlab structure to hold all output information.
	 * */
	mxArray *out_struct;

	/*
	 * Matlab structure that holds the point information.
	 *
	 * */
	mxArray *data_struct;
	
	/*
	 * Matlab structure that holds the attribute information.
	 * */
	mxArray *att_struct;
	
	/*
	 * 
	 * */
	mxArray *x_out, *y_out;

	/*
	 * temporary matlab array
	 * */
	mxArray *mxtmp;


	double *x_out_ptr, *y_out_ptr;

	/*
	 * Shortcuts into the output arrays.
	 * */
	double *mx_ptr, *my_ptr;

	int part_start;        /* start of a polygon part */
	int part_count;        /* how many vertices in a polygon part. */

	int dims[2];
	size_t sizebuf;

	/*
	 * This string will describe the type of shapefile.
	 * The possibilities are currently
	 *
	 *     MultiPoint
	 *     Point
	 *     Arc
	 *     Polygon
	 * */
	char *shapeTypeString;

	/*
	 * Initialize the dbf record.
	 * */
	dbf_field = NULL;



	/* Check for proper number of arguments */
	if (nrhs != 1) { 
		mexErrMsgTxt("One input argument is required."); 
	}
	if (nlhs != 1) { 
		mexErrMsgTxt("One output argument is required."); 
	}


	/*
	 * Make sure the input is a proper string.
	 * */
	if ( mxIsChar(prhs[0]) != 1 ) {
		mexErrMsgTxt("Shapefile parameter must be a string\n" );
	}
	if ( mxGetM(prhs[0]) != 1 ) {
		mexErrMsgTxt("Shapefile parameter must be a row vector, not a column string\n" );
	}

	buflen = mxGetN(prhs[0]) + 1; 
	shapefile = mxCalloc ( buflen, sizeof(char) );

	/*
	 * copy the string data from prhs[0] into a C string.
	 * */
	status = mxGetString ( prhs[0], shapefile, buflen );
	if ( status != 0 ) {
		mexErrMsgTxt ( "Not enough space for shapefile argument.\n" );
	}







	/* -------------------------------------------------------------------- */
	/*      Open the passed shapefile.                                      */
	/* -------------------------------------------------------------------- */
	hSHP = SHPOpen( shapefile, "rb" );
	if( hSHP == NULL ) {
		sprintf ( error_msg, "Unable to open:%s\n", shapefile );
		mexErrMsgTxt( error_msg );
	}




	/* -------------------------------------------------------------------- */
	/*      Get the needed information about the shapefile.                 */
	/* -------------------------------------------------------------------- */
	SHPGetInfo( hSHP, &nEntities, &nShapeType, adfMinBound, adfMaxBound );

	

	/*
	 * Make sure that we can handle the type.
	 * */
	switch ( nShapeType ) {
		case SHPT_MULTIPOINT:
		case SHPT_POINT:
		case SHPT_ARC:
		case SHPT_POLYGON:
			break;

		default:
			sprintf ( error_buffer, "Unhandled shape code %d (%s)\n", nShapeType, SHPTypeName ( nShapeType ) );
	        	mexErrMsgTxt( error_buffer ); 

	}
    
	/*
	 * Create the output shape type parameter.  
	 * */
	shapeTypeString = (char *) SHPTypeName ( nShapeType );


	/*
	 * Open the DBF in order to retrieve the number of fields and records.
	 * */
	dbh = DBFOpen (shapefile, "rb");
	num_dbf_fields = DBFGetFieldCount ( dbh );
	num_dbf_records = DBFGetRecordCount ( dbh );


	/*
	 * Allocate space for a description of each record, and populate it.
	 * I allocate space for two extra "dummy" records that go in positions
	 * 0 and 1.  These I reserve for the xy data.
	 * */
	dbf_field = (DBF_Field_Descriptor *) mxCalloc ( num_dbf_fields, sizeof ( DBF_Field_Descriptor ) );
	if ( dbf_field == NULL ) {
		mexErrMsgTxt("Memory allocation for DBF_Field_Descriptor failed."); 
	}


	for ( j = 0; j < num_dbf_fields; ++j ) {
		dbf_field[j].field_type = DBFGetFieldInfo ( dbh, j, dbf_field[j].pszFieldName, NULL, NULL );
	}




	/*
	 * Allocate space for the datapoint structure.
	 * */
	data_struct = mxCreateStructMatrix ( nEntities, 1, 2, (const char **)shape_fnames );


	/*
	 * Allocate space for the field names for the attributes.
	 * According to the API, each field name can have up to 12
	 * characters.
	 * */
	att_fnames = (char **) mxCalloc ( num_dbf_fields, sizeof(char *) );
	if ( att_fnames == NULL ) {
		mexErrMsgTxt("Memory allocation for attribute field names failed."); 
	}

	/*
	 * Copy the attribute names, create the matlab structure.
	 * */
	for ( j = 0; j < num_dbf_fields; ++j ) {
		att_fnames[j] = dbf_field[j].pszFieldName;
	}
	att_struct = mxCreateStructMatrix ( nEntities, 1, num_dbf_fields, (const char **)att_fnames );

    
	/* -------------------------------------------------------------------- */
	/*	Skim over the list of shapes, printing all the vertices.	*/
	/* -------------------------------------------------------------------- */
	for( i = 0; i < nEntities; i++ ) {

		psShape = SHPReadObject( hSHP, i );
		/*
		fprintf ( stdout, "Num parts = %d\n", psShape->nParts );
		*/


		/*
		 * Create the fields in this struct element.
		 * We will stick in one nan for each shape part.
		 */
		dims[0] = psShape->nVertices + psShape->nParts;
		dims[1] = 1;
		x_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL );
		x_out_ptr = mxGetData ( x_out );
		y_out = mxCreateNumericArray ( 2, dims, mxDOUBLE_CLASS, mxREAL );
		y_out_ptr = mxGetData ( y_out );



		/*
		 * Just copy the verticies over.
		 * */
		sizebuf = mxGetElementSize ( x_out ) * psShape->nVertices;

		mx_ptr = x_out_ptr;
		my_ptr = y_out_ptr;


		for ( j = 0; j < psShape->nParts-1; ++j ) {

			part_count = psShape->panPartStart[j+1] - psShape->panPartStart[j];
			sizebuf = mxGetElementSize ( x_out ) * part_count;

			part_start = psShape->panPartStart[j];
			memcpy ( (void *) (mx_ptr), (void *) &(psShape->padfX[part_start]), sizebuf );
			memcpy ( (void *) (my_ptr), (void *) &(psShape->padfY[part_start]), sizebuf );

			/*
			 * Stick a nan here to separate the parts.
			 * */
			mx_ptr[part_count] = mxGetNaN();
			my_ptr[part_count] = mxGetNaN();

			/*
			 * Update the pointers to the next part.
			 * */
			mx_ptr += (part_count+1);
			my_ptr += (part_count+1);

		}


		/*
		 * Do the last one
		 *
		 * Special case if there is only a single point?  
		 * */
		if ( psShape->nParts == 0 ) {
			memcpy ( (void *) (mx_ptr), (void *) &(psShape->padfX[0]), sizebuf );
			memcpy ( (void *) (my_ptr), (void *) &(psShape->padfY[0]), sizebuf );
		} else {

			part_count = psShape->nVertices - psShape->panPartStart[psShape->nParts-1];
			sizebuf = mxGetElementSize ( x_out ) * part_count;
	
			part_start = psShape->panPartStart[psShape->nParts-1];
			memcpy ( (void *) (mx_ptr), (void *) &(psShape->padfX[part_start]), sizebuf );
			memcpy ( (void *) (my_ptr), (void *) &(psShape->padfY[part_start]), sizebuf );

			/*
			 * Stick a nan here to separate the parts.
			 * */
			mx_ptr[part_count] = mxGetNaN();
			my_ptr[part_count] = mxGetNaN();

		}


		mxSetField ( data_struct, i, "x", x_out );
		mxSetField ( data_struct, i, "y", y_out );






		/*
		 * Now do the attributes
		 * */
		for ( j = 0; j < num_dbf_fields; ++j ) {
			switch ( dbf_field[j].field_type ) {
				case FTString:
					dbf_char_val = (char *) DBFReadStringAttribute ( dbh, i, j );
					mxtmp = mxCreateString ( dbf_char_val );
					mxSetField ( att_struct, i, dbf_field[j].pszFieldName, mxtmp );
					break;

				case FTDouble:
					dbf_double_val = DBFReadDoubleAttribute ( dbh, i, j );
					mxtmp = mxCreateDoubleScalar ( dbf_double_val );
					mxSetField ( att_struct, i, dbf_field[j].pszFieldName, mxtmp );
					break;

				case FTInteger:
				case FTLogical:
					dbf_integer_val = DBFReadIntegerAttribute ( dbh, i, j );
					dbf_double_val = dbf_integer_val;
					mxtmp = mxCreateDoubleScalar ( dbf_double_val );
					mxSetField ( att_struct, i, dbf_field[j].pszFieldName, mxtmp );
					break;

				default:
					sprintf ( error_buffer, "Unhandled code %d, shape %d, record %d\n", dbf_field[j].field_type, i, j );
	        			mexErrMsgTxt("Unhandled code"); 

			}
		}


        SHPDestroyObject( psShape );

	}



	/*
	 * Clean up, close up shop.
	 * */
	SHPClose( hSHP );

	DBFClose ( dbh );




	/*
	 * Allocate space for the output structure.
	 * */
	out_struct = mxCreateStructMatrix ( 1, 1, 3, (const char **)outstruct_fnames );

	/*
	 * Set the fields properly.
	 * */
	mxSetField ( out_struct, 0, "Shape", data_struct );
	mxSetField ( out_struct, 0, "Attribute", att_struct );
	mxSetField ( out_struct, 0, "Type", mxCreateString ( shapeTypeString ) );

	plhs[0] = out_struct;
	return;

}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  double	*m, *h, *g, *iwm, *f_ptr, *buf, *iwm_out_ptr;
  double        *m_ptr, *iwm_ptr, *col_ptr, *in_ptr, *out_ptr, *pos, *f_pos;
  double        *d_start_h, *d_start_g, *d_end_h, *d_end_g;
  double        d, res1, res2;
  int           dlp, dhp, dlp_12, dhp_12, odd_dlp, odd_dhp, n_cols, col;
  int           st_wrap_h, st_wrap_g, len_mid, len_h_12_p, len_g_12_p, dlp_12_p, dhp_12_p;
  int           reco_detail, len_h_12, len_g_12, len_x_12_m_h, len_x_12_m_g; 
  int		len_x, len_x_12, len_h, len_g, len_buf, i, j, k, odd_h, odd_g;
  long int      size_m;
  
  if (nrhs < 5) 
    mexErrMsgTxt("Need at least matrix, two filters, two delays.");
  if (nlhs > 1)
    mexErrMsgTxt("Only one output returned.");
  if (mxIsComplex(M))
    mexErrMsgTxt("Cannot wt complex matrix.");
  if (mxGetClassID(M) != mxDOUBLE_CLASS)
    mexErrMsgTxt("Input matrix should be of class double");
  if (nrhs > 5)
    reco_detail = ((int)*(mxGetPr(RECO_D))!=0);
  else reco_detail = 1;

  /* Assign pointers to the parameters */
  m        = mxGetPr(M);
  h        = mxGetPr(RH);
  g        = mxGetPr(RG);

  /* get delay lengths */
  dlp      = (int)*(mxGetPr(DLP));
  dlp_12   = dlp/2;
  odd_dlp  = isodd(dlp);
  dhp      = (int)*(mxGetPr(DHP));
  dhp_12   = dhp/2;
  odd_dhp  = isodd(dhp);

  /* get dimensions */
  len_x    = mxGetM(M);
  n_cols   = mxGetN(M);
  size_m   = len_x * n_cols;
  len_h    = mxGetM(RH) * mxGetN(RH);
  len_h_12 = len_h/2;
  odd_h    = isodd(len_h);
  len_g    = mxGetM(RG) * mxGetN(RG);
  len_g_12 = len_g/2;
  odd_g    = isodd(len_g);

  /* check length divisible by 2 */
  if (isodd(len_x))
    mexErrMsgTxt("Length of x dimension must be divisible by 2.");    
  len_x_12 = len_x/2;

  /* prepare altered lengths for odd filter delays */
  len_x_12_m_h = len_x_12 - odd_dlp;
  len_x_12_m_g = len_x_12 - odd_dhp;
  len_h_12_p = len_h_12 + odd_h;
  dlp_12_p   = dlp_12 + odd_dlp;
  len_g_12_p = len_g_12 + odd_g;
  dhp_12_p   = dhp_12 + odd_dhp;
   
  /* check constants */
  if (dlp < 0 || dlp > len_h || 
      dhp < 0 || dhp > len_g) 
    mexErrMsgTxt("Filter delays seem to be out of range.");

  /* make output matrix */
  IWM = mxCreateNumericArray(mxGetNumberOfDimensions(M),
			    mxGetDimensions(M), 
			    mxDOUBLE_CLASS, mxREAL);
  iwm = mxGetPr(IWM);
  m_ptr = m; 
  iwm_ptr = iwm;
  for (i=0; i<size_m; i++)
    *(iwm_ptr++) = *(m_ptr++);

  /* make buffer to contain whole row sample, wraparounds */
  st_wrap_h = max((len_h_12 + odd_h - dlp_12 - 1), 0); /* start wrap size for h */
  st_wrap_g = max((len_g_12 + odd_g - dhp_12 - 1), 0); /* start wrap size for g */
  len_mid   = min(dlp_12 + odd_dlp, st_wrap_h + len_x_12);
  len_buf   = st_wrap_h + len_x_12 + len_mid + len_x_12 + dhp_12 + odd_dhp;
  buf = (double *)mxCalloc(len_buf, sizeof(double));
  d_start_h = buf + st_wrap_h;
  d_end_h   = d_start_h + len_x_12 - 1;
  d_start_g = d_end_h + 1 + len_mid;
  d_end_g   = d_start_g + len_x_12 - 1;
  
  /* for each x column */
  col_ptr = iwm;
  for (col=0; col < n_cols; col++) {
    /* copy the row data to buffer */
    out_ptr = d_start_h;
    in_ptr  = col_ptr;
    for (i=0; i<len_x_12; i++)
      *(out_ptr++) = *(in_ptr++);
    if (reco_detail) {
      out_ptr = d_start_g;
      for (i=0; i<len_x_12; i++)
	*(out_ptr++) = *(in_ptr++);
    }

    /* do low pass filter */
    iwm_out_ptr = col_ptr;
      
    /* make end wrap */
    out_ptr = d_end_h + 1;
    in_ptr  = d_start_h;
    for (i=0; i < dlp_12_p; i++) {
      *(out_ptr++) = *(in_ptr++);
      if (in_ptr > d_end_h)
	in_ptr = d_start_h;
    }
    /* make start wrap */
    out_ptr = d_start_h-1;
    in_ptr = d_end_h;
    for (i=0; i < st_wrap_h; i++) {
      *(out_ptr--) = *(in_ptr--);
      if (in_ptr < d_start_h)
	in_ptr = d_end_h;
    }
    
    /* do convolution */
    pos = d_start_h + dlp_12;
    
    /* do start conv for odd delay */
    if (odd_dlp) {
      
      /* move back along even part of filter */
      f_ptr = h;
      f_pos = pos++;
      res2 = 0;
      for (j=0; j<len_h_12; j++) {
	res2 += *(f_pos--) * *(++f_ptr);
	f_ptr++;
      }
      *(iwm_out_ptr++) = res2;
    }
    
    /* move along row */
    for (i=0; i<len_x_12_m_h; i++) { /* taking into account odd_delay */
      f_ptr = h;
      f_pos = pos++;
      res1 = 0;
      res2 = 0;
      /* move back along filter */
      for (j=0; j<len_h_12; j++) {
	d = *f_pos--;
	res1 += d * *(f_ptr++);  /* odd portion of filter */
	res2 += d * *(f_ptr++);  /* even portion */
      }
      if (odd_h)
	res1 += *(f_pos) * *(f_ptr);
    
      *(iwm_out_ptr++) = res1;
      *(iwm_out_ptr++) = res2;
    } /* along row */
  
    /* do end conv for odd delay */
    if (odd_dlp) {
      /* move back along odd part of filter */
      f_ptr = h;
      f_pos = pos;
      res1 = 0;
      for (j=0; j<len_h_12_p; j++) {
	res1 += *(f_pos--) * *(f_ptr++);
	f_ptr++;
      }
      *(iwm_out_ptr++) = res1;
    } /* end conv */


    /* high pass filter if required */
    if (reco_detail) {
      iwm_out_ptr = col_ptr;
      
      /* make end wrap */
      out_ptr = d_end_g + 1;
      in_ptr  = d_start_g;
      for (i=0; i < dhp_12_p; i++) {
	*(out_ptr++) = *(in_ptr++);
	if (in_ptr > d_end_g)
	  in_ptr = d_start_g;
      }
      /* make start wrap */
      out_ptr = d_start_g-1;
      in_ptr = d_end_g;
      for (i=0; i < st_wrap_g; i++) {
	*(out_ptr--) = *(in_ptr--);
	if (in_ptr < d_start_g)
	  in_ptr = d_end_g;
      }
      
      /* do convolution */
      pos = d_start_g + dhp_12;
      
      /* do start conv for odd delay */
      if (odd_dhp) {
	
	/* move back along even part of filter */
	f_ptr = g;
	f_pos = pos++;
	res2 = 0;
	for (j=0; j<len_g_12; j++) {
	  res2 += *(f_pos--) * *(++f_ptr);
	  f_ptr++;
	}
	*(iwm_out_ptr++) += res2;
      }
      
      /* move along row */
      for (i=0; i<len_x_12_m_g; i++) { /* taking into account odd_delay */
	f_ptr = g;
	f_pos = pos++;
	res1 = 0;
	res2 = 0;
	/* move back along filter */
	for (j=0; j<len_g_12; j++) {
	  d = *f_pos--;
	  res1 += d * *(f_ptr++);  /* odd portion of filter */
	  res2 += d * *(f_ptr++);  /* even portion */
	}
	if (odd_g)
	  res1 += *(f_pos) * *(f_ptr);
	
	*(iwm_out_ptr++) += res1;
	*(iwm_out_ptr++) += res2;
      } /* along row */
      
      /* do end conv for odd delay */
      if (odd_dhp) {
	/* move back along odd part of filter */
	f_ptr = g;
	f_pos = pos;
	res1 = 0;
	for (j=0; j<len_g_12_p; j++) {
	  res1 += *(f_pos--) * *(f_ptr++);
	  f_ptr++;
	}
	*(iwm_out_ptr++) += res1;
      } /* end conv */
      
    } /* end if reco_detail */
    
    /* move to next row */
    col_ptr += len_x; 
    
  } /* for each column */
  
  /* free memory */
  mxFree(buf);

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

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

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

  // apply forest to each patch
  #pragma omp parallel for
  for( int c=0; c<widthOut; c++ ) {
      for( int r=0; r<heightOut; r++ ) {
        // classify a single patch using all trees
        float *chns1 = chns + (r*stride) + (c*stride)*height;
        float *chnsSs1 = chnsSs + (r*stride) + (c*stride)*height;
        
        for( int t = 0; t < nTrees; t++ ) {
            uint32 k = t*nTreeNodes, res;
            
            while( child[k] ) {
                // compute feature (either lookup in channel or self-similarity feature)
                uint32 f = fids[k], cid1 = cids1[f], cid2 = cids2[f];
                float ftr;
                
                if( f<nChnFtrs )
                    ftr = chns1[cid1];
                else
                    ftr = chnsSs1[cid1] - chnsSs1[cid2];
                
                // compare ftr to threshold and move left or right accordingly
                if( ftr < thrs[k] )
                    k = child[k]-1;
                else
                    k = child[k];
                
                res = k;
                k += t*nTreeNodes;
            }
            
            // lookup probability and store results
            for( int i = 0; i < nTokens; i++ ) {
                S[r*nTokens + c*heightOut*nTokens + i] += distr[t*nTreeNodes*nTokens + res*nTokens + i];
            }
        }
      }
  }
}
/* Matlab Gateway routine */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	char	*pszSRS_WKT = NULL;
	GDALDatasetH	hSrcDS, hDstDS;
	GDALDriverH	hDriver;
	GDALRasterBandH hBand;
	OGRSpatialReference oSrcSRS, oDstSRS; 
	GDALResampleAlg	interpMethod = GRA_NearestNeighbour;
	GDALTransformerFunc pfnTransformer = NULL;
	CPLErr		eErr;
	GDAL_GCP	*pasGCPs = NULL;
	void		*hTransformArg;
	static int runed_once = FALSE;	/* It will be set to true if reaches end of main */

	int	nx, ny, i, j, m, n, c = 0, n_pts, n_fields;
	char	*pszSrcSRS = NULL, *pszSrcWKT = NULL;
	char	*pszDstSRS = NULL, *pszDstWKT = NULL;
	double	*in_data, *ptr_d, *x, *y, *z;
	mxArray	*mx_ptr;

	int	nGCPCount = 0, nOrder = 0;
	char	**papszMetadataOptions = NULL;
	char	*tmp, *txt;
	int	bInverse = FALSE;
	int	*bSuccess;
	char	**papszTO = NULL;


	if (nrhs == 2 && mxIsStruct(prhs[1])) {

		/* -------------------------------------------------- */

		/* -------- See for projection stuff ---------------- */
		mx_ptr = mxGetField(prhs[1], 0, "SrcProjSRS");
		if (mx_ptr != NULL)
			pszSrcSRS = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "SrcProjWKT");
		if (mx_ptr != NULL)
			pszSrcWKT = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "DstProjSRS");
		if (mx_ptr != NULL)
			pszDstSRS = (char *)mxArrayToString(mx_ptr);

		mx_ptr = mxGetField(prhs[1], 0, "DstProjWKT");
		if (mx_ptr != NULL)
			pszDstWKT = (char *)mxArrayToString(mx_ptr);
		/* -------------------------------------------------- */

		/* -------- Do we have GCPs? ----------------------- */
		mx_ptr = mxGetField(prhs[1], 0, "gcp");
		if (mx_ptr != NULL) {
			nGCPCount = mxGetM(mx_ptr);
			if (mxGetN(mx_ptr) != 4)
				mexErrMsgTxt("GDALWARP: GCPs must be a Mx4 array");
			ptr_d = mxGetPr(mx_ptr);
			pasGCPs = (GDAL_GCP *) mxCalloc( nGCPCount, sizeof(GDAL_GCP) );
			GDALInitGCPs( 1, pasGCPs + nGCPCount - 1 );
			for (i = 0; i < nGCPCount; i++) {
				pasGCPs[i].dfGCPPixel = ptr_d[i];
				pasGCPs[i].dfGCPLine = ptr_d[i+nGCPCount];
				pasGCPs[i].dfGCPX = ptr_d[i+2*nGCPCount];
				pasGCPs[i].dfGCPY = ptr_d[i+3*nGCPCount];
				pasGCPs[i].dfGCPZ = 0;
			}
		}
			/* ---- Have we an order request? --- */
		mx_ptr = mxGetField(prhs[1], 0, "order");
		if (mx_ptr != NULL) {
			ptr_d = mxGetPr(mx_ptr);
			nOrder = (int)*ptr_d;
			if (nOrder != -1 || nOrder != 0 || nOrder != 1 ||
				nOrder != 2 || nOrder != 3)
				nOrder = 0;
		}
		/* -------------------------------------------------- */
		mx_ptr = mxGetField(prhs[1], 0, "inverse");
		if (mx_ptr != NULL)
			bInverse = TRUE;

		mx_ptr = mxGetField(prhs[1], 0, "ResampleAlg");
		if (mx_ptr != NULL) {
			txt = (char *)mxArrayToString(mx_ptr);
			if (!strcmp(txt,"nearest"))
				interpMethod = GRA_NearestNeighbour;
			else if (!strcmp(txt,"bilinear"))
				interpMethod = GRA_Bilinear;
			else if (!strcmp(txt,"cubic") || !strcmp(txt,"bicubic"))
				interpMethod = GRA_Cubic;
			else if (!strcmp(txt,"spline"))
				interpMethod = GRA_CubicSpline;
		}

	}
	else {
		mexPrintf("Usage: out = gdaltransform_mex(IN,PAR_STRUCT)\n\n");
		mexPrintf("      IN is a Mx2 or Mx3 array of doubles with X, Y (,Z)\n");
		mexPrintf("      PAR_STRUCT is a structure with at most two of the next fields:\n");
		mexPrintf("\t\t'SrcProjSRS', 'SrcProjWKT' -> Source projection string\n");
		mexPrintf("\t\t'DstProjSRS', 'DstProjWKT' -> Target projection string\n");
		mexPrintf("\t\t\tSRS stands for a string of the type used by proj4\n");
		mexPrintf("\t\t\tWKT stands for a string on the 'Well Known Text' format\n\n");
		mexPrintf("\t\t\tIf one of the Src or Dst fields is absent a GEOGRAPHIC WGS84 is assumed\n");
		mexPrintf("\nOPTIONS\n");
		mexPrintf("\t\t'gcp' a [Mx4] array with Ground Control Points\n");
		mexPrintf("\t\t'inverse' reverse transformation. e.g from georef to rows-columns\n");

		if (!runed_once)		/* Do next call only at first time this MEX is loaded */
			GDALAllRegister();

        	mexPrintf( "The following format drivers are configured and support Create() method:\n" );
        	for( i = 0; i < GDALGetDriverCount(); i++ ) {
			hDriver = GDALGetDriver(i);
			if( GDALGetMetadataItem( hDriver, GDAL_DCAP_CREATE, NULL ) != NULL)
				mexPrintf("%s: %s\n", GDALGetDriverShortName(hDriver), 
							GDALGetDriverLongName(hDriver));
		}
		return;
	}


	if (!runed_once) 		/* Do next call only at first time this MEX is loaded */
		GDALAllRegister();


	/* ----- Check that first argument contains at least a mx2 table */
	n_pts = mxGetM (prhs[0]);
	n_fields = mxGetN(prhs[0]);
	if (!mxIsNumeric(prhs[0]) || (n_fields < 2)) {
		mexPrintf("GDALTRANSFORM ERROR: first argument must contain a mx2 (or mx3) table\n");
		mexErrMsgTxt("               with the x,y (,z) positions to convert.\n");
	}

DEBUGA(1);
	/* ---------- Set the Source projection ---------------------------- */
	/* If it was not provided assume it is Geog WGS84 */
	if (pszSrcSRS == NULL && pszSrcWKT == NULL)
		oSrcSRS.SetWellKnownGeogCS( "WGS84" ); 
	else if (pszSrcWKT != NULL)
		oSrcSRS.importFromWkt( &pszSrcWKT );

	else {
		if( oSrcSRS.SetFromUserInput( pszSrcSRS ) != OGRERR_NONE )
			mexErrMsgTxt("GDALTRANSFORM: Translating source SRS failed.");
	}
	if (pszSrcWKT == NULL)
		oSrcSRS.exportToWkt( &pszSrcWKT );

	/* ------------------------------------------------------------------ */


DEBUGA(2);
	/* ---------- Set up the Target coordinate system ------------------- */
	/* If it was not provided assume it is Geog WGS84 */
	CPLErrorReset();
	if (pszDstSRS == NULL && pszDstWKT == NULL)
		oDstSRS.SetWellKnownGeogCS( "WGS84" ); 
	else if (pszDstWKT != NULL)
		oDstSRS.importFromWkt( &pszDstWKT );
	else {
		if( oDstSRS.SetFromUserInput( pszDstSRS ) != OGRERR_NONE )
			mexErrMsgTxt("GDALTRANSFORM: Translating target SRS failed.");
	}
	if (pszDstWKT == NULL)
		oDstSRS.exportToWkt( &pszDstWKT );
	/* ------------------------------------------------------------------ */



	/* -------------------------------------------------------------------- */
	/*      Create a transformation object from the source to               */
	/*      destination coordinate system.                                  */
	/* -------------------------------------------------------------------- */
	if( nGCPCount != 0 && nOrder == -1 ) {
		pfnTransformer = GDALTPSTransform;
		hTransformArg = GDALCreateTPSTransformer( nGCPCount, pasGCPs, FALSE );
	}
	else if( nGCPCount != 0 ) {
DEBUGA(3);
		pfnTransformer = GDALGCPTransform;
		hTransformArg = GDALCreateGCPTransformer( nGCPCount, pasGCPs, nOrder, FALSE );
	}
	else {
		pfnTransformer = GDALGenImgProjTransform;
		//hTransformArg = GDALCreateGenImgProjTransformer2( hSrcDS, hDstDS, papszTO );
		hTransformArg = 
    			GDALCreateGenImgProjTransformer( NULL, pszSrcWKT, NULL, pszDstWKT, 
						 nGCPCount == 0 ? FALSE : TRUE, 0, nOrder );
	}

	//CSLDestroy( papszTO );
DEBUGA(4);

	if( hTransformArg == NULL )
		mexErrMsgTxt("GDALTRANSFORM: Generating transformer failed.");

	in_data = (double *)mxGetData(prhs[0]);

	if (n_pts == 1) {
		x = &in_data[0];
		y = &in_data[1];
		bSuccess = &c;
	}
	else {
		x = (double *)mxCalloc(n_pts, sizeof(double));
		y = (double *)mxCalloc(n_pts, sizeof(double));
		bSuccess = (int *)mxCalloc(n_pts, sizeof(int));

		for (j = 0; j < n_pts; j++) {
			x[j] = in_data[j];
			y[j] = in_data[j+n_pts];
		}
	}
DEBUGA(5);

	z = (double *)mxCalloc(n_pts, sizeof(double));
	if (n_fields == 3)
		for (j = 0; j < n_pts; j++)
			z[j] = in_data[j+2*n_pts];

	if ( !pfnTransformer( hTransformArg, bInverse, n_pts, x, y, z, bSuccess ) )
		mexPrintf( "Transformation failed.\n" );


DEBUGA(6);
	if( nGCPCount != 0 && nOrder == -1 )
		GDALDestroyTPSTransformer(hTransformArg);
	else if( nGCPCount != 0 )
		GDALDestroyGCPTransformer(hTransformArg);
	else
		GDALDestroyGenImgProjTransformer(hTransformArg);


	/* -------------- Copy the result into plhs  --------------------------------- */
	plhs[0] = mxCreateDoubleMatrix (n_pts,n_fields, mxREAL);
	ptr_d = mxGetPr(plhs[0]);

	for (j = 0; j < n_pts; j++) {
		ptr_d[j] = x[j];
		ptr_d[j+n_pts] = y[j];
	}

	if (n_pts > 1) {
		mxFree((void *)x);	mxFree((void *)y);	mxFree((void *)bSuccess);
	}

	if (n_fields == 3) {
		for (j = 0; j < n_pts; j++)
			ptr_d[j+2*n_pts] = z[j];
	}
	mxFree((void *)z);


	if (pszDstWKT && strlen(pszDstWKT) > 1 ) OGRFree(pszDstWKT);	
	if (pszSrcWKT && strlen(pszSrcWKT) > 1 ) OGRFree(pszSrcWKT);
	//OGRFree(pszSrcWKT);
	//OGRFree(pszDstWKT);
	if (nGCPCount > 0) {
		GDALDeinitGCPs( nGCPCount, pasGCPs );	// makes this mex crash in the next call
		mxFree((void *) pasGCPs );
	}

	runed_once = TRUE;	/* Signals that next call won't need to call GDALAllRegister() again */

}
Exemple #7
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *Prhs[])
{
register int i;
register double *pdbl;
mxArray **prhs=(mxArray **)&Prhs[0], *At, *Ct;
struct mexdata mdata;
int len, status;
double *p, *p0, *ret, *x;
int m, n, havejac, Arows, Crows, itmax, nopts, mintype, nextra;
double opts[LM_OPTS_SZ]={LM_INIT_MU, LM_STOP_THRESH, LM_STOP_THRESH, LM_STOP_THRESH, LM_DIFF_DELTA};
double info[LM_INFO_SZ];
double *lb=NULL, *ub=NULL, *A=NULL, *b=NULL, *wghts=NULL, *C=NULL, *d=NULL, *covar=NULL;

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

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

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

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

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

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

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

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

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

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

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

    mxFree(minhowto);

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

  if(mintype==MIN_UNCONSTRAINED) goto extraargs;

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

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

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

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

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

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

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

        ++prhs;
        --nrhs;
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  if(status==LM_ERROR)
    mexWarnMsgTxt("levmar: optimization returned with an error!");
}
Exemple #8
0
void mexFunction(
   int nlhs, mxArray *plhs[],
   int nrhs, const mxArray *prhs[])
{
  double *a, *b, *x, *c, *y; /*mxGetPr, mxGetPr, mxGetPr, mCalloc(double), mxGetPr*/
  double *cptr, *ccol, *xptr, *yptr, *cin, *cend, *cp, *cstart; /*ccol, cend, x, cptr, mxGetPr, c, ccol, cend*/
  double z, z2, dd, di, temp; /*2.0, 2.0, 0.0, 0.0, di*/
  mwSize *cind, *n; /*p, (mwSize)*/
  mwSize d, m, p, N, i, j, nj, xrows, csize; /**/

  /* Error checking on inputs */  
  if (nrhs<5) mexErrMsgTxt("Not enough input arguments.");
  if (nrhs>5) mexErrMsgTxt("Too many input arguments.");
  if (nlhs>1) mexErrMsgTxt("Too many output arguments.");
  for (i=0; i<nrhs; i++) {
    if (!mxIsDouble(prhs[i]) || mxIsSparse(prhs[i]))
      mexErrMsgTxt("Function not defined for variables of input class");
    if (mxIsComplex(prhs[i]))
      mexErrMsgTxt("Arguments must be real.");
  }

  p=mxGetN(prhs[0]);

  m=mxGetM(prhs[1]);
  d=mxGetN(prhs[1]);
  x=mxGetPr(prhs[1]);

  if (mxGetNumberOfElements(prhs[2])!=d)
    mexErrMsgTxt("n has improper dimension");
  a=mxGetPr(prhs[2]);
  n=mxCalloc(d,sizeof(mwSize));
  for (i=0;i<d;i++) n[i]=(mwSize)a[i];

  if (mxGetNumberOfElements(prhs[3])!=d)
    mexErrMsgTxt("a has improper dimension");
  a=mxGetPr(prhs[3]);

  if (mxGetNumberOfElements(prhs[4])!=d)
    mexErrMsgTxt("b has improper dimension");
  b=mxGetPr(prhs[4]);

  N=1; for(i=0;i<d; i++) N *= n[i];
  if (mxGetM(prhs[0])!=N)
    mexErrMsgTxt("c has improper number of rows");

  plhs[0]=mxCreateDoubleMatrix(m,p,mxREAL);

  cind=mxCalloc(d,sizeof(mwSize));  
  cind[d-1]=p; for (i=d-1;i>0;i--) cind[i-1]=cind[i]*n[i];
  c=mxCalloc(N*p,sizeof(double));
  y=mxGetPr(plhs[0]);

  cin=mxGetPr(prhs[0]);
  csize=N*p*sizeof(double);
  cend=c+N*p;
  for (xrows=0;xrows<m; xrows++)
  {  
    memcpy(c,cin,csize);
    xptr=x+xrows;
    for (j=0; j<d; j++, xptr+=m)
    {
      z=(2.0**xptr-a[j]-b[j])/(b[j]-a[j]);
      z2=z*2.0;
      nj=n[j];
      ccol=cend-1;
      cptr=ccol;
      cstart=cend;
      for (cp=ccol-cind[j]; ccol>cp;)
      {
        di=0.0; 
        dd=0.0;
        for (cstart-=nj;cptr>cstart;)
        {
          temp=di;
          di=z2*di-dd+*cptr--;
          dd=temp;
        }
        *ccol--=z*di-dd+*cptr--;
      }
    }
    for (cptr=cend-p, yptr=y+xrows; cptr<cend; yptr+=m) 
       *yptr=*cptr++;
  }
  mxFree(c);
  mxFree(cind);
  mxFree(n);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
                 const mxArray *prhs[])
{
  int len;  
  double rs, cs, re, ce;
  int *rr, *cc;
  double *p;
  int i;
  int row, col;
    
  /* Check for proper number of arguments. */
  if (nrhs != 5 || nlhs > 1) {
    mexErrMsgTxt("SegInMat::Invalid calling method...please type help LineTwoPntsInMat in"                  "command for help\n");
  } 
  rs = mxGetScalar(prhs[1]);
  cs = mxGetScalar(prhs[2]);
  re = mxGetScalar(prhs[3]);
  ce = mxGetScalar(prhs[4]);
  /* 获取所得线段的长度 */
  len = bresenham_len((int)rs, (int)cs, (int)re, (int)ce);
  rr = (int*)mxCalloc(len, sizeof(int));
  cc = (int*)mxCalloc(len, sizeof(int));
  
  
  /* 求线段上所有点 */
  bresenham((int)rs, (int)cs, (int)re, (int)ce, rr, cc);
  
  /* 
   * 将对应点上的值填入输出.
   * 注意!!Matlab中矩阵按列存储,下标从1开始。C中下标从0开始
   */
  
  int nrow = mxGetM(prhs[0]);
  int ncol = mxGetN(prhs[0]);

  // 注意:检查行列是否在范围内
  if ( rs > nrow || rs < 1
    || re > nrow || re < 1
    || cs > ncol || cs < 1
    || ce > ncol || ce < 1) 
  {
    mexErrMsgTxt("SegInMat::Input point out of range...\n");
  }
  else 
  {
    plhs[0] = mxCreateDoubleMatrix(1, len, mxREAL);
    p = mxGetPr(plhs[0]);
  }

  
  if (mxIsDouble(prhs[0])) {
    double* pmat = (double* )mxGetPr(prhs[0]);
    for (i = 0; i < len; ++i) {
      row = *(rr+i);
      col = *(cc+i);
      *(p+i) = (double)(*(pmat + (col-1)*nrow + row - 1));
    }
    return;
  }
  else {
    mexErrMsgTxt("SegInMat::Only supports double matrix\n" 
      "Try forced casting:\n"
      "SegInMat(double(mat),rs,cs, re,ce)\n"
      "Or use:\n"
      "  [rr,cc] = LineTwoPnts(rs,ce, re,ce);\n"
      "  idx     = sub2ind(rr,cc);\n"
      "  elems   = mat(idx);\n"
      "as alternative.");
  }
  
  

}
Exemple #10
0
/* The key idea is to look at symmetrization and convolution as two separate steps */ 
void adj_wavelet_one_level(double *u, double *w, int nj, double *h0, double *h1, int l, int sym) {
    int m, d, k, L, Ly, m_even_odd, kl, a, cm, cn;
    double *y;
    
    L = l/2;
    d = nj/2;
    Ly = nj+l-1;
    y = (double*) mxCalloc(Ly, sizeof(double));
    
    /* Decompose symmetric extension and filtering into two steps */
    
    /* adjoint for linear convolution */
    for (m = 0; m < Ly; m++) {
        y[m] = 0;
        m_even_odd = ((m)%2)+1;
        if ( m < (l-1) && m < nj){
            for (k = 0; k <= m; k = k+2){
                y[m] += h0[l-k-m_even_odd]*w[m/2-k/2] + h1[l-k-m_even_odd]*w[d+m/2-k/2];
                /* mexPrintf("\n\t First: filter index = %i, wave index = %i, m_even_odd = %i ",l-k-m_even_odd, m/2-k/2,m_even_odd);*/
            }
        }
        else if (m >= nj){
            kl = ((Ly-m-2) < (nj-2))? (Ly-m-2) : (nj-2);
            for (k = 0; k <= kl; k = k+2){
                y[m] += h0[Ly-m-k-2]*w[nj/2-k/2-1] + h1[Ly-m-k-2]*w[d+nj/2-k/2-1];
                /* mexPrintf("\n\t Last: filter index = %i, wave index = %i, m_even_odd = %i ",Ly-m-k-2, nj/2-k/2-1,m_even_odd); */
            }
        }
        else{
            for (k = 0; k <= l-1; k = k+2){
                y[m] += h0[l-k-m_even_odd]*w[m/2-k/2] + h1[l-k-m_even_odd]*w[d+m/2-k/2];
                /* mexPrintf("\n\t Middle: filter index = %i, wave index = %i, m_even_odd = %i ",l-k-m_even_odd, m/2-k/2,m_even_odd); */
            }
        }
    }
    
    /* clear memory for output */
    for (cn=0; cn<nj; cn++) {
        u[cn] = 0;
    }
    
    /* adjoint for symmetric extension */
    if (sym == 0){
        for (m=0; m<Ly; m++) {
            cm = m+1-(l/2);
            if (cm<0) {
                a = cm%nj;
                cn = (a < 0) ? a+nj: a;
            }
            else if (cm > nj-1){
                cn = cm % (nj);
            }
            else{
                cn = cm;
            }
            u[cn] = u[cn]+y[m];
            /* mexPrintf("\n\t nj = %i, periodic indices are = %i, convolution index = %i",nj, cn, cm); */
        }
    }
    if (sym == 1){
        for (m = 0; m < Ly; m++) {
            cm = m+1-(l/2);
            if (cm < 0){
                a = (-cm) % (2*(nj-1));
                cn = (a > (nj-1)) ? (2*(nj-1)-a) : (a);
            }
            else if (cm > (nj-1)){
                a = (cm) % (2*(nj-1));
                cn = (a > (nj-1)) ? (2*(nj-1)-a) : (a);
            }
            else {
                cn = cm;
            }
            /* mexPrintf("\n\t cn = %i, Value u[cn] = %lf, y[m] = %lf ",cn, u[cn],y[m]); */
            u[cn] = u[cn]+y[m];
        }
    }
    if (sym == 2){
        for (m = 0; m < Ly; m++) {
            cm = m+1-(l/2);
            if (cm < 0){
                a = (-cm-1) % (2*nj);
                cn = (a > (nj-1)) ? (2*nj-a-1) : (a);
            }
            else if (cm > (nj-1)){
                a = (cm) % (2*nj);
                cn = (a > (nj-1)) ? (2*nj-1-a) : (a);
            }
            else {
                cn = cm;
            }
            u[cn] = u[cn]+y[m];
        }
    }
    mxFree(y);
}
Exemple #11
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
//Input variables
	double *weights;
	unsigned int *Hs;
	unsigned int *Ws;
	double *alphabet;
	double *targets;
	unsigned int num_layers;
	unsigned int num_threads;
	unsigned int set_size;
	double desired_error;
	unsigned int max_epochs;
	unsigned int max_time;
	double lambda;
	double sigma;
	unsigned int report_interval;
	unsigned int log_size[2]; 
	unsigned int net_size[2]; 
	mkl_network *net;
	
	mxArray *mMSE_log;
	mxArray *mtime_log;
	mxArray *mweights;
	double *new_weights;
	
//Body
	if(nrhs != 15){
		mexErrMsgTxt("Must be 15 input arguments!");
		return;
	}
	
	weights = (double *)mxGetData(prhs[0]);
	Hs = (unsigned int *)mxGetData(prhs[1]);
	Ws = (unsigned int *)mxGetData(prhs[2]);
	alphabet = (double *)mxGetData(prhs[3]);
	targets = (double *)mxGetData(prhs[4]);
	num_layers = (unsigned int)mxGetScalar(prhs[5]);
	num_threads = (unsigned int)mxGetScalar(prhs[6]);
	set_size = (unsigned int)mxGetScalar(prhs[7]);
	desired_error = (double)mxGetScalar(prhs[8]);
	max_epochs = (unsigned int)mxGetScalar(prhs[9]);
	max_time = (unsigned int)mxGetScalar(prhs[10]);
	lambda = (double)mxGetScalar(prhs[11]);
	sigma = (double)mxGetScalar(prhs[12]);
	report_interval = (unsigned int)mxGetScalar(prhs[13]);
	port = (unsigned int)mxGetScalar(prhs[14]);
	MSE_log = (double *)mxCalloc(max_epochs, sizeof(double));
	time_log = (unsigned int *)mxCalloc(max_time, sizeof(unsigned int));
	
	net = mkl_net_init(Hs, Ws, num_layers, weights, num_threads);
	net_start_sockets(port);
	mkl_net_train_scg(alphabet, targets, set_size, net, max_time, max_epochs,
						desired_error, report_interval, lambda, sigma, train_callback);
	net_stop_sockets();
	mexPrintf("Saving!\n");
	
	new_weights =  (double *)mxCalloc(net->total_weights, sizeof(double));
	memcpy((void *)new_weights, (void *)net->weights, sizeof(double) * net->total_weights);
	
	nlhs = 3;
	log_size[0] = net->epoch;
	log_size[1] = 1;
	
	net_size[0] = net->total_weights;
	net_size[1] = 1;
	
	mMSE_log = mxCreateNumericArray(2, log_size, mxDOUBLE_CLASS, mxREAL);
	mtime_log = mxCreateNumericArray(2, log_size, mxINT32_CLASS, mxREAL);
	mweights = mxCreateNumericArray(2, net_size, mxDOUBLE_CLASS, mxREAL);
	mxSetData(mMSE_log, MSE_log);
	mxSetData(mtime_log, time_log);
	mxSetData(mweights, new_weights);
	
	plhs[0] = mweights;
	plhs[1] = mMSE_log;
	plhs[2] = mtime_log;
	
	mkl_net_destroy(net);
}
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
char filename[256];
mxArray *pa1;
mxArray **mat_elem;
double *matData;
const char *field_name[20] = {"name","data"};
int i,j,count;
HEADER_FRAME *first_header_frame;
DATA_FRAME *first_data_frame, *cur_data_frame;
NAME_LIST *first_sig_name, *cur_sig_name;
int num_sigs,num_samples;

first_data_frame = init_data_frame();
first_header_frame = init_header_frame();
first_sig_name = init_name_list();


if (nrhs != 1)
  mexErrMsgTxt("Error: missing filename. Usage:  x = loadsig_cppsim('filename')");
if (!mxIsChar(prhs[0]))
  mexErrMsgTxt("Error: filename must be a string");
if (nlhs != 1)
  mexErrMsgTxt("Error: missing output variable.  Usage:  x = loadsig_cppsim('filename')");

mxGetString(prhs[0],filename,255);


if (load_data_from_file(filename,first_header_frame,first_data_frame,
                        &num_sigs, &num_samples) == -1)
    mexErrMsgTxt("File not read");

extract_signal_names(first_header_frame,num_sigs,first_sig_name);


/* write into MATLAB structure */
plhs[0] = mxCreateStructMatrix(num_sigs,1,2,field_name);


/* copy signal name */
cur_sig_name = first_sig_name;
for (i = 0; i < num_sigs; i++)
    {
     pa1 = mxCreateString(cur_sig_name->name);
     mxSetField(plhs[0],i,field_name[0],pa1);
     cur_sig_name = cur_sig_name->next;  
    }

/* copy data */
if ((mat_elem = (mxArray **) mxCalloc(num_sigs,sizeof(mxArray *))) == NULL)   
    {   
     mexPrintf("error in loadsig_cppsim:  calloc call failed - \n");   
     mexPrintf("  not enough memory!!\n");   
     return;   
    }   
for (i = 0; i < num_sigs; i++)   
     mat_elem[i] = mxCreateDoubleMatrix(num_samples,1,mxREAL);

cur_data_frame = first_data_frame;

count = 0;
for (j = 0; j < num_samples; j++)
  {
   for (i = 0; i < num_sigs; i++)
      {
	if (count == cur_data_frame->length)
	  {
	    cur_data_frame = cur_data_frame->next;
	    if (cur_data_frame == NULL)
	      {
		mexPrintf("error: data frame too short!\n");
		return;
	      }
            count = 0;
	  }
        matData = mxGetPr(mat_elem[i]);
	if (cur_data_frame->data_type == 32)
           matData[j] = cur_data_frame->fbuf[count];
        else
           matData[j] = cur_data_frame->dbuf[count];
        count++;
      }
  }

for (i = 0; i < num_sigs; i++)
    mxSetField(plhs[0],i,field_name[1],mat_elem[i]);

free_header_frames(first_header_frame);
free_data_frames(first_data_frame);
free_name_list(first_sig_name);


return;
}
//Gateway routine
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	//General vars
	char errMsg[512];

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

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

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

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

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

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

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

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

	//Write data
	int32 scansWritten;

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

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

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

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

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

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

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

				mxFree(writeData);
			}
		break;

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

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

	// Handle output arguments, if needed
	if (nlhs > 0) 
	{
		plhs[0] = mxCreateDoubleScalar(0);	
		double * sampsPerChanWritten = mxGetPr(plhs[0]);
		*sampsPerChanWritten = (double)scansWritten ; 
	}
}
// main function:
// takes a double color image and a bin size
// returns HOG features
mxArray *process(const mxArray *mximage, const mxArray *mxsbin) {
    double *im = (double *)mxGetPr(mximage);
    const int *dims = mxGetDimensions(mximage);
    if (mxGetNumberOfDimensions(mximage) != 3 ||
    dims[2] != 3 ||
    mxGetClassID(mximage) != mxDOUBLE_CLASS)
        mexErrMsgTxt("Invalid input");
    
    int sbin = (int)mxGetScalar(mxsbin);
    
    // memory for caching orientation histograms & their norms
    int blocks[2];
    blocks[0] = (int)round((double)dims[0]/(double)sbin);
    blocks[1] = (int)round((double)dims[1]/(double)sbin);
    double *hist = (double *)mxCalloc(blocks[0]*blocks[1]*18, sizeof(double));
    double *norm = (double *)mxCalloc(blocks[0]*blocks[1], sizeof(double));
    
    // memory for HOG features
    int out[3];
    out[0] = max(blocks[0]-2, 0);
    out[1] = max(blocks[1]-2, 0);
    out[2] = 27+4;
    mxArray *mxfeat = mxCreateNumericArray(3, out, mxDOUBLE_CLASS, mxREAL);
    double *feat = (double *)mxGetPr(mxfeat);
    
    int visible[2];
    visible[0] = blocks[0]*sbin;
    visible[1] = blocks[1]*sbin;
    
    for (int x = 1; x < visible[1]-1; x++) {
        for (int y = 1; y < visible[0]-1; y++) {
            // first color channel
            double *s = im + min(x, dims[1]-2)*dims[0] + min(y, dims[0]-2);
            double dy = *(s+1) - *(s-1);
            double dx = *(s+dims[0]) - *(s-dims[0]);
            double v = dx*dx + dy*dy;
            
            // second color channel
            s += dims[0]*dims[1];
            double dy2 = *(s+1) - *(s-1);
            double dx2 = *(s+dims[0]) - *(s-dims[0]);
            double v2 = dx2*dx2 + dy2*dy2;
            
            // third color channel
            s += dims[0]*dims[1];
            double dy3 = *(s+1) - *(s-1);
            double dx3 = *(s+dims[0]) - *(s-dims[0]);
            double v3 = dx3*dx3 + dy3*dy3;
            
            // pick channel with strongest gradient
            if (v2 > v) {
                v = v2;
                dx = dx2;
                dy = dy2;
            }
            if (v3 > v) {
                v = v3;
                dx = dx3;
                dy = dy3;
            }
            
            // snap to one of 18 orientations
            double best_dot = 0;
            int best_o = 0;
            for (int o = 0; o < 9; o++) {
                double dot = uu[o]*dx + vv[o]*dy;
                if (dot > best_dot) {
                    best_dot = dot;
                    best_o = o;
                } else if (-dot > best_dot) {
                    best_dot = -dot;
                    best_o = o+9;
                }
            }
            
            // add to 4 histograms around pixel using linear interpolation
            double xp = ((double)x+0.5)/(double)sbin - 0.5;
            double yp = ((double)y+0.5)/(double)sbin - 0.5;
            int ixp = (int)floor(xp);
            int iyp = (int)floor(yp);
            double vx0 = xp-ixp;
            double vy0 = yp-iyp;
            double vx1 = 1.0-vx0;
            double vy1 = 1.0-vy0;
            v = sqrt(v);
            
            if (ixp >= 0 && iyp >= 0) {
                *(hist + ixp*blocks[0] + iyp + best_o*blocks[0]*blocks[1]) +=
                vx1*vy1*v;
            }
            
            if (ixp+1 < blocks[1] && iyp >= 0) {
                *(hist + (ixp+1)*blocks[0] + iyp + best_o*blocks[0]*blocks[1]) +=
                vx0*vy1*v;
            }
            
            if (ixp >= 0 && iyp+1 < blocks[0]) {
                *(hist + ixp*blocks[0] + (iyp+1) + best_o*blocks[0]*blocks[1]) +=
                vx1*vy0*v;
            }
            
            if (ixp+1 < blocks[1] && iyp+1 < blocks[0]) {
                *(hist + (ixp+1)*blocks[0] + (iyp+1) + best_o*blocks[0]*blocks[1]) +=
                vx0*vy0*v;
            }
        }
    }
    
    // compute energy in each block by summing over orientations
    for (int o = 0; o < 9; o++) {
        double *src1 = hist + o*blocks[0]*blocks[1];
        double *src2 = hist + (o+9)*blocks[0]*blocks[1];
        double *dst = norm;
        double *end = norm + blocks[1]*blocks[0];
        while (dst < end) {
            *(dst++) += (*src1 + *src2) * (*src1 + *src2);
            src1++;
            src2++;
        }
    }
    
    // compute features
    for (int x = 0; x < out[1]; x++) {
        for (int y = 0; y < out[0]; y++) {
            double *dst = feat + x*out[0] + y;
            double *src, *p, n1, n2, n3, n4;
            
            p = norm + (x+1)*blocks[0] + y+1;
            n1 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps);
            p = norm + (x+1)*blocks[0] + y;
            n2 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps);
            p = norm + x*blocks[0] + y+1;
            n3 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps);
            p = norm + x*blocks[0] + y;
            n4 = 1.0 / sqrt(*p + *(p+1) + *(p+blocks[0]) + *(p+blocks[0]+1) + eps);
            
            double t1 = 0;
            double t2 = 0;
            double t3 = 0;
            double t4 = 0;
            
            // contrast-sensitive features
            src = hist + (x+1)*blocks[0] + (y+1);
            for (int o = 0; o < 18; o++) {
                double h1 = min(*src * n1, 0.2);
                double h2 = min(*src * n2, 0.2);
                double h3 = min(*src * n3, 0.2);
                double h4 = min(*src * n4, 0.2);
                *dst = 0.5 * (h1 + h2 + h3 + h4);
                t1 += h1;
                t2 += h2;
                t3 += h3;
                t4 += h4;
                dst += out[0]*out[1];
                src += blocks[0]*blocks[1];
            }
            
            // contrast-insensitive features
            src = hist + (x+1)*blocks[0] + (y+1);
            for (int o = 0; o < 9; o++) {
                double sum = *src + *(src + 9*blocks[0]*blocks[1]);
                double h1 = min(sum * n1, 0.2);
                double h2 = min(sum * n2, 0.2);
                double h3 = min(sum * n3, 0.2);
                double h4 = min(sum * n4, 0.2);
                *dst = 0.5 * (h1 + h2 + h3 + h4);
                dst += out[0]*out[1];
                src += blocks[0]*blocks[1];
            }
            
            // texture gradients
            *dst = 0.2357 * t1;
            dst += out[0]*out[1];
            *dst = 0.2357 * t2;
            dst += out[0]*out[1];
            *dst = 0.2357 * t3;
            dst += out[0]*out[1];
            *dst = 0.2357 * t4;
        }
    }
    
    mxFree(hist);
    mxFree(norm);
    return mxfeat;
}
Exemple #15
0
void mexFunction(
      int nlhs,   mxArray  *plhs[], 
      int nrhs,   const mxArray  *prhs[] )

{    double   *A, *U, *V, *VT, *S, *flag, *work, *AA;  

     mwIndex  *irS, *jcS, *iwork; 
     mwSize   M, N, lwork, info, options, minMN, maxMN, k, j; 
     mwSize   LDA, LDU, LDVT, nU, mVT, mS, nS; 
     char     *jobz;

/* CHECK FOR PROPER NUMBER OF ARGUMENTS */

   if (nrhs > 2){
      mexErrMsgTxt("mexsvd: requires at most 2 input arguments."); }
   if (nlhs > 4){ 
      mexErrMsgTxt("mexsvd: requires at most 4 output argument."); }   

/* CHECK THE DIMENSIONS */

    M = mxGetM(prhs[0]); 
    N = mxGetN(prhs[0]); 
    if (mxIsSparse(prhs[0])) {
       mexErrMsgTxt("mexeig: sparse matrix not allowed."); }   
    A = mxGetPr(prhs[0]); 
    LDA = M; 
    minMN = MIN(M,N); 
    maxMN = MAX(M,N); 
    options = 0; 
    if (nrhs==2) { options = (int)*mxGetPr(prhs[1]); } 
    if (options==0) { 
        /***** economical SVD ******/
       jobz="S"; nU = minMN; mVT = minMN; mS = minMN; nS = minMN; 
    } else {
        /***** full SVD ******/
       jobz="A"; nU = M; mVT = N; mS = M; nS = N; 
    }   
    LDU  = M; 
    LDVT = mVT; 
    /***** create return argument *****/
    if (nlhs >=3) {
       /***** compute singular values and vectors ******/
       plhs[0] = mxCreateDoubleMatrix(M,nU,mxREAL); 
       U = mxGetPr(plhs[0]);  
       plhs[1] = mxCreateSparse(mS,nS,minMN,mxREAL); 
       S   = mxGetPr(plhs[1]); 
       irS = mxGetIr(plhs[1]); 
       jcS = mxGetJc(plhs[1]);
       plhs[2] = mxCreateDoubleMatrix(N,mVT,mxREAL);     
       V = mxGetPr(plhs[2]); 
       plhs[3] = mxCreateDoubleMatrix(1,1,mxREAL);     
       flag = mxGetPr(plhs[3]); 
    } else { 
       /***** compute only singular values ******/
       plhs[0]= mxCreateDoubleMatrix(minMN,1,mxREAL); 
       S = mxGetPr(plhs[0]); 
       plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);     
       flag = mxGetPr(plhs[1]); 
       U = mxCalloc(M*nU,sizeof(double)); 
       V = mxCalloc(N*mVT,sizeof(double)); 
       jobz="N";
    }
    /***** Do the computations in a subroutine *****/   
    lwork = 4*minMN*minMN + MAX(maxMN,5*minMN*minMN+4*minMN);  
    work  = mxCalloc(lwork,sizeof(double)); 
    iwork = mxCalloc(8*minMN,sizeof(int)); 
    VT = mxCalloc(mVT*N,sizeof(double)); 
    AA = mxCalloc(M*N,sizeof(double)); 
    memcpy(AA,mxGetPr(prhs[0]),(M*N)*sizeof(double));

    dgesdd_(jobz,&M,&N, AA,&LDA,S,U,&LDU,VT,&LDVT,work,&lwork,iwork, &info); 

    flag[0] = (double)info; 
    if (nlhs >= 3) { 
       for (k=0; k<minMN; k++) { irS[k] = k; }
       jcS[0] = 0;
       for (k=1; k<=nS; k++) { 
          if (k<minMN) { jcS[k] = k; } else { jcS[k] = minMN; }
       }  
       for (k=0; k<mVT; k++) { 
          for (j=0; j<N; j++) { V[j+k*N] = VT[k+j*mVT]; }
       }
    }
    return;
 }
Exemple #16
0
// matlab entry point
// C = fconv(A, cell of B, start, end);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
    if (nrhs != 4)
        mexErrMsgTxt("Wrong number of inputs");
    if (nlhs != 1)
        mexErrMsgTxt("Wrong number of outputs");
    
    // get A
    const mxArray *mxA = prhs[0];
    if (mxGetNumberOfDimensions(mxA) != 3 ||
            mxGetClassID(mxA) != mxDOUBLE_CLASS)
        mexErrMsgTxt("Invalid input: A");
    
    // get B and start/end
    const mxArray *cellB = prhs[1];
    mwSize num_bs = mxGetNumberOfElements(cellB);
    int start = (int)mxGetScalar(prhs[2]) - 1;
    int end = (int)mxGetScalar(prhs[3]) - 1;
    if (start < 0 || end >= num_bs || start > end)
        mexErrMsgTxt("Invalid input: start/end");
    int len = end-start+1;
    
    // start threads
    thread_data *td = (thread_data *)mxCalloc(len, sizeof(thread_data));

    HANDLE  *hThreadArray = (HANDLE *)mxCalloc(len, sizeof(HANDLE));
    const mwSize *A_dims = mxGetDimensions(mxA);
    double *A = (double *)mxGetPr(mxA);
    
    // return value
    plhs[0] = mxCreateCellMatrix(1, len);
    int batch_len = ceil(1.0*len/THREAD_MAX);
    
    for(int b = 0; b<batch_len; b++) {
        int nthread = 0;
        for (int t = 0; t < THREAD_MAX; t++) {
            int i = b*THREAD_MAX + t;
            if(i >= len)
                break;
            nthread++;
            //mexPrintf("i = %d\n", i);
            const mxArray *mxB = mxGetCell(cellB, i+start);
            td[i].A_dims = A_dims;
            td[i].A = A;
            td[i].B_dims = mxGetDimensions(mxB);
            td[i].B = (double *)mxGetPr(mxB);
            if (mxGetNumberOfDimensions(mxB) != 3 ||
                    mxGetClassID(mxB) != mxDOUBLE_CLASS ||
                    td[i].A_dims[2] != td[i].B_dims[2])
                mexErrMsgTxt("Invalid input: B");
            
            // compute size of output
            int height = td[i].A_dims[0] - td[i].B_dims[0] + 1;
            int width = td[i].A_dims[1] - td[i].B_dims[1] + 1;
            if (height < 1 || width < 1)
                mexErrMsgTxt("Invalid input: B should be smaller than A");
            td[i].C_dims[0] = height;
            td[i].C_dims[1] = width;
            td[i].mxC = mxCreateNumericArray(2, td[i].C_dims, mxDOUBLE_CLASS, mxREAL);
            td[i].C = (double *)mxGetPr(td[i].mxC);
            
            hThreadArray[i] = CreateThread(
                    NULL,
                    0,
                    process,
                    &td[i],
                    0,
                    NULL);
            
            if (hThreadArray[i] == NULL)
                mexErrMsgTxt("Error creating thread");
        }
        
        // wait for the treads to finish and set return values
        WaitForMultipleObjects(nthread, hThreadArray+b*THREAD_MAX, TRUE, INFINITE);
        void *status;
        for (int t = 0; t < nthread; t++) {
            int i = b*THREAD_MAX + t;
            CloseHandle(hThreadArray[i]);
            mxSetCell(plhs[0], i, td[i].mxC);
        }
    }
    
    mxFree(td);
    mxFree(hThreadArray);
}
Exemple #17
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
	mxArray*    img;
	u_int8_t*   p_img;               /*The image from Matlab*/
	u_int8_t**  p_gray;              /*Image converted for texture calcs*/
	int         mrows;               /*Image height*/
	int         ncols;               /*Image width*/
	TEXTURE*    features ;           /*Returned struct of features*/
	int         i ;
	int         imgsize[2] ;              
	int         imgindex[2] ;
	long        offset ;                  
	int         outputsize[2] ;      /*Dimensions of TEXTURE struct*/
	int         outputindex[2] ;
	
	float*      output ;             /*Features to return*/
	int         distance, angle;     /*Parameters for texture calculations*/

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

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


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

	/*
	    Memory clean-up.
	*/
	for (i=0; i<mrows ; i++)
		mxFree(p_gray[i]) ;
	mxFree(p_gray) ;  
	
	/* features is calloc'd inside of Extract_Texture_Features */
	free(features) ;
}
Exemple #18
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 * high;
  double * low;
  double * close;
/* 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 < 3 || nrhs > 4) mexErrMsgTxt("#4 inputs possible #1 optional.");
  if (nlhs != 1) mexErrMsgTxt("#1 output required.");
/* ----------------- INPUT ----------------- */ 
  /* Create a pointer to the input matrix high. */
  high = mxGetPr(prhs[0]);
  /* Get the dimensions of the matrix input high. */
  inSeriesCols = mxGetN(prhs[0]);
  if (inSeriesCols != 1) mexErrMsgTxt("high only vector alowed.");
  /* Create a pointer to the input matrix low. */
  low = mxGetPr(prhs[1]);
  /* Get the dimensions of the matrix input low. */
  inSeriesCols = mxGetN(prhs[1]);
  if (inSeriesCols != 1) mexErrMsgTxt("low only vector alowed.");
  /* Create a pointer to the input matrix close. */
  close = mxGetPr(prhs[2]);
  /* Get the dimensions of the matrix input close. */
  inSeriesCols = mxGetN(prhs[2]);
  if (inSeriesCols != 1) mexErrMsgTxt("close only vector alowed.");
  inSeriesRows = mxGetM(prhs[2]);  
  endIdx = inSeriesRows - 1;  
  startIdx = 0;

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

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

	retCode = TA_DX(
                   startIdx, endIdx,
                   high,
                   low,
                   close,
                   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 */
Exemple #19
0
/*!
	\param nlhs number of left-hand-side output arguments
	\param plhs mxArray of output arguments
	\param nrhs number of right-hand-side input arguments
	\param prhs mxArray of input arguments
*/
void mexFunction( int nlhs, mxArray *plhs[], 
		  int nrhs, const mxArray*prhs[] )
     
{ 
	int p, nStage, L, flag;
	int i, j, m, n, N, J, K, M;
	double *v_in, *v_out, *v_ext, *v_final, *temp;

	/* Check for proper number of arguments */    
    if (nrhs != 1) { 
		mexErrMsgTxt("Only one input arguments required."); 
	} 
	else if (nlhs > 1) {
		mexErrMsgTxt("Too many output arguments."); 
    }

	/* Get the size and pointers to input data. */
	m  = mxGetM(prhs[0]);
	n  = mxGetN(prhs[0]);


	if (MIN(m,n) != 1) {
		mexErrMsgTxt("Only vectors accepted as input right now."); 
	}

	/* flag == 1, row vector; flag == 0, column vector. */
	flag = 1;
	if ( m != 1) {
		flag = 0;
	}

    /* Make sure that both input and output vectors have the length with 2^p where p is some integer. */ 
	n = MAX(m,n);
	p = ceil(log2(n));
    N = pow(2,p);	
    // sqrtN = sqrt(N);
	if ( flag == 1) {
		plhs[0] = mxCreateDoubleMatrix(1, N, mxREAL);
	}
	else {
		plhs[0] = mxCreateDoubleMatrix(N, 1, mxREAL);
	}
	v_final = mxGetPr(plhs[0]);
	v_in = mxGetPr(prhs[0]);
	
	/* Extend the input vector if necessary. */
	v_ext = (double*) mxCalloc (N,sizeof(double));
	v_out = (double*) mxCalloc (N,sizeof(double));
	for (j = 0; j <n; j++){
		v_ext[j] = v_in[j];
	}
	// mxDestroyArray(prhs[0]);

	
	for (i=0; i<N-1; i = i+2) {
		v_ext[i] = v_ext[i] + v_ext[i+1];
		v_ext[i+1] = v_ext[i] - v_ext[i+1] * 2;
	}
	L = 1;
    
	/* main loop */
	for (nStage = 2; nStage<=p; ++nStage){
		M = pow(2,L);
		J = 0;
		K = 0; // difference between Matlab and C++
		while (K<N-1){
			for (j = J;j < J+M-1; j = j+2){
				/* sequency order  */
				v_out[K] = v_ext[j] + v_ext[j+M];
				v_out[K+1] = v_ext[j] - v_ext[j+M];
				v_out[K+2] = v_ext[j+1] - v_ext[j+1+M];
				v_out[K+3] = v_ext[j+1] + v_ext[j+1+M];

				K = K+4;
			}

			J = J+2*M;
		}

		// for ( i =0; i<N; ++i){
		// 	v_ext[i] = v_out[i];
		// }

		// mxFree(v_ext);
		temp = v_ext;
		v_ext = v_out;
		v_out = temp;
		// v_out = (double*) mxMalloc (N,sizeof(double));

		L = L+1;
	}

	/* Perform scaling of coefficients. */
	for ( i =0; i<N; ++i){
			v_final[i] = v_ext[i]/N;
	}
	
	/* Set free the memory. */
	mxFree(v_out);
	mxFree(v_ext);

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

#ifdef MATLAB_VERBOSE
    //Allows my DBGM macro to redirect output to matlab console
    mystream mout; //defined in utils.h
    std::streambuf *outbuf = std::cout.rdbuf(&mout); //buffer redirection
#endif//MATLAB_VERBOSE  

    //=======================================================================
    // *** User error handling and initialization ***
    // Check the number of input and output parameters
    // This is more important than in regular m-files, as an error at this
    // stage may cause the Matlab instance to crash
    //=======================================================================
    if(nrhs>3)
        mexErrMsgTxt("Too many inputs: Should be an in signal vector followed by (optional) parameter structures");
    if(nrhs<1)
        mexErrMsgTxt("Too few inputs: At minimum, a signal vector must be supplied.");
    if(nlhs > 1)
        mexErrMsgTxt("Too many output arguments:\n"
                     "You are attempting to run the mex version of the algorithm.\n"
                     "Inspection of parameters is disabled.");

    bool isUniqueParsSupplied = (nrhs>1); //alias for readability
    bool isSharedParsSupplied = (nrhs>2); //alias for readability

    if (isUniqueParsSupplied)
        if(!mxIsStruct(UNIQUE_PARS_IN))
            mexErrMsgTxt("(optional) second input argument must be a parameter structure");

    if (isSharedParsSupplied)
        if(!mxIsStruct(SHARED_PARS_IN))
            mexErrMsgTxt("(optional) third input argument must be a parameter structure");

    int xM = mxGetM(AUDIO_DATA_IN); //columns (NxM)=Matlab
    int xN = mxGetN(AUDIO_DATA_IN); //rows (NxM)=Matlab

    if ((xN>2) || (xN<1))
        mexErrMsgTxt("Input must be a single or double channel column matrix i.e. (n,1) or (n,2)");
    bool isStereo = (xN==2); //alias for readability

    if(mxIsChar(AUDIO_DATA_IN) ||
            !mxIsNumeric(AUDIO_DATA_IN) ||
            mxIsSparse(AUDIO_DATA_IN) ||
            mxIsComplex(AUDIO_DATA_IN)   )
        mexErrMsgTxt("Audio data must be non-complex, non-sparse, and numeric");

    int numUniqueParSets =0;
    int numUniqueParFields =0;
    if (isUniqueParsSupplied)
    {
        numUniqueParSets   = mxGetNumberOfElements(UNIQUE_PARS_IN);
        numUniqueParFields = mxGetNumberOfFields(UNIQUE_PARS_IN);
    }

    int numSharedParFields =0;
    if (isSharedParsSupplied)
    {
        if(  mxGetNumberOfElements(SHARED_PARS_IN)   >   1  )
            mexErrMsgTxt("Parameter structure for pars shared between stereo channels should only have one element");
        numSharedParFields = mxGetNumberOfFields(SHARED_PARS_IN);
    }

    bool isStereoPars = (numUniqueParSets == 2); //alias for readability

    if (numUniqueParSets > 2)
        mexErrMsgTxt("Too many parameter sets supplied (parameter struct has more than 2 elements).\n"
                     "Algorithm only functions in mono or stereo - please supply 1x1 or 1x2 element struct.");

    if (isStereoPars && !isStereo)
        mexErrMsgTxt("Ambiguous parameters: Stereo parameters supplied for a mono signal.\n"
                     "Please supply a 1x1 element struct for a mono input, or convert input to stereo" );


    int totalNumElements = xM*xN; /* this is elements for all channels combined */


    //=======================================================================
    // *** Instantiate and modify parameter class(es) ***
    // Set parameter object values according to the supplied structures
    //=======================================================================

    //Create 2: We might waste one, but they are cheap and it saves dynamic allocation
    cUniqueStereoParams uniquePars[2];
    cSharedStereoParams sharedPars; // We only need one of these

    mxArray* tmpData;
    const char* tmpName;

    //============= UNIQUE ================
    for (int structIdx=0; structIdx<numUniqueParSets; ++structIdx)
    {
        for (int fieldIdx=0; fieldIdx<numUniqueParFields; ++fieldIdx)
        {
            tmpData = mxGetFieldByNumber(UNIQUE_PARS_IN, structIdx, fieldIdx);
            tmpName = mxGetFieldNameByNumber(UNIQUE_PARS_IN, fieldIdx);

            checkParamValidity(tmpName, tmpData);

            if(  uniquePars[structIdx].setParam(tmpName, (float)mxGetScalar(tmpData))  ) //The actual setting occurs here (returns TRUE on error)
            {
                std::string errMsg = std::string("Field named \"") + std::string(tmpName)
                                     + std::string("\" is not an existing field name in \"UNIQUE\" parameters");
                mexErrMsgTxt(errMsg.c_str());
            }
        }
    }

    //============= SHARED ================
    for (int fieldIdx=0; fieldIdx<numSharedParFields; ++fieldIdx)
    {
        tmpData = mxGetFieldByNumber(SHARED_PARS_IN, 0, fieldIdx);
        tmpName = mxGetFieldNameByNumber(SHARED_PARS_IN, fieldIdx);

        checkParamValidity(tmpName, tmpData);

        if(  sharedPars.setParam(tmpName, (float)mxGetScalar(tmpData))  ) //The actual setting occurs here (returns TRUE on error)
        {
            std::string errMsg = std::string("Field named \"") + std::string(tmpName)
                                 + std::string("\" is not an existing field name in \"SHARED\" parameters");
            mexErrMsgTxt(errMsg.c_str());
        }
    }


    //=======================================================================
    // *** Signal processing ***
    //=======================================================================
    AUDIO_DATA_OUT = mxCreateDoubleMatrix(xM,xN,mxREAL);

    double* out  = mxGetPr(AUDIO_DATA_OUT);
    double* in   = mxGetPr(AUDIO_DATA_IN);

    float*  in32  =  (float*)mxCalloc(totalNumElements, sizeof(float));
    float*  out32 =  (float*)mxCalloc(totalNumElements, sizeof(float));


    // ---------> DOWNCAST <---------
    for (int mm = 0; mm < totalNumElements; ++mm)
        in32[mm] = (float)in[mm];
    // ---------- DOWNCAST ----------

    // Make the data look like 2D C-style arrays
    //(this fits with other audio APIs [like VST] nicely)
    float* in2D[] =  {in32,  &in32[xM]};
    float* out2D[] = {out32, &out32[xM]};

    if(!isStereo) {
        cAidAlgo myAlgo(uniquePars[0], sharedPars);
        myAlgo.processSampleBlock ((const float**) in2D,  1,  (float**) out2D,   1,   xM);

    } else {
        if (isStereoPars) {
            cAidAlgo myAlgo(uniquePars[0], uniquePars[1], sharedPars);
            myAlgo.processSampleBlock ((const float**) in2D,  2,  (float**) out2D,   2,   xM);
        } else {
            cAidAlgo myAlgo(uniquePars[0], uniquePars[0], sharedPars);
            myAlgo.processSampleBlock ((const float**) in2D,  2,  (float**) out2D,   2,   xM);
        }
    }

    // ---------> UPCAST <---------
    for (int mm = 0; mm < totalNumElements; ++mm)
        out[mm] = (double)out32[mm];
    // ---------- UPCAST ----------


    mxFree(in32);
    mxFree(out32);

#ifdef MATLAB_VERBOSE
    // Play nice and restore the std stream buffer (not strictly necessary)
    std::cout.rdbuf(outbuf);
#endif//MATLAB_VERBOSE
}
/* The gateway routine */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
/* ----------------- Variables ----------------- */
/* input variables */
/* mandatory input */
  int startIdx;
  int endIdx;
  double * inReal;
/* optional input */
  int	 optInTimePeriod;
  int	 optInFastKPeriod;
  int	 optInFastDPeriod;
  double	 optInFastDMA;
/* output variables */ 
  int outBegIdx;
  int outNbElement;
  double*	 outFastK;
  double*	 outFastD;
/* input dimentions */ 
  int inSeriesRows;
  int inSeriesCols;
/* error handling */
  TA_RetCode retCode;

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

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

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

	retCode = TA_STOCHRSI(
                   startIdx, endIdx,
                   inReal,
                   optInTimePeriod,
                   optInFastKPeriod,
                   optInFastDPeriod,
                   optInFastDMA,
                   &outBegIdx, &outNbElement,
                   outFastK,                   outFastD);
/* -------------- Errors ---------------- */
   if (retCode) {
   	   mxFree(outFastK);
   	   mxFree(outFastD);
       mexPrintf("%s%i","Return code=",retCode);
       mexErrMsgTxt(" Error!");
   }
  
   // Populate Output
  plhs[0] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL);
  memcpy(((double *) mxGetData(plhs[0]))+outBegIdx, outFastK, outNbElement*mxGetElementSize(plhs[0]));
  mxFree(outFastK);  
  plhs[1] = mxCreateDoubleMatrix(outBegIdx+outNbElement,1, mxREAL);
  memcpy(((double *) mxGetData(plhs[1]))+outBegIdx, outFastD, outNbElement*mxGetElementSize(plhs[1]));
  mxFree(outFastD);  
} /* END mexFunction */
Exemple #22
0
void
mexFunction( int nlhs, mxArray *plhs[],
	     int nrhs, const mxArray *prhs[] )
{
  MATFile *ph;

  char *matfile;
  char *varnamelist[100];
  
  int   counter=0;
  
  if(nrhs==0) {
    /*
     * no arguments; so load by default from 'matlab.mat'
     */
    matfile=(char *)mxCalloc(11,sizeof(char));
    matfile=strcat(matfile,"matlab.mat");
  }
  else {
    /* 
     * parse the argument list for the
     * filename and any variable names 
     *
     * note: the first argument must be a filename.
     *       therefore you can't request specific
     *       variables from 'matlab.mat' without
     *       passing the filename in
     */
    
    /*
     * we're adding 5 to the size of the string.
     * 1 for '\0' and 4 in case the '.mat' was
     * forgotten
     */
    int buflen=mxGetN(prhs[0])+5;
    int index;
    
    /* filename */
    matfile=(char *)mxCalloc(buflen,sizeof(char));
    mxGetString(prhs[0],matfile,buflen);
    
    /* 
     * make sure '.mat' suffix exists
     */
    if(!strstr(matfile,"."))
      matfile=strcat(matfile,".mat");
    
    /* variable name list */
    for(index=1;index<nrhs;index++) {
      
      int varlength=mxGetN(prhs[index])+1;
      
      varnamelist[counter]=(char *)mxCalloc(varlength,sizeof(char));
      mxGetString(prhs[index],varnamelist[counter],varlength);
      
      counter++;
    }
  }

  /* open the MAT-File to read from */
  ph=matOpen(matfile,"r");

  if(ph<(MATFile *)3) {
    char errmsg[]="Failed to open '";
    
    strcat(errmsg,matfile);
    strcat(errmsg,"'");

    mxFree(matfile);
    mexErrMsgTxt(errmsg);
  }
  
  if(counter>0) {
    /* there where variables in the argument list */
    mxArray *var;
    int      index;
    
    for(index=0;index<counter;index++) {
      var=matGetVariable(ph,varnamelist[index]);
      mexPutVariable("caller", varnamelist[index],var);
      
      mxFree(varnamelist[index]);
    }
  }
  else {
    /* 
     * the variable argument list 
     * was empty so get everything 
     */
    mxArray *var;
    const char *var_name;
    
    while((var=matGetNextVariable(ph, &var_name))!=NULL) {
      mexPutVariable("caller", var_name, var);
    }
  }
  
  matClose(ph);
  mxFree(matfile);
}
Exemple #23
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,const mxArray *prhs[])
{
    mxArray *cell_element_ptr;
    char* last_dir = "*.flo |wc -l>>";
    char digit;
    float *outData;
    char databuf[4];
    mwSize number_of_dimensions, buflen;
    int N1,N2,i,width,height,flag,count,skip,filecount,selected,in;
    float tag,data;
    N1 = mxGetN(prhs[0]);
    skip=320*2*240*10;
    plhs[0]=mxCreateNumericMatrix(1,320*2*240*10*N1,mxSINGLE_CLASS,mxREAL);
    outData=mxGetPr(plhs[0]);
    #pragma omp parallel sections
    for (i=0; i<N1; i++) {
        char prefix_dir[200]="ls -lR ";
        char rm[25]="rm ";
        char tmpfile[20];
        cell_element_ptr = mxGetCell(prhs[0],i);
        N2 = mxGetN(cell_element_ptr);
        buflen = mxGetNumberOfElements(cell_element_ptr) + 1;
        char* buf = mxCalloc(buflen, sizeof(char));
        if (mxGetString(cell_element_ptr, buf, buflen) != 0) {
            mexErrMsgIdAndTxt( "MATLAB:explore:invalidStringArray","Could not convert string data.");
        }
        strcat(prefix_dir,buf);
        strcat(prefix_dir,last_dir);
        sprintf(tmpfile,"count_%03d.txt",i);
        strcat(prefix_dir,tmpfile);
        system(prefix_dir);
        FILE *dp = fopen(tmpfile,"r");
        filecount=0;
        while(!feof(dp)) {
            digit=fgetc(dp);
            if(digit>='0'&&digit<='9')
                filecount = filecount*10 + digit-'0';
            else break;
        }
        fclose(dp);
        strcat(rm,tmpfile);
        system(rm);
        if (filecount <= 10) selected = 0;
        else  selected = (int)rand()%(filecount-9);
        count=0;
        for (in=0; in<=9; in++) {
            char filename[250];
            sprintf(filename,"%sflownets-pred-%07d.flo",buf,selected+in);
            FILE *fp = fopen(filename,"rb+");
            flag=0;
            while(!feof(fp)) {
                if (flag==0) {
                    fscanf(fp,"%4c",databuf);
                    tag = *(float*)databuf;
                    fscanf(fp,"%4c",databuf);
                    width = *(int*) databuf;
                    fscanf(fp,"%4c",databuf);
                    height = *(int*) databuf;
                    flag=1;
                }
                fscanf(fp,"%4c",databuf);
                data = *(float*)databuf;
                outData[skip*i+count++] = data;
                if(count>=skip) {
                    break;
                }
            }
            fclose(fp);
        }
    }
}
//=========================================================================
void populate_object_flags(unsigned char *js,mxArray *plhs[], struct sdata *slog){
    //
    //  For each object, identify which "unique" object it belongs to and
    //  which index it has in that object.
    //
    //  Populates (into object_info structure)
    //  ---------------------------------------
    //  max_keys_in_object
    //  n_uniqe_objects: scalar 
    //  object_ids: array
    //  unique_object_first_md_indices: array
    //
    
    mxArray *object_info = plhs[0]; //mxGetField(plhs[0],0,"object_info");
    
    //TODO: Change this to numeric ...
    int n_objects = get_field_length2(object_info,"obj__next_sibling_index_object");
    
    if (n_objects == 0){
        slog->obj__n_unique_objects = 0;
        setStructField2(object_info,0,mxINT32_CLASS,0,E_obj__object_ids); 
        return;
    }
    
    
    //Main data info
    //-------------------------------------
    uint8_t *types = get_u8_field_by_number(plhs[0],E_types);
    int *d1 = get_int_field_by_number(plhs[0],E_d1);
    
    //TODO: Change this to numeric ...
    mwSize n_entries = get_field_length(plhs,"d1");

    //Information needed for this processing
    //---------------------------------------------------------------------
    //Object related
    uint8_t *object_depths = get_u8_field_by_number(object_info,E_obj__object_depths);
    int *child_count_object = get_int_field_by_number(object_info,E_obj__child_count_object);
    int *next_sibling_index_object = get_int_field_by_number(object_info,E_obj__next_sibling_index_object);
    int *n_objects_at_depth = slog->obj__n_objects_at_depth;
    
    mwSize n_depths = MAX_DEPTH_ARRAY_LENGTH; //get_field_length2(object_info,"n_objects_at_depth");
    
    //Some initial - meta setup
    //---------------------------------------------------------------------
    int *process_order = mxMalloc(n_objects*sizeof(int));
    populateProcessingOrder(process_order, types, n_entries, TYPE_OBJECT, n_objects_at_depth, n_depths, object_depths);
    
    //What is the max # of keys per object?
    int max_children = 0;
    for (int iObject = 0; iObject < n_objects; iObject++){
        if (child_count_object[iObject] > max_children){
            max_children = child_count_object[iObject];
        }
    }
    slog->obj__max_keys_in_object = max_children;
    
    if (max_children == 0){
        //So we only have an empty object
        int *unique_object_first_md_indices = mxMalloc(1*sizeof(int));
        unique_object_first_md_indices[0] = process_order[0];
        int *object_ids = mxCalloc(n_objects,sizeof(int));
        
    	setStructField2(object_info,unique_object_first_md_indices,
                mxINT32_CLASS,1,E_obj__unique_object_first_md_indices);
        setStructField2(object_info,object_ids,mxINT32_CLASS,n_objects,E_obj__object_ids); 
        slog->obj__n_unique_objects = 1;
        return;
    }

    //Key related
    //---------------------------------
    mxArray *key_info = plhs[0];
    mxArray *temp_key_p = mxGetFieldByNumber(key_info,0,E_key__key_p);
    unsigned char **key_p = (unsigned char **)mxGetData(temp_key_p);
    int *key_sizes = get_int_field_by_number(key_info,E_key__key_sizes);
    int *next_sibling_index_key = get_int_field_by_number(key_info,E_key__next_sibling_index_key); 

    //These are our outputs
    //---------------------------------------------------------------------
    //Which unique object, each object entry belongs to
    int *object_ids = mxMalloc(n_objects*sizeof(int));
    
    int n_unique_allocated;
    if (n_objects > N_INITIAL_UNIQUE_OBJECTS){
        n_unique_allocated = N_INITIAL_UNIQUE_OBJECTS;
    }else{
        n_unique_allocated = n_objects;
    }
        
    //We need this so that later we can go back and parse the keys
    //TODO: We could technically parse the keys right away ...
    int *unique_object_first_md_indices = mxMalloc(n_unique_allocated*sizeof(int));
    //---------------------------------------------------------------------
    
    //Variables for the loop 
    int cur_object_id = -1; //-1, allows incrementing into current value

    //po - process order
    int cur_po_index = 0; 
    int cur_object_md_index;
    int cur_object_data_index;
    
    int cur_key_data_index;
    int temp_key_md_index;
    int n_keys_current_object;
    
    int *object_key_sizes = mxMalloc(max_children*sizeof(int));
    unsigned char **object_key_pointers = mxMalloc(max_children*sizeof(unsigned char *));
    
    
    int last_obj_iter = -1;
    
    bool done = false;
    bool diff_object;
    
    //  Main Loop
    //---------------------------------------------------------------------
    while (!done){
        
        //Creation of a Reference Object
        //-----------------------------------------------------------------
        // - other objects will be compared to this object
        cur_object_md_index = process_order[cur_po_index];
        cur_object_data_index = RETRIEVE_DATA_INDEX(cur_object_md_index);
        n_keys_current_object = child_count_object[cur_object_data_index];
        
        object_ids[cur_object_data_index] = ++cur_object_id;
        
        //Logging of unique_object_first_data_indices
        //Technically we could post-process this bit ...
        //i.e. after assigning all objects unique ids, run through
        //and populate unique_object_first_data_indices
        if (cur_object_id >= n_unique_allocated){
            n_unique_allocated = 2*n_unique_allocated;
            if (n_unique_allocated > n_objects){
                n_unique_allocated = n_objects;
            }
            unique_object_first_md_indices = mxRealloc(unique_object_first_md_indices,
                    n_unique_allocated*sizeof(int));
        }
        
        unique_object_first_md_indices[cur_object_id] = cur_object_md_index; 


        //-----------------------------------------------------------------
        //Store key information for comparison to other objects ...
        //-----------------------------------------------------------------
        cur_key_data_index = RETRIEVE_DATA_INDEX((cur_object_md_index + 1));
        for (int iKey = 0; iKey < n_keys_current_object; iKey ++){
            object_key_sizes[iKey] = key_sizes[cur_key_data_index];
            object_key_pointers[iKey] = key_p[cur_key_data_index];
            
            temp_key_md_index = next_sibling_index_key[cur_key_data_index];
            cur_key_data_index = RETRIEVE_DATA_INDEX(temp_key_md_index);
        }
        
        //-----------------------------------------------------------------
        //      Loop through the other objects and compare
        //-----------------------------------------------------------------
        diff_object = false;
        while (!diff_object){
            ++cur_po_index;
            if (cur_po_index == n_objects){
                done = true;
                break;
            }
            
            cur_object_md_index = process_order[cur_po_index];
            cur_object_data_index = RETRIEVE_DATA_INDEX(cur_object_md_index);
            
            if (n_keys_current_object == child_count_object[cur_object_data_index]){
                
                //TODO
                //It might be better to combine these two loops
                
                //Here we check if the keys are the same length
                //---------------------------------------------------------
                cur_key_data_index = RETRIEVE_DATA_INDEX((cur_object_md_index + 1));
                for (int iKey = 0; iKey < n_keys_current_object; iKey ++){
                    if (object_key_sizes[iKey] != key_sizes[cur_key_data_index]){
                        diff_object = true;
                        break;
                    }
                    temp_key_md_index = next_sibling_index_key[cur_key_data_index];
                    cur_key_data_index = RETRIEVE_DATA_INDEX(temp_key_md_index);
                }    
                
                //Here we check if the key values are the same
                //---------------------------------------------------------
                if (!diff_object){
                    cur_key_data_index = RETRIEVE_DATA_INDEX((cur_object_md_index + 1));
                    for (int iKey = 0; iKey < n_keys_current_object; iKey ++){
                        
                        if (memcmp(object_key_pointers[iKey],
                                key_p[cur_key_data_index],object_key_sizes[iKey])){
                            diff_object = true;
                            break;
                        };
                        temp_key_md_index = next_sibling_index_key[cur_key_data_index];
                        cur_key_data_index = RETRIEVE_DATA_INDEX(temp_key_md_index);
                    }  
                }
                
                if (!diff_object){
                    object_ids[cur_object_data_index] = cur_object_id;
                }
                
            }else{
                diff_object = true;
            }
        }   
    }
    
    mxFree(object_key_pointers);
    mxFree(object_key_sizes);
    mxFree(process_order);
    
    //TODO: We could truncate these ...
    //TODO: Change to #2 method with enumeration ...
    setStructField2(object_info,unique_object_first_md_indices,
            mxINT32_CLASS,cur_object_id+1,E_obj__unique_object_first_md_indices);    
    setStructField2(object_info,object_ids,
            mxINT32_CLASS,n_objects,E_obj__object_ids); 
    slog->obj__n_unique_objects = cur_object_id+1;
}
/* entry point */
void mexFunction(int nlhs, mxArray *plhs[], 
                 int nrhs, const mxArray *prhs[])                
{
    int ind, i, x, y, o, dataDim, j, bytes_to_copy, nGaborFilter;
    const mxArray *f;
    const mxArray *pAS1Map;
    mxArray *outPA;
    mwSize ndim;
    const mwSize* dims;
    mwSize dimsOutput[2];
    void* start_of_pr;
    mxClassID datatype;

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

    StoreShift();
    Compute();
    
    /* =============================================
     * Handle output variables.
     * ============================================= 
     */
    
    /*
     * output variable 0: M1 map
     */
    dimsOutput[0] = 1; dimsOutput[1] = nGaborScale * nGaborOri;
	plhs[0] = mxCreateCellArray( 2, dimsOutput );
    dimsOutput[0] = sizexSubsample; dimsOutput[1] = sizeySubsample;
    for( i = 0; i < nGaborOri * nGaborScale; ++i )
    {
        outPA = mxCreateNumericArray( 2, dimsOutput, mxSINGLE_CLASS, mxREAL );
        /* populate the real part of the created array */
        start_of_pr = (float*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, M1Map[i], bytes_to_copy );
        mxSetCell( plhs[0], i, outPA );
    }
    
    /*
     * output variable 1: M1 trace
     */
    dimsOutput[0] = 1; dimsOutput[1] = nGaborScale * nGaborOri;
	plhs[1] = mxCreateCellArray( 2, dimsOutput );
    dimsOutput[0] = sizexSubsample; dimsOutput[1] = sizeySubsample;
    for( i = 0; i < nGaborOri * nGaborScale; ++i )
    {
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        /* populate the real part of the created array */
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, M1Trace[i], bytes_to_copy );
        mxSetCell( plhs[1], i, outPA );
    }
    
    /*
     * output variable 2: stored Gabor shifts : row shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[2] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, rowShift[i], bytes_to_copy );
        mxSetCell( plhs[2], i, outPA );
    }
    
    /*
     * output variable 3: stored Gabor shifts : col shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[3] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, colShift[i], bytes_to_copy );
        mxSetCell( plhs[3], i, outPA );
    }
    
    /*
     * output variable 4: stored Gabor shifts : orientation shifts
     */
    dimsOutput[0] = nGaborScale * nGaborOri; dimsOutput[1] = 1;
    plhs[4] = mxCreateCellArray( 2, dimsOutput );
    for( i = 0; i < nGaborScale*nGaborOri; ++i )
    {
        dimsOutput[0] = numShift; dimsOutput[1] = 1;
        outPA = mxCreateNumericArray( 2, dimsOutput, mxINT32_CLASS, mxREAL );
        start_of_pr = (int*)mxGetData(outPA);
        bytes_to_copy = dimsOutput[0] * dimsOutput[1] * mxGetElementSize(outPA);
        memcpy( start_of_pr, orientShift[i], bytes_to_copy );
        mxSetCell( plhs[4], i, outPA );
    }
}
void mexFunction ( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] )
{
	Dbptr	db;
	Tbl	*tbl;
	char	**sortfields;
	char	errmsg[STRSZ];
	int	i, arg_index, nvarargs;
	int	flags = 0;
	int	rc;

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

	nvarargs = nrhs - 1;
	for( i = 0; i<nvarargs; i++) 
	{
		arg_index = i + 1;
		if( mxGetClassID( prhs[arg_index] ) != mxCHAR_CLASS )
		{
			antelope_mexUsageMsgTxt ( USAGE );
			return;
		}
	}

	if( nvarargs > 0 )
	{
		tbl = newtbl( nvarargs );
		sortfields = (char **) mxCalloc( nvarargs, sizeof( char * ) );
		for( i = 0; i < nvarargs; i++ )
		{
			arg_index = i + 1;
			get_malloced_string( prhs[arg_index], &sortfields[i] );

			if( STREQ( sortfields[i], "dbSORT_UNIQUE" ) ) {

				flags |= dbSORT_UNIQUE;

			} else if( STREQ( sortfields[i], "dbSORT_REVERSE" ) ) {

				flags |= dbSORT_REVERSE;

			} else {

				pushtbl( tbl, sortfields[i] );
			}
		}
	}
	else
	{
		rc = dbquery ( db, dbPRIMARY_KEY, &tbl );
		antelope_mex_clear_register( 1 );
		if( rc == dbINVALID ) 
		{
			mexErrMsgTxt( "dbsort: query for primary keys failed" );
		}
	}

	db = dbsort ( db, tbl, flags, 0) ;
	antelope_mex_clear_register( 1 );

	if( nvarargs > 0 )
	{
		for( i = 0; i < nvarargs; i++ )
		{
			mxFree( sortfields[i] );
		}
		mxFree( sortfields );
		freetbl( tbl, 0 );
	}

	if( db.table == dbINVALID )
	{
		mexErrMsgTxt( "dbsort failed" );
	}

	plhs[0] = CreateDbptrStructFromDbptr( db );

	if( plhs[0] == NULL )
	{
		sprintf( errmsg, "dbsort: failed to create database-pointer " );
		strcat( errmsg, "structure for result" );
		mexErrMsgTxt( errmsg );
	}
}
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){
		int i;

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

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

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

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

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

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

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

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

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

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

		/* I assume that we can rely on the nifti routine to byte-swap for us? */
		nifti_image_write(nim);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
   /* Variables */
   int n, s,s1,s2,n1,n2,e, yInd,
   nNodes, nEdges, maxState, sizeYmap[3],
   *y,
   *edgeEnds, *nStates,*yMAP;
   
   double pot,maxPot,
   *nodePot, *edgePot;
   
   /* Input */
   
   nodePot = mxGetPr(prhs[0]);
   edgePot = mxGetPr(prhs[1]);
   edgeEnds = (int*)mxGetPr(prhs[2]);
   nStates = (int*)mxGetPr(prhs[3]);
   
   if (!mxIsClass(prhs[2],"int32")||!mxIsClass(prhs[3],"int32"))
        mexErrMsgTxt("edgeEnds and nStates must be int32");
   
   /* Compute Sizes */
   
   nNodes = mxGetDimensions(prhs[0])[0];
   maxState = mxGetDimensions(prhs[0])[1];
   nEdges = mxGetDimensions(prhs[2])[0];
   
   /* Output */
   sizeYmap[0] = nNodes;
   sizeYmap[1] = 1;
   plhs[0] = mxCreateNumericArray(2,sizeYmap,mxINT32_CLASS,mxREAL);
   yMAP = mxGetData(plhs[0]);
   
   /* Initialize */
   y = mxCalloc(nNodes,sizeof(int));
   maxPot = -1;
   while(1)
   {
      pot = 1;
      
   /* Node Potentials */
      for(n = 0; n < nNodes; n++)
      {
         pot *= nodePot[n + nNodes*y[n]];
      }
      
   /* Edge Potentials */
      for(e = 0; e < nEdges; e++)
      {
         n1 = edgeEnds[e]-1;
         n2 = edgeEnds[e+nEdges]-1;
         pot *= edgePot[y[n1] + maxState*(y[n2] + maxState*e)];
      }
      
      
      /* Compare potential of current configuration against best */
      if (pot > maxPot)
      {
        maxPot = pot;
        for(n = 0; n < nNodes;n++)
        {
            yMAP[n] = y[n]+1;
        }
      }
      
      
   /* Go to next y */
      
      for(yInd = 0; yInd < nNodes; yInd++)
      {
         y[yInd] += 1;
         if(y[yInd] < nStates[yInd])
         {
          break;  
         }
         else
         {
            y[yInd] = 0;
         }
      }

   /* Stop when we are done all y combinations */
      if(yInd == nNodes)
      {
         break;
      }
   }
   
   
   /* Free memory */
   mxFree(y);
}
Exemple #29
0
    void phasemethods( int nlhs, mxArray *plhs[],
        int nrhs, const mxArray *prhs[] )
    {
        double vv;
        int iok=0, k;
        int ph  = getInt(prhs[1]);
        int job = getInt(prhs[2]);
            
        bool ok = true;
        char* input_buf;
        double* ptr = 0;
        size_t nsp, n, m;
        int mjob, show_thermo;

        // methods to set attributes
        if (job < 0) {
            mjob = -job;
            if (mxIsChar(prhs[3]) != 1) {
                ptr = mxGetPr(prhs[3]);
            }
            m = mxGetM(prhs[3]);
            n = mxGetN(prhs[3]);
            
            nsp = phase_nSpecies(ph);
            
            // set scalar attributes
            bool ok = true;
            if (mjob < 10) {
                if (m != 1 || n != 1)
                    mexErrMsgTxt("value must be scalar.");

                switch (mjob) {
                case 1:
                    iok = phase_setTemperature(ph,*ptr); break; 
                case 2:
                    iok = phase_setDensity(ph,*ptr); break;
                default:
                    ok = false;
                }
            }

            // set array attributes
            else if (mjob < 30) {
                if ((m == nsp && n == 1) || (m == 1 && n == nsp)) {
                    int norm = 1;
                    switch (mjob) {
                    case 20:
                        iok = phase_setMoleFractions(ph, nsp, ptr, norm);
                        break;
                    case 21:
                        iok = phase_setMassFractions(ph, nsp, ptr, norm);
                        break;
                    case 22:
                        norm = 0;
                        iok = phase_setMoleFractions(ph, nsp, ptr, norm);
                        break;
                    case 23:
                        norm = 0;
                        iok = phase_setMassFractions(ph, nsp, ptr, norm);
                        break;
                    default:
                        ok = false;
                    }
                }
                else { 
                    mexErrMsgTxt("wrong array size");
                }
            }

            // set attributes from a string
            else {
                int status;
                mwSize buflen;
                char* input_buf;
                if (mxIsChar(prhs[3]) == 1) {
                    if(mxGetM(prhs[3]) != 1)
                        mexErrMsgTxt("Input must be a row vector.");
                    buflen = (mwSize) (mxGetM(prhs[3]) * mxGetN(prhs[3])) + 1;
                    input_buf = (char*)mxCalloc(buflen, sizeof(char));
                    status = mxGetString(prhs[3], input_buf, buflen);
                    if (status != 0) 
                        mexWarnMsgTxt("Not enough space. "
                            "String is truncated.");

                    switch (mjob) {
                    case 30:
                        iok = phase_setMoleFractionsByName(ph, input_buf);
                        break;
                    case 31:
                        iok = phase_setMassFractionsByName(ph, input_buf);
                        break;
                    case 32:
                        iok = phase_setName(ph, input_buf);
                        break;
                    default:
                        mexErrMsgTxt("what?");
                    }   
                }
                else {
                    mexErrMsgTxt("expected a string.");
                }
            }
        }

        else if (job < 20) {

            switch (job) {
            case 0:
                vv = (double) newThermoFromXML(ph); break;
                // floating-point attributes
            case 1:
                vv = phase_temperature(ph); break; 
            case 2:
                vv = phase_density(ph); break;
            case 3:
                vv = phase_molarDensity(ph); break;
            case 4:
                vv = phase_meanMolecularWeight(ph); break;
            case 8:
                vv = 1.0/phase_density(ph); break;            
            case 10:
                vv = (double) phase_nElements(ph); break;
            case 11:
                vv = (double) phase_nSpecies(ph); break;
            case 12:
                input_buf = getString(prhs[3]);
                vv = (double) phase_speciesIndex(ph, input_buf) + 1;
                break;
            case 13:
                input_buf = getString(prhs[3]);
                vv = (double) phase_elementIndex(ph, input_buf) + 1;
                break;
            case 14:
                k = getInt(prhs[3]);
                m = getInt(prhs[4]);
                vv = phase_nAtoms(ph,k-1,m-1); break;
            case 15:
                show_thermo = getInt(prhs[3]);
                vv = write_phase(ph,show_thermo); 
                break;
            default:
                ok = false;
            }
            if (ok) {
                if (vv == DERR) reportError();
                plhs[0] = mxCreateNumericMatrix(1,1,mxDOUBLE_CLASS,mxREAL);
                double *h = mxGetPr(plhs[0]);
                *h = vv;
                return;
            }
        }
        //ok = true;

        else if (job < 30) {

            iok = 0;
            size_t nsp = phase_nSpecies(ph);
            double* x = new double[nsp];
            switch (job) {
            case 20:
                iok = phase_getMoleFractions(ph,nsp,x);
                break;
            case 21:
                iok = phase_getMassFractions(ph,nsp,x);
                break;
            case 22:
                iok = phase_getMolecularWeights(ph,nsp,x);
                break;
            default:
                ;
            }
            plhs[0] = mxCreateNumericMatrix((mwSize) nsp,1,
                mxDOUBLE_CLASS,mxREAL);
            double *h = mxGetPr(plhs[0]);
            if (iok >= 0) {
                for (size_t i = 0; i < nsp; i++) h[i] = x[i];
                delete x;
                return;
            }
            else {
                for (size_t i = 0; i < nsp; i++) h[i] = -999.99;
                delete x;
                mexErrMsgTxt("unknown attribute");
                return;
            }
        }

        else if (job < 40) {

            iok = 0;
            size_t nel = phase_nElements(ph);
            double* x = new double[nel];
            switch (job) {
            case 30:
                iok = phase_getAtomicWeights(ph,nel,x);
                break;
            default:
                ;
            }
            plhs[0] = mxCreateNumericMatrix((mwSize) nel,1,
                mxDOUBLE_CLASS,mxREAL);
            double *h = mxGetPr(plhs[0]);
            if (iok >= 0) {
                for (size_t i = 0; i < nel; i++) h[i] = x[i];
                delete x;
                return;
            }
            else {
                for (size_t i = 0; i < nel; i++) h[i] = -999.99;
                delete x;
                mexErrMsgTxt("unknown attribute");
                return;
            }
        }

        else if (job < 50) {
            iok = -1;
            int ksp, mel;
            int buflen;
            char* output_buf;
            switch (job) {
            case 40:
                ksp = getInt(prhs[3]);
                buflen = 40;
                output_buf = (char*)mxCalloc(buflen, sizeof(char));
                iok = phase_getSpeciesName(ph, ksp-1, buflen, output_buf);
                break;
            case 41:
                mel = getInt(prhs[3]);
                buflen = 40;
                output_buf = (char*)mxCalloc(buflen, sizeof(char));
                iok = phase_getElementName(ph, mel-1, buflen, output_buf);
                break;
            case 42:
                buflen = 40;
                output_buf = (char*)mxCalloc(buflen, sizeof(char));
                iok = phase_getName(ph, buflen, output_buf);
                break;
            default:
                iok = -1;
            }
            if (iok >= 0) {
                plhs[0] = mxCreateString(output_buf);
                return;
            }
            else {
                mexErrMsgTxt("error or unknown method.");
                reportError();
                return;
            }
        }
        else {
            mexErrMsgTxt("unimplemented method.");
            return;
        }
        if (iok < 0) reportError();
    }
Exemple #30
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	
	double *px, cf, binwidth, reptime, cohc, cihc;
	int    nrep, pxbins, lp, outsize[2], totalstim;

	double *pxtmp, *cftmp, *nreptmp, *binwidthtmp, *reptimetmp, *cohctmp, *cihctmp;
	
    double *ihcout;
   
	void   SingleAN(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]);
	binwidthtmp	= 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");

    binwidth = binwidthtmp[0];
	
	reptime = reptimetmp[0];
	if (reptime<pxbins*binwidth)  /* duration of stimulus = pxbins*binwidth */
		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)/(binwidth*1e3));

    outsize[0] = 1;
	outsize[1] = totalstim;

    px = (double*)mxCalloc(outsize[1],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 */
	
	plhs[0] = mxCreateNumericArray(2, outsize, mxDOUBLE_CLASS, mxREAL);
	
	/* Assign pointers to the outputs */
	
	ihcout  = mxGetPr(plhs[0]);
		
	/* run the model */

	SingleAN(px,cf,nrep,binwidth,totalstim,cohc,cihc,ihcout);

 mxFree(px);

}