Skip to content

Commit

Permalink
core: Avoid some redudant lookups in the particle type map (#4202)
Browse files Browse the repository at this point in the history
Description of changes:
- The particle type map stores an index of particle ids for the particle types, this switches the
  the data type from an unordered_set to a flat_set, which is more efficient for the typical use
  of the index, which is picking a random particle of a type in the hot loop of MC methods.
- Avoid some redundant lookups in the type index
  • Loading branch information
kodiakhq[bot] authored Apr 7, 2021
2 parents 8a2a79a + 153d0e0 commit 42fa06b
Showing 1 changed file with 23 additions and 13 deletions.
36 changes: 23 additions & 13 deletions src/core/particle_data.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1142,39 +1142,49 @@ void init_type_map(int type) {
if (type < 0)
throw std::runtime_error("Types may not be negative");

// fill particle map
if (particle_type_map.count(type) == 0)
particle_type_map[type] = std::unordered_set<int>();

auto &map_for_type = particle_type_map[type];
map_for_type.clear();
for (auto const &p : partCfg()) {
if (p.p.type == type)
particle_type_map.at(type).insert(p.p.identity);
map_for_type.insert(p.p.identity);
}
}

void remove_id_from_map(int part_id, int type) {
if (particle_type_map.find(type) != particle_type_map.end())
particle_type_map.at(type).erase(part_id);
auto it = particle_type_map.find(type);
if (it != particle_type_map.end())
it->second.erase(part_id);
}

int get_random_p_id(int type, int random_index_in_type_map) {
if (random_index_in_type_map + 1 > particle_type_map.at(type).size())
auto it = particle_type_map.find(type);
if (it == particle_type_map.end()) {
throw std::runtime_error("The provided particle type " +
std::to_string(type) +
" is currently not tracked by the system.");
}

if (random_index_in_type_map + 1 > it->second.size())
throw std::runtime_error("The provided index exceeds the number of "
"particle types listed in the particle_type_map");
return *std::next(particle_type_map[type].begin(), random_index_in_type_map);
return *std::next(it->second.begin(), random_index_in_type_map);
}

void add_id_to_type_map(int part_id, int type) {
if (particle_type_map.find(type) != particle_type_map.end())
particle_type_map.at(type).insert(part_id);
auto it = particle_type_map.find(type);
if (it != particle_type_map.end())
it->second.insert(part_id);
}

int number_of_particles_with_type(int type) {
if (particle_type_map.count(type) == 0)
auto it = particle_type_map.find(type);
if (it == particle_type_map.end()) {
throw std::runtime_error("The provided particle type " +
std::to_string(type) +
" is currently not tracked by the system.");
return static_cast<int>(particle_type_map.at(type).size());
}

return static_cast<int>(it->second.size());
}

// The following functions are used by the python interface to obtain
Expand Down

0 comments on commit 42fa06b

Please sign in to comment.