void testPositionDependence() {
    ReferencePlatform platform;
    System system;
    system.addParticle(1.0);
    system.addParticle(1.0);
    VerletIntegrator integrator(0.01);
    CustomGBForce* force = new CustomGBForce();
    force->addComputedValue("a", "r", CustomGBForce::ParticlePair);
    force->addComputedValue("b", "a+x*y", CustomGBForce::SingleParticle);
    force->addEnergyTerm("b*z", CustomGBForce::SingleParticle);
    force->addEnergyTerm("b1+b2", CustomGBForce::ParticlePair); // = 2*r+x1*y1+x2*y2
    force->addParticle(vector<double>());
    force->addParticle(vector<double>());
    system.addForce(force);
    Context context(system, integrator, platform);
    vector<Vec3> positions(2);
    vector<Vec3> forces(2);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);

    for (int i = 0; i < 5; i++) {
        positions[0] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt));
        positions[1] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt));
        context.setPositions(positions);
        State state = context.getState(State::Forces | State::Energy);
        const vector<Vec3>& forces = state.getForces();
        Vec3 delta = positions[0]-positions[1];
        double r = sqrt(delta.dot(delta));
        double energy = 2*r+positions[0][0]*positions[0][1]+positions[1][0]*positions[1][1];
        for (int j = 0; j < 2; j++)
            energy += positions[j][2]*(r+positions[j][0]*positions[j][1]);
        Vec3 force1(-(1+positions[0][2])*delta[0]/r-(1+positions[0][2])*positions[0][1]-(1+positions[1][2])*delta[0]/r,
                    -(1+positions[0][2])*delta[1]/r-(1+positions[0][2])*positions[0][0]-(1+positions[1][2])*delta[1]/r,
                    -(1+positions[0][2])*delta[2]/r-(r+positions[0][0]*positions[0][1])-(1+positions[1][2])*delta[2]/r);
        Vec3 force2((1+positions[0][2])*delta[0]/r+(1+positions[1][2])*delta[0]/r-(1+positions[1][2])*positions[1][1],
                    (1+positions[0][2])*delta[1]/r+(1+positions[1][2])*delta[1]/r-(1+positions[1][2])*positions[1][0],
                    (1+positions[0][2])*delta[2]/r+(1+positions[1][2])*delta[2]/r-(r+positions[1][0]*positions[1][1]));
        ASSERT_EQUAL_VEC(force1, forces[0], 1e-4);
        ASSERT_EQUAL_VEC(force2, forces[1], 1e-4);
        ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), 0.02);

        // Take a small step in the direction of the energy gradient and see whether the potential energy changes by the expected amount.

        double norm = 0.0;
        for (int i = 0; i < (int) forces.size(); ++i)
            norm += forces[i].dot(forces[i]);
        norm = std::sqrt(norm);
        const double stepSize = 1e-3;
        double step = 0.5*stepSize/norm;
        vector<Vec3> positions2(2), positions3(2);
        for (int i = 0; i < (int) positions.size(); ++i) {
            Vec3 p = positions[i];
            Vec3 f = forces[i];
            positions2[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step);
            positions3[i] = Vec3(p[0]+f[0]*step, p[1]+f[1]*step, p[2]+f[2]*step);
        }
        context.setPositions(positions2);
        State state2 = context.getState(State::Energy);
        context.setPositions(positions3);
        State state3 = context.getState(State::Energy);
        ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state3.getPotentialEnergy())/stepSize, 1e-3);
    }
}
Example #2
0
pair<vector<int>, vector<int> > BFS::solve() {
  // inicializa o conjunto de estados vistos
  states = 1;
  parent.clear();

  // enfileira o estado inicial
  State initial = {"", 0, 0};
  queue<State> Q;
  parent[initial] = make_pair(initial, -1);
  Q.push(initial);

  // continua enquanto houver estados a serem visitados OU
  // o estado final ainda não tiver sido encontrado
  while (!Q.empty()) {

    // retira o primeiro estado da fila
    State cur = Q.front();
    Q.pop();

    // checa se é um estado final
    if (cur.is_final()) {
      // constrói o caminho a partir do map parent e retorna as sequências
      // resultantes
      vector<int> res[2];

      // enquanto o estado atual não for o estado inicial, sobe um nível na
      // árvore e atualiza as sequências resultantes
      while (!cur.is_initial()) {
        State prev;
        int step;
        tie(prev, step) = parent[cur];
        res[prev.current ^ 1].push_back(step);
        cur = prev;
      }

      reverse(res[0].begin(), res[0].end());
      reverse(res[1].begin(), res[1].end());

      // retorna uma solução
      return {res[0], res[1]};
    }

    // se não for estado final, descobre os vizinhos ainda não visitados
    int addon = cur.current ^ 1;
    const vector<string>& sequences = get_sequences(addon);

    // testa cada possibilidade de sequência de movimentos a ser adicionada
    // à coreografia do dançarino cur.current
    for (unsigned i = 0; i < sequences.size(); i++) {
      const string& s = sequences[i];
      int matches = 0;
      int s_sz = s.size();
      int suffix_sz = cur.suffix.size();

      for (; matches < s_sz && matches < suffix_sz; matches++)
        if (s[matches] != cur.suffix[matches])
          break;

      if (matches < s_sz && matches != suffix_sz)
        continue;

      // computa os parâmetros do vizinho. existem dois casos:
      State next;
      if (matches == suffix_sz) {
        // o dançarino detentor da cauda muda
        next = {s.substr(matches), addon, 1};
      } else {
        // o dançarino detentor da cauda permanece igual
        next = {cur.suffix.substr(matches), cur.current, 1};
      }

      // checa se o vizinho já foi visitado
      if (parent.find(next) == parent.end()) {
        // caso não tenha sido, enfileira o mesmo, armazenando o pai na árvore
        // de busca e a transição (sequência de movimentos) que foi utilizada
        parent[next] = {cur, i};
        states++;
        Q.push(next);
      }
    }
  }

  // nenhuma solução foi encontrada
  return {{}, {}};
}
Example #3
0
int RWGame::run()
{
	last_clock_time = clock.now();

	// Loop until the window is closed or we run out of state.
	while (window.isOpen() && StateManager::get().states.size()) {
		State* state = StateManager::get().states.back();

		RW_PROFILE_FRAME_BOUNDARY();
		
		RW_PROFILE_BEGIN("Input");
		SDL_Event event;
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
			case SDL_QUIT:
				window.close();
				break;

			case SDL_WINDOWEVENT:
				switch (event.window.event) {
				case SDL_WINDOWEVENT_FOCUS_GAINED:
					inFocus = true;
					break;

				case SDL_WINDOWEVENT_FOCUS_LOST:
					inFocus = false;
					break;
				}
				break;

			case SDL_KEYDOWN:
				globalKeyEvent(event);
				break;

			case SDL_MOUSEMOTION:
				event.motion.xrel *= MOUSE_SENSITIVITY_SCALE;
				event.motion.yrel *= MOUSE_SENSITIVITY_SCALE;
				break;
			}

			RW_PROFILE_BEGIN("State");
			state->handleEvent(event);
			RW_PROFILE_END()
		}
		RW_PROFILE_END();

		auto now = clock.now();
		float timer = std::chrono::duration<float>(now - last_clock_time).count();
		last_clock_time = now;
		accum += timer * timescale;

		RW_PROFILE_BEGIN("Update");
		if ( accum >= GAME_TIMESTEP ) {
			RW_PROFILE_BEGIN("state");
			StateManager::get().tick(GAME_TIMESTEP);
			RW_PROFILE_END();

			if (StateManager::get().states.size() == 0) {
				break;
			}

			RW_PROFILE_BEGIN("engine");
			tick(GAME_TIMESTEP);
			RW_PROFILE_END();
			
			accum -= GAME_TIMESTEP;
			
			// Throw away time if the accumulator reaches too high.
			if ( accum > GAME_TIMESTEP * 5.f )
			{
				accum = 0.f;
			}
		}
		RW_PROFILE_END();

		float alpha = fmod(accum, GAME_TIMESTEP) / GAME_TIMESTEP;
		if( ! state->shouldWorldUpdate() )
		{
			alpha = 1.f;
		}

		RW_PROFILE_BEGIN("Render");
		RW_PROFILE_BEGIN("engine");
		render(alpha, timer);
		RW_PROFILE_END();

		RW_PROFILE_BEGIN("state");
		if (StateManager::get().states.size() > 0) {
			StateManager::get().draw(renderer);
		}
		RW_PROFILE_END();
		RW_PROFILE_END();

		renderProfile();

		window.swap();
	}

    if( httpserver_thread )
    {
        httpserver_thread->join();
    }

	return 0;
}
int player_prepare(State **ps, int from_thread)
{
	int audio_index = -1;
	int video_index = -1;
	int i;

	State *state = *ps;
	
	if (state && state->pFormatCtx) {
		avformat_close_input(&state->pFormatCtx);
	}

	state->pFormatCtx = NULL;
	state->audio_stream = -1;
	state->video_stream = -1;
	state->audio_st = NULL;
	state->video_st = NULL;

    printf("Path: %s\n", state->filename);

    AVDictionary *options = NULL;
    av_dict_set(&options, "user-agent", "FFmpegMediaPlayer", 0);
    
    if (avformat_open_input(&state->pFormatCtx, state->filename, NULL, &options) != 0) {
	    printf("Input file could not be opened\n");
		*ps = NULL;
    	return FAILURE;
    }

	if (avformat_find_stream_info(state->pFormatCtx, NULL) < 0) {
	    printf("Stream information could not be retrieved\n");
	    avformat_close_input(&state->pFormatCtx);
		*ps = NULL;
    	return FAILURE;
	}

	char duration[30] = "0";
	get_duration(state->pFormatCtx, duration);
	av_dict_set(&state->pFormatCtx->metadata, DURATION, duration, 0);
	
    // Find the first audio and video stream
	for (i = 0; i < state->pFormatCtx->nb_streams; i++) {
		if (state->pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO && video_index < 0) {
			video_index = i;
		}

		if (state->pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO && audio_index < 0) {
			audio_index = i;
		}
		
		set_codec(state->pFormatCtx, i);
	}

	if (audio_index >= 0) {
		stream_component_open(state, audio_index, from_thread);
	}

	if (video_index >= 0) {
		stream_component_open(state, video_index, from_thread);
	}

	if (state->video_stream < 0 && state->audio_stream < 0) {
	    avformat_close_input(&state->pFormatCtx);
		*ps = NULL;
		return FAILURE;
	}

	state->pFormatCtx->interrupt_callback.callback = decode_interrupt_cb;
	state->pFormatCtx->interrupt_callback.opaque = state;
	
    // fill the inital buffer
	AVPacket packet;
	memset(&packet, 0, sizeof(packet)); //make sure we can safely free it

	int j, ret;
    int bytes_written = 0;
	
	while (bytes_written < state->buffer_size) {
		for (j = 0; j < state->pFormatCtx->nb_streams; j++) {
			//av_init_packet(&packet);
			ret = av_read_frame(state->pFormatCtx, &packet);

			if (ret < 0) {
				if (ret == AVERROR_EOF || url_feof(state->pFormatCtx->pb)) {
					//break;
			    }
			}

			int frame_size_ptr = 0;
			ret = decode_frame_from_packet(state, &packet, &frame_size_ptr, from_thread);
		    __android_log_print(ANDROID_LOG_ERROR, "TAG", "Fill buffer: %d -> %d", frame_size_ptr, state->buffer_size);
			bytes_written = bytes_written + frame_size_ptr;
			av_free_packet(&packet);
		}
	}
		
	*ps = state;

	state->notify_callback(state->clazz, MEDIA_PREPARED, 0, 0, from_thread);

	return SUCCESS;
}
Example #5
0
bool HDPSolver::dfs(mlcore::State* s, double plaus)
{
    auto curTime = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::milliseconds>(
            curTime - beginTime_).count();
    if (maxTime_ > -1 && duration > maxTime_)
        return false;

    if (plaus > minPlaus_) {
        return false;
    }
    if (s->checkBits(mdplib::SOLVED) ||
            problem_->goal(s) ||
            s->deadEnd()) {
        s->setBits(mdplib::SOLVED);
        solvedStates_.insert(s);
        return false;
    }
    bool neededUpdate = false;
    if (residual(problem_, s) > epsilon_) {
        neededUpdate = true;
        // mini-gpt adds this loop, but this actually worsens convergence.
        // do {
        //     bellmanUpdate(problem_, s);
        // } while (residual(problem_, s) > epsilon_);
        // return true;
    }
    inStack_.insert(s);
    stateStack_.push_back(s);
    indices_[s] = index_;
    low_[s] = index_;
    index_++;

    Action* a = greedyAction(problem_, s);

    if (s->deadEnd()) {
        return false;   // state is a dead-end, nothing to do
    }

    list<Successor> successors = problem_->transition(s, a);
    if (minPlaus_ != INT_MAX)
        computeKappa(successors, kappaList_);
    int i = 0;
    for (auto const & successor : successors) {
        State* next = successor.su_state;
        if (indices_.count(next) == 0) {
            neededUpdate |= dfs(next, plaus + kappaList_.at(i));
            low_[s] = std::min(low_[s], low_[next]);
        } else if (inStack_.count(next) > 0) {
            // State is in the current connected component stack.
            low_[s] = std::min(low_[s], indices_[next]);
        }
        i++;
    }
    if (neededUpdate) {
        bellmanUpdate(problem_, s);
        // same as above (mini-gpt code).
        // do {
        //     bellmanUpdate(problem_, s);
        // } while (residual(problem_, s) > epsilon_);
        //return true;
    } else if (indices_[s] == low_[s]) {
        // State s is the root of a connected component.
        while (true) {
            State* currentState = stateStack_.back();
            stateStack_.pop_back();
            inStack_.erase(currentState);
            currentState->setBits(mdplib::SOLVED);
            solvedStates_.insert(currentState);
            if (currentState == s)
                break;
        }
    }
    return neededUpdate;
}
Example #6
0
void generateDepthBias(GLBackend::GLState::Commands& commands, const State& state) {
     commands.push_back(CommandPointer(new CommandDepthBias(&GLBackend::do_setStateDepthBias, Vec2(state.getDepthBias(), state.getDepthBiasSlopeScale()))));
}
Example #7
0
void generateBlend(GLBackend::GLState::Commands& commands, const State& state) {
    commands.push_back(CommandPointer(new CommandBlend(&GLBackend::do_setStateBlend, state.getBlendFunction())));
}
Example #8
0
void testPME(bool triclinic) {
    // Create a cloud of random point charges.

    const int numParticles = 51;
    const double boxWidth = 5.0;
    const double cutoff = 1.0;
    Vec3 boxVectors[3];
    if (triclinic) {
        boxVectors[0] = Vec3(boxWidth, 0, 0);
        boxVectors[1] = Vec3(0.2*boxWidth, boxWidth, 0);
        boxVectors[2] = Vec3(-0.3*boxWidth, -0.1*boxWidth, boxWidth);
    }
    else {
        boxVectors[0] = Vec3(boxWidth, 0, 0);
        boxVectors[1] = Vec3(0, boxWidth, 0);
        boxVectors[2] = Vec3(0, 0, boxWidth);
    }
    System system;
    system.setDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
    NonbondedForce* force = new NonbondedForce();
    system.addForce(force);
    vector<Vec3> positions(numParticles);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);

    for (int i = 0; i < numParticles; i++) {
        system.addParticle(1.0);
        force->addParticle(-1.0+i*2.0/(numParticles-1), 1.0, 0.0);
        positions[i] = Vec3(boxWidth*genrand_real2(sfmt), boxWidth*genrand_real2(sfmt), boxWidth*genrand_real2(sfmt));
    }
    force->setNonbondedMethod(NonbondedForce::PME);
    force->setCutoffDistance(cutoff);
    force->setReciprocalSpaceForceGroup(1);
    force->setEwaldErrorTolerance(1e-4);
    
    // Compute the reciprocal space forces with the reference platform.
    
    Platform& platform = Platform::getPlatformByName("Reference");
    VerletIntegrator integrator(0.01);
    Context context(system, integrator, platform);
    context.setPositions(positions);
    State refState = context.getState(State::Forces | State::Energy, false, 1<<1);
    
    // Now compute them with the optimized kernel.
    
    double alpha;
    int gridx, gridy, gridz;
    NonbondedForceImpl::calcPMEParameters(system, *force, alpha, gridx, gridy, gridz, false);
    CpuCalcPmeReciprocalForceKernel pme(CalcPmeReciprocalForceKernel::Name(), platform);
    IO io;
    double sumSquaredCharges = 0;
    for (int i = 0; i < numParticles; i++) {
        io.posq.push_back(positions[i][0]);
        io.posq.push_back(positions[i][1]);
        io.posq.push_back(positions[i][2]);
        double charge, sigma, epsilon;
        force->getParticleParameters(i, charge, sigma, epsilon);
        io.posq.push_back(charge);
        sumSquaredCharges += charge*charge;
    }
    double ewaldSelfEnergy = -ONE_4PI_EPS0*alpha*sumSquaredCharges/sqrt(M_PI);
    pme.initialize(gridx, gridy, gridz, numParticles, alpha, true);
    pme.beginComputation(io, boxVectors, true);
    double energy = pme.finishComputation(io);

    // See if they match.
    
    ASSERT_EQUAL_TOL(refState.getPotentialEnergy(), energy+ewaldSelfEnergy, 1e-3);
    for (int i = 0; i < numParticles; i++)
        ASSERT_EQUAL_VEC(refState.getForces()[i], Vec3(io.force[4*i], io.force[4*i+1], io.force[4*i+2]), 1e-3);
}
Example #9
0
void testLJPME(bool triclinic) {
    // Create a cloud of random LJ particles.

    const int numParticles = 51;
    const double boxWidth = 5.0;
    const double cutoff = 1.0;
    const double alpha = 2.91842;
    Vec3 boxVectors[3];
    if (triclinic) {
        boxVectors[0] = Vec3(boxWidth, 0, 0);
        boxVectors[1] = Vec3(0.2*boxWidth, boxWidth, 0);
        boxVectors[2] = Vec3(-0.3*boxWidth, -0.1*boxWidth, boxWidth);
    }
    else {
        boxVectors[0] = Vec3(boxWidth, 0, 0);
        boxVectors[1] = Vec3(0, boxWidth, 0);
        boxVectors[2] = Vec3(0, 0, boxWidth);
    }
    System system;
    system.setDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
    NonbondedForce* force = new NonbondedForce();
    system.addForce(force);
    vector<Vec3> positions(numParticles);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);

    for (int i = 0; i < numParticles; i++) {
        system.addParticle(1.0);
        force->addParticle(0, 0.5, 1.0);
        positions[i] = Vec3(boxWidth*genrand_real2(sfmt), boxWidth*genrand_real2(sfmt), boxWidth*genrand_real2(sfmt));
    }
    force->setNonbondedMethod(NonbondedForce::LJPME);
    force->setCutoffDistance(cutoff);
    force->setReciprocalSpaceForceGroup(1);
    force->setLJPMEParameters(alpha, 64, 64, 64);
    
    // Compute the reciprocal space forces with the reference platform.
    
    Platform& platform = Platform::getPlatformByName("Reference");
    VerletIntegrator integrator(0.01);
    Context context(system, integrator, platform);
    context.setPositions(positions);
    State refState = context.getState(State::Forces | State::Energy, false, 1<<1);
    
    // Now compute them with the optimized kernel.
    
    CpuCalcDispersionPmeReciprocalForceKernel pme(CalcDispersionPmeReciprocalForceKernel::Name(), platform);
    IO io;
    double ewaldSelfEnergy = 0;
    for (int i = 0; i < numParticles; i++) {
        io.posq.push_back(positions[i][0]);
        io.posq.push_back(positions[i][1]);
        io.posq.push_back(positions[i][2]);
        double charge, sigma, epsilon;
        force->getParticleParameters(i, charge, sigma, epsilon);
        io.posq.push_back(pow(sigma, 3.0) * 2.0*sqrt(epsilon));
        ewaldSelfEnergy += pow(alpha*sigma, 6.0) * epsilon / 3.0;
    }
    pme.initialize(64, 64, 64, numParticles, alpha, true);
    pme.beginComputation(io, boxVectors, true);
    double energy = pme.finishComputation(io);

    // See if they match.
    
    ASSERT_EQUAL_TOL(refState.getPotentialEnergy(), energy+ewaldSelfEnergy, 1e-3);
    for (int i = 0; i < numParticles; i++)
        ASSERT_EQUAL_VEC(refState.getForces()[i], Vec3(io.force[4*i], io.force[4*i+1], io.force[4*i+2]), 1e-3);
}
Example #10
0
void compile(State& state, Safepoint::Result& safepointResult)
{
    char* error = 0;
    
    {
        GraphSafepoint safepoint(state.graph, safepointResult);
        
        LLVMMCJITCompilerOptions options;
        llvm->InitializeMCJITCompilerOptions(&options, sizeof(options));
        options.OptLevel = Options::llvmBackendOptimizationLevel();
        options.NoFramePointerElim = true;
        if (Options::useLLVMSmallCodeModel())
            options.CodeModel = LLVMCodeModelSmall;
        options.EnableFastISel = enableLLVMFastISel;
        options.MCJMM = llvm->CreateSimpleMCJITMemoryManager(
            &state, mmAllocateCodeSection, mmAllocateDataSection, mmApplyPermissions, mmDestroy);
    
        LLVMExecutionEngineRef engine;
        
        if (isARM64()) {
#if OS(DARWIN)
            llvm->SetTarget(state.module, "arm64-apple-ios");
#elif OS(LINUX)
            llvm->SetTarget(state.module, "aarch64-linux-gnu");
#else
#error "Unrecognized OS"
#endif
        }

        if (llvm->CreateMCJITCompilerForModule(&engine, state.module, &options, sizeof(options), &error)) {
            dataLog("FATAL: Could not create LLVM execution engine: ", error, "\n");
            CRASH();
        }
        
        // At this point we no longer own the module.
        LModule module = state.module;
        state.module = nullptr;

        // The data layout also has to be set in the module. Get the data layout from the MCJIT and apply
        // it to the module.
        LLVMTargetMachineRef targetMachine = llvm->GetExecutionEngineTargetMachine(engine);
        LLVMTargetDataRef targetData = llvm->GetExecutionEngineTargetData(engine);
        char* stringRepOfTargetData = llvm->CopyStringRepOfTargetData(targetData);
        llvm->SetDataLayout(module, stringRepOfTargetData);
        free(stringRepOfTargetData);

        LLVMPassManagerRef functionPasses = 0;
        LLVMPassManagerRef modulePasses;

        if (Options::llvmSimpleOpt()) {
            modulePasses = llvm->CreatePassManager();
            llvm->AddTargetData(targetData, modulePasses);
            llvm->AddAnalysisPasses(targetMachine, modulePasses);
            llvm->AddPromoteMemoryToRegisterPass(modulePasses);
            llvm->AddGlobalOptimizerPass(modulePasses);
            llvm->AddFunctionInliningPass(modulePasses);
            llvm->AddPruneEHPass(modulePasses);
            llvm->AddGlobalDCEPass(modulePasses);
            llvm->AddConstantPropagationPass(modulePasses);
            llvm->AddAggressiveDCEPass(modulePasses);
            llvm->AddInstructionCombiningPass(modulePasses);
            // BEGIN - DO NOT CHANGE THE ORDER OF THE ALIAS ANALYSIS PASSES
            llvm->AddTypeBasedAliasAnalysisPass(modulePasses);
            llvm->AddBasicAliasAnalysisPass(modulePasses);
            // END - DO NOT CHANGE THE ORDER OF THE ALIAS ANALYSIS PASSES
            llvm->AddGVNPass(modulePasses);
            llvm->AddCFGSimplificationPass(modulePasses);
            llvm->AddDeadStoreEliminationPass(modulePasses);
            
            if (enableLLVMFastISel)
                llvm->AddLowerSwitchPass(modulePasses);

            llvm->RunPassManager(modulePasses, module);
        } else {
            LLVMPassManagerBuilderRef passBuilder = llvm->PassManagerBuilderCreate();
            llvm->PassManagerBuilderSetOptLevel(passBuilder, Options::llvmOptimizationLevel());
            llvm->PassManagerBuilderUseInlinerWithThreshold(passBuilder, 275);
            llvm->PassManagerBuilderSetSizeLevel(passBuilder, Options::llvmSizeLevel());
        
            functionPasses = llvm->CreateFunctionPassManagerForModule(module);
            modulePasses = llvm->CreatePassManager();
        
            llvm->AddTargetData(llvm->GetExecutionEngineTargetData(engine), modulePasses);
        
            llvm->PassManagerBuilderPopulateFunctionPassManager(passBuilder, functionPasses);
            llvm->PassManagerBuilderPopulateModulePassManager(passBuilder, modulePasses);
        
            llvm->PassManagerBuilderDispose(passBuilder);
        
            llvm->InitializeFunctionPassManager(functionPasses);
            for (LValue function = llvm->GetFirstFunction(module); function; function = llvm->GetNextFunction(function))
                llvm->RunFunctionPassManager(functionPasses, function);
            llvm->FinalizeFunctionPassManager(functionPasses);
        
            llvm->RunPassManager(modulePasses, module);
        }

        if (shouldShowDisassembly() || verboseCompilationEnabled())
            state.dumpState(module, "after optimization");
        
        // FIXME: Need to add support for the case where JIT memory allocation failed.
        // https://bugs.webkit.org/show_bug.cgi?id=113620
        state.generatedFunction = reinterpret_cast<GeneratedFunction>(llvm->GetPointerToGlobal(engine, state.function));
        if (functionPasses)
            llvm->DisposePassManager(functionPasses);
        llvm->DisposePassManager(modulePasses);
        llvm->DisposeExecutionEngine(engine);
    }

    if (safepointResult.didGetCancelled())
        return;
    RELEASE_ASSERT(!state.graph.m_vm.heap.isCollecting());
    
    if (state.allocationFailed)
        return;
    
    if (shouldShowDisassembly()) {
        for (unsigned i = 0; i < state.jitCode->handles().size(); ++i) {
            ExecutableMemoryHandle* handle = state.jitCode->handles()[i].get();
            dataLog(
                "Generated LLVM code for ",
                CodeBlockWithJITType(state.graph.m_codeBlock, JITCode::FTLJIT),
                " #", i, ", ", state.codeSectionNames[i], ":\n");
            disassemble(
                MacroAssemblerCodePtr(handle->start()), handle->sizeInBytes(),
                "    ", WTF::dataFile(), LLVMSubset);
        }
        
        for (unsigned i = 0; i < state.jitCode->dataSections().size(); ++i) {
            DataSection* section = state.jitCode->dataSections()[i].get();
            dataLog(
                "Generated LLVM data section for ",
                CodeBlockWithJITType(state.graph.m_codeBlock, JITCode::FTLJIT),
                " #", i, ", ", state.dataSectionNames[i], ":\n");
            dumpDataSection(section, "    ");
        }
    }
    
    std::unique_ptr<RegisterAtOffsetList> registerOffsets = parseUnwindInfo(
        state.unwindDataSection, state.unwindDataSectionSize,
        state.generatedFunction);
    if (shouldShowDisassembly()) {
        dataLog("Unwind info for ", CodeBlockWithJITType(state.graph.m_codeBlock, JITCode::FTLJIT), ":\n");
        dataLog("    ", *registerOffsets, "\n");
    }
    state.graph.m_codeBlock->setCalleeSaveRegisters(WTF::move(registerOffsets));
    
    if (state.stackmapsSection && state.stackmapsSection->size()) {
        if (shouldShowDisassembly()) {
            dataLog(
                "Generated LLVM stackmaps section for ",
                CodeBlockWithJITType(state.graph.m_codeBlock, JITCode::FTLJIT), ":\n");
            dataLog("    Raw data:\n");
            dumpDataSection(state.stackmapsSection.get(), "    ");
        }
        
        RefPtr<DataView> stackmapsData = DataView::create(
            ArrayBuffer::create(state.stackmapsSection->base(), state.stackmapsSection->size()));
        state.jitCode->stackmaps.parse(stackmapsData.get());
    
        if (shouldShowDisassembly()) {
            dataLog("    Structured data:\n");
            state.jitCode->stackmaps.dumpMultiline(WTF::dataFile(), "        ");
        }
        
        StackMaps::RecordMap recordMap = state.jitCode->stackmaps.computeRecordMap();
        fixFunctionBasedOnStackMaps(
            state, state.graph.m_codeBlock, state.jitCode.get(), state.generatedFunction,
            recordMap);
        if (state.allocationFailed)
            return;
        
        if (shouldShowDisassembly() || Options::asyncDisassembly()) {
            for (unsigned i = 0; i < state.jitCode->handles().size(); ++i) {
                if (state.codeSectionNames[i] != SECTION_NAME("text"))
                    continue;
                
                ExecutableMemoryHandle* handle = state.jitCode->handles()[i].get();
                
                CString header = toCString(
                    "Generated LLVM code after stackmap-based fix-up for ",
                    CodeBlockWithJITType(state.graph.m_codeBlock, JITCode::FTLJIT),
                    " in ", state.graph.m_plan.mode, " #", i, ", ",
                    state.codeSectionNames[i], ":\n");
                
                if (Options::asyncDisassembly()) {
                    disassembleAsynchronously(
                        header, MacroAssemblerCodeRef(handle), handle->sizeInBytes(), "    ",
                        LLVMSubset);
                    continue;
                }
                
                dataLog(header);
                disassemble(
                    MacroAssemblerCodePtr(handle->start()), handle->sizeInBytes(),
                    "    ", WTF::dataFile(), LLVMSubset);
            }
        }
    }
}
Example #11
0
void test_water2_dpme_energies_forces_no_exclusions() {
    const double cutoff = 7.0*OpenMM::NmPerAngstrom;
    const double dalpha = 4.0124063605;
    const int grid = 32;
    NonbondedForce* forceField = new NonbondedForce();

    vector<Vec3> positions;
    vector<double> epsvals;
    vector<double> sigvals;
    vector<pair<int, int> > bonds;
    System system;

    const int NATOMS = 6;
    double boxEdgeLength = 25*OpenMM::NmPerAngstrom;

    make_waterbox(NATOMS, boxEdgeLength, forceField,  positions, epsvals, sigvals, bonds, system, false);
    forceField->setNonbondedMethod(OpenMM::NonbondedForce::LJPME);
    forceField->setPMEParameters(0.0f, grid, grid, grid);
    forceField->setReciprocalSpaceForceGroup(1);
    forceField->setLJPMEParameters(dalpha, grid, grid, grid);
    forceField->setCutoffDistance(cutoff);
    forceField->setReactionFieldDielectric(1.0);
    system.addForce(forceField);

    // Reference calculation
    VerletIntegrator integrator(0.01);
    Platform& platform = Platform::getPlatformByName("Reference");
    Context context(system, integrator, platform);
    context.setPositions(positions);
    State state = context.getState(State::Forces | State::Energy, false, 1<<1);
    double refenergy = state.getPotentialEnergy();
    const vector<Vec3>& refforces = state.getForces();

    // Optimized CPU calculation
    CpuCalcDispersionPmeReciprocalForceKernel pme(CalcPmeReciprocalForceKernel::Name(), platform);
    IO io;
    double selfEwaldEnergy = 0;
    double dalpha6 = pow(dalpha, 6.0);
    for (int i = 0; i < NATOMS; i++) {
        io.posq.push_back((float)positions[i][0]);
        io.posq.push_back((float)positions[i][1]);
        io.posq.push_back((float)positions[i][2]);
        double c6 = 8.0f * pow(sigvals[i], 3) * epsvals[i];
        io.posq.push_back(c6);
        selfEwaldEnergy += dalpha6 * c6 * c6 / 12.0;
    }
    pme.initialize(grid, grid, grid, NATOMS, dalpha, false);
    Vec3 boxVectors[3];
    system.getDefaultPeriodicBoxVectors(boxVectors[0], boxVectors[1], boxVectors[2]);
    pme.beginComputation(io, boxVectors, true);
    double recenergy = pme.finishComputation(io);

    ASSERT_EQUAL_TOL(recenergy, -2.179629087, 5e-3);
    ASSERT_EQUAL_TOL(selfEwaldEnergy, 1.731404285, 1e-5);

    std::vector<Vec3> knownforces(6);
    knownforces[0] = Vec3(    -1.890360546,    -1.890723915,    -1.879662698);
    knownforces[1] = Vec3( -0.003161352455, -0.000922244929, -0.005391616425);
    knownforces[2] = Vec3( 0.0009199035545, -0.001453894176, -0.006188087146);
    knownforces[3] = Vec3(     1.887108856,     1.887241446,      1.89644647);
    knownforces[4] = Vec3( 0.0008242336483,  0.003778910089, -0.002116131106);
    knownforces[5] = Vec3(  0.004912763044,  0.002324059399, -0.002844482646);
    for (int i = 0; i < NATOMS; i++)
        ASSERT_EQUAL_VEC(refforces[i], knownforces[i], 5e-3);

    recenergy += selfEwaldEnergy;

    // See if they match.

    ASSERT_EQUAL_TOL(refenergy, recenergy, 1e-3);
    for (int i = 0; i < NATOMS; i++)
        ASSERT_EQUAL_VEC(refforces[i], Vec3(io.force[4*i], io.force[4*i+1], io.force[4*i+2]), 5e-3);

}
Example #12
0
/**
 * If the loading fails, it shows an error, otherwise moves on to the game.
 */
void StartState::think()
{
	State::think();
	_timer->think(this, 0);

	switch (loading)
	{
	case LOADING_FAILED:
	{
		CrossPlatform::flashWindow(_game->getScreen()->getWindow());
		addLine(L"");
		addLine(L"ERROR: " + Language::utf8ToWstr(error));
		addLine(L"Make sure you installed OpenXcom correctly.");
		addLine(L"Check the wiki documentation for more details.");
		addLine(L"");
#ifdef __ANDROID__
		std::wstring wsDataFolder(Language::utf8ToWstr(Options::getDataFolder()));
		addLine(L"Android users: your data folder is located at:");
		addLine(wsDataFolder);
		addLine(L"(as reported by your system)");
		addLine(L"");
#endif
		addLine(L"Press any key to continue.");
		loading = LOADING_DONE;
		break;
	}
	case LOADING_SUCCESSFUL:
		CrossPlatform::flashWindow(_game->getScreen()->getWindow());
		Log(LOG_INFO) << "OpenXcom started successfully!";
		if (!Options::reload && Options::playIntro)
		{
			bool letterbox = Options::keepAspectRatio;
			Options::keepAspectRatio = true;
			Options::baseXResolution = Screen::ORIGINAL_WIDTH;
			Options::baseYResolution = Screen::ORIGINAL_HEIGHT;
			_game->getScreen()->resetDisplay(false);
			_game->setState(new IntroState(letterbox));
		}
		else
		{
			Screen::updateScale(Options::geoscapeScale, Options::geoscapeScale, Options::baseXGeoscape, Options::baseYGeoscape, true);
			_game->getScreen()->resetDisplay(false);
			State *state = new MainMenuState;
			_game->setState(state);
			// Check for mod loading errors
			if (!Options::badMods.empty())
			{
				std::wostringstream error;
				error << tr("STR_MOD_UNSUCCESSFUL") << L'\x02';
				for (std::vector<std::string>::iterator i = Options::badMods.begin(); i != Options::badMods.end(); ++i)
				{
					error << Language::fsToWstr(*i) << L'\n';
				}
				Options::badMods.clear();
				_game->pushState(new ErrorMessageState(error.str(), state->getPalette(), Palette::blockOffset(8)+10, "BACK01.SCR", 6));
			}
			Options::reload = false;
		}
		_game->getCursor()->setVisible(true);
		_game->getFpsCounter()->setVisible(Options::fpsCounter);
		break;
	default:
		break;
	}
}
Example #13
0
ReachabilityResult IndexedBestFS::reachable(const PetriNet &net,
											const MarkVal *m0,
											const VarVal *v0,
											const BoolVal *ba,
											PQL::Condition *query){
	StateAllocator<> allocator(net);

	State* s0 = allocator.createState();
	memcpy(s0->marking(), m0, sizeof(MarkVal) * net.numberOfPlaces());
	memcpy(s0->intValuation(), v0, sizeof(VarVal) * net.numberOfIntVariables());
	memcpy(s0->boolValuation(), ba, sizeof(BoolVal) * net.numberOfBoolVariables());

	if(query->evaluate(*s0))
		return ReachabilityResult(ReachabilityResult::Satisfied, "Satisfied initially", 0, 0);

	//Initialize subclasses
	MonotonicityContext context(&net, query);
	context.analyze();

	//Initialise StateSet
	IndexedBestFSStateSet states(net, &context, _distanceStrategy, query, _varianceFirst);
	states.add(s0);

	//Allocate new state
	State* ns = allocator.createState();
	int count = 0;
	BigInt expandedStates = 0;
	BigInt exploredStates = 0;
	BigInt transitionFired  = 0;
	size_t max = 1;
	State* s = states.getNextState();
	while(s){
		if(count++ & 1<<16){
			count = 0;
			if(states.waitingSize() > max)
				max = states.waitingSize();
			this->reportProgress((double)(max - states.waitingSize()) / ((double)(max)));
			if(this->abortRequested())
				return ReachabilityResult(ReachabilityResult::Unknown,
										  "Query aborted!");
		}

		// Attempt to fire each transition
		for(unsigned int t = 0; t < net.numberOfTransitions(); t++){
			if(net.fire(t, s, ns)){
				//If it's new
				transitionFired++;
				if(states.add(ns)){
					exploredStates++;
					//Set parent and transition for the state
					ns->setParent(s);
					ns->setTransition(t);

					//Test query
					if(query->evaluate(*ns)){
						//ns->dumpTrace(net);
						return ReachabilityResult(ReachabilityResult::Satisfied,
												  "Query was satified!", expandedStates, exploredStates, transitionFired, states.getCountRemove(), ns->pathLength(), ns->trace());
					}

					//Allocate new state, as states take ownership
					ns = allocator.createState();
				}
			}
		}
		//Take something out of the queue
		expandedStates++;
		s = states.getNextState();
	}

	return ReachabilityResult(ReachabilityResult::NotSatisfied,
							  "Query cannot be satisfied!", expandedStates, exploredStates, transitionFired, states.getCountRemove());
}
void testExclusions() {
    ReferencePlatform platform;
    for (int i = 3; i < 4; i++) {
        System system;
        system.addParticle(1.0);
        system.addParticle(1.0);
        VerletIntegrator integrator(0.01);
        CustomGBForce* force = new CustomGBForce();
        force->addComputedValue("a", "r", i < 2 ? CustomGBForce::ParticlePair : CustomGBForce::ParticlePairNoExclusions);
        force->addEnergyTerm("a", CustomGBForce::SingleParticle);
        force->addEnergyTerm("(1+a1+a2)*r", i%2 == 0 ? CustomGBForce::ParticlePair : CustomGBForce::ParticlePairNoExclusions);
        force->addParticle(vector<double>());
        force->addParticle(vector<double>());
        force->addExclusion(0, 1);
        system.addForce(force);
        Context context(system, integrator, platform);
        vector<Vec3> positions(2);
        positions[0] = Vec3(0, 0, 0);
        positions[1] = Vec3(1, 0, 0);
        context.setPositions(positions);
        State state = context.getState(State::Forces | State::Energy);
        const vector<Vec3>& forces = state.getForces();
        double f, energy;
        switch (i)
        {
            case 0: // e = 0
                f = 0;
                energy = 0;
                break;
            case 1: // e = r
                f = 1;
                energy = 1;
                break;
            case 2: // e = 2r
                f = 2;
                energy = 2;
                break;
            case 3: // e = 3r + 2r^2
                f = 7;
                energy = 5;
                break;
            default:
                ASSERT(false);
        }
        ASSERT_EQUAL_VEC(Vec3(f, 0, 0), forces[0], 1e-4);
        ASSERT_EQUAL_VEC(Vec3(-f, 0, 0), forces[1], 1e-4);
        ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), 1e-4);

        // Take a small step in the direction of the energy gradient and see whether the potential energy changes by the expected amount.

        double norm = 0.0;
        for (int i = 0; i < (int) forces.size(); ++i)
            norm += forces[i].dot(forces[i]);
        norm = std::sqrt(norm);
        const double stepSize = 1e-3;
        double step = stepSize/norm;
        for (int i = 0; i < (int) positions.size(); ++i) {
            Vec3 p = positions[i];
            Vec3 f = forces[i];
            positions[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step);
        }
        context.setPositions(positions);
        State state2 = context.getState(State::Energy);
        ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state.getPotentialEnergy())/stepSize, 1e-3*abs(state.getPotentialEnergy()));
    }
}
Example #15
0
void HeadingModel::getExpectedValue(MeasurementVector& y_pred, const State& state)
{
  y_pred(0) = state.getYaw();
}
Example #16
0
double ReducedModel::evaluateMarkovChain(ReducedModel* reducedModel)
{
    ReducedModel* markovChain =
        new ReducedModel(reducedModel->originalProblem_,
                         reducedModel->reducedTransition_,
                         reducedModel->k_);

    // First we generate all states that are reachable in the full model.
    markovChain->useFullTransition(true);
    markovChain->generateAll();

    // Then we create copies of all these states for j=1,...,k and add
    // them to the Markov Chain.
    std::list<State*> statesFullModel(markovChain->states().begin(),
                                              markovChain->states().end());
    for (int j = 0; j <= reducedModel->k_; j++) {
        for (State* s : statesFullModel) {
            ReducedState* rs = static_cast<ReducedState*>(s);
            if (j > 0) {
                markovChain->addState(
                    new ReducedState(rs->originalState(), j, markovChain));
            }
            // We need to add a copy also in the reduced model, because some
            // of these states might be unreachable from its initial state.
            State* aux = reducedModel->addState(
                new ReducedState(rs->originalState(), j, reducedModel));
        }
    }

    // Computing an universal plan for all of these states in the reduced model.
    mlsolvers::VISolver solver(reducedModel, 1000000, 1.0e-3);
    solver.solve();

    // Finally, we make sure the MC uses the continual planning
    // transition function.
    markovChain->useContPlanEvaluationTransition(true);

    // Now we compute the expected cost of traversing this Markov Chain.
    double maxResidual = mdplib::dead_end_cost;
    while (maxResidual > 1.0e-3) {
        maxResidual = 0.0;
        for (State* s : markovChain->states()) {
            if (markovChain->goal(s))
                continue;
            ReducedState* markovChainState = static_cast<ReducedState*>(s);
            // currentState is the state that markovChainState represents in
            // the reduced model.
            State* currentState =
                reducedModel->addState(
                    new ReducedState(markovChainState->originalState(),
                                     markovChainState->exceptionCount(),
                                     reducedModel));

            if (currentState->deadEnd()) {
                // state->deadEnd is set by the solver when there is no
                // applicable action in state.
                s->setCost(mdplib::dead_end_cost);
                continue;
            }

            assert(currentState->bestAction() != nullptr);
            Action* a = currentState->bestAction();
            double previousCost = s->cost();
            double currentCost = 0.0;
            for (Successor successor : markovChain->transition(s, a)) {
                currentCost += successor.su_prob * successor.su_state->cost();
            }
            currentCost *= markovChain->gamma();
            currentCost += markovChain->cost(s, a);
            currentCost = std::min(currentCost, mdplib::dead_end_cost);
            double currentResidual = fabs(currentCost - previousCost);
            if (currentResidual > maxResidual) {
                maxResidual = currentResidual;
            }
            s->setCost(currentCost);
        }
    }
    return markovChain->initialState()->cost();
}
Example #17
0
void HeadingModel::getStateJacobian(MeasurementMatrix& C, const State& state, bool)
{
  if (state.orientation()) {
    state.orientation()->cols(C)(0,Z) = 1.0;
  }
}
Example #18
0
 Real getValue(const State& state) const {
     return state.getQ(pendulum.getGuts().getSubsysIndex())[0];
 }
Example #19
0
void generateStencil(GLBackend::GLState::Commands& commands, const State& state) {
    commands.push_back(CommandPointer(new CommandStencil(&GLBackend::do_setStateStencil, state.getStencilActivation(), state.getStencilTestFront(), state.getStencilTestBack())));
}
LfcCommand * ReplicaCpDelRepStateSess2::NextState(
        std::vector<Item *>::const_iterator & iterator,
        vector<Item*> items,
        Item* item) {

    vector<Item *> itemsToAssigne;
    bool sess = false;
    bool endsess = false;
    bool statg = false;
    int numberOfFailsFileComparation = 0;
    bool startTrans = false;
    int backUpTid = item->GetTid();
    int itemsSize = items.size();

    for (int i = 0; i < itemsSize; i++, iterator++) {
        Item * item2 = *iterator;

        if (!item2->IsAssigned()) {
            FunctionType command = item2->GetCommand()->getName();

            if (item->compareUserSite(item2) && !sess && !endsess) {
                if (command == STARTTRANS) {
                    PrintMessage("CP2 START TRANS", item2);
                    itemsToAssigne.push_back(item2);
                    item->SetTid(item2->GetTid());
                    startTrans = true;
                } else if (command == STARTSESS && !sess && !startTrans) {
                    PrintMessage("CP2 START SESS", item2);
                    itemsToAssigne.push_back(item2);
                    item->SetTid(item2->GetTid());
                    sess = true;
                }
            }

            if (item->compareUserSiteTid(item2) && sess && !endsess && !startTrans) {
                if (command == GETREPLICA && statg) {
                    PrintMessage("CP2 GETREPLICA", item2);
                    itemsToAssigne.push_back(item2);
                    item->SetFilePath(item2->GetFilePath());
                } else if (command == ENDSESS && statg) {
                    PrintMessage("CP2 ENDSESS", item2);
                    itemsToAssigne.push_back(item2);
                    endsess = true;
                } else if (command == STATG && !statg) {
                    PrintMessage("CP2 STATG", item2);
                    itemsToAssigne.push_back(item2);
                    statg = true;
                    if (!item->compareUserSiteFirstPartOfFile(item2)) {
                        PrintMessage("CP2 FAIL", item2);
                        itemsToAssigne.clear();
                        item->SetTid(backUpTid); 
                       sess = false;
                        statg = false;
                        if (numberOfFailsFileComparation > 4) {
                            break;
                        }
                        numberOfFailsFileComparation++;
                    }
                }
            }


            if (command == ACCESS && !startTrans) {
                if (item->compareUserSiteFirstPartOfFile(item2) && sess && endsess) {
                    PrintMessage("CP2 ACCESS", item2);
                    itemsToAssigne.push_back(item2);
                    this->AssignAllItems(itemsToAssigne);
                    State * state = new DellAll();
                    return state->NextState(iterator, items, item);
                }
            }

            if (command == STATG and !statg) {
                PrintMessage("CP2 STATG STR", item2);
                if (!item->compareUserSiteFile(item2)) {
                    PrintMessage("CP2 STATG FAIL STR", item2);
                    itemsToAssigne.clear();
                    item->SetTid(backUpTid);
                    startTrans = false;
                    if (numberOfFailsFileComparation > 4) {
                        break;
                    }
                    numberOfFailsFileComparation++;
                } else {
                    itemsToAssigne.push_back(item2);
                    this->AssignAllItems(itemsToAssigne);
                    State * state = new ReplicateStateTransaction();
                    return state->NextState(iterator, items, item);
                }
            }
           
        }

        if (*iterator == items.back()) {
            break;
        }
    }

    PrintMessage("LCG CP", item);
    return new LfcCpCommand(
            item->GetStartTime(),
            item->GetEndTime(),
            item->GetFilePath(),
            item->GetUser(),
            item->GetSite(),
            false);
}
void player_decode(void *data)
{
	State *state = (State *) data;
	
	int ret;
	int eof = 0;

	for (;;) {

		if (state->abort_request) {
			break;
		}

        if (state->paused != state->last_paused) {
        	state->last_paused = state->paused;
            if (state->paused) {
            	state->read_pause_return = av_read_pause(state->pFormatCtx);
            } else {
                av_read_play(state->pFormatCtx);
            }
        }

        if (state->seek_req) {
            int64_t seek_target = state->seek_pos;
            int64_t seek_min = state->seek_rel > 0 ? seek_target - state->seek_rel + 2: INT64_MIN;
            int64_t seek_max = state->seek_rel < 0 ? seek_target - state->seek_rel - 2: INT64_MAX;

            ret = avformat_seek_file(state->pFormatCtx, -1, seek_min, seek_target, seek_max, state->seek_flags);
            if (ret < 0) {
                fprintf(stderr, "%s: error while seeking\n", state->pFormatCtx->filename);
            } else {
                if (state->audio_stream >= 0) {
                	avcodec_flush_buffers(state->audio_st->codec);
                }
                state->notify_callback(state->clazz, MEDIA_SEEK_COMPLETE, 0, 0, FROM_THREAD);
            }
            state->seek_req = 0;
            eof = 0;
        }

        if (state->paused) {
        	goto sleep;
        }

		AVPacket packet;
		memset(&packet, 0, sizeof(packet)); //make sure we can safely free it

		int i;
			
		for (i = 0; i < state->pFormatCtx->nb_streams; ++i) {
			//av_init_packet(&packet);
			ret = av_read_frame(state->pFormatCtx, &packet);

	        if (ret < 0) {
	            if (ret == AVERROR_EOF || url_feof(state->pFormatCtx->pb)) {
	                eof = 1;
	                break;
	            }
	        }

	        int frame_size_ptr;
			ret = decode_frame_from_packet(state, &packet, &frame_size_ptr, FROM_THREAD);
			av_free_packet(&packet);

			if (ret != 0) { //an error or a frame decoded
				// TODO add this bacl=k
			}
		}

		if (eof) {
			break;
		}

		sleep:
		    usleep(100);
	}

	if (eof) {
		state->notify_callback(state->clazz, MEDIA_PLAYBACK_COMPLETE, 0, 0, FROM_THREAD);
	}
}
Example #22
0
	void SplitPanel::_receive(Msg * pMsg)
	{
		//TODO: Implement!!!

		State handleState = m_handleState;

		switch (pMsg->type())
		{
			case MsgType::MouseEnter:
			case MsgType::MouseMove:
			{
				if (m_handleState.isPressed())
					return;

				Coord pos = InputMsg::cast(pMsg)->pointerPos() - globalPos();

				bool bHovered = m_handleGeo.contains(pos);
				handleState.setHovered(bHovered);
				break;
			}

			case MsgType::MouseLeave:
			{
				// Unhover handle unless it is pressed

				if (!handleState.isPressed())
					handleState.setHovered(false);
				break;
			}
			case MsgType::MousePress:
			{
				auto p = MouseButtonMsg::cast(pMsg);

				if (p->button() != MouseButton::Left)
					return;

				Coord pos = p->pointerPos() - globalPos();
				if (m_handleGeo.contains(pos))
				{
					m_handlePressOfs = m_bHorizontal ? pos.x - m_handleGeo.x : pos.y - m_handleGeo.y;
					handleState.setPressed(true);
					pMsg->swallow();
				}
				break;
			}

			case MsgType::MouseRelease:
			{
				auto p = MouseButtonMsg::cast(pMsg);

				if (p->button() != MouseButton::Left)
					return;

				if (handleState.isPressed() )
				{
					handleState.setPressed(false);
					pMsg->swallow();
				}
				break;
			}

			case MsgType::MouseDrag:
			{
				auto p = MouseButtonMsg::cast(pMsg);

				if (p->button() != MouseButton::Left)
					return;

				if (handleState.isPressed())
				{
					Coord pos = p->pointerPos() - globalPos();
					int diff = (m_bHorizontal ? pos.x - m_handleGeo.x : pos.y - m_handleGeo.y) - m_handlePressOfs;

					_updateGeo(diff);
					pMsg->swallow();
				}
				break;
			}

			default:
				break;
		}

		if (handleState != m_handleState && m_pHandleSkin)
		{
			if (!m_pHandleSkin->isStateIdentical(handleState, m_handleState))
				_requestRender(m_handleGeo);

			m_handleState = handleState;
		}
	}
Example #23
0
int main(int argc, char** argv) {
  cout << endl << "Hello World: begin main" << endl;

  std::time_t default_seed = 0;
  string default_data_filename = "SynData2.csv";
  string default_samples_filename = "samples.out";
  int default_nChains = 1;
  int default_nSamples = 4;
  int default_burnIn = 5;
  int default_lag = 2;
  int default_nGrid = 31;
  //
  std::time_t seed;
  string data_filename;
  string samples_filename;
  int nChains;
  int nSamples;
  int burnIn;
  int lag;
  int nGrid;

  //parse some arguments
  namespace po = boost::program_options;
  po::options_description desc("Options");
  desc.add_options()
    ("help,h", "produce help message")
    ("seed", po::value<std::time_t>(&seed)->default_value(default_seed), "set inference seed")
    ("data_filename", po::value<string>(&data_filename)->default_value(default_data_filename), "data to run inference on")
    ("samples_filename", po::value<string>(&samples_filename)->default_value(default_samples_filename), "filename to save samples in")
    ("nChains", po::value<int>(&nChains)->default_value(default_nChains), "set number of inference chains to run")
    ("nSamples", po::value<int>(&nSamples)->default_value(default_nSamples), "set number of samples to draw (@lag)")
    ("burnIn", po::value<int>(&burnIn)->default_value(default_burnIn), "set number of burn in iterations")
    ("lag", po::value<int>(&lag)->default_value(default_lag), "set number of iterations per sample")
    ("nGrid", po::value<int>(&nGrid)->default_value(default_nGrid), "set number of bins in hyper inference")
    ;
  po::variables_map vm;
  try {
    po::store(po::parse_command_line( argc, argv, desc ), vm);
    po::notify( vm );
    if ( vm.count("help") ) {
      std::cout << desc << "\n";
      exit(0);
    }
  } catch ( const boost::program_options::error& e ) {
    std::cerr << e.what() << std::endl;
  }

  matrixD data;
  LoadData(data_filename, data);
  vector<int> global_row_indices = create_sequence(data.size1());
  vector<int> global_column_indices = create_sequence(data.size2());

  ofstream out(samples_filename.c_str(), ios_base::app);
  if(!out) { cout << "Cannot open file: " << samples_filename << endl; return -1; }
  out << "nChains = " << nChains << endl;
  out << "nSamples = " << nSamples << endl;
  out << "burnIn = " << burnIn << endl;
  out << "lag = " << lag << endl;
  out << endl;
  out.close();

  int raw_sample_idx = 0;
  for(int nc=0; nc<nChains; nc++) {
    cout << "nc = " << nc << endl;
    // need to randomize initialization of State
    State s = State(data, global_row_indices, global_column_indices, nGrid);
    Timer T(true);
    for(int nb=0; nb<burnIn; nb++) {
      s.transition(data);
      cout << "Done raw sample idx: " << raw_sample_idx++ << endl;
    }

    //s.SaveResult(samples_filename, 0);
    cout << " t1 = " << T.GetElapsed() << endl;
    //
    for(int ns=1; ns<nSamples; ns++) {
      cout << "ns = " << ns << endl;
      for(int nl=0; nl<lag; nl++) {
	s.transition(data);
	cout << "Done raw sample idx: " << raw_sample_idx++ << endl;
      }
      //s.SaveResult(samples_filename, ns);
      cout << "t2 = " <<  T.GetElapsed() << endl;
    }
  }
  cout << endl << "Goodbye World: end main" << endl;
}
Example #24
0
int ScriptInterpreter::Registry(State& S, const char* pszKey)
{
	return S.getFieldI(pszKey, LUA_REGISTRYINDEX);
}
 void operator()( const State &x , double t ) const
 {
     m_out << t;
     m_out << "\t" << x.real() << "\t" << x.imag() ;
     m_out << "\n";
 }
Example #26
0
void ScriptInterpreter::PushTraceback(State& S, IScript* pScript)
{
	S.push(Userdata<IScript>(pScript))
	 .push(m_bEditor ? Traceback : NoTraceback, 1);
}
Example #27
0
void EngineClient::setState(State& s) {
	if (&s == mState) return;
  
	s.begin(*this);
	mState = &s;
}
static void testObservedPointFitter(bool useConstraint) {
    int failures = 0;
    for (int iter = 0; iter < ITERATIONS; ++iter) {
        
        // Build a system consisting of a chain of bodies with occasional side chains, and
        // a variety of mobilizers.

        MultibodySystem mbs;
        SimbodyMatterSubsystem matter(mbs);
        Body::Rigid body = Body::Rigid(MassProperties(1, Vec3(0), Inertia(1)));
        body.addDecoration(Transform(), DecorativeSphere(.1));
        MobilizedBody* lastBody = &matter.Ground();
        MobilizedBody* lastMainChainBody = &matter.Ground();
        vector<MobilizedBody*> bodies;
        Random::Uniform random(0.0, 1.0);
        random.setSeed(iter);

        for (int i = 0; i < NUM_BODIES; ++i) {
            bool mainChain = random.getValue() < 0.5;
            MobilizedBody* parent = (mainChain ? lastMainChainBody : lastBody);
            int type = (int) (random.getValue()*4);
            MobilizedBody* nextBody;
            if (type == 0) {
                MobilizedBody::Cylinder cylinder(*parent, Transform(Vec3(0, 0, 0)), body, Transform(Vec3(0, BOND_LENGTH, 0)));
                nextBody = &matter.updMobilizedBody(cylinder.getMobilizedBodyIndex());
            }
            else if (type == 1) {
                MobilizedBody::Slider slider(*parent, Transform(Vec3(0, 0, 0)), body, Transform(Vec3(0, BOND_LENGTH, 0)));
                nextBody = &matter.updMobilizedBody(slider.getMobilizedBodyIndex());
            }
            else if (type == 2) {
                MobilizedBody::Ball ball(*parent, Transform(Vec3(0, 0, 0)), body, Transform(Vec3(0, BOND_LENGTH, 0)));
                nextBody = &matter.updMobilizedBody(ball.getMobilizedBodyIndex());
            }
            else {
                MobilizedBody::Pin pin(*parent, Transform(Vec3(0, 0, 0)), body, Transform(Vec3(0, BOND_LENGTH, 0)));
                nextBody = &matter.updMobilizedBody(pin.getMobilizedBodyIndex());
            }
            bodies.push_back(nextBody);
            if (mainChain)
                lastMainChainBody = nextBody;
            lastBody = nextBody;
        }
        mbs.realizeTopology();
        State s = mbs.getDefaultState();
        matter.setUseEulerAngles(s, true);
        mbs.realizeModel(s);

        // Choose a random initial conformation.

        vector<Real> targetQ(s.getNQ(), Real(0));
        for (MobilizedBodyIndex mbx(1); mbx < matter.getNumBodies(); ++mbx) {
            const MobilizedBody& mobod = matter.getMobilizedBody(mbx);
            for (int i = 0; i < mobod.getNumQ(s); ++i) {
                const QIndex qx0 = mobod.getFirstQIndex(s);
                s.updQ()[qx0+i] = targetQ[qx0+i] = 2.0*random.getValue();
            }
        }
        //cout << "q0=" << s.getQ() << endl;
        mbs.realize(s, Stage::Position);

        // Select some random stations on each body.

        vector<vector<Vec3> > stations(NUM_BODIES);
        vector<vector<Vec3> > targetLocations(NUM_BODIES);
        vector<MobilizedBodyIndex> bodyIxs;
        for (int i = 0; i < NUM_BODIES; ++i) {
            MobilizedBodyIndex id = bodies[i]->getMobilizedBodyIndex();
            bodyIxs.push_back(id);
            int numStations = 1 + (int) (random.getValue()*4);
            for (int j = 0; j < numStations; ++j) {
                Vec3 pos(2.0*random.getValue()-1.0, 2.0*random.getValue()-1.0, 2.0*random.getValue()-1.0);
                stations[i].push_back(pos);
                targetLocations[i].push_back(bodies[i]->getBodyTransform(s)*pos);
            }
        }

        Real distance = -1;
        if (useConstraint) {
            // Add a constraint fixing the distance between the first and last bodies.
            Real distance = (bodies[0]->getBodyOriginLocation(s)-bodies[NUM_BODIES-1]->getBodyOriginLocation(s)).norm();
            // (sherm 140506) Without this 1.001 this failed on clang.
            Constraint::Rod(*bodies[0], Vec3(0), *bodies[NUM_BODIES-1], Vec3(0), 1.001*distance);
        }
        s = mbs.realizeTopology();
        matter.setUseEulerAngles(s, true);
        mbs.realizeModel(s);

        // Try fitting it.
        State initState = s;
        // (sherm 140506) I raised this from .02 to .03 to make this more robust.
        if (!testFitting(mbs, s, bodyIxs, stations, targetLocations, 0.0, 0.03, distance))
            failures++;

        //cout << "q1=" << s.getQ() << endl;

        // Now add random noise to the target locations, and see if it can still fit decently.

        Random::Gaussian gaussian(0.0, 0.15);
        for (int i = 0; i < (int) targetLocations.size(); ++i) {
            for (int j = 0; j < (int) targetLocations[i].size(); ++j) {
                targetLocations[i][j] += Vec3(gaussian.getValue(), gaussian.getValue(), gaussian.getValue());
            }
        }

        s = initState; // start from same config as before
        if (!testFitting(mbs, s, bodyIxs, stations, targetLocations, 0.1, 0.5, distance))
            failures++;

        //cout << "q2=" << s.getQ() << endl;

    }

    ASSERT(failures == 0); // It found a reasonable fit every time.
    std::cout << "Done" << std::endl;
}
Example #29
0
void RWGame::tick(float dt)
{
	// Process the Engine's background work.
	world->_work->update();
	
	State* currState = StateManager::get().states.back();

	world->chase.update(dt);
	
	static float clockAccumulator = 0.f;
	if ( currState->shouldWorldUpdate() ) {
		// Clear out any per-tick state.
		world->clearTickData();

		state->gameTime += dt;

		clockAccumulator += dt;
		while( clockAccumulator >= 1.f ) {
			world->state->basic.gameMinute ++;
			while( state->basic.gameMinute >= 60 ) {
				state->basic.gameMinute = 0;
				state->basic.gameHour ++;
				while( state->basic.gameHour >= 24 ) {
					state->basic.gameHour = 0;
				}
			}
			clockAccumulator -= 1.f;
		}
		
		// Clean up old VisualFX
		for( int i = 0; i < world->effects.size(); ++i )
		{
			VisualFX* effect = world->effects[i];
			if( effect->getType() == VisualFX::Particle )
			{
				auto& part = effect->particle;
				if( part.lifetime < 0.f ) continue;
				if( world->getGameTime() >= part.starttime + part.lifetime )
				{
					world->destroyEffect( effect );
					--i;
				}
			}
		}

		for( auto& object : world->allObjects ) {
			object->_updateLastTransform();
			object->tick(dt);
		}
		
		world->destroyQueuedObjects();

		state->text.tick(dt);

		world->dynamicsWorld->stepSimulation(dt, 2, dt);
		
		if( script ) {
			try {
				script->execute(dt);
			}
			catch( SCMException& ex ) {
				std::cerr << ex.what() << std::endl;
				log.error( "Script", ex.what() );
				throw;
			}
		}
		
		if ( state->playerObject )
		{
			// Use the current camera position to spawn pedestrians.
			auto p = nextCam.position;
			world->cleanupTraffic(p);
			world->createTraffic(p);
		}
	}
	
	// render() needs two cameras to smoothly interpolate between ticks.
	lastCam = nextCam;
	nextCam = currState->getCamera();
}
void testMembrane() {
    const int numMolecules = 70;
    const int numParticles = numMolecules*2;
    const double boxSize = 10.0;
    ReferencePlatform platform;

    // Create a system with an implicit membrane.

    System system;
    for (int i = 0; i < numParticles; i++) {
        system.addParticle(1.0);
    }
    system.setDefaultPeriodicBoxVectors(Vec3(boxSize, 0.0, 0.0), Vec3(0.0, boxSize, 0.0), Vec3(0.0, 0.0, boxSize));
    CustomGBForce* custom = new CustomGBForce();
    custom->setCutoffDistance(2.0);
    custom->addPerParticleParameter("q");
    custom->addPerParticleParameter("radius");
    custom->addPerParticleParameter("scale");
    custom->addGlobalParameter("thickness", 3);
    custom->addGlobalParameter("solventDielectric", 78.3);
    custom->addGlobalParameter("soluteDielectric", 1);
    custom->addComputedValue("Imol", "step(r+sr2-or1)*0.5*(1/L-1/U+0.25*(1/U^2-1/L^2)*(r-sr2*sr2/r)+0.5*log(L/U)/r+C);"
                             "U=r+sr2;"
                             "C=2*(1/or1-1/L)*step(sr2-r-or1);"
                             "L=max(or1, D);"
                             "D=abs(r-sr2);"
                             "sr2 = scale2*or2;"
                             "or1 = radius1-0.009; or2 = radius2-0.009", CustomGBForce::ParticlePairNoExclusions);
    custom->addComputedValue("Imem", "(1/radius+2*log(2)/thickness)/(1+exp(7.2*(abs(z)+radius-0.5*thickness)))", CustomGBForce::SingleParticle);
    custom->addComputedValue("B", "1/(1/or-tanh(1*psi-0.8*psi^2+4.85*psi^3)/radius);"
                             "psi=max(Imol,Imem)*or; or=radius-0.009", CustomGBForce::SingleParticle);
    custom->addEnergyTerm("28.3919551*(radius+0.14)^2*(radius/B)^6-0.5*138.935456*(1/soluteDielectric-1/solventDielectric)*q^2/B", CustomGBForce::SingleParticle);
    custom->addEnergyTerm("-138.935456*(1/soluteDielectric-1/solventDielectric)*q1*q2/f;"
                          "f=sqrt(r^2+B1*B2*exp(-r^2/(4*B1*B2)))", CustomGBForce::ParticlePairNoExclusions);
    vector<Vec3> positions(numParticles);
    vector<Vec3> velocities(numParticles);
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(0, sfmt);
    vector<double> params(3);
    for (int i = 0; i < numMolecules; i++) {
        if (i < numMolecules/2) {
            params[0] = 1.0;
            params[1] = 0.2;
            params[2] = 0.5;
            custom->addParticle(params);
            params[0] = -1.0;
            params[1] = 0.1;
            custom->addParticle(params);
        }
        else {
            params[0] = 1.0;
            params[1] = 0.2;
            params[2] = 0.8;
            custom->addParticle(params);
            params[0] = -1.0;
            params[1] = 0.1;
            custom->addParticle(params);
        }
        positions[2*i] = Vec3(boxSize*genrand_real2(sfmt), boxSize*genrand_real2(sfmt), boxSize*genrand_real2(sfmt));
        positions[2*i+1] = Vec3(positions[2*i][0]+1.0, positions[2*i][1], positions[2*i][2]);
        velocities[2*i] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt));
        velocities[2*i+1] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt));
    }
    system.addForce(custom);
    VerletIntegrator integrator(0.01);
    Context context(system, integrator, platform);
    context.setPositions(positions);
    context.setVelocities(velocities);
    State state = context.getState(State::Forces | State::Energy);
    const vector<Vec3>& forces = state.getForces();

    // Take a small step in the direction of the energy gradient and see whether the potential energy changes by the expected amount.

    double norm = 0.0;
    for (int i = 0; i < (int) forces.size(); ++i)
        norm += forces[i].dot(forces[i]);
    norm = std::sqrt(norm);
    const double stepSize = 1e-3;
    double step = 0.5*stepSize/norm;
    vector<Vec3> positions2(numParticles), positions3(numParticles);
    for (int i = 0; i < (int) positions.size(); ++i) {
        Vec3 p = positions[i];
        Vec3 f = forces[i];
        positions2[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step);
        positions3[i] = Vec3(p[0]+f[0]*step, p[1]+f[1]*step, p[2]+f[2]*step);
    }
    context.setPositions(positions2);
    State state2 = context.getState(State::Energy);
    context.setPositions(positions3);
    State state3 = context.getState(State::Energy);
    ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state3.getPotentialEnergy())/stepSize, 1e-3);
}