int MultFive_updateBoundVariableAttributes(DATA *data) { /* min ******************************************************** */ infoStreamPrint(LOG_INIT, 1, "updating min-values"); if (ACTIVE_STREAM(LOG_INIT)) messageClose(LOG_INIT); /* max ******************************************************** */ infoStreamPrint(LOG_INIT, 1, "updating max-values"); if (ACTIVE_STREAM(LOG_INIT)) messageClose(LOG_INIT); /* nominal **************************************************** */ infoStreamPrint(LOG_INIT, 1, "updating nominal-values"); if (ACTIVE_STREAM(LOG_INIT)) messageClose(LOG_INIT); /* start ****************************************************** */ infoStreamPrint(LOG_INIT, 1, "updating start-values"); if (ACTIVE_STREAM(LOG_INIT)) messageClose(LOG_INIT); return 0; }
/*! \fn printStatus * * \param [in] [solverData] * \param [in] [nfunc_evals] * \param [in] [xerror] * \param [in] [xerror_scaled] * \param [in] [logLevel] * * \author wbraun */ static void printStatus(DATA *data, DATA_HYBRD *solverData, int eqSystemNumber, const int *nfunc_evals, const double *xerror, const double *xerror_scaled, const int logLevel) { long i; if (!ACTIVE_STREAM(logLevel)) return; infoStreamPrint(logLevel, 1, "nls status"); infoStreamPrint(logLevel, 1, "variables"); for(i=0; i<solverData->n; i++) infoStreamPrint(logLevel, 0, "[%ld] %s = %.20e\n - scaling factor internal = %.16e\n" " - scaling factor external = %.16e", i+1, modelInfoGetEquation(&data->modelData.modelDataXml,eqSystemNumber).vars[i], solverData->x[i], solverData->diag[i], solverData->xScalefactors[i]); messageClose(logLevel); infoStreamPrint(logLevel, 1, "functions"); for(i=0; i<solverData->n; i++) infoStreamPrint(logLevel, 0, "res[%ld] = %.20e [scaling factor = %.16e]", i+1, solverData->fvec[i], solverData->resScaling[i]); messageClose(logLevel); infoStreamPrint(logLevel, 1, "statistics"); infoStreamPrint(logLevel, 0, "nfunc = %d\nerror = %.20e\nerror_scaled = %.20e", *nfunc_evals, *xerror, *xerror_scaled); messageClose(logLevel); messageClose(logLevel); }
/*! \fn printSparseStructure * * prints sparse structure of jacobian A * * \param [in] [data] * \param [in] [stream] * * \author lochel */ void printSparseStructure(DATA *data, int stream) { const int index = data->callback->INDEX_JAC_A; unsigned int row, col, i, j; /* Will crash with a static size array */ char *buffer = NULL; if (!ACTIVE_STREAM(stream)) return; buffer = (char*)omc_alloc_interface.malloc(sizeof(char)* 2*data->simulationInfo.analyticJacobians[index].sizeCols + 4); infoStreamPrint(stream, 1, "sparse structure of jacobian A [size: %ux%u]", data->simulationInfo.analyticJacobians[index].sizeRows, data->simulationInfo.analyticJacobians[index].sizeCols); infoStreamPrint(stream, 0, "%u nonzero elements", data->simulationInfo.analyticJacobians[index].sparsePattern.numberOfNoneZeros); /* sprintf(buffer, ""); for(row=0; row < data->simulationInfo.analyticJacobians[index].sizeRows; row++) sprintf(buffer, "%s%u ", buffer, data->simulationInfo.analyticJacobians[index].sparsePattern.leadindex[row]); infoStreamPrint(stream, 0, "leadindex: %s", buffer); sprintf(buffer, ""); for(i=0; i < data->simulationInfo.analyticJacobians[index].sparsePattern.numberOfNoneZeros; i++) sprintf(buffer, "%s%u ", buffer, data->simulationInfo.analyticJacobians[index].sparsePattern.index[i]); infoStreamPrint(stream, 0, "index: %s", buffer); */ infoStreamPrint(stream, 1, "transposed sparse structure (rows: states)"); i=0; for(row=0; row < data->simulationInfo.analyticJacobians[index].sizeRows; row++) { j=0; for(col=0; i < data->simulationInfo.analyticJacobians[index].sparsePattern.leadindex[row]; col++) { if(data->simulationInfo.analyticJacobians[index].sparsePattern.index[i] == col) { buffer[j++] = '*'; ++i; } else { buffer[j++] = ' '; } buffer[j++] = ' '; } buffer[j] = '\0'; infoStreamPrint(stream, 0, "%s", buffer); } messageClose(stream); messageClose(stream); }
void debugMatrixDoubleLS(int logName, char* matrixName, double* matrix, int n, int m) { if(ACTIVE_STREAM(logName)) { int i, j; int sparsity = 0; char *buffer = (char*)malloc(sizeof(char)*m*18); infoStreamPrint(logName, 1, "%s [%dx%d-dim]", matrixName, n, m); for(i=0; i<n;i++) { buffer[0] = 0; for(j=0; j<m; j++) { if (sparsity) { if (fabs(matrix[i + j*(m-1)])<1e-12) sprintf(buffer, "%s 0", buffer); else sprintf(buffer, "%s *", buffer); } else { sprintf(buffer, "%s%12.4g ", buffer, matrix[i + j*(m-1)]); } } infoStreamPrint(logName, 0, "%s", buffer); } messageClose(logName); free(buffer); } }
/*! \fn int initializeMixedSystems(DATA *data) * * This function allocates memory for all mixed systems. * * \param [ref] [data] */ int initializeMixedSystems(DATA *data, threadData_t *threadData) { int i; int size; MIXED_SYSTEM_DATA *system = data->simulationInfo->mixedSystemData; infoStreamPrint(LOG_NLS, 1, "initialize mixed system solvers"); infoStreamPrint(LOG_NLS, 0, "%ld mixed systems", data->modelData->nMixedSystems); for(i=0; i<data->modelData->nMixedSystems; ++i) { size = system[i].size; system[i].iterationVarsPtr = (modelica_boolean**) malloc(size*sizeof(modelica_boolean*)); system[i].iterationPreVarsPtr = (modelica_boolean**) malloc(size*sizeof(modelica_boolean*)); /* allocate solver data */ switch(data->simulationInfo->mixedMethod) { case MIXED_SEARCH: allocateMixedSearchData(size, &system[i].solverData); break; default: throwStreamPrint(threadData, "unrecognized mixed solver"); } } messageClose(LOG_NLS); return 0; }
/*! \fn updateInitialGuessDB * * This function writes new values to solution list. * * \param [in] [nonlinsys] * \param [in] [time] time for extrapolation * \param [in] [context] current context of evaluation * */ int updateInitialGuessDB(NONLINEAR_SYSTEM_DATA *nonlinsys, double time, int context) { /* write solution to oldValue list for extrapolation */ if (nonlinsys->solved == 1) { /* do not use solution of jacobian for next extrapolation */ if (context < 4) { addListElement((VALUES_LIST*)nonlinsys->oldValueList, createValueElement(nonlinsys->size, time, nonlinsys->nlsx)); } } else if (nonlinsys->solved == 2) { if (listLen(((VALUES_LIST*)nonlinsys->oldValueList)->valueList)>0) { cleanValueList((VALUES_LIST*)nonlinsys->oldValueList, NULL); } /* do not use solution of jacobian for next extrapolation */ if (context < 4) { addListElement((VALUES_LIST*)nonlinsys->oldValueList, createValueElement(nonlinsys->size, time, nonlinsys->nlsx)); } } messageClose(LOG_NLS_EXTRAPOLATE); return 0; }
/*! \fn freeMixedSystems * * Thi function frees memory of mixed systems. * * \param [ref] [data] */ int freeMixedSystems(DATA *data, threadData_t *threadData) { int i; MIXED_SYSTEM_DATA* system = data->simulationInfo->mixedSystemData; infoStreamPrint(LOG_NLS, 1, "free mixed system solvers"); for(i=0;i<data->modelData->nMixedSystems;++i) { free(system[i].iterationVarsPtr); free(system[i].iterationPreVarsPtr); /* allocate solver data */ switch(data->simulationInfo->mixedMethod) { case MIXED_SEARCH: freeMixedSearchData(&system[i].solverData); break; default: throwStreamPrint(threadData, "unrecognized mixed solver"); } free(system[i].solverData); } messageClose(LOG_NLS); return 0; }
static int nlsKinsolConfigPrint(NLS_KINSOL_DATA *kinsolData, NONLINEAR_SYSTEM_DATA *nlsData) { int retValue; double fNorm; double *xStart = NV_DATA_S(kinsolData->initialGuess); double *xScaling = NV_DATA_S(kinsolData->xScale); DATA* data = kinsolData->userData.data; int eqSystemNumber = nlsData->equationIndex; infoStreamPrint(LOG_NLS_V, 1, "Kinsol Configuration"); _omc_printVectorWithEquationInfo(_omc_createVector(kinsolData->size, xStart), "Initial guess values", LOG_NLS_V, modelInfoGetEquation(&data->modelData->modelDataXml,eqSystemNumber)); _omc_printVectorWithEquationInfo(_omc_createVector(kinsolData->size, xScaling), "xScaling", LOG_NLS_V, modelInfoGetEquation(&data->modelData->modelDataXml,eqSystemNumber)); infoStreamPrint(LOG_NLS_V, 0, "KINSOL F tolerance: %g", (*(KINMem)kinsolData->kinsolMemory).kin_fnormtol); infoStreamPrint(LOG_NLS_V, 0, "KINSOL minimal step size %g", (*(KINMem)kinsolData->kinsolMemory).kin_scsteptol); infoStreamPrint(LOG_NLS_V, 0, "KINSOL max iterations %d", 20*kinsolData->size); infoStreamPrint(LOG_NLS_V, 0, "KINSOL strategy %d", kinsolData->kinsolStrategy); infoStreamPrint(LOG_NLS_V, 0, "KINSOL current retry %d", kinsolData->retries); messageClose(LOG_NLS_V); return retValue; }
/*! \fn freeNonlinearSystems * * This function frees memory of nonlinear systems. * * \param [ref] [data] */ int freeNonlinearSystems(DATA *data, threadData_t *threadData) { TRACE_PUSH int i; NONLINEAR_SYSTEM_DATA* nonlinsys = data->simulationInfo.nonlinearSystemData; struct csvStats* stats; infoStreamPrint(LOG_NLS, 1, "free non-linear system solvers"); for(i=0; i<data->modelData.nNonLinearSystems; ++i) { free(nonlinsys[i].nlsx); free(nonlinsys[i].nlsxExtrapolation); free(nonlinsys[i].nlsxOld); free(nonlinsys[i].nominal); free(nonlinsys[i].min); free(nonlinsys[i].max); #if !defined(OMC_MINIMAL_RUNTIME) if (data->simulationInfo.nlsCsvInfomation) { stats = nonlinsys[i].csvData; omc_write_csv_free(stats->callStats); omc_write_csv_free(stats->iterStats); } #endif /* free solver data */ switch(data->simulationInfo.nlsMethod) { #if !defined(OMC_MINIMAL_RUNTIME) case NLS_HYBRID: freeHybrdData(&nonlinsys[i].solverData); break; case NLS_KINSOL: nls_kinsol_free(&nonlinsys[i]); break; case NLS_NEWTON: freeNewtonData(&nonlinsys[i].solverData); break; #endif case NLS_HOMOTOPY: freeHomotopyData(&nonlinsys[i].solverData); break; #if !defined(OMC_MINIMAL_RUNTIME) case NLS_MIXED: freeHomotopyData(&((struct dataNewtonAndHybrid*) nonlinsys[i].solverData)->newtonData); freeHybrdData(&((struct dataNewtonAndHybrid*) nonlinsys[i].solverData)->hybridData); break; #endif default: throwStreamPrint(threadData, "unrecognized nonlinear solver"); } free(nonlinsys[i].solverData); } messageClose(LOG_NLS); TRACE_POP return 0; }
static int simulationUpdate(DATA* data, threadData_t *threadData, SOLVER_INFO* solverInfo) { prefixedName_updateContinuousSystem(data, threadData); if (solverInfo->solverMethod == S_SYM_IMP_EULER) data->callback->symEulerUpdate(data, solverInfo->solverStepSize); saveZeroCrossings(data, threadData); /***** Event handling *****/ if (measure_time_flag) rt_tick(SIM_TIMER_EVENT); int syncRet = handleTimers(data, threadData, solverInfo); int syncRet1; do { int eventType = checkEvents(data, threadData, solverInfo->eventLst, !solverInfo->solverRootFinding, /*out*/ &solverInfo->currentTime); if(eventType > 0 || syncRet == 2) /* event */ { threadData->currentErrorStage = ERROR_EVENTHANDLING; infoStreamPrint(LOG_EVENTS, 1, "%s event at time=%.12g", eventType == 1 ? "time" : "state", solverInfo->currentTime); /* prevent emit if noEventEmit flag is used */ if (!(omc_flag[FLAG_NOEVENTEMIT])) /* output left limit */ sim_result.emit(&sim_result, data, threadData); handleEvents(data, threadData, solverInfo->eventLst, &(solverInfo->currentTime), solverInfo); cleanUpOldValueListAfterEvent(data, solverInfo->currentTime); messageClose(LOG_EVENTS); threadData->currentErrorStage = ERROR_SIMULATION; solverInfo->didEventStep = 1; overwriteOldSimulationData(data); } else /* no event */ { solverInfo->laststep = solverInfo->currentTime; solverInfo->didEventStep = 0; } if (measure_time_flag) rt_accumulate(SIM_TIMER_EVENT); /***** End event handling *****/ /***** check state selection *****/ if (stateSelection(data, threadData, 1, 1)) { /* if new set is calculated reinit the solver */ solverInfo->didEventStep = 1; overwriteOldSimulationData(data); } /* Check for warning of variables out of range assert(min<x || x>xmax, ...)*/ data->callback->checkForAsserts(data, threadData); storePreValues(data); storeOldValues(data); syncRet1 = handleTimers(data, threadData, solverInfo); syncRet = syncRet1 == 0 ? syncRet : syncRet1; } while (syncRet1); return syncRet; }
void debugStringLS(int logName, char* message) { if(ACTIVE_STREAM(logName)) { infoStreamPrint(logName, 1, "%s", message); messageClose(logName); } }
void debugIntLS(int logName, char* message, int value) { if(ACTIVE_STREAM(logName)) { infoStreamPrint(logName, 1, "%s %d", message, value); messageClose(logName); } }
/*! \fn damping_heuristic * * first damping heuristic: * x_increment will be halved until the Euclidean norm of the residual function * is smaller than the Euclidean norm of the current point * * treshold for damping = 0.01 * compiler flag: -newton = damped */ void damping_heuristic(double* x, int(*f)(int*, double*, double*, void*, int), double current_fvec_enorm, int* n, double* fvec, double* lambda, int* k, DATA_NEWTON* solverData, void* userdata) { int i,j=0; double enorm_new, treshold = 1e-2; /* calculate new function values */ (*f)(n, solverData->x_new, fvec, userdata, 1); solverData->nfev++; enorm_new=enorm_(n,fvec); if (enorm_new >= current_fvec_enorm) infoStreamPrint(LOG_NLS_V, 1, "Start Damping: enorm_new : %e; current_fvec_enorm: %e ", enorm_new, current_fvec_enorm); while (enorm_new >= current_fvec_enorm) { j++; *lambda*=0.5; for (i=0; i<*n; i++) solverData->x_new[i]=x[i]-*lambda*solverData->x_increment[i]; /* calculate new function values */ (*f)(n, solverData->x_new, fvec, userdata, 1); solverData->nfev++; enorm_new=enorm_(n,fvec); if (*lambda <= treshold) { warningStreamPrint(LOG_NLS_V, 0, "Warning: lambda reached a threshold."); /* if damping is without success, trying full newton step; after 5 full newton steps try a very little step */ if (*k >= 5) for (i=0; i<*n; i++) solverData->x_new[i]=x[i]-*lambda*solverData->x_increment[i]; else for (i=0; i<*n; i++) solverData->x_new[i]=x[i]-solverData->x_increment[i]; /* calculate new function values */ (*f)(n, solverData->x_new, fvec, userdata, 1); solverData->nfev++; (*k)++; break; } } *lambda = 1; messageClose(LOG_NLS_V); }
int MultFive_checkForDiscreteChanges(DATA *data) { int needToIterate = 0; infoStreamPrint(LOG_EVENTS_V, 1, "check for discrete changes"); if (ACTIVE_STREAM(LOG_EVENTS_V)) messageClose(LOG_EVENTS_V); return needToIterate; }
/*! \fn printVector * * \param [in] [vector] * \param [in] [size] * \param [in] [logLevel] * \param [in] [name] * * \author wbraun */ static void printVector(const double *vector, const integer *size, const int logLevel, const char *name) { int i; if (!ACTIVE_STREAM(logLevel)) return; infoStreamPrint(logLevel, 1, "%s", name); for(i=0; i<*size; i++) infoStreamPrint(logLevel, 0, "[%2d] %20.12g", i, vector[i]); messageClose(logLevel); }
static void nlsKinsolInfoPrint(const char *module, const char *function, char *msg, void *user_data) { if (ACTIVE_STREAM(LOG_NLS_V)) { warningStreamPrint(LOG_NLS_V, 1, "%s %s:", module, function); warningStreamPrint(LOG_NLS_V, 0, "%s", msg); messageClose(LOG_NLS_V); } }
/*! \fn printNonLinearSystemSolvingStatistics * * This function prints memory for all non-linear systems. * * \param [ref] [data] * [in] [sysNumber] index of corresponding non-linear system */ void printNonLinearSystemSolvingStatistics(DATA *data, int sysNumber, int logLevel) { NONLINEAR_SYSTEM_DATA* nonlinsys = data->simulationInfo->nonlinearSystemData; infoStreamPrint(logLevel, 1, "Non-linear system %d of size %d solver statistics:", (int)nonlinsys[sysNumber].equationIndex, (int)nonlinsys[sysNumber].size); infoStreamPrint(logLevel, 0, " number of calls : %ld", nonlinsys[sysNumber].numberOfCall); infoStreamPrint(logLevel, 0, " number of iterations : %ld", nonlinsys[sysNumber].numberOfIterations); infoStreamPrint(logLevel, 0, " number of function evaluations : %ld", nonlinsys[sysNumber].numberOfFEval); infoStreamPrint(logLevel, 0, " average time per call : %f", nonlinsys[sysNumber].totalTime/nonlinsys[sysNumber].numberOfCall); infoStreamPrint(logLevel, 0, " total time : %f", nonlinsys[sysNumber].totalTime); messageClose(logLevel); }
/* \fn printCurrentStatesVector(int logLevel, double* y, DATA* data, double time) * * \param [in] [logLevel] * \param [in] [states] * \param [in] [data] * \param [in] [time] * * This function outputs states vector. * */ int printCurrentStatesVector(int logLevel, double* states, DATA* data, double time) { int i; infoStreamPrint(logLevel, 1, "states at time=%g", time); for(i=0;i<data->modelData->nStates;++i) { infoStreamPrint(logLevel, 0, "%d. %s = %g", i+1, data->modelData->realVarsData[i].info.name, states[i]); } messageClose(logLevel); return 0; }
/* \fn printVector(int logLevel, double* y, DATA* data, double time) * * \param [in] [logLevel] * \param [in] [name] * \param [in] [vec] * \param [in] [size] * \param [in] [time] * * This function outputs a vector of size * */ int printVector(int logLevel, const char* name, double* vec, int n, double time) { int i; infoStreamPrint(logLevel, 1, "%s at time=%g", name, time); for(i=0; i<n; ++i) { infoStreamPrint(logLevel, 0, "%d. %g", i+1, vec[i]); } messageClose(logLevel); return 0; }
/*! \fn printRelationsDebug * * print all relations * * \param [in] [data] * \param [in] [stream] */ void printRelationsDebug(DATA *data, int stream) { TRACE_PUSH long i; debugStreamPrint(stream, 1, "status of relations at time=%.12g", data->localData[0]->timeValue); for(i=0; i<data->modelData.nRelations; i++) debugStreamPrint(stream, 0, "[%ld] %s = %c | pre(%s) = %c", i, data->callback->relationDescription(i), data->simulationInfo.relations[i] ? 'T' : 'F', data->callback->relationDescription(i), data->simulationInfo.relationsPre[i] ? 'T' : 'F'); messageClose(stream); TRACE_POP }
static void nlsKinsolErrorPrint(int errorCode, const char *module, const char *function, char *msg, void *userData) { NLS_KINSOL_DATA *kinsolData = (NLS_KINSOL_DATA*) userData; DATA* data = kinsolData->userData.data; int sysNumber = kinsolData->userData.sysNumber; long eqSystemNumber = data->simulationInfo->nonlinearSystemData[sysNumber].equationIndex; if (ACTIVE_STREAM(LOG_NLS)) { warningStreamPrint(LOG_NLS, 1, "kinsol failed for %d", modelInfoGetEquation(&data->modelData->modelDataXml,eqSystemNumber).id); warningStreamPrint(LOG_NLS, 0, "[module] %s | [function] %s | [error_code] %d", module, function, errorCode); warningStreamPrint(LOG_NLS, 0, "%s", msg); messageClose(LOG_NLS); } }
/*! \fn printAllVars * * prints all variable values * * \param [in] [data] * \param [in] [ringSegment] * \param [in] [stream] * * \author wbraun */ void printAllVars(DATA *data, int ringSegment, int stream) { TRACE_PUSH long i; MODEL_DATA *mData = &(data->modelData); SIMULATION_INFO *sInfo = &(data->simulationInfo); if (!ACTIVE_STREAM(stream)) return; infoStreamPrint(stream, 1, "Print values for buffer segment %d regarding point in time : %g", ringSegment, data->localData[ringSegment]->timeValue); infoStreamPrint(stream, 1, "states variables"); for(i=0; i<mData->nStates; ++i) infoStreamPrint(stream, 0, "%ld: %s = %g (pre: %g)", i+1, mData->realVarsData[i].info.name, data->localData[ringSegment]->realVars[i], sInfo->realVarsPre[i]); messageClose(stream); infoStreamPrint(stream, 1, "derivatives variables"); for(i=mData->nStates; i<2*mData->nStates; ++i) infoStreamPrint(stream, 0, "%ld: %s = %g (pre: %g)", i+1, mData->realVarsData[i].info.name, data->localData[ringSegment]->realVars[i], sInfo->realVarsPre[i]); messageClose(stream); infoStreamPrint(stream, 1, "other real values"); for(i=2*mData->nStates; i<mData->nVariablesReal; ++i) infoStreamPrint(stream, 0, "%ld: %s = %g (pre: %g)", i+1, mData->realVarsData[i].info.name, data->localData[ringSegment]->realVars[i], sInfo->realVarsPre[i]); messageClose(stream); infoStreamPrint(stream, 1, "integer variables"); for(i=0; i<mData->nVariablesInteger; ++i) infoStreamPrint(stream, 0, "%ld: %s = %ld (pre: %ld)", i+1, mData->integerVarsData[i].info.name, data->localData[ringSegment]->integerVars[i], sInfo->integerVarsPre[i]); messageClose(stream); infoStreamPrint(stream, 1, "boolean variables"); for(i=0; i<mData->nVariablesBoolean; ++i) infoStreamPrint(stream, 0, "%ld: %s = %s (pre: %s)", i+1, mData->booleanVarsData[i].info.name, data->localData[ringSegment]->booleanVars[i] ? "true" : "false", sInfo->booleanVarsPre[i] ? "true" : "false"); messageClose(stream); infoStreamPrint(stream, 1, "string variables"); for(i=0; i<mData->nVariablesString; ++i) infoStreamPrint(stream, 0, "%ld: %s = %s (pre: %s)", i+1, mData->stringVarsData[i].info.name, MMC_STRINGDATA(data->localData[ringSegment]->stringVars[i]), MMC_STRINGDATA(sInfo->stringVarsPre[i])); messageClose(stream); messageClose(stream); TRACE_POP }
/*! \fn check_mixed_solutions * This function checks whether some of the mixed systems * are failed to solve. If one is failed it returns 1 otherwise 0. * * \param [in] [data] * \param [in] [printFailingSystems] * * \author wbraun */ int check_mixed_solutions(DATA *data, int printFailingSystems) { MIXED_SYSTEM_DATA* system = data->simulationInfo->mixedSystemData; int i, j, retVal=0; for(i=0; i<data->modelData->nMixedSystems; ++i) if(system[i].solved == 0) { retVal = 1; if(printFailingSystems && ACTIVE_WARNING_STREAM(LOG_NLS)) { warningStreamPrint(LOG_NLS, 1, "mixed system fails: %d at t=%g", modelInfoGetEquation(&data->modelData->modelDataXml, system->equationIndex).id, data->localData[0]->timeValue); messageClose(LOG_NLS); } } return retVal; }
void printErrors(double delta_x, double delta_x_scaled, double delta_f, double error_f, double scaledError_f, double* eps) { infoStreamPrint(LOG_NLS_V, 1, "errors "); infoStreamPrint(LOG_NLS_V, 0, "delta_x = %e \ndelta_x_scaled = %e \ndelta_f = %e \nerror_f = %e \nscaledError_f = %e", delta_x, delta_x_scaled, delta_f, error_f, scaledError_f); if (delta_x < *eps) infoStreamPrint(LOG_NLS_V, 0, "delta_x reached eps"); if (delta_x_scaled < *eps) infoStreamPrint(LOG_NLS_V, 0, "delta_x_scaled reached eps"); if (delta_f < *eps) infoStreamPrint(LOG_NLS_V, 0, "delta_f reached eps"); if (error_f < *eps) infoStreamPrint(LOG_NLS_V, 0, "error_f reached eps"); if (scaledError_f < *eps) infoStreamPrint(LOG_NLS_V, 0, "scaledError_f reached eps"); messageClose(LOG_NLS_V); }
void printLisMatrixCSR(LIS_MATRIX A, int n) { char buffer[16384]; int i, j; /* A matrix */ infoStreamPrint(LOG_LS_V, 1, "A matrix [%dx%d] nnz = %d ", n, n, A->nnz); for(i=0; i<n; i++) { buffer[0] = 0; for(j=A->ptr[i]; j<A->ptr[i+1]; j++){ sprintf(buffer, "%s(%d,%d,%g) ", buffer, i, A->index[j], A->value[j]); } infoStreamPrint(LOG_LS_V, 0, "%s", buffer); } messageClose(LOG_LS_V); }
/*! \fn int updateStaticDataOfNonlinearSystems(DATA *data) * * This function allocates memory for all nonlinear systems. * * \param [ref] [data] */ int updateStaticDataOfNonlinearSystems(DATA *data, threadData_t *threadData) { TRACE_PUSH int i; int size; NONLINEAR_SYSTEM_DATA *nonlinsys = data->simulationInfo->nonlinearSystemData; struct dataNewtonAndHybrid *mixedSolverData; infoStreamPrint(LOG_NLS, 1, "update static data of non-linear system solvers"); for(i=0; i<data->modelData->nNonLinearSystems; ++i) { nonlinsys[i].initializeStaticNLSData(data, threadData, &nonlinsys[i]); } messageClose(LOG_NLS); TRACE_POP return 0; }
void debugVectorDoubleLS(int logName, char* vectorName, double* vector, int n) { if(ACTIVE_STREAM(logName)) { int i; char buffer[4096]; infoStreamPrint(logName, 1, "%s [%d-dim]", vectorName, n); buffer[0] = 0; for(i=0; i<n; i++) { if (vector[i]<-1e+300) sprintf(buffer, "%s -INF ", buffer); else if (vector[i]>1e+300) sprintf(buffer, "%s +INF ", buffer); else sprintf(buffer, "%s%16.8g ", buffer, vector[i]); } infoStreamPrint(logName, 0, "%s", buffer); messageClose(logName); } }
/*! \fn comparePivot * * ??? desc ??? * * \param [ref] [oldPivot] * \param [ref] [newPivot] * \param [ref] [nCandidates] * \param [ref] [nDummyStates] * \param [ref] [nStates] * \param [ref] [A] * \param [ref] [states] * \param [ref] [statecandidates] * \param [ref] [data] * \return ??? */ static int comparePivot(modelica_integer *oldPivot, modelica_integer *newPivot, modelica_integer nCandidates, modelica_integer nDummyStates, modelica_integer nStates, VAR_INFO* A, VAR_INFO** states, VAR_INFO** statecandidates, DATA *data, int switchStates) { TRACE_PUSH modelica_integer i; int ret = 0; modelica_integer* oldEnable = (modelica_integer*) calloc(nCandidates, sizeof(modelica_integer)); modelica_integer* newEnable = (modelica_integer*) calloc(nCandidates, sizeof(modelica_integer)); for(i=0; i<nCandidates; i++) { modelica_integer entry = (i < nDummyStates) ? 1: 2; newEnable[ newPivot[i] ] = entry; oldEnable[ oldPivot[i] ] = entry; } for(i=0; i<nCandidates; i++) { if(newEnable[i] != oldEnable[i]) { if(switchStates) { infoStreamPrint(LOG_DSS, 1, "select new states at time %f", data->localData[0]->timeValue); setAMatrix(newEnable, nCandidates, nStates, A, states, statecandidates, data); messageClose(LOG_DSS); } ret = -1; break; } } free(oldEnable); free(newEnable); TRACE_POP return ret; }
int nlsKinsolSolve(DATA *data, threadData_t *threadData, int sysNumber) { NONLINEAR_SYSTEM_DATA *nlsData = &(data->simulationInfo->nonlinearSystemData[sysNumber]); NLS_KINSOL_DATA *kinsolData = (NLS_KINSOL_DATA*)nlsData->solverData; long eqSystemNumber = nlsData->equationIndex; int indexes[2] = {1,eqSystemNumber}; int flag, i; long nFEval; int success = 0; int retry = 0; double *xStart = NV_DATA_S(kinsolData->initialGuess); double *xScaling = NV_DATA_S(kinsolData->xScale); double *fScaling = NV_DATA_S(kinsolData->fScale); double fNormValue; /* set user data */ kinsolData->userData.data = data; kinsolData->userData.threadData = threadData; kinsolData->userData.sysNumber = sysNumber; /* reset configuration settings */ nlsKinsolConfigSetup(kinsolData); infoStreamPrint(LOG_NLS, 0, "------------------------------------------------------"); infoStreamPrintWithEquationIndexes(LOG_NLS, 1, indexes, "Start solving non-linear system >>%ld<< using Kinsol solver at time %g", eqSystemNumber, data->localData[0]->timeValue); nlsKinsolResetInitial(data, kinsolData, nlsData, INITIAL_EXTRAPOLATION); /* set x scaling */ nlsKinsolXScaling(data, kinsolData, nlsData, SCALING_NOMINALSTART); /* set f scaling */ _omc_fillVector(_omc_createVector(nlsData->size, fScaling), 1.); /* */ do{ /* dump configuration */ nlsKinsolConfigPrint(kinsolData, nlsData); flag = KINSol(kinsolData->kinsolMemory, /* KINSol memory block */ kinsolData->initialGuess, /* initial guess on input; solution vector */ kinsolData->kinsolStrategy, /* global strategy choice */ kinsolData->xScale, /* scaling vector, for the variable cc */ kinsolData->fScale); /* scaling vector for function values fval */ infoStreamPrint(LOG_NLS_V, 0, "KINSol finished with errorCode %d.", flag); /* check for errors */ if(flag < 0) { retry = nlsKinsolErrorHandler(flag, data, nlsData, kinsolData); } /* solution found */ if ((flag == KIN_SUCCESS) || (flag == KIN_INITIAL_GUESS_OK) || (flag == KIN_STEP_LT_STPTOL)) { success = 1; } kinsolData->retries++; /* write statistics */ KINGetNumNonlinSolvIters(kinsolData->kinsolMemory, &nFEval); nlsData->numberOfIterations += nFEval; nlsData->numberOfFEval += kinsolData->countResCalls; infoStreamPrint(LOG_NLS_V, 0, "Next try? success = %d, retry = %d, retries = %d = %s\n", success, retry, kinsolData->retries,!success && !(retry<1) && kinsolData->retries<RETRY_MAX ? "true" : "false" ); }while(!success && !(retry<0) && kinsolData->retries < RETRY_MAX); /* solution found */ if (success) { /* check if solution really solves the residuals */ nlsKinsolResiduals(kinsolData->initialGuess, kinsolData->fRes, &kinsolData->userData); fNormValue = N_VWL2Norm(kinsolData->fRes, kinsolData->fRes); infoStreamPrint(LOG_NLS, 0, "scaled Euclidean norm of F(u) = %e", fNormValue); if (FTOL_WITH_LESS_ACCURANCY<fNormValue) { warningStreamPrint(LOG_NLS, 0, "False positive solution. FNorm is too small."); success = 0; } else /* solved system for reuse linear solver information */ { kinsolData->solved = 1; } /* copy solution */ memcpy(nlsData->nlsx, xStart, nlsData->size*(sizeof(double))); /* dump solution */ if(ACTIVE_STREAM(LOG_NLS)) { infoStreamPrintWithEquationIndexes(LOG_NLS, 1, indexes, "solution for NLS %ld at t=%g", eqSystemNumber, kinsolData->userData.data->localData[0]->timeValue); for(i=0; i<nlsData->size; ++i) { infoStreamPrintWithEquationIndexes(LOG_NLS, 0, indexes, "[%d] %s = %g", i+1, modelInfoGetEquation(&kinsolData->userData.data->modelData->modelDataXml,eqSystemNumber).vars[i], nlsData->nlsx[i]); } messageClose(LOG_NLS); } } messageClose(LOG_NLS); return success; }
/* * function calculates a jacobian matrix by * numerical method finite differences with coloring * into a sparse SlsMat matrix */ static int nlsSparseJac(N_Vector vecX, N_Vector vecFX, SlsMat Jac, void *userData, N_Vector tmp1, N_Vector tmp2) { NLS_KINSOL_USERDATA *kinsolUserData = (NLS_KINSOL_USERDATA*) userData; DATA* data = kinsolUserData->data; threadData_t *threadData = kinsolUserData->threadData; int sysNumber = kinsolUserData->sysNumber; NONLINEAR_SYSTEM_DATA *nlsData = &(data->simulationInfo->nonlinearSystemData[sysNumber]); NLS_KINSOL_DATA* kinsolData = (NLS_KINSOL_DATA*) nlsData->solverData; /* prepare variables */ double *x = N_VGetArrayPointer(vecX); double *fx = N_VGetArrayPointer(vecFX); double *xsave = N_VGetArrayPointer(tmp1); double *delta_hh = N_VGetArrayPointer(tmp2); double *xScaling = NV_DATA_S(kinsolData->xScale); double *fRes = NV_DATA_S(kinsolData->fRes); SPARSE_PATTERN* sparsePattern = &(nlsData->sparsePattern); const double delta_h = sqrt(DBL_EPSILON*2e1); long int i,j,ii; int nth = 0; /* performance measurement */ rt_ext_tp_tick(&nlsData->jacobianTimeClock); /* reset matrix */ SlsSetToZero(Jac); for(i = 0; i < sparsePattern->maxColors; i++) { for(ii=0; ii < kinsolData->size; ii++) { if(sparsePattern->colorCols[ii]-1 == i) { xsave[ii] = x[ii]; delta_hh[ii] = delta_h * (fabs(xsave[ii]) + 1.0); if ((xsave[ii] + delta_hh[ii] >= nlsData->max[ii])) delta_hh[ii] *= -1; x[ii] += delta_hh[ii]; /* Calculate scaled difference quotient */ delta_hh[ii] = 1. / delta_hh[ii]; } } nlsKinsolResiduals(vecX, kinsolData->fRes, userData); for(ii = 0; ii < kinsolData->size; ii++) { if(sparsePattern->colorCols[ii]-1 == i) { nth = sparsePattern->leadindex[ii]; while(nth < sparsePattern->leadindex[ii+1]) { j = sparsePattern->index[nth]; setJacElementKluSparse(j, ii, (fRes[j] - fx[j]) * delta_hh[ii], nth, Jac); nth++; }; x[ii] = xsave[ii]; } } } /* finish sparse matrix */ finishSparseColPtr(Jac); /* debug */ if (ACTIVE_STREAM(LOG_NLS_JAC)){ infoStreamPrint(LOG_NLS_JAC, 1, "##KINSOL## Sparse Matrix."); PrintSparseMat(Jac); nlsKinsolJacSumSparse(Jac); messageClose(LOG_NLS_JAC); } /* performance measurement and statistics */ nlsData->jacobianTime += rt_ext_tp_tock(&(nlsData->jacobianTimeClock)); nlsData->numberOfJEval++; return 0; }