Beispiel #1
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    char *pOption = mxArrayToString( prhs[0] );
    if ( pOption )
    {
        std::string option = pOption;
        if ( option == "newRx" )
        {
            createMxArray(plhs[0], 1);
            createMxArray(plhs[1], reinterpret_cast<long int>( new usrplib::Rx() ));
        } else {
            char *error;
            sprintf(error, "Unrecognized option: %s", pOption);
        }
    } else {
        mexErrMsgTxt("Invalid option type! Must be a string.");
    }
}
Beispiel #2
0
/* Convert FLAME attributes specified as a string in MATLAB to the numerical values 
   required when calling FLAME C functions. */
int FLA_M2C_ConvertAttribute(const mxArray *mobj) {
  char *attr;
  int value;

  if (!mxIsChar(mobj)) {
    mexErrMsgTxt("Char array expected.");
  }
  else {
    /* Convert to C style string */
    attr = mxArrayToString(mobj);

    if (strcmp(attr, "FLA_NO_TRANSPOSE") == 0)
      value = FLA_NO_TRANSPOSE;
    else if (strcmp(attr, "FLA_TRANSPOSE") == 0)
      value = FLA_TRANSPOSE;
    else if (strcmp(attr, "FLA_CONJUGATE") == 0)
      value = FLA_CONJUGATE;
    else if (strcmp(attr, "FLA_NO_CONJUGATE") == 0)
      value = FLA_NO_CONJUGATE;
    else if (strcmp(attr, "FLA_CONJ_TRANSPOSE") == 0)
      value = FLA_CONJ_TRANSPOSE;
    else if (strcmp(attr, "FLA_LOWER_TRIANGULAR") == 0)
      value = FLA_LOWER_TRIANGULAR;
    else if (strcmp(attr, "FLA_UPPER_TRIANGULAR") == 0)
      value = FLA_UPPER_TRIANGULAR;
    else if (strcmp(attr, "FLA_NONUNIT_DIAG") == 0)
      value = FLA_NONUNIT_DIAG;
    else if (strcmp(attr, "FLA_UNIT_DIAG") == 0)
      value = FLA_UNIT_DIAG;
    else if (strcmp(attr, "FLA_ZERO_DIAG") == 0)
      value = FLA_ZERO_DIAG;
    else if (strcmp(attr, "FLA_LEFT") == 0)
      value = FLA_LEFT;
    else if (strcmp(attr, "FLA_RIGHT") == 0)
      value = FLA_RIGHT;
    else
      value = -1;

    mxFree(attr);
    
    return value;
  }

}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    double *data_set = mxGetPr(prhs[0]);
    unsigned dim = mxGetM(prhs[0]);
    unsigned size = mxGetN(prhs[0]);
    double *query_set = mxGetPr(prhs[1]);
    unsigned query_size = mxGetN(prhs[1]);
    double *params = mxGetPr(prhs[2]);
    std::string index = mxArrayToString(prhs[3]);
    plhs[0] = mxCreateDoubleMatrix(int(params[1]), mxGetN(prhs[1]), mxREAL);
    plhs[1] = mxCreateDoubleMatrix(int(params[1]), mxGetN(prhs[1]), mxREAL);
    double *indices = mxGetPr(plhs[0]);
    double *dists = mxGetPr(plhs[1]);
    lshbox::matkdbqLsh mylsh;
    mylsh.init(data_set, dim, size, index, unsigned(params[2]),
               unsigned(params[3]), unsigned(params[4]), unsigned(params[5]));
    mylsh.query(query_set, query_size, indices, dists,
                unsigned(params[0]), unsigned(params[1]));
}
Beispiel #4
0
void 
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
    char *str;
    (void) plhs;      /* unused parameter */

    /* Check for proper number of input and output arguments */    
    if (nrhs != 1) {
        mexErrMsgIdAndTxt( "MATLAB:mexatexit:invalidNumInputs",
                "One input argument required.");
    } 
    if(nlhs > 1){
        mexErrMsgIdAndTxt( "MATLAB:mexatexit:maxrhs",
                "Too many output arguments.");
    }
    if (!(mxIsChar(prhs[0]))){
        mexErrMsgIdAndTxt( "MATLAB:mexatexit:invalidInput",
                "Input must be of type string.\n.");
    }
    
    if (fp==NULL){
	fp = fopen("matlab.data", "w");
	if (fp == NULL){
	    mexErrMsgIdAndTxt( "MATLAB:mexatexit:errorOpeningFile",
                "Could not open file matlab.data."); 
	}
	mexPrintf("Opening file matlab.data.\n");
	
	/* Register an exit function. You should only register the
	   exit function after the file has been opened successfully*/
	mexAtExit(CloseStream);
    }
    /* The user passes a string in prhs[0]; write the string
       to the data file. NOTE: you must free str after it is used */ 
    str=mxArrayToString(prhs[0]);
    if ((size_t)fprintf(fp,"%s\n", str) != strlen(str) +1){
        mxFree(str);
        mexErrMsgIdAndTxt( "MATLAB:mexatexit:errorWritingFile",
                "Could not write data to file.\n");
    }
    mexPrintf("Writing data to file.\n");
    mxFree(str);
} 
void
mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
    int i;
    char *str[100];

    /* Check for proper number of input and output arguments */    
    if (nrhs < 2) {
	mexErrMsgTxt("At least two input arguments required.");
    } 
    if(nlhs > 1){
	mexErrMsgTxt("Too many output arguments.");
    }
    
    for (i=0; i<nrhs; i++){
	/* Check input to be sure it is of type char. */
	if(!mxIsChar(prhs[i])){
	    mexErrMsgTxt("Input must be of type char.");
	}
	/* Copy the string data from prhs and place it into str. */ 
        str[i] = mxArrayToString(prhs[i]); 
    }
    
    /* Create a 2-Dimensional string mxArray with NULL padding. */
    plhs[0]= mxCreateCharMatrixFromStrings(nrhs, (const char **)str); 

    /* If compile with -DSPACE_PADDING, convert NULLs to spaces */
#if defined(SPACE_PADDING)
    {
        int nelem = mxGetNumberOfElements(plhs[0]);
        mxChar *charData = (mxChar *)mxGetData(plhs[0]);
	for(i=0; i < nelem; i++) {
	    if(charData[i] == (mxChar) 0) {
	        charData[i] = (mxChar) ' ';
	    }
	}
    }
#endif
    /* Free the allocated memory */
    for (i=0; i<nrhs; i++){
        mxFree(str[i]); 
    }
}
Beispiel #6
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

	// make sure arguments are valid
	if( !CheckArgs( nlhs, nrhs, prhs ) )
	{
		PrintUsage();
		return;
	}

	char* dat_file_path = mxArrayToString( prhs[0] );

	if( dat_file_path == 0 )
	{
		mexPrintf( "dat_file_path needs to be strings!\n" );
		return;
	}

	// load data
	mexPrintf( "loading %s...\n", dat_file_path );
	MRIDataHeader header;
	std::vector<MRIMeasurement> meas_vector;
	if( !SiemensTool::LoadDatFile( dat_file_path, header, meas_vector ) )
		mexErrMsgTxt( "Loading dat file failed!\n" );

	// load measurements
	MRIData mri_data( header.Size(), header.IsComplex() );
	std::vector<MRIMeasurement>::iterator it;
	for( it = meas_vector.begin(); it != meas_vector.end(); it++ )
		if( !it->UnloadData( mri_data ) )
			mexErrMsgTxt( "MRIMasurement::UnloadData failed!\n" );
		
	// export
	plhs[0] = MexData::ExportMexArray( mri_data );

	if( nlhs > 1 )
	{
		mxArray* meas_struct = 0;
		CreateMeasStructure( meas_vector, &meas_struct );
		plhs[1] = meas_struct;
	}

	mexPrintf( "Done!\n" );
}
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
{
  const mxArray *cmd;
  int i;
  std::string cmdname, errString = "";
  char *tmp = 0;

  /* Check for proper number of arguments. */
  if(nrhs < 2) {
      errString += "At least two input arguments are required.\n";
      goto err_out;
  } else
      cmd = prhs[0];

  if (!mxIsChar(cmd)) {
      errString +=  "First argument must be a string.\n";
      goto err_out;
  }
  if (mxGetM(cmd) != 1) {
      errString += "First argument must be a row vector.\n";
      goto err_out;
  }
  tmp = mxArrayToString(cmd);
  cmdname = tmp;
  mxFree(tmp);
  for (i = 0; i < n_functions; ++i) {
      // try and match cmdname to a command we know about
    if (::strcmpi(functions[i].name, cmdname.c_str()) == 0 ) {
        // a match.., call function for the command, popping off first prhs
        functions[i].func(nlhs, plhs, nrhs-1, prhs+1); // call function by function pointer...
        return;
    }
  }
  if (i == n_functions) { // cmdname didn't match anything we know about
  err_out:
      errString += "Unrecognized CalinsNetMex command.\nMust be one of: ";
      for (int i = 0; i < n_functions; ++i)
          errString += std::string("\n'") + functions[i].name + "'";
      mexErrMsgTxt(errString.c_str());
  }
}
Beispiel #8
0
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
     char *dir_name;
     struct file *files;
     int nfiles, i;
     const char *field_names[2];

     if (nlhs > 1)
          mexErrMsgTxt("Too many output arguments.");
     
     if (nrhs == 0)
          dir_name = ".";
     else if (nrhs == 1) {
          if (mxIsChar(prhs[0]) != 1)
               mexErrMsgTxt("Input must be a string.");
          if (mxGetM(prhs[0]) != 1)
               mexErrMsgTxt("Input must be a row vector.");
          dir_name = mxArrayToString(prhs[0]);
     } else
          mexErrMsgTxt("Too many input arguments.");

     files = dir(dir_name, &nfiles);

     field_names[0] = "name";
     field_names[1] = "isdir";
     plhs[0] = mxCreateStructMatrix(nfiles, 1, 2, field_names);

     for (i = 0; i < nfiles; i++) {
          mxSetFieldByNumber(plhs[0], i, 0, mxCreateString(files[i].name));
          mxSetFieldByNumber(plhs[0], i, 1,
                             mxCreateLogicalScalar(files[i].is_dir));
     }

     for (i = 0; i < nfiles; i++)
          mxFree(files[i].name);
     mxFree(files);
     if (nrhs > 0)
          mxFree(dir_name);
     return;
}
// print_msg
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    size_t ncin_ = mxGetScalar(prhs[0]);
    char* pcin_ = mxArrayToString(prhs[1]);
    excentury::STextInterface<excentury::load_mode> XC_LI_(pcin_, ncin_);
    std::string msg; XC_LI_.load(msg);
    XC_LI_.close();

    fprintf(stderr, "%s\n", msg.c_str());

    excentury::STextInterface<excentury::dump_mode> XC_DI_;
    
    XC_DI_.close();
    std::string xc_mex_str_ = XC_DI_.str();
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    double* ncout_ = mxGetPr(plhs[0]);
    ncout_[0] = xc_mex_str_.size();
    plhs[1] = mxCreateString(xc_mex_str_.data());
    mxFree(pcin_);
}
Beispiel #10
0
void sendString(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  NetClient *nc = GetNetClient(nrhs, prhs);
  
  if(nrhs != 2)		mexErrMsgTxt("Two arguments required: handle, string.");
  //if(nlhs < 1) mexErrMsgTxt("One output argument required.");
  if(mxGetClassID(prhs[1]) != mxCHAR_CLASS) 
	  mexErrMsgTxt("Argument 2 must be a string.");

  char *tmp = mxArrayToString(prhs[1]);
  std::string theString (tmp);
  mxFree(tmp);

  try {
    nc->sendString(theString);
  } catch (const SocketException & e) {
    mexWarnMsgTxt(e.why().c_str());
    RETURN_NULL();
  }  
  RETURN(1);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { 
    if (nrhs != 3) {
        mexErrMsgTxt("Must have 3 inputs"); 
    }
    if (nlhs != 0) {
        mexErrMsgTxt("Must have 0 outputs");
    }

    // Read images
    if (!mxIsUint8(prhs[0]) || mxGetNumberOfDimensions(prhs[0]) != 4) {
        mexErrMsgTxt("images must be a 4D uint8 array");
    }
    uint8_t* images = (uint8_t*) mxGetData(prhs[0]);
    const mwSize* images_size = mxGetDimensions(prhs[0]);
    int width = images_size[0];
    int height = images_size[1];
    int num_channels = images_size[2];
    if (num_channels != 3) {
        mexErrMsgTxt("Expected 3 channels for images");
    }
    int num_images = images_size[3];
    int img_length = width * height * num_channels;
    std::cout << "Image info: width: " << width << " height: " << height << " channels: " << num_channels << " num: " << num_images << std::endl;

    // Read serialized triplets
    if (!mxIsInt32(prhs[1]) || mxGetN(prhs[1]) != 1) {
        mexErrMsgTxt("triplets must have type int32 and have 1 column");
    }
    int32_t* serialized_triplets = (int32_t*) mxGetData(prhs[1]);
    int num_examples = mxGetM(prhs[1]);

    // Read db filename
    char* db_filename = mxArrayToString(prhs[2]);
    printf("%s\n", db_filename);

    google::InitGoogleLogging("triplets_to_caffedb");
    process(images, num_images, width, height, serialized_triplets, num_examples, db_filename);
    
    mxFree(db_filename);
}
/* The gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    char *problem_suite;
    int findex;
    coco_problem_t *pb = NULL;
    long long *res; 

    /* check for proper number of arguments */
    if(nrhs!=2) {
        mexErrMsgIdAndTxt("cocoSuiteGetProblem:nrhs","Two inputs required.");
    }
    /* get problem_suite */
    problem_suite = mxArrayToString(prhs[0]);
    /* get function_index */
    findex = (int)mxGetScalar(prhs[1]);
    /* call coco_suite_get_problem() */
    pb = coco_suite_get_problem(problem_suite, findex);
    /* prepare the return value */
    plhs[0] = mxCreateNumericMatrix(1, 1 ,mxINT64_CLASS, mxREAL);
    res = (long long *)mxGetData(plhs[0]);
    *res = (long long)pb;   
}
Beispiel #13
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Check number of arguments
	if (nlhs != 0 || nrhs != 2)
		mexErrMsgTxt("Unexpected number of arguments.");
    const char* fname = mxArrayToString(prhs[1]);
    if (fname == NULL )
        mexErrMsgTxt("Second input argument expected to be a filename.");
        
    // Parse the object
    std::unique_ptr<json> j(new json);
    recurse_object(prhs[0], *j);
    
    // Write out the file
    std::ofstream fs(fname);
    if (!fs.is_open())
        mexErrMsgTxt("Failed to open file for writing.");
    fs << std::setw(2);
    fs << std::setprecision(17);
    fs << *j << std::endl;
    fs.close();
}
Beispiel #14
0
// Get parameters from inputs
int getParams(const int nrhs, const mxArray *prhs[], short& L, unsigned int& maxIter, \
			  short& nRes, string& dist, bool& isVerbose) {
  
  // Get L
  L = (short)mxGetScalar(prhs[2]);
  
  // Get options
  maxIter   = (unsigned int)10000;
  nRes      = (unsigned int)1;
  dist      = "l1";
  isVerbose = true;
    
  if (nrhs >= 4) {
    // Get option "maxIter"
    mxArray* bufMaxIter = mxGetField(prhs[3],0,"maxIter");
    if ( bufMaxIter != NULL )
      maxIter = (unsigned int)mxGetScalar(bufMaxIter);

	// Get option "nRes"
    mxArray* bufRes = mxGetField(prhs[3],0,"nRes");
    if ( bufRes != NULL )
      nRes = (short)mxGetScalar(bufRes);

    // Get option "dist"
    mxArray* bufDist = mxGetField(prhs[3],0,"dist");
    if ( bufDist != NULL )
      dist = mxArrayToString(bufDist);
        
    // Get option "isVerbose"
    mxArray* bufVerb = mxGetField(prhs[3],0,"isVerbose");
    if ( bufVerb != NULL )
      isVerbose = (mxGetScalar(bufVerb) == 1.0f);
  }
    
  // Display
  mexPrintf("+ Load parameters: L=%d, ", L);
  mexPrintf("maxIter=%d, nRes=%d, dist=\"%s\", isVerbose=%d\n", maxIter, nRes, dist.c_str(), isVerbose);
  return 0;
}
Beispiel #15
0
void mexFunction(int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[]) {

	/* Declarations */
	char *filename = NULL;
	
	if (nlhs>0) {
	  mexErrMsgTxt("Bad number of output arguments");
	}
	/* Input */
	switch(nrhs) {
	case 0:
	  break;
	case 1:
	  filename = mxArrayToString(prhs[0]);
	  break;
	default:
	  mexErrMsgTxt("Bad number of arguments");
	}

  /* Register the display functions */
  /* We could set a flag variable to do it only once */
    MPTK_Server_c::get_msg_server()->register_display_function("info_message_display", &msgfunc);
    MPTK_Server_c::get_msg_server()->register_display_function("error_message_display", &msgfunc);
    MPTK_Server_c::get_msg_server()->register_display_function("warning_message_display", &msgfunc);
    MPTK_Server_c::get_msg_server()->register_display_function("progress_message_display", &msgfunc);
    MPTK_Server_c::get_msg_server()->register_display_function("debug_message_display", &msgfunc);


	if (!MPTK_Env_c::get_env()->load_environment_if_needed(filename)) {
	  mexPrintf("Could not load environment");
	  mxFree(filename);
	  mexErrMsgTxt("Aborting");
	} else {
	  mxFree(filename);
	}
	
}
Beispiel #16
0
// matlab helper function
void MatReadCodingOpt(const mxArray * mat_opt, CodingOpt * opt)
{
    mxArray * mx_name = mxGetField(mat_opt, 0, "name");
    ASSERT(mx_name != NULL);    
    opt->name = mxArrayToString(mx_name);
    
//     mexPrintf("%s\n", opt->name);
    
    // get parameters    
    mxArray * mx_param = mxGetField(mat_opt, 0, "param");
    if(mx_param == NULL || mxGetNumberOfElements(mx_param) == 0)
    {
        opt->param = NULL;
        opt->nparam = 0;
    }
    else
    {
        opt->param = (double *)mxGetPr(mx_param);
        opt->nparam = mxGetNumberOfElements(mxGetField(mat_opt, 0, "param"));    
    }
    
    
#ifdef CODING_NAME
    opt->func_init = NULL;
    opt->func_proc = NULL;
#else
    if(!CodingSelect(opt))
    {        
        mexPrintf("%s\n", opt->name);
        mexErrMsgTxt("Coding method is not implemented");
    }
#endif    
    
    // get codebook
    MatReadFisherVectorCodebook(mxGetField(mat_opt, 0, "fv_codebook"), &opt->fv_codebook);    
    MatReadVectorQuantizationCodebook(mxGetField(mat_opt, 0, "vq_codebook"), &opt->vq_codebook);    
}
// entry point
void mexFunction(int nlhs,mxArray *plhs[], int nrhs,const mxArray *prhs[]) 
{
  char* str;
  str = mxArrayToString(prhs[0]);

  if ( 0 == strcmp(str,"train") ) {
    train(nlhs,plhs, nrhs,prhs);
  }
  else if ( 0 == strcmp(str,"get") ) {
    get(nlhs,plhs, nrhs,prhs);
  }
  else if ( 0 == strcmp(str,"predict") ) {
    predict(nlhs,plhs, nrhs,prhs);
  }
  else if ( 0 == strcmp(str,"delete") ) {
    del(nlhs,plhs, nrhs,prhs);
  }
  else if ( 0 == strcmp(str,"save") ) {
    save(nlhs,plhs, nrhs,prhs);
  }
  else {
    mexErrMsgTxt("pSampVTLogitBoost_mex::unknown option.");
  }
}
Beispiel #18
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    bool status    = false;
    char *filename = NULL;
    FILE *fid      = NULL;

    if (nrhs != 1)
        mexErrMsgTxt("One input only required.");
    else
    {
        if (!mxIsChar(prhs[0]))
            mexErrMsgTxt("Input must be a string.");
        filename = mxArrayToString(prhs[0]);
        fid = fopen(filename,"r");
        if (fid != NULL)
        {
            status = true;
            fclose(fid);
        }
        mxFree(filename);
    }

    plhs[0] = mxCreateLogicalScalar(status);
}
Beispiel #19
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	char* dat_file_path = mxArrayToString( prhs[0] );

	if( dat_file_path == 0 )
	{
		mexPrintf( "dat_file_path needs to be a string.\n" );
		return;
	}

	MRIDataHeader header;
	std::vector<MRIMeasurement> meas_vector;
	SiemensTool::LoadDatFile( dat_file_path, header, meas_vector );
		
	MRIData mri_data( header.Size(), true );

	std::vector<MRIMeasurement>::iterator it;
	for( it = meas_vector.begin(); it != meas_vector.end(); it++ )
		if( !it->UnloadData( mri_data ) )
			GIRLogger::LogError( "DataSorter::SortReplace -> MRIMasurement::UnloadData failed, measurement was not added!\n" );

	mexPrintf( "header size: %s\n", header.Size().ToString().c_str() );

	plhs[0] = MexData::ExportMexArray( mri_data );
}
Beispiel #20
0
void mexFunction(int nlhs, mxArray* plhs[], const int nrhs, const mxArray* prhs[]) {
  if (nrhs != 1) {
    mexErrMsgTxt("Number of arguments must be exactly 1.");
  } else if (!mxIsChar(prhs[0])) {
    mexErrMsgTxt("Input must be a string.");
  }

  // get the length of the filename.
  mwSize filename_length = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1;
  char *filename = mxArrayToString(prhs[0]);
  
  FILE* fp = fopen(filename, "r");
  if (fp == NULL) {
    mexErrMsgIdAndTxt("filename:notFound", "file %s not found", filename);
  }
  
  int data_size = get_data_size(fp);
  if (data_size != sizeof(freenect_raw_tilt_state)) {
    mexErrMsgIdAndTxt("filename:notAccel",
        "file %s's size doesnt match freenect_raw_tilt_state.", filename);
  }
  
  freenect_raw_tilt_state state;
  fread(&state, sizeof(state), 1, fp);
  
  mwSize ndim = 2;
  const mwSize dim_size[] = {4, 1};
  plhs[0] = mxCreateNumericArray(ndim, dim_size, mxDOUBLE_CLASS, mxREAL);
  double* output_data = (double*) mxGetData(plhs[0]);
  output_data[0] = state.accelerometer_x;
  output_data[1] = state.accelerometer_y;
  output_data[2] = state.accelerometer_z;
  output_data[3] = state.tilt_angle;
  
  fclose(fp);
}
Beispiel #21
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]){
	static const struct dispatch_entry dispatch[] = {
		{ "init", &S4mex_init },
		{ "new", &S4mex_Simulation_New },
		{ "destroy", &S4mex_Simulation_Destroy },
		{ "set_material", &S4mex_Simulation_SetMaterial },
		{ "add_layer", &S4mex_Simulation_AddLayer },
		{ "set_layer_thickness", &S4mex_Simulation_SetLayerThickness },
		{ "add_layer_copy", &S4mex_Simulation_AddLayerCopy },
		{ "set_layer_region", &S4mex_Simulation_SetLayerRegion },
		{ "set_planewave", &S4mex_Simulation_SetPlanewave },
		{ "set_frequency", &S4mex_Simulation_SetFrequency },
		{ "get_bases", &S4mex_Simulation_GetBases },
		{ "get_power_flux", &S4mex_Simulation_GetPowerFlux },
		{ "get_waves", &S4mex_Simulation_GetWaves },
		{ NULL, NULL }
	};
	const struct dispatch_entry *entry = &dispatch[0];
	const char *cmd = NULL;
	
	mexAtExit(&ExitFcn);
	if(!(mxIsChar(prhs[0]))){
		mexErrMsgIdAndTxt("S4:invalidInput", "First argument must be of type string.");
	}
	cmd = mxArrayToString(prhs[0]);
	while(NULL != entry->cmd){
		if(0 == strcmp(cmd, entry->cmd)){
			entry->handler(nlhs, plhs, nrhs, prhs);
			return;
		}
		entry++;
	}
	if(NULL == entry->cmd){
		mexErrMsgIdAndTxt("S4:invalidInput", "Unrecognized command.");
	}
}
// scale_array
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    size_t ncin_ = mxGetScalar(prhs[0]);
    char* pcin_ = mxArrayToString(prhs[1]);
    excentury::STextInterface<excentury::load_mode> XC_LI_(pcin_, ncin_);
    excentury::DynamicTensor<1, double, 0, 1> v; XC_LI_.load(v, v[0]);
    double s; XC_LI_.load(s);
    XC_LI_.close();

    for (unsigned int i=0; i < v.dim(); ++i) {
        v[i] *= s;
    }

    excentury::STextInterface<excentury::dump_mode> XC_DI_;
    XC_DI_.dump(v, "v");
    XC_DI_.close();
    std::string xc_mex_str_ = XC_DI_.str();
    plhs[0] = mxCreateDoubleMatrix(1, 1, mxREAL);
    double* ncout_ = mxGetPr(plhs[0]);
    ncout_[0] = xc_mex_str_.size();
    plhs[1] = mxCreateString(xc_mex_str_.data());
    mxFree(pcin_);
}
Beispiel #23
0
int bytesToMx(mxArray **mx, const char *byteArray, int byteArrayLength) {
    int ii;
    int nInfoBytes=0, nFreeBytes=0, nBytesRead=0;
    mxGramInfo info;
    
    // for complex types
    int jj;
    int nElements;
    mxArray *elementData;
    mxArray *elementName;
    const char *elementByteArray;
    int elementBytesRead;
    char **fieldNames;
    
    mxArray *callMatlabError;
    
    info.gramBytes = (char *)byteArray;
    nInfoBytes = readInfoFieldsFromBytes(&info, byteArray, byteArrayLength);
    nBytesRead += nInfoBytes;
    
    info.dataBytes = (char *)byteArray + MX_GRAM_OFFSET_DATA;
    nFreeBytes = byteArrayLength - MX_GRAM_OFFSET_DATA;
    
    //printMxGramInfo(&info);
    //printBytes(info.gramBytes, info.gramLength);
    
    if (info.gramType==mxGramDouble) {
        *mx = mxCreateDoubleMatrix(info.dataM, info.dataN, mxREAL);
        nBytesRead += readMxDoubleDataFromBytes(*mx, &info, nFreeBytes);
        
    } else if (info.gramType==mxGramChar) {
        mwSize dims[2];
        dims[0] = info.dataM;
        dims[1] = info.dataN;
        *mx = mxCreateCharArray(2, dims);
        nBytesRead += readMxCharDataFromBytes(*mx, &info, nFreeBytes);
        
    } else if (info.gramType==mxGramLogical) {
        *mx = mxCreateLogicalMatrix(info.dataM, info.dataN);
        nBytesRead += readMxLogicalDataFromBytes(*mx, &info, nFreeBytes);
        
    } else if (info.gramType==mxGramCell) {
        *mx = mxCreateCellMatrix(info.dataM, info.dataN);
        
        nElements = info.dataM * info.dataN;
        elementByteArray = info.dataBytes;
        elementBytesRead = 0;
        
        for (ii=0; ii<nElements; ii++) {
            elementBytesRead = bytesToMx(&elementData, elementByteArray, nFreeBytes);
            if (elementBytesRead > 0) {
                mxSetCell(*mx, ii, elementData);
                nBytesRead += elementBytesRead;
                elementByteArray += elementBytesRead;
                nFreeBytes -= elementBytesRead;
            }
        }
        
    } else if (info.gramType==mxGramStruct) {
        
        // struct arrays may have size 1xn, with m fields
        nElements = info.dataM;
        fieldNames = mxMalloc(nElements*sizeof(char*));
        
        // recur to read out fieldNames
        elementByteArray = info.dataBytes;
        for (ii=0; ii<nElements; ii++) {
            elementBytesRead = bytesToMx(&elementName, elementByteArray, nFreeBytes);
            fieldNames[ii] = mxArrayToString(elementName);
            mxDestroyArray(elementName);
            
            nBytesRead += elementBytesRead;
            elementByteArray += elementBytesRead;
            nFreeBytes -= elementBytesRead;
        }
        
        *mx = mxCreateStructMatrix(1, info.dataN, info.dataM, (const char **)fieldNames);
        mxFree(fieldNames);
        
        // recur to fill in field data
        for (ii=0; ii<nElements; ii++) {
            for (jj=0; jj<info.dataN; jj++) {
                elementBytesRead = bytesToMx(&elementData, elementByteArray, nFreeBytes);
                mxSetFieldByNumber(*mx, jj, ii, elementData);
                
                nBytesRead += elementBytesRead;
                elementByteArray += elementBytesRead;
                nFreeBytes -= elementBytesRead;
            }
        }
        
    } else if (info.gramType==mxGramFunctionHandle) {
        // recur to read out stringified version of function
        elementBytesRead = bytesToMx(&elementData, info.dataBytes, nFreeBytes);
        if (elementBytesRead > 0) {
            nBytesRead += elementBytesRead;
            callMatlabError = mexCallMATLABWithTrap(1, mx, 1, &elementData, MX_GRAM_STRING_TO_FUNCTION);
        }
        
    } else {
        *mx = mxCreateDoubleScalar(-1);
        nBytesRead = 0;
    }
    
    return(nBytesRead);
}
/* Gateway function with Matlab */
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[]) {
    char *cmd;
    /* If no input argument, print out the usage */
    if (nrhs == 0) {
        mexErrMsgTxt("Usage: messenger('init|listen|respond', extra1, extra2, ...)");
    }

    /* Get the input command */
    if(!(cmd = mxArrayToString(prhs[0]))) {
        mexErrMsgTxt("Cannot read the command");
    }

    /* Initialize a new server session */
    if (strcmp(cmd, "init") == 0) {
        char *socket_addr;
        mxLogical *p;

        /* Check if the input format is valid */
        if (nrhs != 2) {
            mexErrMsgTxt("Missing argument: socket address");
        }
        if (!(socket_addr = mxArrayToString(prhs[1]))) {
            mexErrMsgTxt("Cannot read socket address");
        }

        plhs[0] = mxCreateLogicalMatrix(1, 1);
        p = mxGetLogicals(plhs[0]);

        if (!initialized) {
            if (!initialize(socket_addr)) {
                p[0] = 1;
                mexPrintf("Socket created at: %s\n", socket_addr);
            } else {
                p[0] = 0;
                mexErrMsgTxt("Socket creation failed.");
            }
        } else {
            mexErrMsgTxt("One socket has already been initialized.");
        }

        return;

    /* Listen over an existing socket */
    } else if (strcmp(cmd, "listen") == 0) {
        char *recv_buffer = mxCalloc(BUFLEN, sizeof(char));

        int byte_recvd = listen_zmq(recv_buffer, BUFLEN);

        while (byte_recvd == -1 && errno == EAGAIN) {
        	mexCallMATLAB(0, NULL, 0, NULL, "drawnow");
        	byte_recvd = listen_zmq(recv_buffer, BUFLEN);
       	}

        /* Check if the received data is complete and correct */
        if ((byte_recvd > -1) && (byte_recvd <= BUFLEN)) {
            plhs[0] = mxCreateString(recv_buffer);
        } else if (byte_recvd > BUFLEN){
            mexErrMsgTxt("Receiver buffer overflow. Message truncated");
        } else {
        	sprintf(recv_buffer, "Failed to receive a message due to ZMQ error %s", strerror(errno));
            mexErrMsgTxt(recv_buffer);
        }

        return;

    /* Send a message out */
    } else if (strcmp(cmd, "respond") == 0) {
        size_t msglen;
        char *msg_out;
        mxLogical *p;

        /* Check if the input format is valid */
        if (nrhs != 2) {
            mexErrMsgTxt("Please provide the message to send");
        }

        msglen = mxGetNumberOfElements(prhs[1]);
        msg_out = mxArrayToString(prhs[1]);

        plhs[0] = mxCreateLogicalMatrix(1, 1);
        p = mxGetLogicals(plhs[0]);

        if (msglen == respond(msg_out, msglen)) {
            p[0] = 1;
        } else {
            p[0] = 0;
            mexErrMsgTxt("Failed to send message due to ZMQ error");
        }

        return;

    /* Close the socket and context */
    } else if (strcmp(cmd, "exit") == 0) {
        cleanup();

        return;
    } else {
        mexErrMsgTxt("Unidentified command");
    }
}
Beispiel #25
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

	struct	EULER *p;		/* Pointer to array of stage poles */
	struct	ISOC_SCALE *isoc_scale;	/* Pointer to array of time scale */
	int	error = FALSE, brick = FALSE, age_flow = FALSE;
	int	multi_flow = FALSE, first_seg = TRUE, invert_rot = FALSE, linear_age = FALSE;
	int	np_in_seg, switch_xy = FALSE, first = TRUE, n_flow, isoc_c = FALSE, isoc_cm = TRUE;
	int	n_seg;			/* Number of segments in input data */
	int	m, i_min = 0, int_seg = FALSE, ts_file = FALSE, isoc_p = FALSE, isoc_o = FALSE;
	int	data_in_input = FALSE, ages_given = FALSE, fake_origin = FALSE;
	int     i, ii, j, jj, k, l, ll, ndata, n_alloc, ix = 0, iy = 1, ns;
	int	n_stages;		/* Number of stage poles */
	int	n_isoc;			/* Number of isochrons in time scale */
	int 	n_chunk;		/* Total length or array returned by libeuler functions */
	int	argc, n_arg_no_char = 0, np_in, np_out;
	double	in[2], lon, lat, *tmp, *out, *out2, *out_n_data, *out_n_seg, *out_n_flow;
	double	upper_age = 0.0;	/* Extend oldest age back to this time, in Ma */
	double	t_zero = 0.0;		/* Current age in Ma */
	double	age = 0.0;		/* Age of isochron, in Ma */
	double	age_shift = 0.0;	/* Fake the chron table by shifting it by this amount, in Ma */
	double	*c;			/* Array com os pts de todos os tijolos de cada seg */
	double	filter_width = 0.001;	/* Full width of filter in user's units */
	double	dl = 0.05;		/* Delta resolution in degrees for along segment interpolation */
	double	ddeg = 0.005;		/* Delta resolution in degrees for flow interpolation */
	double	age_lin_start, age_lin_stop, age_lin_inc, *first_mag;
	double	ecc2_1 = (1 - 0.0818191908426215 * 0.0818191908426215);	/* Parameter for convertion to geocentrics in WGS84 */
	char	line[MAXCHAR], *newseg = ">";
	char	*euler_file = NULL;	/* Name pointer for file with stage poles */
	char	*t_scale = NULL;	/* Name pointer for file with time scale */
	char	**argv;
	FILE    *fp = NULL, *fp_ts = NULL;
	
	argc = nrhs;
	for (i = 0; i < nrhs; i++) {		/* Check input to find how many arguments are of type char */
		if(!mxIsChar(prhs[i])) {
			argc--;
			n_arg_no_char++;	/* Number of arguments that have a type other than char */
		}
	}
	argc++;					/* to account for the program's name to be inserted in argv[0] */

	/* get the length of the input string */
	argv=(char **)mxCalloc(argc, sizeof(char *));
	argv[0] = "telha";
	for (i = 1; i < argc; i++)
		argv[i] = (char *)mxArrayToString(prhs[i+n_arg_no_char-1]);

	for (i = 1; i < argc; i++) {
		if (argv[i][0] == '-') {
			switch (argv[i][1]) {
 		
				/* Common parameters */
			
				case '\0':
					error = TRUE;
					break;
				case ':':
					switch_xy = TRUE;
					break;
				case 'A':
					age_flow = TRUE;
					break;
				case 'B':
					brick   = TRUE;
					break;
				case 'C':
					if (strlen (&argv[i][2]) == 1) { /* use one of default time scales */
						if (strcmp (&argv[i][2], "P") == 0) /* Patriat */
							isoc_p = TRUE;
						else if (strcmp (&argv[i][2], "C") == 0) /* Cande & Kent 95 */
							isoc_c = TRUE;
						else if (strcmp (&argv[i][2], "O") == 0) /* Cande (old scale given by Patriat)*/
							isoc_o = TRUE;
						else if (strcmp (&argv[i][2], "M") == 0) /* Cande & Kent 95 + Malinverno 2012 */
							isoc_cm = TRUE;
						else
							mexPrintf ("SYNTAX ERROR -C option: Must choose only between -CP (Patriat) or -CC (Cande)\n");
					}
					else {
						t_scale = &argv[i][2];
						ts_file = TRUE;
					}
					break;
				case 'D':
					ddeg = atof (&argv[i][2]);
					break;
				case 'E':	/* File with stage poles */
					euler_file  = &argv[i][2];
					break;
				case 'F':
					filter_width = atof (&argv[i][2]);
					break;
				case 'G':
					multi_flow = TRUE;
					break;
				case 'I':
					invert_rot = TRUE;
					break;
				case 'L':
					sscanf (&argv[i][2], "%lf/%lf/%lf", &age_lin_start, &age_lin_stop, &age_lin_inc);
					linear_age = TRUE;
					break;
				case 'N':	/* Extend oldest stage back to this time [no extension] */
					upper_age = atof (&argv[i][2]);
					break;
				case 'O':
					age_shift = fabs(atof (&argv[i][2]));
					fake_origin = TRUE;
					break;
				case 'P':
					ages_given = TRUE;
					break;
				case 'S':
					dl = atof (&argv[i][2]);
					int_seg = TRUE;
					break;
				case 'T':	/* Current age [0 Ma] */
					t_zero = atof (&argv[i][2]);
					break;
				default:
					error = TRUE;
					break;
			}
		}
		else {
			if (!data_in_input && argv[i][0] != ' ') {
				if ((fp = fopen(argv[i], "r")) == NULL) {
					mexPrintf("%s:  Cannot open %s\n", "telha", argv[i]);
					error = TRUE;
				}
			}
		}
	}

	if (argc == 1) {	/* Display usage */
 		mexPrintf ("Telha - 3D magnetic modeling program\n");
		mexPrintf("usage:  telha infile -E<euler> -N<upper_age> [-A] [-T<t_zero>] [-F<filterwidth>] [-G] [-I] [-B] [-D<inc_deg>] [-S<inc_deg>] [-C[P|C][<time_scale>]] [-L<start/stop/inc>] [-P] [-:]\n\n");
		mexPrintf ("	infile (ASCII) has 2 columns defining segment limits.\n");
 		
		mexPrintf ("\t-E specifies the stage pole file to be used\n");
		mexPrintf ("\n\tOPTIONS:\n");
		mexPrintf ("\t-A create age flow lines (instead of mag) starting at points as \n\t  determined by -S and -G options\n");
		mexPrintf ("\t-B output a file with direct/reverse polarity blocks\n");
		mexPrintf ("\t-C choose between different isochron time scales. Append:\n");
		mexPrintf ("\t     M (-CM) to select the Cand & Kent 95 + Mailvento 2012 [Default]\n");
		mexPrintf ("\t     C (-CC) to select the Cand & Kent 95 time scale\n");
		mexPrintf ("\t     O (-CO) to select the old Cand time scale\n");
		mexPrintf ("\t     P (-CP) to select the Patriat time scale\n");
		mexPrintf ("\t   Altervatively give a file name (-Ctime_scale) with a user provided time scale.\n");
		mexPrintf ("\t-D<inc_deg> distance in degrees used to reinterpolate the flow line \n\t  equidistantly [default 0.005]\n");
		mexPrintf ("\t-F<filterwidth> apply a gaussian filter (width in meters)\n");
		mexPrintf ("\t-G create multiple flow lines starting at points defining the \n\t  segment OR at interpolated positions controled by -S option\n");
		mexPrintf ("\t-I invert sense of rotation as defined in the stage pole file\n");
		mexPrintf ("\t-L compute rotated points along a linear 'age-line'.\n");
		mexPrintf ("\t-P It means that age points are transmited in input (They MUST be).\n");
		mexPrintf ("\t-N<age> extends earliest stage pole back to <upper_age> [no extension]\n");
		mexPrintf ("\t-S<inc_deg> reinterpolate the segment at inc_deg spacing\n");
		mexPrintf ("\t-T<age> sets the starting age in Ma [0]\n");
		mexPrintf("\t-: Expect lat/lon input rather than lon/lat [OFF].\n");
		mexErrMsgTxt("\n");
        }

	if (age_flow && filter_width > 0.001) {
		mexPrintf ("%s: Warning -A option overuns -F<filterwidth>\n", "telha");
		filter_width = 0.001;
	}
	if (multi_flow && brick) {
		mexPrintf ("%s: Warning -B option overuns -G\n", "telha");
	}
	if (ts_file) {
		if ((fp_ts = fopen (t_scale, "r")) == NULL) {
			mexPrintf ("%s: Cannot open file %s\n", argv[0], t_scale);
			mexErrMsgTxt("\n");
		}
	}
	if (n_arg_no_char == 0 && ages_given) {		/* This will fail if -P and data_in_input */
		mexPrintf ("%s: ERROR: -P option requires ages to be transmited in input\n", "telha");
		mexErrMsgTxt("\n");
	}

	if (error) mexErrMsgTxt("\n");

	if (switch_xy) {iy = 0; ix = 1;}

	if (n_arg_no_char == 1 && !ages_given) {		/* Not all combinations are tested */
		tmp = mxGetPr(prhs[0]);
		np_in = mxGetM(prhs[0]);
		data_in_input = TRUE;
	}
	else if (n_arg_no_char == 1 && ages_given) {		/* prhs[0] MUST contain the "rotation ages" */
		tmp = mxGetPr(prhs[0]);
		n_isoc = MAX(mxGetM(prhs[0]),mxGetN(prhs[0]));
		isoc_scale = (struct ISOC_SCALE *) mxCalloc ((size_t) n_isoc, sizeof(struct ISOC_SCALE));
		for (i = 0; i < n_isoc; i++)
			isoc_scale[i].age = tmp[i];
		linear_age = ts_file = isoc_p = isoc_o = isoc_c = FALSE;
	}
	else if (n_arg_no_char == 2) {		/* Here, prhs[0] MUST contain the object to rotate */
						/* and prhs[1] the "rotation ages" */ 
		/* The "rotation ages" */
		tmp = mxGetPr(prhs[1]);
		n_isoc = MAX(mxGetM(prhs[1]),mxGetN(prhs[1]));
		isoc_scale = (struct ISOC_SCALE *) mxCalloc ((size_t) n_isoc, sizeof(struct ISOC_SCALE));
		for (i = 0; i < n_isoc; i++)
			isoc_scale[i].age = tmp[i];
		linear_age = ts_file = isoc_p = isoc_o = isoc_c = FALSE;
		/* And now the the object to rotate */
		tmp = mxGetPr(prhs[0]);
		np_in = mxGetM(prhs[0]);
		data_in_input = TRUE;
	}

	if (linear_age) {
		n_isoc = (int)floor(fabs(age_lin_stop - age_lin_start) / age_lin_inc + 0.5) + 1;
		isoc_scale = (struct ISOC_SCALE *) mxCalloc ((size_t) n_isoc, sizeof(struct ISOC_SCALE));
		isoc_scale[0].age = age_lin_start;
		for (i = 1; i < n_isoc; i++)
			isoc_scale[i].age = isoc_scale[i-1].age + age_lin_inc;
	}
	else if (ts_file) /* read time scale provided by user */
		n_isoc = read_time_scale (fp_ts, isoc_scale);
	else if (isoc_p) {	/* use Patriat time scale */ 
		n_isoc = sizeof isoc_scale_p / sizeof (struct ISOC_SCALE);
		isoc_scale = (struct ISOC_SCALE *) mxCalloc ((size_t)n_isoc, sizeof(struct ISOC_SCALE));
		isoc_scale = isoc_scale_p;
	}
	else if (isoc_cm) {     /* use Cande & Kent 95 time scale (DEFAULT) */
		n_isoc = sizeof isoc_scale_cm / sizeof (struct ISOC_SCALE);
		isoc_scale = (struct ISOC_SCALE *) mxCalloc ((size_t)n_isoc, sizeof(struct ISOC_SCALE));
		isoc_scale = isoc_scale_cm;
	}
	else if (isoc_c) {     /* use Cande & Kent 95 time scale */
		n_isoc = sizeof isoc_scale_c / sizeof (struct ISOC_SCALE);
		isoc_scale = (struct ISOC_SCALE *) mxCalloc ((size_t)n_isoc, sizeof(struct ISOC_SCALE));
		isoc_scale = isoc_scale_c;
	}
	else if (isoc_o) {     /* use old Cande time scale (by Patriat) */
		n_isoc = sizeof(isoc_scale_o) / sizeof (struct ISOC_SCALE);
		isoc_scale = (struct ISOC_SCALE *) mxCalloc ((size_t)n_isoc, sizeof(struct ISOC_SCALE));
		isoc_scale = isoc_scale_o;
	}
	else if (ages_given);
	else {
		mexPrintf ("%s: ERROR, should not pass here %s\n", argv[0]);
		mexErrMsgTxt("\n");
	}


	n_alloc = CHUNK;
	ndata = 0;	n_seg = 0;	np_in_seg = 0;

	if (data_in_input) {	/* Data was transmited as arguments. */
		data = (struct DATA *) mxCalloc ((size_t) np_in, sizeof(struct DATA));
		for (i = 0; i < np_in; i++) {
			if (!mxIsNaN (tmp[i])) {
				data[ndata].x = tmp[i];
				/* Convert to geocentrics */
				data[ndata].y = atan2( ecc2_1 * sin(tmp[i+np_in]*D2R), cos(tmp[i+np_in]*D2R) ) / D2R;
				ndata++;
				np_in_seg++;
			}
			else if (first) {
				first = FALSE;
				n_seg++;
			}
			else {
				data[n_seg-1].np = np_in_seg; 
				n_seg++;
				np_in_seg = 0;
			}
		}
		if (first) n_seg++; 		/* Single segment file without any NaNs */
		data[n_seg-1].np = np_in_seg;	/* Save npoints of the last segment */
		np_in = ndata + n_seg - 1;
	}
	else {			/* Data was not transmited as arguments. So we must read it from file */
		data = (struct DATA *) mxCalloc ((size_t) n_alloc, sizeof(struct DATA));
		while (fgets (line, MAXCHAR, fp)) { /* Reading file */
			if (ns = strncmp(newseg, line, 1)) { /* Multisegment file */
				if (sscanf (line, "%lg %lg", &in[0], &in[1]) < 2)
					mexPrintf ("ERROR deciphering line %d\n",ndata+1);
				if (ndata == n_alloc) {
					n_alloc += CHUNK;
					data = (struct DATA *) mxRealloc ((void *)data, (size_t)(n_alloc * sizeof(struct DATA)));
				}
				data[ndata].x = in[ix];
				data[ndata].y = in[iy];
				ndata++;
				np_in_seg++;
			}
			else if (first) {
				first = FALSE;
				n_seg++;
			}
			else {
				data[n_seg-1].np = np_in_seg;
				n_seg++;
				np_in_seg = 0;
			}
		}
		if (first) n_seg++; 		/* Single segment file without any ">" */
		data[n_seg-1].np = np_in_seg;	/* Save npoints of the last segment */
		fclose(fp);
		np_in = ndata + n_seg - 1;
	}
	
	if (int_seg) intp_along_seg(n_seg, dl);

	/* I'm not sure that the user realy wants this all the times */
	if (upper_age == 0.0 && linear_age) upper_age = age_lin_stop;

	/* Load in the stage poles */

	n_stages = spotter_init (euler_file, &p, 0, upper_age);
	if (upper_age == 0.0) upper_age = p[0].t_start;

	if (invert_rot) /* Want to revert sense of rotation */
		for (i = 0; i < n_stages; i++) {
			p[i].omega *= -1;	p[i].omega_r *= -1;
		}

	if (p[n_stages - 1].t_stop > 0) {
		mexPrintf ("ERROR: A idade mais nova do polo mais recente \ntem que ser 0 nao %lg como e o caso\n", p[n_stages - 1].t_stop);
		return;
	}
	if (t_zero > 0)
		while (isoc_scale[i_min].age < t_zero) i_min++;


	if (linear_age || ages_given) {		/* The -B (brick) option should not pass here */
		n_flow = 0;	l = 0;
		/* Count number of rotations for each point in segment */
		for (jj = 0; jj < n_isoc && isoc_scale[jj].age <= upper_age; jj++) n_flow++;
		n_flow -= i_min;
		np_out = np_in * n_flow + n_flow;
		plhs[0] = mxCreateDoubleMatrix (np_out, 2, mxREAL); 
		out = mxGetPr(plhs[0]);
		for (j = i_min; j < n_flow + i_min; j++) {	/* Loop over number of rotations*/
			age = isoc_scale[j].age;
			m = 0;
			for (k = 0; k < n_seg; k++) {	/* Loop over segments */
				ii = 0;
				c = mxCalloc (data[k].np * 2, sizeof (double));
				for (i = 0; i < data[k].np; i++) { /* Loop over np in segment */
					lon =  data[m].x * D2R;	
					lat = data[m].y * D2R;
					n_chunk = spotter_backtrack (&lon, &lat, &age, 1, p, n_stages, 0);
					lon *= R2D;	lat *= R2D;
					if (fabs(lon / 180.) > 1) lon -= 360.;
					c[ii++] = lon;	c[ii++] = lat;
					m++;
				}
				if (n_flow > 1 || n_seg > 1) {
					out[l] = mxGetNaN();	out[l+np_out] = mxGetNaN();
					l++;
				}
				for (ll = 0; ll < data[k].np; ll++) {
					out[l] = c[ll*2];	out[l+np_out] = c[ll*2+1];
					l++;
				}
				mxFree(c);
			}
		}
		if (!data_in_input) mxFree ((void *)data);
	}

	if (nlhs > 1) {
		plhs[1] = mxCreateDoubleMatrix (1, 1, mxREAL); 
		out_n_data = mxGetPr(plhs[1]);	out_n_data[0] = ndata; 
	}
	if (nlhs > 2) {
		plhs[2] = mxCreateDoubleMatrix (1, 1, mxREAL); 
		out_n_seg = mxGetPr(plhs[2]);	out_n_seg[0] = n_seg; 
	}
	if (nlhs > 3) {
		plhs[3] = mxCreateDoubleMatrix (1, 1, mxREAL); 
		out_n_flow = mxGetPr(plhs[3]);	out_n_flow[0] = n_flow; 
	}

	if (!brick)	{	/* Not very clean code, but we are done here */
		for (k = 0; k < np_out; k++) {
			lat = out[k+np_out];
			if (mxIsNaN(lat))
				continue;
			else
				lat *= D2R;
			lat = atan2( sin(lat), ecc2_1 * cos(lat) ) * R2D;	/* Convert back to geodetics */
			out[k+np_out] = lat;
		}
		return;
	}

	n_flow = 0;
	/* Count number of rotations for each point in segment */
	for (jj = 0; jj < n_isoc && isoc_scale[jj].age <= upper_age; jj++) n_flow++;
	n_flow -= i_min;

	/* NOTE. Since from the above loop jj is allways < n_isoc, but it also is incremented one
	   too much before the condition fails, we can safely do the following. The intention is that
	   we can have also the portion of the last brick between isoc_scale[jj-1].age and upper_age */
	if (isoc_scale[jj].age != upper_age) {		/* Otherwise we would be repeating last point */
		isoc_scale[jj].age = upper_age;
		n_flow++;
	}

	/* For the same reason, that is to account for the portion of the brick from t_start
	   to the next closest entry in the chronological table, we do this trick. */
	if (t_zero > 0 && i_min > 0) {
		i_min--;
		isoc_scale[i_min].age = t_zero;
		n_flow++;
	}

	for (k = m = 0; k < n_seg; k++) {	/* Loop over segments */
		c = mxCalloc ((size_t)(n_flow * data[k].np * 2), sizeof(double));
		ii = 0;		m = 0;
		for (i = 0; i < data[k].np; i++) { /* Loop over np in segment */
			for (j = i_min; j < n_flow + i_min; j++) { /* Loop over number of rotations*/ 
				lon = data[i].x * D2R;	
				lat = data[i].y * D2R;
				age = isoc_scale[j].age;
				n_chunk = spotter_backtrack (&lon, &lat, &age, 1, p, n_stages, 0);
				lon *= R2D;
				lat = atan2( sin(lat), ecc2_1 * cos(lat) ) * R2D;	/* Convert back to geodetics */
				if (fabs(lon / 180.) > 1) lon -= 360.;
				c[ii++] = lon;	c[ii++] = lat;
			}
			m++;
		}
		if (brick) {	/* Always true because otherwise it has already returned further up (shity code) */
			i = 0;
			if (first_seg) {
				plhs[0] = mxCreateDoubleMatrix (np_in * 2, n_flow, mxREAL); 
				plhs[1] = mxCreateDoubleMatrix (np_in * 2, n_flow, mxREAL); 
				out = mxGetPr(plhs[0]); 
				out2 = mxGetPr(plhs[1]);
				if (nlhs > 2) {
					plhs[2] = mxCreateDoubleMatrix (1, 1, mxREAL); 
					first_mag = mxGetPr(plhs[2]);
					first_mag[0] = isoc_scale[i_min].mag;
				}
			}

			for (l = 0; l < n_flow-1; l++) {
				for (ll = 0; ll < data[k].np; ll++) {
					out[i] = c[(l+ll*n_flow)*2];
					out2[i] = c[(l+ll*n_flow)*2+1];
					i++;
				}
				for (ll = data[k].np; ll > 0; ll--) {
					out[i] = c[((ll-1)*n_flow+l+1)*2];
					out2[i] = c[((ll-1)*n_flow+l+1)*2+1];
					i++;
				}
			}
			first_seg = FALSE;
		}
		else
			int_perf (c, i_min, n_flow, k, age_flow, multi_flow, ddeg, filter_width, isoc_scale);
		mxFree ((void *)c);
	}
	mxFree ((void *)data);
	mxFree ((void *)p);
	mxFree ((void *)argv);
}
Beispiel #26
0
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{
    int64_T len; /* File length in bytes */
    int64_T numRecs; /* Num records in file */
    char *filename;
    char *flag;
    short suppressText; /* boolean */
    FILE *fp;
    double *V;
    double *t;
    int64_T i, j;  /* Loop indices */
    short numChannels;
    int freq; /* Sampling rate */
    short gain;
    short* dt; /* Date and time */
    double scalingCoeffs[4]; /* Scaling coefficients to convert raw digital values to voltages */
    double* timeSpan; /* start and stop times to retrieve from file */
    int64_T outN; /* number of time pts. for output vectors */
    int64_T* timeSpanIdx;
    int64_T position; /* current position of file */
    int64_T offset; /* offset for next file jump */
    int isUsingTimespan = 0;
    int isUsingChannel = 0;
    
    
    /* Variables for temp storage of input */
    short val;
    
    int ch = -1; /* Channel num to extract (-1 if all channels, the default) */
    
    /* Check number of arguments */
    if (nrhs > 4)
        mexErrMsgTxt("Filename, channel number (optional), timespan (optional), and FLAGs (optional) are only allowable arguments.");
    if (nrhs < 1)
        mexErrMsgTxt("No input arguments. Include filename, channel number (optional), and timespan (optional).");
    if (nlhs > 2)
        mexErrMsgTxt("Too many output arguments (max. 2).");
    
    /* Input must be a string */
    if (mxIsChar(prhs[0]) != 1)
        mexErrMsgTxt("Input must be a string.");
    /* Input must be a row vector */
    if (mxGetM(prhs[0])!=1)
        mexErrMsgTxt("Input must be a row vector.");
    
    /* Copy the string data from prhs[0] into a C string 'filename'. */
    filename = mxArrayToString(prhs[0]);
    if (filename == NULL) 
        mexErrMsgTxt("Could not convert input to string.");
    
    /* Open file */
    fp = fopen(filename,"rb");
    if (fp == NULL)
        mexErrMsgTxt("Could not open file.");
    mxFree(filename);
    
    /* Get channel to extract (optional) */
    if (nrhs > 1) {
        if (!mxIsNumeric(prhs[1])) {
            fclose(fp);
            mexErrMsgTxt("Channel number or time span must be numeric.");
        }
        else {
            int numMembers;
            numMembers = mxGetNumberOfElements(prhs[1]);
            if (numMembers == 1) {
                ch = (int)(mxGetScalar(prhs[1]));    
                isUsingChannel = 1;
            }
            else if (numMembers == 2) {
                timeSpan = mxGetPr(prhs[1]);
                if (timeSpan[1] < timeSpan[0]) {
                    fclose(fp);
                    mexErrMsgTxt("First element of time span (i.e., start time) must be less than second (i.e., stop time).");
                }
                isUsingTimespan = 1;
            }
            else {
                fclose(fp);
                mexErrMsgTxt("Too many elements in second argument.");
            }
        }
    }
    
    /* Get times to extract (optional) */
    if (nrhs > 2) {
        if (!mxIsNumeric(prhs[2])) {
            fclose(fp);
            mexErrMsgTxt("Time span must be numeric.");
        }
        else {
            int numMembers;
            numMembers = mxGetNumberOfElements(prhs[2]);
            if (numMembers != 2) {
                fclose(fp);
                mexErrMsgTxt("Time span must have start and stop times.");
            }
            else {
                timeSpan = mxGetPr(prhs[2]);
                if (timeSpan[1] < timeSpan[0]) {
                    fclose(fp);
                    mexErrMsgTxt("First element of time span (i.e., start time) must be less than second (i.e., stop time).");
                }
                isUsingTimespan = 1;
            }
        }
    }
    
    /* Check whether text was suppressed */
    suppressText = 0;
    if (nrhs > 3) {
        if (mxIsChar(prhs[3]) != 1)
            mexErrMsgTxt("FLAGs must be strings.");
        flag = mxArrayToString(prhs[0]);
        if (flag == NULL)
            mexErrMsgTxt("Could not convert FLAG input to string.");
        if (strcmpi(flag, "suppresstext"))
            suppressText = 1;
        mxFree(flag);
    }
    
    /* Get file length */  
/*    fseek(fp,0,SEEK_END); /* Seek from end of file */
/*    len = ftell(fp); /* Where am I? */
/*    fseek(fp,0,SEEK_SET); /* Return to beginning of file */
/*    fflush(fp);
 */
    /* Deal with large files */
    {
        structStat statbuf;
        int64_T fileSize = 0;

        if (0 == getFileFstat(fileno(fp), &statbuf))
        {
            len = statbuf.st_size;
            if(!suppressText)
                mexPrintf("File size is %" FMT64 "d bytes\n", len);
        }
    }
    
    /* There are 54 bytes in the header, then each record */
    fread(&numChannels,2,1,fp); /* Read numChannels */
    fread(&freq,4,1,fp); /* Read sampling rate */
    fread(&gain,2,1,fp); /* Read gain */
    fread(scalingCoeffs,8,4,fp);     /* Read scaling coeffs */
    dt = mxCalloc(7, sizeof(short)); /* Allocate memory for date&time */
    fread(dt,2,7,fp); /* Read date and time */

    /* Compute #records */
    numRecs = (len - 54) / (2 * (int64_T)numChannels);

    /* Print summary (header) data */
    if (!suppressText) {
        mexPrintf("#chs: %i\nsampling rate: %i\ngain: %i\n", numChannels, freq, gain);
        mexPrintf("date/time: %i-%i-%i %i:%i:%i:%i\n", dt[0], dt[1], dt[2], dt[3], dt[4], dt[5], dt[6]);
		 mexPrintf("scaling coefficients: %f +%f *x + %f*x^2 + %f*x^3 \n", scalingCoeffs[0], scalingCoeffs[1], scalingCoeffs[2], scalingCoeffs[3]);
        mexPrintf("\nTotal num. samples per channel: %i\n", numRecs);
    }

    /* Compute start and stop indices, if time span was specified */
    timeSpanIdx = mxCalloc(2, sizeof(int64_T)); /* Allocate memory for start/stop indices */
    if (isUsingTimespan) {
        timeSpanIdx[0] = (int64_T)(ceil(timeSpan[0] * (double)freq));
        timeSpanIdx[1] = (int64_T)(ceil(timeSpan[1] * (double)freq));
        ++timeSpanIdx[1];
        /* Take care of over/underrun */
        if (timeSpanIdx[0] < 0) {
            timeSpanIdx[0] = 0;
        }
        else if (timeSpanIdx[0] >= numRecs || timeSpanIdx[1] < 0) {
            fclose(fp);
            mexErrMsgTxt("No records in indicated time span.");
        }
        if (timeSpanIdx[1] >= numRecs) {
            timeSpanIdx[1] = numRecs;
        }
        
        outN = timeSpanIdx[1] - timeSpanIdx[0];
    }
    else {
        timeSpanIdx[0] = 0;
        timeSpanIdx[1] = numRecs;
        outN = numRecs;
    }
    
    
    /* Create output matrix */
    if (ch < 0) /* default, all channels */
        plhs[0] = mxCreateDoubleMatrix(numChannels,outN,mxREAL);
    else { /* just the specified channel */
        if (ch == 0 || ch > numChannels) {
            fclose(fp);
            mexErrMsgTxt("Specified extraction channel does not exist in dataset.");
        }
        plhs[0] = mxCreateDoubleMatrix(1,outN,mxREAL);
    }
    V = mxGetPr(plhs[0]);
    
    /* If more than two left-hand side arguments, output times */
    if (nlhs > 1) {
        plhs[1] = mxCreateDoubleMatrix(1,outN,mxREAL);
        t = mxGetPr(plhs[1]);
    }
    
    /* Seek to start of time span, if specified */
    getFilePos(fp, (fpos_T*) &position);
    offset = position + (int64_T)(2*numChannels*timeSpanIdx[0]);
    setFilePos(fp, (fpos_T*) &offset);
    /*fseek(fp, 2*numChannels*timeSpanIdx[0], SEEK_CUR);*/
    
    /* Read each record */
    for (i = 0; i < outN; ++i) {
        if (nlhs > 1)
            t[i] = (double)(i + timeSpanIdx[0]) / (double)freq;
        if (ch < 0) {
            for (j = 0; j < numChannels; ++j) {
                fread(&val,2,1,fp); /* Read digital value */
                V[i*numChannels+j] = scalingCoeffs[0] + scalingCoeffs[1] * (double)val +
                    scalingCoeffs[2] * (double)val * (double)val +
                    scalingCoeffs[3] * (double)val * (double)val * (double)val;
            } /* NB: Matlab's indices go down each column, then to the next row */
        }
        else { /* just extract one channel */
            getFilePos(fp, (fpos_T*) &position);
            offset = position + (int64_T)(2*(ch-1));
            setFilePos(fp, (fpos_T*) &offset);
            /*fseek(fp, 2*ch, SEEK_CUR); /* advance to next time channel appears */
            fread(&val,2,1,fp); /* Read value */
            V[i] = scalingCoeffs[0] + scalingCoeffs[1] * (double)val +
                scalingCoeffs[2] * (double)val * (double)val +
                scalingCoeffs[3] * (double)val * (double)val * (double)val;
            getFilePos(fp, (fpos_T*) &position);
            offset = position + (int64_T)(2*(numChannels - 1 - (ch-1)));
            setFilePos(fp, (fpos_T*) &offset);
            /*fseek(fp, 2*(numChannels - 1 - ch), SEEK_CUR); /* skip past remaining channels */
            /* NB: We could just do one initial seek, then always seek ahead by all channels,
             * but that code would be harder to read and not a whole lot faster */
        }
    }
    
    /* Free used memory */
    mxFree(timeSpanIdx);
    mxFree(dt);
    fclose(fp);
}
Beispiel #27
0
void SetCollection(mxArray *coll)
{
    collection = mxArrayToString(coll);
    mexPrintf("collection已设置为%s\n", collection.c_str());
}
Beispiel #28
0
/*
 * Application entry point.
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) 
{
	char *string_command;
	double *outArray;
	mwSize M; //mwSize is a platform independent alternative to int
	mwSize i;
	
	if(nrhs!=1) {
		mexErrMsgIdAndTxt("myex:nrhs:invalidN", "Invalid input: One command string required.\n\nValid commands are:\n   myex('connect')\n   myex('getdata')\n   myex('disconnect')");
	}

	string_command = mxArrayToString(prhs[0]);
    //mexPrintf(">> %s\n", string_command);
	switch (string_command[0]) {
	case 'c':
		Connect();
		break;
	case 'g':
		openForData = false;
		// retrieve (any) data from the internal buffer - return as plhs[0]
		M = q_nelements();
		i = M; // start at the end of the output array, because we're actually using a FILO data structure for the internal buffer (stack)
		plhs[0] = mxCreateDoubleMatrix(M,12,mxREAL);
		outArray = mxGetPr(plhs[0]);
		// iterate through internal buffer
		while (!q_isempty())
		{
			// get next item from the internal buffer
			struct node *topelement = q_topelement();
			i--;
			// add gaze data to output row
			outArray[i] = topelement->X_px;
			outArray[i+M] = topelement->Y_px;  // N.B. C indexing is like the tranpose of MATLAB variable: http://uk.mathworks.com/matlabcentral/newsreader/view_thread/249954
			outArray[i+2*M] = topelement->Timestamp;
			// add eye position data to output row
			outArray[i+3*M] = topelement->HasLeftEyePosition;
			outArray[i+4*M] = topelement->HasRightEyePosition;
			outArray[i+5*M] = topelement->LeftEyeX_mm;
			outArray[i+6*M] = topelement->LeftEyeY_mm;
			outArray[i+7*M] = topelement->LeftEyeZ_mm;
			outArray[i+8*M] = topelement->RightEyeX_mm;
			outArray[i+9*M] = topelement->RightEyeY_mm;
			outArray[i+10*M] = topelement->RightEyeZ_mm;
			outArray[i+11*M] = topelement->EyePosTimestamp;
			// remove this item from the internal buffer
			q_pop();
		}
	openForData = true;	
		break;
	case 'd':
		openForData = false;
		Disconnect();		
		break;		
	default:
		mexErrMsgIdAndTxt("myex:nrhs:unrecognised", "Invalid input: Unrecognised command.\n\nValid commands are:\n   myex('connect')\n   myex('getdata')\n   myex('disconnect')");
		break;
	}
    mxFree(string_command);	

	return;
}
Beispiel #29
0
static void get_map_file(int i, const mxArray *ptr, MAPTYPE *maps)
{
    int j;
    mxArray *tmp;
    double *pr;
    mwSize dsize = 0;
    mwSize off;
#ifdef SPM_BIGENDIAN
    int be = 1;
#else
    int be = 0;
#endif

    tmp=mxGetField(ptr,i,"dim");
    if (tmp == (mxArray *)0)
    {
        free_maps(maps,i);
        mexErrMsgTxt("Cant find dim.");
    }
    if (mxGetM(tmp)*mxGetN(tmp) != 3)
    {
        free_maps(maps,i);
        mexErrMsgTxt("Wrong sized dim.");
    }
    pr = mxGetPr(tmp);
    maps[i].dim[0] = (int)fabs(pr[0]);
    maps[i].dim[1] = (int)fabs(pr[1]);
    maps[i].dim[2] = (int)fabs(pr[2]);
    maps[i].dtype  = (int)fabs(pr[3]);
    maps[i].data   = (void  **)mxCalloc(maps[i].dim[2],sizeof(void *));
    maps[i].scale  = (double *)mxCalloc(maps[i].dim[2],sizeof(double));
    maps[i].offset = (double *)mxCalloc(maps[i].dim[2],sizeof(double));

    tmp=mxGetField(ptr,i,"dt");
    if (tmp == (mxArray *)0)
    {
        free_maps(maps,i+1);
        mexErrMsgTxt("Cant find dt.");
    }
    if (mxGetM(tmp)*mxGetN(tmp) != 2)
    {
        free_maps(maps,i+1);
        mexErrMsgTxt("Wrong sized dt.");
    }
    pr = mxGetPr(tmp);
    if ((int)(pr[1])==be)
    {
        if      (pr[0]==    2) {maps[i].dtype = SPM_UNSIGNED_CHAR;  dsize =  8;}
        else if (pr[0]==  256) {maps[i].dtype = SPM_SIGNED_CHAR;    dsize =  8;}
        else if (pr[0]==    4) {maps[i].dtype = SPM_SIGNED_SHORT;   dsize = 16;}
        else if (pr[0]==  512) {maps[i].dtype = SPM_UNSIGNED_SHORT; dsize = 16;}
        else if (pr[0]==    8) {maps[i].dtype = SPM_SIGNED_INT;     dsize = 32;}
        else if (pr[0]==  768) {maps[i].dtype = SPM_UNSIGNED_INT;   dsize = 32;}
        else if (pr[0]==   16) {maps[i].dtype = SPM_FLOAT;          dsize = 32;}
        else if (pr[0]==   64) {maps[i].dtype = SPM_DOUBLE;         dsize = 64;}
        else {free_maps(maps,i+1);mexErrMsgTxt("Unknown datatype.");}
    }
    else
    {
        if      (pr[0]==    2) {maps[i].dtype = SPM_UNSIGNED_CHAR;    dsize =  8;}
        else if (pr[0]==  256) {maps[i].dtype = SPM_SIGNED_CHAR;      dsize =  8;}
        else if (pr[0]==    4) {maps[i].dtype = SPM_SIGNED_SHORT_S;   dsize = 16;}
        else if (pr[0]==  512) {maps[i].dtype = SPM_UNSIGNED_SHORT_S; dsize = 16;}
        else if (pr[0]==    8) {maps[i].dtype = SPM_SIGNED_INT_S;     dsize = 32;}
        else if (pr[0]==  768) {maps[i].dtype = SPM_UNSIGNED_INT_S;   dsize = 32;}
        else if (pr[0]==   16) {maps[i].dtype = SPM_FLOAT_S;          dsize = 32;}
        else if (pr[0]==   64) {maps[i].dtype = SPM_DOUBLE_S;         dsize = 64;}
        else {free_maps(maps,i+1);mexErrMsgTxt("Unknown datatype.");}
    }

    tmp=mxGetField(ptr,i,"fname");
    if (tmp == (mxArray *)0)
    {
        free_maps(maps,i+1);
        mexErrMsgTxt("Cant find fname.");
    }
    if (mxIsChar(tmp))
    {
#ifdef SPM_WIN32
        HANDLE hFile, hMapping;
#endif
        char *buf = NULL;
        int fd;
        struct stat stbuf;
        if ((buf = mxArrayToString(tmp)) == NULL)
        {
            mxFree(buf);
            free_maps(maps,i+1);
            mexErrMsgTxt("Cant get filename.");
        }
        if ((fd = open(buf, O_RDONLY)) == -1)
        {
            mxFree(buf);
            free_maps(maps,i+1);
            mexErrMsgTxt("Cant open image file.");
        }
        if (fstat(fd, &stbuf) == -1)
        {
            (void)close(fd);
            mxFree(buf);
            free_maps(maps,i+1);
            mexErrMsgTxt("Cant get file size.");
        }
        maps[i].len = stbuf.st_size;
#ifdef SPM_WIN32
        (void)close(fd);

        /* maps[i].addr = map_file(buf, (caddr_t)0, maps[i].len,
         *  PROT_READ, MAP_SHARED, (off_t)0); */

        /* http://msdn.microsoft.com/library/default.asp?
               url=/library/en-us/fileio/base/createfile.asp */
        hFile = CreateFile(buf, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS, NULL);
        mxFree(buf);
        if (hFile == NULL)
            mexErrMsgTxt("Cant open file.  It may be locked by another program.");

        /* http://msdn.microsoft.com/library/default.asp?
               url=/library/en-us/fileio/base/createfilemapping.asp */
        hMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
        (void)CloseHandle(hFile);
        if (hMapping == NULL)
            mexErrMsgTxt("Cant create file mapping.  It may be locked by another program.");

        /* http://msdn.microsoft.com/library/default.asp?
               url=/library/en-us/fileio/base/mapviewoffile.asp */
        maps[i].addr    = (caddr_t)MapViewOfFileEx(hMapping, FILE_MAP_READ, 0, 0, maps[i].len, 0);
        (void)CloseHandle(hMapping);
        if (maps[i].addr == NULL)
            mexErrMsgTxt("Cant map view of file.  It may be locked by another program.");

#else
        maps[i].addr = mmap((caddr_t)0, maps[i].len,
            PROT_READ, MAP_SHARED, fd, (off_t)0);
        (void)close(fd);
        if (maps[i].addr == (void *)-1)
        {
            (void)perror("Memory Map");
            mxFree(buf);
            free_maps(maps,i+1);
            mexErrMsgTxt("Cant map image file.");
        }
        mxFree(buf);
#endif
    }


    tmp=mxGetField(ptr,i,"pinfo");
    if (tmp != (mxArray *)0)
    {
        if (mxGetM(tmp) != 3 || (mxGetN(tmp) != 1 && mxGetN(tmp) != maps[i].dim[2]))
        {
            free_maps(maps,i+1);
            mexErrMsgTxt("Wrong sized pinfo.");
        }
        pr = mxGetPr(tmp);
        if (mxGetN(tmp) == 1)
        {
            off = (mwSize)fabs(pr[2]);
            if (off+maps[i].dim[0]*maps[i].dim[1]*maps[i].dim[2]*(dsize/8) > maps[i].len)
            {
                free_maps(maps,i+1);
                mexErrMsgTxt("File too small.");
            }
            for(j=0; j<maps[i].dim[2]; j++)
            {
                maps[i].scale[j]  = pr[0];
                maps[i].offset[j] = pr[1];
                maps[i].data[j]   = maps[i].addr+off+j*maps[i].dim[0]*maps[i].dim[1]*(dsize/8);
            }
        }
        else
        {
            for(j=0; j<maps[i].dim[2]; j++)
            {
                maps[i].scale[j]  = pr[0+j*3];
                maps[i].offset[j] = pr[1+j*3];
                off = (mwSize)fabs(pr[2+j*3]);
                maps[i].data[j]   = maps[i].addr+off;
                if (off+maps[i].dim[0]*maps[i].dim[1]*(dsize/8) > maps[i].len)
                {
                    free_maps(maps,i+1);
                    mexErrMsgTxt("File too small.");
                }
            }
        }
    }
    else
    {
        if (maps[i].dim[0]*maps[i].dim[1]*maps[i].dim[2]*(dsize/8) > maps[i].len)
        {
            free_maps(maps,i+1);
            mexErrMsgTxt("File too small.");
        }
        for(j=0; j<maps[i].dim[2]; j++)
        {
            maps[i].scale[j]  = 1.0;
            maps[i].offset[j] = 0.0;
            maps[i].data[j]   = maps[i].addr+j*maps[i].dim[0]*maps[i].dim[1]*(dsize/8);
        }
    }

    tmp=mxGetField(ptr,i,"mat");
    if (tmp != (mxArray *)0)
    {
        if (mxGetM(tmp) != 4 || mxGetN(tmp) != 4)
        {
            free_maps(maps,i+1);
            mexErrMsgTxt("Wrong sized mat.");
        }
        pr = mxGetPr(tmp);
        for(j=0; j<16; j++)
            maps[i].mat[j] = pr[j];
    }
    else
    {
        for(j=0; j<16; j++)
            maps[i].mat[j] = 0.0;
        for(j=0; j<4; j++)
            maps[i].mat[j + j*4] = 1.0;
    }
}
Beispiel #30
0
void mexFunction (int nlhs, mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
  int port;
  char *command = NULL, *argument = NULL, *hostname = NULL;
  int num;
  int rc, t;
  int server, errorCode = 0;
  
  if (nrhs <2)
    mexErrMsgTxt ("Invalid number of input arguments");
  
  if (nrhs>0) {
    /* first argument is command, e.g. GET_HDR or TCPSERVER */
    command = mxArrayToString(prhs[0]);
    if (command==NULL)
      mexErrMsgTxt ("invalid input argument #1");
  }
  
  if (nrhs>1) {
    /* second argument depends on the command */
    /* this will be processed below           */
  }
  
  if (nrhs>2) {
    /* third argument is the hostname (optional) */
    hostname = mxArrayToString(prhs[2]);
    if (hostname==NULL)
      mexErrMsgTxt ("invalid input argument #3");
  }
  else {
    /* use the default value */
    hostname = (char *) mxMalloc(strlen(DEFAULT_HOST)+1);
    strncpy(hostname, DEFAULT_HOST, strlen(DEFAULT_HOST)+1);
  }
  
  if (nrhs>3) {
    /* fourth argument is the port number (optional) */
    if (mxIsEmpty(prhs[3]) || !mxIsNumeric(prhs[3]))
      mexErrMsgTxt ("invalid input argument #4");
    else
      port = (int)mxGetScalar(prhs[3]);
  }
  else {
    /* use the default value */
    port = DEFAULT_PORT;
  }
      
  if (strcasecmp(command, "tcpserver")==0) {
    argument = mxArrayToString(prhs[1]);
    if (argument==NULL)
      mexErrMsgTxt ("invalid input argument #2");
    if (strcasecmp(argument, "init")==0) {
		
      if (tcpserverStatus)
        mexErrMsgTxt("thread is already running");
      mexPrintf("In main: spawning tcpserver thread\n");
	  
      strncpy(host_for_server.name, hostname, 256);  /* the 256 is a limit inside the host_t structure */
      host_for_server.port = port;
	  
      rc = pthread_create(&tcpserverThread, NULL, tcpserver, (void *)&host_for_server);
      if (rc)
        mexErrMsgTxt("problem with return code from pthread_create()");
		
	  /* put this as a "connection" with sock=0 into the list */
	  add_hps_item(hostname, port, 0);
    }
    else if (strcasecmp(argument, "exit")==0) {
      if (!tcpserverStatus)
        mexErrMsgTxt("thread is not running");
      mexPrintf("In main: requesting cancelation of tcpserver thread\n");
      rc = pthread_cancel(tcpserverThread);
      if (rc)
        mexErrMsgTxt("problem with return code from pthread_cancel()");
	  /* remove sock=0 connection from host/port/socket list */
	  remove_hps_item(0);
    }
	else if (strcasecmp(argument, "status")==0) {
		plhs[0] = mxCreateDoubleScalar(tcpserverStatus);
	}
  }
  
  else if (strcasecmp(command, "get_hdr")==0) {
	server = open_connection_with_list(hostname, port);
    errorCode = buffer_gethdr(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "get_dat")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_getdat(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "get_evt")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_getevt(server, &(plhs[0]), &(prhs[1]));
  }
    
  else if (strcasecmp(command, "put_hdr")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_puthdr(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "put_dat")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_putdat(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "put_evt")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_putevt(server, &(plhs[0]), &(prhs[1]));
  }
    
  else if (strcasecmp(command, "flush_hdr")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_flushhdr(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "flush_dat")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_flushdat(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "flush_evt")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_flushevt(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "wait_dat")==0) {
    server = open_connection_with_list(hostname, port);
    errorCode = buffer_waitdat(server, &(plhs[0]), &(prhs[1]));
  }
  
  else if (strcasecmp(command, "list_connections")==0) {
	dump_hps_list();
  }

  else if (strcasecmp(command, "lookup_connection")==0) {
	plhs[0] = mxCreateDoubleScalar(lookup_hps_item(hostname, port));
  }

  else if (strcasecmp(command, "close_connection")==0) {
	int sock = lookup_hps_item(hostname, port);
	/* Note that we ignore request to close the dma "connection" */
	if (sock > 0) {
		close_connection(sock);
		remove_hps_item(sock);
	}
	dump_hps_list();
  }

  else {
    mexErrMsgTxt ("unknown command");
  }
  
  /* These are either allocated using mxMalloc'ed or mxArrayToString.
	 Deallocating them manually is not strictly necessary, but cleaner (says Mathworks)
  */
  if (argument) mxFree(argument); 
  if (command)  mxFree(command);
  if (hostname) mxFree(hostname); 

  if (errorCode > 0) {
    char msg[512];
    /* valid connection, but invalid request */
    sprintf(msg, "ERROR: the buffer returned an error (%d)\n", errorCode);
    mexErrMsgTxt(msg);
  } 
  else if (errorCode == -3) {
    /* valid connection, but invalid request, we'll close the socket and remove the list item */
    printf("Trying to close socket %i\n", server);
	close_connection(server);
	remove_hps_item(server);
    mexErrMsgTxt("ERROR: tcp connection to buffer failed.");
  }
  
  return;
}