modelica_string enum_to_modelica_string(modelica_integer nr, const char *e[],modelica_integer minLen, modelica_boolean leftJustified) { size_t sz = snprintf(NULL, 0, leftJustified ? "%-*s" : "%*s", (int) minLen, e[nr-1]); void *res = alloc_modelica_string(sz); sprintf(MMC_STRINGDATA(res), leftJustified ? "%-*s" : "%*s", (int) minLen, e[nr-1]); return res; }
modelica_string modelica_boolean_to_modelica_string(modelica_boolean b, modelica_integer minLen, modelica_boolean leftJustified) { size_t sz = snprintf(NULL, 0, leftJustified ? "%-*s" : "%*s", (int) minLen, b ? "true" : "false"); void *res = alloc_modelica_string(sz); sprintf(MMC_STRINGDATA(res), leftJustified ? "%-*s" : "%*s", (int) minLen, b ? "true" : "false"); return res; }
modelica_string modelica_real_to_modelica_string(modelica_real r, modelica_integer signDigits, modelica_integer minLen, modelica_boolean leftJustified) { size_t sz = snprintf(NULL, 0, leftJustified ? "%-*.*g" : "%*.*g", (int) minLen, (int) signDigits, r); void *res = alloc_modelica_string(sz); sprintf(MMC_STRINGDATA(res), leftJustified ? "%-*.*g" : "%*.*g", (int) minLen, (int) signDigits, r); return res; }
modelica_string modelica_integer_to_modelica_string(modelica_integer i, modelica_integer minLen, modelica_boolean leftJustified) { size_t sz = snprintf(NULL, 0, leftJustified ? "%-*ld" : "%*ld", (int) minLen, i); void *res = alloc_modelica_string(sz); sprintf(MMC_STRINGDATA(res), leftJustified ? "%-*ld" : "%*ld", (int) minLen, i); return res; }
metamodelica_string stringAppendList(modelica_metatype lst) { /* fprintf(stderr, "stringAppendList(%s)\n", anyString(lst)); */ modelica_integer lstLen = 0, len = 0; unsigned nbytes = 0, header = 0, nwords = 0; modelica_metatype car = NULL, lstHead = NULL, lstTmp = NULL; char *tmp = NULL; struct mmc_string *res = NULL; void *p = NULL; lstLen = 0; nbytes = 0; lstHead = lst; lstTmp = lst; while (!listEmpty(lstTmp)) { MMC_CHECK_STRING(MMC_CAR(lstTmp)); nbytes += MMC_STRLEN(MMC_CAR(lstTmp)); /* fprintf(stderr, "stringAppendList: Has success reading input %d: %s\n", lstLen, MMC_STRINGDATA(MMC_CAR(lst))); */ lstTmp = MMC_CDR(lstTmp); lstLen++; } if (nbytes == 0) return mmc_emptystring; if (lstLen == 1) return MMC_CAR(lstHead); header = MMC_STRINGHDR(nbytes); nwords = MMC_HDRSLOTS(header) + 1; res = (struct mmc_string *) mmc_alloc_words_atomic(nwords); res->header = header; tmp = (char*) res->data; nbytes = 0; lstTmp = lstHead; while (!listEmpty(lstTmp)) { car = MMC_CAR(lstTmp); len = MMC_STRLEN(car); /* fprintf(stderr, "stringAppendList: %s %d %d\n", MMC_STRINGDATA(car), len, strlen(MMC_STRINGDATA(car))); */ /* Might be useful to check this when debugging. String literals are often done wrong :) */ MMC_DEBUG_ASSERT(len == strlen(MMC_STRINGDATA(car))); memcpy(tmp+nbytes,MMC_STRINGDATA(car),len); nbytes += len; lstTmp = MMC_CDR(lstTmp); } tmp[nbytes] = '\0'; /* fprintf(stderr, "stringAppendList(%s)=>%s\n", anyString(lstHead), anyString(MMC_TAGPTR(res))); */ p = MMC_TAGPTR(res); MMC_CHECK_STRING(p); return p; }
/* adrpo: see the comment above about djb2 hash */ modelica_integer stringHashDjb2(metamodelica_string_const s) { const char* str = MMC_STRINGDATA(s); long res = djb2_hash((const unsigned char*)str); res = labs(res); /* fprintf(stderr, "stringHashDjb2 %s-> %ld %ld %ld\n", str, res, mmc_mk_icon(res), mmc_unbox_integer(mmc_mk_icon(res))); */ return res; }
modelica_integer nobox_stringCharInt(threadData_t *threadData,metamodelica_string chr) { unsigned char c; if (MMC_STRLEN(chr) != 1) MMC_THROW_INTERNAL(); MMC_CHECK_STRING(chr); return (unsigned char) MMC_STRINGDATA(chr)[0]; }
modelica_metatype boxptr_stringGetStringChar(threadData_t *threadData,metamodelica_string str, modelica_metatype iix) { modelica_metatype res; int ix = MMC_UNTAGFIXNUM(iix); MMC_CHECK_STRING(str); if (ix < 1 || ix > (long) MMC_STRLEN(str)) MMC_THROW_INTERNAL(); return mmc_strings_len1[(size_t)MMC_STRINGDATA(str)[ix-1]]; }
/* adrpo: really bad hash :) */ modelica_integer stringHash(metamodelica_string_const s) { const char* str = MMC_STRINGDATA(s); long res = 0, i=0; while (0 != (str[i])) { res += str[i]; i++; } return res; }
/* adrpo: see the comment above about djb2 hash */ modelica_integer stringHashDjb2Mod(metamodelica_string_const s, modelica_integer mod) { const char* str = MMC_STRINGDATA(s); long res; if (mod == 0) { MMC_THROW(); } res = djb2_hash((const unsigned char*)str) % (unsigned int) mod; res = labs(res); /* fprintf(stderr, "stringHashDjb2Mod %s %ld-> %ld %ld %ld\n", str, mod, res, mmc_mk_icon(res), mmc_unbox_integer(mmc_mk_icon(res))); */ return res; }
extern void Error_addSourceMessage(threadData_t *threadData,int _id, void *msg_type, void *severity, int _sline, int _scol, int _eline, int _ecol, int _read_only, const char* _filename, const char* _msg, void* tokenlst) { ErrorMessage::TokenList tokens; while(MMC_GETHDR(tokenlst) != MMC_NILHDR) { tokens.push_back(string(MMC_STRINGDATA(MMC_CAR(tokenlst)))); tokenlst=MMC_CDR(tokenlst); } add_source_message(threadData,_id, (ErrorType) (MMC_HDRCTOR(MMC_GETHDR(msg_type))-Error__SYNTAX_3dBOX0), (ErrorLevel) (MMC_HDRCTOR(MMC_GETHDR(severity))-Error__INTERNAL_3dBOX0), _msg,tokens,_sline,_scol,_eline,_ecol,_read_only,_filename); }
modelica_real nobox_stringReal(threadData_t *threadData,metamodelica_string s) { modelica_real res; char *endptr,*str=MMC_STRINGDATA(s); MMC_CHECK_STRING(s); errno = 0; res = strtod(str,&endptr); if (errno != 0 || str == endptr) MMC_THROW_INTERNAL(); if (*endptr != '\0') MMC_THROW_INTERNAL(); return res; }
extern void Error_addMessage(threadData_t *threadData,int errorID, void *msg_type, void *severity, const char* message, modelica_metatype tokenlst) { ErrorMessage::TokenList tokens; while (MMC_GETHDR(tokenlst) != MMC_NILHDR) { const char* token = MMC_STRINGDATA(MMC_CAR(tokenlst)); tokens.push_back(string(token)); tokenlst=MMC_CDR(tokenlst); } add_source_message(threadData,errorID, (ErrorType) (MMC_HDRCTOR(MMC_GETHDR(msg_type))-Error__SYNTAX_3dBOX0), (ErrorLevel) (MMC_HDRCTOR(MMC_GETHDR(severity))-Error__INTERNAL_3dBOX0), message,tokens,0,0,0,0,0,""); }
void print_string_array(const string_array_t *source) { _index_t i; modelica_string *data; assert(base_array_ok(source)); data = (modelica_string *) source->data; if(source->ndims == 1) { for(i = 1; i < source->dim_size[0]; ++i) { printf("%s, ", MMC_STRINGDATA(*data)); ++data; } if(0 < source->dim_size[0]) { printf("%s", MMC_STRINGDATA(*data)); } } else if(source->ndims > 1) { size_t k, n; _index_t j; n = base_array_nr_of_elements(*source) / (source->dim_size[0] * source->dim_size[1]); for(k = 0; k < n; ++k) { for(i = 0; i < source->dim_size[1]; ++i) { for(j = 0; j < source->dim_size[0]; ++j) { printf("%s, ", MMC_STRINGDATA(*data)); ++data; } if(0 < source->dim_size[0]) { printf("%s", MMC_STRINGDATA(*data)); } printf("\n"); } if((k + 1) < n) { printf("\n ================= \n"); } } } }
void Error_addMessage(int errorID, void *msg_type, void *severity, const char* message, modelica_metatype tokenlst) { ErrorMessage::TokenList tokens; if (error_on) { while(MMC_GETHDR(tokenlst) != MMC_NILHDR) { const char* token = MMC_STRINGDATA(MMC_CAR(tokenlst)); tokens.push_back(string(token)); tokenlst=MMC_CDR(tokenlst); } add_message(errorID, (ErrorType) (MMC_HDRCTOR(MMC_GETHDR(msg_type))-Error__SYNTAX_3dBOX0), (ErrorLevel) (MMC_HDRCTOR(MMC_GETHDR(severity))-Error__ERROR_3dBOX0), message,tokens); } }
/* Convert a modelica_real to a modelica_string, used in String(real, format="xxx") */ modelica_string modelica_real_to_modelica_string_format(modelica_real r,modelica_string format) { void *res; size_t sz; void *c_fmt = modelica_string_format_to_c_string_format(format); switch (MMC_STRINGDATA(c_fmt)[MMC_STRLEN(c_fmt)-1]) { case 'f': case 'e': case 'E': case 'g': case 'G': /* double */ sz = snprintf(NULL, 0, MMC_STRINGDATA(c_fmt), (double) r); res = alloc_modelica_string(sz); sprintf(MMC_STRINGDATA(res), MMC_STRINGDATA(c_fmt), (double) r); break; default: /* integer values, etc */ omc_assert(NULL, dummyFILE_INFO, "Invalid conversion specifier for Real: %c", MMC_STRINGDATA(c_fmt)[MMC_STRLEN(c_fmt)-1]); } return res; }
modelica_integer nobox_stringInt(threadData_t *threadData,metamodelica_string s) { long res; char *endptr,*str=MMC_STRINGDATA(s); MMC_CHECK_STRING(s); errno = 0; res = strtol(str,&endptr,10); if (errno != 0 || str == endptr) MMC_THROW_INTERNAL(); if (*endptr != '\0') MMC_THROW_INTERNAL(); if (res > INT_MAX || res < INT_MIN) MMC_THROW_INTERNAL(); return res; }
metamodelica_string stringListStringChar(metamodelica_string s) { const char *str = MMC_STRINGDATA(s); char chr[2] = {'\0', '\0'}; modelica_metatype res = NULL; int i = 0; MMC_CHECK_STRING(s); res = mmc_mk_nil(); for (i=MMC_STRLEN(s)-1; i>=0; i--) { chr[0] = str[i]; res = mmc_mk_cons(mmc_mk_scon(chr), res); } return res; }
void print_string_matrix(const string_array_t *source) { if(source->ndims == 2) { _index_t i,j; modelica_string value; printf("%d X %d matrix:\n", (int) source->dim_size[0], (int) source->dim_size[1]); for(i = 0; i < source->dim_size[0]; ++i) { for(j = 0; j < source->dim_size[1]; ++j) { value = string_get(*source, (i * source->dim_size[1]) + j); printf("%s\t", MMC_STRINGDATA(value)); } printf("\n"); } } else { printf("array with %d dimensions\n", source->ndims); } }
modelica_metatype boxptr_substring(threadData_t *threadData, metamodelica_string_const str, modelica_metatype boxstart, modelica_metatype boxstop) { unsigned header = 0, nwords; long start = MMC_UNTAGFIXNUM(boxstart) - 1; long stop = MMC_UNTAGFIXNUM(boxstop) - 1; long totalLen = MMC_STRLEN(str), len = stop-start+1; struct mmc_string *res; char *tmp; modelica_metatype p; /* Bad indexes */ if (start < 0 || start >= totalLen || stop < start || stop >= totalLen) { MMC_THROW_INTERNAL(); } header = MMC_STRINGHDR(len); nwords = MMC_HDRSLOTS(header) + 1; res = (struct mmc_string *) mmc_alloc_words_atomic(nwords); res->header = header; tmp = (char*) res->data; memcpy(tmp, MMC_STRINGDATA(str) + start, len); tmp[len] = '\0'; p = MMC_TAGPTR(res); MMC_CHECK_STRING(p); return p; }
static void* SimulationResultsImpl__readDataset(const char *filename, void *vars, int dimsize, int suggestReadAllVars, SimulationResult_Globals* simresglob, int runningTestsuite) { const char *msg[2] = {"",""}; void *res,*col; char *var; double *vals; int i; if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(filename,simresglob)) { return NULL; } res = mmc_mk_nil(); switch (simresglob->curFormat) { case MATLAB4: { ModelicaMatVariable_t *mat_var; if (dimsize == 0) { dimsize = simresglob->matReader.nrows; } else if (simresglob->matReader.nrows != dimsize) { fprintf(stderr, "dimsize: %d, rows %d\n", dimsize, simresglob->matReader.nrows); c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("readDataset(...): Expected and actual dimension sizes do not match."), NULL, 0); return NULL; } if (suggestReadAllVars) { omc_matlab4_read_all_vals(&simresglob->matReader); } while (MMC_NILHDR != MMC_GETHDR(vars)) { var = MMC_STRINGDATA(MMC_CAR(vars)); vars = MMC_CDR(vars); mat_var = omc_matlab4_find_var(&simresglob->matReader,var); if (mat_var == NULL) { msg[0] = runningTestsuite ? SystemImpl__basename(filename) : filename; msg[1] = var; c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s."), msg, 2); return NULL; } else if (mat_var->isParam) { col=mmc_mk_nil(); for (i=0;i<dimsize;i++) col=mmc_mk_cons(mmc_mk_rcon((mat_var->index<0)?-simresglob->matReader.params[abs(mat_var->index)-1]:simresglob->matReader.params[abs(mat_var->index)-1]),col); res = mmc_mk_cons(col,res); } else { vals = omc_matlab4_read_vals(&simresglob->matReader,mat_var->index); col=mmc_mk_nil(); for (i=0;i<dimsize;i++) col=mmc_mk_cons(mmc_mk_rcon(vals[i]),col); res = mmc_mk_cons(col,res); } } return res; } case PLT: { return read_ptolemy_dataset(filename,vars,dimsize); } case CSV: { while (MMC_NILHDR != MMC_GETHDR(vars)) { var = MMC_STRINGDATA(MMC_CAR(vars)); vars = MMC_CDR(vars); vals = simresglob->csvReader ? read_csv_dataset(simresglob->csvReader,var) : NULL; if (vals == NULL) { msg[0] = runningTestsuite ? SystemImpl__basename(filename) : filename; msg[1] = var; c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s."), msg, 2); return NULL; } else { col=mmc_mk_nil(); for (i=0;i<dimsize;i++) { col=mmc_mk_cons(mmc_mk_rcon(vals[i]),col); } res = mmc_mk_cons(col,res); } } return res; } default: msg[0] = PlotFormatStr[simresglob->curFormat]; c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("readDataSet() not implemented for plot format: %s\n"), msg, 1); return NULL; } }
modelica_integer nobox_stringGet(threadData_t *threadData,metamodelica_string str, modelica_integer ix) { if (ix < 1 || ix > (long) MMC_STRLEN(str)) MMC_THROW_INTERNAL(); return ((unsigned char*)MMC_STRINGDATA(str))[ix-1]; }
modelica_string modelica_string_format_to_c_string_format(modelica_string format) { char buf[FMT_BUFSIZE]; const char *str = MMC_STRINGDATA(format), *tmp = str; int cont=1, n=0; buf[n++] = '%'; while (cont) { /* Parse flag characters */ switch (*tmp) { /* Extended flags? ',I */ case '#': case '0': case '-': case ' ': case '+': buf[n] = *(tmp++); checkBufSize(str, n++); break; default: cont = 0; } } // width: [1-9][0-9]* if ((*tmp >= '1') || (*tmp <= '9')) { while (*tmp >= '0' && *tmp <= '9') { buf[n] = *(tmp++); checkBufSize(str, n++); } } // precision: .[0-9]* if (*tmp == '.') { buf[n] = *(tmp++); checkBufSize(str, n++); while (*tmp >= '0' && *tmp <= '9') { buf[n] = *(tmp++); checkBufSize(str, n++); } } switch (*tmp) { case 'f': case 'e': case 'E': case 'g': case 'G': /* double */ case 'c': /* int */ buf[n] = *(tmp++); checkBufSize(str, n++); break; case 'd': case 'i': /* int */ case 'o': case 'x': case 'X': case 'u': /* uint */ buf[n] = 'l'; /* we use long in OpenModelica */ checkBufSize(str, n++); buf[n] = *(tmp++); checkBufSize(str, n++); break; case 'h': case 'l': case 'L': case 'q': case 'j': case 'z': case 't': omc_assert(NULL, dummyFILE_INFO, "Length modifiers are not legal in Modelica format strings: %s", str); break; default: omc_assert(NULL, dummyFILE_INFO, "Could not parse format string: invalid conversion specifier: %c in %s", *tmp, str); } if (*tmp) { omc_assert(NULL, dummyFILE_INFO, "Could not parse format string: trailing data after the format directive", *tmp, str); } buf[n] = '\0'; return mmc_mk_scon(buf); }
/* adrpo: see the comment above about sdbm hash */ modelica_integer stringHashSdbm(metamodelica_string_const s) { const char* str = MMC_STRINGDATA(s); long res = sdbm_hash((const unsigned char*)str); return res; }
void boxptr_print(threadData_t *threadData,modelica_metatype str) { fputs(MMC_STRINGDATA(str), stdout); }
/*! performQSSSimulation(DATA* data, SOLVER_INFO* solverInfo) * * \param [ref] [data] * \param [ref] [solverInfo] * * This function performs the simulation controlled by solverInfo. */ modelica_integer prefixedName_performQSSSimulation(DATA* data, SOLVER_INFO* solverInfo) { TRACE_PUSH SIMULATION_INFO *simInfo = &(data->simulationInfo); MODEL_DATA *mData = &(data->modelData); uinteger currStepNo = 0; modelica_integer retValIntegrator = 0; modelica_integer retValue = 0; uinteger ind = 0; solverInfo->currentTime = simInfo->startTime; warningStreamPrint(LOG_STDOUT, 0, "This QSS method is under development and should not be used yet."); if (data->callback->initialAnalyticJacobianA(data)) { infoStreamPrint(LOG_STDOUT, 0, "Jacobian or sparse pattern is not generated or failed to initialize."); return UNKNOWN; } printSparseStructure(data, LOG_SOLVER); /* *********************************************************************************** */ /* Initialization */ uinteger i = 0; /* loop var */ SIMULATION_DATA *sData = (SIMULATION_DATA*)data->localData[0]; modelica_real* state = sData->realVars; modelica_real* stateDer = sData->realVars + data->modelData.nStates; const SPARSE_PATTERN* pattern = &(data->simulationInfo.analyticJacobians[data->callback->INDEX_JAC_A].sparsePattern); const uinteger ROWS = data->simulationInfo.analyticJacobians[data->callback->INDEX_JAC_A].sizeRows; const uinteger STATES = data->modelData.nStates; uinteger numDer = 0; /* number of derivatives influenced by state k */ modelica_boolean fail = 0; modelica_real* qik = NULL; /* Approximation of states */ modelica_real* xik = NULL; /* states */ modelica_real* derXik = NULL; /* Derivative of states */ modelica_real* tq = NULL; /* Time of approximation, because not all approximations are calculated at a specific time, each approx. has its own timestamp */ modelica_real* tx = NULL; /* Time of the states, because not all states are calculated at a specific time, each state has its own timestamp */ modelica_real* tqp = NULL; /* Time of the next change in state */ modelica_real* nQh = NULL; /* next value of the state */ modelica_real* dQ = NULL; /* change in quantity of every state, default = nominal*10^-4 */ /* allocate memory*/ qik = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (qik == NULL) ? 1 : ( 0 | fail); xik = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (xik == NULL) ? 1 : ( 0 | fail); derXik = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (derXik == NULL) ? 1 : ( 0 | fail); tq = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (tq == NULL) ? 1 : ( 0 | fail); tx = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (tx == NULL) ? 1 : ( 0 | fail); tqp = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (tqp == NULL) ? 1 : ( 0 | fail); nQh = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (nQh == NULL) ? 1 : ( 0 | fail); dQ = (modelica_real*)calloc(STATES, sizeof(modelica_real)); fail = (dQ == NULL) ? 1 : ( 0 | fail); if (fail) return OO_MEMORY; /* end - allocate memory */ /* further initialization of local variables */ modelica_real diffQ = 0.0, dTnextQ = 0.0, nextQ = 0.0; for (i = 0; i < STATES; i++) { dQ[i] = 0.0001 * data->modelData.realVarsData[i].attribute.nominal; tx[i] = tq[i] = simInfo->startTime; qik[i] = state[i]; xik[i] = state[i]; derXik[i] = stateDer[i]; retValue = deltaQ(data, dQ[i], i, &dTnextQ, &nextQ, &diffQ); if (OK != retValue) return retValue; tqp[i] = tq[i] + dTnextQ; nQh[i] = nextQ; } /* Transform the sparsity pattern into a data structure for an index based access. */ modelica_integer* der = (modelica_integer*)calloc(ROWS, sizeof(modelica_integer)); if (NULL==der) return OO_MEMORY; for (i = 0; i < ROWS; i++) der[i] = -1; /* how many states are involved in each derivative */ /* **** This is needed if we have QSS2 or higher **** */ /* uinteger* numStatesInDer = calloc(ROWS,sizeof(uinteger)); if (NULL==numStatesInDer) return OO_MEMORY; */ /* * dx1/dt = x2 * dx2/dt = x1 + x2 * lead to * StatesInDer[0]-{ 2 } * StatesInDer[1]-{ 1, 2 } */ /* uinteger** StatesInDer = calloc(ROWS,sizeof(uinteger*)); if (NULL==StatesInDer) return OO_MEMORY; */ /* count number of states in each derivative*/ /* for (i = 0; i < pattern->leadindex[ROWS-1]; i++) numStatesInDer[ pattern->index[i] ]++; */ /* collect memory for all stateindices */ /* for (i = 0; i < ROWS; i++) { *(StatesInDer + i) = calloc(numStatesInDer[i], sizeof(uinteger)); if (NULL==*(StatesInDer + i)) return OO_MEMORY; } retValue = getStatesInDer(pattern->index, pattern->leadindex, ROWS, STATES, StatesInDer); if (OK != retValue) return retValue; */ /* retValue = getDerWithStateK(pattern->index, pattern->leadindex, der, &numDer, 0); if (OK != retValue) return retValue; */ /* End of transformation */ #ifdef D FILE* fid=NULL; fid = fopen("log_qss.txt","w"); #endif /* *********************************************************************************** */ /***** Start main simulation loop *****/ while(solverInfo->currentTime < simInfo->stopTime) { modelica_integer success = 0; threadData->currentErrorStage = ERROR_SIMULATION; omc_alloc_interface.collect_a_little(); #if !defined(OMC_EMCC) /* try */ MMC_TRY_INTERNAL(simulationJumpBuffer) { #endif #ifdef USE_DEBUG_TRACE if (useStream[LOG_TRACE]) printf("TRACE: push loop step=%u, time=%.12g\n", currStepNo, solverInfo->currentTime); #endif #ifdef D fprintf(fid,"t = %.8f\n",solverInfo->currentTime); fprintf(fid,"%16s\t%16s\t%16s\t%16s\t%16s\t%16s\n","tx","x","dx","tq","q","tqp"); for (i = 0; i < STATES; i++) { fprintf(fid,"%16.8f\t%16.8f\t%16.8f\t%16.8f\t%16.8f\t%16.8f\n",tx[i],xik[i],derXik[i],tq[i],qik[i],tqp[i]); } #endif currStepNo++; ind = minStep(tqp, STATES); if (isnan(tqp[ind])) { #ifdef D fprintf(fid,"Exit caused by #QNAN!\tind=%d",ind); #endif return ISNAN; } if (isinf(tqp[ind])) { /* If all derivatives are zero, the states stay constant and only the * time propagates till stop->time. */ warningStreamPrint(LOG_STDOUT, 0, "All derivatives are zero at time %f!.\n", sData->timeValue); solverInfo->currentTime = simInfo->stopTime; sData->timeValue = solverInfo->currentTime; continue; } qik[ind] = nQh[ind]; xik[ind] = qik[ind]; state[ind] = qik[ind]; tx[ind] = tqp[ind]; tq[ind] = tqp[ind]; solverInfo->currentTime = tqp[ind]; #ifdef D fprintf(fid,"Index: %d\n\n",ind); #endif /* the state[ind] will change again in dTnextQ*/ retValue = deltaQ(data, dQ[ind], ind, &dTnextQ, &nextQ, &diffQ); if (OK != retValue) return retValue; tqp[ind] = tq[ind] + dTnextQ; nQh[ind] = nextQ; if (0 != strcmp("ia", MMC_STRINGDATA(data->simulationInfo.outputFormat))) { communicateStatus("Running", (solverInfo->currentTime-simInfo->startTime)/(simInfo->stopTime-simInfo->startTime)); } /* get the derivatives depending on state[ind] */ for (i = 0; i < ROWS; i++) der[i] = -1; retValue = getDerWithStateK(pattern->index, pattern->leadindex, der, &numDer, ind); uinteger k = 0, j = 0; for (k = 0; k < numDer; k++) { j = der[k]; if (j != ind) { xik[j] = xik[j] + derXik[j] * (solverInfo->currentTime - tx[j]); state[j] = xik[j]; tx[j] = solverInfo->currentTime; } } /* * Recalculate all equations which are affected by state[ind]. * Unfortunately all equations will be calculated up to now. And we need to evaluate * the equations as f(t,q) and not f(t,x). So all states were saved onto a local stack * and overwritten by q. After evaluating the equations the states are written back. */ for (i = 0; i < STATES; i++) { xik[i] = state[i]; /* save current state */ state[i] = qik[i]; /* overwrite current state for dx/dt = f(t,q) */ } /* update continous system */ sData->timeValue = solverInfo->currentTime; externalInputUpdate(data); data->callback->input_function(data); data->callback->functionODE(data); data->callback->functionAlgebraics(data); data->callback->output_function(data); data->callback->function_storeDelayed(data); for (i = 0; i < STATES; i++) { state[i] = xik[i]; /* restore current state */ } /* * Get derivatives affected by state[ind] and write back ALL derivatives. After that we have * states and derivatives for different times tx. */ for (k = 0; k < numDer; k++) { j = der[k]; derXik[j] = stateDer[j]; } derXik[ind] = stateDer[ind]; /* not in every case part of the above derivatives */ for (i = 0; i < STATES; i++) { stateDer[i] = derXik[i]; /* write back all derivatives */ } /* recalculate the time of next change only for the affected states */ for (k = 0; k < numDer; k++) { j = der[k]; retValue = deltaQ(data, dQ[j], j, &dTnextQ, &nextQ, &diffQ); if (OK != retValue) return retValue; tqp[j] = solverInfo->currentTime + dTnextQ; nQh[j] = nextQ; } /*sData->timeValue = solverInfo->currentTime;*/ solverInfo->laststep = solverInfo->currentTime; sim_result.emit(&sim_result, data); /* check if terminate()=true */ if (terminationTerminate) { printInfo(stdout, TermInfo); fputc('\n', stdout); infoStreamPrint(LOG_STDOUT, 0, "Simulation call terminate() at time %f\nMessage : %s", data->localData[0]->timeValue, TermMsg); simInfo->stopTime = solverInfo->currentTime; } /* terminate for some cases: * - integrator fails * - non-linear system failed to solve * - assert was called */ if (retValIntegrator) { retValue = -1 + retValIntegrator; infoStreamPrint(LOG_STDOUT, 0, "model terminate | Integrator failed. | Simulation terminated at time %g", solverInfo->currentTime); break; } else if (check_nonlinear_solutions(data, 0)) { retValue = -2; infoStreamPrint(LOG_STDOUT, 0, "model terminate | non-linear system solver failed. | Simulation terminated at time %g", solverInfo->currentTime); break; } else if (check_linear_solutions(data, 0)) { retValue = -3; infoStreamPrint(LOG_STDOUT, 0, "model terminate | linear system solver failed. | Simulation terminated at time %g", solverInfo->currentTime); break; } else if (check_mixed_solutions(data, 0)) { retValue = -4; infoStreamPrint(LOG_STDOUT, 0, "model terminate | mixed system solver failed. | Simulation terminated at time %g", solverInfo->currentTime); break; } success = 1; #if !defined(OMC_EMCC) } /* catch */ MMC_CATCH_INTERNAL(simulationJumpBuffer) #endif if (!success) { retValue = -1; infoStreamPrint(LOG_STDOUT, 0, "model terminate | Simulation terminated by an assert at time: %g", data->localData[0]->timeValue); break; } TRACE_POP /* pop loop */ } /* End of main loop */ #ifdef D fprintf(fid,"t = %.8f\n",solverInfo->currentTime); fprintf(fid,"%16s\t%16s\t%16s\t%16s\t%16s\t%16s\n","tx","x","dx","tq","q","tqp"); for (i = 0; i < STATES; i++) { fprintf(fid,"%16.8f\t%16.8f\t%16.8f\t%16.8f\t%16.8f\t%16.8f\n",tx[i],xik[i],derXik[i],tq[i],qik[i],tqp[i]); } fclose(fid); #endif /* free memory*/ free(der); /* for (i = 0; i < ROWS; i++) free(*(StatesInDer + i)); free(StatesInDer); free(numStatesInDer); */ free(qik); free(xik); free(derXik); free(tq); free(tx); free(tqp); free(nQh); free(dQ); /* end - free memory */ TRACE_POP return retValue; }
int SimulationResults_filterSimulationResults(const char *inFile, const char *outFile, void *vars, int numberOfIntervals) { const char *msg[5] = {"","","","",""}; void *tmp; if (UNKNOWN_PLOT == SimulationResultsImpl__openFile(inFile, &simresglob)) { return 0; } vars = mmc_mk_cons(mmc_mk_scon("time"),vars); switch (simresglob.curFormat) { case MATLAB4: { int numToFilter = listLength(vars); int i, j; int numUnique = 0; int numUniqueParam = 1; int longestName = 0; int longestDesc = 0; ModelicaMatVariable_t **mat_var = omc_alloc_interface.malloc(numToFilter*sizeof(ModelicaMatVariable_t*)); int *indexes = (int*) omc_alloc_interface.malloc(simresglob.matReader.nvar*sizeof(int)); /* Need it to be zeros; note that the actual number of indexes is smaller */ int *parameter_indexes = (int*) omc_alloc_interface.malloc(simresglob.matReader.nparam*sizeof(int)); /* Need it to be zeros; note that the actual number of indexes is smaller */ int *indexesToOutput = NULL; int *parameter_indexesToOutput = NULL; FILE *fout = NULL; char *tmp; double start_stop[2] = {0}; double start = omc_matlab4_startTime(&simresglob.matReader); double stop = omc_matlab4_stopTime(&simresglob.matReader); parameter_indexes[0] = 1; /* time */ omc_matlab4_read_all_vals(&simresglob.matReader); if (endsWith(outFile,".csv")) { double **vals = omc_alloc_interface.malloc(sizeof(double*)*numToFilter); FILE *fout = NULL; for (i=0; i<numToFilter; i++) { const char *var = MMC_STRINGDATA(MMC_CAR(vars)); vars = MMC_CDR(vars); mat_var[i] = omc_matlab4_find_var(&simresglob.matReader, var); if (mat_var[i] == NULL) { msg[0] = SystemImpl__basename(inFile); msg[1] = var; c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s."), msg, 2); return 0; } if (mat_var[i]->isParam) { msg[0] = var; c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not filter parameter %s since the output format is CSV (only variables are allowed)."), msg, 1); return 0; } else { vals[i] = omc_matlab4_read_vals(&simresglob.matReader, mat_var[i]->index); } } fout = fopen(outFile, "w"); fprintf(fout, "time"); for (i=1; i<numToFilter; i++) { fprintf(fout, ",\"%s\"", mat_var[i]->name); } fprintf(fout, ",nrows=%d\n", simresglob.matReader.nrows); for (i=0; i<simresglob.matReader.nrows; i++) { fprintf(fout, "%.15g", vals[0][i]); for (j=1; j<numToFilter; j++) { fprintf(fout, ",%.15g", vals[j][i]); } fprintf(fout, "\n"); } fclose(fout); return 1; } /* Not CSV */ for (i=0; i<numToFilter; i++) { const char *var = MMC_STRINGDATA(MMC_CAR(vars)); vars = MMC_CDR(vars); mat_var[i] = omc_matlab4_find_var(&simresglob.matReader,var); if (mat_var[i] == NULL) { msg[0] = SystemImpl__basename(inFile); msg[1] = var; c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("Could not read variable %s in file %s."), msg, 2); return 0; } if (mat_var[i]->isParam) { /* Store the old index in the array */ if (0==parameter_indexes[abs(mat_var[i]->index)-1]++) { numUniqueParam++; } } else { /* Store the old index in the array */ if (0==indexes[abs(mat_var[i]->index)-1]++) { numUnique++; } } longestName = intMax(longestName, strlen(mat_var[i]->name)); longestDesc = intMax(longestDesc, strlen(mat_var[i]->descr)); } /* Create the list of variable indexes to output */ indexesToOutput = omc_alloc_interface.malloc_atomic(numUnique * sizeof(int)); parameter_indexesToOutput = omc_alloc_interface.malloc_atomic(numUniqueParam * sizeof(int)); j=0; for (i=0; i<simresglob.matReader.nvar; i++) { if (indexes[i]) { indexesToOutput[j++] = i+1; } /* indexes becomes the lookup table from old index to new index */ indexes[i] = j; } j=0; for (i=0; i<simresglob.matReader.nparam; i++) { if (parameter_indexes[i]) { parameter_indexesToOutput[j++] = i+1; } /* indexes becomes the lookup table from old index to new index */ parameter_indexes[i] = j; } fout = fopen(outFile, "wb"); if (fout == NULL) { return failedToWriteToFile(outFile); } /* Matrix list: "Aclass" "name" "description" "dataInfo" "data_1" "data_2" */ if (writeMatVer4AclassNormal(fout)) { return failedToWriteToFile(outFile); } if (writeMatVer4MatrixHeader(fout, "name", numToFilter, longestName, sizeof(int8_t))) { return failedToWriteToFile(outFile); } tmp = omc_alloc_interface.malloc(numToFilter*longestName); for (i=0; i<numToFilter; i++) { int len = strlen(mat_var[i]->name); for (j=0; j<len; j++) { tmp[numToFilter*j+i] = mat_var[i]->name[j]; } } if (1 != fwrite(tmp, numToFilter*longestName, 1, fout)) { return failedToWriteToFile(outFile); } GC_free(tmp); if (writeMatVer4MatrixHeader(fout, "description", numToFilter, longestDesc, sizeof(int8_t))) { return failedToWriteToFile(outFile); } tmp = omc_alloc_interface.malloc(numToFilter*longestDesc); for (i=0; i<numToFilter; i++) { int len = strlen(mat_var[i]->descr); for (j=0; j<len; j++) { tmp[numToFilter*j+i] = mat_var[i]->descr[j]; } } if (1 != fwrite(tmp, numToFilter*longestDesc, 1, fout)) { return failedToWriteToFile(outFile); } GC_free(tmp); if (writeMatVer4MatrixHeader(fout, "dataInfo", numToFilter, 4, sizeof(int32_t))) { return failedToWriteToFile(outFile); } for (i=0; i<numToFilter; i++) { int32_t x = mat_var[i]->isParam ? 1 : 2; /* data_1 or data_2 */ if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) { return failedToWriteToFile(outFile); } } for (i=0; i<numToFilter; i++) { int32_t x = (mat_var[i]->index < 0 ? -1 : 1) * (mat_var[i]->isParam ? parameter_indexes[abs(mat_var[i]->index)-1] : indexes[abs(mat_var[i]->index)-1]); if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) { return failedToWriteToFile(outFile); } } for (i=0; i<numToFilter; i++) { int32_t x = 0; /* linear interpolation */ if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) { return failedToWriteToFile(outFile); } } for (i=0; i<numToFilter; i++) { int32_t x = -1; /* not defined outside the time interval */ if (1 != fwrite(&x, sizeof(int32_t), 1, fout)) { return failedToWriteToFile(outFile); } } if (writeMatVer4MatrixHeader(fout, "data_1", 2, numUniqueParam, sizeof(double))) { return failedToWriteToFile(outFile); } start = omc_matlab4_startTime(&simresglob.matReader); stop = omc_matlab4_stopTime(&simresglob.matReader); start_stop[0]=start; start_stop[1]=stop; if (1 != fwrite(start_stop, sizeof(double)*2, 1, fout)) { return failedToWriteToFile(outFile); } for (i=1; i<numUniqueParam; i++) { int paramIndex = parameter_indexesToOutput[i]; double d[2] = {simresglob.matReader.params[abs(paramIndex)-1],0}; d[1] = d[0]; if (1!=fwrite(d, sizeof(double)*2, 1, fout)) { return failedToWriteToFile(outFile); } } if (numberOfIntervals) { double *timevals = omc_matlab4_read_vals(&simresglob.matReader, 1); int last_found=0; int nevents=0, neventpoints=0; for (i=1; i<numberOfIntervals; i++) { double t = start + (stop-start)*((double)i)/numberOfIntervals; while (timevals[j]<=t) { if (timevals[j]==timevals[j+1]) { while (timevals[j]==timevals[j+1]) { j++; neventpoints++; } nevents++; } j++; } } msg[4] = inFile; GC_asprintf((char**)msg+3, "%d", simresglob.matReader.nrows); GC_asprintf((char**)msg+2, "%d", numberOfIntervals); GC_asprintf((char**)msg+1, "%d", nevents); GC_asprintf((char**)msg+0, "%d", neventpoints); c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_notification, gettext("Resampling %s from %s points to %s points, removing %s events stored in %s points.\n"), msg, 5); } if (writeMatVer4MatrixHeader(fout, "data_2", numberOfIntervals ? numberOfIntervals+1 : simresglob.matReader.nrows, numUnique, sizeof(double))) { return failedToWriteToFile(outFile); } for (i=0; i<numUnique; i++) { double *vals = NULL; int nrows; if (numberOfIntervals) { omc_matlab4_read_all_vals(&simresglob.matReader); nrows = numberOfIntervals+1; vals = omc_alloc_interface.malloc_atomic(sizeof(double)*nrows); for (j=0; j<=numberOfIntervals; j++) { double t = j==numberOfIntervals ? stop : start + (stop-start)*((double)j)/numberOfIntervals; ModelicaMatVariable_t var = {0}; var.name=""; var.descr=""; var.isParam=0; var.index=indexesToOutput[i]; if (omc_matlab4_val(vals+j, &simresglob.matReader, &var, t)) { msg[2] = inFile; GC_asprintf((char**)msg+1, "%d", indexesToOutput[i]); GC_asprintf((char**)msg+0, "%.15g", t); c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("Resampling %s failed to get variable %s at time %s.\n"), msg, 3); return 0; } } } else { vals = omc_matlab4_read_vals(&simresglob.matReader, indexesToOutput[i]); nrows = simresglob.matReader.nrows; } if (1!=fwrite(vals, sizeof(double)*nrows, 1, fout)) { return failedToWriteToFile(outFile); } if (numberOfIntervals) { GC_free(vals); } } fclose(fout); return 1; } default: msg[0] = PlotFormatStr[simresglob.curFormat]; c_add_message(NULL,-1, ErrorType_scripting, ErrorLevel_error, gettext("filterSimulationResults not implemented for plot format: %s\n"), msg, 1); return 0; } }
/*! \fn printParameters * * prints all parameter values * * \param [in] [data] * \param [in] [stream] * * \author wbraun */ void printParameters(DATA *data, int stream) { TRACE_PUSH long i; MODEL_DATA *mData = &(data->modelData); if (!ACTIVE_STREAM(stream)) return; infoStreamPrint(stream, 1, "parameter values"); if (0 < mData->nParametersReal) { infoStreamPrint(stream, 1, "real parameters"); for(i=0; i<mData->nParametersReal; ++i) infoStreamPrint(stream, 0, "[%ld] parameter Real %s(start=%g, fixed=%s) = %g", i+1, mData->realParameterData[i].info.name, mData->realParameterData[i].attribute.start, mData->realParameterData[i].attribute.fixed ? "true" : "false", data->simulationInfo.realParameter[i]); messageClose(stream); } if (0 < mData->nParametersInteger) { infoStreamPrint(stream, 1, "integer parameters"); for(i=0; i<mData->nParametersInteger; ++i) infoStreamPrint(stream, 0, "[%ld] parameter Integer %s(start=%ld, fixed=%s) = %ld", i+1, mData->integerParameterData[i].info.name, mData->integerParameterData[i].attribute.start, mData->integerParameterData[i].attribute.fixed ? "true" : "false", data->simulationInfo.integerParameter[i]); messageClose(stream); } if (0 < mData->nParametersBoolean) { infoStreamPrint(stream, 1, "boolean parameters"); for(i=0; i<mData->nParametersBoolean; ++i) infoStreamPrint(stream, 0, "[%ld] parameter Boolean %s(start=%s, fixed=%s) = %s", i+1, mData->booleanParameterData[i].info.name, mData->booleanParameterData[i].attribute.start ? "true" : "false", mData->booleanParameterData[i].attribute.fixed ? "true" : "false", data->simulationInfo.booleanParameter[i] ? "true" : "false"); messageClose(stream); } if (0 < mData->nParametersString) { infoStreamPrint(stream, 1, "string parameters"); for(i=0; i<mData->nParametersString; ++i) infoStreamPrint(stream, 0, "[%ld] parameter String %s(start=\"%s\") = \"%s\"", i+1, mData->stringParameterData[i].info.name, MMC_STRINGDATA(mData->stringParameterData[i].attribute.start), MMC_STRINGDATA(data->simulationInfo.stringParameter[i])); messageClose(stream); } messageClose(stream); TRACE_POP }
static const char* path_to_name(void* path, char del) { threadData_t *threadData = (threadData_t *) pthread_getspecific(mmc_thread_data_key); char delStr[2] = {del,'\0'}; return MMC_STRINGDATA(omc_Absyn_pathString2(threadData, path, mmc_mk_scon(delStr))); }
extern const char* System_trimChar(const char* str, const char* char_to_remove) { if (!char_to_remove[0] || char_to_remove[1]) MMC_THROW(); return MMC_STRINGDATA(SystemImpl__trimChar(str,*char_to_remove)); }