Skip to content

Adding new particle identifier: name. Removing: hash. #885

Description

@hannorein

I'm working on rewriting how particles are identified in REBOUND. Currently, we have a hash property which is an integer. We provide reb_hash() which maps strings to integers. After this change, the primary way to identify a particle (other than by index or pointer) will be a string. The syntax to add a particle with a name is short and concise in C:

reb_simulation_add(r, (struct reb_particle){.m=1.0, .name="Sun"});
// or
struct reb_particle p = {
    .m = 1.0,
    .name = "Sun"
};
reb_simulation_add(r, p);
// or
reb_simulation_add_fmt(r, "m name", 1.0, "Sun");

and python:

sim.add(m=1.0, name="Sun")
# or 
sim.add("Sun")  # queries Horizon, then adds a particle with name Sun
# or
p = rebound.Particle(m=1, name="Sun")
sim.add(p)

To retrieve a particle, the syntax is

struct reb_particle* p = reb_simulation_get_particle_by_name(r,"Sun");
// maybe a shorter alias of reb_simulation_get_particle_by_name() would make sense.

and

sim["Sun"]

Thanks to unicode, one can do fun things such as

print(sim["🌍"])

The memory for the strings is managed by the simulation as soon as the particle is added to a simulation (the string gets copied when a particle is added). This allows one to create many particles with names without having to worry about memory management:

char name[256];
for (int i=0; i<100;i++){
    sprintf(name, "asteroid %d", i);
    reb_simulation_add(r, (struct reb_particle){.m=1.0, .name=name});
}

It's up to the user to decide whether to use use unique names or not. For example, one group of particles could be called "planet" and another group called "asteroid". Then different forces can be applied to the different groups.

The strings are saved to simulation archives and restored automatically.

The current implementation works (see slightly mislabled branch hash_table), but is not optimized yet. I plan to implement a simple cache for reb_simulation_get_particle_by_name and a hash table for large simulations.

Happy to hear any comments.

@dtamayo: Note that this will break several effect in REBOUNDx. But I don't think it will limit the functionality in any way. It's just a matter of changing integers to strings.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions