Exemplo n.º 1
0
void Cvode::giveZeroVal(const double &t, const double *y, double *zeroValue)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(cvodeEvalZeroHandler, "evaluateZeroFuncs");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(measuredFunctionStartValues, cvodeEvalZeroHandler, "evaluateZeroFuncs");
  }
  #endif

  _time_system->setTime(t);
  _continuous_system->setContinuousStates(y);

  // System aktualisieren
  _continuous_system->evaluateZeroFuncs(IContinuous::DISCRETE);

  _event_system->getZeroFunc(zeroValue);

  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[3], cvodeEvalZeroHandler);
  }
  #endif
}
Exemplo n.º 2
0
void Ida::giveZeroVal(const double &t, const double *y,const double *yp,double *zeroValue)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(idaEvalZeroHandler, "evaluateZeroFuncs");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(measuredFunctionStartValues, idaEvalZeroHandler, "evaluateZeroFuncs");
  }
  #endif

  _time_system->setTime(t);
  _continuous_system->setContinuousStates(y);
   if(_dimAE>0)
   {
	 _mixed_system->setAlgebraicDAEVars(y+_dimStates);
	 _continuous_system->setStateDerivatives(yp);
   }
  // System aktualisieren
  _continuous_system->evaluateZeroFuncs(IContinuous::DISCRETE);

  _event_system->getZeroFunc(zeroValue);

  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[3], idaEvalZeroHandler);
  }
  #endif
}
void SolverDefaultImplementation::writeToFile(const int& stp, const double& t, const double& h)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(writeFunctionStartValues, "solverWriteOutput");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(writeFunctionStartValues, solverWriteOutputHandler, "solverWriteOutput");
  }
  #endif

  if(_settings->getGlobalSettings()->getOutputFormat()!= EMPTY)
  {
    IWriteOutput* writeoutput_system = dynamic_cast<IWriteOutput*>(_system);

    if(_outputCommand & IWriteOutput::WRITEOUT)
    {
      writeoutput_system->writeOutput(_outputCommand);

    }
  }
  checkTimeout();

  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(writeFunctionStartValues, writeFunctionEndValues, measureTimeFunctionsArray[0], solverWriteOutputHandler);
  }
  #endif
}
Exemplo n.º 4
0
int Ida::calcFunction(const double& time, const double* y, double* f)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(idaCalcFunctionHandler, "IDACalcFunction");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(measuredFunctionStartValues, idaCalcFunctionHandler, "IDACalcFunction");
  }
  #endif

  int returnValue = 0;
  try
  {
    _time_system->setTime(time);
    _continuous_system->setContinuousStates(y);
    _continuous_system->evaluateODE(IContinuous::CONTINUOUS);
    _continuous_system->getRHS(f);
  }      //workaround until exception can be catch from c- libraries
  catch (std::exception& ex)
  {
    std::string error = ex.what();
    cerr << "IDA integration error: " << error;
    returnValue = -1;
  }

  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[0], idaCalcFunctionHandler);
  }
  #endif

  return returnValue;
}
Exemplo n.º 5
0
int Ida::calcFunction(const double& time, const double* y, double *yp,double* res)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(idaCalcFunctionHandler, "IDACalcFunction");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(measuredFunctionStartValues, idaCalcFunctionHandler, "IDACalcFunction");
  }
  #endif

  int returnValue = 0;
  try
  {
    if(_dimAE>0)
	{
	   _time_system->setTime(time);
      _continuous_system->setContinuousStates(y);
	  _continuous_system->setStateDerivatives(yp);
	  _mixed_system->setAlgebraicDAEVars(y+_dimStates);
	  _continuous_system->evaluateDAE(IContinuous::CONTINUOUS);
	  _mixed_system->getResidual(res);

	}
	else
	{
	  _time_system->setTime(time);
      _continuous_system->setContinuousStates(y);
      _continuous_system->evaluateODE(IContinuous::CONTINUOUS);
      _continuous_system->getRHS(res);
	  for(size_t i(0); i<_dimSys; ++i)
		   res[i]-=yp[i];

	}
  }      //workaround until exception can be catch from c- libraries
  catch (std::exception& ex)
  {
    std::string error = ex.what();
    cerr << "IDA integration error: " << error;
    returnValue = -1;
  }

  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[0], idaCalcFunctionHandler);
  }
  #endif

  return returnValue;
}
Exemplo n.º 6
0
void SimManager::runSimulation()
{
    #ifdef RUNTIME_PROFILING
    MEASURETIME_REGION_DEFINE(runSimHandler, "runSimulation");
    if (MeasureTime::getInstance() != NULL)
    {
        MEASURETIME_START(runSimStartValues, runSimHandler, "runSimulation");
    }
    #endif
    try
    {
        Logger::write("SimManager: start simulation at t = " + boost::lexical_cast<std::string>(_tStart),LC_SOLV,LL_INFO);
        runSingleProcess();
        // Zeit messen, Ausgabe der SimInfos
        ISolver::SOLVERSTATUS status = _solver->getSolverStatus();
        if ((status & ISolver::DONE) || (status & ISolver::USER_STOP))
        {
            Logger::write("SimManager: simulation done at t = " + boost::lexical_cast<std::string>(_tEnd),LC_SOLV,LL_INFO);
            Logger::write("SimManager: number of steps = " + boost::lexical_cast<std::string>(_totStps),LC_SOLV,LL_INFO);
            writeProperties();
        }
    }
    catch (std::exception & ex)
    {
        Logger::write("SimManager: simulation finish with errors at t = " + boost::lexical_cast<std::string>(_tEnd),LC_SOLV,LL_ERROR);
        Logger::write("SimManager: number of steps = " + boost::lexical_cast<std::string>(_totStps),LC_SOLV,LL_INFO);
        writeProperties();

        Logger::write("SimManager: error = " + boost::lexical_cast<std::string>(ex.what()),LC_SOLV,LL_ERROR);
        //ex << error_id(SIMMANAGER);
        throw;
    }
    #ifdef RUNTIME_PROFILING
    if (MeasureTime::getInstance() != NULL)
    {
        MEASURETIME_END(runSimStartValues, runSimEndValues, measureTimeFunctionsArray[1], runSimHandler);
    }
    #endif
}
Exemplo n.º 7
0
void SimManager::runSimulation()
{
    #ifdef RUNTIME_PROFILING
    MEASURETIME_REGION_DEFINE(runSimHandler, "runSimulation");
    if (MeasureTime::getInstance() != NULL)
    {
        MEASURETIME_START(runSimStartValues, runSimHandler, "runSimulation");
    }
    #endif
    try
    {
        LOGGER_WRITE("SimManager: Start simulation at t = " + to_string(_tStart), LC_SOLV, LL_INFO);
        runSingleProcess();
        // Measure time; Output SimInfos
        ISolver::SOLVERSTATUS status = _solver->getSolverStatus();
        if ((status & ISolver::DONE) || (status & ISolver::USER_STOP))
        {
            //LOGGER_WRITE("SimManager: Simulation done at t = " + to_string(_tEnd), LC_SOLV, LL_INFO);
            writeProperties();
        }
    }
    catch (std::exception & ex)
    {
        LOGGER_WRITE("SimManager: Simulation finish with errors at t = " + to_string(_tEnd), LC_SOLV, LL_ERROR);
        writeProperties();

        LOGGER_WRITE("SimManager: Error = " + string(ex.what()), LC_SOLV, LL_ERROR);
        //ex << error_id(SIMMANAGER);
        throw;
    }
    #ifdef RUNTIME_PROFILING
    if (MeasureTime::getInstance() != NULL)
    {
        MEASURETIME_END(runSimStartValues, runSimEndValues, (*measureTimeFunctionsArray)[1], runSimHandler);
    }
    #endif
}
Exemplo n.º 8
0
int Cvode::calcFunction(const double& time, const double* y, double* f)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(cvodeCalcFunctionHandler, "CVodeCalcFunction");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(measuredFunctionStartValues, cvodeCalcFunctionHandler, "CVodeCalcFunction");
  }
  #endif

  int returnValue = 0;
  try
  {
    f[0] = 0.0; // in case of dummy state
    _time_system->setTime(time);
    _continuous_system->setContinuousStates(y);
    _continuous_system->evaluateODE(IContinuous::CONTINUOUS);
    _continuous_system->getRHS(f);
    _numberOfOdeEvaluations++;
  }      //workaround until exception can be catch from c- libraries
  catch (std::exception & ex )
  {

    //cerr << "CVode integration error: " <<  diagnostic_information(ex);
    returnValue = 1;
  }

  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[0], cvodeCalcFunctionHandler);
  }
  #endif

  return returnValue;
}
Exemplo n.º 9
0
void Ida::writeIDAOutput(const double &time, const double &h, const int &stp)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(idaWriteOutputHandler, "IDAWriteOutput");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(measuredFunctionStartValues, idaWriteOutputHandler, "IDAWriteOutput");
  }
  #endif

  if (stp > 0)
  {
    if (_idasettings->getDenseOutput())
    {
      _bWritten = false;
      double *oldValues = NULL;

      //We have to find all output-points within the last solver step
      while (_tLastWrite + dynamic_cast<ISolverSettings*>(_idasettings)->getGlobalSettings()->gethOutput() <= time)
      {
        if (!_bWritten)
        {
          //Rescue the calculated derivatives
          oldValues = new double[_continuous_system->getDimRHS()];
          _continuous_system->getRHS(oldValues);
        }
        _bWritten = true;
        _tLastWrite = _tLastWrite + dynamic_cast<ISolverSettings*>(_idasettings)->getGlobalSettings()->gethOutput();
        //Get the state vars at the output-point (interpolated)
        _idid = IDAGetDky(_idaMem, _tLastWrite, 0, _CV_yWrite);
        _time_system->setTime(_tLastWrite);
        _continuous_system->setContinuousStates(NV_DATA_S(_CV_yWrite));
		if(_dimAE>0)
		{
		   _mixed_system->setAlgebraicDAEVars(NV_DATA_S(_CV_y)+_dimStates);
		   _idid = IDAGetDky(_idaMem, _tLastWrite, 1, _CV_ypWrite);
		   _continuous_system->setStateDerivatives(NV_DATA_S(_CV_ypWrite));
		   _continuous_system->evaluateDAE(IContinuous::CONTINUOUS);
        }
		else
		{
			_continuous_system->evaluateAll(IContinuous::CONTINUOUS);
		}
        #ifdef RUNTIME_PROFILING
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[2], idaWriteOutputHandler);
        }
        #endif
        SolverDefaultImplementation::writeToFile(stp, _tLastWrite, h);
        #ifdef RUNTIME_PROFILING
        MEASURETIME_REGION_DEFINE(idaWriteOutputHandler, "IDAWriteOutput");
        if(MeasureTime::getInstance() != NULL)
        {
          (*measureTimeFunctionsArray)[2]->_sumMeasuredValues->_numCalcs--;
            MEASURETIME_START(measuredFunctionStartValues, idaWriteOutputHandler, "IDAWriteOutput");
        }
        #endif
      }      //end if time -_tLastWritten
      if (_bWritten)
      {
        _time_system->setTime(time);
        _continuous_system->setContinuousStates(_y);
        _continuous_system->setStateDerivatives(oldValues);
		if(_dimAE>0)
		{
		   _mixed_system->setAlgebraicDAEVars(_y+_dimStates);
		}
        delete[] oldValues;

      }
      else if (time == _tEnd && _tLastWrite != time)
      {
        _idid = IDAGetDky(_idaMem, time, 0, _CV_y);
		_idid = IDAGetDky(_idaMem, time, 1, _CV_yp);
        _time_system->setTime(time);
        _continuous_system->setContinuousStates(NV_DATA_S(_CV_y));
		if(_dimAE>0)
		{
		   _mixed_system->setAlgebraicDAEVars(NV_DATA_S(_CV_y)+_dimStates);
		   _continuous_system->setStateDerivatives(NV_DATA_S(_CV_yp));
		   _continuous_system->evaluateDAE(IContinuous::CONTINUOUS);
        }
		else
		{
		   _continuous_system->evaluateAll(IContinuous::CONTINUOUS);
		}
        #ifdef RUNTIME_PROFILING
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[2], idaWriteOutputHandler);
        }
        #endif
        SolverDefaultImplementation::writeToFile(stp, _tEnd, h);
      }
    }
    else
    {
        #ifdef RUNTIME_PROFILING
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[2], idaWriteOutputHandler);
        }
        #endif
        SolverDefaultImplementation::writeToFile(stp, time, h);
    }
  }
}
Exemplo n.º 10
0
void Ida::IDACore()
{
  _idid = IDAReInit(_idaMem, _tCurrent, _CV_y,_CV_yp);
  _idid = IDASetStopTime(_idaMem, _tEnd);
  _idid = IDASetInitStep(_idaMem, 1e-12);
  if (_idid < 0)
    throw std::runtime_error("IDA::ReInit");

  bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL);
  bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE);

  while ((_solverStatus & ISolver::CONTINUE) && !_interrupt )
  {
    _cv_rt = IDASolve(_idaMem, _tEnd, &_tCurrent,  _CV_y, _CV_yp, IDA_ONE_STEP);

    _idid = IDAGetNumSteps(_idaMem, &_locStps);
    if (_idid != IDA_SUCCESS)
      throw std::runtime_error("IDAGetNumSteps failed. The ida mem pointer is NULL");

    _idid =IDAGetLastStep(_idaMem, &_h);
    if (_idid != IDA_SUCCESS)
      throw std::runtime_error("IDAGetLastStep failed. The ida mem pointer is NULL");

    //Check if there was at least one output-point within the last solver interval
    //  -> Write output if true
    if (writeOutput)
    {
        writeIDAOutput(_tCurrent, _h, _locStps);
    }

    #ifdef RUNTIME_PROFILING
    MEASURETIME_REGION_DEFINE(idaStepCompletedHandler, "IDAStepCompleted");
    if(MeasureTime::getInstance() != NULL)
    {
        MEASURETIME_START(measuredFunctionStartValues, idaStepCompletedHandler, "IDAStepCompleted");
    }
    #endif

    //set completed step to system and check if terminate was called
    if(_continuous_system->stepCompleted(_tCurrent))
        _solverStatus = DONE;

    #ifdef RUNTIME_PROFILING
    if(MeasureTime::getInstance() != NULL)
    {
        MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[5], idaStepCompletedHandler);
    }
    #endif

    // Perform state selection
    bool state_selection = stateSelection();
    if (state_selection)
      _continuous_system->getContinuousStates(_y);

    _zeroFound = false;

    // Check if step was successful
    if (check_flag(&_cv_rt, "IDA", 1))
    {
      _solverStatus = ISolver::SOLVERERROR;
      break;
    }

    // A root was found
    if ((_cv_rt == IDA_ROOT_RETURN) && !isInterrupted())
    {
      // IDA 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 std::runtime_error("Number of events exceeded  in time interval " + to_string(_abs) + " at time " + to_string(_tCurrent));

      // IDA 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)
      {
		if(_dimAE>0)
		{
			 _continuous_system->evaluateDAE(IContinuous::CONTINUOUS);
        }
		else
		{
		    _continuous_system->evaluateAll(IContinuous::CONTINUOUS);
		}
        writeToFile(0, _tCurrent, _h);
      }

      _idid = IDAGetRootInfo(_idaMem, _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 ida-solver
        // Take care about the memory regions, _z is the same like _CV_y
        _continuous_system->getContinuousStates(_y);
        if(_dimAE>0)
		{
           _mixed_system->getAlgebraicDAEVars(_y+_dimStates);
		   _continuous_system->getRHS(_yp);
		}
		calcFunction(_tCurrent, NV_DATA_S(_CV_y), NV_DATA_S(_CV_yp),_dae_res);

      }
    }

    if ((_zeroFound || state_selection)&& !isInterrupted())
    {
      // Write the values of (P2)
      if (writeEventOutput)
      {
        // If we want to write the event-results, we should evaluate the whole system again
        if(_dimAE>0)
		{
			 _continuous_system->evaluateDAE(IContinuous::CONTINUOUS);
        }
		else
		{
		    _continuous_system->evaluateAll(IContinuous::CONTINUOUS);
		}
        writeToFile(0, _tCurrent, _h);
      }

      _idid = IDAReInit(_idaMem, _tCurrent, _CV_y,_CV_yp);
      if (_idid < 0)
        throw std::runtime_error("IDA::ReInit()");

      // Der Eventzeitpunkt kann auf der Endzeit liegen (Time-Events). In diesem Fall wird der Solver beendet, da IDA sonst eine interne Warnung schmeißt
      if (_tCurrent == _tEnd)
        _cv_rt = IDA_TSTOP_RETURN;
    }

    // Zähler für die Anzahl der ausgegebenen Schritte erhöhen
    ++_outStps;
    _tLastSuccess = _tCurrent;

    if (_cv_rt == IDA_TSTOP_RETURN)
    {
      _time_system->setTime(_tEnd);
      _continuous_system->setContinuousStates(NV_DATA_S(_CV_y));
	  if(_dimAE>0)
	  {
	    _mixed_system->setAlgebraicDAEVars(NV_DATA_S(_CV_y)+_dimStates);
	    _continuous_system->setStateDerivatives(NV_DATA_S(_CV_yp));
		_continuous_system->evaluateDAE(IContinuous::CONTINUOUS);
      }
	  else
	  {
		_continuous_system->evaluateAll(IContinuous::CONTINUOUS);
      }
      if(writeOutput)
         writeToFile(0, _tEnd, _h);

      _accStps += _locStps;
      _solverStatus = DONE;
    }
  }
}
Exemplo n.º 11
0
void Ida::solve(const SOLVERCALL action)
{
  bool writeEventOutput = (_settings->getGlobalSettings()->getOutputPointType() == OPT_ALL);
  bool writeOutput = !(_settings->getGlobalSettings()->getOutputPointType() == OPT_NONE);

  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(idaSolveFunctionHandler, "solve");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(solveFunctionStartValues, idaSolveFunctionHandler, "solve");
  }
  #endif

  if (_idasettings && _system)
  {
    // Solver und System für Integration vorbereiten
    if ((action & RECORDCALL) && (action & FIRST_CALL))
    {
        #ifdef RUNTIME_PROFILING
        MEASURETIME_REGION_DEFINE(idaInitializeHandler, "IDAInitialize");
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_START(measuredFunctionStartValues, idaInitializeHandler, "IDAInitialize");
        }
        #endif

        initialize();

        #ifdef RUNTIME_PROFILING
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[4], idaInitializeHandler);
        }
        #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)
        writeIDAOutput(_tCurrent, _h, _locStps);
       _continuous_system->getContinuousStates(_y);
    }

    // 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
        IDACore();

      }

      // Integration war nicht erfolgreich und wurde auch nicht vom User unterbrochen
      if (_idid != 0 && _idid != 1)
      {
        _solverStatus = ISolver::SOLVERERROR;
        //throw std::invalid_argument(_idid,_tCurrent,"IDA::solve()");
        throw std::invalid_argument("IDA::solve()");
      }

      // Abbruchkriterium (erreichen der Endzeit)
      else if ((_tEnd - _tCurrent) <= dynamic_cast<ISolverSettings*>(_idasettings)->getEndTimeTol())
        _solverStatus = DONE;
    }

    _firstCall = false;

  }
  else
  {

    throw std::invalid_argument("IDA::solve()");
  }

  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(solveFunctionStartValues, solveFunctionEndValues, (*measureTimeFunctionsArray)[1], idaSolveFunctionHandler);

      long int nst, nfe, nsetups, netf, nni, ncfn;
      int qlast, qcur;
      realtype h0u, hlast, hcur, tcur;

      int flag;

      flag = IDAGetIntegratorStats(_idaMem, &nst, &nfe, &nsetups, &netf, &qlast, &qcur, &h0u, &hlast, &hcur, &tcur);
      flag = IDAGetNonlinSolvStats(_idaMem, &nni, &ncfn);

      MeasureTimeValuesSolver solverVals = MeasureTimeValuesSolver(nfe, netf);
      (*measureTimeFunctionsArray)[6]->_sumMeasuredValues->_numCalcs += nst;
      (*measureTimeFunctionsArray)[6]->_sumMeasuredValues->add(&solverVals);
  }
  #endif
}
Exemplo n.º 12
0
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
}
Exemplo n.º 13
0
void Cvode::writeCVodeOutput(const double &time, const double &h, const int &stp)
{
  #ifdef RUNTIME_PROFILING
  MEASURETIME_REGION_DEFINE(cvodeWriteOutputHandler, "CVodeWriteOutput");
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_START(measuredFunctionStartValues, cvodeWriteOutputHandler, "CVodeWriteOutput");
  }
  #endif

  if (stp > 0)
  {
    if (_cvodesettings->getDenseOutput())
    {
      _bWritten = false;
     /* double *oldValues = NULL;*/

      //We have to find all output-points within the last solver step
      while (_tLastWrite + dynamic_cast<ISolverSettings*>(_cvodesettings)->getGlobalSettings()->gethOutput() <= time)
      {
        if (!_bWritten)
        {
           _continuous_system->restoreOldValues();
		   ////Rescue the calculated derivatives
     //      oldValues = new double[_continuous_system->getDimRHS()];
     //      _continuous_system->getRHS(oldValues);

        }
        _bWritten = true;
        _tLastWrite = _tLastWrite + dynamic_cast<ISolverSettings*>(_cvodesettings)->getGlobalSettings()->gethOutput();
        //Get the state vars at the output-point (interpolated)
        _idid = CVodeGetDky(_cvodeMem, _tLastWrite, 0, _CV_yWrite);
        _time_system->setTime(_tLastWrite);
        _continuous_system->setContinuousStates(NV_DATA_S(_CV_yWrite));
        _continuous_system->evaluateAll(IContinuous::CONTINUOUS);
        SolverDefaultImplementation::writeToFile(stp, _tLastWrite, h);
      }      //end if time -_tLastWritten
      if (_bWritten)
      {
        _time_system->setTime(time);
        _continuous_system->setContinuousStates(_z);
        _continuous_system->restoreNewValues();
        /* _continuous_system->setRHS(oldValues);
         delete[] oldValues;*/
      }
      else if (time == _tEnd && _tLastWrite != time)
      {
        _idid = CVodeGetDky(_cvodeMem, time, 0, _CV_y);
        _time_system->setTime(time);
        _continuous_system->setContinuousStates(NV_DATA_S(_CV_y));
        _continuous_system->evaluateAll(IContinuous::CONTINUOUS);
        SolverDefaultImplementation::writeToFile(stp, _tEnd, h);
      }
    }
    else
    {
        SolverDefaultImplementation::writeToFile(stp, time, h);
    }
  }
  #ifdef RUNTIME_PROFILING
  if(MeasureTime::getInstance() != NULL)
  {
      MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, (*measureTimeFunctionsArray)[2], cvodeWriteOutputHandler);
  }
  #endif
}
Exemplo n.º 14
0
void SimManager::initialize()
{
    #ifdef RUNTIME_PROFILING
    MEASURETIME_REGION_DEFINE(initSimHandler, "initializeSimulation");
    if (MeasureTime::getInstance() != NULL)
    {
        MEASURETIME_START(initSimStartValues, initSimHandler, "initializeSimulation");
    }
    #endif

    _cont_system = boost::dynamic_pointer_cast<IContinuous>(_mixed_system);
    _timeevent_system = boost::dynamic_pointer_cast<ITime>(_mixed_system);
    _event_system = boost::dynamic_pointer_cast<IEvent>(_mixed_system);
    _step_event_system = boost::dynamic_pointer_cast<IStepEvent>(_mixed_system);

    //Check dynamic casts
    if (!_event_system)
    {
        std::cerr << "Could not get event system" << std::endl;
        return;
    }
    if (!_cont_system)
    {
        std::cerr << "Could not get continuous-event system" << std::endl;
        return;
    }
    if (!_timeevent_system)
    {
        std::cerr << "Could not get time-event system" << std::endl;
        return;
    }
    if (!_step_event_system)
    {
        std::cerr << "Could not get step-event system" << std::endl;
        return;
    }

    Logger::write("SimManager start init",LC_INIT,LL_DEBUG);
    // Flag für Endlossimulaton (wird gesetzt wenn Solver zurückkommt)
    _continueSimulation = true;

    // Reset debug ID
    _idid = 0;

    try
    {
        // System zusammenbauen und einmal updaten
        _initialization->initializeSystem();
    }
    catch (std::exception&  ex)
    {
        //ex << error_id(SIMMANAGER);
        throw;
    }
    _totStps = 0;
    _accStps = 0;
    _rejStps = 0;

    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();
    // _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
}
Exemplo n.º 15
0
void SimController::Start(SimSettings simsettings, string modelKey)
{
    try
    {
        #ifdef RUNTIME_PROFILING
        MEASURETIME_REGION_DEFINE(simControllerInitializeHandler, "SimControllerInitialize");
        MEASURETIME_REGION_DEFINE(simControllerSolveInitialSystemHandler, "SimControllerSolveInitialSystem");
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_START(measuredFunctionStartValues, simControllerInitializeHandler, "CVodeWriteOutput");
        }
        #endif
        boost::shared_ptr<IMixedSystem> mixedsystem = getSystem(modelKey).lock();

        IGlobalSettings* global_settings = _config->getGlobalSettings();

        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->setLogSettings(simsettings.logSettings);
        global_settings->setAlarmTime(simsettings.timeOut);
        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);
        #ifdef RUNTIME_PROFILING
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, measureTimeFunctionsArray[0], simControllerInitializeHandler);
            measuredFunctionStartValues = MeasureTime::getZeroValues();
            measuredFunctionEndValues = MeasureTime::getZeroValues();
            MEASURETIME_START(measuredFunctionStartValues, simControllerSolveInitialSystemHandler, "SolveInitialSystem");
        }
        #endif

        _simMgr->initialize();

        #ifdef RUNTIME_PROFILING
        if(MeasureTime::getInstance() != NULL)
        {
            MEASURETIME_END(measuredFunctionStartValues, measuredFunctionEndValues, measureTimeFunctionsArray[1], simControllerSolveInitialSystemHandler);
            MeasureTime::addResultContentBlock(mixedsystem->getModelName(),"simController",&measureTimeFunctionsArray);
        }
        #endif

        _simMgr->runSimulation();

        boost::shared_ptr<IWriteOutput> writeoutput_system = boost::dynamic_pointer_cast<IWriteOutput>(mixedsystem);

        boost::shared_ptr<ISimData> simData = getSimData(modelKey).lock();
        //get history object to query simulation results
        IHistory* history = writeoutput_system->getHistory();
        //simulation results (output variables)
        ublas::matrix<double> Ro;
        //query simulation result otuputs
        history->getOutputResults(Ro);
        vector<string> output_names;
        history->getOutputNames(output_names);
        string name;
        int j=0;

        BOOST_FOREACH(name,output_names)
        {
            ublas::vector<double> o_j;
            o_j = ublas::row(Ro,j);
            simData->addOutputResults(name,o_j);
            j++;
        }

        vector<double> time_values = history->getTimeEntries();
        simData->addTimeEntries(time_values);
    }