Example #1
0
/*
 * check_nargin --- interface to IPT checknargin function for 
 * checking for the proper number of input arguments.
 */
void check_nargin(double low, 
                  double high, 
                  int numInputs, 
                  const char *function_name)
{
    mxArray *prhs[4];
    mxArray *plhs[1];
    int nlhs = 0;
    int nrhs = 4;

    plhs[0] = NULL;

    prhs[0] = mxCreateScalarDouble((double) low);
    prhs[1] = mxCreateScalarDouble((double) high);
    prhs[2] = mxCreateScalarDouble((double) numInputs);
    prhs[3] = mxCreateString(function_name);

    mexCallMATLAB(nlhs, plhs, nrhs, prhs, "checknargin");
    
    mxDestroyArray(prhs[0]);
    mxDestroyArray(prhs[1]);
    mxDestroyArray(prhs[2]);
    mxDestroyArray(prhs[3]);

    if (plhs[0] != NULL)
    {
        mxDestroyArray(plhs[0]);
    }
}
int mtlb_IdaSensRes(int Nsens, realtype tres,
                    N_Vector yy, N_Vector yp, N_Vector rr,
                    N_Vector *yyS, N_Vector *ypS, N_Vector *rrS,
                    void *rdataS,
                    N_Vector tmp1, N_Vector tmp2, N_Vector tmp3)
{
    mxArray *mx_in[9], *mx_out[3];
    int is, ret;
    double *tmp_yyS, *tmp_ypS, *tmp_rrS;

    /* Inputs to the Matlab function */
    mx_in[0] = mxCreateScalarDouble(tres);          /* current t */
    mx_in[1] = mxCreateDoubleMatrix(N,1,mxREAL);    /* current yy */
    mx_in[2] = mxCreateDoubleMatrix(N,1,mxREAL);    /* current yp */
    mx_in[3] = mxCreateDoubleMatrix(N,1,mxREAL);    /* current rr */
    mx_in[4] = mxCreateScalarDouble(Ns);            /* number of sensitivities */
    mx_in[5] = mxCreateDoubleMatrix(N*Ns,1,mxREAL); /* current yyS */
    mx_in[6] = mxCreateDoubleMatrix(N*Ns,1,mxREAL); /* current ypS */
    mx_in[7] = mx_SRESfct;                          /* matlab function handle */
    mx_in[8] = mx_data;                             /* matlab user data */

    /* Call matlab wrapper */
    GetData(yy, mxGetPr(mx_in[1]), N);
    GetData(yp, mxGetPr(mx_in[2]), N);
    GetData(rr, mxGetPr(mx_in[3]), N);
    tmp_yyS = mxGetPr(mx_in[5]);
    tmp_ypS = mxGetPr(mx_in[6]);
    for (is=0; is<Ns; is++) {
        GetData(yyS[is], &tmp_yyS[is*N], N);
        GetData(ypS[is], &tmp_ypS[is*N], N);
    }

    mexCallMATLAB(3,mx_out,9,mx_in,"idm_resS");

    tmp_rrS = mxGetPr(mx_out[0]);

    for(is=0; is<Ns; is++)
        PutData(rrS[is], &tmp_rrS[is*N], N);

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

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

    /* 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_in[6]);
    mxDestroyArray(mx_out[0]);
    mxDestroyArray(mx_out[1]);
    mxDestroyArray(mx_out[2]);

    return(ret);
}
int mtlb_IdaDenseJacB(long int NeqB, realtype tt,
                      N_Vector yy, N_Vector yp,
                      N_Vector yyB, N_Vector ypB, N_Vector rrB,
                      realtype c_jB, void *jac_dataB,
                      DenseMat JacB,
                      N_Vector tmp1B, N_Vector tmp2B,
                      N_Vector tmp3B)
{
    double *JB_data;
    long int i;
    mxArray *mx_in[10], *mx_out[3];
    int ret;

    /* Inputs to the Matlab function */
    mx_in[0] = mxCreateScalarDouble(-1.0);        /* type=-1: backward 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(NB,1,mxREAL); /* current yyB */
    mx_in[5] = mxCreateDoubleMatrix(NB,1,mxREAL); /* current ypB */
    mx_in[6] = mxCreateDoubleMatrix(NB,1,mxREAL); /* current rrB */
    mx_in[7] = mxCreateScalarDouble(c_jB);        /* current c_jB */
    mx_in[8] = mx_JACfctB;                        /* matlab function handle */
    mx_in[9] = mx_data;                           /* matlab user data */

    /* Call matlab wrapper */
    GetData(yy, mxGetPr(mx_in[2]), N);
    GetData(yp, mxGetPr(mx_in[3]), N);
    GetData(yyB, mxGetPr(mx_in[4]), NB);
    GetData(ypB, mxGetPr(mx_in[5]), NB);
    GetData(rrB, mxGetPr(mx_in[6]), NB);

    mexCallMATLAB(3,mx_out,10,mx_in,"idm_djac");

    JB_data = mxGetPr(mx_out[0]);
    for (i=0; i<NB; i++)
        memcpy(DENSE_COL(JacB,i), JB_data + i*NB, NB*sizeof(double));

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

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

    /* 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_in[6]);
    mxDestroyArray(mx_in[7]);
    mxDestroyArray(mx_out[0]);
    mxDestroyArray(mx_out[1]);
    mxDestroyArray(mx_out[2]);

    return(ret);
}
int mtlb_IdaSpilsPsolB(realtype tt,
                       N_Vector yy, N_Vector yp,
                       N_Vector yyB, N_Vector ypB, N_Vector rrB,
                       N_Vector rvecB, N_Vector zvecB,
                       realtype c_jB, realtype deltaB,
                       void *prec_dataB, N_Vector tmpB)
{
    mxArray *mx_in[11], *mx_out[3];
    int ret;

    /* Inputs to the Matlab function */
    mx_in[0] = mxCreateScalarDouble(-1.0);        /* type=-1: backward 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(NB,1,mxREAL); /* current yyB */
    mx_in[5] = mxCreateDoubleMatrix(NB,1,mxREAL); /* current ypB */
    mx_in[6] = mxCreateDoubleMatrix(NB,1,mxREAL); /* current rrB */
    mx_in[7] = mxCreateDoubleMatrix(NB,1,mxREAL); /* right hand side rB */
    mx_in[8] = mxCreateScalarDouble(c_jB);        /* current c_jB */
    mx_in[9] = mx_PSOLfctB;                       /* matlab function handle */
    mx_in[10] = mx_data;                          /* matlab user data */

    /* Call matlab wrapper */
    GetData(yy, mxGetPr(mx_in[2]), N);
    GetData(yp, mxGetPr(mx_in[3]), N);
    GetData(yyB, mxGetPr(mx_in[4]), NB);
    GetData(ypB, mxGetPr(mx_in[5]), NB);
    GetData(rrB, mxGetPr(mx_in[6]), NB);
    GetData(rvecB, mxGetPr(mx_in[7]), NB);

    mexCallMATLAB(3,mx_out,11,mx_in,"idm_psol");

    PutData(zvecB, mxGetPr(mx_out[0]), NB);
    ret = (int)*mxGetPr(mx_out[1]);

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

    /* 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_in[6]);
    mxDestroyArray(mx_in[7]);
    mxDestroyArray(mx_in[8]);
    mxDestroyArray(mx_out[0]);
    mxDestroyArray(mx_out[1]);
    mxDestroyArray(mx_out[2]);

    return(ret);

}
int mtlb_IdaBandJac(long int Neq, long int mupper,
                    long int mlower, realtype tt,
                    N_Vector yy, N_Vector yp, N_Vector rr,
                    realtype c_j, void *jac_data, BandMat Jac,
                    N_Vector tmp1, N_Vector tmp2,
                    N_Vector tmp3)
{
    double *J_data;
    long int eband, i;
    int ret;
    mxArray *mx_in[8], *mx_out[3];

    /* 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] = mxCreateScalarDouble(c_j);         /* current c_j */
    mx_in[6] = mx_JACfct;                         /* 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(3,mx_out,8,mx_in,"idm_bjac");

    /* Extract data */
    eband =  mupper + mlower + 1;
    J_data = mxGetPr(mx_out[0]);
    for (i=0; i<N; i++)
        memcpy(BAND_COL(Jac,i) - mupper, J_data + i*eband, eband*sizeof(double));

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

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

    /* 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);
}
int mtlb_IdaSpilsJac(realtype tt,
                     N_Vector yy, N_Vector yp, N_Vector rr,
                     N_Vector v, N_Vector Jv,
                     realtype c_j, void *jac_data,
                     N_Vector tmp1, N_Vector tmp2)
{
    mxArray *mx_in[9], *mx_out[3];
    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] = mxCreateDoubleMatrix(N,1,mxREAL);  /* vector v */
    mx_in[6] = mxCreateScalarDouble(c_j);         /* current c_j */
    mx_in[7] = mx_JACfct;                         /* matlab function handle */
    mx_in[8] = 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);
    GetData(v, mxGetPr(mx_in[5]), N);

    mexCallMATLAB(3,mx_out,9,mx_in,"idm_jtv");

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

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

    /* 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_in[6]);
    mxDestroyArray(mx_out[0]);
    mxDestroyArray(mx_out[1]);
    mxDestroyArray(mx_out[2]);

    return(ret);
}
Example #7
0
void __cdecl mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    double *port;
    int mrows, ncols;
    double *val;
    
/* Check for proper number of arguments. */
    if (nrhs != 1) {
        mexErrMsgTxt("One input argument required.");
    } else if (nlhs != 1) {
        mexErrMsgTxt("One output argument required.");
    }
    
/* The input must be noncomplex scalar double.*/
    mrows = mxGetM(prhs[0]);
    ncols = mxGetN(prhs[0]);
    if (!mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || !(mrows == 1 && ncols == 1)) {
        mexErrMsgTxt("Input must be noncomplex scalar double.");
    }
    
/* Assign pointers to the input. */
    port = mxGetData(prhs[0]);
    plhs[0] = mxCreateScalarDouble(0);
    val = mxGetPr(plhs[0]);
    
    OpenPortTalk();
    *val = inportb(*port);
    ClosePortTalk();    
}
Example #8
0
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
  rtsys = getrtsys() ; // Get pointer to rtsys 

  if (rtsys==NULL) {
    return;
  }

  // Check number and type of arguments. 
  if (nrhs != 1) {
    TT_MEX_ERROR("ttGetCPUTime: Wrong number of input arguments!\nUsage: ttGetCPUTime(taskname)");
    return;
  }

  if (mxIsChar(prhs[0]) != 1 || mxGetM(prhs[0]) != 1) {
    TT_MEX_ERROR("ttGetCPUTime: taskname must be a non-empty string");
    return;
  }

  char taskname[MAXCHARS];
  mxGetString(prhs[0], taskname, MAXCHARS);

  double retval = ttGetCPUTime(taskname); 
    
  plhs[0] = mxCreateScalarDouble(retval);
}
Example #9
0
/*
 * check_input --- interface to IPT checkarray function for
 * checking validity of input arguments.
 */
void check_input(const mxArray *A,
                 const char    *classes,
                 const char    *attributes,
                 const char    *function_name,
                 const char    *variable_name,
                 int           argument_position)
{
    mxArray *prhs[6];
    mxArray *plhs[1];
    int nlhs = 0;
    int nrhs = 6;
        
    prhs[0] = (mxArray *) A;
    prhs[1] = mxCreateString(classes);
    prhs[2] = mxCreateString(attributes);
    prhs[3] = mxCreateString(function_name);
    prhs[4] = mxCreateString(variable_name);
    prhs[5] = mxCreateScalarDouble((double) argument_position);

    plhs[0] = NULL;
    
    mexCallMATLAB(nlhs, plhs, nrhs, prhs, "checkinput");

    mxDestroyArray(prhs[1]);
    mxDestroyArray(prhs[2]);
    mxDestroyArray(prhs[3]);
    mxDestroyArray(prhs[4]);
    mxDestroyArray(prhs[5]);

    if (plhs[0] != NULL)
    {
        mxDestroyArray(plhs[0]);
    }
}
Example #10
0
void *run_main( void *in )
{
    mxArray *N;    /* Matrix containing n. */
    mxArray *R = NULL;    /* Result matrix. */
    int      n;    /* Integer parameter from command line. */

    seterr(0); /*reset the error code */
    /* Get any command line parameter. */
    if (((inputs*)in)->ac >= 2) {
        n = atoi(((inputs*)in)->av[1]);
    } else {
        n = 12;
    }

    /* Call the mclInitializeApplication routine. Make sure that the application
     * was initialized properly by checking the return status. This initialization
     * has to be done before calling any MATLAB API's or MATLAB Compiler generated
     * shared library functions. */
    if( !mclInitializeApplication(NULL,0) )
    {
        fprintf(stderr, "Could not initialize the application.\n");
        seterr(-2);
	return in;
    }
    /* Call the library intialization routine and make sure that the
     * library was initialized properly */
    if (!libPkgInitialize())
    {
      fprintf(stderr,"Could not initialize the library.\n");
      seterr(-3);
    }
    else
    {
	/* Create a 1-by-1 matrix containing n. */
        N = mxCreateScalarDouble(n);
      
	/* Call mlfMrank, the compiled version of mrank.m. */
	mlfMrank(1, &R, N);
	
	/* Print the results. */
	mlfPrintmatrix(R);
	
	/* Free the matrices allocated during this computation. */
	mxDestroyArray(N);
	mxDestroyArray(R);
	
	libPkgTerminate();    /* Terminate the library of M-functions */
    }
/* On MAC, you need to call mclSetExitCode with the appropriate exit status
 * Also, note that you should call mclTerminate application in the end of
 * your application. mclTerminateApplication terminates the entire 
 * application and exits with the exit code set using mclSetExitCode. Note
 * that this behavior is only on MAC platform.
 */
#ifdef __APPLE_CC__
    mclSetExitCode(((inputs*)in)->err);
#endif
    mclTerminateApplication();
    return in;
}
int mtlb_IdaQuadFctB(realtype tt,
                     N_Vector yy, N_Vector yp,
                     N_Vector yyB, N_Vector ypB,
                     N_Vector ypQB, void *rdataQB)
{
    mxArray *mx_in[8], *mx_out[3];
    int ret;

    /* Inputs to the Matlab function */
    mx_in[0] = mxCreateScalarDouble(-1.0);        /* type=-1: backward 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(NB,1,mxREAL); /* current yyB */
    mx_in[5] = mxCreateDoubleMatrix(NB,1,mxREAL); /* current ypB */
    mx_in[6] = mx_QUADfctB;                       /* 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(yyB, mxGetPr(mx_in[4]), NB);
    GetData(ypB, mxGetPr(mx_in[5]), NB);

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

    PutData(ypQB, mxGetPr(mx_out[0]), NqB);

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

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

    /* 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);
}
void mtlb_IdaMonitorB(int call, double tB, N_Vector yyB, N_Vector ypB, N_Vector yQB)
{
    mxArray *mx_in[10], *mx_out[1];

    mx_in[0] = mxCreateScalarDouble(call);            /* 0: first, 1: interm. 2: last */
    mx_in[1] = mxCreateScalarDouble(tB);              /* current time */
    mx_in[2] = mxCreateDoubleMatrix(NB,1,mxREAL);     /* current yyB */
    mx_in[3] = mxCreateDoubleMatrix(NB,1,mxREAL);     /* current ypB */
    if (idm_quadB) {
        mx_in[4] = mxCreateDoubleMatrix(NqB,1,mxREAL);  /* current quadratures */
    } else {
        mx_in[4] = mxCreateDoubleMatrix(0,0,mxREAL);
    }
    mx_in[5] = mxCreateScalarDouble(0.0);             /* Ns is always zero here */
    mx_in[6] = mxCreateDoubleMatrix(0,0,mxREAL);      /* yyS is always empty here */
    mx_in[7] = mxCreateDoubleMatrix(0,0,mxREAL);      /* ypS is always empty here */
    mx_in[8] = mx_MONfctB;
    mx_in[9] = mx_MONdataB;

    if (call == 1) {

        GetData(yyB, mxGetPr(mx_in[2]), NB);
        GetData(ypB, mxGetPr(mx_in[3]), NB);

        if (idm_quadB)
            GetData(yQB, mxGetPr(mx_in[4]), NqB);
    }

    mexCallMATLAB(1,mx_out,10,mx_in,"idm_monitor");

    if (!mxIsEmpty(mx_out[0])) {
        UpdateMonitorDataB(mx_out[0]);
    }

    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_in[6]);
    mxDestroyArray(mx_in[7]);
    mxDestroyArray(mx_out[0]);
}
/** Returns a struct description of a network object. */
mxArray *getMxClassInfo(Advancable *a)
{
  csimClassInfo *classInfo=a->getClassInfo();

  // figure out the number of RW fields
  int i,nRW=0;
  for(i=0;i<classInfo->nFields();i++)
    nRW += classInfo->isFieldRW(i);

  // write rw fields into cell array
  mxArray *fields = mxCreateCellMatrix(1,nRW);
  int ii=0;
  for(i=0;i<classInfo->nFields();i++)
    if ( classInfo->isFieldRW(i) )
      mxSetCell(fields,ii++,mxCreateString(classInfo->getFieldName(i)));

  // make struct array with fields/values
  const char **fieldNames = (const char **)malloc((classInfo->nFields()+3)*sizeof(char *));
  fieldNames[0] = "className";
  fieldNames[1] = "spiking";
  fieldNames[2] = "fields";
  for(i=0;i<classInfo->nFields();i++) {
    fieldNames[3+i] = classInfo->getFieldName(i);
  }
  mxArray *info = mxCreateStructMatrix(1,1,classInfo->nFields()+3,fieldNames);
  free(fieldNames);

  //
  // fill in values
  //

  // className
  mxSetField(info,0,"className",mxCreateString(classInfo->name));

  // spiking
  double spiking=0.0;
  SpikingSynapse *s=dynamic_cast<SpikingSynapse *>(a);
  if ( s ) spiking=1.0;
  SpikingNeuron *n=dynamic_cast<SpikingNeuron *>(a);
  if ( n ) spiking=1.0;
  mxSetField(info,0,"spiking",mxCreateScalarDouble(spiking));

  // fields
  mxSetField(info,0,"fields",fields);
  
  // fields and values
  for(ii=0, i=0;i<classInfo->nFields();i++) {
    int mm = a->getFieldSizeById((char *)a,i);
    mxArray *fv = mxCreateDoubleMatrix(mm,1,mxREAL);
    double *value=mxGetPr(fv);
    a->getFieldById((char *)a,i,value);
    mxSetField(info,0,classInfo->getFieldName(i),fv);
  }

  return info;  
}
Example #14
0
/* NO INDEX,
 * VALUE = uint8 */
static void setUINT8(int command, uint8_T value) {
   enum { COMMAND_ARG = 0, VALUE_ARG, NUMARGS };
   mxArray *rhs[NUMARGS];
   int i;
   rhs[COMMAND_ARG] = mxCreateScalarDouble(command);
   setUINT8arg(rhs, VALUE_ARG, value);
   mexCallMATLAB(0, NULL, NUMARGS, rhs, MEX_FILE);
   for (i=0; i<NUMARGS; i++) {
      mxDestroyArray(rhs[i]);
   }
}
Example #15
0
/* Special case setMTA,
 * INDEX = uint8, MTA = uint32 */
void setMTA(uint8_T index, uint32_T mta) {
   enum { COMMAND_ARG = 0, INDEX_ARG, MTA_ARG, NUMARGS };
   mxArray *rhs[NUMARGS];
   int i;
   rhs[COMMAND_ARG] = mxCreateScalarDouble(E_SET_MTA);
   setUINT8arg(rhs, INDEX_ARG, index);
   setUINT32arg(rhs, MTA_ARG, mta);
   mexCallMATLAB(0, NULL, NUMARGS, rhs, MEX_FILE);
   for (i=0; i<NUMARGS; i++) {
      mxDestroyArray(rhs[i]);
   }
}
int mtlb_IdaBBDgloc(long int Nlocal, realtype tt,
                    N_Vector yy, N_Vector yp, N_Vector gval,
                    void *res_data)
{
    mxArray *mx_in[6], *mx_out[3];
    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] = mx_GLOCfct;                        /* matlab function handle */
    mx_in[5] = mx_data;                           /* matlab user data */

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

    mexCallMATLAB(3,mx_out,6,mx_in,"idm_gloc");

    PutData(gval, mxGetPr(mx_out[0]), N);
    ret = (int)*mxGetPr(mx_out[1]);

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

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

    return(ret);
}
Example #17
0
void mexFunction(int nOut, mxArray *pOut[], 
		 int nIn, const mxArray *pIn[])
{ 

  mxArray *address, *data;
  char *field_name;
  int field_number;

  // assert(nOut == 2)
  // assert(nIn == 2)

  address = GetPointerData(pIn[0]);
  data = GetPointerData(address);

  if (!data)
  {
     //mexErrMsgTxt("Pointer is NULL");
     pOut[0] = mxCreateScalarDouble(0);
     pOut[1] = mxCreateScalarDouble(0);
  }
  else
  {
    field_name = AllocAndGetString(pIn[1]);

    field_number = mxGetFieldNumber(data, field_name);
    if (field_number == -1)
    {
      //mexErrMsgTxt("Reference to non-existent field");
      pOut[0] = mxCreateScalarDouble(-1);
      pOut[1] = mxCreateScalarDouble(-1);
    }
    else
    {
      pOut[0] = mxGetFieldByNumber(data, 0, field_number);
      pOut[1] = mxCreateScalarDouble(1);
    }
    mxFree(field_name);
  }
}
Example #18
0
mxArray *convert_to_logical(const mxArray *A)
{
    int nrhs = 2;
    int nlhs = 1;
    mxArray *prhs[2];
    mxArray *plhs[1];

    prhs[0] = (mxArray *) A;
    prhs[1] = mxCreateScalarDouble(0.0);
    
    mexCallMATLAB(nlhs, plhs, nrhs, prhs, "ne");

    mxDestroyArray(prhs[1]);
    
    return plhs[0];
}
static void KIM_Solve(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    double *y0, *ys, *fs;
    N_Vector yscale, fscale;
    int buflen, status, strategy;
    char *bufval;

    if ( kim_Kdata == NULL) return ;
    /* Exract y0 and load initial guess in y */
    y0 = mxGetPr(prhs[0]);
    PutData(y, y0, N);

    /* Extract strategy */
    buflen = mxGetM(prhs[1]) * mxGetN(prhs[1]) + 1;
    bufval = mxCalloc(buflen, sizeof(char));
    status = mxGetString(prhs[1], bufval, buflen);
    if(!strcmp(bufval,"None")) strategy = KIN_NONE;
    if(!strcmp(bufval,"LineSearch")) strategy = KIN_LINESEARCH;

    /* Extract yscale */
    ys = mxGetPr(prhs[2]);
    yscale = N_VCloneEmpty(y);
    N_VSetArrayPointer(ys, yscale);

    /* Extract fscale */
    fs = mxGetPr(prhs[3]);
    fscale = N_VCloneEmpty(y);
    N_VSetArrayPointer(fs, fscale);

    /* call KINSol() */
    status = KINSol(kin_mem, y, strategy, yscale, fscale);

    /* KINSOL return flag */
    plhs[0] = mxCreateScalarDouble((double)status);

    /* Solution vector */
    plhs[1] = mxCreateDoubleMatrix(N,1,mxREAL);
    GetData(y, mxGetPr(plhs[1]), N);

    /* Free temporary N_Vectors */
    N_VDestroy(yscale);
    N_VDestroy(fscale);

    return;
}
Example #20
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs,
                 const mxArray *prhs[])
{
  time_t utc;
  
  if (nlhs > 1) {
    mexErrMsgTxt("Too many output arguments");
  }
  
  // Here is a nice reference: http://www.cplusplus.com/ref/ctime/time.html
  time(&utc);
  //mexPrintf("UTC time displayed in local zone: %s",ctime(&utc));
  //mexPrintf("UTC time displayed in GMT: %s",asctime(gmtime(&utc)));
  
  /* Create matrix for the return argument. */
  plhs[0] = mxCreateScalarDouble((double)utc);
   
}
Example #21
0
/* NO INDEX,
 * VALUE = uint8 */
static uint8_T getUINT8(int command) {
   enum { COMMAND_ARG = 0, NUMRHS };
   enum { VALUE_ARG = 0, NUMLHS };
   int i;
   uint8_T value;
   mxArray *rhs[NUMRHS];
   mxArray *lhs[NUMLHS];
   rhs[COMMAND_ARG] = mxCreateScalarDouble(command);
   mexCallMATLAB(NUMLHS, lhs, NUMRHS, rhs, MEX_FILE);
   value = getUINT8arg((const mxArray **) lhs, VALUE_ARG);
   for (i=0; i<NUMRHS; i++) {
      mxDestroyArray(rhs[i]);
   }
   for (i=0; i<NUMLHS; i++) {
      mxDestroyArray(lhs[i]);
   } 
   return value;
}
Example #22
0
/* The mex function returns a uint32 address
 * which is interpreted as a pointer to a uint8
 * value */
uint8_T * getDataPtr(uint8_T index) {
   enum { COMMAND_ARG = 0, INDEX_ARG, NUMRHS };
   enum { ADDRESS_ARG = 0, NUMLHS };
   int i;
   uint32_T address;
   mxArray *rhs[NUMRHS];
   mxArray *lhs[NUMLHS];
   rhs[COMMAND_ARG] = mxCreateScalarDouble(E_GET_DATA_PTR);
   setUINT8arg(rhs, INDEX_ARG, index);
   mexCallMATLAB(NUMLHS, lhs, NUMRHS, rhs, MEX_FILE);
   address = getUINT32arg((const mxArray **) lhs, ADDRESS_ARG);
   for (i=0; i<NUMRHS; i++) {
      mxDestroyArray(rhs[i]);
   }
   for (i=0; i<NUMLHS; i++) {
      mxDestroyArray(lhs[i]);
   }
   return (uint8_T *) address;
}
Example #23
0
/* special case 
 * INDEX = uint8, MTA = uint32 */
uint32_T getMTA(uint8_T index) {
   enum { COMMAND_ARG = 0, INDEX_ARG, NUMRHS };
   enum { MTA_ARG = 0, NUMLHS };
   int i;
   uint32_T mta;
   mxArray *rhs[NUMRHS];
   mxArray *lhs[NUMLHS];
   rhs[COMMAND_ARG] = mxCreateScalarDouble(E_GET_MTA);
   setUINT8arg(rhs, INDEX_ARG, index);
   mexCallMATLAB(NUMLHS, lhs, NUMRHS, rhs, MEX_FILE);
   mta = getUINT32arg((const mxArray **) lhs, MTA_ARG);
   for (i=0; i<NUMRHS; i++) {
      mxDestroyArray(rhs[i]);
   }
   for (i=0; i<NUMLHS; i++) {
      mxDestroyArray(lhs[i]);
   }
   return mta; 
}
int mtlb_IdaGfct(realtype t, N_Vector yy, N_Vector yp,
                 realtype *gout, void *g_data)
{
    double *gdata;
    int i, ret;
    mxArray *mx_in[5], *mx_out[3];

    /* Inputs to the Matlab function */
    mx_in[0] = mxCreateScalarDouble(t);          /* current t */
    mx_in[1] = mxCreateDoubleMatrix(N,1,mxREAL); /* current yy */
    mx_in[2] = mxCreateDoubleMatrix(N,1,mxREAL); /* current yp */
    mx_in[3] = mx_Gfct;                          /* matlab function handle */
    mx_in[4] = mx_data;                          /* matlab user data */

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

    mexCallMATLAB(3,mx_out,5,mx_in,"idm_root");

    gdata = mxGetPr(mx_out[0]);
    for (i=0; i<Ng; i++) gout[i] = gdata[i];

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

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

    /* 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]);

    return(ret);
}
void mexFunction(int nargout, mxArray *argout[], int nargin, const mxArray *argin[])
{
  double tol;
  double *A, *b, *L, *x, *u, *ut, *v, *vt, *d, *z;
  double beta, alpha, normr;
  double c, s, phibar, phi, nn;
  double thet, rhot, rho;
  double mbeta;

  double *resvec, *xvec, *Atr, *r;

  long m, n;
  long maxit, it, i;

  long int_zero = 0;
  long int_one = 1;
  double dbl_one = 1.0;
  double dbl_mone = -1.0;
  double dbl_zero = 0.0;

  A = mxGetPr(argin[0]);
  b = mxGetPr(argin[1]);
  L = mxIsEmpty(argin[2]) ? NULL : mxGetPr(argin[2]);

  m = mxGetM(argin[0]);
  n = mxGetN(argin[0]);

  tol = mxGetScalar(argin[3]) * DNRM2(&m, b, &int_one);
  maxit = (int)mxGetScalar(argin[4]);

  u = malloc(m * sizeof(double));
  ut = malloc(m * sizeof(double));
  v = malloc(n * sizeof(double));
  vt = malloc(n * sizeof(double));
  d = malloc(n * sizeof(double));
  z = malloc(n * sizeof(double));

  argout[0] = mxCreateDoubleMatrix(n, 1, mxREAL);
  x = mxGetPr(argout[0]);

  if (nargout > 2) {
    argout[2] = mxCreateDoubleMatrix(maxit+1, 1, mxREAL);
    resvec = mxGetPr(argout[2]);
    argout[3] = mxCreateDoubleMatrix(maxit+1, 1, mxREAL);
    xvec = mxGetPr(argout[3]);

    r = malloc(m * sizeof(double));
    memcpy(r, b, m * sizeof(double));

    resvec[0] = DNRM2(&m, r, &int_one);
    xvec[0] = DNRM2(&n, x, &int_one);
  }

  memset(x, 0, n * sizeof(double));
  memset(d, 0, n * sizeof(double));

  memcpy(u, b, m * sizeof(double));
  if (L != NULL)
  	DTRSV("L", "N", "Not Unit", &m, L, &m, u, &int_one);

  beta = DNRM2(&m, u, &int_one);
  normr = beta;
  scale(u, m, 1/beta);
  c = 1; s = 0; phibar = beta;

  memcpy(z, u, m * sizeof(double));
  if (L != NULL)
    DTRSV("L", "T", "Not Unit", &m, L, &m, z, &int_one); 
  DGEMV("T", &m, &n, &dbl_one, A, &m, z, &int_one, &dbl_zero, v, &int_one);

  alpha = DNRM2(&n, v, &int_one);
  scale(v, n, 1/alpha);

  it = 0;
  while (it < maxit) {

    DGEMV("N", &m, &n, &dbl_one, A, &m, v, &int_one, &dbl_zero, ut, &int_one);
    if (L != NULL)
      DTRSV("L", "N", "Not Unit", &m, L, &m, ut, &int_one);
    for (i = 0; i < m; i++)
      u[i] = ut[i] - alpha * u[i];

    beta = DNRM2(&m, u, &int_one);
    scale(u, m, 1/beta);

    thet = - s * alpha;
    rhot = c * alpha;
    rho = sqrt(rhot * rhot + beta * beta);
    c = rhot / rho;
    s = - beta / rho;
    phi = c * phibar;
    phibar = s * phibar;
		
    for (i = 0; i < n; i++) {      
      d[i] = (v[i] - thet * d[i]) / rho;
      x[i] = x[i] + phi * d[i];
    }
    it++;

    if (nargout > 2) {
      memcpy(r, b, m * sizeof(double));
      DGEMV("N", &m, &n,  &dbl_mone, A, &m, x, &int_one, &dbl_one, r, &int_one);
      resvec[it] = DNRM2(&m, r, &int_one);
      xvec[it] = DNRM2(&n, x, &int_one);
    }

    normr = fabs(s) * normr;
    if (normr < tol)
      break;

    mbeta = -beta;
    memcpy(z, u, m * sizeof(double));
    if (L != NULL)
      DTRSV("L", "T", "Not Unit", &m, L, &m, z, &int_one);
    DGEMV("T", &m, &n, &dbl_one, A, &m, z, &int_one, &mbeta, v, &int_one);


    alpha = DNRM2(&n, v, &int_one);
    scale(v, n, 1/alpha);	
  }

  if (nargout > 2){
    mxSetM(argout[2] , it + 1);
    mxSetM(argout[3] , it + 1);
  }

  if (nargout > 1)
    argout[1] = mxCreateScalarDouble(it);
  if (nn > tol)
    mexPrintf("dense_lsqr: did not converge\n");
  else
    mexPrintf("dense_lsqr: converged at iteration %d\n", it);

  free(u);
  free(ut);
  free(v);
  free(d);
  free(z);
  if (nargout > 2)
    free(r);
}
/*
 * This ist the Entry Function of this Mex-DLL
 */
void mexFunction(int nlhs, mxArray*plhs[], int nrhs, const mxArray*prhs[])
{
    mexAtExit(CloseDBs);
    
    /*
     * Get the current Language
     */
    if (Language == -1)
    {
#ifdef _WIN32        
        switch(PRIMARYLANGID(GetUserDefaultLangID()))
        {
            case LANG_GERMAN:
                Language = 1;
                break;
                
            default:
                Language = 0;
        }
#else
        Language = 0;
#endif
    }
    
	/*
	 * Print Version Information
	 */
	if (! FirstStart)
    {
    	FirstStart = true;

        mexPrintf (MSG_HELLO, sqlite3_libversion());
    }
    
    /*
     * Check if the first argument is a number, then we have to use
	 * this number as an database id.
     */
    int db_id = 0;
    int FirstArg = 0;
    int NumArgs = nrhs;
    
    if (nrhs >= 1 && mxIsNumeric(prhs[0]))
    {
        db_id = (int) *mxGetPr(prhs[0]);
        if (db_id < 0 || db_id > MaxNumOfDbs)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        db_id --;
        FirstArg ++;
        NumArgs --;
    }

	/*
	 * All remaining arguments have to be strings
	 */
    bool isNotOK = false;
    int  i;
    
    for (i = FirstArg; i < nrhs; i++)
    {
        if (! mxIsChar(prhs[i]))
        {
            isNotOK = true;
            break;
        }
    }
    if (NumArgs < 1 || isNotOK)
    {
        mexPrintf(MSG_USAGE);
        mexErrMsgTxt(MSG_INVALIDARG);
    }

	/*
	 * Get the first string argument, this is the command string
	 */
    char *command = getstring(prhs[FirstArg]);
    
    if (! strcmp(command, "open"))
    {
		/*
		 * open a database. There have to be two string arguments.
		 * The command 'open' and the database filename
		 */
        if (NumArgs != 2)
        {
            mexPrintf(MSG_NOOPENARG, mexFunctionName());
			mxFree(command);
            mexErrMsgTxt(MSG_INVALIDARG);
        }
        
		// TODO: Memoryleak 'command not freed' when getstring fails
        char* dbname = getstring(prhs[FirstArg +1]);

		/*
		 * Is there an database ID? The close the database with the same id 
		 */
        if (db_id > 0 && g_dbs[db_id])
        {
            sqlite3_close(g_dbs[db_id]);
            g_dbs[db_id] = 0;
        }

		/*
		 * If there isn't an database id, then try to get one
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i] == 0)
                {
                    db_id = i;
                    break;
                }
            }
        }
		/*
		 * no database id? sorry, database id table full
		 */
        if (db_id < 0)
        {
            plhs[0] = mxCreateScalarDouble((double) 0);
            mexPrintf(MSG_NOFREESLOT);
			mxFree(command);
        	mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
       
		/*
		 * Open the database
		 */
        int rc = sqlite3_open(dbname, &g_dbs[db_id]);
        
        if (rc)
        {
			/*
			 * Anything wrong? free the database id and inform the user
			 */
            mexPrintf(MSG_CANTOPEN, sqlite3_errmsg(g_dbs[db_id]));
            sqlite3_close(g_dbs[db_id]);

            g_dbs[db_id] = 0;
            plhs[0] = mxCreateScalarDouble((double) 0);
            
			mxFree(command);
	        mxFree(dbname);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
		/*
		 * return value will be the used database id
		 */
        plhs[0] = mxCreateScalarDouble((double) db_id +1);
        mxFree(dbname);
    }
    else if (! strcmp(command, "close"))
    {
		/*
		 * close a database
		 */

		/*
		 * if the database id is < 0 than close all open databases
		 */
        if (db_id < 0)
        {
            for (i = 0; i < MaxNumOfDbs; i++)
            {
                if (g_dbs[i])
                {
                    sqlite3_close(g_dbs[i]);
                    g_dbs[i] = 0;
                }
            }
        }
        else
        {
			/*
			 * If the database is open, then close it. Otherwise
			 * inform the user
			 */
            if (! g_dbs[db_id])
            {
				mxFree(command);
                mexErrMsgTxt(MSG_DBNOTOPEN);
            }
            else
            {
                sqlite3_close(g_dbs[db_id]);
                g_dbs[db_id] = 0;
            }
        }
    }
    else if (! strcmp(command, "status"))
    {
    	for (i = 0; i < MaxNumOfDbs; i++)
        {
            mexPrintf("DB Handle %d: %s\n", i, g_dbs[i] ? "OPEN" : "CLOSED");
        }
    }
    else
    {
		/*
		 * Every unknown command is treated as an sql query string
		 */

		/*
		 * database id < 0? Thats an error...
		 */
        if (db_id < 0)
        {
            mexPrintf(MSG_INVALIDDBHANDLE);
			mxFree(command);
            mexErrMsgTxt(MSG_IMPOSSIBLE);
        }
        
		/*
		 * database not open? -> error
		 */
        if (!g_dbs[db_id])
        {
			mxFree(command);
            mexErrMsgTxt(MSG_DBNOTOPEN);
        }

		const char* query = command;

		/*
		 * emulate the "show tables" sql query
		 */
        if (! strcmpi(query, "show tables"))
        {
            query = "SELECT name as tablename FROM sqlite_master "
                    "WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' "
                    "UNION ALL "
                    "SELECT name as tablename FROM sqlite_temp_master "
                    "WHERE type IN ('table','view') "
                    "ORDER BY 1";
        }

		/*
		 * complete the query
		 */
        if (sqlite3_complete(query))
        {
			mxFree(command);
            mexErrMsgTxt(MSG_INVQUERY);
        }
        
        sqlite3_stmt *st;
        
		/*
		 * and prepare it
		 * if anything is wrong with the query, than complain about it.
		 */
        if (sqlite3_prepare_v2(g_dbs[db_id], query, -1, &st, 0))
        {
            if (st)
                sqlite3_finalize(st);
            
			mxFree(command);
            mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
        }

		/*
		 * Any results?
		 */
        int ncol = sqlite3_column_count(st);
        if (ncol > 0)
        {
            char **fieldnames = new char *[ncol];   /* Column names */
            Values* allrows = 0;                    /* All query results */
            Values* lastrow = 0;					/* pointer to the last result row */
            int rowcount = 0;						/* number of result rows */
            
			/*
			 * Get the column names of the result set
			 */
            for(i=0; i<ncol; i++)
            {
                const char *cname = sqlite3_column_name(st, i);
                
                fieldnames[i] = new char [strlen(cname) +1];
                strcpy (fieldnames[i], cname);
				/*
				 * replace invalid chars by '_', so we can build
				 * valid MATLAB structs
				 */
                char *mk_c = fieldnames[i];
                while (*mk_c)
                {
                	if ((*mk_c == ' ') || (*mk_c == '*') || (*mk_c == '?'))
                    	*mk_c = '_';
                    mk_c++;
                }
            }
            
            /*
			 * get the result rows from the engine
			 *
			 * We cannot get the number of result lines, so we must
			 * read them in a loop and save them into an temporary list.
			 * Later, we can transfer this List into an MATLAB array of structs.
			 * This way, we must allocate enough memory for two result sets,
			 * but we save time by allocating the MATLAB Array at once.
			 */
            for(;;)
            {
				/*
				 * Advance to teh next row
				 */
                int step_res = sqlite3_step(st);

				/*
				 * no row left? break out of the loop
				 */
                if (step_res != SQLITE_ROW)
                    break;

				/*
				 * get new memory for the result
				 */
                Values* RecordValues = new Values(ncol);
                
                Value *v = RecordValues->m_Values;
                for (int j = 0; j < ncol; j++, v++)
                {
                     int fieldtype = sqlite3_column_type(st,j);

                     v->m_Type = fieldtype;
                        
                     switch (fieldtype)
                     {
                         case SQLITE_NULL:      v->m_NumericValue = g_NaN;                                   break;
                         case SQLITE_INTEGER:	v->m_NumericValue = (double) sqlite3_column_int(st, j);      break;
                         case SQLITE_FLOAT:     v->m_NumericValue = (double) sqlite3_column_double(st, j);	 break;
                         case SQLITE_TEXT:      v->m_StringValue  = strnewdup((const char*) sqlite3_column_text(st, j));   break;
                                
                         default:	
							mxFree(command);
							mexErrMsgTxt(MSG_UNKNWNDBTYPE);
                     }
                }
				/*
				 * and add this row to the list of all result rows
				 */
                if (! lastrow)
                {
                    allrows = lastrow = RecordValues;
                }
                else
                {
                    lastrow->m_NextValues = RecordValues;
                    lastrow = lastrow->m_NextValues;
                }
				/*
				 * we have one more...
				 */
                rowcount ++;
            }
            
			/*
			 * end the sql engine
			 */
            sqlite3_finalize(st);

			/*
			 * got nothing? return an empty result to MATLAB
			 */
            if (rowcount == 0 || ! allrows)
            {
                if (!( plhs[0] = mxCreateDoubleMatrix(0,0,mxREAL) ))
				{
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
				}
            }
            else
            {
				/*
				 * Allocate an array of MATLAB structs to return as result
				 */
                int ndims[2];
                
                ndims[0] = rowcount;
                ndims[1] = 1;
                
                if (( plhs[0] = mxCreateStructArray (2, ndims, ncol, (const char**)fieldnames)) == 0)
                {
					mxFree(command);
                    mexErrMsgTxt(MSG_CANTCREATEOUTPUT);
                }
                
				/*
				 * transfer the result rows from the temporary list into the result array
				 */
                lastrow = allrows;
                i = 0;
                while(lastrow)
                {
                    Value* recordvalue = lastrow->m_Values;
                    
                    for (int j = 0; j < ncol; j++, recordvalue++)
                    {
                        if (recordvalue -> m_Type == SQLITE_TEXT)
                        {
                            mxArray* c = mxCreateString(recordvalue->m_StringValue);
                            mxSetFieldByNumber(plhs[0], i, j, c);
                        }
                        else if (recordvalue -> m_Type == SQLITE_NULL && !NULLasNaN)
                        {
                            mxArray* out_double = mxCreateDoubleMatrix(0,0,mxREAL);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                        else
                        {
                            mxArray* out_double = mxCreateDoubleScalar(recordvalue->m_NumericValue);
                            mxSetFieldByNumber(plhs[0], i, j, out_double);
                        }
                    }
                    allrows = lastrow;
                    lastrow = lastrow->m_NextValues;
                    delete allrows;
                    i++;
                }
            }
            for(int i=0; i<ncol; i++)
                delete [] fieldnames[i];
            delete [] fieldnames;
        }
        else
        {
			/*
			 * no result, cleanup the sqlite engine
			 */
            int res = sqlite3_step(st);
            sqlite3_finalize(st);

            if (res != SQLITE_DONE)
            {
				mxFree(command);
                mexErrMsgIdAndTxt(TransErrToIdent(g_dbs[db_id]), sqlite3_errmsg(g_dbs[db_id]));
            }            
        }
    }
	mxFree(command);
}
Example #27
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
	OID ID;
	
	/* OMEIS data structures */
	omeis* is;
	pixHeader* head;
	
	/* MATLAB data structueres */
	mxArray *m_url, *m_sessionkey;
	mxArray *permute_inputs[2];
	mxArray *copy_input_array; /* we need a local copy so we can transpose it */
	
	char* url, *sessionkey;
	
	if (nrhs != 3)
		mexErrMsgTxt("\n [pix] = setPixels (is, ID, pixels)");
		
	if (!mxIsStruct(prhs[0]))
		mexErrMsgTxt("setPixels requires the first input to be the struct outputed"
					 " from openConnectionOMEIS\n");
					 
	if (!(m_url = mxGetField(prhs[0], 0, "url")))
		mexErrMsgTxt("setPixels requires the first input, OMEIS struct, to have field: url");
	if (!(m_sessionkey = mxGetField(prhs[0], 0, "sessionkey")))
		mexErrMsgTxt("setPixels requires the first input, OMEIS struct, to have field: sessionkey");
		
	if (!mxIsChar(m_url) || !mxIsChar(m_sessionkey))
		mexErrMsgTxt("OMEIS field aren't character array.\n");		
	
	if (!mxIsNumeric(prhs[1]))
		mexErrMsgTxt("setPixels requires the second input to be the PixelsID\n") ;
		
	ID = (OID) mxGetScalar(prhs[1]) ;
	
	url = mxArrayToString(m_url);
	sessionkey = mxArrayToString(m_sessionkey);

	is = openConnectionOMEIS (url, sessionkey);
	
	if (!(head = pixelsInfo (is, ID))){
		char err_str[128];
		sprintf(err_str, "PixelsID %llu or OMEIS URL '%s' is probably wrong\n", ID, is->url);		
		
		/* clean up */
		mxFree(url);
		mxFree(sessionkey);
		mxFree(is);
		
		mexErrMsgTxt(err_str);
	}
	
	/*
		In OMEIS Size_X corresponds to columns and Size_Y corresponds to rows.
		This is diametrically opposite to MATLAB's assumptions.
		hence we do
		"$matlab_var_name = permute($matlab_var_name, [2 1 3 4 5]);" 
		the hard way (groan)
	*/
	
	permute_inputs[0] = prhs[2]; /* permute_input isn't being modified so
									discarding the const qualifier is okay */
	permute_inputs[1] = mxCreateDoubleMatrix(1, 5, mxREAL);
 	mxGetPr(permute_inputs[1])[0] = 2;
 	mxGetPr(permute_inputs[1])[1] = 1;
 	mxGetPr(permute_inputs[1])[2] = 3;
 	mxGetPr(permute_inputs[1])[3] = 4;
 	mxGetPr(permute_inputs[1])[4] = 5;
 	
	/* mexCallMATLAB allocates memory for copy_input_array */
 	if (mexCallMATLAB(1, &copy_input_array, 2, permute_inputs, "permute")) {
		/* clean up */
		mxFree(url);
		mxFree(sessionkey);
		mxFree(head);
		mxFree(is);
		
 		char err_str[128];
		sprintf(err_str, "Couldn't permute the pixels to get them in MATLAB orientation");
		mexErrMsgTxt(err_str);
 	}
	
	
	/* check dimension and class check */
	const mwSize* dims = mxGetDimensions (copy_input_array);
	switch (mxGetNumberOfDimensions (copy_input_array)) {
		char err_str[128];
		case 5:
			if (head->dt != dims[4]) {
				sprintf (err_str, "5th Dimension (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[4], head->dt);
				mexErrMsgTxt(err_str);
			}
		case 4:
			if (head->dc != dims[3]) {
				sprintf (err_str, "4th Dimension (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[3], head->dc);
				mexErrMsgTxt(err_str);
			}
		case 3:
			if (head->dz != dims[2]){
				sprintf (err_str, "3th Dimension (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[2], head->dz);
				mexErrMsgTxt(err_str);
			}
		case 2:
			if (head->dy != dims[1]){
				sprintf (err_str, "Height (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[1], head->dy);
				mexErrMsgTxt(err_str);
			}
		case 1:
			if (head->dx != dims[0]){
				sprintf (err_str, "Width (%d) of input array doesn't match OMEIS Pixels (%d).\n", dims[0], head->dx);
				mexErrMsgTxt(err_str);
			}
			break;
		default:
			/* clean up */
			mxFree(url);
			mxFree(sessionkey);
			mxFree(head);
			mxFree(is);
			mxDestroyArray(copy_input_array);
					
			mexErrMsgTxt("Input Array must be 5D or less");
		break;
	}
	
	pixHeader tmp_head;
	CtoOMEISDatatype ((char*) mxGetClassName(copy_input_array), &tmp_head);
	
	if ( !samePixelType(&tmp_head, head)) {
		/* clean up */
		mxFree(url);
		mxFree(sessionkey);
		mxFree(head);
		mxFree(is);
		mxDestroyArray(copy_input_array);
		
		mexErrMsgTxt("Types of input array and Pixels don't match\n");
	}
	
	/* set the pixels */
	int pix = setPixels (is, ID, mxGetPr(copy_input_array));
	
	/* record number of pixels written */
	plhs[0] = mxCreateScalarDouble((double) pix);
	
	/* clean up */
	mxFree(url);
	mxFree(sessionkey);
	mxFree(head);
	mxFree(is);
	mxDestroyArray(copy_input_array);
}
Example #28
0
void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[])
{
	OID ID;
	
	/* OMEIS data structures */
	omeis* is;
	pixHeader* head = (pixHeader*) mxMalloc(sizeof(pixHeader));
	
	/* MATLAB data structueres */
	mxArray *m_dx, *m_dy, *m_dz, *m_dc, *m_dt, *m_bp, *m_isSigned, *m_isFloat;
	mxArray *m_url, *m_sessionkey;
	char* url, *sessionkey;
	
	if (nrhs != 2)
		mexErrMsgTxt("\n [ID] = newPixels (is, ph)");
		
	if (!mxIsStruct(prhs[0]))
		mexErrMsgTxt("newPixels requires the first input to be the struct outputed"
					 " from openConnectionOMEIS\n");
					 
	if (!(m_url = mxGetField(prhs[0], 0, "url")))
		mexErrMsgTxt("newPixels requires the first input, OMEIS struct, to have field: url");
	if (!(m_sessionkey = mxGetField(prhs[0], 0, "sessionkey")))
		mexErrMsgTxt("newPixels requires the first input, OMEIS struct, to have field: sessionkey");
		
	if (!mxIsChar(m_url) || !mxIsChar(m_sessionkey))
		mexErrMsgTxt("OMEIS field aren't character array.\n");		
	
	if (!mxIsStruct(prhs[0]))
		mexErrMsgTxt("newPixels requires the first input to be the struct outputed"
					 " from openConnectionOMEIS\n");
					 
	if (!mxIsStruct(prhs[1]))
		mexErrMsgTxt("newPixels requires the second input to be a pixHeader struct.");
		
	if (!(m_dx = mxGetField(prhs[1], 0, "dx")))
		mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: dx");
	if (!(m_dy = mxGetField(prhs[1], 0, "dy")))
			mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: dy");
	if (!(m_dz = mxGetField(prhs[1], 0, "dz")))
		mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: dz");
	if (!(m_dc = mxGetField(prhs[1], 0, "dc")))
		mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: dc");
	if (!(m_dt = mxGetField(prhs[1], 0, "dt")))
		mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: dt");
	if (!(m_bp = mxGetField(prhs[1], 0, "bp")))
		mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: bp");
	if (!(m_isSigned = mxGetField(prhs[1], 0, "isSigned")))
		mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: isSigned");
	if (!(m_isFloat  = mxGetField(prhs[1], 0, "isFloat")))
		mexErrMsgTxt("newPixels requires the second input, pixHeader struct, to have field: isFloat");

	head->dx = (ome_dim) mxGetScalar(m_dx);
 	head->dy = (ome_dim) mxGetScalar(m_dy);
 	head->dz = (ome_dim) mxGetScalar(m_dz);
 	head->dc = (ome_dim) mxGetScalar(m_dc);
 	head->dt = (ome_dim) mxGetScalar(m_dt);
 	head->bp = (u_int8_t) mxGetScalar(m_bp);
 	head->isSigned = (u_int8_t) mxGetScalar(m_isSigned);
 	head->isFloat  = (u_int8_t) mxGetScalar(m_isFloat);
	
	url = mxArrayToString(m_url);
	sessionkey = mxArrayToString(m_sessionkey);
	
	is = openConnectionOMEIS (url, sessionkey);

	if ( !(ID = newPixels (is, head)) ) {	
		/* clean up */
		mxFree(url);
		mxFree(sessionkey);
		mxFree(head);
		mxFree(is);
		
		mexErrMsgTxt("newPixels OMEIS method failed.\n");
	}

	plhs[0] = mxCreateScalarDouble((double) ID);

	/* clean up */
	mxFree(url);
	mxFree(sessionkey);
	mxFree(head);
	mxFree(is);
}
/** Returns either all network parameters, the values of a global variable, values of an object, connections or parameter lists. */
int csimMexGet(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{ 
  if ( !TheNetwork ) 
    mexErrMsgTxt("CSIM: No network initialized yet!\n");
  
  if ( nrhs < 1 || nrhs > 3 )
    mexErrMsgTxt("CSIM-Usage: value = csim('get',idx[,fieldName]); or\n"
                 "            value = csim('get'[,globalvar]); or\n"
                 "            [pre,post] = csim('get',idx,'connections');\n" );

  if ( nrhs < 2 ) {
    // csim('get'): return all network parameters
    TheNetwork->printFields(); return 0;
  }

  char *globalVar;
  if ( getString(prhs[1],&globalVar) == 0) {
    // csim('get', 'globalVar'): return value of a global variable
    if ( nrhs > 2 )
      mexErrMsgTxt("CSIM-Usage: csim('get',globalvar);");
    double tmp;
    if ( TheNetwork->getField(globalVar,&tmp) < 0 ) return -1;
    plhs[0] = mxCreateScalarDouble(tmp);
  } 


  else {
    // Return info about a network object
    Advancable *a;
    uint32 *idx; int nIdx;
    char *fieldName;

    // Get index of the object
    if ( getUint32Vector(prhs[1],&idx,&nIdx) )
      mexErrMsgTxt("CSIM-Usage: P=csim('get',idx[,fieldName]);  idx is not a uint32 vector.\n");
    
    if ( (a=TheNetwork->getObject(idx[0])) ){
      Recorder *r;
      if ( (r = dynamic_cast<Recorder *>(a)) && (nrhs > 2) ) {
	// Return recorder traces

        if ( getString(prhs[2],&fieldName) )
          mexErrMsgTxt("CSIM-Usage: P=csim('get',idx,fieldName); fieldName is not a string.\n");
        if ( (0 == strncmp(fieldName,"traces",strlen(fieldName))) ) {
          plhs[0] = r->getMxStructArray();
          return 0;
        }
      }

      /* *************** BEGIN MICHAEL PFEIFFER **************** */

      // Return readout info

      Readout *ro;
      if ( (ro = dynamic_cast<Readout *>(a)) && (nrhs > 2) ) {

	if ( getString(prhs[2],&fieldName) )
          mexErrMsgTxt("CSIM-Usage: P=csim('get',idx,fieldName); fieldName is not a string.\n");

	// Return readout filters
	if ( (0 == strncmp(fieldName,"filters",strlen(fieldName))) ) {
	  plhs[0] = getMxReadoutFilters(ro);
	  return 0;
	}

	// Return readout preprocessors
	if ( (0 == strncmp(fieldName,"preprocessors",strlen(fieldName))) ) {
	  plhs[0] = getMxReadoutPreprocessors(ro);
	  return 0;
	}

	// Return readout algorithm
	if ( (0 == strncmp(fieldName,"algorithm",strlen(fieldName))) ) {
	  plhs[0] = getMxReadoutAlgorithm(ro);
	  return 0;
	}

      }


      PhysicalModel *phm;
      if ( (phm = dynamic_cast<PhysicalModel *>(a)) && (nrhs > 2) ) {

	if ( getString(prhs[2],&fieldName) )
          mexErrMsgTxt("CSIM-Usage: P=csim('get',idx,fieldName); fieldName is not a string.\n");

	// Return model input names and connections
	if ( (0 == strncmp(fieldName,"inputs",strlen(fieldName))) ) {
	  plhs[0] = getMxModelInputs(phm);
	  return 0;
	}

	// Return model output names and connections
	if ( (0 == strncmp(fieldName,"outputs",strlen(fieldName))) ) {
	  plhs[0] = getMxModelOutputs(phm);
	  return 0;
	}
      }
      
      /* *************** END MICHAEL PFEIFFER **************** */
    
    } else {
      TheCsimError.add("csim('get',idx,...); idx(1) is not a valid object index!\n");
      return -1;
    }

    if ( nrhs == 3 ) {
      if ( getString(prhs[2],&fieldName) )
        mexErrMsgTxt("CSIM-Usage: P=csim('get',idx,fieldName); fieldName is not a string.\n");
      
      if ( 0 == strcmp(fieldName,"connections") ) {
	// Return connections of a network object

        if ( nlhs != 2 ) {
          mexErrMsgTxt("CSIM-Usage: [pre,post]=csim('get',idx,'connections');"
                       " needs two return arguments.\n");
        }
        if ( nIdx != 1 ) {
          mexErrMsgTxt("CSIM-Usage: [pre,post]=csim('get',idx,'connections');"
                       " idx must be a uint32 scalar.\n");
        }

        if ( (a=TheNetwork->getObject(idx[0])) ) {
	  // Return connections of neuron or synapse
	  
          Neuron  *n;
          Synapse *s;
          if ( (s = dynamic_cast<Synapse *>(a)) ) {
	    // Get synapse connections
            plhs[0] = mxCreateNumericMatrix ( 1, 1, mxUINT32_CLASS, mxREAL );
            plhs[1] = mxCreateNumericMatrix ( 1, 1, mxUINT32_CLASS, mxREAL );
            *(uint32 *)(mxGetData(plhs[0])) = s->getPre();
            *(uint32 *)(mxGetData(plhs[1])) = s->getPost();
          } else if ( (n = dynamic_cast<Neuron *>(a)) ) {
	    // Get neuron connections
            unsigned nPre  = 0;
            unsigned nPost = 0;
            if ( (nPre = n->nPre()) > 0  ) {
	      // Get presynaptic connections
              plhs[0] = mxCreateNumericMatrix ( 1, nPre,  mxUINT32_CLASS, mxREAL );
              n->getPre((uint32 *)mxGetData(plhs[0]));
            } else {
              plhs[0] = mxCreateDoubleMatrix ( 0, 0, mxREAL );
            }
            if ( (nPost = n->nPost()) > 0 ) {
	      // Get postsynaptic inputs
              plhs[1] = mxCreateNumericMatrix ( 1, nPost, mxUINT32_CLASS, mxREAL );
              n->getPost((uint32 *)mxGetData(plhs[1]));
            } else {
              plhs[1] = mxCreateDoubleMatrix ( 0, 0, mxREAL );
            }
          } else
            {TheCsimError.add("csim('get',idx,'connections'); idx(1) is not a synapse or neuron!\n"); return -1;}

        } else
          {TheCsimError.add("csim('get',idx,'connections'); idx(1) is not a valid object index!\n"); return -1;}

      } else if ( 0 == strcmp(fieldName,"struct") ) {
	// Return struct description of the object
        Advancable *a;
        if ( (a=TheNetwork->getObject(idx[0])) )
          plhs[0] = getMxClassInfo(a);
        else
          {TheCsimError.add("csim('get',idx,'struct'); idx(1) is not a valid object index!\n"); return -1;}
      } else {
	// Return single parameter value of several objects

        double *p=0; int m;
        if ( TheNetwork->getParameter(idx,nIdx,fieldName,&p,&m) < 0 ) {
          if ( p ) free(p); p=0;
          return -1;
        }
        
        plhs[0] = mxCreateDoubleMatrix(m, nIdx, mxREAL);
        memcpy(mxGetPr(plhs[0]),p,m*nIdx*sizeof(double));
        if ( p ) free(p); p=0;
      
        return 0;
      }
    } else if ( nrhs == 2 ) {
      // nrhs == 2: no fieldName given
      // so we print out the values of all registerd fields of idx[0]

      Advancable *a;
      if ( nlhs < 1 ) {
        for(int i=0; i<nIdx; i++) {
          if ( (a=TheNetwork->getObject(idx[i])) )
            a->printFields((char *)a);
          else
            {TheCsimError.add("csim('get',idx); idx(%i) is not a valid object index!\n",i+1); return -1;}
        }
      } else {
        if ( (a=TheNetwork->getObject(idx[0])) )
          plhs[0] = getMxClassInfo(a);
        else
          {TheCsimError.add("csim('get',idx); idx(1) is not a valid object index!\n"); return -1;}
      }
    }
  }

  return 0;
}
void mtlb_IdaMonitor(int call, double t,
                     N_Vector yy, N_Vector yp,
                     N_Vector yQ,
                     N_Vector *yyS, N_Vector *ypS)
{
    mxArray *mx_in[10], *mx_out[1];
    double *tmp_yyS, *tmp_ypS;
    int is;

    mx_in[0] = mxCreateScalarDouble(call);            /* call type (0:first, 1:interm. 2:last) */
    mx_in[1] = mxCreateScalarDouble(t);               /* current time */
    mx_in[2] = mxCreateDoubleMatrix(N,1,mxREAL);      /* current yy */
    mx_in[3] = mxCreateDoubleMatrix(N,1,mxREAL);      /* current yp */
    if (idm_quad) {
        mx_in[4] = mxCreateDoubleMatrix(Nq,1,mxREAL);   /* current quadratures */
    } else {
        mx_in[4] = mxCreateDoubleMatrix(0,0,mxREAL);
    }
    mx_in[5] = mxCreateScalarDouble(Ns);              /* number of sensitivities */
    if (idm_fsa) {
        mx_in[6] = mxCreateDoubleMatrix(N*Ns,1,mxREAL); /* current yyS */
        mx_in[7] = mxCreateDoubleMatrix(N*Ns,1,mxREAL); /* current ypS */
    } else {
        mx_in[6] = mxCreateDoubleMatrix(0,0,mxREAL);
        mx_in[7] = mxCreateDoubleMatrix(0,0,mxREAL);
    }
    mx_in[8] = mx_MONfct;                             /* Matlab monitor function */
    mx_in[9] = mx_MONdata;                            /* data for monitor function */

    if (call == 1) {

        GetData(yy, mxGetPr(mx_in[2]), N);
        GetData(yp, mxGetPr(mx_in[3]), N);

        if (idm_quad) {
            GetData(yQ, mxGetPr(mx_in[4]), Nq);
        }

        if (idm_fsa) {
            tmp_yyS = mxGetPr(mx_in[6]);
            tmp_ypS = mxGetPr(mx_in[7]);
            for (is=0; is<Ns; is++) {
                GetData(yyS[is], &tmp_yyS[is*N], N);
                GetData(ypS[is], &tmp_ypS[is*N], N);
            }
        }

    }

    mexCallMATLAB(1,mx_out,10,mx_in,"idm_monitor");

    if (!mxIsEmpty(mx_out[0])) {
        UpdateMonitorData(mx_out[0]);
    }

    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_in[6]);
    mxDestroyArray(mx_in[7]);
    mxDestroyArray(mx_out[0]);
}