// Determine whether the button has been released
boolean SwitchableButton::released()
{
	// Save current pin state
	boolean previousState = state();
	// Call debouncing method
	setState(debounce(previousState));
	
	// Return the result
	return state() == initialState() && previousState != initialState();
}
示例#2
0
bool GuardianModule::executeChestClickAction(int nClicks)
{
    switch(nClicks)
    {
    case NO_CLICKS:
        return false;
        break;
    case 1:
        advanceState();
        break;
    case 2:
        shutoffGains();
        break;
    case 3:
        enableGains();
        break;
    case 4:
        initialState();
        break;
    case 5:
        printJointAngles();
        break;
    case 7:
        break;
    case 9:
        //Easter EGG!
        playFile(nbsdir+"easter_egg.wav");
        break;
    default:
        //nothing
        return false;
        break;
    }
    return true;
}
int main(){

    const long treeRoot = 1;
    long n; scanf("%ld\n", &n);
    std::vector<std::vector<long> > edges(n + 1);
    for(long p = 1; p < n; p++){
        long u, v; scanf("%ld %ld\n", &u, &v);
        edges[u].push_back(v); edges[v].push_back(u);
    }

    std::map<long, std::vector<long> > tree = makeTreeFromEdges(edges, 1);

    std::vector<int> initialState(n + 1, 0); for(long p = 1; p <= n; p++){scanf("%d", &initialState[p]);}
    std::vector<int> targetState(n + 1, 0);  for(long p = 1; p <= n; p++){scanf("%d", &targetState[p]);}
    //for(long p = 1; p <= n; p++){printf("*%d\t", targetState[p]);}; puts("");

    long total = countFlips(treeRoot, 0, 0, 0, tree, initialState, targetState);
    
    /*
    for(std::map<long, std::vector<long> >::iterator mapIter = tree.begin(); mapIter != tree.end(); mapIter++){
        long parent = mapIter->first;
        std::vector<long> sons = mapIter->second;
        for(int p = 0; p < sons.size(); p++){printf("%ld --> %ld\n", parent, sons[p]);}
    }
    */

    printf("%ld\n", flippedNodes.size()); 
    for(long p = 0; p < flippedNodes.size(); p++){printf("%ld\n", flippedNodes[p]);}

    return 0;
}
示例#4
0
void LDA::gibbs(int K,double alpha,double beta) {

    this->K=K;
    this->alpha=alpha;
    this->beta=beta;

    if(SAMPLE_LAG >0) {
        thetasum = MatrixXd(documentsSize(),K);
        phisum= MatrixXd(K,V);
        numstats=0;
    }

    initialState(K);

    for(int i=0; i<ITERATIONS; i++) {
        for(int m=0; m<z.rows(); m++) {
            for(int n=0; n<z.cols(); n++) {
                z(m,n)=sampleFullConditional(m,n);
            }
        }
        if(i > BURN_IN && (i%THIN_INTERVAL==0)) {
            dispcol++;
        }
        if ((i > BURN_IN) && (SAMPLE_LAG > 0) && (i % SAMPLE_LAG == 0)) {
            updateParams();
            if (i % THIN_INTERVAL != 0)
                dispcol++;
        }
        if (dispcol >= 100) {
            dispcol = 0;
        }
    }
}
示例#5
0
 Perturb7(const vle::devs::DynamicsInit& init, const vle::devs::InitEventList& events) :
     vf::Statechart(init, events), a(0)
 {
     states(this) << A;
     transition(this, A, A) << after(5.)
                                << send(&Perturb7::out);
     state(this, A) << eventInState("a", &Perturb7::a_in);
     initialState(A);
 }
示例#6
0
    Perturb10(const vle::devs::DynamicsInit& init, const vle::devs::InitEventList& events) :
        vf::Statechart(init, events)
    {
        states(this) << A << B;
        transition(this, A, B) << after(5.) << send(&Perturb10::out1);
        transition(this, B, A) << after(5.) << send(&Perturb10::out2);

        initialState(A);
    }
示例#7
0
    Perturb7(const vd::DynamicsInit& init, const vd::InitEventList& events) :
        vf::Statechart(init, events)
    {
        states(this) << A;

        transition(this, A, A) << after(5.)
                               << send(&Perturb7::out);

        initialState(A);
    }
示例#8
0
int QState::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QAbstractState::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        if (_id < 2)
            qt_static_metacall(this, _c, _id, _a);
        _id -= 2;
    }
#ifndef QT_NO_PROPERTIES
    else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0:
            *reinterpret_cast< QAbstractState**>(_v) = initialState();
            break;
        case 1:
            *reinterpret_cast< QAbstractState**>(_v) = errorState();
            break;
        case 2:
            *reinterpret_cast< ChildMode*>(_v) = childMode();
            break;
        }
        _id -= 3;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0:
            setInitialState(*reinterpret_cast< QAbstractState**>(_v));
            break;
        case 1:
            setErrorState(*reinterpret_cast< QAbstractState**>(_v));
            break;
        case 2:
            setChildMode(*reinterpret_cast< ChildMode*>(_v));
            break;
        }
        _id -= 3;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 3;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 3;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
NoOperation::IndexIntervals
NoOperation::findNoopSubsequences(const std::vector<SgAsmInstruction*> &insns) const {
    IndexIntervals retval;
    Sawyer::Message::Stream debug(mlog[DEBUG]);

    if (debug) {
        debug <<"findNoopSubsequences(\n";
        BOOST_FOREACH (SgAsmInstruction *insn, insns)
            debug <<"  " <<unparseInstructionWithAddress(insn) <<"\n";
        debug <<")\n";
    }

    // If we have no instruction semantics then assume that all instructions have an effect.
    if (!cpu_ || insns.empty())
        return retval;

    // Process each instruction as if insns were a basic block. Store insns[i]'s initial state in states[i] and its final state
    // in states[i+1].  States don't generally have a way to compare them for equality, so use a simple string-based comparison
    // for now. FIXME[Robb P. Matzke 2015-05-11]
    std::vector<std::string> states;
    bool hadError = false;
    cpu_->get_operators()->currentState(initialState(insns.front()));
    const RegisterDescriptor regIP = cpu_->instructionPointerRegister();
    try {
        BOOST_FOREACH (SgAsmInstruction *insn, insns) {
            cpu_->get_operators()->writeRegister(regIP, cpu_->get_operators()->number_(regIP.get_nbits(), insn->get_address()));
            states.push_back(normalizeState(cpu_->currentState()));
            if (debug) {
                debug <<"  normalized state #" <<states.size()-1 <<":\n" <<StringUtility::prefixLines(states.back(), "    ");
                debug <<"  instruction: " <<unparseInstructionWithAddress(insn) <<"\n";
            }
            cpu_->processInstruction(insn);
        }
    } catch (const BaseSemantics::Exception &e) {
        hadError = true;
        SAWYER_MESG(debug) <<"  semantic exception: " <<e <<"\n";
    }
    if (!hadError) {
        states.push_back(normalizeState(cpu_->currentState()));
        if (debug)
            debug <<"  normalized state #" <<states.size()-1 <<":\n" <<StringUtility::prefixLines(states.back(), "    ");
    }

    // Look for pairs of states that are the same, and call that sequence of instructions a no-op
    for (size_t i=0; i+1<states.size(); ++i) {
        for (size_t j=i+1; j<states.size(); ++j) {
            if (states[i]==states[j]) {
                retval.push_back(IndexInterval::hull(i, j-1));
                SAWYER_MESG(debug) <<"  no-op: " <<i <<".." <<(j-1) <<"\n";
            }
        }
    }
    
    return retval;
}
示例#10
0
devs::Time Mealy::init(devs::Time /* time */)
{
    if (not isInit()) {
        throw utils::InternalError(
            "FSA::Mealy model, initial state not defined");
    }

    currentState(initialState());
    mPhase = IDLE;
    return 0;
}
示例#11
0
    Perturb4(const vd::DynamicsInit& init, const vd::InitEventList& events) :
        vf::Statechart(init, events)
	{
	    states(this) << A;

	    transition(this, A, A) << event("in1")
                                   << send(&Perturb4::out1);
	    transition(this, A, A) << event("in2")
                                   << send(&Perturb4::out2);

	    initialState(A);
	}
示例#12
0
devs::Time Moore::init(devs::Time time)
{
    if (not isInit()) {
        throw utils::InternalError(
            "FSA::Moore model, initial state not defined");
    }

    currentState(initialState());

    ActionsIterator it = mActions.find(initialState());

    if (it != mActions.end()) {
        devs::ExternalEvent* event = new devs::ExternalEvent("");

        (it->second)(time, event);
        delete event;
    }

    mPhase = IDLE;
    return 0;
}
示例#13
0
void CReliveUI::onOpen()
{
	initialState();

	vector<int> rules = gMap->getReliveRules();

	for (size_t i=0; i<rules.size()&&i<Max_Relive_Choices; ++i)
	{
		RecoverLifeRuleCfg* pRuleCfg = RecoverLifeRuleData.get(rules[i]);
		if(!pRuleCfg) continue;
		showReliveChoice(pRuleCfg);
	}
}
示例#14
0
int QtStateMachine::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QObject::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    if (_c == QMetaObject::InvokeMetaMethod) {
        switch (_id) {
        case 0: started(); break;
        case 1: stopped(); break;
        case 2: finished(); break;
        case 3: start(); break;
        case 4: stop(); break;
        case 5: d_func()->_q_start(); break;
        case 6: d_func()->_q_process(); break;
        default: ;
        }
        _id -= 7;
    }
#ifndef QT_NO_PROPERTIES
      else if (_c == QMetaObject::ReadProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 0: *reinterpret_cast< QtState**>(_v) = rootState(); break;
        case 1: *reinterpret_cast< QtAbstractState**>(_v) = initialState(); break;
        case 2: *reinterpret_cast< QtAbstractState**>(_v) = errorState(); break;
        case 3: *reinterpret_cast< QString*>(_v) = errorString(); break;
        }
        _id -= 4;
    } else if (_c == QMetaObject::WriteProperty) {
        void *_v = _a[0];
        switch (_id) {
        case 1: setInitialState(*reinterpret_cast< QtAbstractState**>(_v)); break;
        case 2: setErrorState(*reinterpret_cast< QtAbstractState**>(_v)); break;
        }
        _id -= 4;
    } else if (_c == QMetaObject::ResetProperty) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyDesignable) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyScriptable) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyStored) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyEditable) {
        _id -= 4;
    } else if (_c == QMetaObject::QueryPropertyUser) {
        _id -= 4;
    }
#endif // QT_NO_PROPERTIES
    return _id;
}
        void CNonLinearSolver::solve()
        {
            m_IGUState = m_IGU.getState();
            std::vector<double> initialState(m_IGUState);
            std::vector<double> bestSolution(m_IGUState.size());
            auto achievedTolerance = 1000.0;
            m_SolutionTolerance = achievedTolerance;

            m_Iterations = 0;
            bool iterate = true;

            while(iterate)
            {
                ++m_Iterations;
                std::vector<double> aSolution = m_QBalance.calcBalanceMatrix();

                achievedTolerance = calculateTolerance(aSolution);

                estimateNewState(aSolution);

                m_IGU.setState(m_IGUState);

                if(achievedTolerance < m_SolutionTolerance)
                {
                    initialState = m_IGUState;
                    m_SolutionTolerance = std::min(achievedTolerance, m_SolutionTolerance);
                    bestSolution = m_IGUState;
                }

                if(m_Iterations > IterationConstants::NUMBER_OF_STEPS)
                {
                    m_Iterations = 0;
                    m_RelaxParam -= IterationConstants::RELAXATION_PARAMETER_STEP;

                    m_IGU.setState(initialState);
                    m_IGUState = initialState;
                }

                iterate = achievedTolerance > m_Tolerance;

                if(m_RelaxParam < IterationConstants::RELAXATION_PARAMETER_MIN)
                {
                    iterate = false;
                }
            }
            m_IGUState = bestSolution;
        }
示例#16
0
void Grammar::generateStates() {
  verbose(2, _T("Computing FIRST1 sets\n"));
  findFirst1Sets();
  m_stateMap.clear();
  m_unfinishedSet.clear();

  BitSet eoiset(getTerminalCount());
  eoiset.add(0); // EOI
  LR1Item initialItem(true, 0, 0, eoiset);
  LR1State initialState(0);
  initialState.addItem(initialItem);

  computeClosure(initialState, true);
  addState(initialState);
//  dump(initialState);
  verbose(2, _T("Computing LALR(1) states\n"));

  for(int i = 0; i < getStateCount(); i++) {
    verbose(2, _T("state %d\r"), i);
    computeSuccessors(m_states[i]);
  }

/*
  Array<int> length = m_stateHash.length();
  FILE *ff = fopen("c:\\temp\\hlength.dat", "w");
  for(i = 0; i < length.size(); i++) {
    fprintf(ff, "%d %d\n", i, length[i]);
  }
  fclose(ff);
*/
  while(!m_unfinishedSet.isEmpty()) {
    const int unfinishedState = m_unfinishedSet.select();
    m_unfinishedSet.remove(unfinishedState);
    verbose(2, _T("Closing state %d.\r"), unfinishedState);
    computeClosure(m_states[unfinishedState], false);
    computeSuccessors(m_states[unfinishedState]);
  }

  verbose(2, _T("Checking consistensy\n"));

  m_warningCount = m_SRconflicts = m_RRconflicts = 0;
  for(int i = 0; i < getStateCount(); i++) {
    LR1State &state = m_states[i];
    m_result.add(StateResult());
    checkStateIsConsistent(state, m_result.last());
  }
}
示例#17
0
void GoCodeFormatter::restoreCurrentState(const QTextBlock &block)
{
    if (block.isValid()) {
        BlockData blockData;
        if (loadBlockData(block, &blockData)) {
            m_indentation = blockData.indentation;
            m_padding = blockData.padding;
            m_currentState = blockData.endState;
            m_beginState = m_currentState;
            return;
        }
    }

    m_currentState = initialState();
    m_beginState = m_currentState;
    m_indentation = 0;
    m_padding = 0;
}
示例#18
0
int main(int argc, char *argv[])
{
	if (argc != 3) {
		std::cout << "Usage: " << argv[0] << " <DEPTH> <EDGE FILE>\n";
		return 0;
	}

	try {

		Graph graph;
		loadEdgeFile(argv[2], graph);
		State initialState(&graph, std::stoi(std::string(argv[1])));
		State *solution = astar(&initialState);
		solution->print(std::cout);
		
		//for (State::SuccessorIterator iter = initialState.successors(); iter.hasCurrent(); iter.next()) {
		//	State *current = iter.current();
		//	current->print(std::cout);
		//	std::cout << "Heuristic non-adopters: " << current->heuristicNonAdopters() << "\n\n";
		//}


		//std::cout << "heuristicNonAdopters: " << initialState.heuristicNonAdopters() << "\n";
		//std::cout << "nonAdopters: " << initialState.nonAdopters() << "\n";
		//solution->print(std::cout);
		//std::cout << "heuristicNonAdopters: " << solution->heuristicNonAdopters() << "\n";
		//std::cout << "nonAdopters: " << solution->nonAdopters() << "\n";
		//printGraphStats(graph);
		//iterativeDeepening(&graph, 10, std::cout);
		//State initialState(&graph, 3);
		//State *solution = uniformCostSearch(&initialState);
		//solution->print(std::cout);
		//delete solution;

		return 0;

	} catch (std::exception *e) {
		std::cout << "search: An exception occurred: " << e->what();
	}

	return 1;
}
bool
NoOperation::isNoop(const std::vector<SgAsmInstruction*> &insns) const {
    if (!cpu_)
        return false;                                   // assume sequence has effect if we can't prove otherwise
    if (insns.empty())
        return true;

    cpu_->get_operators()->currentState(initialState(insns.front()));
    std::string startState = normalizeState(cpu_->currentState());
    try {
        BOOST_FOREACH (SgAsmInstruction *insn, insns)
            cpu_->processInstruction(insn);
    } catch (const BaseSemantics::Exception&) {
        return false;
    }

    std::string endState = normalizeState(cpu_->currentState());
    SAWYER_MESG(mlog[DEBUG]) <<"== startState ==\n" <<startState <<"\n";
    SAWYER_MESG(mlog[DEBUG]) <<"== endState ==\n" <<endState   <<"\n";
    SAWYER_MESG(mlog[DEBUG]) <<"start and end states " <<(startState==endState ? "are equal":"differ") <<"\n";
    return startState == endState;
}
示例#20
0
void GoCodeFormatter::updateStateUntil(const QTextBlock &endBlock)
{
    QStack<CodeState> previousState = initialState();
    QTextBlock it = endBlock.document()->firstBlock();

    // find the first block that needs recalculation
    while (it.isValid() && it != endBlock) {
        BlockData blockData;
        if (!loadBlockData(it, &blockData))
            break;
        if (blockData.revision != it.revision())
            break;
        if (previousState.isEmpty() || blockData.beginState.isEmpty()
                || previousState != blockData.beginState)
            break;
        if (TextEditor::TextDocumentLayout::lexerState(endBlock) == -1)
            break;

        previousState = blockData.endState;
        it = it.next();
    }

    if (it == endBlock) // No need to recalculate
        return;

    // update everthing until endBlock
    while (it.isValid() && it != endBlock) {
        recalculateStateAfter(it);
        it = it.next();
    }

    // invalidate everything below by marking the state in endBlock as invalid
    if (it.isValid()) {
        BlockData invalidBlockData;
        saveBlockData(&it, invalidBlockData);
    }
}
示例#21
0
		REQUIRE(description.variables().size() == 37u);
		CHECK(description.variables()[0].axiomLayer() == -1);
		CHECK(description.variables()[0].values()[0].sign() == plasp::sas::Value::Sign::Positive);
		CHECK(description.variables()[0].values()[0].name() == "activate(philosopher-0, forks--pid-rfork)");
		CHECK(description.variables()[36].axiomLayer() == -1);
		CHECK(description.variables()[36].values()[1].sign() == plasp::sas::Value::Sign::Negative);
		CHECK(description.variables()[36].values()[1].name() == "queue-tail-msg(forks-1-, fork)");

		REQUIRE(description.mutexGroups().size() == 8u);
		REQUIRE(description.mutexGroups()[0].facts().size() == 9u);
		CHECK(&description.mutexGroups()[0].facts()[0].value() == &description.variables()[0].values()[0]);
		REQUIRE(description.mutexGroups()[7].facts().size() == 2u);
		CHECK(&description.mutexGroups()[7].facts()[1].value() == &description.variables()[34].values()[1]);

		REQUIRE(description.initialState().facts().size() == 37u);
		CHECK(&description.initialState().facts()[0].value() == &description.variables()[0].values()[8]);
		CHECK(&description.initialState().facts()[36].value() == &description.variables()[36].values()[1]);

		REQUIRE(description.goal().facts().size() == 2u);
		CHECK(&description.goal().facts()[0].value() == &description.variables()[6].values()[0]);
		CHECK(&description.goal().facts()[1].value() == &description.variables()[7].values()[0]);

		REQUIRE(description.operators().size() == 34u);
		CHECK(description.operators()[0].predicate().name() == "activate-trans");
		REQUIRE(description.operators()[0].predicate().arguments().size() == 5u);
		CHECK(description.operators()[0].predicate().arguments()[0] == "philosopher-0");
		CHECK(description.operators()[0].predicate().arguments()[4] == "state-3");
		REQUIRE(description.operators()[0].preconditions().size() == 3u);
		CHECK(&description.operators()[0].preconditions()[0].value() == &description.variables()[4].values()[4]);
		CHECK(&description.operators()[0].preconditions()[1].value() == &description.variables()[16].values()[1]);
 int check(std::string str, bool write){
     return initialState(str,false);
 };
示例#23
0
      /* Compute satellite position & velocity at the given time
       * using this ephemeris.
       *
       *  @throw InvalidRequest if required data has not been stored.
       */
   Xvt GloEphemeris::svXvt(const CommonTime& epoch) const
      throw( gpstk::InvalidRequest )
   {

         // Check that the given epoch is within the available time limits.
         // We have to add a margin of 15 minutes (900 seconds).
      if ( epoch <  (ephTime - 900.0) ||
           epoch >= (ephTime + 900.0)   )
      {
         InvalidRequest e( "Requested time is out of ephemeris data" );
         GPSTK_THROW(e);
      }

         // Values to be returned will be stored here
      Xvt sv;

         // If the exact epoch is found, let's return the values
      if ( epoch == ephTime )       // exact match for epoch
      {

         sv.x[0] = x[0]*1.e3;   // m
         sv.x[1] = x[1]*1.e3;   // m
         sv.x[2] = x[2]*1.e3;   // m
         sv.v[0] = v[0]*1.e3;  // m/sec
         sv.v[1] = v[1]*1.e3;  // m/sec
         sv.v[2] = v[2]*1.e3;  // m/sec

            // In the GLONASS system, 'clkbias' already includes the
            // relativistic correction, therefore we must substract the late
            // from the former.
         sv.relcorr = sv.computeRelativityCorrection();
         sv.clkbias = clkbias + clkdrift * (epoch - ephTime) - sv.relcorr;
         sv.clkdrift = clkdrift;
         sv.frame = ReferenceFrame::PZ90;

            // We are done, let's return
         return sv;

      }

         // Get the data out of the GloRecord structure
      double px( x[0] );   // X coordinate (km)
      double vx( v[0] );   // X velocity   (km/s)
      double ax( a[0] );   // X acceleration (km/s^2)
      double py( x[1] );   // Y coordinate
      double vy( v[1] );   // Y velocity
      double ay( a[1] );   // Y acceleration
      double pz( x[2] );   // Z coordinate
      double vz( v[2] );   // Z velocity
      double az( a[2] );   // Z acceleration

         // We will need some PZ-90 ellipsoid parameters
      PZ90Ellipsoid pz90;
      double we( pz90.angVelocity() );

         // Get sidereal time at Greenwich at 0 hours UT
      double gst( getSidTime( ephTime ) );
      double s0( gst*PI/12.0 );
      YDSTime ytime( ephTime );
      double numSeconds( ytime.sod );
      double s( s0 + we*numSeconds );
      double cs( std::cos(s) );
      double ss( std::sin(s) );

         // Initial state matrix
      Vector<double> initialState(6), accel(3), dxt1(6), dxt2(6), dxt3(6),
                     dxt4(6), tempRes(6);

         // Get the reference state out of GloEphemeris object data. Values
         // must be rotated from PZ-90 to an absolute coordinate system
         // Initial x coordinate (m)
      initialState(0)  = (px*cs - py*ss);
         // Initial y coordinate
      initialState(2)  = (px*ss + py*cs);
         // Initial z coordinate
      initialState(4)  = pz;

         // Initial x velocity   (m/s)
      initialState(1)  = (vx*cs - vy*ss - we*initialState(2) );
         // Initial y velocity
      initialState(3)  = (vx*ss + vy*cs + we*initialState(0) );
         // Initial z velocity
      initialState(5)  = vz;


         // Integrate satellite state to desired epoch using the given step
      double rkStep( step );

      if ( (epoch - ephTime) < 0.0 ) rkStep = step*(-1.0);
      CommonTime workEpoch( ephTime );

      double tolerance( 1e-9 );
      bool done( false );
      while (!done)
      {

            // If we are about to overstep, change the stepsize appropriately
            // to hit our target final time.
         if( rkStep > 0.0 )
         {
            if( (workEpoch + rkStep) > epoch )
               rkStep = (epoch - workEpoch);
         }
         else
         {
            if ( (workEpoch + rkStep) < epoch )
               rkStep = (epoch - workEpoch);
         }

         numSeconds += rkStep;
         s = s0 + we*( numSeconds );
         cs = std::cos(s);
         ss = std::sin(s);

            // Accelerations are computed once per iteration
         accel(0) = ax*cs - ay*ss;
         accel(1) = ax*ss + ay*cs;
         accel(2) = az;

         dxt1 = derivative( initialState, accel );
         for( int j = 0; j < 6; ++j )
            tempRes(j) = initialState(j) + rkStep*dxt1(j)/2.0;

         dxt2 = derivative( tempRes, accel );
         for( int j = 0; j < 6; ++j )
            tempRes(j) = initialState(j) + rkStep*dxt2(j)/2.0;

         dxt3 = derivative( tempRes, accel );
         for( int j = 0; j < 6; ++j )
            tempRes(j) = initialState(j) + rkStep*dxt3(j);

         dxt4 = derivative( tempRes, accel );
         for( int j = 0; j < 6; ++j )
            initialState(j) = initialState(j) + rkStep * ( dxt1(j)
                            + 2.0 * ( dxt2(j) + dxt3(j) ) + dxt4(j) ) / 6.0;


            // If we are within tolerance of the target time, we are done.
         workEpoch += rkStep;
         if ( std::fabs(epoch - workEpoch ) < tolerance )
            done = true;

      }  // End of 'while (!done)...'


      px = initialState(0);
      py = initialState(2);
      pz = initialState(4);
      vx = initialState(1);
      vy = initialState(3);
      vz = initialState(5);

      sv.x[0] = 1000.0*( px*cs + py*ss );         // X coordinate
      sv.x[1] = 1000.0*(-px*ss + py*cs);          // Y coordinate
      sv.x[2] = 1000.0*pz;                        // Z coordinate
      sv.v[0] = 1000.0*( vx*cs + vy*ss + we*(sv.x[1]/1000.0) ); // X velocity
      sv.v[1] = 1000.0*(-vx*ss + vy*cs - we*(sv.x[0]/1000.0) ); // Y velocity
      sv.v[2] = 1000.0*vz;                        // Z velocity

         // In the GLONASS system, 'clkbias' already includes the relativistic
         // correction, therefore we must substract the late from the former.
      sv.relcorr = sv.computeRelativityCorrection();
      sv.clkbias = clkbias + clkdrift * (epoch - ephTime) - sv.relcorr;
      sv.clkdrift = clkdrift;
      sv.frame = ReferenceFrame::PZ90;

         // We are done, let's return
      return sv;


   }  // End of method 'GloEphemeris::svXvt(const CommonTime& t)'
/*!
 * integrate the equations of motion for a particle around a point mass gravitational centre.
 */
void boostIntegratorRestrictedTwoBodyProblem( const double gravParameter,
                                              std::vector< double > &initialOrbitalElements,
                                              const double initialStepSize,
                                              const double startTime,
                                              const double endTime,
                                              std::ostringstream &outputFilePath,
                                              const int dataSaveIntervals )
{
    //! open the output csv file to save data. Declare file headers.
    std::ofstream outputFile;
    outputFile.open( outputFilePath.str( ) );
    outputFile << "x" << ",";
    outputFile << "y" << ",";
    outputFile << "z" << ",";
    outputFile << "vx" << ",";
    outputFile << "vy" << ",";
    outputFile << "vz" << ",";
    outputFile << "t" << std::endl;
    outputFile.precision( 16 );

    //! convert the initial orbital elements to cartesian state
    std::vector< double > initialState( 6, 0.0 );
    initialState = convertKeplerianElementsToCartesianCoordinates( initialOrbitalElements,
                                                                   gravParameter );

    // set up boost odeint
    const double absoluteTolerance = 1.0e-10;
    const double relativeTolerance = 1.0e-10;
    typedef boost::numeric::odeint::runge_kutta_fehlberg78< std::vector< double > > stepperType;

    // state step size guess (at each step this initial guess will be used)
    double stepSizeGuess = initialStepSize;

    // initialize the ode system
    equationsOfMotion restrictedTwoBodyProblem( gravParameter );

    // initialize current state vector and time
    std::vector< double > currentStateVector = initialState;
    double currentTime = startTime;
    double intermediateEndTime = currentTime + dataSaveIntervals;

    // save the initial state vector
    outputFile << currentStateVector[ xPositionIndex ] << ",";
    outputFile << currentStateVector[ yPositionIndex ] << ",";
    outputFile << currentStateVector[ zPositionIndex ] << ",";
    outputFile << currentStateVector[ xVelocityIndex ] << ",";
    outputFile << currentStateVector[ yVelocityIndex ] << ",";
    outputFile << currentStateVector[ zVelocityIndex ] << ",";
    outputFile << currentTime << std::endl;

    // start the integration outer loop
    while( intermediateEndTime <= endTime )
    {
        // perform integration, integrated result stored in currentStateVector
        size_t steps = boost::numeric::odeint::integrate_adaptive(
                            make_controlled( absoluteTolerance, relativeTolerance, stepperType( ) ),
                            restrictedTwoBodyProblem,
                            currentStateVector,
                            currentTime,
                            intermediateEndTime,
                            stepSizeGuess );

        // update the time variables
        currentTime = intermediateEndTime;
        intermediateEndTime = currentTime + dataSaveIntervals;

        // save data
        outputFile << currentStateVector[ xPositionIndex ] << ",";
        outputFile << currentStateVector[ yPositionIndex ] << ",";
        outputFile << currentStateVector[ zPositionIndex ] << ",";
        outputFile << currentStateVector[ xVelocityIndex ] << ",";
        outputFile << currentStateVector[ yVelocityIndex ] << ",";
        outputFile << currentStateVector[ zVelocityIndex ] << ",";
        outputFile << currentTime << std::endl;

    } // end of outer while loop for integration

    outputFile.close( );
}
示例#25
0
void EventDispatcherBase<TDerived>::markDescendantsForEntry()
{
    for (auto state = derived().begin(); state != derived().end(); ++state)
    {
        if (!(state->m_flags & state_type::InEnterSet))
        {
            state.skipChildren();
            continue;
        }

        if (state->isCompound())
        {
            // Exactly one state of a compound state has to be marked for entry.
            bool childMarked = false;
            for (auto child = state.child_begin();
                 child != state.child_end(); ++child)
            {
                if (child->m_flags & state_type::InEnterSet)
                {
                    childMarked = true;
                    break;
                }
            }

            if (!childMarked)
            {
                if (state->m_flags
                    & (state_type::ShallowHistory | state_type::DeepHistory))
                {
                    using history_state_type = ShallowHistoryState<TDerived>;
                    history_state_type* historyState
                            = static_cast<history_state_type*>(&*state);

                    if (historyState->m_latestActiveChild)
                    {
                        historyState->m_latestActiveChild->m_flags |= state_type::InEnterSet;
                        continue;
                    }
                }

                if (state_type* initialState = state->initialState())
                {
                    do
                    {
                        initialState->m_flags |= state_type::InEnterSet;
                        initialState = initialState->parent();
                    } while (initialState != &*state);
                }
                else
                {
                    state->m_children->m_flags |= state_type::InEnterSet;
                }
            }
        }
        else if (state->isParallel())
        {
            // All child states of a parallel state have to be marked for entry.
            for (auto child = state.child_begin();
                 child != state.child_end(); ++child)
            {
                child->m_flags |= state_type::InEnterSet;
            }
        }
    }
}