static void fmtEmitStep(DATA* data, threadData_t *threadData, MEASURE_TIME* mt, int didEventStep) { if(mt->fmtReal) { int i, flag=1; double tmpdbl; unsigned int tmpint; int total = data->modelData->modelDataXml.nFunctions + data->modelData->modelDataXml.nProfileBlocks; rt_tick(SIM_TIMER_OVERHEAD); rt_accumulate(SIM_TIMER_STEP); /* Disable time measurements if we have trouble writing to the file... */ flag = flag && 1 == fwrite(&mt->stepNo, sizeof(unsigned int), 1, mt->fmtInt); mt->stepNo++; flag = flag && 1 == fwrite(&(data->localData[0]->timeValue), sizeof(double), 1, mt->fmtReal); tmpdbl = rt_accumulated(SIM_TIMER_STEP); flag = flag && 1 == fwrite(&tmpdbl, sizeof(double), 1, mt->fmtReal); flag = flag && total == fwrite(rt_ncall_arr(SIM_TIMER_FIRST_FUNCTION), sizeof(uint32_t), total, mt->fmtInt); for(i=0; i<data->modelData->modelDataXml.nFunctions + data->modelData->modelDataXml.nProfileBlocks; i++) { tmpdbl = rt_accumulated(i + SIM_TIMER_FIRST_FUNCTION); flag = flag && 1 == fwrite(&tmpdbl, sizeof(double), 1, mt->fmtReal); } rt_accumulate(SIM_TIMER_OVERHEAD); if(!flag) { warningStreamPrint(LOG_SOLVER, 0, "Disabled time measurements because the output file could not be generated: %s", strerror(errno)); fclose(mt->fmtInt); fclose(mt->fmtReal); mt->fmtInt = NULL; mt->fmtReal = NULL; } } /* prevent emit if noEventEmit flag is used, if it's an event */ if ((omc_flag[FLAG_NOEVENTEMIT] && didEventStep == 0) || !omc_flag[FLAG_NOEVENTEMIT]) { sim_result.emit(&sim_result, data, threadData); } #if !defined(OMC_MINIMAL_RUNTIME) embedded_server_update(data->embeddedServerState, data->localData[0]->timeValue); if (data->real_time_sync.enabled) { double time = data->localData[0]->timeValue; int64_t res = rt_ext_tp_sync_nanosec(&data->real_time_sync.clock, (uint64_t) (data->real_time_sync.scaling*(time-data->real_time_sync.time)*1e9)); int64_t maxLateNano = data->simulationInfo->stepSize*1e9*0.1*data->real_time_sync.scaling /* Maximum late time: 10% of step size */; if (res > maxLateNano) { int t=0,tMaxLate=0; const char *unit = prettyPrintNanoSec(res, &t); const char *unit2 = prettyPrintNanoSec(maxLateNano, &tMaxLate); errorStreamPrint(LOG_RT, 0, "Missed deadline at time %g; delta was %d %s (maxLate=%d %s)", time, t, unit, tMaxLate, unit2); } if (res > data->real_time_sync.maxLate) { data->real_time_sync.maxLate = res; } } printAllVarsDebug(data, 0, LOG_DEBUG); /* ??? */ #endif }
void* embedded_server_load_functions(const char *server_name) { void *dll, *funcInit, *funcWaitForStep, *funcDeinit, *funcUpdate; if (NULL==server_name || 0==strcmp("none", server_name)) { return NULL; } if (0==strcmp("opc-ua", server_name)) { server_name = "libomopcua" DLL_EXT; } else if (0==strcmp("opc-da", server_name)) { #if defined(UPC_DA) server_name = "libomopcda" DLL_EXT; #else errorStreamPrint(LOG_DEBUG, 0, "OPC DA interface is not available on this platform (requires WIN32)"); MMC_THROW(); #endif } infoStreamPrint(LOG_DEBUG, 0, "Try to load embedded server %s", server_name); dll = dlopen(server_name, RTLD_LAZY); if (dll == NULL) { errorStreamPrint(LOG_DEBUG, 0, "Failed to load shared object %s: %s\n", server_name, dlerror()); MMC_THROW(); } funcInit = dlsym(dll, "omc_embedded_server_init"); if (!funcInit) { errorStreamPrint(LOG_DEBUG, 0, "Failed to load function omc_embedded_server_init: %s\n", dlerror()); MMC_THROW(); } funcWaitForStep = dlsym(dll, "omc_wait_for_step"); if (!funcWaitForStep) { errorStreamPrint(LOG_DEBUG, 0, "Failed to load function omc_wait_for_step: %s\n", dlerror()); MMC_THROW(); } funcDeinit = dlsym(dll, "omc_embedded_server_deinit"); if (!funcDeinit) { errorStreamPrint(LOG_DEBUG, 0, "Failed to load function omc_embedded_server_deinit: %s\n", dlerror()); MMC_THROW(); } funcUpdate = dlsym(dll, "omc_embedded_server_update"); if (!funcUpdate) { errorStreamPrint(LOG_DEBUG, 0, "Failed to load function omc_embedded_server_update: %s\n", dlerror()); MMC_THROW(); } embedded_server_init = funcInit; wait_for_step = funcWaitForStep; embedded_server_deinit = funcDeinit; embedded_server_update = funcUpdate; infoStreamPrint(LOG_DEBUG, 0, "Loaded embedded server"); return dll; }
static int nlsKinsolErrorHandler(int errorCode, DATA *data, NONLINEAR_SYSTEM_DATA *nlsData, NLS_KINSOL_DATA *kinsolData) { int retValue, i, retValue2=0; double fNorm; double *xStart = NV_DATA_S(kinsolData->initialGuess); double *xScaling = NV_DATA_S(kinsolData->xScale); /* check what kind of error * retValue < 0 -> a non recoverable issue * retValue == 1 -> try with other settings */ KINSetNoInitSetup(kinsolData->kinsolMemory, FALSE); switch(errorCode) { case KIN_MEM_NULL: case KIN_ILL_INPUT: case KIN_NO_MALLOC: errorStreamPrint(LOG_NLS, 0, "kinsol has a serious memory issue ERROR %d\n", errorCode); return errorCode; break; /* just retry with new initial guess */ case KIN_MXNEWT_5X_EXCEEDED: warningStreamPrint(LOG_NLS, 0, "initial guess was too far away from the solution. Try again.\n"); return 1; break; /* just retry without line search */ case KIN_LINESEARCH_NONCONV: warningStreamPrint(LOG_NLS, 0, "kinsols line search did not convergence. Try without.\n"); kinsolData->kinsolStrategy = KIN_NONE; return 1; /* maybe happened because of an out-dated factorization, so just retry */ case KIN_LSETUP_FAIL: case KIN_LSOLVE_FAIL: warningStreamPrint(LOG_NLS, 0, "kinsols matrix need new factorization. Try again.\n"); KINKLUReInit(kinsolData->kinsolMemory, kinsolData->size, kinsolData->nnz, 2); return 1; case KIN_MAXITER_REACHED: case KIN_REPTD_SYSFUNC_ERR: warningStreamPrint(LOG_NLS, 0, "kinsols runs into issues retry with differnt configuration.\n"); retValue = 1; break; default: errorStreamPrint(LOG_STDOUT, 0, "kinsol has a serious solving issue ERROR %d\n", errorCode); return errorCode; break; } /* check if the current solution is sufficient anyway */ KINGetFuncNorm(kinsolData->kinsolMemory, &fNorm); if (fNorm<FTOL_WITH_LESS_ACCURANCY) { warningStreamPrint(LOG_NLS, 0, "Move forward with a less accurate solution."); KINSetFuncNormTol(kinsolData->kinsolMemory, FTOL_WITH_LESS_ACCURANCY); KINSetScaledStepTol(kinsolData->kinsolMemory, FTOL_WITH_LESS_ACCURANCY); retValue2 = 1; } else { warningStreamPrint(LOG_NLS, 0, "Current status of fx = %f", fNorm); } /* reconfigure kinsol for an other try */ if (retValue == 1 && !retValue2) { switch(kinsolData->retries) { case 0: /* try without x scaling */ nlsKinsolXScaling(data, kinsolData, nlsData, SCALING_ONES); break; case 1: /* try without line-search and oldValues */ nlsKinsolResetInitial(data, kinsolData, nlsData, INITIAL_OLDVALUES); kinsolData->kinsolStrategy = KIN_LINESEARCH; break; case 2: /* try without line-search and oldValues */ nlsKinsolResetInitial(data, kinsolData, nlsData, INITIAL_EXTRAPOLATION); kinsolData->kinsolStrategy = KIN_NONE; break; case 3: /* try with exact newton */ nlsKinsolXScaling(data, kinsolData, nlsData, SCALING_NOMINALSTART); nlsKinsolResetInitial(data, kinsolData, nlsData, INITIAL_EXTRAPOLATION); KINSetMaxSetupCalls(kinsolData->kinsolMemory, 1); kinsolData->kinsolStrategy = KIN_LINESEARCH; break; case 4: /* try with exact newton to with out x scaling values */ nlsKinsolXScaling(data, kinsolData, nlsData, SCALING_ONES); nlsKinsolResetInitial(data, kinsolData, nlsData, INITIAL_OLDVALUES); KINSetMaxSetupCalls(kinsolData->kinsolMemory, 1); kinsolData->kinsolStrategy = KIN_LINESEARCH; break; default: retValue = 0; break; } } return retValue+retValue2; }
int nlsKinsolAllocate(int size, NONLINEAR_SYSTEM_DATA *nlsData, int linearSolverMethod) { int i, flag, printLevel; NLS_KINSOL_DATA *kinsolData = (NLS_KINSOL_DATA*) malloc(sizeof(NLS_KINSOL_DATA)); /* allocate system data */ nlsData->solverData = (void*)kinsolData; kinsolData->size = size; kinsolData->linearSolverMethod = linearSolverMethod; kinsolData->solved = 0; kinsolData->fnormtol = sqrt(newtonFTol); /* function tolerance */ kinsolData->scsteptol = sqrt(newtonXTol); /* step tolerance */ kinsolData->initialGuess = N_VNew_Serial(size); kinsolData->xScale = N_VNew_Serial(size); kinsolData->fScale = N_VNew_Serial(size); kinsolData->fRes = N_VNew_Serial(size); kinsolData->kinsolMemory = KINCreate(); /* setup user defined functions */ KINSetErrHandlerFn(kinsolData->kinsolMemory, nlsKinsolErrorPrint, kinsolData); KINSetInfoHandlerFn(kinsolData->kinsolMemory, nlsKinsolInfoPrint, kinsolData); KINSetUserData(kinsolData->kinsolMemory, (void*)&(kinsolData->userData)); flag = KINInit(kinsolData->kinsolMemory, nlsKinsolResiduals, kinsolData->initialGuess); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } /* Specify linear solver and/or corresponding jacobian function*/ if (kinsolData->linearSolverMethod == 3) { if(nlsData->isPatternAvailable) { kinsolData->nnz = nlsData->sparsePattern.numberOfNoneZeros; flag = KINKLU(kinsolData->kinsolMemory, size, kinsolData->nnz); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } flag = KINSlsSetSparseJacFn(kinsolData->kinsolMemory, nlsSparseJac); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL Sparse Solver!"); } } else { flag = KINDense(kinsolData->kinsolMemory, size); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } } } else if (kinsolData->linearSolverMethod == 1) { flag = KINDense(kinsolData->kinsolMemory, size); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } } else if (kinsolData->linearSolverMethod == 2) { flag = KINDense(kinsolData->kinsolMemory, size); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL solver!"); } flag = KINDlsSetDenseJacFn(kinsolData->kinsolMemory, nlsDenseJac); if (checkReturnFlag(flag)){ errorStreamPrint(LOG_STDOUT, 0, "##KINSOL## Something goes wrong while initialize KINSOL Sparse Solver!"); } } /* configuration */ nlsKinsolConfigSetup(kinsolData); /* debug print level of kinsol */ if (ACTIVE_STREAM(LOG_NLS)) printLevel = 1; else if (ACTIVE_STREAM(LOG_NLS_V)) printLevel = 3; else printLevel = 0; KINSetPrintLevel(kinsolData->kinsolMemory, printLevel); return 0; }
/*! * write results in result file * author: Vitalij Ruge **/ void res2file(OptData *optData, SOLVER_INFO* solverInfo, double *vopt){ const int nu = optData->dim.nu; const int nx = optData->dim.nx; const int nv = optData->dim.nv; const int nsi = optData->dim.nsi; const int np = optData->dim.np; const int nReal = optData->dim.nReal; const int nBoolean = optData->data->modelData.nVariablesBoolean; const int nInteger = optData->data->modelData.nVariablesInteger; const int nRelations = optData->data->modelData.nRelations; const int nvnp = nv*np; long double a[np]; modelica_real *** v = optData->v; float tmp_u; int i,j,k, ii, jj; char buffer[4096]; DATA * data = optData->data; SIMULATION_DATA *sData = (SIMULATION_DATA*)data->localData[0]; FILE * pFile = optData->pFile; double * v0 = optData->v0; double *vnom = optData->bounds.vnom; long double **t = optData->time.t; long double t0 = optData->time.t0; long double tmpv; if(np == 3){ a[0] = 1.5580782047249223824319753706862790293163070736617; a[1] = -0.89141153805825571576530870401961236264964040699507; a[2] = 0.33333333333333333333333333333333333333333333333333; }else if(np == 1){ a[0] = 1.000; }else{ errorStreamPrint(LOG_STDOUT, 0, "Not support np = %i", np); assert(0); } optData2ModelData(optData, vopt, 0); /******************/ fprintf(pFile, "%lf ",(double)t0); for(i=0,j = nx; i < nu; ++i,++j){ for(k = 0, tmpv = 0.0; k < np; ++k){ tmpv += a[k]*vopt[k*nv + j]; } tmpv = fmin(fmax(tmpv,optData->bounds.vmin[j]),optData->bounds.vmax[j]); data->simulationInfo.inputVars[i] = (double)tmpv*vnom[j]; fprintf(pFile, "%lf ", (float)data->simulationInfo.inputVars[i]); } fprintf(pFile, "%s", "\n"); /******************/ memcpy(sData->realVars, v0, nReal*sizeof(modelica_real)); memcpy(data->localData[0]->integerVars, optData->i0, nInteger*sizeof(modelica_integer)); memcpy(data->localData[0]->booleanVars, optData->b0, nBoolean*sizeof(modelica_boolean)); memcpy(data->simulationInfo.integerVarsPre, optData->i0Pre, nInteger*sizeof(modelica_integer)); memcpy(data->simulationInfo.booleanVarsPre, optData->b0Pre, nBoolean*sizeof(modelica_boolean)); memcpy(data->simulationInfo.realVarsPre, optData->v0Pre, nReal*sizeof(modelica_real)); memcpy(data->simulationInfo.relationsPre, optData->rePre, nRelations*sizeof(modelica_boolean)); memcpy(data->simulationInfo.relations, optData->re, nRelations*sizeof(modelica_boolean)); memcpy(data->simulationInfo.storedRelations, optData->storeR, nRelations*sizeof(modelica_boolean)); /******************/ solverInfo->currentTime = (double)t0; sData->timeValue = solverInfo->currentTime; /*updateDiscreteSystem(data);*/ data->callback->input_function(data); /*data->callback->functionDAE(data);*/ updateDiscreteSystem(data); sim_result.emit(&sim_result,data); /******************/ for(ii = 0; ii < nsi; ++ii){ for(jj = 0; jj < np; ++jj){ /******************/ memcpy(sData->realVars, v[ii][jj], nReal*sizeof(modelica_real)); /******************/ fprintf(pFile, "%lf ",(double)t[ii][jj]); for(i = 0; i < nu; ++i){ tmp_u = (float)(vopt[ii*nvnp+jj*nv+nx+i]*vnom[i + nx]); fprintf(pFile, "%lf ", tmp_u); } fprintf(pFile, "%s", "\n"); /******************/ solverInfo->currentTime = (double)t[ii][jj]; sData->timeValue = solverInfo->currentTime; sim_result.emit(&sim_result,data); } } fclose(pFile); }
/* pick up information(startTime, stopTime, dt) from model data to optimizer struct * author: Vitalij Ruge */ static inline void pickUpTime(OptDataTime * time, OptDataDim * dim, DATA* data, const double preSimTime){ const int nsi = dim->nsi; const int np = dim->np; const int np1 = np - 1; long double c[np]; long double dc[np]; int i, k; double t; char * cflags = NULL; time->t0 = (long double)fmax(data->simulationInfo.startTime, preSimTime); time->tf = (long double)data->simulationInfo.stopTime; time->dt = (long double*) malloc((nsi+1)*sizeof(long double)); time->dt[0] = (time->tf - time->t0)/nsi; time->t = (long double**)malloc(nsi*sizeof(long double*)); for(i = 0; i<nsi; ++i) time->t[i] = (long double*)malloc(np*sizeof(long double)); if(nsi < 1){ errorStreamPrint(LOG_STDOUT, 0, "Not support numberOfIntervals = %i < 1", nsi); assert(0); } if(np == 1){ c[0] = 1.0; }else if(np == 3){ c[0] = 0.15505102572168219018027159252941086080340525193433; c[1] = 0.64494897427831780981972840747058913919659474806567; c[2] = 1.00000; }else{ errorStreamPrint(LOG_STDOUT, 0, "Not support np = %i", np); assert(0); } for(k = 0; k < np; ++k){ dc[k] = c[k]*time->dt[0]; time->t[0][k] = time->t0 + dc[k]; } for(i = 1; i < nsi; ++i){ time->dt[i] = time->dt[i-1]; for(k = 0; k < np; ++k) time->t[i][k] = time->t[i-1][np1] + dc[k]; } time->t[nsi-1][np1] = time->tf; if(nsi > 1){ i = nsi - 1; time->dt[nsi-1] = time->t[i][np1] - time->t[i-1][np1]; for(k = 0; k < np; ++k) time->t[i][k] = time->t[i-1][np1] + c[k]*time->dt[nsi-1]; }else time->dt[1] = time->dt[0]; cflags = (char*)omc_flagValue[FLAG_OPTIMIZER_TGRID]; if(cflags) overwriteTimeGridFile(time, cflags, c, np, nsi); if(time->model_grid) overwriteTimeGridModel(time, c, np, nsi); }
/*! \fn int importStartValues(DATA *data, const char *pInitFile, const double initTime) * * \param [ref] [data] * \param [in] [pInitFile] * \param [in] [initTime] * * \author lochel */ int importStartValues(DATA *data, threadData_t *threadData, const char *pInitFile, const double initTime) { ModelicaMatReader reader; ModelicaMatVariable_t *pVar = NULL; double value; const char *pError = NULL; char* newVarname = NULL; MODEL_DATA *mData = data->modelData; long i; infoStreamPrint(LOG_INIT, 0, "import start values\nfile: %s\ntime: %g", pInitFile, initTime); if(!strcmp(data->modelData->resultFileName, pInitFile)) { errorStreamPrint(LOG_INIT, 0, "Cannot import a result file for initialization that is also the current output file <%s>.\nConsider redirecting the output result file (-r=<new_res.mat>) or renaming the result file that is used for initialization import.", pInitFile); return 1; } pError = omc_new_matlab4_reader(pInitFile, &reader); if(pError) { throwStreamPrint(threadData, "unable to read input-file <%s> [%s]", pInitFile, pError); return 1; } else { infoStreamPrint(LOG_INIT, 0, "import real variables"); for(i=0; i<mData->nVariablesReal; ++i) { pVar = omc_matlab4_find_var(&reader, mData->realVarsData[i].info.name); if(!pVar) { newVarname = mapToDymolaVars(mData->realVarsData[i].info.name); pVar = omc_matlab4_find_var(&reader, newVarname); free(newVarname); } if(pVar) { omc_matlab4_val(&(mData->realVarsData[i].attribute.start), &reader, pVar, initTime); infoStreamPrint(LOG_INIT, 0, "| %s(start=%g)", mData->realVarsData[i].info.name, mData->realVarsData[i].attribute.start); } else if((strlen(mData->realVarsData[i].info.name) > 0) && (mData->realVarsData[i].info.name[0] != '$') && (strncmp(mData->realVarsData[i].info.name, "der($", 5) != 0)) { /* skip warnings about self-generated variables */ warningStreamPrint(LOG_INIT, 0, "unable to import real variable %s from given file", mData->realVarsData[i].info.name); } } infoStreamPrint(LOG_INIT, 0, "import real parameters"); for(i=0; i<mData->nParametersReal; ++i) { pVar = omc_matlab4_find_var(&reader, mData->realParameterData[i].info.name); if(!pVar) { newVarname = mapToDymolaVars(mData->realParameterData[i].info.name); pVar = omc_matlab4_find_var(&reader, newVarname); free(newVarname); } if(pVar) { omc_matlab4_val(&(mData->realParameterData[i].attribute.start), &reader, pVar, initTime); data->simulationInfo->realParameter[i] = mData->realParameterData[i].attribute.start; infoStreamPrint(LOG_INIT, 0, "| %s(start=%g)", mData->realParameterData[i].info.name, mData->realParameterData[i].attribute.start); } else { warningStreamPrint(LOG_INIT, 0, "unable to import real parameter %s from given file", mData->realParameterData[i].info.name); } } infoStreamPrint(LOG_INIT, 0, "import real discrete"); for(i=mData->nVariablesReal-mData->nDiscreteReal; i<mData->nDiscreteReal; ++i) { pVar = omc_matlab4_find_var(&reader, mData->realParameterData[i].info.name); if(!pVar) { newVarname = mapToDymolaVars(mData->realParameterData[i].info.name); pVar = omc_matlab4_find_var(&reader, newVarname); free(newVarname); } if(pVar) { omc_matlab4_val(&(mData->realParameterData[i].attribute.start), &reader, pVar, initTime); infoStreamPrint(LOG_INIT, 0, "| %s(start=%g)", mData->realParameterData[i].info.name, mData->realParameterData[i].attribute.start); } else { warningStreamPrint(LOG_INIT, 0, "unable to import real parameter %s from given file", mData->realParameterData[i].info.name); } } infoStreamPrint(LOG_INIT, 0, "import integer parameters"); for(i=0; i<mData->nParametersInteger; ++i) { pVar = omc_matlab4_find_var(&reader, mData->integerParameterData[i].info.name); if (!pVar) { newVarname = mapToDymolaVars(mData->integerParameterData[i].info.name); pVar = omc_matlab4_find_var(&reader, newVarname); free(newVarname); } if (pVar) { omc_matlab4_val(&value, &reader, pVar, initTime); mData->integerParameterData[i].attribute.start = (modelica_integer)value; data->simulationInfo->integerParameter[i] = (modelica_integer)value; infoStreamPrint(LOG_INIT, 0, "| %s(start=%ld)", mData->integerParameterData[i].info.name, mData->integerParameterData[i].attribute.start); } else { warningStreamPrint(LOG_INIT, 0, "unable to import integer parameter %s from given file", mData->integerParameterData[i].info.name); } } infoStreamPrint(LOG_INIT, 0, "import boolean parameters"); for(i=0; i<mData->nParametersBoolean; ++i) { pVar = omc_matlab4_find_var(&reader, mData->booleanParameterData[i].info.name); if(!pVar) { newVarname = mapToDymolaVars(mData->booleanParameterData[i].info.name); pVar = omc_matlab4_find_var(&reader, newVarname); free(newVarname); } if(pVar) { omc_matlab4_val(&value, &reader, pVar, initTime); mData->booleanParameterData[i].attribute.start = (modelica_boolean)value; data->simulationInfo->booleanParameter[i] = (modelica_boolean)value; infoStreamPrint(LOG_INIT, 0, "| %s(start=%s)", mData->booleanParameterData[i].info.name, mData->booleanParameterData[i].attribute.start ? "true" : "false"); } else { warningStreamPrint(LOG_INIT, 0, "unable to import boolean parameter %s from given file", mData->booleanParameterData[i].info.name); } } omc_free_matlab4_reader(&reader); } return 0; }