Exemple #1
0
void SeedFinder::getSeeds(std::string const &read,
        std::map<int, std::vector<Seed>> &seed_map,
        std::vector<int> &seeds_of_size, std::vector<int> &map_keys,
        int &seed_count, int const &seed_min_length) const
{
        //mem finding
        vector<match_t> matches;        //will contain the matches
        bool print = 0;        //not sure what it prints if set to 1
        sa_->findMEM(0, read, matches, seed_min_length, print);
                
        //parse the results
        for (int i = 0; i < matches.size(); ++i) {
                match_t m = matches[i];
                int node_nr = binary_node_search(m.ref);
                int node_start = startOfHit(node_nr, m.ref);
                seed_map[node_nr].push_back(Seed(node_nr, node_start, m.query, m.len));
                while (seeds_of_size.size() <= m.len) {
                        seeds_of_size.push_back(0);
                }
                ++seeds_of_size[m.len];
                ++seed_count;
                if (std::find(map_keys.begin(), map_keys.end(), node_nr) == map_keys.end()) {
                        map_keys.push_back(node_nr);
                }
        }
}
Exemple #2
0
Seed
generateSeed (std::string const& passPhrase)
{
    sha512_half_hasher_s h;
    h(passPhrase.data(), passPhrase.size());
    auto const digest =
        sha512_half_hasher::result_type(h);
    return Seed({ digest.data(), 16 });
}
Exemple #3
0
boost::optional<Seed>
parseBase58 (std::string const& s)
{
    auto const result = decodeBase58Token(
         s, TokenType::TOKEN_FAMILY_SEED);
    if (result.empty())
        return boost::none;
    if (result.size() != 16)
        return boost::none;
    return Seed(makeSlice(result));
}
Exemple #4
0
void DepthFilter::initializeSeeds(FramePtr frame)
{
  Features new_features;
  feature_detector_->setExistingFeatures(frame->fts_);
  feature_detector_->detect(frame.get(), frame->img_pyr_,
                            Config::triangMinCornerScore(), new_features);

  // initialize a seed for every new feature
  seeds_updating_halt_ = true;
  lock_t lock(seeds_mut_); // by locking the updateSeeds function stops
  ++Seed::batch_counter;
  std::for_each(new_features.begin(), new_features.end(), [&](Feature* ftr){
    seeds_.push_back(Seed(ftr, new_keyframe_mean_depth_, new_keyframe_min_depth_));
  });

  if(options_.verbose)
    SVO_INFO_STREAM("DepthFilter: Initialized "<<new_features.size()<<" new seeds");
  seeds_updating_halt_ = false;
}
	void SpinMatrix::Init(const Options& options)
	{
		const unsigned int size = m_cols * m_rows;

		//Tc at 2.26918531421
		J = options.J;
		B = options.B;

		Seed();

		switch (options.startIsing)
		{
		case Options::IsingStart::InfiniteTemperature:
		{
			Temperature = 10;

			std::uniform_int_distribution<> d{ 0, 1 };

			for (unsigned int i = 0; i < size; ++i) m_spins[i] = (d(rndEngine) ? 1 : -1);

			Energy = 0;

			for (unsigned int row = 0; row < m_rows; ++row)
				for (unsigned int col = 0; col < m_cols; ++col)
				{
					Energy += PartSiteEnergy(row, col);
					Magnetization += GetSpin(row, col);
				}
		}
		break;
		case Options::IsingStart::ZeroTemperature:
			Temperature = 0.1;

			for (unsigned int i = 0; i < size; ++i) m_spins[i] = (options.B > 0 ? -1 : 1);

			Energy = (-2. - options.B) * size;
			Magnetization = size * (options.B > 0 ? -1 : 1);
			break;
		}

		setExpMap();
	}
Exemple #6
0
std::string HDSeed::Bip32Root(const std::string& fingerprint) const
{
    // TODO: make fingerprint non-const
    std::string input(fingerprint);
    std::uint32_t notUsed = 0;
    auto seed = Seed(input, notUsed);

    if (!seed) { return ""; }

    auto start = static_cast<const unsigned char*>(seed->getMemory());
    const auto end = start + seed->getMemorySize();

    std::vector<unsigned char> bytes(start, end);
    std::ostringstream stream;
    stream << std::hex << std::setfill('0');

    for (int byte : bytes) { stream << std::setw(2) << byte; }

    return stream.str();
}
Exemple #7
0
std::shared_ptr<proto::AsymmetricKey> HDSeed::GetStorageKey(
    std::string& fingerprint) const
{
    std::uint32_t notUsed = 0;
    auto seed = Seed(fingerprint, notUsed);

    if (false == bool(seed)) {
        otErr << OT_METHOD << __FUNCTION__ << ": Unable to load seed."
              << std::endl;

        return {};
    }

    proto::HDPath path;
    path.set_root(fingerprint);
    path.add_child(
        static_cast<std::uint32_t>(Bip43Purpose::FS) |
        static_cast<std::uint32_t>(Bip32Child::HARDENED));
    path.add_child(
        static_cast<std::uint32_t>(Bip32Child::ENCRYPT_KEY) |
        static_cast<std::uint32_t>(Bip32Child::HARDENED));

    return bip32_.GetHDKey(EcdsaCurve::SECP256K1, *seed, path);
}
Exemple #8
0
std::shared_ptr<proto::AsymmetricKey> HDSeed::GetPaymentCode(
    std::string& fingerprint,
    const std::uint32_t nym) const
{
    std::shared_ptr<proto::AsymmetricKey> output;
    std::uint32_t notUsed = 0;
    auto seed = Seed(fingerprint, notUsed);

    if (!seed) { return output; }

    proto::HDPath path;
    path.set_root(fingerprint);
    path.add_child(
        static_cast<std::uint32_t>(Bip43Purpose::PAYCODE) |
        static_cast<std::uint32_t>(Bip32Child::HARDENED));
    path.add_child(
        static_cast<std::uint32_t>(Bip44Type::BITCOIN) |
        static_cast<std::uint32_t>(Bip32Child::HARDENED));
    path.add_child(nym | static_cast<std::uint32_t>(Bip32Child::HARDENED));

    output = bip32_.GetHDKey(EcdsaCurve::SECP256K1, *seed, path);

    return output;
}
Exemple #9
0
MATH_BEGIN_NAMESPACE

LCG::LCG()
{
	Seed(Clock::TickU32());
}
Exemple #10
0
bool RandomNumberGenerator::Init()
{
	Seed((int32_t)time(0));
	return true;
}
std::pair <std::vector<StateOfCar>, Seed> AStarSeed::findPathToTarget(const cv::Mat& map, const State& start, const State& goal, const int distance_transform, const int debug_current_state, int& status) {
    // USE : for guaranteed termination of planner
    int no_of_iterations = 0;
    int max_iterations = 10000;

    node_handle.getParam("local_planner/max_iterations", max_iterations);

    fusion_map = map;
    map_max_rows = map.rows;
    map_max_cols = map.cols;

    if (distance_transform == 1) {
        distanceTransform();
    }

    if (debug_current_state) {
        image = fusion_map.clone();
    }

    StateOfCar start_state(start), target_state(goal);
    std::map<StateOfCar, open_map_element> open_map;
    std::map<StateOfCar, StateOfCar, comparatorMapState> came_from;
    SS::PriorityQueue<StateOfCar> open_set;

    open_set.push(start_state);

    if (start_state.isCloseTo(target_state)) {
        status = 1;
        return std::make_pair(std::vector<StateOfCar>(), Seed());
    } else if (isOnTheObstacle(start_state)) {
        std::cout << "Bot is on the Obstacle Map \n";
        return std::make_pair(std::vector<StateOfCar>(), Seed());
    } else if (isOnTheObstacle(target_state)) {
        std::cout << "Target is on the Obstacle Map \n";
        return std::make_pair(std::vector<StateOfCar>(), Seed());
    }

    while (!open_set.empty() && ros::ok()) {
        if (no_of_iterations > max_iterations) {
            status = open_set.size();
            return std::make_pair(std::vector<StateOfCar>(), Seed());
        }

        StateOfCar current_state = open_set.top();

        if (open_map.find(current_state) != open_map.end() && open_map[current_state].membership == CLOSED) {
            open_set.pop();
        }

        current_state = open_set.top();
        if (debug_current_state) {
            std::cout << "current x : " << current_state.x() << " current y : " << current_state.y() << std::endl;

            plotPointInMap(current_state);
            cv::imshow("[PLANNER] Map", image);
            cvWaitKey(0);
        }
        // TODO : use closeTo instead of onTarget
        if (current_state.isCloseTo(target_state)) {
            status = 2;
            return reconstructPath(current_state, came_from);
        }

        open_set.pop();
        open_map[current_state].membership = UNASSIGNED;
        open_map[current_state].cost = -current_state.gCost();
        open_map[current_state].membership = CLOSED;

        std::vector<StateOfCar> neighbors_of_current_state = neighborNodesWithSeeds(current_state);

        for (unsigned int iterator = 0; iterator < neighbors_of_current_state.size(); iterator++) {
            StateOfCar neighbor = neighbors_of_current_state[iterator];

            double tentative_gcost_along_followed_path = neighbor.gCost() + current_state.gCost();
            double admissible = neighbor.distanceTo(target_state);
            double consistent = admissible;

            if (!((open_map.find(neighbor) != open_map.end()) &&
                    (open_map[neighbor].membership == OPEN))) {
                came_from[neighbor] = current_state;
                neighbor.hCost(consistent);
                neighbor.gCost(tentative_gcost_along_followed_path);
                neighbor.updateTotalCost();
                open_set.push(neighbor);
                open_map[neighbor].membership = OPEN;
                open_map[neighbor].cost = neighbor.gCost();
            }
        }
        no_of_iterations++;
    }
    status = 0;
    return std::make_pair(std::vector<StateOfCar>(), Seed());
}
Exemple #12
0
 Random()
   : gen_(Seed())
   , dst_(std::numeric_limits<T>::min(), std::numeric_limits<T>::max())
   , rand_(gen_, dst_)
 {}
Exemple #13
0
void 
ASCRandNumGen::Seed()
{
	Seed(SC_UINT(time(0)));
}
Exemple #14
0
void RNG::SeedTime() {
	Kernal::uint32 t = Watch::GetTime();
	Seed(t);
}
Exemple #15
0
void sar(char *argv[], unsigned int seed)
{
    RandomLib::Random rng;
    rng.Reseed();

    // List of variables for run conditions:
    const int num_species = 50;
    const int num_patches = 300;
    const int num_step = 5000;
    const int search_radius = 5;

    // Species characteristics:
    const double d = 0.5; // Species mean dispersal distance (shapes dispersal kernel): 1/d
    const double m = 0.1; // Disturbance probability (disturbance kills individual)
    const double niche_min = 0.1; // Competitive strength of empty cells
    const double emi_from_out = 0.001; // Seed bank

    array2Ddouble E;
    array2Dint occupied;
    array2Dint disturbance_counter;

    SetArraySize2d(E, num_patches, num_patches);
    SetArraySize2d(occupied, num_patches, num_patches);
    SetArraySize2d(disturbance_counter, num_patches, num_patches);

    // List of global species characteristic parameters (read in from file or defined in main function):
    double *h = new double[num_species];
    double *u = new double[num_species];
    double *c = new double[num_species];
    double *sigma = new double[num_species];

    // read in species characteristics from file
    char buffer[100];
    sprintf(buffer, "%s_st.txt", argv[1]);
    std::ifstream input_traits(buffer);
    for (int i = 0; i < num_species; ++i)
    {
        input_traits >> sigma[i]; // Niche width
        input_traits >> h[i]; // Performance at niche optimum (height, y at maximum)
        input_traits >> c[i]; // Seed production
        input_traits >> u[i]; // Resource at niche optimum (location, x at maximum)
    }
    input_traits.close();
  
    sprintf(buffer, "%s_species.txt", argv[1]);
    std::ifstream input_species(buffer);
    {
        int i = 0, j = 0;
        while (!input_species.eof())
        {
            input_species >> i;
            input_species >> j;
            input_species >> E[i][j];
            input_species >> occupied[i][j];
            input_species >> disturbance_counter[i][j];
        }
    }
    input_species.close();

    for (int block = 0; block < 1; ++block)
    {
        sprintf(buffer, "%s_dest%d.txt", argv[1], block);
        std::ifstream input_dest(buffer);
		
        for (int i = 0; i < num_patches; ++i)
        {
            for (int j = 0; j < num_patches; ++j)
            {
                disturbance_counter[i][j] = 0;
				//                occupied[i][j] = 0;
            }
        }
		
		// Removed the input_dest as a matrix and replaced by a list (see next loop).
		
		//		for (int i = 0; i < num_patches; ++i)
		//        {
		//            for (int j = 0; j < num_patches; ++j)
		//            {
		//                input_dest >> E[i][j];
		//            }
		//        }
		
		// The input file is now x,y,E with 90000 lines
		
		{										
			int i = 0, j = 0;			
			while (!input_dest.eof())
			{
				input_dest >> i;
				input_dest >> j;
				input_dest >> E[i][j];
			}
		}										
		
        input_dest.close();
		
		//        for (int x = 0; x < num_patches; x++)
		//        {
		//            for (int y = 0; y < num_patches; y++)
		//            {
		//                const int s = (int)(rng.Fixed() * num_species); // Select a species at random
		//                occupied[x][y] = NICHE_F(h[s], u[s], E[x][y], sigma[s]) < niche_min ? EMPTY : s;
		//            }
		//       }
        double all_possible_seeds = 0;

        for (int dx = -search_radius; dx <= search_radius; dx++)
        {
            for (int dy = -search_radius; dy <= search_radius; dy++)
            {
                if ((dx != 0) || (dy != 0))
                {
                    all_possible_seeds += exp(-d * sqrt(dx * dx + dy * dy));
                }
            }
        }
        all_possible_seeds += emi_from_out * num_species;

        for (int t = 0; t < num_step; ++t)
        {
            for (int cell = 0; cell < num_patches * num_patches; cell++)
            {
                const int x = (int)(rng.Fixed() * num_patches);
                const int y = (int)(rng.Fixed() * num_patches);

                if(rng.Fixed() < m)
                {
                    occupied[x][y] = EMPTY;
                    ++disturbance_counter[x][y]; // BR
                }

                double Niche_res = niche_min;
                if (occupied[x][y] != EMPTY)
                {
                    int i = occupied[x][y];
                    Niche_res = NICHE_F(h[i], u[i], E[x][y], sigma[i]);
                }

                std::vector<double> Seed(num_species, 0.0);

                const int dx_min = (x - search_radius < 0) ? -x : -search_radius; 
                const int dx_max = (x + search_radius >= num_patches) ? num_patches - 1 - x : search_radius;
                const int dy_min = (y - search_radius < 0) ? -y : -search_radius;
                const int dy_max = (y + search_radius >= num_patches) ? num_patches - 1 - y : search_radius; 

                assert(x + dx_min >= 0 && x + dx_max < num_patches);
                assert(y + dy_min >= 0 && y + dy_max < num_patches);

                for (int dx = dx_min; dx <= dx_max; ++dx)
                {
                    for (int dy = dy_min; dy <= dy_max; ++dy)
                    {
                        if (((dx != 0) || (dy != 0)) && (occupied[x + dx][y + dy] != EMPTY))
                        {
                            int i = occupied[x + dx][y + dy];
                            if (NICHE_F(h[i], u[i], E[x][y], sigma[i]) > Niche_res)
                            {
                                Seed[i] += c[i] * (exp(-d * sqrt(dx * dx + dy * dy)));
                            }
                        }
                    }
                }
                double all_seeds = 0.0;
                for (int i = 0; i < num_species; ++i)
                {
                    if (NICHE_F(h[i], u[i], E[x][y], sigma[i]) > Niche_res)
                    {
                        Seed[i] += emi_from_out;
                    }
                    all_seeds += Seed[i];
                }

                bool total_colon = false;
                if (all_seeds / all_possible_seeds > rng.Fixed())
                {
                    total_colon = true;
                }

                std::vector<double> Prob_recruit(num_species, 0.0);
                if (total_colon == true)
                {
                    //Prob_recruit[0] = Colon[0]/double(total_colon);
                    Prob_recruit[0] = Seed[0] / all_seeds;
                    for (int i = 1; i < num_species; ++i)
                    {
                        Prob_recruit[i] = Seed[i] / all_seeds + Prob_recruit[i-1];
                    }

                    occupied[x][y] = EMPTY;

                    double randnumb = rng.Fixed();
                    for (int i = 0; i < num_species; i++)
                    {
                        if (randnumb < Prob_recruit[i])
                        {
                            assert(NICHE_F(h[i], u[i], E[x][y], sigma[i]) > niche_min);
                            occupied[x][y] = i;
                            break;
                        }
                    }
                }
            } // ends loop over cells
        } // ends loop t

        sprintf(buffer, "%s_out200_%d.txt", argv[1], block);
        std::ofstream out(buffer);
        for (int x = 0; x < num_patches; ++x)
        {
            for (int y = 0; y < num_patches; ++y)
            {
                out << x << " " << y << " " << E[x][y] << " " << occupied[x][y] << " " << disturbance_counter[x][y] << "\n";
            }
        }
        out.close();
    }
}
void AIClientApp::HandleMessage(const Message& msg) {
    //DebugLogger() << "AIClientApp::HandleMessage " << msg.Type();
    switch (msg.Type()) {
    case Message::ERROR_MSG: {
        ErrorLogger() << "AIClientApp::HandleMessage : Received ERROR message from server: " << msg.Text();
        break;
    }

    case Message::HOST_ID: {
        const std::string& text = msg.Text();
        int host_id = Networking::INVALID_PLAYER_ID;
        if (text.empty()) {
            ErrorLogger() << "AIClientApp::HandleMessage for HOST_ID : Got empty message text?!";
        } else {
            try {
                host_id = boost::lexical_cast<int>(text);
            } catch(const boost::bad_lexical_cast& ex) {
                ErrorLogger() << "AIClientApp::HandleMessage for HOST_ID : Couldn't parse message text \"" << text << "\": " << ex.what();
            }
        }
        m_networking->SetHostPlayerID(host_id);
        break;
    }

    case Message::JOIN_GAME: {
        if (PlayerID() == Networking::INVALID_PLAYER_ID) {
            DebugLogger() << "AIClientApp::HandleMessage : Received JOIN_GAME acknowledgement";
            try {
                int player_id;
                boost::uuids::uuid cookie; // ignore
                ExtractJoinAckMessageData(msg, player_id, cookie);
                m_networking->SetPlayerID(player_id);
            } catch(const boost::bad_lexical_cast& ex) {
                ErrorLogger() << "AIClientApp::HandleMessage for JOIN_GAME : Couldn't parse message text \"" << msg.Text() << "\": " << ex.what();
            }
        } else {
            ErrorLogger() << "AIClientApp::HandleMessage : Received erroneous JOIN_GAME acknowledgement when already in a game";
        }
        break;
    }

    case Message::GAME_START: {
        DebugLogger() << "AIClientApp::HandleMessage : Received GAME_START message; starting AI turn...";
        bool single_player_game;        // ignored
        bool loaded_game_data;
        bool ui_data_available;         // ignored
        SaveGameUIData ui_data;         // ignored
        bool state_string_available;    // ignored, as save_state_string is sent even if not set by ExtractMessageData
        std::string save_state_string;
        m_empire_status.clear();

        ExtractGameStartMessageData(msg,                     single_player_game,     m_empire_id,
                                    m_current_turn,          m_empires,              m_universe,
                                    GetSpeciesManager(),     GetCombatLogManager(),  GetSupplyManager(),
                                    m_player_info,           m_orders,               loaded_game_data,
                                    ui_data_available,       ui_data,                state_string_available,
                                    save_state_string,       m_galaxy_setup_data);

        DebugLogger() << "Extracted GameStart message for turn: " << m_current_turn << " with empire: " << m_empire_id;

        GetUniverse().InitializeSystemGraph(m_empire_id);

        DebugLogger() << "Message::GAME_START loaded_game_data: " << loaded_game_data;
        if (loaded_game_data) {
            TraceLogger() << "Message::GAME_START save_state_string: " << save_state_string;
            m_AI->ResumeLoadedGame(save_state_string);
            Orders().ApplyOrders();
        } else {
            DebugLogger() << "Message::GAME_START Starting New Game!";
            // % Distribution of aggression levels
            // Aggression   :  0   1   2   3   4   5   (0=Beginner, 5=Maniacal)
            //                __  __  __  __  __  __
            //Max 0         :100   0   0   0   0   0
            //Max 1         : 25  75   0   0   0   0
            //Max 2         :  0  25  75   0   0   0
            //Max 3         :  0   0  25  75   0   0
            //Max 4         :  0   0   0  25  75   0
            //Max 5         :  0   0   0   0  25  75

            // Optional aggression table, possibly for 0.4.4+?
            // Aggression   :  0   1   2   3   4   5   (0=Beginner, 5=Maniacal)
            //                __  __  __  __  __  __
            //Max 0         :100   0   0   0   0   0
            //Max 1         : 25  75   0   0   0   0
            //Max 2         :  8  17  75   0   0   0
            //Max 3         :  0   8  17  75   0   0
            //Max 4         :  0   0   8  17  75   0
            //Max 5         :  0   0   0   8  17  75

            const std::string g_seed = GetGalaxySetupData().m_seed;
            const std::string emp_name = GetEmpire(m_empire_id)->Name();
            unsigned int my_seed = 0;

            try {
                // generate consistent my_seed values from galaxy seed & empire name.
                boost::hash<std::string> string_hash;
                std::size_t h = string_hash(g_seed);
                my_seed = 3 * static_cast<unsigned int>(h) * static_cast<unsigned int>(string_hash(emp_name));
                DebugLogger() << "Message::GAME_START getting " << emp_name << " AI aggression, RNG Seed: " << my_seed;
            } catch (...) {
                DebugLogger() << "Message::GAME_START getting " << emp_name << " AI aggression, could not initialise RNG.";
            }

            int rand_num = 0;
            int this_aggr = m_max_aggression;

            if (this_aggr > 0  && my_seed > 0) {
                Seed(my_seed);
                rand_num = RandSmallInt(0, 99);
                // if it's in the top 25% then decrease aggression.
                if (rand_num > 74) this_aggr--;
                // Leaving the following as commented out code for now. Possibly for 0.4.4+?
                // in the top 8% ? decrease aggression again, unless it's already as low as it gets.
                // if (rand_num > 91 && this_aggr > 0) this_aggr--;
            }

            DebugLogger() << "Message::GAME_START setting AI aggression as " << this_aggr << " (from rnd " << rand_num << "; max aggression " << m_max_aggression << ")";

            m_AI->SetAggression(this_aggr);
            m_AI->StartNewGame();
        }
        m_AI->GenerateOrders();
        break;
    }

    case Message::SAVE_GAME_COMPLETE:
        break;

    case Message::TURN_UPDATE: {
        //DebugLogger() << "AIClientApp::HandleMessage : extracting turn update message data";
        ExtractTurnUpdateMessageData(msg,                     m_empire_id,        m_current_turn,
                                     m_empires,               m_universe,         GetSpeciesManager(),
                                     GetCombatLogManager(),   GetSupplyManager(), m_player_info);
        //DebugLogger() << "AIClientApp::HandleMessage : generating orders";
        GetUniverse().InitializeSystemGraph(m_empire_id);
        m_AI->GenerateOrders();
        //DebugLogger() << "AIClientApp::HandleMessage : done handling turn update message";
        break;
    }

    case Message::TURN_PARTIAL_UPDATE:
        ExtractTurnPartialUpdateMessageData(msg, m_empire_id, m_universe);
        break;

    case Message::TURN_PROGRESS: {
        Message::TurnProgressPhase phase_id;
        ExtractTurnProgressMessageData(msg, phase_id);
        ClientApp::HandleTurnPhaseUpdate(phase_id);
        break;
    }

    case Message::PLAYER_STATUS:
        break;

    case Message::END_GAME: {
        DebugLogger() << "Message::END_GAME : Exiting";
        DebugLogger() << "Acknowledge server shutdown message.";
        Networking().SendMessage(AIEndGameAcknowledgeMessage());
        ExitApp(0);
        break;
    }

    case Message::PLAYER_CHAT: {
        std::string data;
        int player_id;
        boost::posix_time::ptime timestamp;
        ExtractServerPlayerChatMessageData(msg, player_id, timestamp, data);
        m_AI->HandleChatMessage(player_id, data);
        break;
    }

    case Message::DIPLOMACY: {
        DiplomaticMessage diplo_message;
        ExtractDiplomacyMessageData(msg, diplo_message);
        m_AI->HandleDiplomaticMessage(diplo_message);
        break;
    }

    case Message::DIPLOMATIC_STATUS: {
        DiplomaticStatusUpdateInfo diplo_update;
        ExtractDiplomaticStatusMessageData(msg, diplo_update);
        m_AI->HandleDiplomaticStatusUpdate(diplo_update);
        break;
    }

    case Message::LOGGER_CONFIG: {
         std::set<std::tuple<std::string, std::string, LogLevel>> options;
         ExtractLoggerConfigMessageData(msg, options);

         SetLoggerThresholds(options);
         break;
    }

    case Message::CHECKSUM: {
        TraceLogger() << "(AIClientApp) CheckSum.";
        VerifyCheckSum(msg);
        break;
    }

    default: {
        ErrorLogger() << "AIClientApp::HandleMessage : Received unknown Message type code " << msg.Type();
        break;
    }
    }
    //DebugLogger() << "AIClientApp::HandleMessage done";
}
Exemple #17
0
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	TRandom::TRandom
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TRandom::TRandom()
{
	Seed(12345);
}
Exemple #18
0
//----------------------------------------------------------------
unsigned int SeedT(){ return Seed(); }
Exemple #19
0
unsigned RandomGen::Seed()
{
    unsigned seed = (unsigned)time(NULL);
    return Seed(seed);
}
Exemple #20
0
// Open libraries
void startup_open_libraries()
{
    BPTR file;
    long seed=0;

    // Open the other libraries that we need
    if (!(GfxBase=(struct GfxBase *)main_open_library("graphics.library",37)) ||
            !(IntuitionBase=(struct IntuitionBase *)main_open_library("intuition.library",37)) ||
            !(LayersBase=main_open_library("layers.library",37)) ||
            !(DiskfontBase=main_open_library("diskfont.library",36)) ||
            !(IconBase=main_open_library("icon.library",37)) ||
            !(WorkbenchBase=main_open_library("workbench.library",37)) ||
            !(CxBase=main_open_library("commodities.library",37)) ||
            !(UtilityBase=(struct UtilityBase *)main_open_library("utility.library",37)) ||
            !(GadToolsBase=main_open_library("gadtools.library",37)) ||
            !(RexxSysBase=main_open_library("rexxsyslib.library",0)) ||
            !(AslBase=main_open_library("asl.library",37))) quit(0);

#ifdef __amigaos4__
    // obtain ifaces
    if (!(IGraphics=(struct GraphicsIFace *)GetInterface((struct Library *)GfxBase,"main",1,NULL)) ||
            !(IIntuition=(struct IntuitionIFace *)GetInterface((struct Library *)IntuitionBase,"main",1,NULL)) ||
            !(ILayers=(struct LayersIFace *)GetInterface(LayersBase,"main",1,NULL)) ||
            !(IDiskfont=(struct DiskfontIFace *)GetInterface(DiskfontBase,"main",1,NULL)) ||
            !(IIcon=(struct IconIFace *)GetInterface(IconBase,"main",1,NULL)) ||
            !(IWorkbench=(struct WorkbenchIFace *)GetInterface(WorkbenchBase,"main",1,NULL)) ||
            !(ICommodities=(struct CommoditiesIFace *)GetInterface(CxBase,"main",1,NULL)) ||
            !(IUtility=(struct UtilityIFace *)GetInterface((struct Library *)UtilityBase,"main",1,NULL)) ||
            !(IGadTools=(struct GadToolsIFace *)GetInterface(GadToolsBase,"main",1,NULL)) ||
            !(IRexxSys=(struct RexxSysIFace *)GetInterface(RexxSysBase,"main",1,NULL)) ||
            !(IAsl=(struct AslIFace *)GetInterface(AslBase,"main",1,NULL))) quit(0);
#endif


    // Some other useful libraries
    DataTypesBase=OpenLibrary("datatypes.library",0);
    AmigaGuideBase=OpenLibrary("amigaguide.library",0);
    NewIconBase=OpenLibrary("newicon.library",0);
#ifdef __amigaos4__
    IDataTypes=(struct DataTypesIFace *)GetInterface(DataTypesBase,"main",1,NULL);
    IAmigaGuide=(struct AmigaGuideIFace *)GetInterface(AmigaGuideBase,"main",1,NULL);
    INewIcon=(struct NewIconIFace *)GetInterface(NewIconBase,"main",1,NULL);
#endif


    // Is CyberGfx library already in system? If so, open it for ourselves
    if (FindName(&SysBase->LibList,"cybergraphics.library")) {
        CyberGfxBase=OpenLibrary("cybergraphics.library",0);
#ifdef __amigaos4__
        ICyberGfx=(struct CyberGfxIFace *)GetInterface(CyberGfxBase,"main",1,NULL);
#endif
    }

    // Get input.device base
#ifdef __AROS__
    input_req.io_Message.mn_Length = sizeof(input_req);
#endif
    if (!OpenDevice("input.device",0,(struct IORequest *)&input_req,0)) {
        InputBase=(struct Library *)input_req.io_Device;
#ifdef __amigaos4__
        IInput = (struct InputIFace *)GetInterface(InputBase,"main",1,NULL);
#endif
    }

    // Get timer.device base
    if (!OpenDevice("timer.device",0,(struct IORequest *)&timer_req,0)) {
        TimerBase=(APTR)timer_req.io_Device;
#ifdef __amigaos4__
        ITimer = (struct TimerIFace *)GetInterface((struct Library *)TimerBase,"main",1,NULL);
#endif
    }
    else {
        quit(0);
    }

    // Get console.device base
    if (!OpenDevice("console.device",-1,(struct IORequest *)&console_req,0)) {
        ConsoleDevice=(APTR)console_req.io_Device;
#ifdef __amigaos4__
        IConsole = (struct ConsoleIFace *)GetInterface((struct Library *)ConsoleDevice,"main",1,NULL);
#endif
    }
    else {
        quit(0);
    };

    // Seed random number with something interesting
    if ((file=Open("dopus5:system/seed",MODE_OLDFILE)))
    {
        char buf[20];
        Read(file,buf,20);
        Close(file);
        seed=atoi((buf[0]=='-'?buf+1:buf));
    }
    seed+=(long)IntuitionBase+(long)AslBase*(long)WorkbenchBase*IntuitionBase->Micros;
    Seed(seed);
}
Random::Random()
{
	Seed(static_cast<unsigned int>(time(nullptr)));
}
Random::Random(unsigned int p_Seed)
{
	Seed(p_Seed);
}
Exemple #23
0
void AutoResolveCombat(CombatInfo& combat_info) {
    if (combat_info.objects.Empty())
        return;

    const System* system = combat_info.objects.Object<System>(combat_info.system_id);
    if (!system)
        Logger().errorStream() << "AutoResolveCombat couldn't get system with id " << combat_info.system_id;
    else
        Logger().debugStream() << "AutoResolveCombat at " << system->Name();

    if (GetOptionsDB().Get<bool>("verbose-logging")) {
        Logger().debugStream() << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%";
        Logger().debugStream() << "AutoResolveCombat objects before resolution: " << combat_info.objects.Dump();
    }

    // reasonably unpredictable but reproducible random seeding
    const int base_seed = combat_info.objects.begin()->first + CurrentTurn();


    // compile list of valid objects to attack or be attacked in this combat
    std::set<int> valid_target_object_ids;                          // all objects that can be attacked
    std::set<int> valid_attacker_object_ids;                        // all objects that can attack
    std::map<int, std::set<int> > empire_valid_attacker_object_ids; // objects that can attack that each empire owns
    float monster_detection = 0.0;

    for (ObjectMap::iterator it = combat_info.objects.begin(); it != combat_info.objects.end(); ++it) {
        const UniverseObject* obj = it->second;
        //Logger().debugStream() << "Considerting object " << obj->Name() << " owned by " << obj->Owner();
        if (ObjectCanAttack(obj)) {
            //Logger().debugStream() << "... can attack";
            valid_attacker_object_ids.insert(it->first);
            empire_valid_attacker_object_ids[obj->Owner()].insert(it->first);
        }
        if (ObjectCanBeAttacked(obj)) {
            //Logger().debugStream() << "... can be attacked";
            valid_target_object_ids.insert(it->first);
        }
        if (obj->Unowned() && obj->ObjectType() == OBJ_SHIP)
            monster_detection = std::max(monster_detection, obj->CurrentMeterValue(METER_DETECTION));
    }


    // map from empire to set of IDs of objects that empire's objects
    // could potentially target.
    std::map<int, std::set<int> > empire_valid_target_object_ids;   // objects that each empire can attack
    for (std::set<int>::const_iterator target_it = valid_target_object_ids.begin();
         target_it != valid_target_object_ids.end(); ++target_it)
    {
        int object_id = *target_it;
        const UniverseObject* obj = combat_info.objects.Object(object_id);
        //Logger().debugStream() << "Considering attackability of object " << obj->Name() << " owned by " << obj->Owner();

        // for all empires, can they attack this object?
        for (std::set<int>::const_iterator empire_it = combat_info.empire_ids.begin();
             empire_it != combat_info.empire_ids.end(); ++empire_it)
        {
            int attacking_empire_id = *empire_it;
            if (attacking_empire_id == ALL_EMPIRES) {
                if (ObjectAttackableByMonsters(obj, monster_detection)) {
                    //Logger().debugStream() << "object: " << obj->Name() << " attackable by monsters";
                    empire_valid_target_object_ids[ALL_EMPIRES].insert(object_id);
                }

            } else {
                // call function to find if empires can attack objects...
                if (ObjectAttackableByEmpire(obj, attacking_empire_id)) {
                    //Logger().debugStream() << "object: " << obj->Name() << " attackable by empire " << attacking_empire_id;
                    empire_valid_target_object_ids[attacking_empire_id].insert(object_id);
                }
            }
        }
    }


    // Each combat "round" a randomly-selected object in the battle attacks
    // something, if it is able to do so.  The number of rounds scales with the
    // number of objects, so the total actions per object is independent of
    // number of objects in the battle
    const int NUM_COMBAT_ROUNDS = 3*valid_attacker_object_ids.size();

    for (int round = 1; round <= NUM_COMBAT_ROUNDS; ++round) {
        Seed(base_seed + round);    // ensure each combat round produces different results

        // ensure something can attack and something can be attacked
        if (valid_attacker_object_ids.empty()) {
            Logger().debugStream() << "Nothing left can attack; combat over";
            break;
        }
        if (empire_valid_target_object_ids.empty()) {
            Logger().debugStream() << "Nothing left can be attacked; combat over";
            break;
        }
        // empires may have valid targets, but nothing to attack with.  If all
        // empires have no attackers or no valid targers, combat is over
        bool someone_can_attack_something = false;
        for (std::map<int, std::set<int> >::const_iterator attacker_it = empire_valid_attacker_object_ids.begin();
             attacker_it != empire_valid_attacker_object_ids.end(); ++attacker_it)
        {
            if (empire_valid_target_object_ids.find(attacker_it->first) != empire_valid_target_object_ids.end()) {
                someone_can_attack_something = true;
                break;
            }
        }
        if (!someone_can_attack_something) {
            Logger().debugStream() << "No empire has valid targets and something to attack with; combat over.";
            break;
        }

        Logger().debugStream() << "Combat at " << system->Name() << " (" << combat_info.system_id << ") Round " << round;

        // select attacking object in battle
        SmallIntDistType attacker_id_num_dist = SmallIntDist(0, valid_attacker_object_ids.size() - 1);
        std::set<int>::const_iterator attacker_it = valid_attacker_object_ids.begin();
        std::advance(attacker_it, attacker_id_num_dist());
        assert(attacker_it != valid_attacker_object_ids.end());
        int attacker_id = *attacker_it;

        UniverseObject* attacker = combat_info.objects.Object(attacker_id);
        if (!attacker) {
            Logger().errorStream() << "AutoResolveCombat couldn't get object with id " << attacker_id;
            continue;
        }
        Logger().debugStream() << "Attacker: " << attacker->Name();


        Ship* attack_ship = universe_object_cast<Ship*>(attacker);
        Planet* attack_planet = universe_object_cast<Planet*>(attacker);

        // loop over weapons of attacking object.  each gets a shot at a
        // randomly selected target object
        std::vector<PartAttackInfo> weapons;

        if (attack_ship) {
            weapons = ShipWeaponsStrengths(attack_ship);
            for (std::vector<PartAttackInfo>::const_iterator part_it = weapons.begin();
                 part_it != weapons.end(); ++part_it)
            {
                Logger().debugStream() << "weapon: " << part_it->part_type_name <<
                                          " attack: " << part_it->part_attack;
            }
        } else if (attack_planet) { // treat planet defenses as short range
            weapons.push_back(PartAttackInfo(PC_SHORT_RANGE, "", attack_planet->CurrentMeterValue(METER_DEFENSE)));
        }

        if (weapons.empty()) {
            Logger().debugStream() << "no weapons' can't attack";
            continue;   // no ability to attack!
        }

        for (std::vector<PartAttackInfo>::const_iterator weapon_it = weapons.begin();
             weapon_it != weapons.end(); ++weapon_it)
        {
            // select object from valid targets for this object's owner   TODO: with this weapon...
            Logger().debugStream() << "Attacking with weapon " << weapon_it->part_type_name << " with power " << weapon_it->part_attack;

            // get valid targets set for attacker owner.  need to do this for
            // each weapon that is attacking, as the previous shot might have
            // destroyed something
            int attacker_owner_id = attacker->Owner();

            std::map<int, std::set<int> >::iterator target_vec_it = empire_valid_target_object_ids.find(attacker_owner_id);
            if (target_vec_it == empire_valid_target_object_ids.end()) {
                Logger().debugStream() << "No targets for attacker with id: " << attacker_owner_id;
                break;
            }

            const std::set<int>& valid_target_ids = target_vec_it->second;
            if (valid_target_ids.empty())
                break; // should be redundant with this entry being erased when emptied


            // select target object
            SmallIntDistType target_id_num_dist = SmallIntDist(0, valid_target_ids.size() - 1);
            std::set<int>::const_iterator target_it = valid_target_ids.begin();
            std::advance(target_it, target_id_num_dist());
            assert(target_it != valid_target_ids.end());
            int target_id = *target_it;

            UniverseObject* target = combat_info.objects.Object(target_id);
            if (!target) {
                Logger().errorStream() << "AutoResolveCombat couldn't get target object with id " << target_id;
                continue;
            }
            Logger().debugStream() << "Target: " << target->Name();


            // do actual attacks, and mark attackers as valid targets for attacked object's owners
            if (attack_ship) {
                if (Ship* target_ship = universe_object_cast<Ship*>(target)) {
                    AttackShipShip(attack_ship, weapon_it->part_attack, target_ship, combat_info.damaged_object_ids);
                    empire_valid_target_object_ids[target_ship->Owner()].insert(attacker_id);
                } else if (Planet* target_planet = universe_object_cast<Planet*>(target)) {
                    AttackShipPlanet(attack_ship, weapon_it->part_attack,  target_planet, combat_info.damaged_object_ids);
                    empire_valid_target_object_ids[target_planet->Owner()].insert(attacker_id);
                }
            } else if (attack_planet) {
                if (Ship* target_ship = universe_object_cast<Ship*>(target)) {
                    AttackPlanetShip(attack_planet, target_ship, combat_info.damaged_object_ids);
                    empire_valid_target_object_ids[target_ship->Owner()].insert(attacker_id);
                } else if (Planet* target_planet = universe_object_cast<Planet*>(target)) {
                    AttackPlanetPlanet(attack_planet, target_planet, combat_info.damaged_object_ids);
                    empire_valid_target_object_ids[target_planet->Owner()].insert(attacker_id);
                }
            }


            // check for destruction of target object
            if (target->ObjectType() == OBJ_SHIP) {
                if (target->CurrentMeterValue(METER_STRUCTURE) <= 0.0) {
                    Logger().debugStream() << "!! Target Ship is destroyed!";
                    // object id destroyed
                    combat_info.destroyed_object_ids.insert(target_id);
                    // all empires in battle know object was destroyed
                    for (std::set<int>::const_iterator it = combat_info.empire_ids.begin();
                         it != combat_info.empire_ids.end(); ++it)
                    {
                        int empire_id = *it;
                        if (empire_id != ALL_EMPIRES)
                            combat_info.destroyed_object_knowers[empire_id].insert(target_id);
                    }

                    // remove destroyed ship's ID from lists of valid attackers and targets
                    valid_attacker_object_ids.erase(target_id);
                    valid_target_object_ids.erase(target_id);   // probably not necessary as this set isn't used in this loop

                    for (target_vec_it = empire_valid_target_object_ids.begin();
                         target_vec_it != empire_valid_target_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); }

                    for (target_vec_it = empire_valid_attacker_object_ids.begin();
                         target_vec_it != empire_valid_attacker_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); } // TODO: only erase from owner's entry in this list
                }

            } else if (target->ObjectType() == OBJ_PLANET) {
                if (target->CurrentMeterValue(METER_SHIELD) <= 0.0 &&
                    target->CurrentMeterValue(METER_DEFENSE) <= 0.0 &&
                    target->CurrentMeterValue(METER_CONSTRUCTION) <= 0.0)
                {
                    Logger().debugStream() << "!! Target Planet is knocked out of battle";

                    // remove disabled planet's ID from lists of valid attackers and targets
                    valid_attacker_object_ids.erase(target_id);
                    valid_target_object_ids.erase(target_id);   // probably not necessary as this set isn't used in this loop

                    for (target_vec_it = empire_valid_target_object_ids.begin();
                         target_vec_it != empire_valid_target_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); }

                    for (target_vec_it = empire_valid_attacker_object_ids.begin();
                         target_vec_it != empire_valid_attacker_object_ids.end(); ++target_vec_it)
                    { target_vec_it->second.erase(target_id); } // TODO: only erase from owner's entry in this list
                }
            }

            // check if any empire has no remaining target or attacker objects.
            // If so, remove that empire's entry
            std::map<int, std::set<int> > temp = empire_valid_target_object_ids;
            for (target_vec_it = empire_valid_target_object_ids.begin();
                 target_vec_it != empire_valid_target_object_ids.end(); ++target_vec_it)
            {
                if (target_vec_it->second.empty()) {
                    temp.erase(target_vec_it->first);
                    Logger().debugStream() << "No valid targets left for empire with id: " << target_vec_it->first;
                }
            }
            empire_valid_target_object_ids = temp;

            temp = empire_valid_attacker_object_ids;
            for (target_vec_it = empire_valid_attacker_object_ids.begin();
                 target_vec_it != empire_valid_attacker_object_ids.end(); ++target_vec_it)
            {
                if (target_vec_it->second.empty()) {
                    temp.erase(target_vec_it->first);
                    Logger().debugStream() << "No valid attacking objects left for empire with id: " << target_vec_it->first;
                }
            }
            empire_valid_attacker_object_ids = temp;
        } // end for over weapons
    } // end for over combat arounds

    // ensure every participant knows what happened.
    // TODO: assemble list of objects to copy for each empire.  this should
    //       include objects the empire already knows about with standard
    //       visibility system, and also any objects the empire knows are
    //       destroyed or
    for (std::map<int, ObjectMap>::iterator it = combat_info.empire_known_objects.begin();
         it != combat_info.empire_known_objects.end(); ++it)
    { it->second.Copy(combat_info.objects); }

    if (GetOptionsDB().Get<bool>("verbose-logging"))
        Logger().debugStream() << "AutoResolveCombat objects after resolution: " << combat_info.objects.Dump();
}
    std::pair<std::vector<StateOfCar>, Seed> AStarSeed::findPathToTargetWithAstar(const cv::Mat& img,const State&  start,const State&  goal) {
        // USE : for garanteed termination of planner
        int no_of_iterations = 0;

        fusionMap = img;
        MAP_MAX_ROWS = img.rows;
        MAP_MAX_COLS = img.cols;
        if(DT==1)
            distanceTransform();
        if (DEBUG)  {
            image = fusionMap.clone();
        }
        StateOfCar startState(start), targetState(goal);

        std::map<StateOfCar, open_map_element> openMap;

        std::map<StateOfCar,StateOfCar, comparatorMapState> came_from;

        SS::PriorityQueue<StateOfCar> openSet;

        openSet.push(startState);

        if (startState.isCloseTo(targetState)) {
            std::cout<<"Bot is On Target"<<std::endl;
            return std::make_pair(std::vector<StateOfCar>(), Seed());
        }
        
        else if(isOnTheObstacle(startState)){
            std::cout<<"Bot is on the Obstacle Map \n";
            return std::make_pair(std::vector<StateOfCar>(), Seed());
        }
        else if(isOnTheObstacle(targetState)){
            std::cout<<"Target is on the Obstacle Map \n";
            return std::make_pair(std::vector<StateOfCar>(), Seed());
        }

        while (!openSet.empty() && ros::ok()) {
            // std::cout<<"openSet size : "<<openSet.size()<<"\n";

            if(no_of_iterations > MAX_ITERATIONS){
                std::cerr<<"Overflow : openlist size : "<<openSet.size()<<"\n";
            return std::make_pair(std::vector<StateOfCar>(), Seed());
            }

            StateOfCar currentState=openSet.top();

            if (openMap.find(currentState)!=openMap.end() && openMap[currentState].membership == CLOSED) {
                openSet.pop();
            }
            
            currentState=openSet.top();

            if (DEBUG)  {
               std::cout<<"current x : "<<currentState.x()<<" current y : "<<currentState.y()<<std::endl;

               plotPointInMap(currentState);
               cv::imshow("[PLANNER] Map", image);
               cvWaitKey(0);
            }
            // TODO : use closeTo instead of onTarget
            if (currentState.isCloseTo(targetState)) {
               std::cout<<"openSet size : "<<openSet.size()<<"\n";
//                std::cout<<"Target Reached"<<std::endl;
                return reconstructPath(currentState, came_from);
            }
            openSet.pop();
            openMap[currentState].membership = UNASSIGNED;
            openMap[currentState].cost=-currentState.gCost(); 
            openMap[currentState].membership=CLOSED;
            
            std::vector<StateOfCar> neighborsOfCurrentState = neighborNodesWithSeeds(currentState);
            
            for (unsigned int iterator=0; iterator < neighborsOfCurrentState.size(); iterator++) {
                StateOfCar neighbor = neighborsOfCurrentState[iterator];

                double tentativeGCostAlongFollowedPath = neighbor.gCost() + currentState.gCost();
                double admissible = neighbor.distanceTo(targetState);
                double consistent = admissible;
                double intensity = fusionMap.at<uchar>(neighbor.y(), neighbor.x());
                
                double consistentAndIntensity = (neighbor.hCost()*neighbor.hCost()+2 + intensity*intensity)/(neighbor.hCost()+intensity+2);

                
                if (!((openMap.find(neighbor) != openMap.end()) &&
                      (openMap[neighbor].membership == OPEN))) {
                    came_from[neighbor] = currentState;
                    neighbor.gCost( tentativeGCostAlongFollowedPath) ;
                    if(DT==1)
                        neighbor.hCost(consistentAndIntensity);
                    else
                        neighbor.hCost( consistent) ;
                    neighbor.updateTotalCost();

                    openSet.push(neighbor);
                    openMap[neighbor].membership = OPEN;
                    openMap[neighbor].cost = neighbor.gCost();
                }
            }
            no_of_iterations++;
        }
        std::cerr<<"NO PATH FOUND"<<std::endl;
            return std::make_pair(std::vector<StateOfCar>(), Seed());
    }