void SimManager::computeSampleCycles() { int counter = 0; time_event_type timeEventPairs; ///< - Contains start times and time spans _timeevent_system->getTimeEvent(timeEventPairs); std::vector<std::pair<double, double> >::iterator iter; iter = timeEventPairs.begin(); for (; iter != timeEventPairs.end(); ++iter) { if (iter->first != 0.0 || iter->second == 0.0) { throw ModelicaSimulationError(SIMMANAGER,"Time event not starting at t=0.0 or not cyclic!"); } else { // Check if sample time is a multiple of the cycle time (with a tolerance) if ((iter->second / _config->getGlobalSettings()->gethOutput()) - int((iter->second / _config->getGlobalSettings()->gethOutput()) + 0.5) <= 1e6 * UROUND) { _sampleCycles[counter] = int((iter->second / _config->getGlobalSettings()->gethOutput()) + 0.5); } else { throw ModelicaSimulationError(SIMMANAGER,"Sample time is not a multiple of the cycle time!"); } } counter++; } }
/// (Re-) initialize the system of equations void AlgLoopDefaultImplementation::initialize() { // Anfangswerte einlesen: InitialValue = ConstrValue // und Dimension der Bindungsgleichungen zur Lösung der Schleife bestimmen _dimAEq = 0; if(_constraintType ==IAlgLoop::REAL) { std::vector<double>::const_iterator constr_iter = __xd.begin(), constr_iter_end = __xd.end(); std::vector<double>::iterator init_iter = _xd_init.begin(); for (; constr_iter != constr_iter_end; ++constr_iter) { *init_iter++ = *constr_iter; ++_dimAEq; } } else if(_constraintType == IAlgLoop::INTEGER) { std::vector<int>::const_iterator constr_iter = __xi.begin(), constr_iter_end = __xi.end(); std::vector<int>::iterator init_iter = _xi_init.begin(); for (; constr_iter != constr_iter_end; ++constr_iter) { *init_iter++ = *constr_iter; ++_dimAEq; } } else if(_constraintType == IAlgLoop::BOOLEAN) { std::vector<bool>::const_iterator constr_iter = __xb.begin(), constr_iter_end = __xb.end(); std::vector<bool>::iterator init_iter = _xb_init.begin(); for (; constr_iter != constr_iter_end; ++constr_iter) { *init_iter++ = *constr_iter; ++_dimAEq; } } else throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,"AlgLoopDefaultImplementation::initialize(): Unknown _constraintType."); //nach default algloop verschieben // Prüfen ob min. eine Bindungsgleichung vorhanden if ( _dimAEq == 0 ) throw ModelicaSimulationError(ALGLOOP_EQ_SYSTEM,"AlgLoop::initialize(): No constraint defined."); };
void MeasureTimePAPI::getTimeValuesStartP(MeasureTimeValues *res) const { #ifdef USE_PAPI MeasureTimeValuesPAPI *val = static_cast<MeasureTimeValuesPAPI*>(res); // if (PAPI_reset(eventSet) != PAPI_OK) // { // std::cerr << "PAPI_reset - FAILED" << std::endl; // throw ModelicaSimulationError(UTILITY,"PAPI_reset_counters - FAILED"); // } long long values[NUM_PAPI_EVENTS]; if (PAPI_read(_eventSet, values) != PAPI_OK) { std::cerr << "PAPI_read_counters - FAILED" << std::endl; throw ModelicaSimulationError(UTILITY,"PAPI_read_counters - FAILED"); } // val->time = 0; // val->l2CacheMisses = 0; // val->instructions = 0; val->_time = values[0]; val->_l2CacheMisses = values[1]; val->_instructions = values[2]; #endif }
boost::weak_ptr<IMixedSystem> SimController::LoadModelicaSystem(PATH modelica_path,string modelKey) { if(_use_modelica_compiler) { // if the modell is already loaded std::map<string,boost::shared_ptr<IMixedSystem> >::iterator iter = _systems.find(modelKey); if(iter != _systems.end()) { // destroy simdata std::map<string,boost::shared_ptr<ISimData> >::iterator iter2 = _sim_data.find(modelKey); if(iter2 != _sim_data.end()) { _sim_data.erase(iter2); } // destroy system _systems.erase(iter); } boost::shared_ptr<ISimData> simData = getSimData(modelKey).lock(); boost::shared_ptr<ISimVars> simVars = getSimVars(modelKey).lock(); boost::shared_ptr<IMixedSystem> system = createModelicaSystem(modelica_path, modelKey, _config->getGlobalSettings(), _algloopsolverfactory, simData, simVars); _systems[modelKey] = system; return system; } else throw ModelicaSimulationError(SIMMANAGER,"No Modelica Compiler configured"); }
shared_ptr<ISimController> OMCFactory::loadSimControllerLib(PATH simcontroller_path, type_map simcontroller_type_map) { LOADERRESULT result = LoadLibrary(simcontroller_path, simcontroller_type_map); if (result != LOADER_SUCCESS) throw ModelicaSimulationError(MODEL_FACTORY,string("Failed loading SimConroller library!") + simcontroller_path); map<string, factory<ISimController,PATH,PATH> >::iterator iter; map<string, factory<ISimController,PATH,PATH> >& factories(simcontroller_type_map.get()); iter = factories.find("SimController"); if (iter ==factories.end()) throw ModelicaSimulationError(MODEL_FACTORY,"No such SimController library"); return shared_ptr<ISimController>(iter->second.create(_library_path, _modelicasystem_path)); }
MeasureTimePAPI::MeasureTimePAPI(unsigned long int (*threadHandle)()) : MeasureTime(), threadHandle(threadHandle) { _events = new int[NUM_PAPI_EVENTS]; #ifdef USE_PAPI _events[0] = PAPI_TOT_CYC; _events[1] = PAPI_L2_TCM; _events[2] = PAPI_TOT_INS; _eventSet = PAPI_NULL; int initRetVal = PAPI_library_init(PAPI_VER_CURRENT); if (initRetVal != PAPI_VER_CURRENT && initRetVal > 0) { std::cerr << "PAPI library init failed!" << std::endl; exit(1); } if (PAPI_thread_init(threadHandle) != PAPI_OK) { std::cerr << "PAPI thread init failed!" << std::endl; exit(1); } if (PAPI_create_eventset(&_eventSet) != PAPI_OK) { std::cerr << "PAPI create eventset failed!" << " Error: " << PAPI_create_eventset(&_eventSet) << std::endl; exit(1); } if (PAPI_add_events(_eventSet, _events, NUM_PAPI_EVENTS) != PAPI_OK) { std::cerr << "PAPI add events failed!" << std::endl; exit(1); } if (PAPI_start(_eventSet) != PAPI_OK) { std::cerr << "PAPI_start_counters - FAILED" << std::endl; throw ModelicaSimulationError(UTILITY,"PAPI_start_counters - FAILED"); } #else _eventSet = 0; throw ModelicaSimulationError(UTILITY,"Papi not supported!"); #endif }
double division (const double &a,const double &b, const char* text) { if(b != 0) return a/b ; else { std::string error_msg = "Division by zero: "; throw ModelicaSimulationError(UTILITY,error_msg+string(text)); } }
LoggerXMLTCP(std::string host, int port, LogSettings &logSettings) : LoggerXML(logSettings, true, _sstream) , _endpoint(boost::asio::ip::address::from_string(host), port) , _socket(_ios) { if (logSettings.format != LF_XML && logSettings.format != LF_XMLTCP) { throw ModelicaSimulationError(MODEL_FACTORY, "xmltcp logger requires log-format xml"); } _socket.connect(_endpoint); }
boost::weak_ptr<IMixedSystem> SimController::getSystem(string modelname) { std::map<string,boost::shared_ptr<IMixedSystem> >::iterator iter = _systems.find(modelname); if(iter!=_systems.end()) { return iter->second; } else { string error = string("Simulation data was not found for model: ") + modelname; throw ModelicaSimulationError(SIMMANAGER,error); } }
double division (const double &a,const double &b, bool throwEx,const char* text) { if(b != 0) return a/b ; else { std::string error_msg = "Division by zero: "; if(throwEx) throw ModelicaSimulationError(UTILITY,error_msg+string(text)); else { // LOGGER_WRITE("Division: Solver will try to handle division by zero for" + string(text), LC_INIT, LL_DEBUG); return a; } } }
double division (const double &a,const double &b, bool throwEx,const char* text) { if(b != 0) return a/b ; else { if(a==0) { //LOGGER_WRITE("Division by Zero: Solver will try to handle division by zero with minimu norm for" + string(text), LC_INIT, LL_DEBUG); return 0; } if(throwEx) throw ModelicaSimulationError(UTILITY,"Division by zero: "+string(text)); else { //LOGGER_WRITE("Division: Solver will try to handle division by zero for" + string(text), LC_INIT, LL_DEBUG); return a; } } }
/// Creates a solver according to given system of equations of type algebraic loop boost::shared_ptr<IAlgLoopSolver> AlgLoopSolverFactory::createAlgLoopSolver(IAlgLoop* algLoop) { if(algLoop->getDimReal() > 0) { #if defined(__vxworks) #else if(algLoop->isLinear()) { try { string linsolver_name = _global_settings->getSelectedLinSolver(); boost::shared_ptr<ILinSolverSettings> algsolversetting= createLinSolverSettings(linsolver_name); _linalgsolversettings.push_back(algsolversetting); boost::shared_ptr<IAlgLoopSolver> algsolver= createLinSolver(algLoop,linsolver_name,algsolversetting); _algsolvers.push_back(algsolver); return algsolver; } catch(std::exception &arg) { //the linear solver was not found -> take the nonlinear solver } } #endif string nonlinsolver_name = _global_settings->getSelectedNonLinSolver(); boost::shared_ptr<INonLinSolverSettings> algsolversetting= createNonLinSolverSettings(nonlinsolver_name); _algsolversettings.push_back(algsolversetting); boost::shared_ptr<IAlgLoopSolver> algsolver= createNonLinSolver(algLoop,nonlinsolver_name,algsolversetting); _algsolvers.push_back(algsolver); return algsolver; } else { // TODO: Throw an error message here. throw ModelicaSimulationError(MODEL_FACTORY,"AlgLoop solver is not available"); } }
// Added for real-time simulation using VxWorks and Bodas void SimController::StartVxWorks(SimSettings simsettings,string modelKey) { try { boost::shared_ptr<IMixedSystem> mixedsystem = getSystem(modelKey).lock(); IGlobalSettings* global_settings = _config->getGlobalSettings(); global_settings->useEndlessSim(true); global_settings->setStartTime(simsettings.start_time); global_settings->setEndTime(simsettings.end_time); global_settings->sethOutput(simsettings.step_size); global_settings->setResultsFileName(simsettings.outputfile_name); global_settings->setSelectedLinSolver(simsettings.linear_solver_name); global_settings->setSelectedNonLinSolver(simsettings.nonlinear_solver_name); global_settings->setSelectedSolver(simsettings.solver_name); global_settings->setAlarmTime(simsettings.timeOut); global_settings->setLogSettings(simsettings.logSettings); global_settings->setOutputPointType(simsettings.outputPointType); /*boost::shared_ptr<SimManager>*/ _simMgr = boost::shared_ptr<SimManager>(new SimManager(mixedsystem, _config.get())); ISolverSettings* solver_settings = _config->getSolverSettings(); solver_settings->setLowerLimit(simsettings.lower_limit); solver_settings->sethInit(simsettings.lower_limit); solver_settings->setUpperLimit(simsettings.upper_limit); solver_settings->setRTol(simsettings.tolerance); solver_settings->setATol(simsettings.tolerance); _simMgr->initialize(); } catch( ModelicaSimulationError& ex) { string error = add_error_info(string("Simulation failed for ") + simsettings.outputfile_name,ex.what(),ex.getErrorID()); printf("Fehler %s\n", error.c_str()); throw ModelicaSimulationError(SIMMANAGER,error); } }
void SimManager::runSingleStep() { // Increase time event counter double cycletime = _config->getGlobalSettings()->gethOutput(); if (_dimtimeevent && cycletime > 0.0) { if (_lastCycleTime && cycletime != _lastCycleTime) throw ModelicaSimulationError(SIMMANAGER,"Cycle time can not be changed, if time events (samples) are present!"); else _lastCycleTime = cycletime; for (int i = 0; i < _dimtimeevent; i++) { if (_cycleCounter % _sampleCycles[i] == 0) _timeEventCounter[i]++; } // Handle time event _timeevent_system->handleTimeEvent(_timeEventCounter); _cont_system->evaluateAll(IContinuous::CONTINUOUS); _event_system->saveAll(); _timeevent_system->handleTimeEvent(_timeEventCounter); } // Solve _solver->solve(_solverTask); _cycleCounter++; // Reset everything to prevent overflows if (_cycleCounter == _resetCycle + 1) { _cycleCounter = 1; for (int i = 0; i < _dimtimeevent; i++) _timeEventCounter[i] = 0; } }
void SystemDefaultImplementation::Terminate(string msg) { throw ModelicaSimulationError(MODEL_EQ_SYSTEM,msg); }
void Arkode::initialize() { _properties = dynamic_cast<ISystemProperties*>(_system); _continuous_system = dynamic_cast<IContinuous*>(_system); _event_system = dynamic_cast<IEvent*>(_system); _mixed_system = dynamic_cast<IMixedSystem*>(_system); _time_system = dynamic_cast<ITime*>(_system); IGlobalSettings* global_settings = dynamic_cast<ISolverSettings*>(_arkodesettings)->getGlobalSettings(); // Kennzeichnung, dass initialize()() (vor der Integration) aufgerufen wurde _idid = 5000; _tLastEvent = 0.0; _event_n = 0; SolverDefaultImplementation::initialize(); _dimSys = _continuous_system->getDimContinuousStates(); _dimZeroFunc = _event_system->getDimZeroFunc(); if (_dimSys == 0) _dimSys = 1; // introduce dummy state if (_dimSys <= 0) { _idid = -1; throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); } else { // Allocate state vectors, stages and temporary arrays if (_z) delete[] _z; if (_zInit) delete[] _zInit; if (_zWrite) delete[] _zWrite; if (_zeroSign) delete[] _zeroSign; if (_absTol) delete[] _absTol; if(_delta) delete [] _delta; if(_deltaInv) delete [] _deltaInv; if(_ysave) delete [] _ysave; _z = new double[_dimSys]; _zInit = new double[_dimSys]; _zWrite = new double[_dimSys]; _zeroSign = new int[_dimZeroFunc]; _absTol = new double[_dimSys]; _delta =new double[_dimSys]; _deltaInv =new double[_dimSys]; _ysave =new double[_dimSys]; memset(_z, 0, _dimSys * sizeof(double)); memset(_zInit, 0, _dimSys * sizeof(double)); memset(_ysave, 0, _dimSys * sizeof(double)); // Counter initialisieren _outStps = 0; if (_arkodesettings->getDenseOutput()) { // Ausgabeschrittweite _hOut = global_settings->gethOutput(); } // Allocate memory for the solver //arkodeCreate _arkodeMem = ARKodeCreate(); /* if (check_flag((void*) _cvodeMem, "CVodeCreate", 0)) { _idid = -5; throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); } */ // // Make Cvode ready for integration // // Set initial values for CVODE _continuous_system->evaluateAll(IContinuous::CONTINUOUS); _continuous_system->getContinuousStates(_zInit); memcpy(_z, _zInit, _dimSys * sizeof(double)); // Get nominal values _absTol[0] = 1.0; // in case of dummy state _continuous_system->getNominalStates(_absTol); for (int i = 0; i < _dimSys; i++) _absTol[i] *= dynamic_cast<ISolverSettings*>(_arkodesettings)->getATol(); _ARK_y0 = N_VMake_Serial(_dimSys, _zInit); _ARK_y = N_VMake_Serial(_dimSys, _z); _ARK_yWrite = N_VMake_Serial(_dimSys, _zWrite); _ARK_absTol = N_VMake_Serial(_dimSys, _absTol); /* if (check_flag((void*) _CV_y0, "N_VMake_Serial", 0)) { _idid = -5; throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); } */ // Initialize Cvode (Initial values are required) _idid = ARKodeInit(_arkodeMem, NULL, ARK_fCallback, _tCurrent, _ARK_y0); if (_idid < 0) { _idid = -5; throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); } // Set Tolerances _idid = ARKodeSVtolerances(_arkodeMem, dynamic_cast<ISolverSettings*>(_arkodesettings)->getRTol(), _ARK_absTol); // RTOL and ATOL if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::initialize()"); // Set the pointer to user-defined data _idid = ARKodeSetUserData(_arkodeMem, _data); if (_idid < 0) throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); _idid = ARKodeSetInitStep(_arkodeMem, 1e-6); // INITIAL STEPSIZE if (_idid < 0) throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); _idid = ARKodeSetMaxConvFails(_arkodeMem, 100); // Maximale Fehler im Konvergenztest if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVoder::initialize()"); _idid = ARKodeSetMinStep(_arkodeMem, dynamic_cast<ISolverSettings*>(_arkodesettings)->getLowerLimit()); // MINIMUM STEPSIZE if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::initialize()"); _idid = ARKodeSetMaxStep(_arkodeMem, global_settings->getEndTime() / 10.0); // MAXIMUM STEPSIZE if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::initialize()"); _idid = ARKodeSetMaxNonlinIters(_arkodeMem, 5); // Max number of iterations if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::initialize()"); _idid = ARKodeSetMaxErrTestFails(_arkodeMem, 100); if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::initialize()"); _idid = ARKodeSetMaxNumSteps(_arkodeMem, 1000); // Max Number of steps if (_idid < 0) throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); // Initialize linear solver /* #ifdef USE_SUNDIALS_LAPACK _idid = CVLapackDense(_cvodeMem, _dimSys); #else */ _idid = ARKDense(_arkodeMem, _dimSys); /* #endif */ if (_idid < 0) throw ModelicaSimulationError(SOLVER,"Cvode::initialize()"); // Use own jacobian matrix // Check if Colored Jacobians are worth to use if (_idid < 0) throw ModelicaSimulationError(SOLVER,"ARKode::initialize()"); if (_dimZeroFunc) { _idid = ARKodeRootInit(_arkodeMem, _dimZeroFunc, &ARK_ZerofCallback); memset(_zeroSign, 0, _dimZeroFunc * sizeof(int)); _idid = ARKodeSetRootDirection(_arkodeMem, _zeroSign); if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::initialize()"); memset(_zeroSign, -1, _dimZeroFunc * sizeof(int)); memset(_zeroVal, -1, _dimZeroFunc * sizeof(int)); } _arkode_initialized = true; // // CVODE is ready for integration // // BOOST_LOG_SEV(cvode_lg::get(), cvode_info) << "CVode initialized"; } }
void Arkode::ArkodeCore() { _idid = ARKodeReInit(_arkodeMem, NULL, ARK_fCallback, _tCurrent, _ARK_y); _idid = ARKodeSetStopTime(_arkodeMem, _tEnd); _idid = ARKodeSetInitStep(_arkodeMem, 1e-12); if (_idid < 0) throw ModelicaSimulationError(SOLVER,"ARKode::ReInit"); bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); while (_solverStatus & ISolver::CONTINUE && !_interrupt ) { _ark_rt = ARKode(_arkodeMem, _tEnd, _ARK_y, &_tCurrent, ARK_ONE_STEP); _idid = ARKodeGetNumSteps(_arkodeMem, &_locStps); //if (_idid != CV_SUCCESS) // throw ModelicaSimulationError(SOLVER,"CVodeGetNumSteps failed. The cvode mem pointer is NULL"); _idid = ARKodeGetLastStep(_arkodeMem, &_h); //if (_idid != CV_SUCCESS) // throw ModelicaSimulationError(SOLVER,"CVodeGetLastStep failed. The cvode mem pointer is NULL"); //Check if there was at least one output-point within the last solver interval // -> Write output if true if (writeOutput) { writeArkodeOutput(_tCurrent, _h, _locStps); } //set completed step to system and check if terminate was called if(_continuous_system->stepCompleted(_tCurrent)) _solverStatus = DONE; // Perform state selection bool state_selection = stateSelection(); if (state_selection) _continuous_system->getContinuousStates(_z); _zeroFound = false; // Check if step was successful /* if (check_flag(&_cv_rt, "CVode", 1)) { _solverStatus = ISolver::SOLVERERROR; break; }*/ // A root was found if ((_ark_rt == ARK_ROOT_RETURN) && !isInterrupted()) { // CVode is setting _tCurrent to the time where the first event occurred double _abs = fabs(_tLastEvent - _tCurrent); _zeroFound = true; if ((_abs < 1e-3) && _event_n == 0) { _tLastEvent = _tCurrent; _event_n++; } else if ((_abs < 1e-3) && (_event_n >= 1 && _event_n < 500)) { _event_n++; } else if ((_abs >= 1e-3)) { //restart event counter _tLastEvent = _tCurrent; _event_n = 0; } else throw ModelicaSimulationError(EVENT_HANDLING,"Number of events exceeded in time interval " + to_string(_abs) + " at time " + to_string(_tCurrent)); // CVode has interpolated the states at time 'tCurrent' _time_system->setTime(_tCurrent); // To get steep steps in the result file, two value points (P1 and P2) must be added // // Y | (P2) X........... // | : // | : // |........X (P1) // |----------------------------------> // | ^ t // _tCurrent // Write the values of (P1) if (writeEventOutput) { _continuous_system->evaluateAll(IContinuous::CONTINUOUS); writeToFile(0, _tCurrent, _h); } _idid = ARKodeGetRootInfo(_arkodeMem, _zeroSign); for (int i = 0; i < _dimZeroFunc; i++) _events[i] = bool(_zeroSign[i]); if (_mixed_system->handleSystemEvents(_events)) { // State variables were reinitialized, thus we have to give these values to the cvode-solver // Take care about the memory regions, _z is the same like _CV_y _continuous_system->getContinuousStates(_z); } } if ((_zeroFound || state_selection)&& !isInterrupted()) { if (writeEventOutput) { _continuous_system->evaluateAll(IContinuous::CONTINUOUS); writeToFile(0, _tCurrent, _h); } _idid = ARKodeReInit(_arkodeMem, NULL, ARK_fCallback, _tCurrent, _ARK_y); if (_idid < 0) throw ModelicaSimulationError(SOLVER,"CVode::ReInit()"); // Der Eventzeitpunkt kann auf der Endzeit liegen (Time-Events). In diesem Fall wird der Solver beendet, da CVode sonst eine interne Warnung if (_tCurrent == _tEnd) _ark_rt = ARK_TSTOP_RETURN; } ++_outStps; _tLastSuccess = _tCurrent; if (_ark_rt == ARK_TSTOP_RETURN) { _time_system->setTime(_tEnd); //Solver has finished calculation - calculate the final values _continuous_system->setContinuousStates(NV_DATA_S(_ARK_y)); _continuous_system->evaluateAll(IContinuous::CONTINUOUS); if(writeOutput) writeToFile(0, _tEnd, _h); _accStps += _locStps; _solverStatus = DONE; } } }
void Arkode::solve(const SOLVERCALL action) { bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); if (_arkodesettings && _system) { // if ((action & RECORDCALL) && (action & FIRST_CALL)) { initialize(); if (writeOutput) writeToFile(0, _tCurrent, _h); _tLastWrite = 0; return; } if ((action & RECORDCALL) && !(action & FIRST_CALL)) { writeToFile(_accStps, _tCurrent, _h); return; } // Nach einem TimeEvent wird der neue Zustand recorded if (action & RECALL) { _firstStep = true; if (writeEventOutput) writeToFile(0, _tCurrent, _h); if (writeOutput) writeArkodeOutput(_tCurrent, _h, _locStps); _continuous_system->getContinuousStates(_z); } // Solver soll fortfahren _solverStatus = ISolver::CONTINUE; while (_solverStatus & ISolver::CONTINUE && !_interrupt ) { // Zuvor wurde initialize aufgerufen und hat funktioniert => RESET IDID if (_idid == 5000) _idid = 0; // Solveraufruf if (_idid == 0) { // Zähler zurücksetzen _accStps = 0; _locStps = 0; // Solverstart //ARKode Core !!!! ArkodeCore(); } // Integration war nicht erfolgreich und wurde auch nicht vom User unterbrochen if (_idid != 0 && _idid != 1) { _solverStatus = ISolver::SOLVERERROR; //throw ModelicaSimulationError(SOLVER,_idid,_tCurrent,"CVode::solve()"); throw ModelicaSimulationError(SOLVER,"CVode::solve()"); } // Abbruchkriterium (erreichen der Endzeit) else if ((_tEnd - _tCurrent) <= dynamic_cast<ISolverSettings*>(_arkodesettings)->getEndTimeTol()) _solverStatus = DONE; } _firstCall = false; } else { throw ModelicaSimulationError(SOLVER,"CVode::solve()"); } }
int Cvode::calcJacobian(double t, long int N, N_Vector fHelp, N_Vector errorWeight, N_Vector jthCol, double* y, N_Vector fy, DlsMat Jac) { try { int l,g; double fnorm, minInc, *f_data, *fHelp_data, *errorWeight_data, h, srur, delta_inv; f_data = NV_DATA_S(fy); errorWeight_data = NV_DATA_S(errorWeight); fHelp_data = NV_DATA_S(fHelp); //Get relevant info _idid = CVodeGetErrWeights(_cvodeMem, errorWeight); if (_idid < 0) { _idid = -5; throw ModelicaSimulationError(SOLVER,"Cvode::calcJacobian()"); } _idid = CVodeGetCurrentStep(_cvodeMem, &h); if (_idid < 0) { _idid = -5; throw ModelicaSimulationError(SOLVER,"Cvode::calcJacobian()"); } srur = sqrt(UROUND); fnorm = N_VWrmsNorm(fy, errorWeight); minInc = (fnorm != 0.0) ? (1000.0 * abs(h) * UROUND * N * fnorm) : 1.0; for(int j=0;j<N;j++) { _delta[j] = max(srur*abs(y[j]), minInc/errorWeight_data[j]); } for(int j=0;j<N;j++) { _deltaInv[j] = 1/_delta[j]; } if (_jacobianANonzeros != 0) { for(int color=1; color <= _maxColors; color++) { for(int k=0; k < _dimSys; k++) { if((_colorOfColumn[k] ) == color) { _ysave[k] = y[k]; y[k]+= _delta[k]; } } calcFunction(t, y, fHelp_data); for (int k = 0; k < _dimSys; k++) { if((_colorOfColumn[k]) == color) { y[k] = _ysave[k]; int startOfColumn = k * _dimSys; for (int j = _jacobianALeadindex[k]; j < _jacobianALeadindex[k+1];j++) { l = _jacobianAIndex[j]; g = l + startOfColumn; Jac->data[g] = (fHelp_data[l] - f_data[l]) * _deltaInv[k]; } } } } } } /* //Calculation of J without colouring for (j = 0; j < N; j++) { //N_VSetArrayPointer(DENSE_COL(Jac,j), jthCol); _ysave[j] = y[j]; y[j] += _delta[j]; calcFunction(t, y, fHelp_data); y[j] = _ysave[j]; delta_inv = 1.0/_delta[j]; N_VLinearSum(delta_inv, fHelp, -delta_inv, fy, jthCol); for(int i=0; i<_dimSys; ++i) { Jac->data[i+j*_dimSys] = NV_Ith_S(jthCol,i); } //DENSE_COL(Jac,j) = N_VGetArrayPointer(jthCol); } */ //workaround until exception can be catch from c- libraries catch (std::exception & ex ) { cerr << "CVode integration error: " << ex.what(); return 1; } return 0; }
void Modelica::getStateSetJacobian(matrix_t& matrix) { throw ModelicaSimulationError(MODEL_EQ_SYSTEM,"giveStateJacobian is not yet implemented"); }
bool Modelica::checkConditions() { throw ModelicaSimulationError(MODEL_EQ_SYSTEM,"checkConditions is not yet implemented"); }
bool Modelica::stepCompleted(double time) { throw ModelicaSimulationError(MODEL_EQ_SYSTEM,"stepCompleted is not yet implemented"); }
void Hybrj::solve() { // If initialize() was not called yet if (_firstCall) initialize(); if(_algLoop->isLinear()) { long int dimRHS = 1; // Dimension of right hand side of linear system (=b) long int dimSys= _dimSys; long int irtrn = 0; // Retrun-flag of Fortran code //calcFunction(_yHelp,_fHelp); const matrix_t& A = _algLoop->getSystemMatrix(); const double* jac = A.data().begin(); memcpy(_jac, jac, _dimSys*_dimSys*sizeof(double)); dgesv_(&dimSys, &dimRHS, _jac, &dimSys, _iHelp, _f,&dimSys,&irtrn); memcpy(_x,_f,_dimSys*sizeof(double)); _algLoop->setReal(_x); if(irtrn != 0) throw ModelicaSimulationError(ALGLOOP_SOLVER,"error solving linear tearing system"); else _iterationStatus = DONE; } else if(_algLoop->isLinearTearing()) { long int dimRHS = 1; // Dimension of right hand side of linear system (=b) long int dimSys= _dimSys; long int irtrn = 0; // Retrun-flag of Fortran code _algLoop->setReal(_zeroVec); _algLoop->evaluate(); _algLoop->getRHS(_f); const matrix_t& A = _algLoop->getSystemMatrix(); const double* jac = A.data().begin(); memcpy(_jac, jac, _dimSys*_dimSys*sizeof(double)); dgesv_(&dimSys, &dimRHS, _jac, &dimSys, _iHelp, _f,&dimSys,&irtrn); for(int i=0; i<_dimSys; i++) _f[i]=-_f[i]; memcpy(_x, _f, _dimSys*sizeof(double)); _algLoop->setReal(_x); _algLoop->evaluate(); if(irtrn != 0) throw ModelicaSimulationError(ALGLOOP_SOLVER,"error solving linear tearing system"); else _iterationStatus = DONE; } else { bool restart =true; int iter = 0; int iter_retry = 0; int iter_retry2 = 0; int info; _iterationStatus = CONTINUE; bool isConsistent = true; double local_tol = 1e-12; while(_iterationStatus == CONTINUE) { /* Scaling x vector */ if(_usescale) std::transform (_x, _x+_dimSys, _x_scale,_x, std::divides<double>()); __minpack_func__(hybrj)((minpack_funcder_nn)fcn, &_dimSys, _x, _f, _jac, &_ldfjac, &_xtol, &_maxfev, _diag, &_mode, &_factor, &_nprint, &info, &_nfev, &_njev, _r, &_lr, _qtf, _wa1, _wa2, _wa3, _wa4,_data); //check if the conditions of the system has changed if(isConsistent) { isConsistent = _algLoop->isConsistent(); if(!isConsistent) _algLoop->getReal(_x_restart); } /* re-scaling x vector */ if(_usescale) std::transform (_x, _x+_dimSys, _x_scale, _x, std::multiplies<double>()); _fnorm = __minpack_func__(enorm)(&_dimSys, _f); /*solution was found*/ if(info==1 || (_fnorm <= local_tol)) _iterationStatus = DONE; /* first try to decrease factor */ else if((info==4 || info == 5) && iter<3) { _algLoop->getReal(_x); _iterationStatus = CONTINUE; _factor/=10; iter++; // cout << " - iteration making no progress:\t decreasing initial step bound to "<< _factor << std::endl ; } /* try to vary the initial values */ else if((info==4 || info == 5) && iter<4) { _factor=_initial_factor; for(int i = 0; i < _dimSys; i++) _x[i] += _x_nom[i] * 0.1; iter++; // cout <<"iteration making no progress:\t vary solution point by 1%%"<< std::endl ; } /* try old values as x-Scaling factors */ else if((info==4 || info == 5) && iter<5) { for(int i = 0; i < _dimSys; i++) _x_scale[i] = std::max(_x0[i], _x_nom[i]); iter++; //cout << "iteration making no progress:\t try without scaling at all."<< std::endl ; } /* try to disable x-Scaling */ else if((info==4 || info == 5) && iter<6) { _usescale = false; memcpy(_x_scale, _x_nom,_dimSys*(sizeof(double))); iter++; // cout << "iteration making no progress:\t try without scaling at all."<< std::endl ; } /*try with old values (instead of extrapolating )*/ else if((info==4 || info == 5) && iter_retry<1) { memcpy(_x, _x0, _dimSys*(sizeof(double))); iter=0; iter_retry++; // cout << "- iteration making no progress:\t use old values instead extrapolated."<< std::endl ; } /* try to vary the initial values */ else if((info==4 || info == 5) && iter_retry<2) { memcpy(_x, _x_ex, _dimSys*(sizeof(double))); for(int i = 0; i < _dimSys; i++) { _x[i] *= 1.01; } iter = 0; iter_retry++; //cout << "- iteration making no progress:\t vary initial point by adding 1%%."<< std::endl ; } /* try to vary the initial values */ else if((info==4 || info == 5) && iter_retry<3) { memcpy(_x, _x_ex, _dimSys*(sizeof(double))); for(int i = 0; i < _dimSys; i++) { _x[i] *= 0.99; } iter = 0; iter_retry++; //cout << "- iteration making no progress:\t vary initial point by -1%%."<< std::endl ; } /* try to vary the initial values */ else if((info==4 || info == 5) && iter_retry<4) { memcpy(_x, _x_nom, _dimSys*(sizeof(double))); iter = 0; iter_retry++; // cout << "- iteration making no progress:\t try scaling factor as initial point."<< std::endl ; } /* try own scaling factors */ else if((info==4 || info == 5) && iter_retry<5) { memcpy(_x, _x_ex, _dimSys*(sizeof(double))); for(int i = 0; i < _dimSys; i++) { _diag[i] = fabs(_x_scale[i]); if(_diag[i] <= 0) _diag[i] = 1e-16; } _mode = 2; iter = 0; iter_retry++; // cout << "- iteration making no progress:\t try with own scaling factors."<< std::endl ; } /* try without internal scaling */ else if((info==4 || info == 5) && iter_retry2<2) { memcpy(_x, _x_ex, _dimSys*(sizeof(double))); for(int i = 0; i < _dimSys; i++) { _diag[i] = 1.0; } _mode=2; _usescale=true; iter = 0; iter_retry=0; iter_retry2++; // cout << "- - iteration making no progress:\t disable solver internal scaling."<< std::endl ; } /* try to reduce the tolerance a bit */ else if((info==4 || info == 5) && iter_retry2<6) { memcpy(_x, _x_ex, _dimSys*(sizeof(double))); _xtol*=10; _factor = _initial_factor; iter = 0; iter_retry=0; iter_retry2++; _mode=1; // cout << " - iteration making no progress:\t reduce the tolerance slightly to %e."<< std::endl ; } else _iterationStatus = SOLVERERROR; } if(_iterationStatus == SOLVERERROR) { if(!isConsistent) { _algLoop->setReal(_x_restart); } else throw ModelicaSimulationError(ALGLOOP_SOLVER,"Unsuccessful termination of HYBRJ, iteration is making no progress "); } /* if(iter>4) { std::cout << " iterations: " << iter << " , " <<iter_retry << " , " << iter_retry2 << " norm: " <<_fnorm << std::endl; }*/ _factor=100; _mode=1; } }
void Cvode::solve(const SOLVERCALL action) { bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL); bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE); #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(cvodeSolveFunctionHandler, "solve"); if(MeasureTime::getInstance() != NULL) { MEASURETIME_START(solveFunctionStartValues, cvodeSolveFunctionHandler, "solve"); } #endif if (_cvodesettings && _system) { // Solver und System für Integration vorbereiten if ((action & RECORDCALL) && (action & FIRST_CALL)) { #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(cvodeInitializeHandler, "CVodeInitialize"); if(MeasureTime::getInstance() != NULL) { MEASURETIME_START(measuredFunctionStartValues, cvodeInitializeHandler, "CVodeInitialize"); } #endif initialize(); #ifdef RUNTIME_PROFILING if(MeasureTime::getInstance() != NULL) { MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[4], cvodeInitializeHandler); } #endif if (writeOutput) writeToFile(0, _tCurrent, _h); _tLastWrite = 0; return; } if ((action & RECORDCALL) && !(action & FIRST_CALL)) { writeToFile(_accStps, _tCurrent, _h); return; } // Nach einem TimeEvent wird der neue Zustand recorded if (action & RECALL) { _firstStep = true; if (writeEventOutput) writeToFile(0, _tCurrent, _h); if (writeOutput) writeCVodeOutput(_tCurrent, _h, _locStps); _continuous_system->getContinuousStates(_z); } // Solver soll fortfahren _solverStatus = ISolver::CONTINUE; while ((_solverStatus & ISolver::CONTINUE) && !_interrupt ) { // Zuvor wurde initialize aufgerufen und hat funktioniert => RESET IDID if (_idid == 5000) _idid = 0; // Solveraufruf if (_idid == 0) { // Zähler zurücksetzen _accStps = 0; _locStps = 0; // Solverstart CVodeCore(); } // Integration war nicht erfolgreich und wurde auch nicht vom User unterbrochen if (_idid != 0 && _idid != 1) { _solverStatus = ISolver::SOLVERERROR; //throw ModelicaSimulationError(SOLVER,_idid,_tCurrent,"CVode::solve()"); throw ModelicaSimulationError(SOLVER,"CVode::solve()"); } // Abbruchkriterium (erreichen der Endzeit) else if ((_tEnd - _tCurrent) <= dynamic_cast<ISolverSettings*>(_cvodesettings)->getEndTimeTol()) _solverStatus = DONE; } _firstCall = false; } else { throw ModelicaSimulationError(SOLVER,"CVode::solve()"); } #ifdef RUNTIME_PROFILING if(MeasureTime::getInstance() != NULL) { MEASURETIME_END(solveFunctionStartValues, solveFunctionEndValues, (*measureTimeFunctionsArray)[1], cvodeSolveFunctionHandler); long int nst, nfe, nsetups, netf, nni, ncfn; int qlast, qcur; realtype h0u, hlast, hcur, tcur; int flag; flag = CVodeGetIntegratorStats(_cvodeMem, &nst, &nfe, &nsetups, &netf, &qlast, &qcur, &h0u, &hlast, &hcur, &tcur); flag = CVodeGetNonlinSolvStats(_cvodeMem, &nni, &ncfn); MeasureTimeValuesSolver solverVals = MeasureTimeValuesSolver(nfe, netf); (*measureTimeFunctionsArray)[6]->_sumMeasuredValues->_numCalcs += nst; (*measureTimeFunctionsArray)[6]->_sumMeasuredValues->add(&solverVals); } #endif }
void SimManager::initialize() { #ifdef RUNTIME_PROFILING MEASURETIME_REGION_DEFINE(initSimHandler, "initializeSimulation"); if (MeasureTime::getInstance() != NULL) { MEASURETIME_START(initSimStartValues, initSimHandler, "initializeSimulation"); } #endif _cont_system = dynamic_pointer_cast<IContinuous>(_mixed_system); _timeevent_system = dynamic_pointer_cast<ITime>(_mixed_system); _event_system = dynamic_pointer_cast<IEvent>(_mixed_system); _step_event_system = dynamic_pointer_cast<IStepEvent>(_mixed_system); // Check dynamic casts if (!_event_system) { throw ModelicaSimulationError(SIMMANAGER,"Could not get event system."); } if (!_cont_system) { throw ModelicaSimulationError(SIMMANAGER,"Could not get continuous-event system."); } if (!_timeevent_system) { throw ModelicaSimulationError(SIMMANAGER,"Could not get time-event system."); } if (!_step_event_system) { throw ModelicaSimulationError(SIMMANAGER,"Could not get step-event system."); } LOGGER_WRITE("SimManager: Start initialization",LC_INIT,LL_DEBUG); // Reset debug ID _dbgId = 0; try { // Build up system and update once _initialization->initializeSystem(); } catch (std::exception& ex) { //ex << error_id(SIMMANAGER); throw ModelicaSimulationError(SIMMANAGER,"Could not initialize system.",string(ex.what()),false); } if (_timeevent_system) { _dimtimeevent = _timeevent_system->getDimTimeEvent(); if (_timeEventCounter) delete[] _timeEventCounter; _timeEventCounter = new int[_dimtimeevent]; memset(_timeEventCounter, 0, _dimtimeevent * sizeof(int)); // compute sampleCycles for RT simulation if (_config->getGlobalSettings()->useEndlessSim()) { if (_sampleCycles) delete[] _sampleCycles; _sampleCycles = new int[_dimtimeevent]; computeSampleCycles(); } } else _dimtimeevent = 0; _tStart = _config->getGlobalSettings()->getStartTime(); _tEnd = _config->getGlobalSettings()->getEndTime(); // Set flag for endless simulation (if solver returns) _continueSimulation = _tEnd > _tStart; // _solver->setTimeOut(_config->getGlobalSettings()->getAlarmTime()); _dimZeroFunc = _event_system->getDimZeroFunc(); _solverTask = ISolver::SOLVERCALL(ISolver::FIRST_CALL); if (_dimZeroFunc == _event_system->getDimZeroFunc()) { if (_events) delete[] _events; _events = new bool[_dimZeroFunc]; memset(_events, false, _dimZeroFunc * sizeof(bool)); } LOGGER_WRITE("SimManager: Assemble completed",LC_INIT,LL_DEBUG); //#if defined(__TRICORE__) || defined(__vxworks) // Initialization for RT simulation if (_config->getGlobalSettings()->useEndlessSim()) { _cycleCounter = 0; _resetCycle = _sampleCycles[0]; for (int i = 1; i < _dimtimeevent; i++) _resetCycle *= _sampleCycles[i]; // All Events are updated every cycle. In order to have a change in timeEventCounter, the reset is set to two if(_resetCycle == 1) _resetCycle++; _solver->initialize(); } //#endif #ifdef RUNTIME_PROFILING if (MeasureTime::getInstance() != NULL) { MEASURETIME_END(initSimStartValues, initSimEndValues, (*measureTimeFunctionsArray)[0], initSimHandler); } #endif }
static LogSettings initializeLogger(const po::variables_map& vm) { map<string, LogCategory> logCatMap = MAP_LIST_OF "init", LC_INIT MAP_LIST_SEP "nls", LC_NLS MAP_LIST_SEP "ls", LC_LS MAP_LIST_SEP "solver", LC_SOLVER MAP_LIST_SEP "output", LC_OUTPUT MAP_LIST_SEP "events", LC_EVENTS MAP_LIST_SEP "model", LC_MODEL MAP_LIST_SEP "other", LC_OTHER MAP_LIST_END; map<string, LogLevel> logLvlMap = MAP_LIST_OF "error", LL_ERROR MAP_LIST_SEP "warning", LL_WARNING MAP_LIST_SEP "info", LL_INFO MAP_LIST_SEP "debug", LL_DEBUG MAP_LIST_END; map<string, LogFormat> logFormatMap = MAP_LIST_OF "txt", LF_TXT MAP_LIST_SEP "xml", LF_XML MAP_LIST_SEP "xmltcp", LF_XMLTCP MAP_LIST_END; map<string, LogOMEdit> logOMEditMap = MAP_LIST_OF "LOG_EVENTS", LOG_EVENTS MAP_LIST_SEP "LOG_INIT", LOG_INIT MAP_LIST_SEP "LOG_LS", LOG_LS MAP_LIST_SEP "LOG_NLS", LOG_NLS MAP_LIST_SEP "LOG_SOLVER", LOG_SOLVER MAP_LIST_SEP "LOG_STATS", LOG_STATS MAP_LIST_END; LogSettings logSettings; std::string logOMEditWarning; if (vm.count("log-settings")) { vector<string> log_vec = vm["log-settings"].as<vector<string> >(); vector<string> tmpvec; for (int i = 0; i < log_vec.size(); i++) { // translate XML stream options to native options if (log_vec[i].compare(0, 4, "LOG_") == 0) { LogOMEdit logOMEdit; boost::split(tmpvec, log_vec[i], boost::is_any_of(",")); for (int j = 0; j < tmpvec.size(); j++) { if (logOMEditMap.find(tmpvec[j]) != logOMEditMap.end()) logOMEdit = logOMEditMap[tmpvec[j]]; else { if (logOMEditWarning.size() > 0) logOMEditWarning += ","; logOMEditWarning += tmpvec[j]; continue; } switch (logOMEdit) { case LOG_EVENTS: logSettings.modes[LC_EVENTS] = LL_DEBUG; break; case LOG_INIT: logSettings.modes[LC_INIT] = LL_DEBUG; break; case LOG_LS: logSettings.modes[LC_LS] = LL_DEBUG; break; case LOG_NLS: logSettings.modes[LC_NLS] = LL_DEBUG; break; case LOG_SOLVER: logSettings.modes[LC_SOLVER] = LL_DEBUG; //case LOG_STATS: default: if (logSettings.modes[LC_SOLVER] < LL_INFO) logSettings.modes[LC_SOLVER] = LL_INFO; } } } // treat native option else { boost::split(tmpvec, log_vec[i], boost::is_any_of("=")); if (tmpvec.size() > 1 && logLvlMap.find(tmpvec[1]) != logLvlMap.end() && (tmpvec[0] == "all" || logCatMap.find(tmpvec[0]) != logCatMap.end())) { if (tmpvec[0] == "all") { logSettings.setAll(logLvlMap[tmpvec[1]]); break; } else logSettings.modes[logCatMap[tmpvec[0]]] = logLvlMap[tmpvec[1]]; } else throw ModelicaSimulationError(MODEL_FACTORY, "log-settings flags not supported: " + log_vec[i] + "\n"); } } } if (vm.count("warn-all") && vm["warn-all"].as<bool>()) { for (int i = 0; i < logSettings.modes.size(); i++) if (logSettings.modes[i] < LL_WARNING) logSettings.modes[i] = LL_WARNING; } if (vm.count("log-format")) { string logFormat_str = vm["log-format"].as<string>(); if (logFormatMap.find(logFormat_str) != logFormatMap.end()) logSettings.format = logFormatMap[logFormat_str]; else throw ModelicaSimulationError(MODEL_FACTORY, "Unknown log-format " + logFormat_str); } // make sure other infos get issued and initialize logger if (logSettings.modes[LC_OTHER] < LL_INFO) logSettings.modes[LC_OTHER] = LL_INFO; // initialize logger if it has been enabled if (Logger::isEnabled()) { int port = vm["log-port"].as<int>(); if (port > 0) { try { LoggerXMLTCP::initialize("127.0.0.1", port, logSettings); } catch (std::exception &ex) { throw ModelicaSimulationError(MODEL_FACTORY, "Failed to start logger with port " + to_string(port) + ": " + ex.what() + '\n'); } } else Logger::initialize(logSettings); } if (logOMEditWarning.size() > 0) { LOGGER_WRITE("Warning: unrecognized logging " + logOMEditWarning, LC_OTHER, LL_WARNING); ostringstream os; os << "Supported are: "; map<std::string, LogOMEdit>::const_iterator it; for (it = logOMEditMap.begin(); it != logOMEditMap.end(); ++it) { if (it != logOMEditMap.begin()) os << ","; os << it->first; } LOGGER_WRITE(os.str(), LC_OTHER, LL_INFO); } return logSettings; }
SimSettings OMCFactory::readSimulationParameter(int argc, const char* argv[]) { int opt; int portnum; map<string, OutputPointType> outputPointTypeMap = MAP_LIST_OF "all", OPT_ALL MAP_LIST_SEP "step", OPT_STEP MAP_LIST_SEP "none", OPT_NONE MAP_LIST_END; map<string, OutputFormat> outputFormatMap = MAP_LIST_OF "csv", CSV MAP_LIST_SEP "mat", MAT MAP_LIST_SEP "buffer", BUFFER MAP_LIST_SEP "empty", EMPTY MAP_LIST_END; map<string, EmitResults> emitResultsMap = MAP_LIST_OF "all", EMIT_ALL MAP_LIST_SEP "public", EMIT_PUBLIC MAP_LIST_SEP "none", EMIT_NONE MAP_LIST_END; po::options_description desc("Allowed options"); //program options that can be overwritten by OMEdit must be declared as vector //so that the same value can be set multiple times //(e.g. 'executable -F arg1 -r=arg2' -> 'executable -F arg1 -F=arg2') //the variables of OMEdit are always the first elements of the result vectors, if they are set desc.add_options() ("help", "produce help message") ("nls-continue", po::bool_switch()->default_value(false), "non linear solver will continue if it can not reach the given precision") ("runtime-library,R", po::value<string>(), "path to cpp runtime libraries") ("modelica-system-library,M", po::value<string>(), "path to Modelica library") ("input-path", po::value< string >(), "directory with input files, like init xml (defaults to modelica-system-library)") ("output-path", po::value< string >(), "directory for output files, like results (defaults to modelica-system-library)") ("results-file,F", po::value<vector<string> >(),"name of results file") ("start-time,S", po::value< double >()->default_value(0.0), "simulation start time") ("stop-time,E", po::value< double >()->default_value(1.0), "simulation stop time") ("step-size,H", po::value< double >()->default_value(0.0), "simulation step size") ("solver,I", po::value< string >()->default_value("euler"), "solver method") ("lin-solver,L", po::value< string >()->default_value(_defaultLinSolver), "linear solver method") ("non-lin-solver,N", po::value< string >()->default_value(_defaultNonLinSolver), "non linear solver method") ("number-of-intervals,G", po::value< int >()->default_value(500), "number of intervals in equidistant grid") ("tolerance,T", po::value< double >()->default_value(1e-6), "solver tolerance") ("warn-all,W", po::bool_switch()->default_value(false), "issue all warning messages") ("log-settings,V", po::value< vector<string> >(), "log information: init, nls, ls, solver, output, events, model, other") ("log-format,X", po::value< string >()->default_value("txt"), "log format: txt, xml, xmltcp") ("log-port", po::value< int >()->default_value(0), "tcp port for log messages (default 0 meaning stdout/stderr)") ("alarm,A", po::value<unsigned int >()->default_value(360), "sets timeout in seconds for simulation") ("output-type,O", po::value< string >()->default_value("all"), "the points in time written to result file: all (output steps + events), step (just output points), none") ("output-format,P", po::value< string >()->default_value("mat"), "simulation results output format: csv, mat, buffer, empty") ("emit-results,U", po::value< string >()->default_value("public"), "emit results: all, public, none") ; // a group for all options that should not be visible if '--help' is set po::options_description descHidden("Hidden options"); descHidden.add_options() ("ignored", po::value<vector<string> >(), "ignored options") ("unrecognized", po::value<vector<string> >(), "unsupported options") ("solver-threads", po::value<int>()->default_value(1), "number of threads that can be used by the solver") ; po::options_description descAll("All options"); descAll.add(desc); descAll.add(descHidden); po::variables_map vm; boost::function<pair<string, string> (const string&)> parserFunction(boost::bind(&OMCFactory::parseIngoredAndWrongFormatOption, this, _1)); po::parsed_options parsed = po::command_line_parser(argc, argv) .options(descAll) .style((po::command_line_style::default_style | po::command_line_style::allow_long_disguise) & ~po::command_line_style::allow_guessing) .extra_parser(parserFunction) .allow_unregistered() .run(); po::store(parsed, vm); po::notify(vm); if (vm.count("help")) { cout << desc << endl; throw ModelicaSimulationError(MODEL_FACTORY, "Cannot parse command line arguments correctly, because the help message was requested.", "",true); } LogSettings logSettings = initializeLogger(vm); // warn about unrecognized command line options vector<string> unrecognized = po::collect_unrecognized(parsed.options, po::include_positional); if (vm.count("unrecognized")) { vector<string> opts = vm["unrecognized"].as<vector<string> >(); unrecognized.insert(unrecognized.begin(), opts.begin(), opts.end()); } if (unrecognized.size() > 0) { ostringstream os; os << "Warning: unrecognized command line options "; copy(unrecognized.begin(), unrecognized.end(), ostream_iterator<string>(os, " ")); LOGGER_WRITE(os.str(), LC_OTHER, LL_WARNING); } string runtime_lib_path; string modelica_lib_path; double starttime = vm["start-time"].as<double>(); double stoptime = vm["stop-time"].as<double>(); double stepsize =vm["step-size"].as<double>(); bool nlsContinueOnError = vm["nls-continue"].as<bool>(); int solverThreads = vm["solver-threads"].as<int>(); if (!(stepsize > 0.0)) stepsize = (stoptime - starttime) / vm["number-of-intervals"].as<int>(); double tolerance = vm["tolerance"].as<double>(); string solver = vm["solver"].as<string>(); string nonLinSolver = vm["non-lin-solver"].as<string>(); string linSolver = vm["lin-solver"].as<string>(); unsigned int timeOut = vm["alarm"].as<unsigned int>(); if (vm.count("runtime-library")) { //cout << "runtime library path set to " << vm["runtime-library"].as<string>() << endl; runtime_lib_path = vm["runtime-library"].as<string>(); normalizePath(runtime_lib_path); } else throw ModelicaSimulationError(MODEL_FACTORY,"runtime libraries path is not set"); if (vm.count("modelica-system-library")) { //cout << "Modelica library path set to " << vm["Modelica-system-library"].as<string>() << endl; modelica_lib_path = vm["modelica-system-library"].as<string>(); normalizePath(modelica_lib_path); } else throw ModelicaSimulationError(MODEL_FACTORY,"Modelica library path is not set"); string inputPath, outputPath; if (vm.count("input-path")) { inputPath = vm["input-path"].as<string>(); normalizePath(inputPath); } else inputPath = modelica_lib_path; if (vm.count("output-path")) { outputPath = vm["output-path"].as<string>(); normalizePath(outputPath); } else outputPath = modelica_lib_path; string resultsfilename; if (vm.count("results-file")) { //cout << "results file: " << vm["results-file"].as<string>() << endl; resultsfilename = vm["results-file"].as<vector<string> >().front(); } else throw ModelicaSimulationError(MODEL_FACTORY,"results-filename is not set"); OutputPointType outputPointType; if (vm.count("output-type")) { string outputType_str = vm["output-type"].as<string>(); if (outputPointTypeMap.find(outputType_str) != outputPointTypeMap.end()) outputPointType = outputPointTypeMap[outputType_str]; else throw ModelicaSimulationError(MODEL_FACTORY, "Unknown output-type " + outputType_str); } else throw ModelicaSimulationError(MODEL_FACTORY, "output-type is not set"); OutputFormat outputFormat; if (vm.count("output-format")) { string outputFormat_str = vm["output-format"].as<string>(); if (outputFormatMap.find(outputFormat_str) != outputFormatMap.end()) outputFormat = outputFormatMap[outputFormat_str]; else throw ModelicaSimulationError(MODEL_FACTORY, "Unknown output-format " + outputFormat_str); } else throw ModelicaSimulationError(MODEL_FACTORY, "output-format is not set"); EmitResults emitResults = EMIT_PUBLIC; // emit public per default for OMC use if (vm.count("emit-results")) { string emitResults_str = vm["emit-results"].as<string>(); if (emitResultsMap.find(emitResults_str) != emitResultsMap.end()) emitResults = emitResultsMap[emitResults_str]; else throw ModelicaSimulationError(MODEL_FACTORY, "Unknown emit-results " + emitResults_str); } fs::path libraries_path = fs::path( runtime_lib_path) ; fs::path modelica_path = fs::path( modelica_lib_path) ; libraries_path.make_preferred(); modelica_path.make_preferred(); SimSettings settings = {solver, linSolver, nonLinSolver, starttime, stoptime, stepsize, 1e-24, 0.01, tolerance, resultsfilename, timeOut, outputPointType, logSettings, nlsContinueOnError, solverThreads, outputFormat, emitResults, inputPath, outputPath}; _library_path = libraries_path.string(); _modelicasystem_path = modelica_path.string(); return settings; }
bool Modelica::provideSymbolicJacobian() { throw ModelicaSimulationError(MODEL_EQ_SYSTEM,"provideSymbolicJacobian is not yet implemented"); }
SimSettings OMCFactory::readSimulationParameter(int argc, const char* argv[]) { int opt; int portnum; map<string, LogCategory> logCatMap = MAP_LIST_OF "init", LC_INIT MAP_LIST_SEP "nls", LC_NLS MAP_LIST_SEP "ls", LC_LS MAP_LIST_SEP "solv", LC_SOLV MAP_LIST_SEP "output", LC_OUT MAP_LIST_SEP "event", LC_EVT MAP_LIST_SEP "model", LC_MOD MAP_LIST_SEP "other", LC_OTHER MAP_LIST_END; map<string, LogLevel> logLvlMap = MAP_LIST_OF "error", LL_ERROR MAP_LIST_SEP "warning", LL_WARNING MAP_LIST_SEP "info", LL_INFO MAP_LIST_SEP "debug", LL_DEBUG MAP_LIST_END; map<string, OutputPointType> outputPointTypeMap = MAP_LIST_OF "all", OPT_ALL MAP_LIST_SEP "step", OPT_STEP MAP_LIST_SEP "none", OPT_NONE MAP_LIST_END; map<string, OutputFormat> outputFormatTypeMap = MAP_LIST_OF "csv", CSV MAP_LIST_SEP "mat", MAT MAP_LIST_SEP "buffer", BUFFER MAP_LIST_SEP "empty", EMPTY MAP_LIST_END; po::options_description desc("Allowed options"); //program options that can be overwritten by OMEdit must be declared as vector //so that the same value can be set multiple times //(e.g. 'executable -F arg1 -r=arg2' -> 'executable -F arg1 -F=arg2') //the variables of OMEdit are always the first elements of the result vectors, if they are set desc.add_options() ("help", "produce help message") ("nls-continue", po::bool_switch()->default_value(false),"non linear solver will continue if it can not reach the given precision") ("runtime-library,R", po::value<string>(),"path to cpp runtime libraries") ("modelica-system-library,M", po::value<string>(), "path to Modelica library") ("results-file,F", po::value<vector<string> >(),"name of results file") ("start-time,S", po::value< double >()->default_value(0.0), "simulation start time") ("stop-time,E", po::value< double >()->default_value(1.0), "simulation stop time") ("step-size,H", po::value< double >()->default_value(0.0), "simulation step size") ("solver,I", po::value< string >()->default_value("euler"), "solver method") ("lin-solver,L", po::value< string >()->default_value(_defaultLinSolver), "linear solver method") ("non-lin-solver,N", po::value< string >()->default_value(_defaultNonLinSolver), "non linear solver method") ("number-of-intervals,G", po::value< int >()->default_value(500), "number of intervals in equidistant grid") ("tolerance,T", po::value< double >()->default_value(1e-6), "solver tolerance") ("log-settings,V", po::value< vector<string> >(), "log information: init, nls, ls, solv, output, event, model, other") ("alarm,A", po::value<unsigned int >()->default_value(360), "sets timeout in seconds for simulation") ("output-type,O", po::value< string >()->default_value("all"), "the points in time written to result file: all (output steps + events), step (just output points), none") ("output-format,P", po::value< string >()->default_value("mat"), "The simulation results output format") ; // a group for all options that should not be visible if '--help' is set po::options_description descHidden("Hidden options"); descHidden.add_options() ("ignored", po::value<vector<string> >(), "ignored options") ("unrecognized", po::value<vector<string> >(), "unsupported options") ("solverThreads", po::value<int>()->default_value(1), "number of threads that can be used by the solver") ; po::options_description descAll("All options"); descAll.add(desc); descAll.add(descHidden); po::variables_map vm; boost::function<pair<string, string> (const string&)> parserFunction(boost::bind(&OMCFactory::parseIngoredAndWrongFormatOption, this, _1)); po::parsed_options parsed = po::command_line_parser(argc, argv) .options(descAll) .style((po::command_line_style::default_style | po::command_line_style::allow_long_disguise) & ~po::command_line_style::allow_guessing) .extra_parser(parserFunction) .allow_unregistered() .run(); po::store(parsed, vm); po::notify(vm); if (vm.count("help")) { cout << desc << "\n"; throw ModelicaSimulationError(MODEL_FACTORY, "Cannot parse command line arguments correctly, because the help message was requested.", "",true); } // warn about unrecognized command line options, including OMEdit for now vector<string> unrecognized = po::collect_unrecognized(parsed.options, po::include_positional); if (vm.count("unrecognized")) { vector<string> opts = vm["unrecognized"].as<vector<string> >(); unrecognized.insert(unrecognized.begin(), opts.begin(), opts.end()); } if (unrecognized.size() > 0) { cerr << "Warning: unrecognized command line options "; copy(unrecognized.begin(), unrecognized.end(), ostream_iterator<string>(cerr, " ")); cerr << endl; } string runtime_lib_path; string modelica_lib_path; double starttime = vm["start-time"].as<double>(); double stoptime = vm["stop-time"].as<double>(); double stepsize =vm["step-size"].as<double>(); bool nlsContinueOnError = vm["nls-continue"].as<bool>(); int solverThreads = vm["solverThreads"].as<int>(); if (!(stepsize > 0.0)) stepsize = (stoptime - starttime) / vm["number-of-intervals"].as<int>(); double tolerance =vm["tolerance"].as<double>(); string solver = vm["solver"].as<string>(); string nonLinSolver = vm["non-lin-solver"].as<string>(); string linSolver = vm["lin-solver"].as<string>(); unsigned int timeOut = vm["alarm"].as<unsigned int>(); if (vm.count("runtime-library")) { //cout << "runtime library path set to " << vm["runtime-library"].as<string>() << endl; runtime_lib_path = vm["runtime-library"].as<string>(); } else throw ModelicaSimulationError(MODEL_FACTORY,"runtime libraries path is not set"); if (vm.count("modelica-system-library")) { //cout << "Modelica library path set to " << vm["Modelica-system-library"].as<string>() << endl; modelica_lib_path =vm["modelica-system-library"].as<string>(); } else throw ModelicaSimulationError(MODEL_FACTORY,"Modelica library path is not set"); string resultsfilename; if (vm.count("results-file")) { //cout << "results file: " << vm["results-file"].as<string>() << endl; resultsfilename = vm["results-file"].as<vector<string> >().front(); } else throw ModelicaSimulationError(MODEL_FACTORY,"results-filename is not set"); string outputPointType_str; OutputPointType outputPointType; if (vm.count("output-type")) { //cout << "results file: " << vm["results-file"].as<string>() << endl; outputPointType_str = vm["output-type"].as<string>(); outputPointType = outputPointTypeMap[outputPointType_str]; } else throw ModelicaSimulationError(MODEL_FACTORY, "output-type is not set"); LogSettings logSet; if (vm.count("log-settings")) { vector<string> log_vec = vm["log-settings"].as<vector<string> >(),tmpvec; for(unsigned i=0;i<log_vec.size();++i) { //cout << i << ". " << log_vec[i] << endl; tmpvec.clear(); boost::split(tmpvec,log_vec[i],boost::is_any_of("=")); if(tmpvec.size()>1 && logLvlMap.find(tmpvec[1]) != logLvlMap.end() && ( tmpvec[0] == "all" || logCatMap.find(tmpvec[0]) != logCatMap.end())) { if(tmpvec[0] == "all") { logSet.setAll(logLvlMap[tmpvec[1]]); break; } else logSet.modes[logCatMap[tmpvec[0]]] = logLvlMap[tmpvec[1]]; } else throw ModelicaSimulationError(MODEL_FACTORY,"log-settings flags not supported: " + log_vec[i] + "\n"); } } OutputFormat outputFormat; if (vm.count("output-format")) { string outputFormatType_str = vm["output-format"].as<string>(); outputFormat = outputFormatTypeMap[outputFormatType_str]; } else throw ModelicaSimulationError(MODEL_FACTORY, "output-format is not set"); fs::path libraries_path = fs::path( runtime_lib_path) ; fs::path modelica_path = fs::path( modelica_lib_path) ; libraries_path.make_preferred(); modelica_path.make_preferred(); SimSettings settings = {solver,linSolver,nonLinSolver,starttime,stoptime,stepsize,1e-24,0.01,tolerance,resultsfilename,timeOut,outputPointType,logSet,nlsContinueOnError,solverThreads,outputFormat}; _library_path = libraries_path.string(); _modelicasystem_path = modelica_path.string(); return settings; }
void Peer::initialize() { IContinuous *continuous_system = dynamic_cast<IContinuous*>(_system); ITime *time_system = dynamic_cast<ITime*>(_system); #ifdef MPIPEER MPI_Comm_size(MPI_COMM_WORLD, &_size); if(_size>=5) { _size=5; } else { throw ModelicaSimulationError(SOLVER,"Peer::MPI initialization error"); } MPI_Comm_rank(MPI_COMM_WORLD, &_rank); for(int i = 0; i < 5; i++) { _continuous_system[i] = continuous_system; _time_system[i] = time_system; } #else _time_system[0] = time_system; _continuous_system[0] = continuous_system; for(int i = 1; i < 5; i++) { IMixedSystem* clonedSystem = _system->clone(); _continuous_system[i] = dynamic_cast<IContinuous*>(clonedSystem); _time_system[i] = dynamic_cast<ITime*>(clonedSystem); dynamic_cast<ISystemInitialization*>(clonedSystem)->initialize(); } #endif //MPIPEER SolverDefaultImplementation::initialize(); _dimSys = _continuous_system[0]->getDimContinuousStates(); _rstages = 5; _G=new double[5]; _G[0]=0.0681; _G[1]=0.1855545484594073; _G[2]=0.3756; _G[3]=0.5656454515405926; _G[4]=0.6831; _E=new double[25]; _E[0]=-4.73606797749979e+00; _E[1]=6.85410196624968e+00; _E[2]=-3.23606797749979e+00; _E[3]=1.61803398874989e+00; _E[4]=-0.5; _E[5]=-1; _E[6]=-4.27050983124845e-01; _E[7]=2.; _E[8]=-8.09016994374946e-01; _E[9]=2.36067977499789e-01; _E[10]=3.09016994374947e-01; _E[11]=-1.30901699437495e+00; _E[12]=2.69090356243347e-15; _E[13]=1.30901699437495e+00; _E[14]=-3.09016994374947e-01; _E[15]=-2.36067977499789e-01; _E[16]=8.09016994374947e-01; _E[17]=-2.; _E[18]=4.27050983124842e-01; _E[19]=1.; _E[20]=0.5; _E[21]=-1.61803398874990e+00; _E[22]=3.23606797749979e+00; _E[23]=-6.85410196624968e+00; _E[24]=4.73606797749979e+00; _Theta=new double[25]; _Theta[0]=0.; _Theta[1]=0.; _Theta[2]=1.; _Theta[3]=0.; _Theta[4]=0.; _Theta[5]=0.045084971874737; _Theta[6]=-0.163118960624632; _Theta[7]=0.527864045000421; _Theta[8]=0.690983005625053; _Theta[9]=-0.100813061875578; _Theta[10]=0.; _Theta[11]=0.; _Theta[12]=0.; _Theta[13]=0.; _Theta[14]=1.; _Theta[15]=1.809016994374949; _Theta[16]=-5.545084971874742; _Theta[17]=9.472135954999576; _Theta[18]=-12.399186938124409; _Theta[19]=7.663118960624626; _Theta[20]=5.854101966249686; _Theta[21]=-17.562305898749063; _Theta[22]=28.416407864998732; _Theta[23]=-33.270509831248397; _Theta[24]=17.562305898749038; _c=new double[5]; _c[0]=-1.; _c[1]=-6.18033988749895e-01; _c[2]=0.; _c[3]=6.18033988749895e-01; _c[4]=1.; _h = std::max(std::min(_h, _peersettings->getUpperLimit()), _peersettings->getLowerLimit()); _y = new double[_dimSys]; #ifdef MPIPEER _F=new double[_dimSys]; _T=new double[_dimSys*_dimSys]; _P=new long int[_dimSys]; if(_rank==0) { _Y1=new double[_dimSys*_rstages]; _Y2=new double[_dimSys*_rstages]; _Y3=new double[_dimSys*_rstages]; } else { _Y1=new double[_dimSys]; _Y2=new double[_dimSys]; _Y3=new double[_dimSys]; } #else _F=new double[_dimSys*5]; _T=new double[_dimSys*_dimSys*5]; _P=new long int[_dimSys*5]; _Y1=new double[_dimSys*_rstages]; _Y2=new double[_dimSys*_rstages]; _Y3=new double[_dimSys*_rstages]; #endif _continuous_system[0]->evaluateAll(IContinuous::ALL); _continuous_system[0]->getContinuousStates(_y); }