Esempio n. 1
0
static void mdlInitializeConditions(SimStruct *S)
{
  /* Now we can be sure that the network blocks have been initialized 
     and that network pointers have been written to workspace. 
     Do the remaining initialization */
  
  RMsys *rmsys = (RMsys*) ssGetUserData(S);

  // Get the network pointer from the MATLAB workspace
  char nwsysbuf[MAXCHARS];
  sprintf(nwsysbuf, "_nwsys_%d", rmsys->networkNbr);
  mxArray *var = (mxArray*)mexGetVariablePtr("global", nwsysbuf);
  if (var == NULL) {
    mexPrintf("Network %d not found!\n", rmsys->networkNbr);
    ssSetErrorStatus(S, "ttreceive: cannot connect to network block");
    return;
  }
  rmsys->nwsys = (RTnetwork *)(*((long long *)mxGetPr(var)));

  // Check the mask input arguments
  if (rmsys->receiver < 1 || rmsys->receiver > rmsys->nwsys->nbrOfNodes) {
    mexPrintf("Receiver number %d out of bounds\n", rmsys->receiver);
    ssSetErrorStatus(S, "ttreceive: receiver number out of bounds");
    return;
  }

}
Esempio n. 2
0
void _testNamespaces_RTTIRegister() {
  const mxArray *alreadyCreated = mexGetVariablePtr("global", "gtsam_testNamespaces_rttiRegistry_created");
  if(!alreadyCreated) {
    std::map<std::string, std::string> types;

    mxArray *registry = mexGetVariable("global", "gtsamwrap_rttiRegistry");
    if(!registry)
      registry = mxCreateStructMatrix(1, 1, 0, NULL);
    typedef std::pair<std::string, std::string> StringPair;
    for(const StringPair& rtti_matlab: types) {
      int fieldId = mxAddField(registry, rtti_matlab.first.c_str());
      if(fieldId < 0)
        mexErrMsgTxt("gtsam wrap:  Error indexing RTTI types, inheritance will not work correctly");
      mxArray *matlabName = mxCreateString(rtti_matlab.second.c_str());
      mxSetFieldByNumber(registry, 0, fieldId, matlabName);
    }
    if(mexPutVariable("global", "gtsamwrap_rttiRegistry", registry) != 0)
      mexErrMsgTxt("gtsam wrap:  Error indexing RTTI types, inheritance will not work correctly");
    mxDestroyArray(registry);
    
    mxArray *newAlreadyCreated = mxCreateNumericMatrix(0, 0, mxINT8_CLASS, mxREAL);
    if(mexPutVariable("global", "gtsam_testNamespaces_rttiRegistry_created", newAlreadyCreated) != 0)
      mexErrMsgTxt("gtsam wrap:  Error indexing RTTI types, inheritance will not work correctly");
    mxDestroyArray(newAlreadyCreated);
  }
}
Esempio n. 3
0
mxArray *mexGetVariable(const char *workspace, const char *name)
{
    mxArray* ret = NULL;
    const mxArray* ptr = mexGetVariablePtr(workspace, name);

    if (ptr)
    {
        ret = (mxArray*)((types::InternalType*)ptr)->clone();
    }
    return ret;
}
Esempio n. 4
0
void _geometry_RTTIRegister() {
  const mxArray *alreadyCreated = mexGetVariablePtr("global", "gtsam_geometry_rttiRegistry_created");
  if(!alreadyCreated) {
    std::map<std::string, std::string> types;

    mxArray *registry = mexGetVariable("global", "gtsamwrap_rttiRegistry");
    if(!registry)
      registry = mxCreateStructMatrix(1, 1, 0, NULL);
    typedef std::pair<std::string, std::string> StringPair;
    BOOST_FOREACH(const StringPair& rtti_matlab, types) {
      int fieldId = mxAddField(registry, rtti_matlab.first.c_str());
      if(fieldId < 0)
        mexErrMsgTxt("gtsam wrap:  Error indexing RTTI types, inheritance will not work correctly");
      mxArray *matlabName = mxCreateString(rtti_matlab.second.c_str());
      mxSetFieldByNumber(registry, 0, fieldId, matlabName);
    }
Esempio n. 5
0
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
  int i;
  int networkNbr=1;
  int nextNode;
  RTnetwork *nwsys;


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

  /* get Network system */
  char nwsysbuf[100];
  sprintf(nwsysbuf, "_nwsys_%d", networkNbr);
  mxArray *var = (mxArray*)mexGetVariablePtr("global", nwsysbuf);
  if (var == NULL) {
    printf("_nwsys_%d not found!\n", networkNbr);
    return;
  }
  nwsys = (RTnetwork *)(*((long *)mxGetPr(var)));


  nextNode = (int)*mxGetPr(prhs[0]);


  /* perform sanity checks */
  if ( nextNode < 0 || nextNode > nwsys->nbrOfNodes ) {
    mexPrintf("NCM: out of range: node %d\n",nextNode);
    return;
  }
    

  /* assign value */
  nwsys->nextNode = nextNode;

  //  mexPrintf("set next node to: %d\n", nextNode);
}
Esempio n. 6
0
void mexFunction(int nlhs, mxArray *plhs[],
		 int nrhs, const mxArray* prhs[])
{
  const mxArray *Kz_mx=mexGetVariablePtr("caller","K0z");
  double *Kz, *Ki, *xd;
  int m=mxGetN(Kz_mx);
  int n=mxGetM(Kz_mx);
  Kz=mxGetPr(Kz_mx);
  Ki=mxGetPr(prhs[0]);
  xd=mxGetPr(prhs[1]);
  for(int j=0;j<m;j++){
    for(int i=0;i<n;i++){
      Kz[j*n+i]=Kz[j*n+i]+Ki[i]*xd[j];
    }
  }
//   for(int i=0;i<n;i++){
//     for(int j=0;j<m;j++){
//       Kz[i*m+j]=Kz[i*m+j]+Ki[i]*xd[j];
//     }
//   }
}
Esempio n. 7
0
static void mdlStart(SimStruct *S)
{
  debugPrintf("'%s': mdlStart\n", S->path);

  rtsys = (RTsys*) ssGetUserData(S);

  // Display the TrueTime splash if global variable TTSPLASH not defined
  mxArray* splvar = (mxArray*)mexGetVariablePtr("global", "TTSPLASH");
  if (splvar == NULL) {
    splvar = mxCreateDoubleMatrix(0, 0, mxREAL);
    mexMakeArrayPersistent(splvar);
    mexPutVariable("global", "TTSPLASH", splvar);
    mexPrintf(
	   "--------------------------------------------------------------\n"
	   "                         Truetime 2.0                         \n"
           "              Copyright (c) 2009 Lund University              \n"
           "   Written by Anton Cervin, Dan Henriksson and Martin Ohlin,  \n"
           " Department of Automatic Control LTH, Lund University, Sweden \n"
           "--------------------------------------------------------------\n"
	   );
  } 

  if (rtsys->init_phase) {
    /* Failure during initialization */
    return;
  } 

  /* DATA ALLOCATION */  
   
  if (rtsys->nbrOfTriggers > 0) {
    rtsys->oldtriggerinputs = new double[rtsys->nbrOfTriggers];
  }
  
  if (rtsys->nbrOfNetworks > 0) {
    rtsys->nwSnd = new double[rtsys->nbrOfNetworks];
    rtsys->oldnwSnd = new double[rtsys->nbrOfNetworks];
    rtsys->oldnetworkinputs = new double[rtsys->nbrOfNetworks];
  }
}
Esempio n. 8
0
static void mdlInitializeSizes(SimStruct *S)
{
  static int printed = 0;
  if (!printed) {
    printed = 1;
    printf("-------------------------------------------------------\n");
    printf("                 TrueTime, Version 1.5\n");            
    printf("                   Copyright (c) 2007\n");
    printf("     Martin Ohlin, Dan Henriksson and Anton Cervin\n");
    printf("          Department of Automatic Control LTH\n");        
    printf("                Lund University, Sweden\n");
    printf("-------------------------------------------------------\n");  
  }

#ifdef KERNEL_MATLAB
  char initfun[100];
  static mxArray *lhs[1]; // warning: used multiple times
  static mxArray *rhs[3]; // warning: used multiple times
  
  segArray = mxCreateDoubleScalar(0.0);
  destroyed = false;
  mexMakeArrayPersistent(segArray);
#endif
  
  ssSetNumSFcnParams(S, 4);  /* Number of expected parameters */
  if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
    return; /* Parameter mismatch will be reported by Simulink */
  }
  
#ifdef KERNEL_MATLAB  
  mxGetString(ssGetSFcnParam(S, 0), initfun, 100);
#endif

  rtsys = new RTsys;

  /* Assign function pointers */
  rtsys->contextSwitchCode = contextSwitchCode;
  rtsys->periodicTaskHandlerCode = periodicTaskHandlerCode;

  rtsys->timeSort = timeSort;
  rtsys->prioSort = prioSort;

  rtsys->default_arrival = default_arrival;
  rtsys->default_release = default_release;
  rtsys->default_start = default_start;
  rtsys->default_suspend = default_suspend;
  rtsys->default_resume = default_resume;
  rtsys->default_finish = default_finish;

  rtsys->prioFP = prioFP;
  rtsys->prioRM = prioRM;
  rtsys->prioEDF = prioEDF;
  rtsys->prioDM = prioDM;

#ifdef KERNEL_MATLAB
  mexSetTrapFlag(1); // return control to the MEX file after an error

  /* Write rtsys pointer to global workspace */
  char rtsysbuf[100];
  sprintf(rtsysbuf, "%p", rtsys);
  mxArray* var = mxCreateDoubleScalar(0.0);
  mexMakeArrayPersistent(var);
  *((long *)mxGetPr(var)) = (long)rtsys;
  mexPutVariable("global", "_rtsys", var);
  rtsys->rtsysptr = (mxArray*)mexGetVariablePtr("global", "_rtsys");

  /* Evaluating user-defined init function (MATLAB) */
  rhs[0] = mxCreateString(initfun);
  if (mexCallMATLAB(1, lhs, 1, rhs, "nargin") != 0) {
    printf("Call to init function failed!\n");
    ssSetErrorStatus(S, "Call to init function failed!");
    return;
  } else {
    if (*mxGetPr(lhs[0]) == 0) {
      if (mexCallMATLAB(0, NULL, 0, NULL, initfun) != 0) {
	printf("Call to init function failed!\n");
	ssSetErrorStatus(S, "Call to init function failed!");
	return;
      } else {
	rtsys->init_phase = false;
      }
    } else if (*mxGetPr(lhs[0]) == 1) {
      rhs[0] = (mxArray *)ssGetSFcnParam(S, 1);
      if (mexCallMATLAB(0, NULL, 1, rhs, initfun) != 0) {
	printf("Call to init function failed!\n");
	ssSetErrorStatus(S, "Call to init function failed!");
	return;
      } else {
	rtsys->init_phase = false;
      }
    } else {
      printf("Init function takes wrong number (> 1) of arguments!\n");
      ssSetErrorStatus(S, "Init function takes wrong number (> 1) of arguments!");
      return;
    }
  }

#else
  /* Save pointer to init args */
  rtsys->initarg = (mxArray *)ssGetSFcnParam(S, 1);
  /* Evaluating user-defined init function (C++) */
  init();
  rtsys->init_phase = false;
#endif

  
  if (!rtsys->initialized) {
    printf("ttInitKernel was not called in init function!\n");
    ssSetErrorStatus(S, "ttInitKernel was not called in init function!");
    return;
  }

  // Clock drift parameters
  const mxArray *arg;
  arg = ssGetSFcnParam(S, 2);
  if (mxIsDoubleScalar(arg)) {
    rtsys->clockDrift = *mxGetPr(arg) + 1;
  }
  arg = ssGetSFcnParam(S, 3);
  if (mxIsDoubleScalar(arg)) {
    rtsys->clockOffset = *mxGetPr(arg);
  }
  //printf("drift: %f, offset:%f\n", rtsys->clockDrift, rtsys->clockOffset);



  if (!ssSetNumInputPorts(S, 4)) return;
  ssSetInputPortDirectFeedThrough(S, 0, 0);
  ssSetInputPortDirectFeedThrough(S, 1, 0);
  ssSetInputPortDirectFeedThrough(S, 2, 0);
  ssSetInputPortDirectFeedThrough(S, 3, 0);
  if (!ssSetNumOutputPorts(S, 5)) return;

  /* Input Ports */

  if (rtsys->nbrOfInputs > 0) 
    ssSetInputPortWidth(S, 0, rtsys->nbrOfInputs);
  else
    ssSetInputPortWidth(S, 0, 1);
  
  if (rtsys->nbrOfTriggers > 0) 
    ssSetInputPortWidth(S, 1, rtsys->nbrOfTriggers);
  else
    ssSetInputPortWidth(S, 1, 1);

  if (rtsys->nbrOfNetworks > 0) 
    ssSetInputPortWidth(S, 2, rtsys->nbrOfNetworks); /* Network receive */
  else
    ssSetInputPortWidth(S, 2, 1);

  ssSetInputPortWidth(S, 3, 1); //battery

  /* Output Ports */

  if (rtsys->nbrOfOutputs > 0) 
    ssSetOutputPortWidth(S, 0, rtsys->nbrOfOutputs);
  else
    ssSetOutputPortWidth(S, 0, 1);

  if (rtsys->nbrOfNetworks > 0) 
    ssSetOutputPortWidth(S, 1, (rtsys->nbrOfNetworks)); /* Network send */
  else
    ssSetOutputPortWidth(S, 1, 1);

  if (rtsys->nbrOfSchedTasks+rtsys->nbrOfSchedHandlers > 0) 
    ssSetOutputPortWidth(S, 2, rtsys->nbrOfSchedTasks+rtsys->nbrOfSchedHandlers);
  else
    ssSetOutputPortWidth(S, 2, 1);

  if (rtsys->nbrOfSchedMonitors > 0) 
    ssSetOutputPortWidth(S, 3, rtsys->nbrOfSchedMonitors*rtsys->nbrOfTasks);
  else
    ssSetOutputPortWidth(S, 3, 1);

  ssSetOutputPortWidth(S, 4, 1); //Energy consumption

  ssSetNumContStates(S, 0);
  ssSetNumDiscStates(S, 0);
  
  ssSetNumSampleTimes(S, 1);
    
  ssSetNumRWork(S, 0);
  ssSetNumIWork(S, 0);
  ssSetNumPWork(S, 0); 
  ssSetNumModes(S, 0);
  ssSetNumNonsampledZCs(S, 1);

  ssSetUserData(S, rtsys);
  
  ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE | SS_OPTION_CALL_TERMINATE_ON_EXIT); 
}
void mexFunction( int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[] )
{
    
    const mxArray * haar_ptr;
    const mxArray * parameter_ptr;
    const mxArray * selector_ptr;
    const mxArray * alpha_ptr;
    
    
    int nfields, NStructElems, ifield, jstruct;
    matrix2d  haarfeature;
    mxArray * tmp;
    
    if(nrhs != 4) {
        mexErrMsgTxt("tow input argument required.");
    }
    // read the prhs[0]  sumimagedata
    // read the prhs[1]  the patches [x , y, w , h]
    // 
    matrix<double> sumimagedata = matrix<double>(A_IN);
    matrix<double> patches      = matrix<double>(B_IN);
    matrix<double> label        = matrix<double>(C_IN);
    matrix<double> importance   = matrix<double>(D_IN);
    // global values
    haar_ptr      = mexGetVariablePtr("caller", "haarfeature");
    selector_ptr  = mexGetVariablePtr("caller", "selectors");
    alpha_ptr     = mexGetVariablePtr("caller", "alpha");
    parameter_ptr = mexGetVariablePtr("caller", "parameter");
            
    matrix<double> selector = matrix<double>(selector_ptr);
    matrix<double> alpha = matrix<double>(alpha_ptr);
    
    // read haar_ptr
    nfields = mxGetNumberOfFields(haar_ptr);
    NStructElems = mxGetNumberOfElements(haar_ptr);
    haarfeature = new matrix<double> * [NStructElems];
    for(jstruct  = 0; jstruct < NStructElems; jstruct ++)
        haarfeature[jstruct] = new matrix<double>[nfields];
    
    // haarfeature is the mxArray point the struct
    // haarfeature[jstruct][ifield] means the i(th) field in j(th) struct
    
    readHaarfeature(haarfeature, haar_ptr, NStructElems, nfields);

    double * parameter = new double[MAX_NUMBER_PARAMETER];
    readParameter(parameter, parameter_ptr);
    
    int labelvalue = (int)label.data[0];
    double importancevalue = importance.data[0];
   
    update(&patches, &alpha, &selector, &haarfeature,&sumimagedata, 
            parameter, labelvalue, importancevalue);
    
     
    
    for(jstruct  = 0; jstruct < NStructElems; jstruct ++)
        delete [] haarfeature[jstruct];
    delete [] haarfeature;
    delete [] parameter;
    
}
/* gateway Function */
void mexFunction(int nlhs,       mxArray * plhs[]
                ,int nrhs, const mxArray * prhs[])
{
    /* check for proper number of arguments */
    /* validate the input values */
    
    /* variable declaration */
    
    /* input variable declaration */
    double dX;
    double mRows;
    double nCols;
    double consideringCellsNo;
    /* 주의: mxArray 자료형 변수는 mexGetVariablePtr 함수를 이용하여
     * 호출함수의 작업공간에 있는 변수들의 포인터만 불러옴 */
    const mxArray * mxArray4;
    const mxArray * mxArray9;
    const mxArray * mxArray10;
    const mxArray * mxArray11;
    const mxArray * mxArray12;
    const mxArray * mxArray13;
    const mxArray * mxArray14;
    const mxArray * mxArray15;
    const mxArray * mxArray16;
    const mxArray * mxArray17;
    const mxArray * mxArray18;
    const mxArray * mxArray19;
    const mxArray * mxArray20;
    
    double * mexSortedIndicies;
    double * mexSDSNbrIndicies;
    double * flood;
    double * floodedRegionCellsNo;
    double * floodedRegionStorageVolume;
    double * bankfullWidth;
    double * transportCapacity;
    double * bedrockIncision;
    double * chanBedSed;
    double * sedimentThick;
    mxLogical * hillslope;
    double * transportCapacityForShallow;
    double * bedrockElev;
    
    /* output variable declaration */
    double * dSedimentThick;
    double * dBedrockElev;
    double * dChanBedSed;
    double * inputFlux;
    double * outputFlux;
    double * inputFloodedRegion;
    mxLogical * isFilled;

    /* create a pointer to the real data in the input matrix */
    dX                  = mxGetScalar(prhs[0]);
    mRows               = mxGetScalar(prhs[1]);
    nCols               = mxGetScalar(prhs[2]);
    consideringCellsNo  = mxGetScalar(prhs[3]);
    
    mxArray4 = mexGetVariablePtr("caller","mexSortedIndicies");    
    mxArray9 = mexGetVariablePtr("caller","mexSDSNbrIndicies");
    mxArray10 = mexGetVariablePtr("caller","flood");
    mxArray11 = mexGetVariablePtr("caller","floodedRegionCellsNo");
    mxArray12 = mexGetVariablePtr("caller","floodedRegionStorageVolume");
    mxArray13 = mexGetVariablePtr("caller","bankfullWidth");
    mxArray14 = mexGetVariablePtr("caller","transportCapacity");
    mxArray15 = mexGetVariablePtr("caller","bedrockIncision");
    mxArray16 = mexGetVariablePtr("caller","chanBedSed");
    mxArray17 = mexGetVariablePtr("caller","sedimentThick");
    mxArray18 = mexGetVariablePtr("caller","hillslope");
    mxArray19 = mexGetVariablePtr("caller","transportCapacityForShallow");
    mxArray20 = mexGetVariablePtr("caller","bedrockElev");
    
    mexSortedIndicies              = mxGetPr(mxArray4);
    mexSDSNbrIndicies              = mxGetPr(mxArray9);    
    flood                          = mxGetPr(mxArray10);    
    floodedRegionCellsNo           = mxGetPr(mxArray11);    
    floodedRegionStorageVolume     = mxGetPr(mxArray12);    
    bankfullWidth                  = mxGetPr(mxArray13);
    transportCapacity              = mxGetPr(mxArray14);    
    bedrockIncision                = mxGetPr(mxArray15);
    chanBedSed                     = mxGetPr(mxArray16);
    sedimentThick                  = mxGetPr(mxArray17);
    hillslope                      = mxGetLogicals(mxArray18);
    transportCapacityForShallow    = mxGetPr(mxArray19);
    bedrockElev                    = mxGetPr(mxArray20);

    /* prepare output data */
    /* create the output matrix */
    plhs[0] = mxCreateDoubleMatrix(mRows,nCols,mxREAL);
    plhs[1] = mxCreateDoubleMatrix(mRows,nCols,mxREAL);
    plhs[2] = mxCreateDoubleMatrix(mRows,nCols,mxREAL);
    plhs[3] = mxCreateDoubleMatrix(mRows,nCols,mxREAL);
    plhs[4] = mxCreateDoubleMatrix(mRows,nCols,mxREAL);
    plhs[5] = mxCreateDoubleMatrix(mRows,nCols,mxREAL);
    plhs[6] = mxCreateLogicalMatrix(mRows,nCols);
    
    /* get a pointer to the real data in the output matrix */
    dSedimentThick      = mxGetPr(plhs[0]);
    dBedrockElev        = mxGetPr(plhs[1]);
    dChanBedSed         = mxGetPr(plhs[2]);
    inputFlux           = mxGetPr(plhs[3]);
    outputFlux          = mxGetPr(plhs[4]);
    inputFloodedRegion  = mxGetPr(plhs[5]);
    isFilled            = mxGetLogicals(plhs[6]);
    
    /* 서브 루틴 수행 */
    EstimateDElevByFluvialProcessBySDS(
        dSedimentThick,
        dBedrockElev,
        dChanBedSed,
        inputFlux,
        outputFlux,
        inputFloodedRegion,
        isFilled,
        dX,
        consideringCellsNo,
        mexSortedIndicies,
        mexSDSNbrIndicies,
        flood,
        floodedRegionCellsNo,
        floodedRegionStorageVolume,
        bankfullWidth,
        transportCapacity,
        bedrockIncision,
        chanBedSed,
        sedimentThick,
        hillslope,
        transportCapacityForShallow,
        bedrockElev);

}
/**
 * \brief Build the list of parameters that configure the tres::Network
 *
 * The tres::Network class (or, more precisely, its underlying concrete
 * implementation) needs to be configured with a bunch of information, such
 * as the description of the message set, the network topology, initialization
 * informations and time resolution, to name only a few. This information is
 * stored inside the T-Res Network block as mask parameters.
 *
 * This function reads the mask parameters and returns a vector-of-string-based
 * description of the information needed by the tres::Network class.
 * Specifically, the information returned by this function has the following form:
 *  - the number of messages in the message-set (#msgs)    - std::string (1)   <-- vector.begin()
 *  - the message-set description                          - std::string (#msgs)
 *      - "message_type;message_UID;"
 *  - the number of items describing the network (#ndescr) - std::string (1)
 *  - the network description                              - std::string (#ndescr)
 *      - "description_type;description_file_paths"
 *  - path to additional libraries for the simulation      - std::string (1)
 *  - the time resolution                                  - std::string (1)
 *                                                                             <-- vector.end()
 *
 * No err checking is performed when reading mask parameters since these are already
 * guaranteed to be valid at MATLAB level (err checking performed by mask callbacks).
 */
static std::vector<std::string> readMaskAndBuildConfVector(SimStruct *S)
{
    char *bufMsgDescr,  // MSG_DESCR_VARNAME
         *bufTimeRes,   // TIME_RESOLUTION
         *bufNtwkDescr, // NTWK_DESCR_VARNAME
         *bufAddLibr;   // OTHER_DEPS

    int bufMsgDescrLen, bufTimeResLen, bufNtwkDescrLen, bufAddLibrLen;
    std::vector<std::string> net_params; // The return list of parameters
    std::stringstream ss;                // A convenience stringstream

    // Get the number of messages (it is equal to the size of output port)
    int_T num_msgs = ssGetOutputPortWidth(S,0);

    // Get the name of the workspace variable for the message set
    bufMsgDescrLen = mxGetN( ssGetSFcnParam(S,MSG_DESCR_VARNAME) )+1;
    bufMsgDescr = new char[bufMsgDescrLen];
    mxGetString(ssGetSFcnParam(S,MSG_DESCR_VARNAME), bufMsgDescr, bufMsgDescrLen);

    // Get the actual message set description
    std::vector<std::string> msg_descr = cellArrayDescrToVectorOfStrings(mexGetVariablePtr("base", bufMsgDescr));
    delete bufMsgDescr;

    // **Insert** the number of messages and
    //            the message set description in the return list
    ss << num_msgs;
    net_params.push_back(ss.str());
    ss.str(std::string());                    // Flush the ss
    net_params.insert(net_params.end(),
                           msg_descr.begin(),
                               msg_descr.end());

    // Get the name of the workspace variable for the Network description
    bufNtwkDescrLen = mxGetN( ssGetSFcnParam(S,NTWK_DESCR_VARNAME) )+1;
    bufNtwkDescr = new char[bufNtwkDescrLen];
    mxGetString(ssGetSFcnParam(S,NTWK_DESCR_VARNAME), bufNtwkDescr, bufNtwkDescrLen);

    // Get the number of Network description entries and
    // the actual Network description
    int_T num_ndescr = mxGetM(mexGetVariablePtr("base", bufNtwkDescr));
    std::vector<std::string> ntwk_descr = cellArrayDescrToVectorOfStrings(mexGetVariablePtr("base", bufNtwkDescr));
    delete bufNtwkDescr;

    // **Insert** the number of Network description entries and
    //            the Network description in the return list
    ss << num_ndescr;
    net_params.push_back(ss.str());
    ss.str(std::string());                    // Flush the ss
    net_params.insert(net_params.end(),
                           ntwk_descr.begin(),
                               ntwk_descr.end());

    // Get the path to additional libraries
    bufAddLibrLen = mxGetN( ssGetSFcnParam(S,OTHER_DEPS) )+1;
    bufAddLibr = new char[bufAddLibrLen];
    mxGetString(ssGetSFcnParam(S,OTHER_DEPS), bufAddLibr, bufAddLibrLen);

    // **Insert** the additional libraries in the return list
    std::string add_libs(bufAddLibr);
    net_params.push_back(add_libs);

    // And finally, get the time resolution
    bufTimeResLen = mxGetN( ssGetSFcnParam(S,TIME_RESOLUTION) )+1;
    bufTimeRes = new char[bufTimeResLen];
    mxGetString(ssGetSFcnParam(S,TIME_RESOLUTION), bufTimeRes, bufTimeResLen);

    // Convert the time resolution to a double
    std::string time_resolution(bufTimeRes);
    delete bufTimeRes;
    if (time_resolution == "Seconds")
        ss << 1.0;
    else if (time_resolution == "Milli_Seconds")
        ss << 1.0e3;
    else if (time_resolution == "Micro_Seconds")
        ss << 1.0e6;
    else if (time_resolution == "Nano_Seconds")
        ss << 1.0e9;

    // **Insert** the time resolution in the return list
    net_params.push_back(ss.str());
    ss.str(std::string());                    // Flush the ss

    // Done, return to the caller
    return (net_params);
}
Esempio n. 12
0
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {
	
// 	printf("start of file \n");
	
	//	Get array_sizes
	const mxArray* mx_array_sizes = mexGetVariablePtr("global", "array_sizes");
	if (mx_array_sizes == NULL) {
		mexErrMsgTxt("array_sizes not defined");
	}
	unsigned array_sizes = (unsigned)mxGetScalar(mx_array_sizes);
	
	//	Get iteration
	const mxArray* mx_iteration = mexGetVariablePtr("caller", "iteration");
	if (mx_iteration == NULL) {
		mexErrMsgTxt("iteration not defined");
	}
	double iteration = mxGetScalar(mx_iteration);
	
	//	Get protection_time
	const mxArray* mx_protection_time = mexGetVariablePtr("caller", "protection_time");
	if (mx_protection_time == NULL) {
		mexErrMsgTxt("protection_time not defined");
	}
	double protection_time = mxGetScalar(mx_protection_time);
	
	//	Get join_probability
	const mxArray* mx_join_probability = mexGetVariablePtr("caller", "join_probability");
	if (mx_join_probability == NULL) {
		mexErrMsgTxt("join_probability not defined");
	}
	double join_probability = mxGetScalar(mx_join_probability);
	
	//	Get threshold_join_nodes
	const mxArray* mx_threshold_join_nodes = mexGetVariablePtr("caller", "threshold_join_nodes");
	if (mx_threshold_join_nodes == NULL) {
		mexErrMsgTxt("threshold_join_nodes not defined");
	}
	double threshold_join_nodes = mxGetScalar(mx_threshold_join_nodes);
	
	//	Get time
	const mxArray* mx_time = mexGetVariablePtr("global", "time");
	if (mx_time == NULL) {
		mexErrMsgTxt("time not defined");
	}
	double time = mxGetScalar(mx_time);
	
	unsigned width_cell_store = mxGetN(prhs[1]);
	unsigned no_cells = mxGetM(prhs[2]);
	unsigned no_FEM_elements = mxGetM(prhs[5]);
	unsigned length_FEM_node_positions = mxGetM(prhs[6]);
	
	double* initial_cell_store = mxGetPr(prhs[1]);
	double* initial_cells_per_node = mxGetPr(prhs[3]);
	double* initial_Dpp = mxGetPr(prhs[4]);
	double* initial_FEM_elements = mxGetPr(prhs[5]);
	double* initial_previous_FEM_node_positions = mxGetPr(prhs[6]);
	double* initial_node_positions = mxGetPr(prhs[7]);
	double* initial_time_nodes_created = mxGetPr(prhs[8]);
	
	plhs[0] = mxCreateCellMatrix(no_cells, 1);
	plhs[1] = mxCreateDoubleMatrix(array_sizes, width_cell_store, mxREAL);
	plhs[2] = mxCreateCellMatrix(no_cells, 1);
	plhs[3] = mxCreateDoubleMatrix(array_sizes, 1, mxREAL);
	plhs[4] = mxCreateDoubleMatrix(length_FEM_node_positions, 1, mxREAL);
	plhs[5] = mxCreateDoubleMatrix(no_FEM_elements, 3, mxREAL);
	plhs[6] = mxCreateDoubleMatrix(length_FEM_node_positions, 2, mxREAL);
	plhs[7] = mxCreateDoubleMatrix(array_sizes, 2, mxREAL);
	plhs[8] = mxCreateDoubleMatrix(array_sizes, 1, mxREAL);
	plhs[9] = mxCreateDoubleMatrix(1, 1, mxREAL);
	
	double* final_cell_store = mxGetPr(plhs[1]);
	double* final_cells_per_node = mxGetPr(plhs[3]);
	double* final_Dpp = mxGetPr(plhs[4]);
	double* final_FEM_elements = mxGetPr(plhs[5]);
	double* final_previous_FEM_node_positions = mxGetPr(plhs[6]);
	double* final_node_positions = mxGetPr(plhs[7]);
	double* final_time_nodes_created = mxGetPr(plhs[8]);
	double* no_join_nodes_this_iteration = mxGetPr(plhs[9]);
	
	*no_join_nodes_this_iteration = 0;
	
	// set output matrices equal to input matrices
	for(unsigned current_node=0;current_node<array_sizes;current_node++){
		final_cells_per_node[current_node] = initial_cells_per_node[current_node];
		final_time_nodes_created[current_node] = initial_time_nodes_created[current_node];
		for(unsigned dim=0;dim<2;dim++){
			final_node_positions[current_node+array_sizes*dim] = initial_node_positions[current_node+array_sizes*dim];
		}
		for(unsigned i=0;i<width_cell_store;i++){
			final_cell_store[current_node+i*array_sizes] = initial_cell_store[current_node+i*array_sizes];
		}
	}
	
	for(unsigned current_element=0;current_element<no_FEM_elements;current_element++){
		for(unsigned i=0;i<3;i++){
			final_FEM_elements[current_element+no_FEM_elements*i] =
					  initial_FEM_elements[current_element+no_FEM_elements*i];
		}
	}
	
	for(unsigned current_FEM_node=0;current_FEM_node<length_FEM_node_positions;current_FEM_node++){
		final_Dpp[current_FEM_node] = initial_Dpp[current_FEM_node];
		for(unsigned dim=0;dim<2;dim++){
			final_previous_FEM_node_positions[current_FEM_node+length_FEM_node_positions*dim] =
					  initial_previous_FEM_node_positions[current_FEM_node+length_FEM_node_positions*dim];
		}
	}
	
	// set output cells equal to input cells
	for(unsigned current_cell=0; current_cell<no_cells; current_cell++) {
		
		mxArray* mx_initial_cell_nodes = mxGetCell(prhs[2], current_cell);
		
		unsigned no_cell_nodes = mxGetN(mx_initial_cell_nodes);
		
		double* initial_cell_nodes = mxGetPr(mx_initial_cell_nodes);
		
		mxArray* mx_final_cell_nodes = mxCreateDoubleMatrix(1, no_cell_nodes, mxREAL);
		double* final_cell_nodes = mxGetPr(mx_final_cell_nodes);
		
		mxArray* mx_initial_cell_elements = mxGetCell(prhs[0], current_cell);
		double* initial_cell_elements = mxGetPr(mx_initial_cell_elements);
		
		mxArray* mx_final_cell_elements = mxCreateDoubleMatrix(1, no_cell_nodes, mxREAL);
		double* final_cell_elements = mxGetPr(mx_final_cell_elements);
		
		for(unsigned i=0; i<no_cell_nodes;i++){
			final_cell_nodes[i] = initial_cell_nodes[i];
			final_cell_elements[i] = initial_cell_elements[i];
		}
		
		mxSetCell(plhs[2], current_cell, mx_final_cell_nodes);
		mxSetCell(plhs[0], current_cell, mx_final_cell_elements);
		
	}
	
	bool join_logical;
	
	// loop over all cells
	for(unsigned current_cell_ci=0; current_cell_ci<no_cells; current_cell_ci++) {
		
		join_logical = false;
		
// 		printf("start of main loop \n");
		
		unsigned current_cell_mi = current_cell_ci+1;
		
		mxArray* mx_cell_nodes = mxGetCell(plhs[2], current_cell_ci);
		double* cell_nodes = mxGetPr(mx_cell_nodes);
		
		unsigned no_cell_nodes = mxGetN(mx_cell_nodes);
		
		// only proceed if there are more than 3 cell nodes
		if(no_cell_nodes > 3){
			
			// loop over the nodes of the current cell
			for(unsigned current_node_local=0; current_node_local<no_cell_nodes; current_node_local++) {
				
				double rand_number = rand()/((double)RAND_MAX);
				
				// only proceed with p(join_probability)
				if(rand_number < join_probability){
					
					// find current node and clockwise node in matlab and c indicies
					unsigned current_node_global_mi = (unsigned)cell_nodes[current_node_local];
					unsigned current_node_global_ci = current_node_global_mi-1;
					
					unsigned clockwise_node_local = (current_node_local+1)%no_cell_nodes;
					
					unsigned clockwise_node_global_mi = (unsigned)cell_nodes[clockwise_node_local];
					unsigned clockwise_node_global_ci = clockwise_node_global_mi - 1;
					
					// extract the positions of the current node and clockwise node from the node positions matrix
					double current_node_position[2], clockwise_node_position[2];
					
					for(unsigned dim=0;dim<2;dim++) {
						
						current_node_position[dim] = final_node_positions[current_node_global_ci + dim*array_sizes];
						clockwise_node_position[dim] = final_node_positions[clockwise_node_global_ci + dim*array_sizes];
					}
					
					// find the current edge length
					double current_edge_length = findStraightLineDistanceBetweenTwoNodes(current_node_position,
							  clockwise_node_position);
					
					// only proceed if edge length is less than threshold, and nodes have not been created very
					// recently
					if(current_edge_length < threshold_join_nodes &&
							  (time-final_time_nodes_created[current_node_global_ci])>protection_time &&
							  (time-final_time_nodes_created[clockwise_node_global_ci])>protection_time){
						
// 						printf("hello \n");
						
						// look for a cell that shares the edge - we need this for a T1 swap
						bool cell_with_same_edge_found = false;
						int cell_with_same_edge_mi = -1;
						
						unsigned counter_1 = 0;
						// loop over all cells containing current_node_global
						for(unsigned i=0;i<final_cells_per_node[current_node_global_ci];i++){
							
							unsigned temp_cell_1_mi = (unsigned)final_cell_store[current_node_global_ci + i*array_sizes];
							
							// if not current_cell, loop over all cells containing clockwise_node_global
							if(temp_cell_1_mi != current_cell_mi && !cell_with_same_edge_found){
								for(unsigned j=0;j<final_cells_per_node[clockwise_node_global_ci];j++){
									
									unsigned temp_cell_2_mi = (unsigned)final_cell_store[clockwise_node_global_ci + j*array_sizes];
									
									// if cell containing clockwise_node_global is also a cell containing current_node_global,
									// but not current_cell, then it is cell_with_same_edge;
									if(temp_cell_2_mi == temp_cell_1_mi){
										cell_with_same_edge_mi = temp_cell_1_mi;
										cell_with_same_edge_found = true;
										break;
									}
								}
							}
							
						}
						
						if(!cell_with_same_edge_found){
							
							join_logical = true;
							(*no_join_nodes_this_iteration)++;
							
// 							printf("doing a join \n");
							
							double new_node_position[2];
							for(unsigned dim=0;dim<2;dim++) {
								new_node_position[dim] = (current_node_position[dim] +
										  clockwise_node_position[dim])/2;
							}
							
							// find two unused nodes to put new nodes in
							unsigned new_node_ci = 0;
							while(final_cells_per_node[new_node_ci]>0){
								new_node_ci++;
							}
							unsigned new_node_mi = new_node_ci+1;
							
							assert(new_node_mi <= array_sizes);
							
							// store new node position
							for(unsigned dim=0;dim<2;dim++){
								final_node_positions[new_node_ci+dim*array_sizes] =
										  new_node_position[dim];
							}
							
							// set time new nodes created to current time
							final_time_nodes_created[new_node_ci] = time;
							
							// edit current cell nodes to contain new node instead of previous two nodes
							mxArray* mx_cell_nodes_edited = mxCreateDoubleMatrix(1, no_cell_nodes-1, mxREAL);
							double* cell_nodes_edited = mxGetPr(mx_cell_nodes_edited);
							
							int temp_counter = -1;
							for(unsigned temp_current_node_local=0;temp_current_node_local<no_cell_nodes;temp_current_node_local++){
								
								unsigned temp_current_node_global_mi = (unsigned)cell_nodes[temp_current_node_local];
								
								if(temp_current_node_global_mi==current_node_global_mi){
									temp_counter++;
									cell_nodes_edited[temp_counter]=new_node_mi;
								}
								else if(temp_current_node_global_mi==clockwise_node_global_mi){}
								else{
									temp_counter++;
									cell_nodes_edited[temp_counter]=temp_current_node_global_mi;
								}
							}
							mxSetCell(plhs[2], current_cell_ci, mx_cell_nodes_edited);
							
// 							printf("edited current cell \n");
							
							final_cells_per_node[new_node_ci] = 1;
							final_cell_store[new_node_ci] = current_cell_mi;
							
							if(final_cells_per_node[current_node_global_ci] > 1.1){
								
								for(unsigned i=0;i<final_cells_per_node[current_node_global_ci];i++){
									
									unsigned temp_cell_mi = (unsigned)final_cell_store[current_node_global_ci + i*array_sizes];
									
									if(temp_cell_mi!=current_cell_mi){
										
										unsigned temp_cell_ci = temp_cell_mi-1;
										
										mxArray* mx_cell_nodes_temp_cell = mxGetCell(plhs[2], temp_cell_ci);
										double* cell_nodes_temp_cell = mxGetPr(mx_cell_nodes_temp_cell);
										unsigned no_cell_nodes_temp_cell = mxGetN(mx_cell_nodes_temp_cell);
										
										mxArray* mx_cell_nodes_temp_cell_edited = mxCreateDoubleMatrix(1, no_cell_nodes_temp_cell, mxREAL);
										double* cell_nodes_temp_cell_edited = mxGetPr(mx_cell_nodes_temp_cell_edited);
										
										for(unsigned temp_current_node_local=0;temp_current_node_local<no_cell_nodes_temp_cell;temp_current_node_local++){
											
											unsigned temp_current_node_global_mi = (unsigned)cell_nodes_temp_cell[temp_current_node_local];
											
											if(temp_current_node_global_mi==current_node_global_mi){
												cell_nodes_temp_cell_edited[temp_current_node_local] = new_node_mi;
											}
											else{
												cell_nodes_temp_cell_edited[temp_current_node_local] = temp_current_node_global_mi;
											}
										}
										
										mxSetCell(plhs[2], temp_cell_ci, mx_cell_nodes_temp_cell_edited);
										
										final_cells_per_node[new_node_ci]++;
										unsigned matrix_index = (unsigned)(new_node_ci+array_sizes*(final_cells_per_node[new_node_ci]-1));
										final_cell_store[matrix_index] = temp_cell_mi;
									}
								}
// 								printf("edited cells with node 1 \n");
							}
							
							if(final_cells_per_node[clockwise_node_global_ci] > 1.1){
								
								for(unsigned i=0;i<final_cells_per_node[clockwise_node_global_ci];i++){
									
									unsigned temp_cell_mi = (unsigned)final_cell_store[clockwise_node_global_ci + i*array_sizes];
									
									if(temp_cell_mi!=current_cell_mi){
										
										unsigned temp_cell_ci = temp_cell_mi-1;
										
										// edit stretch cell 1 by adding in two new nodes in place of current node global
										mxArray* mx_cell_nodes_temp_cell = mxGetCell(plhs[2], temp_cell_ci);
										double* cell_nodes_temp_cell = mxGetPr(mx_cell_nodes_temp_cell);
										unsigned no_cell_nodes_temp_cell = mxGetN(mx_cell_nodes_temp_cell);
										
										mxArray* mx_cell_nodes_temp_cell_edited = mxCreateDoubleMatrix(1, no_cell_nodes_temp_cell, mxREAL);
										double* cell_nodes_temp_cell_edited = mxGetPr(mx_cell_nodes_temp_cell_edited);
										
										for(unsigned temp_current_node_local=0;temp_current_node_local<no_cell_nodes_temp_cell;temp_current_node_local++){
											
											unsigned temp_current_node_global_mi = (unsigned)cell_nodes_temp_cell[temp_current_node_local];
											
											if(temp_current_node_global_mi==clockwise_node_global_mi){
												cell_nodes_temp_cell_edited[temp_current_node_local] = new_node_mi;
											}
											else{
												cell_nodes_temp_cell_edited[temp_current_node_local] = temp_current_node_global_mi;
											}
										}
										
										mxSetCell(plhs[2], temp_cell_ci, mx_cell_nodes_temp_cell_edited);
										
										// add stretch cell 1 to cells_per_node and cell_store for new_node and new_node_2
										final_cells_per_node[new_node_ci]++;
										unsigned matrix_index = (unsigned)(new_node_ci+array_sizes*(final_cells_per_node[new_node_ci]-1));
										final_cell_store[matrix_index] = temp_cell_mi;
										
									}
								}
								printf("edited cells with node 2 \n");
								
							}
							
							// reset cells per node and cell store for current_node_global and clockwise_node_global.
							// they should no longer be part of any cells, unless something has gone horribly wrong.
							final_cells_per_node[current_node_global_ci] = 0;
							final_cells_per_node[clockwise_node_global_ci] = 0;
							
							for(unsigned i=0;i<width_cell_store;i++){
								final_cell_store[current_node_global_ci+i*array_sizes] = 0;
								final_cell_store[clockwise_node_global_ci+i*array_sizes] = 0;
							}
							
							for(unsigned dim=0;dim<2;dim++){
								final_node_positions[current_node_global_ci+dim*array_sizes] = 0;
								final_node_positions[clockwise_node_global_ci+dim*array_sizes] = 0;
							}
						}
					}
				}
				if(join_logical){break;}
			}
		}
		if(join_logical){break;}
	}
}
Esempio n. 13
0
static void mdlInitializeConditions(SimStruct *S)
{
  debugPrintf("'%s': mdlInitializeConditions\n", S->path);

  int i;

  rtsys = (RTsys*) ssGetUserData(S);

  if (rtsys->init_phase) {
    /* Failure during initialization */
    return;
  }
  
  for (i=0; i<rtsys->nbrOfInputs; i++) {
    rtsys->inputs[i] = *ssGetInputPortRealSignalPtrs(S,0)[i];
  }
  for (i=0; i<rtsys->nbrOfOutputs; i++) {
    rtsys->outputs[i] = 0.0;
  }
  
  for (i=0; i<rtsys->nbrOfTriggers; i++) {
    rtsys->oldtriggerinputs[i] = 0.0;
  }
  
  /* Now we can be sure that the network blocks have been initialized and that network */
  /* pointers have been written to workspace. Do the remaining network interface initialization */

  for (i=0; i<rtsys->nbrOfNetworks; i++) {

    rtsys->nwSnd[i] = 0.0;
    rtsys->oldnwSnd[i] = 0.0;
    rtsys->oldnetworkinputs[i] = 0.0;

    void *nwsysp;
    char nwsysvarname[MAXCHARS];
    NetworkInterface* nwi = &(rtsys->networkInterfaces[i]);

    // Find global variable containing network pointer
    snprintf(nwsysvarname, MAXCHARS, "_nwsys_%d", nwi->networkNbr);
    mxArray *var = (mxArray*)mexGetVariablePtr("global", nwsysvarname);
    if (var == NULL) {
      mexPrintf("??? Network %d not found!\n", nwi->networkNbr);
      ssSetErrorStatus(S, "");
	return;
    }
    nwsysp = (void *)(*((long *)mxGetPr(var))); // ugly conversion from long to pointer
    
    RTnetwork *tt_network = (RTnetwork*) nwsysp;
    if (tt_network->networkNbr == nwi->networkNbr) {
      nwi->nwsys = tt_network;
      // if ttSetNetworkParameter() was called from the init_function
      if (nwi->transmitpower != -1.0) {
	nwi->nwsys->nwnodes[nwi->nodeNbr]->transmitPower = 
	  nwi->transmitpower;
	debugPrintf("'%s': transmitpower is set to %.2f mW in node %d from the initfunction\n",
		    rtsys->blockName, nwi->nwsys->nwnodes[nwi->nodeNbr]->transmitPower*1000,
		    nwi->nodeNbr+1);
      }
      if (nwi->predelay != -1.0) {
	nwi->nwsys->nwnodes[nwi->nodeNbr]->predelay = 
	  nwi->predelay;
      }
      if (nwi->postdelay != -1.0) {
	nwi->nwsys->nwnodes[nwi->nodeNbr]->postdelay = 
	  nwi->postdelay;
      }
    }
  }
}
Esempio n. 14
0
static void mdlInitializeSizes(SimStruct *S)
{

  debugPrintf("'%s': mdlInitializeSizes\n", S->path);

  int i;
#ifdef KERNEL_MATLAB
  char initfun[MAXCHARS];
  static mxArray *lhs[1]; // warning: used multiple times
  static mxArray *rhs[3]; // warning: used multiple times
  mxArray *error_msg_array[1];
  char *error_msg;
  int nargin;
#endif

  ssSetNumSFcnParams(S, 7);  /* Number of expected parameters */
  if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
    TT_CALLBACK_ERROR(S, "Wrong number of parameters to S-function!");
    return; /* Parameter mismatch will be reported by Simulink */
  }
  
  rtsys = new RTsys;

  strncpy((char*)rtsys->blockName, ssGetBlockName(S), MAXCHARS);

#ifdef KERNEL_MATLAB
  rtsys->segArray = mxCreateScalarDouble(0.0);
  mexMakeArrayPersistent(rtsys->segArray);
#endif

  /* Assign various function pointers */
  rtsys->contextSwitchCode = contextSwitchCode;
  rtsys->timeCmp = timeCmp;
  rtsys->prioCmp = prioCmp;
  rtsys->default_arrival = default_arrival;
  rtsys->default_release = default_release;
  rtsys->default_start = default_start;
  rtsys->default_suspend = default_suspend;
  rtsys->default_resume = default_resume;
  rtsys->default_finish = default_finish;
  rtsys->default_runkernel = default_runkernel;
  rtsys->prioFP = prioFP;
  rtsys->prioEDF = prioEDF;
  rtsys->prioDM = prioDM;

  /* Create basic kernel data structures */
  rtsys->taskList = new List("TaskList", NULL);
  rtsys->handlerList = new List("HandlerList", NULL);
  rtsys->timerList = new List("TimerList", NULL);
  rtsys->monitorList = new List("MonitorList", NULL);
  rtsys->eventList = new List("EventList", NULL);
  rtsys->mailboxList = new List("MailboxList", NULL);
  rtsys->semaphoreList = new List("SemaphoreList", NULL);
  rtsys->logList = new List("LogList", NULL);
  rtsys->cbsList = new List("CBSList", NULL);

  /* Read number of inputs, outputs, and triggers from block mask */
  const mxArray *arg;
  arg = ssGetSFcnParam(S, 2);
  int m = mxGetM(arg);
  int n = mxGetN(arg);
  if (n != 2 || m != 1) {
    TT_CALLBACK_ERROR(S, "Illegal number of analog inputs/outputs!");
    return;
  }
  int ninputs = (int)mxGetPr(arg)[0];
  int noutputs = (int)mxGetPr(arg)[1];
  if (ninputs < 0 || noutputs < 0) {
    TT_CALLBACK_ERROR(S, "Illegal number of analog inputs/outputs!");
    return;
  }
  rtsys->nbrOfInputs = ninputs;
  rtsys->nbrOfOutputs = noutputs;
  if (ninputs > 0) {
    rtsys->inputs = new double[ninputs];
  }
  if (noutputs > 0) {
    rtsys->outputs = new double[noutputs];
  }

  arg = ssGetSFcnParam(S, 3);
  if (!mxIsDoubleScalar(arg)) {
    TT_CALLBACK_ERROR(S, "Illegal number of triggers!");
    return;
  }
  int ntriggers = (int)*mxGetPr(arg);
  if (ntriggers < 0) {
    TT_CALLBACK_ERROR(S, "Illegal number of triggers!");
    return;
  }
  rtsys->nbrOfTriggers = ntriggers;
  rtsys->triggers = new Trigger[ntriggers]; 
  
  arg = ssGetSFcnParam(S, 4);
  if (!mxIsDoubleScalar(arg)) {
    TT_CALLBACK_ERROR(S, "Illegal trigger type!");
    return;
  }
  int trigType = (int)*mxGetPr(arg);
  rtsys->trigType = trigType;
  
  /* Create network interfaces according to the block mask */
  arg = ssGetSFcnParam(S, 5);
  m = mxGetM(arg);  // number of rows = number of network interfaces
  n = mxGetN(arg);  // number of cols should be 1 or 2
  int networkNbr;
  int nodeNbr;
  char nwname[MAXCHARS];
  if ((n == 1 && m != 1) || n > 2) {
    TT_CALLBACK_ERROR(S, "Illegal network or node numbers!");
    return;
  }
  if (m > 0) {
    rtsys->networkInterfaces = new NetworkInterface[m]; 
    rtsys->nbrOfNetworks = m;
    for (i=0; i<m; i++) {
      if (n == 1) {
	networkNbr = 1;
	nodeNbr = (int)mxGetPr(arg)[i];
      } else {
	networkNbr = (int)mxGetPr(arg)[i];
	nodeNbr = (int)mxGetPr(arg)[i+m];
      }
      NetworkInterface *nwi = &(rtsys->networkInterfaces[i]);
      nwi->networkNbr = networkNbr;
      nwi->nodeNbr = nodeNbr-1;
      nwi->portNbr = i;
      sprintf(nwname, "network_%d", networkNbr);
    }
  } 

  /* Read clock offset and drift parameters from the block mask */
  arg = ssGetSFcnParam(S, 6);

  if (!mxIsEmpty(arg)) {
    if (mxGetM(arg) == 1 && mxGetN(arg) == 2) {
      rtsys->clockOffset = mxGetPr(arg)[0];
      rtsys->clockDrift = mxGetPr(arg)[1] + 1.0;
    } else {
      TT_CALLBACK_ERROR(S, "Illegal offset/drift parameters!");
      return;
    }
  }

#ifdef KERNEL_MATLAB
  mexSetTrapFlag(1); // return control to the MEX file after an error

  /* Write rtsys pointer to global workspace */

  if (mexGetVariablePtr("global", "_rtsys") == 0) {

    // pointer variable does not exist - let's create one
    debugPrintf("Creating global _rtsys variable\n");
    mxArray* var = mxCreateScalarDouble(0.0);
    mexMakeArrayPersistent(var);
    mexPutVariable("global", "_rtsys", var);

  }

  rtsys->rtsysptr = (mxArray*)mexGetVariablePtr("global", "_rtsys");

  *((long *)mxGetPr(rtsys->rtsysptr)) = (long)rtsys;

  /* Evaluating user-defined init function (MATLAB) */
  mxGetString(ssGetSFcnParam(S, 0), initfun, MAXCHARS);
  rhs[0] = mxCreateString(initfun);
  if (mexCallMATLAB(1, lhs, 1, rhs, "nargin") != 0) {
    goto error;
  }
  nargin = (int)*mxGetPr(lhs[0]);
  if (nargin == 0) {
    if (mexCallMATLAB(0, NULL, 0, NULL, initfun) != 0) {
      goto error;
    } else {
      rtsys->init_phase = false;
    }
  } else if (nargin == 1) {
    rhs[0] = (mxArray *)ssGetSFcnParam(S, 1);
    if (mexCallMATLAB(0, NULL, 1, rhs, initfun) != 0) {
      goto error;
    } else {
      rtsys->init_phase = false;
    }
  } else {
    TT_CALLBACK_ERROR(S, "Init function takes wrong number (> 1) of arguments!");
    return;
  }

  if (rtsys->error) {
  error:
    mexCallMATLAB(1 ,error_msg_array, 0, NULL, "lasterr"); 
    error_msg = mxArrayToString(error_msg_array[0]);
    snprintf(errbuf, MAXERRBUF, "Error in init function '%s'\n%s", initfun, error_msg);
    mxFree(error_msg);
    TT_CALLBACK_ERROR(S, errbuf);
    return;
  }
  
#else
  /* Save pointer to init args */
  mxArray *initArg = (mxArray *)ssGetSFcnParam(S, 1);
  rtsys->initArg = initArg;
  /* Evaluating user-defined init function (C++) */
  init();
  if (rtsys->error) {
    TT_RUNKERNEL_ERROR(errbuf);
    mexPrintf("??? Error in init() function\n%s\n\n", errbuf);
    mexPrintf("In block ==> '%s'\nSimulation aborted!\n", ssGetBlockName(S));
    ssSetErrorStatus(S, "");
    return;
  }

  rtsys->init_phase = false;
#endif
  
  if (!rtsys->initialized) {
    TT_CALLBACK_ERROR(S, "ttInitKernel was not called in init function");
    return;
  }
  if (!ssSetNumInputPorts(S, 4)) return;
  ssSetInputPortDirectFeedThrough(S, 0, 0);
  ssSetInputPortDirectFeedThrough(S, 1, 0);
  ssSetInputPortDirectFeedThrough(S, 2, 0);
  ssSetInputPortDirectFeedThrough(S, 3, 0);
  if (!ssSetNumOutputPorts(S, 4)) return;

  /* Input Ports */

  if (rtsys->nbrOfInputs > 0) 
    ssSetInputPortWidth(S, 0, rtsys->nbrOfInputs);
  else
    ssSetInputPortWidth(S, 0, 1);
  
  if (rtsys->nbrOfTriggers > 0) 
    ssSetInputPortWidth(S, 1, rtsys->nbrOfTriggers);
  else
    ssSetInputPortWidth(S, 1, 1);

  if (rtsys->nbrOfNetworks > 0) {
    ssSetInputPortWidth(S, 2, rtsys->nbrOfNetworks); /* Network receive */
  }
  else
    ssSetInputPortWidth(S, 2, 1);

  ssSetInputPortWidth(S, 3, 1); //battery

  /* Output Ports */

  if (rtsys->nbrOfOutputs > 0) 
    ssSetOutputPortWidth(S, 0, rtsys->nbrOfOutputs);
  else
    ssSetOutputPortWidth(S, 0, 1);

  if (rtsys->nbrOfNetworks > 0) 
    ssSetOutputPortWidth(S, 1, (rtsys->nbrOfNetworks)); /* Network send */
  else
    ssSetOutputPortWidth(S, 1, 1);

  if (rtsys->nbrOfSchedTasks > 0) 
    ssSetOutputPortWidth(S, 2, rtsys->nbrOfSchedTasks * rtsys->nbrOfCPUs);
  else
    ssSetOutputPortWidth(S, 2, 1);

  ssSetOutputPortWidth(S, 3, 1); //Energy consumption

  ssSetNumContStates(S, 0);
  ssSetNumDiscStates(S, 0);
  
  ssSetNumSampleTimes(S, 1);
    
  ssSetNumRWork(S, 0);
  ssSetNumIWork(S, 0);
  ssSetNumPWork(S, 0); 
  ssSetNumModes(S, 0);
  ssSetNumNonsampledZCs(S, 1);

  ssSetUserData(S, rtsys);
  
  ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE | SS_OPTION_CALL_TERMINATE_ON_EXIT); 

}