Skip to content

Python: Avoid More Segfaults #1354

@ax3l

Description

@ax3l

We generally do not want to segfault when we run in Python, but throw exceptions.

thank you to @RemiLehe and his twin claude 💖

ImpactX Cookbook

A living document of pitfalls, quirks, and useful patterns for working with ImpactX. Updated by the feedback loop after each design task.

Known Pitfalls

Segfault when calling pc.beam_moments() after sim.finalize() in PIC mode

  • Symptom: After sim.evolve() and sim.finalize(), calling pc.beam_moments() causes a segfault (exit code 139) because the particle container has been deallocated.
  • Root cause: sim.finalize() tears down the AMReX/ImpactX runtime, including the particle container. Any access to pc after this point is undefined behaviour.
  • Solution: Either call pc.beam_moments() before sim.finalize(), or read the final Twiss from the diagnostics CSV after finalize (same pattern as envelope mode). The CSV is always safe to read after finalize.

Reference particle must be set via particle_container() before add_particles() in PIC mode

  • Symptom: Assertion 'ref.charge_qe() != 0.0' failed / SIGABRT when calling sim.add_particles(...).
  • Root cause: In PIC mode, add_particles reads the reference particle from the internal particle container. If the reference particle was created as a standalone RefPart() and set via pc.set_ref_particle(ref) after the call, the container still has a zero-charge reference at the time of the call.
  • Solution: Access the reference particle directly from the container before calling add_particles:
    sim.init_grids()
    ref = sim.particle_container().ref_particle()
    ref.set_charge_qe(-1.0).set_mass_MeV(938.783).set_kin_energy_MeV(170.627)
    sim.add_particles(bunch_charge_C, distr, npart)

beam_moments() returns NaN for Twiss in envelope mode

  • Symptom: After sim.track_envelope(), calling pc.beam_moments() and accessing moments["beta_x"] etc. returns NaN, even though the simulation ran correctly.
  • Root cause: In envelope mode, ImpactX does not populate the particle-level moments used by beam_moments() to compute Twiss. The Twiss are computed and written to the diagnostics CSV, but the in-memory moments object is not filled.
  • Solution: Read the final Twiss from the reduced diagnostics CSV file: diags/reduced_beam_characteristics_final.0.0. Parse it with pandas.read_csv(..., sep=r"\s+") and access columns beta_x, alpha_x, beta_y, alpha_y. The last row gives the final state.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions