Beispiel #1
0
void value(json_object *jo, mxArray ** mxa){

    enum json_type type = json_object_get_type(jo);
    mxArray *ma; 

    switch (type) {
        case json_type_boolean: 
            ma = mxCreateLogicalScalar(json_object_get_boolean(jo));
            break;
        case json_type_int: 
//            ma = mxCreateNumericMatrix(1, 1, mxINT64_CLASS, mxREAL);
//            *((int64_t *)mxGetData(ma)) = json_object_get_int64(jo);
//            break;    
// treat ints as doubles
        case json_type_double: 
            ma = mxCreateDoubleScalar(json_object_get_double(jo));
            break;
        case json_type_string: 
            ma = mxCreateString(json_object_get_string(jo));
            break;
    }

    *mxa = ma;

}
/**
 * @brief This file implements an interface to retrieve the information if a given model has at least one truncated squared difference factor.
 *
 * @param[in] nlhs number of output arguments expected from MatLab.
 * (needs to be 1).
 * @param[out] plhs pointer to the mxArrays containing the results.
 * @param[in] nrhs number of input arguments provided from MatLab.
 * (needs to be 1)
 * @param[in] prhs pointer to the mxArrays containing the input data provided by
 * matlab. prhs[0] needs to contain the handle for the model.
 */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
  //check if data is in correct format
  if(nrhs != 1) {
     mexErrMsgTxt("Wrong number of input variables specified (one needed)\n");
  }
  if(nlhs != 1) {
     mexErrMsgTxt("Wrong number of output variables specified (one needed)\n");
  }

  // get model out of handle
  typedef opengm::interface::MatlabModelType::GmType GmType;
  GmType& gm = opengm::interface::handle<GmType>::getObject(prhs[0]);

  // get number of factors
  const GmType::IndexType numFactors = gm.numberOfFactors();

  // check if model has TL2 factor
  bool hasTL2 = false;
  for(GmType::IndexType i = 0; i < numFactors; i++) {
     if(gm[i].isTruncatedSquaredDifference()) {
        hasTL2 = true;
        break;
     }
  }
  // return result
  plhs[0] = mxCreateLogicalScalar(hasTL2);
}
Beispiel #3
0
void mexFunction(int nOut, mxArray *pOut[], 
		 int nIn, const mxArray *pIn[])
{ 
  mxArray *dataA, *dataB;
  mxLogical value;

  if (mxIsClass(pIn[0], "pointer") && mxIsClass(pIn[1], "pointer"))
  {
    dataA = GetPointerData(pIn[0]);
    if (!GetPointerData(dataA))
      dataA = NULL;
    dataB = GetPointerData(pIn[1]);
    if (!GetPointerData(dataB))
      dataB = NULL;
  }
  else if (mxIsClass(pIn[0], "pointer") && mxIsDouble(pIn[1]) 
    && mxGetM(pIn[1])*mxGetN(pIn[1]) == 1 && !mxGetScalar(pIn[1]))
  {
    dataA = GetPointerData(GetPointerData(pIn[0]));
    dataB = NULL;
  }
  else if (mxIsClass(pIn[1], "pointer") && mxIsDouble(pIn[0]) 
    && mxGetM(pIn[0])*mxGetN(pIn[0]) == 1 && !mxGetScalar(pIn[0]))
  {
    dataA = NULL;
    dataB = GetPointerData(GetPointerData(pIn[1]));
  }
  else
    mexErrMsgTxt("Both inputs must be pointers or one of them is pointer and other is scalar 0 (= NULL)");

  value = dataA == dataB;

  pOut[0] = mxCreateLogicalScalar(value);
}
Beispiel #4
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    int status     = 0;
    char *filename = NULL;
    structStat stbuf;
    
    if (nrhs != 1)
    {
        mexErrMsgTxt("One input only required.");
    }
    else
    {
        if (!mxIsChar(prhs[0]))
        {
            mexErrMsgTxt("Input must be a string.");
        }
        filename = mxArrayToString(prhs[0]);
        
        if ((getFileStat(filename, &stbuf) == 0) && (S_ISREG(stbuf.st_mode)))
        {
            status = 1;
        }

        mxFree(filename);
    }
        
    plhs[0] = mxCreateLogicalScalar(status);
}
Beispiel #5
0
	std::vector<mxArray*> TestCommand::handle()
	{
		UnitTest ut;
		bool b = ut.test(t.val, u.val, f.val, deltaF.val, g.val, deltaG.val);

		std::vector<mxArray*> r(1);
		r[0] = mxCreateLogicalScalar(b);
		return r;
	}
Beispiel #6
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
  if (nrhs < 1) {
    mexPrintf("Usage: getKey(vkey)\n");
    return;
  }

  plhs[0] =
      mxCreateLogicalScalar(GetAsyncKeyState((int)mxGetScalar(prhs[0])) != 0);
}
int mxW_CVodeSpilsPsetB(realtype t, N_Vector y,
                         N_Vector yB, N_Vector fyB,
                         booleantype jokB,
                         booleantype *jcurPtrB, realtype gammaB,
                         void *user_dataB,
                         N_Vector tmp1B, N_Vector tmp2B,
                         N_Vector tmp3B)
{
  cvmPbData fwdPb, bckPb;
  mxArray *mx_in[8], *mx_out[3];
  int ret;

  /* Extract global interface data from user-data */
  bckPb = (cvmPbData) user_dataB;
  fwdPb = bckPb->fwd;

  /* Inputs to the Matlab function */
  mx_in[0] = mxCreateDoubleScalar(t);           /* current t */
  mx_in[1] = mxCreateDoubleMatrix(N,1,mxREAL);  /* current y */
  mx_in[2] = mxCreateDoubleMatrix(NB,1,mxREAL); /* current yB */
  mx_in[3] = mxCreateDoubleMatrix(NB,1,mxREAL); /* current fyB */
  mx_in[4] = mxCreateLogicalScalar(jokB);       /* jokB flag */
  mx_in[5] = mxCreateDoubleScalar(gammaB);      /* gammaB value */
  mx_in[6] = bckPb->PSETfct;                    /* matlab function handle */
  mx_in[7] = bckPb->mtlb_data;                  /* matlab user data */
  
  /* Call matlab wrapper */
  GetData(y, mxGetPr(mx_in[1]), N);
  GetData(yB, mxGetPr(mx_in[2]), NB);
  GetData(fyB, mxGetPr(mx_in[3]), NB);

  mexCallMATLAB(3,mx_out,8,mx_in,"cvm_psetB");

  *jcurPtrB = mxIsLogicalScalarTrue(mx_out[0]);
  ret = (int)*mxGetPr(mx_out[1]);

  if (!mxIsEmpty(mx_out[2])) {
    UpdateUserData(mx_out[2], bckPb);
  }

  /* Free temporary space */
  mxDestroyArray(mx_in[0]);
  mxDestroyArray(mx_in[1]);
  mxDestroyArray(mx_in[2]);
  mxDestroyArray(mx_in[3]);
  mxDestroyArray(mx_in[4]);
  mxDestroyArray(mx_in[5]);
  mxDestroyArray(mx_out[0]);
  mxDestroyArray(mx_out[1]);
  mxDestroyArray(mx_out[2]);

  return(ret);

}
/* mexFunction is the gateway routine for the MEX-file. */ 
void
mexFunction( int nlhs, mxArray *plhs[],
             int nrhs, const mxArray *prhs[] )
{
	SBApiSimpleContext* connection = checkArgs(1,2,nlhs,plhs,nrhs,prhs);
	int res;

	res = sbConfigureAckMode(&connection->control, 
			(int)mxGetScalar(prhs[2]));

	plhs[0] = mxCreateLogicalScalar(res);
}
mxArray* test_any_true(const mxArray *mxV)
{
    if (mxIsEmpty(mxV))
    {
        return mxCreateLogicalScalar((mxLogical)false);
    }
    
    if (!mxIsLogical(mxV))
    {
        mexErrMsgIdAndTxt("dmtoolbox:anytrue:invalidarg", 
            "The input array to anytrue should be logical or empty");
    }
    
    int n = mxGetNumberOfElements(mxV);
    const mxLogical* values = (const mxLogical*)mxGetData(mxV);
    
    for (int i = 0; i < n; ++i)
    {
        if (values[i]) return mxCreateLogicalScalar((mxLogical)true);
    }
    
    return mxCreateLogicalScalar((mxLogical)false);
}
Beispiel #10
0
//
// No Input
// Output two variables
//  - output var 1:  logical, indicate whether succeed
//  - output var 2:  a 1 x 16 uint8 array storing the 128-bit GUID
//                   if not successful, it is an empty array
//
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{            
    if (nrhs > 0)
    {
        mexErrMsgTxt("No input variables are allowed for win32guid_core");
    }
    if (nlhs != 2)
    {
        mexErrMsgTxt("The number of outputs should be exactly 2");
    }
    
    // generate the GUID
    GUID gid;
    HRESULT ret = CoCreateGuid(&gid);
        
    // output
	if (ret == S_OK)
    {
        mxArray *parrGuid = mxCreateNumericMatrix(1, 16, mxUINT8_CLASS, mxREAL);
        unsigned char* pBuffer = (unsigned char*)mxGetData(parrGuid);
        
        memcpy(pBuffer, &gid, 16);
        
        mxArray *pRet = mxCreateLogicalScalar((mxLogical)1);
        
        plhs[0] = pRet;
        plhs[1] = parrGuid;
    }
    else
    {
        mxArray *parrGuid = mxCreateNumericMatrix(0, 0, mxUINT8_CLASS, mxREAL);
        mxArray *pRet = mxCreateLogicalScalar((mxLogical)0);
        
        plhs[0] = pRet;
        plhs[1] = parrGuid;
    }
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs < 0 || nrhs > 0)
    {
        mexErrMsgIdAndTxt("lcr:usage", "Usage: [auto, red, green, blue] = lcrGetLedEnables()");
        return;
    }
    
	bool seqCtrl;
    bool red;
    bool green;
    bool blue;
    int result = DLPC350_GetLedEnables(&seqCtrl, &red, &green, &blue);
    if (result == -1)
    {
        mexErrMsgIdAndTxt("lcr:failedToGetLedEnables", "Failed to get LED enables");
        return;
    }
    
    plhs[0] = mxCreateLogicalScalar(seqCtrl);
    plhs[1] = mxCreateLogicalScalar(red);
    plhs[2] = mxCreateLogicalScalar(green);
	plhs[3] = mxCreateLogicalScalar(blue);
}
Beispiel #12
0
/* the gateway function */
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{

  srslte_cell_t cell; 
  srslte_pss_synch_t pss; 
  cf_t *input_symbols;
  int frame_len; 
  
  if (nrhs != NOF_INPUTS) {
    help();
    return;
  }
    
  if (mexutils_read_cell(ENBCFG, &cell)) {
    help();
    return;
  }
  
  /** Allocate input buffers */
  frame_len = mexutils_read_cf(INPUT, &input_symbols);
  if (frame_len < 0) {
    mexErrMsgTxt("Error reading input symbols\n");
    return;
  }
  
  if (srslte_pss_synch_init_fft(&pss, frame_len, srslte_symbol_sz(cell.nof_prb))) {
    fprintf(stderr, "Error initiating PSS\n");
    exit(-1);
  }
  if (srslte_pss_synch_set_N_id_2(&pss, cell.id%3)) {
    fprintf(stderr, "Error setting N_id_2=%d\n",cell.id%3);
    exit(-1);
  }
      
  int peak_idx = srslte_pss_synch_find_pss(&pss, input_symbols, NULL);
  
  if (nlhs >= 1) { 
    plhs[0] = mxCreateLogicalScalar(peak_idx);
  }
  if (nlhs >= 2) {
    mexutils_write_cf(pss.conv_output, &plhs[1], frame_len, 1);  
  }
    
  srslte_pss_synch_free(&pss);
  free(input_symbols);

  return;
}
Beispiel #13
0
// if mxMeta == NULL, create a scalar struct with meta fields within
// else set mxMeta(index).fields with the meta data
// returns the resulting mxMeta
mxArray* setSignalMetaFields(const SignalDataBuffer* psdb, mxArray* mxMeta, int index) {
    mwSize nFields = 6;
    const char* fieldNames[] = {"type", "units", "groupName", "timeFieldName", "concatDimension", "isVariableSize"};

    if(mxMeta == NULL)
        mxMeta = mxCreateStructMatrix(1,1, nFields, fieldNames);

    mxArray* mxSignal_type;
    mxArray* mxSignal_groupName;
    mxArray* mxSignal_timeFieldName;
    mxArray* mxSignal_units;
    mxArray* mxSignal_concatDimension;
    mxArray* mxSignal_isVariableSize;

    // set the .type field
    // convert uint8_t code to string here using getSignalTypeName
    char signalTypeName[MAX_SIGNAL_TYPE_NAME];
    getSignalTypeName(psdb->type, signalTypeName);
    mxSignal_type = mxCreateString(signalTypeName);
    mxSetField(mxMeta, index, "type", mxSignal_type);

    // set the .units field
    mxSignal_units = mxCreateString(psdb->units);
    mxSetField(mxMeta, index, "units", mxSignal_units);

    // set the .groupName field
    mxSignal_groupName = mxCreateString(psdb->pGroupInfo->name);
    mxSetField(mxMeta, index, "groupName", mxSignal_groupName);

    // set the .timeFieldName field to "groupName_time"
    char timeFieldName[MAX_SIGNAL_NAME];
    snprintf(timeFieldName, MAX_SIGNAL_NAME, "%s_time", psdb->pGroupInfo->name);
    mxSignal_timeFieldName = mxCreateString(timeFieldName);
    mxSetField(mxMeta, index, "timeFieldName", mxSignal_timeFieldName);

    // set the .concatDimension field
    mxSignal_concatDimension = mxCreateNumericMatrix(1, 1, mxUINT8_CLASS, mxREAL);
    memcpy(mxGetData(mxSignal_concatDimension), &psdb->concatDimension, sizeof(uint8_t));
    mxSetField(mxMeta, index, "concatDimension", mxSignal_concatDimension);

    // set the .isVariableSize field
    mxSignal_isVariableSize = mxCreateLogicalScalar((mxLogical)psdb->isVariable);
    mxSetField(mxMeta, index, "isVariableSize", mxSignal_isVariableSize);

    return mxMeta;
}
void addResultsEntry(WIN32_FIND_DATA WFD, int cnt, mxArray *structOut, char *defaultPath)
{
	char *buff[40], *month = "NaN";
	char filename[MAX_PATH + 1];
	double temp;
	mxArray *name, *date, *bytes, *isdir, *datenum;
	SYSTEMTIME stUTC, stLocal;
	FILETIME ftUTC, ftLocal;
	
	// File Name
	if (strlen(defaultPath) > 0){
	PathCombine(filename, defaultPath, WFD.cFileName);
	name = mxCreateString(filename);
	} else {
		name = mxCreateString(WFD.cFileName);
	}
	mxSetFieldByNumber(structOut, cnt, NAMEFIELD , name);
	
	// Size (bytes)
	bytes = mxCreateDoubleScalar((WFD.nFileSizeHigh * (MAXDWORD+1)) + WFD.nFileSizeLow);
	mxSetFieldByNumber(structOut, cnt, BYTESFIELD , bytes);
	
	// Directory flag
	isdir = mxCreateLogicalScalar((WFD.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY));
	mxSetFieldByNumber(structOut, cnt, ISDIRFIELD , isdir);
	
	// Get local time
	ftUTC = WFD.ftLastWriteTime;
	FileTimeToSystemTime(&ftUTC, &stUTC);
    SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);

	// Date string
	month = monthNumToStr(stLocal.wMonth);
	sprintf(buff,"%02d-%s-%04d %02d:%02d:%02d",stLocal.wDay,month,stLocal.wYear,stLocal.wHour,stLocal.wMinute,stLocal.wSecond);
	date = mxCreateString(buff);
	mxSetFieldByNumber(structOut, cnt, DATEFIELD , date);
	
	// Datenum
	SystemTimeToFileTime(&stLocal,&ftLocal);
	temp =  (double) ftLocal.dwHighDateTime;
	temp = temp * ((double)MAXDWORD+1);
	temp = temp + ftLocal.dwLowDateTime;
	datenum = mxCreateDoubleScalar((temp/864000000000) + 584755);
	mxSetFieldByNumber(structOut, cnt, DATENUMFIELD , datenum);

}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs > 0)
    {
        mexErrMsgIdAndTxt("lcr:usage", "Usage: external = lcrGetPatternDisplayMode()");
        return;
    }
    
    bool external;
    int result = LCR_GetPatternDisplayMode(&external);
    if (result == -1)
    {
        mexErrMsgIdAndTxt("lcr:failedToGetPatternDisplayMode", "Failed to get pattern display mode");
        return;
    }
    
    plhs[0] = mxCreateLogicalScalar(external);
}
int mtlb_IdaSpilsPset(realtype tt,
                      N_Vector yy, N_Vector yp, N_Vector rr,
                      realtype c_j, void *prec_data,
                      N_Vector tmp1, N_Vector tmp2,
                      N_Vector tmp3)
{
    mxArray *mx_in[8], *mx_out[2];
    int ret;

    /* Inputs to the Matlab function */
    mx_in[0] = mxCreateScalarDouble(1.0);         /* type=1: forward ODE */
    mx_in[1] = mxCreateScalarDouble(tt);          /* current t */
    mx_in[2] = mxCreateDoubleMatrix(N,1,mxREAL);  /* current yy */
    mx_in[3] = mxCreateDoubleMatrix(N,1,mxREAL);  /* current yp */
    mx_in[4] = mxCreateDoubleMatrix(N,1,mxREAL);  /* current rr */
    mx_in[5] = mxCreateLogicalScalar(c_j);        /* current c_j */
    mx_in[6] = mx_PSETfct;                        /* matlab function handle */
    mx_in[7] = mx_data;                           /* matlab user data */

    /* Call matlab wrapper */
    GetData(yy, mxGetPr(mx_in[2]), N);
    GetData(yp, mxGetPr(mx_in[3]), N);
    GetData(rr, mxGetPr(mx_in[4]), N);

    mexCallMATLAB(2,mx_out,8,mx_in,"idm_pset");

    ret = (int)*mxGetPr(mx_out[0]);

    if (!mxIsEmpty(mx_out[1])) {
        UpdateUserData(mx_out[1]);
    }

    /* Free temporary space */
    mxDestroyArray(mx_in[0]);
    mxDestroyArray(mx_in[1]);
    mxDestroyArray(mx_in[2]);
    mxDestroyArray(mx_in[3]);
    mxDestroyArray(mx_in[4]);
    mxDestroyArray(mx_in[5]);
    mxDestroyArray(mx_out[0]);
    mxDestroyArray(mx_out[1]);

    return(ret);
}
int mxW_KINSpilsJac(N_Vector v, N_Vector Jv,
                     N_Vector y, booleantype *new_y, 
                     void *user_data)
{
  kimInterfaceData kimData;
  mxArray *mx_in[5], *mx_out[4];
  int ret;

  /* Extract global interface data from user-data */
  kimData = (kimInterfaceData) user_data;

  /* Inputs to the Matlab function */
  mx_in[0] = mxCreateDoubleMatrix(N,1,mxREAL);  /* current y */
  mx_in[1] = mxCreateDoubleMatrix(N,1,mxREAL);  /* vector v */
  mx_in[2] = mxCreateLogicalScalar(*new_y);     /* */
  mx_in[3] = kimData->JACfct;                   /* matlab function handle */
  mx_in[4] = kimData->mtlb_data;                /* matlab user data */
 
  /* Call matlab wrapper */

  GetData(y, mxGetPr(mx_in[0]), N);
  GetData(v, mxGetPr(mx_in[1]), N);

  mexCallMATLAB(4,mx_out,5,mx_in,"kim_jtv");

  PutData(Jv, mxGetPr(mx_out[0]), N);
  *new_y = mxIsLogicalScalarTrue(mx_out[1]);
  ret = (int)*mxGetPr(mx_out[2]);

  if (!mxIsEmpty(mx_out[3])) {
    UpdateUserData(mx_out[3], kimData);
  }

  /* Free temporary space */
  mxDestroyArray(mx_in[0]);
  mxDestroyArray(mx_in[1]);
  mxDestroyArray(mx_in[2]);
  mxDestroyArray(mx_out[0]);
  mxDestroyArray(mx_out[1]);
  mxDestroyArray(mx_out[2]);
  mxDestroyArray(mx_out[3]);

  return(ret);
}
Beispiel #18
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;
}
Beispiel #19
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);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs > 0)
    {
        mexErrMsgIdAndTxt("lcr:usage", "Usage: [numLutEntries, repeat, numPatsForTrigOut2, numSplash] = lcrGetPatternConfig()");
        return;
    }
    
    unsigned int numLutEntries;
    bool repeat;
    unsigned int numPatsForTrigOut2;
    unsigned int numSplash;
    int result = LCR_GetPatternConfig(&numLutEntries, &repeat, &numPatsForTrigOut2, &numSplash);
    if (result == -1)
    {
        mexErrMsgIdAndTxt("lcr:failedToGetPatternConfig", "Failed to get pattern config");
        return;
    }
    
    plhs[0] = mxCreateDoubleScalar(numLutEntries);
    plhs[1] = mxCreateLogicalScalar(repeat);
    plhs[2] = mxCreateDoubleScalar(numPatsForTrigOut2);
    plhs[3] = mxCreateDoubleScalar(numSplash);
}
Beispiel #21
0
extern void sf_ANN_uses_exported_functions(int nlhs, mxArray * plhs[], int nrhs,
  const mxArray * prhs[])
{
  plhs[0] = mxCreateLogicalScalar(0);
}
/**
 *  @brief [tree,size] = create_ngrame_tree(texts, N) creates ngram tree from review texts
 *  
 *  @param texts Cell array of cell arrays, each filled with unigrams
 *  @param N Type of grams to generate (2, 3, etc...)
 *  @return tree Tree structure generated
 *  @param size Size of the vocabulary
 */
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    //  check inputs
    if(nrhs != 1 && nrhs != 2)
    {
        mexErrMsgIdAndTxt(  "create_ngram_tree:invalidNumInputs",
                            "One or two inputs required.");
    }
    else if (nlhs != 1 && nlhs != 2)
    {
        mexErrMsgIdAndTxt(  "create_ngram_tree:invalidNumOutputs",
                            "One or two outputs required.");
    }
    else if(!mxIsCell(prhs[0]))
    {
        mexErrMsgIdAndTxt(  "create_ngram_tree:inputNotStruct",
                            "Input must be a cell array.");
    }
    else if ((nrhs==2) && !IS_SCALAR(prhs[1]))
    {
        mexErrMsgIdAndTxt(  "create_ngram_tree:inputNotScalar",
                            "Second input must be a scalar");
    }
    
    TreeNode * tree = 0;
    
    size_t num_observations = mxGetNumberOfElements(prhs[0]);
    if (num_observations == 0) {
        mexErrMsgIdAndTxt("create_ngram_tree:invalidInput",
                          "There must be more than 0 observations!");
    }
    
    double integral = 2.0;  //  default is 2 (bigrams)
    if (nrhs == 2) {
        const double gram_count_input = mxGetScalar(prhs[1]);
        if (std::modf(gram_count_input, &integral) != 0.0) {
            mexErrMsgIdAndTxt("create_ngram_tree:invalidInput",
                              "Bigram count must be an integer!");
        }
    }
    
    const int gram_count = static_cast<int>(integral);
    
    //mexPrintf("Running ngram tree on %i observations\n", num_observations);
    //mexPrintf("Building tree...\n");
    //mexEvalString("drawnow;");  //  force flush of IO
    
    //  iterate over observations
    for (size_t i=0; i < num_observations; i++)
    {
        mxArray * cell = mxGetCell(prhs[0], i);
        
        if (!mxIsCell(cell)) {
            if (tree) {
                delete tree;
            }
            mexErrMsgIdAndTxt("create_ngram_tree:invalidInput",
                              "Input must be a cell array.");
        }
        
        size_t num_unigrams = mxGetNumberOfElements(cell);
        
        //  iterate over unigrams for this observation
        std::vector<std::string> unigrams_cleaned;
        unigrams_cleaned.reserve(num_unigrams);
        
        for (size_t n=0; n < num_unigrams; n++)
        {
            mxArray * gram_cell = mxGetCell(cell, n);
            
            if (!mxIsChar(gram_cell)) {
                if (tree) {
                    delete tree;
                }
                mexErrMsgIdAndTxt(  "create_ngram_tree:invalidInput",
                                    "Input cell arrays must contain strings.");
            }
            
            char * cstr = mxArrayToString(gram_cell);

            //  convert ngram to cpp string
            std::string unigram_string = std::string(cstr);
            mxFree(cstr);
            
            //  make lowercase
            std::transform(unigram_string.begin(), unigram_string.end(), unigram_string.begin(), ::tolower);
            
            //  remove everything except alphanumerics + spaces and tabs
            unigram_string.erase(std::remove_if(unigram_string.begin(), unigram_string.end(), clean_predicate), unigram_string.end());
            
            //  trim starting and ending whitespace
            unigram_string = trim_whitespace(unigram_string);
            
            if (unigram_string.empty()) {
                continue;
            }
            
            //mexPrintf("extracted unigram: %s\n", unigram_string.c_str());
            unigrams_cleaned.push_back(unigram_string);
        }
        
        //  build bigrams
        std::vector <std::string> bigrams;
        build_ngrams(bigrams, unigrams_cleaned, gram_count);
        
        //  append to tree
        for (std::vector <std::string> :: iterator it = bigrams.begin(); it != bigrams.end(); it++) {
            if (!tree) {
                tree = new TreeNode(*it);
            }
            tree->append_increment(*it, static_cast<int>(i));
        }
    }
    
    int col=0;
    if (tree) {
        tree->assign_columns(col);      //  lazy - traverse tree to assign column values
    }
    
    //mexPrintf("Done building tree, %lu instances.\n", tree->count_observations());
    
    //  debug
    //std::string left = tree->leftmost_token();
    //std::string right = tree->rightmost_token();
    //mexPrintf("Leftmost term: %s, rightmost term: %s\n", left.c_str(), right.c_str());
    
    //  pass back tree
    if (tree)
    {
        plhs[0] = tree->create_mex_struct();
        
        if (nlhs == 2) {
            plhs[1] = mxCreateDoubleScalar((double)tree->count_nodes());
        }
        
        //  cleanup
        delete tree;
    }
    else
    {
        //  no tree was created, not enough unigrams - pass back logical false
        plhs[0] = mxCreateLogicalScalar(false);
        if (nlhs == 2) {
            plhs[1] = mxCreateDoubleScalar(0);
        }
    }
}
extern void sf_Engine_Vehicle_CVT_RS_System2_uses_exported_functions(int nlhs,
  mxArray * plhs[], int nrhs, const mxArray * prhs[])
{
  plhs[0] = mxCreateLogicalScalar(0);
}
Beispiel #24
0
void
mexFunction(int nout, mxArray *out[],
            int nin, const mxArray *in[])
{
  char address [1024] ;
  char port [1024] ;
  char key [1024] ;

  struct addrinfo servHints ;
  struct addrinfo *servInfo ;

  int status ;

  enum {IN_HOST, IN_PORT, IN_KEY} ;
  enum {OUT_GO} ;

  if (nin != 3) {
    mexErrMsgTxt("Three arguments required") ;
  }

  if (mxGetString(in[IN_HOST], address, sizeof(address))) {
    mexErrMsgTxt("HOST must be a string") ;
  }
  if (mxGetString(in[IN_PORT], port, sizeof(port))) {
    mexErrMsgTxt("PORT must be a string") ;
  }
  if (mxGetString(in[IN_KEY], key, sizeof(key))) {
    mexErrMsgTxt("KEY must be a string") ;
  }

  /* IN address of server */
  memset(&servHints, 0, sizeof(servHints));
  servHints.ai_family   = AF_INET ; /* AF_UNSPEC */
  servHints.ai_socktype = SOCK_DGRAM ;

  status = getaddrinfo(address, port, &servHints, &servInfo) ;

  if (status) {
    mexPrintf(gai_strerror(status)) ;
    mexErrMsgTxt("getaddrinfo") ;
  }

#if 1
  {
    struct addrinfo *p ;
    for(p = servInfo ; p != NULL ; p = p->ai_next) {
      void *addr;
      char *ipver;
      char ipstr[INET6_ADDRSTRLEN];
      int port ;

      /* get the pointer to the address itself,
       * different fields in IPv4 and IPv6: */
      if (p->ai_family == AF_INET) { /* IPv4 */
        struct sockaddr_in *ipv4 = (struct sockaddr_in *) p->ai_addr ;
        addr = &(ipv4->sin_addr);
        port = ntohs(ipv4->sin_port) ;
        ipver = "IPv4";
      } else { /* IPv6 */
        struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)p->ai_addr;
        addr = &(ipv6->sin6_addr);
        port = ntohs(ipv6->sin6_port) ;
        ipver = "IPv6";
      }

      /* convert the IP to a string and print it: */
      inet_ntop(p->ai_family, addr, ipstr, sizeof ipstr);
      mexPrintf("  %s: %s (port %d)\n", ipver, ipstr, port);
    }
  }
#endif

  {
    char answer [1024] ;
    int unsigned answerLength = sizeof(answer) ;
    int answerRecvLength ;
    int clientSocket ;
    socklen_t fromLength = sizeof(struct sockaddr_in) ;
    int numAttemptsLeft = 5 ;

    memset(answer, 0, answerLength) ;

    clientSocket = socket(servInfo->ai_family,
                          servInfo->ai_socktype,
                          servInfo->ai_protocol) ;

    if (clientSocket < 0) {
      mexErrMsgTxt("socket()") ;
    }

    while (numAttemptsLeft -- > 0) {

      status = sendto(clientSocket,
                      key,
                      strlen(key),
                      0,
                      servInfo->ai_addr,
                      sizeof(struct sockaddr_in)) ;

      status = recvfromTimeOut(clientSocket, 5, 0) ;

      if (status < 0) break ;
      if (status == 0) {
        mexPrintf("Resending request due to timeout (%d left)\n", 
                  numAttemptsLeft) ;
        continue ;
      }

      answerRecvLength = recvfrom(clientSocket,
                                  answer,
                                  answerLength,
                                  0,
                                  servInfo->ai_addr,
                                  &fromLength) ;
      break ;
      /* mexPrintf("answ %d: '%s'\n", answerRecvLength, answer) ; */
    }

    close(clientSocket) ;
    out[OUT_GO] = mxCreateLogicalScalar(strcmp(answer, "stop") != 0) ;
  }

  freeaddrinfo(servInfo) ;
}
Beispiel #25
0
MxArray::MxArray(const bool b) : p_(mxCreateLogicalScalar(b))
{
    if (!p_)
        mexErrMsgIdAndTxt("mexopencv:error", "Allocation error");
}
int main() {

	//SPECIFY PARMETERS, SEE CONFIG.H FILE FOR ENUM OPTIONS
	Configurations config;

	//Algorithm for solving for h
	config.algorithm_solve_h = NEWTON_BRUTE_FORCE;
	//Total time in years
	config.total_time = 20;
	// Initial time step in seconds
	config.initial_time_step = 30000;//12592000;
	// Injection stop
	config.injection_time = 100;
	// Pressure update interval in years
	config.pressure_update_injection = 2;
	config.pressure_update_migration = 5;
	// Permeability type
	config.perm_type = PERM_CONSTANT;
	// Name of formation
	config.formation_name = UTSIRA;
	// Parameter beta for the Corey permeability function
	config.beta = 0.4;

	//////////////////////////////////////////////////////////////////////////

	if (config.formation_name == UTSIRA){
		config.formation = "utsira";
		config.formation_dir = "Utsira";
	} else if(config.formation_name == JOHANSEN){
		config.formation = "johansen";
		config.formation_dir = "Johansen";
	} else {
		printf("ERROR: No data for this formation");
	}

	//Initialize some variables
	int nx, ny, nz;
	float dt, dz;
	float t, tf;
	int year = 60*60*24*365;


	// Device properties
	cudaSetDevice(0);
	int device;
	cudaGetDevice(&device);
	cudaDeviceProp p;
	cudaGetDeviceProperties(&p, device);
	printf("Device name: %s\n", p.name);

	// Set directory path of output and input files
	size_t buff_size= 100;
	char buffer[buff_size];
	const char* path;
	readlink("/proc/self/exe", buffer, buff_size);
	printf("PATH %s", buffer);
	char* output_dir_path = "FullyIntegratedVESimulatorMATLAB/SimulationData/ResultData/";
	char* input_dir_path = "FullyIntegratedVESimulatorMATLAB/SimulationData/FormationData/";

	std::cout << "Trying to open " << input_dir_path << std::endl;
	std::cout << "Output will end up in " << output_dir_path << std::endl;

	// Filename strings
	char dir_input[300];
	char filename_input[300];
	char dir_output[300];
	strcpy(dir_input, input_dir_path);
	strcat(dir_input, config.formation_dir);
	strcat(dir_input, "/");
	strcpy(dir_output, output_dir_path);
	strcat(dir_output, config.formation_dir);
	strcat(dir_output, "/");

	strcpy(filename_input, dir_input);
	strcat (filename_input, "dimensions.mat");

	// Output txt files with results
	FILE* matlab_file_h;
	FILE* matlab_file_coarse_satu;
	FILE* matlab_file_volume;

	// Create output files for coarse saturation, interface height and volume
	// Files are stored in the directory
	createOutputFiles(matlab_file_h, matlab_file_coarse_satu, matlab_file_volume, dir_output);

	readDimensionsFromMATLABFile(filename_input, nx, ny, nz);

	InitialConditions IC(nx, ny, 5);
	printf("nx: %i, ny: %i nz: %i dt: %.10f", nx, ny, nz, dt);

	// Cpu pointers to store formation data from MATLAB
	CpuPtr_2D H(nx, ny, 0, true);
	CpuPtr_2D top_surface(nx, ny, 0, true);
	CpuPtr_2D h(nx, ny, 0, true);
	CpuPtr_2D normal_z(nx, ny, 0, true);
	CpuPtr_3D perm3D(nx, ny, nz + 1, 0, true);
	CpuPtr_3D poro3D(nx, ny, nz + 1, 0, true);
	CpuPtr_2D pv(nx, ny, 0, true);
	CpuPtr_2D flux_north(nx, ny, IC.border, true);
	CpuPtr_2D flux_east(nx, ny, IC.border, true);
	CpuPtr_2D source(nx, ny, 0, true);
	CpuPtr_2D grav_north(nx, ny, 0, true);
	CpuPtr_2D grav_east(nx, ny, 0, true);
	CpuPtr_2D K_face_north(nx, ny, 0, true);
	CpuPtr_2D K_face_east(nx, ny, 0, true);
	CpuPtr_2D active_east(nx, ny, 0, true);
	CpuPtr_2D active_north(nx, ny, 0, true);
	CpuPtr_2D volume(nx, ny, 0,true);

	strcpy(filename_input, dir_input);
	strcat (filename_input, "data.mat");

	readFormationDataFromMATLABFile(filename_input, H.getPtr(), top_surface.getPtr(),
			h.getPtr(), normal_z.getPtr(), perm3D.getPtr(), poro3D.getPtr(),
			pv.getPtr(), flux_north.getPtr(), flux_east.getPtr(),
			grav_north.getPtr(), grav_east.getPtr(), K_face_north.getPtr(),
			K_face_east.getPtr(), dz);
	strcpy(filename_input, dir_input);
	strcat (filename_input, "active_cells.mat");
	readActiveCellsFromMATLABFile(filename_input, active_east.getPtr(), active_north.getPtr());

	//readDtTableFromMATLABFile(filename, dt_table, size_dt_table);

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

	startMatlabEngine(ep, config.formation_dir);

	// Create double precision array for the data exchange between the GPU program and the MATLAB program
	mxArray *h_matrix = NULL, *flux_east_matrix = NULL, *flux_north_matrix=NULL;
	mxArray *source_matrix = NULL, *open_well = NULL;
	open_well = mxCreateLogicalScalar(true);
	engPutVariable(ep, "open_well", open_well);
	double * h_matlab_matrix;
	h_matlab_matrix = new double[nx*ny];
	h_matrix = mxCreateDoubleMatrix(nx, ny, mxREAL);
	flux_east_matrix = mxCreateDoubleMatrix(nx+2*IC.border,ny+2*IC.border,mxREAL);
	flux_north_matrix = mxCreateDoubleMatrix(nx+2*IC.border,ny+2*IC.border,mxREAL);
	source_matrix = mxCreateDoubleMatrix(nx, ny, mxREAL);

	// Cpu Pointer to store the results
	CpuPtr_2D zeros(nx, ny, 0, true);

	//Initial Conditions
	IC.dz = dz;
	IC.createnIntervalsTable(H);
	IC.createScalingParameterTable(H, config.beta);

	IC.createInitialCoarseSatu(H, h);
	IC.computeAllGridBlocks();
	IC.createDtVec();

	// Create mask for sparse grid on GPU
	std::vector<int> active_block_indexes;
	std::vector<int> active_block_indexes_flux;
	int n_active_blocks = 0;
	int n_active_blocks_flux = 0;
	createGridMask(H, IC.grid, IC.block, nx, ny, active_block_indexes,
			n_active_blocks);
	createGridMaskFlux(H, IC.grid_flux, IC.block_flux, nx, ny, active_block_indexes_flux,
			n_active_blocks_flux);

	// Print grid mask properties
	printf("\n nBlocks: %i nActiveBlocks: %i fraction: %.5f\n", IC.grid.x * IC.grid.y,
			n_active_blocks, (float) n_active_blocks / (IC.grid.x * IC.grid.y));
	printf("nBlocks: %i nActiveBlocks: %i fraction: %.5f\n", IC.grid_flux.x * IC.grid_flux.y,
			n_active_blocks_flux, (float) n_active_blocks_flux / (IC.grid_flux.x * IC.grid_flux.y));

	printf("dz: %.3f\n", IC.dz);
	dim3 new_sparse_grid(n_active_blocks, 1, 1);
	dim3 new_sparse_grid_flux(n_active_blocks_flux, 1, 1);

	CommonArgs common_args;
	CoarseMobIntegrationKernelArgs coarse_mob_int_args;
	CoarsePermIntegrationKernelArgs coarse_perm_int_args;
	FluxKernelArgs flux_kernel_args;
	TimeIntegrationKernelArgs time_int_kernel_args;
	TimestepReductionKernelArgs time_red_kernel_args;
	SolveForhProblemCellsKernelArgs solve_problem_cells_args;

	printf("Cuda error 0.5: %s\n", cudaGetErrorString(cudaGetLastError()));
	initAllocate(&common_args, &coarse_perm_int_args, &coarse_mob_int_args,
			&flux_kernel_args, &time_int_kernel_args, &time_red_kernel_args, &solve_problem_cells_args);

	h.convertToDoublePointer(h_matlab_matrix);
	memcpy((void *)mxGetPr(h_matrix), (void *)h_matlab_matrix, sizeof(double)*nx*ny);
	engPutVariable(ep, "h_matrix", h_matrix);
	printf("Cuda error 1: %s\n", cudaGetErrorString(cudaGetLastError()));

	// Allocate and set data on the GPU
	GpuPtr_3D perm3D_device(nx, ny, nz + 1, 0, perm3D.getPtr());
	GpuPtr_2D Lambda_c_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D Lambda_b_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D dLambda_c_device(nx, ny, 0, zeros.getPtr());

	GpuPtr_2D dLambda_b_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D scaling_parameter_C_device(nx, ny, 0, IC.scaling_parameter.getPtr());
	GpuPtr_2D K_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D H_device(nx, ny, 0, H.getPtr());
	GpuPtr_2D h_device(nx, ny, 0, h.getPtr());
	GpuPtr_2D top_surface_device(nx, ny, 0, top_surface.getPtr());
	GpuPtr_2D z_diff_east_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D z_diff_north_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D nInterval_device(nx, ny, 0, IC.nIntervals.getPtr());

	GpuPtr_2D U_x_device(nx, ny, IC.border, flux_east.getPtr());
	GpuPtr_2D U_y_device(nx, ny, IC.border, flux_north.getPtr());
	GpuPtr_2D source_device(nx, ny, 0, source.getPtr());
	GpuPtr_2D K_face_east_device(nx, ny, 0, K_face_east.getPtr());
	GpuPtr_2D K_face_north_device(nx, ny, 0, K_face_north.getPtr());
	GpuPtr_2D grav_east_device(nx, ny, 0, grav_east.getPtr());
	GpuPtr_2D grav_north_device(nx, ny, 0, grav_north.getPtr());
	GpuPtr_2D normal_z_device(nx, ny, 0, normal_z.getPtr());
	GpuPtr_2D R_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D pv_device(nx, ny, 0, pv.getPtr());
	GpuPtr_2D output_test_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D active_east_device(nx, ny, 0, active_east.getPtr());
	GpuPtr_2D active_north_device(nx, ny, 0, active_north.getPtr());
	GpuPtr_2D vol_old_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D vol_new_device(nx, ny, 0, zeros.getPtr());
	GpuPtr_2D coarse_satu_device(nx, ny, 0, IC.initial_coarse_satu_c.getPtr());
	GpuPtr_1D global_dt_device(3, IC.global_time_data);
	GpuPtr_1D dt_vector_device(IC.nElements, IC.dt_vector);

	GpuPtrInt_1D active_block_indexes_device(n_active_blocks,
			&active_block_indexes[0]);

	GpuPtrInt_1D active_block_indexes_flux_device(n_active_blocks_flux,
			&active_block_indexes_flux[0]);

	cudaCheckError();
	setCommonArgs(&common_args, IC.p_ci, IC.delta_rho, IC.g, IC.mu_c, IC.mu_b,
			IC.s_c_res, IC.s_b_res, IC.lambda_end_point_c, IC.lambda_end_point_b,
			active_east_device.getRawPtr(), active_north_device.getRawPtr(),
			H_device.getRawPtr(), pv_device.getRawPtr(),
			nx, ny, IC.border);
	setupGPU(&common_args);

	setCoarsePermIntegrationKernelArgs(&coarse_perm_int_args,
			K_device.getRawPtr(), perm3D_device.getRawPtr(),
			nInterval_device.getRawPtr(), IC.dz);
	callCoarsePermIntegrationKernel(IC.grid, IC.block, &coarse_perm_int_args);

	setCoarseMobIntegrationKernelArgs(&coarse_mob_int_args,
			Lambda_c_device.getRawPtr(), Lambda_b_device.getRawPtr(),
			dLambda_c_device.getRawPtr(), dLambda_b_device.getRawPtr(),
			h_device.getRawPtr(), perm3D_device.getRawPtr(),
			K_device.getRawPtr(), nInterval_device.getRawPtr(),
			scaling_parameter_C_device.getRawPtr(),
			active_block_indexes_device.getRawPtr(), IC.p_ci, IC.dz, config.perm_type);

	setFluxKernelArgs(&flux_kernel_args,
			Lambda_c_device.getRawPtr(),Lambda_b_device.getRawPtr(),
			dLambda_c_device.getRawPtr(), dLambda_b_device.getRawPtr(),
			U_x_device.getRawPtr(), U_y_device.getRawPtr(), source_device.getRawPtr(),
			h_device.getRawPtr(),top_surface_device.getRawPtr(),
			normal_z_device.getRawPtr(),
			K_face_east_device.getRawPtr(), K_face_north_device.getRawPtr(),
			grav_east_device.getRawPtr(), grav_north_device.getRawPtr(),
			R_device.getRawPtr(), dt_vector_device.getRawPtr(), active_block_indexes_flux_device.getRawPtr(),
			output_test_device.getRawPtr());

	setTimestepReductionKernelArgs(&time_red_kernel_args, TIME_THREADS, IC.nElements, global_dt_device.getRawPtr(),
								   IC.cfl_scale, dt_vector_device.getRawPtr());

	//CUDPP
	CUDPPHandle plan;
	unsigned int* d_isValid;
	int* d_in;
	int* d_out;
	size_t* d_numValid = NULL;
	size_t numValidElements;
	unsigned int numElements=nx*ny;
	cudaCheckError();
	cudaMalloc((void**) &d_isValid, sizeof(unsigned int)*numElements);
	cudaMalloc((void**) &d_in, sizeof(int)*numElements);
	cudaMalloc((void**) &d_out, sizeof(int)*numElements);
	cudaMalloc((void**) &d_numValid, sizeof(size_t));
	cudaCheckError();

	CUDPPHandle theCudpp;
	cudppCreate(&theCudpp);

	setUpCUDPP(theCudpp, plan, nx, ny, d_isValid, d_in, d_out, numElements);
	printf("\nCudaMemcpy error: %s", cudaGetErrorString(cudaGetLastError()));
	cudaCheckError();

	setTimeIntegrationKernelArgs(&time_int_kernel_args, global_dt_device.getRawPtr(),
			IC.integral_res,pv_device.getRawPtr(), h_device.getRawPtr(),
			R_device.getRawPtr(),coarse_satu_device.getRawPtr(),
			scaling_parameter_C_device.getRawPtr(),
			vol_old_device.getRawPtr(), vol_new_device.getRawPtr(),
			d_isValid, d_in);

	cudaCheckError();

	setSolveForhProblemCellsKernelArgs(&solve_problem_cells_args, h_device.getRawPtr(),
									   coarse_satu_device.getRawPtr(), scaling_parameter_C_device.getRawPtr(),
									   d_out, IC.integral_res, d_numValid);
	cudaCheckError();

	//Compute start volume
	callCoarseMobIntegrationKernel(new_sparse_grid, IC.block, IC.grid.x, &coarse_mob_int_args);
	callFluxKernel(new_sparse_grid_flux, IC.block_flux, IC.grid_flux.x, &flux_kernel_args);
	callTimeIntegration(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args);

	cudaCheckError();
	vol_old_device.download(volume.getPtr(), 0, 0, nx, ny);
	float total_volume_old = computeTotalVolume(volume, nx, ny);

	t = 0;
	double t2 = 0;
	tf = IC.global_time_data[2];
	int iter_outer_loop = 0;
	int iter_inner_loop = 0;
	int iter_total = 0;
	int iter_total_lim = 5000;
	float time = 0;
	float injected = 0;
	int table_index = 1;
	double time_start = getWallTime();
	double time_start_iter;
	double total_time_gpu = 0;
	while (time < config.total_time && iter_total < iter_total_lim){
		t = 0;
		iter_inner_loop = 0;

		h_device.download(h.getPtr(), 0, 0, nx, ny);
		h.convertToDoublePointer(h_matlab_matrix);

		memcpy((void *)mxGetPr(h_matrix), (void *)h_matlab_matrix, sizeof(double)*nx*ny);
		engPutVariable(ep, "h_matrix", h_matrix);
		if (time >= config.injection_time){
			open_well = mxCreateLogicalScalar(false);
			engPutVariable(ep, "open_well", open_well);
			IC.global_time_data[2] = 31536000*config.pressure_update_migration;
			tf = IC.global_time_data[2];
			cudaMemcpy(global_dt_device.getRawPtr(), IC.global_time_data, sizeof(float)*3, cudaMemcpyHostToDevice);
		}

		// MATLAB call
		engEvalString(ep, "[source, east_flux, north_flux] = pressureFunctionToRunfromCpp(h_matrix, variables, open_well);");

		// Get variables from MATLABs pressure solver
		flux_east_matrix = engGetVariable(ep, "east_flux");
		flux_north_matrix = engGetVariable(ep, "north_flux");
		source_matrix = engGetVariable(ep, "source");

		memcpy((void *)flux_east.getPtr(), (void *)mxGetPr(flux_east_matrix), sizeof(float)*(nx+2*IC.border)*(ny+2*IC.border));
		memcpy((void *)flux_north.getPtr(), (void *)mxGetPr(flux_north_matrix), sizeof(float)*(nx+2*IC.border)*(ny+2*IC.border));
		memcpy((void *)source.getPtr(), (void *)mxGetPr(source_matrix), sizeof(float)*nx*ny);

		source_device.upload(source.getPtr(), 0, 0, nx, ny);
		U_x_device.upload(flux_east.getPtr(), 0, 0, nx+2*IC.border, ny+2*IC.border);
		U_y_device.upload(flux_north.getPtr(), 0, 0,nx+2*IC.border, ny+2*IC.border);
		time_start_iter = getWallTime();
		while (t < tf && iter_total < iter_total_lim){
			cudaCheckError();
			callCoarseMobIntegrationKernel(new_sparse_grid, IC.block, IC.grid.x, &coarse_mob_int_args);
			cudaCheckError();

			callFluxKernel(new_sparse_grid_flux, IC.block_flux, IC.grid_flux.x, &flux_kernel_args);

			cudaCheckError();
			callTimestepReductionKernel(TIME_THREADS, &time_red_kernel_args);
			cudaCheckError();

			// Set the initial time step
			if (iter_total < 1 && iter_inner_loop == 0){
				IC.global_time_data[0] = config.initial_time_step;
				IC.global_time_data[1] += config.initial_time_step;
				cudaMemcpy(global_dt_device.getRawPtr(), IC.global_time_data, sizeof(float)*3, cudaMemcpyHostToDevice);
			}

			//For precomputed time step insertion
			/*
			IC.global_time_data[0] = (float)dt_table[table_index];
			IC.global_time_data[1] += (float)dt_table[table_index];
			cudaMemcpy(global_dt_device.getRawPtr(), IC.global_time_data, sizeof(float)*3, cudaMemcpyHostToDevice);
			*/
			cudaCheckError();

			if (config.algorithm_solve_h == BRUTE_FORCE)
				callTimeIntegration(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args);
			else if (config.algorithm_solve_h == NEWTON_BRUTE_FORCE){
				callTimeIntegrationNewton(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args);
				cudppCompact(plan, d_out, d_numValid, d_in, d_isValid, numElements);
				callSolveForhProblemCells(IC.grid_pc, IC.block_pc, &solve_problem_cells_args);
			} else if (config.algorithm_solve_h == NEWTON_BISECTION){
				callTimeIntegrationNewton(new_sparse_grid, IC.block, IC.grid.x, &time_int_kernel_args);
				cudppCompact(plan, d_out, d_numValid, d_in, d_isValid, numElements);
				callSolveForhProblemCellsBisection(IC.grid_pc, IC.block_pc, &solve_problem_cells_args);
			}
			cudaCheckError();

			cudaMemcpy(IC.global_time_data, global_dt_device.getRawPtr(), sizeof(float)*3, cudaMemcpyDeviceToHost);
			cudaCheckError();

			// Keep track of injected volume, insert injection coordinate and rate
			injected += IC.global_time_data[0]*source(50,50);
			t += IC.global_time_data[0];

			//table_index++;
			iter_inner_loop++;
			iter_total++;

		}
		total_time_gpu += getWallTime() - time_start_iter;
		printf("Total time in years: %.3f time in this round %.3f timestep %.3f GPU time %.3f time per iter %.8f \n", time, t, IC.global_time_data[0], getWallTime() - time_start_iter, (getWallTime() - time_start_iter)/iter_inner_loop);

		time += t/(year);
		iter_outer_loop++;
	}

	printf("Elapsed time program: %.5f gpu part: %.5f", getWallTime() - time_start, total_time_gpu);
    engClose(ep);

	h_device.download(zeros.getPtr(), 0, 0, nx, ny);
	zeros.printToFile(matlab_file_h);
    coarse_satu_device.download(zeros.getPtr(), 0, 0, nx, ny);
    // Divide by the formation thickness H to get the actual coarse satu
	for (int i = 0; i < nx; i++){
		for (int j = 0; j < ny; j++){
			if (H(i,j) != 0)
				zeros(i,j) = zeros(i,j)/H(i,j);
		}
	}
	zeros.printToFile(matlab_file_coarse_satu);
	vol_new_device.download(zeros.getPtr(), 0, 0, nx, ny);
	zeros.printToFile(matlab_file_volume);

	float total_volume_new = computeTotalVolume(zeros, nx, ny);
	printf("total volume new %.2f total volume old %.2f injected %.1f injected fraction %.10f",
			total_volume_new, total_volume_old, injected, (total_volume_new-injected)/(injected));
	printf("volume fraction %.10f",(total_volume_new-total_volume_old)/(total_volume_old));

	printf("\nCudaMemcpy error: %s", cudaGetErrorString(cudaGetLastError()));
	printf("FINITO precise time %.6f iter_total %i", time, iter_total);

}
extern void sf_IPILCO_relativeRPY_ST_uses_exported_functions(int nlhs, mxArray *
  plhs[], int nrhs, const mxArray * prhs[])
{
  plhs[0] = mxCreateLogicalScalar(0);
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	/*
	input:
	-[string]		directory,
	output:
	-[double array] population sizes.
	-[double array] remaining lifetime.
	*/


	if (nrhs <= 3) {
		std::uint32_t S(0), R(0);

		const mwSize *dims = mxGetDimensions(prhs[0]);
		size_t strlen = dims[1] + 1;
		char *dir = (char*)malloc(sizeof(char)*strlen);
		mxGetString(prhs[0], dir, strlen);
		std::string dirstr(dir);
		free(dir);


		size_t  RRtmp1(0), RRtmp2(0);
		if (nrhs == 2) {
			RRtmp1 = (size_t)mxGetScalar(prhs[1]);
			RRtmp2 = RRtmp1;
		}

		if (nrhs == 3) {
			RRtmp1 = (size_t)mxGetScalar(prhs[1]);
			RRtmp2 = (size_t)mxGetScalar(prhs[2]);
		}

		const size_t RR1 = RRtmp1;
		const size_t RR2 = RRtmp2;

		std::string fnamev1 = dirstr + "/segment_pop.dat";
		std::string fnamev2 = dirstr + "/segment_pop.v2.dat";
		std::string fname;
		size_t vers = 0;
		if (fexists(fnamev1)) {
			vers = 1;
			fname = fnamev1;
		}
		else if (fexists(fnamev2)) {
			vers = 2;
			fname = fnamev2;
		}

		//mexPrintf("%s\n", fname.c_str());
		std::uint16_t L;

		std::vector<double> pops;
		std::vector<double> rlft;

		if (fexists(fname)) {
			//mexPrintf("Loading...");

			FILE *file = fopen(fname.c_str(), "rb");

			if (vers == 2) {
				fread(&R, sizeof(std::uint32_t), 1, file);
				//mexPrintf("R = %d\n", R);
				for (size_t r = 0; r < R; r++) {
					fread(&S, sizeof(std::uint32_t), 1, file);
					for (size_t s = 0; s < S; s++) {
						if (pops.size() == pops.max_size() - 1) {
							break;
						}

						L = 0;
						fread(&L, sizeof(std::uint16_t), 1, file);

						std::uint16_t *data = new std::uint16_t[L]();
						fread(data, sizeof(std::uint16_t), L, file);
						bool useable = true;

						if (nrhs == 1 || (r >= RR1 && r <= RR2)) {
							for (size_t lftm = 1; lftm < L; lftm++) {
								double sim = std::min(data[lftm], data[lftm - 1]) / sqrt(data[lftm] * data[lftm - 1]);
								if (sim < 0.7071){
									useable = false;
								}
							}


							if (useable) {
								for (size_t lftm = 0; lftm < L; lftm++) {
									pops.push_back((double)data[lftm]);
									rlft.push_back((double)L - lftm);
								}
							}
						}

						delete[] data;
					}

					if (nrhs >= 2 && r == RR2) {
						break;
					}
				}
			}
			else {
				fread(&S, sizeof(std::uint32_t), 1, file);
				fread(&R, sizeof(std::uint32_t), 1, file);

				for (size_t s = 0; s < S; s++) {
					if (pops.size() == pops.max_size() - 1) {
						break;
					}

					L = 0;
					fread(&L, sizeof(std::uint16_t), 1, file);

					std::uint16_t *data = new std::uint16_t[L]();
					fread(data, sizeof(std::uint16_t), L, file);
					bool useable = true;

					for (size_t lftm = 1; lftm < L; lftm++) {
						double sim = std::min(data[lftm], data[lftm - 1]) / sqrt(data[lftm] * data[lftm - 1]);
						if (sim < 0.7071){
							useable = false;
						}
					}


					if (useable) {
						for (size_t lftm = 0; lftm < L; lftm++) {
							pops.push_back((double)data[lftm]);
							rlft.push_back((double)L - lftm);
						}
					}

					delete[] data;
				}
			}

			fclose(file);

			plhs[0] = mxCreateNumericMatrix(1, pops.size(), mxDOUBLE_CLASS, mxREAL);
			double* popout = (double*)mxGetData(plhs[0]);
			memcpy(popout, &pops[0], sizeof(double)*pops.size());

			plhs[1] = mxCreateNumericMatrix(1, rlft.size(), mxDOUBLE_CLASS, mxREAL);
			double* rlftout = (double*)mxGetData(plhs[1]);
			memcpy(rlftout, &rlft[0], sizeof(double)*rlft.size());

			//mexPrintf("Load Complete\n");
		}
		else {
			plhs[0] = mxCreateLogicalScalar(0);
			mexPrintf("File Does Not Exists.\n");
		}
	}
	else {
		mexPrintf("Wrong Number of Input Arguments.\n");
		plhs[0] = mxCreateLogicalScalar(0);
	}
}
void mexFunction(int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[])
{     
  /* Check for proper number of arguments. */
  if (nrhs < 1 || nrhs > 3) 
    error(SCRIPT_NAME ": Improper usage!");
 
  if( !mxIsChar(prhs[0]) && !is_mex_fid( prhs[0] ) ) {
    error( SCRIPT_NAME ": expected file name or file descriptor as the first argument!");
  }

  int width, height;
  bool writeMode = false;
    
  if( nrhs == 3 ) {
    if( !is_mex_scalar( prhs[1]) || !is_mex_scalar( prhs[2] ) ) {
      error( SCRIPT_NAME ": expected frame dimmensions as argument 2 and 3");
    }
    height = (int)*mxGetPr( prhs[1] );
    width = (int)*mxGetPr( prhs[2] );
    writeMode = true;      
  }
  if( nrhs == 2 ) {
    if( !mxIsNumeric( prhs[1] ) || mxGetM( prhs[1] ) != 1 || mxGetN( prhs[1] ) != 2) {
      error( SCRIPT_NAME ": expected 2-column matrix as argument 2");
    }
	double *dim = mxGetPr( prhs[1] );   
    height = (int)dim[0];
    width = (int)dim[1];
    writeMode = true;
  }

  if( writeMode && (width < 1 || height < 1 || width > 65535 || height > 65535 ) ) {
    error( SCRIPT_NAME ": Illegal frame size");
  }

  // Open file for reading or writing
    
  int fid;
  if( mxIsChar( prhs[0] ) ) {
    // File name given
    char *fileName = get_mex_string( prhs[0] );
    if( writeMode ) {
      if( !strcmp( "stdout", fileName ) ) 
        fid = 1;
      else {
        fid = open( fileName, O_CREAT | O_TRUNC | O_RDWR | O_BINARY, S_IREAD | S_IWRITE );
        if( fid == -1 ) {
          error( SCRIPT_NAME ": cannot open file for writing!");
        }
      }    
    } else {
      if( !strcmp( "stdin", fileName ) ) 
        fid = 0;
      else {
        fid = open( fileName, O_RDONLY | O_BINARY );
        if( fid == -1 ) {
          error( SCRIPT_NAME ": cannot open file for reading!");
        }
      }
    }
    mxFree( fileName );

  } else {
    // File descriptor given
    double *p_fid = mxGetPr( prhs[0] );
    fid = dup( (int)p_fid[0] );
  }

  mxArray *pfs_stream = mxCreateStructMatrix( 1, 1, 0, NULL );
  plhs[0] = pfs_stream;

  int fnum;
  fnum = mxAddField( pfs_stream, "FID" );
  mxSetFieldByNumber( pfs_stream, 0, fnum, create_mex_double( fid ) );

  fnum = mxAddField( pfs_stream, "MODE" );
  if( writeMode )
    mxSetFieldByNumber( pfs_stream, 0, fnum, create_mex_string("W") );
  else
    mxSetFieldByNumber( pfs_stream, 0, fnum, create_mex_string("R") );

  fnum = mxAddField( pfs_stream, "EOF" );
  mxSetFieldByNumber( pfs_stream, 0, fnum, mxCreateLogicalScalar( false ) );

  if( writeMode ) {
	fnum = mxAddField( pfs_stream, "columns" );
	mxSetFieldByNumber( pfs_stream, 0, fnum, create_mex_double( width ) );
	fnum = mxAddField( pfs_stream, "rows" );
	mxSetFieldByNumber( pfs_stream, 0, fnum, create_mex_double( height ) );

	fnum = mxAddField( pfs_stream, "channels" );
	mxArray *channels = mxCreateStructMatrix( 1, 1, 0, NULL );
	mxSetFieldByNumber( pfs_stream, 0, fnum, channels );

  }
}
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
	/*
	input:
		-[string]		directory,

	output:
		-[double array] crowd population sizes.
		-[double array] crowd population lifetimes.
	*/


	if (nrhs == 1) {
		std::uint32_t S(0), R(0);

		const mwSize *dims = mxGetDimensions(prhs[0]);
		size_t strlen = dims[1] + 1;
		char *dir = (char*)malloc(sizeof(char)*strlen);
		mxGetString(prhs[0], dir, strlen);
		std::string dirstr(dir);
		free(dir);

		//mexPrintf("[%d, %d]\n", LR, UR);

		//mexPrintf("%s\n", dirstr.c_str());

		std::string fname = dirstr + "/segment_pop.dat";
		mexPrintf("%s\n", fname.c_str());
		std::uint16_t L;

		std::vector<double> pops;
		std::vector<double> lifetimes;

		if (fexists(fname)) {
			mexPrintf("Loading...");

			FILE *file = fopen(fname.c_str(), "rb");
			fread(&S, sizeof(std::uint32_t), 1, file);
			fread(&R, sizeof(std::uint32_t), 1, file);

			size_t ss = 0;
			for (size_t s = 0; s < S; s++) {
				if (pops.size() == pops.max_size() - 1) {
					break;
				}

				L = 0;
				fread(&L, sizeof(std::uint16_t), 1, file);

				std::uint16_t *data = new std::uint16_t[L]();
				fread(data, sizeof(std::uint16_t), L, file);
				bool useable = true;
				for (size_t lftm = 1; lftm < L; lftm++) {
					double sim = std::min(data[lftm], data[lftm - 1]) / sqrt(data[lftm] * data[lftm - 1]);
					if (sim < 0.7071){
						useable = false;
					}
				}

				if (useable) {
					double maxpop = 0;
					pops.push_back(data[0]);
					lifetimes.push_back(L);
				}

				delete[] data;
			}

			fclose(file);

			plhs[0] = mxCreateNumericMatrix(1, pops.size(), mxDOUBLE_CLASS, mxREAL);
			plhs[1] = mxCreateNumericMatrix(1, lifetimes.size(), mxDOUBLE_CLASS, mxREAL);

			double* popout = (double*)mxGetData(plhs[0]);
			memcpy(popout, &pops[0], sizeof(double)*pops.size());

			double* poplftms = (double*)mxGetData(plhs[1]);
			memcpy(poplftms, &lifetimes[0], sizeof(double)*lifetimes.size());

			mexPrintf("Load Complete\n");
		}
		else {
			plhs[0] = mxCreateLogicalScalar(0);
			mexPrintf("File Does Not Exists.\n");
		}
	}
	else {
		mexPrintf("Wrong Number of Input Arguments.\n");
		plhs[0] = mxCreateLogicalScalar(0);
	}
}