Skip to content

229 port remaining converter functions from cc to python - #230

Open
witNie wants to merge 56 commits into
masterfrom
229-port-remaining-converter-functions-from-cc-to-python
Open

witNie wants to merge 56 commits into
masterfrom
229-port-remaining-converter-functions-from-cc-to-python

Conversation

@witNie

@witNie witNie commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

No description provided.

witNie and others added 30 commits March 2, 2026 21:45
- Introduced `stopping_power` function to calculate stopping power in MeV*cm²/g.
- Refactored existing mass stopping power functionality into `stopping_power.cpp` and `stopping_power.h`.
- Updated stopping bindings to include new `stopping_power` function.
- Enhanced error handling for particle and material processing.
- Added support for both scalar and array inputs for energy, particle, and material.
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Witold Nieć <witold.niec@gmail.com>
…ding-to-one-of-the-models_2' of https://github.com/libamtrack/pyamtrack into 62-add-stopping-power-for-protons-in-liquid-water-according-to-one-of-the-models_2
Co-authored-by: Leszek Grzanka <leszek.grzanka@gmail.com>
Signed-off-by: Witold Nieć <witold.niec@gmail.com>
@witNie witNie linked an issue Oct 2, 2026 that may be closed by this pull request
@PiotrPich2024
PiotrPich2024 marked this pull request as ready for review October 18, 2026 19:25


const char* dose_from_fluence_doc = R"pbdoc(
Calculate absorbed dose from particle fluence.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Calculate absorbed dose from particle fluence.
Calculate absorbed dose in Gy from particle fluence.


Parameters
----------
momentum : float, int, list, or numpy.ndarray

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we add units to momentum, like for energy, i.e. momentum_MeV_c_nucl ?

Check also whether we should use momentum per_u or per_nucl. I think in case of momentum per_u may be more natural.



const char* energy_from_energy_per_amu_doc = R"pbdoc(
Calculate the total kinetic energy of a particle from its kinetic energy

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if something has MeV/u unit then we cannot call it "energy per nucleon", its rather "energy per atomic mass unit"

@grzanka grzanka left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see comments inline

@grzanka

grzanka commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Review of #230: "Port remaining converter functions"

Review written by Claude Opus 5.5 (claude-opus-5-5) via Claude Code, at the request of @grzanka. Each finding was checked against the PR branch and the libamtrack sources.

Verdict: Request changes. CI is green, but the tests only compare each function with itself and only use protons, so they miss real physics bugs. Part of the diff also undoes the stopping-power work merged in #182.

Blocking issues

  1. energy_from_beta, energy_from_gamma and energy_from_momentum return wrong values. The libamtrack routines return MeV/u. The PR then calls AT_E_MeV_u_from_E_MeV, which divides by the atomic weight a second time. It should multiply, using AT_E_MeV_from_E_MeV_u.

    • Locations: src/converters/energy_from_beta.cpp:29, energy_from_gamma.cpp:30, energy_from_momentum.cpp:30.
    • Effect: the result is off by a factor of the atomic weight squared. For carbon that's about 144× (≈12 MeV instead of ≈1731 MeV at β=0.5). For protons it's still about 1.6% off, because hydrogen's atomic weight is 1.008.
  2. The stopping-power changes from stopping power and mass stopping power implemetations #182 are reverted, probably by the merge in fe87000.

    • stopping_power and mass_stopping_power go back to taking energy_MeV_u and calling AT_*_with_no. The PR's own converters move the other way, to total MeV, so the two modules now disagree.
    • The line result = fallback_result; was dropped (src/stopping/stopping_power.cpp:176-181). With allow_bethe_fallback=True, the Bethe fallback result is thrown away: the function returns the failed value but reports Bethe as the source.
    • The tests in tests/test_stopping.py were edited to match the reverted behaviour.
    • particle_to_long.h is no longer used anywhere, and Ion::get_internal_particle_no repeats its logic.
  3. The stopping_power_source argument of dose_from_fluence and fluence_from_dose is passed raw to libamtrack (dose_from_fluence.cpp:24, fluence_from_dose.cpp:24).

    • The docstring says "bethe", "pstar" and similar strings work. They raise TypeError.
    • In libamtrack, 0 means FromFile, not "default". The fix is to call the existing parse_stopping_power_source and the default-selection logic, as the stopping module does.
    • The default here is 1; in the stopping module it is 0.
  4. Two binding errors:

    • fluence_from_dose is registered with dose_from_fluence_doc (converters_bindings.cpp:331).
    • momentum_from_energy is registered with the keyword energy_MeV_u (converters_bindings.cpp:319), but it takes total MeV and its docstring calls the argument energy_MeV.
  5. The breaking API change isn't documented. beta_from_energy and energy_from_beta now need a particle argument.

  6. The new examples/stopping.ipynb can't run. It passes particle=1001 and 6012, and the API rejects integer particle numbers. It also ends with an empty cell and largely repeats stopping_power.ipynb.

Tests

  • None of the 8 new functions has a test.
  • The existing tests can't catch issue 1. Please add round-trip tests with ¹²C, e.g. energy_from_beta(beta_from_energy(E, C12), C12) ≈ E, plus a few known reference values.
  • The removed tests for 0-D and N-D arrays were testing real behaviour, and that behaviour is now lost:
    • N-D arrays now raise "Input NumPy array must be 1-D".
    • A list input now returns an ndarray, while docs/naming_convention.md:48 still says it returns a list.

Docstrings

The particle description is confusing:

  • It describes an internal step ("used to convert the total energy…") rather than what the argument is.
  • "Represented by a pyamtrack Ion object" repeats the type line, and numpy.ndarray doesn't say what the array holds.
  • It's also not accurate. libamtrack divides by the element's standard atomic weight, looked up by Z alone, and ignores A (libamtrack src/AT_PhysicsRoutines.c:35, src/AT_DataParticle.c:131). So "MeV/u" here means per atomic mass unit, not per nucleon, and ³He and ⁴He give the same result.
  • The same paragraph is pasted into energy_from_*, where the conversion goes the other way.

Suggested wording:

particle : Ion, list[Ion], or numpy.ndarray of Ion
    Projectile ion(s), e.g. ``pyamtrack.particles.proton`` or
    ``pyamtrack.particles.from_string("12C")``. Elementary particles
    (electron, neutron) are not supported. A sequence is paired elementwise
    with the other array arguments, or adds a dimension when
    ``cartesian_product=True``.

Notes
-----
Conversion between ``energy_MeV`` and MeV/u divides by the standard atomic
weight of the ion's element (libamtrack convention), not by the mass number A.

Other docstring fixes:

  • "Total kinetic energy": in relativity, "total energy" includes rest mass. Use "kinetic energy of the whole ion (not per nucleon), in MeV".
  • momentum_from_energy: it takes the whole-ion energy but returns momentum per nucleon. Either document that clearly or make input and output use the same basis.
  • Returns: say the array is 1-D, and that with cartesian_product=True the shape is (len(a), len(b), …).
  • Argument names: following docs/naming_convention.md, rename dose to dose_Gy and momentum to momentum_MeV_c_u. Write the material default as "liquid water (ID 1)".
  • Error message: validate_particle_argument says "stopping power requires Z and A", and converter users now see that message.
  • stopping_power.h: @param particle says "Particle number (1000*Z + A) or Ion object", but the binding docstring says integers are rejected.
  • docs/naming_convention.md: the 8 new functions are missing from the function list.

Code cleanup

  • The nine converter files are almost identical (~35 lines each). One shared helper, e.g. wrap_ion_converter(fn, value, particle, cartesian_product), would replace them.
  • Pre-commit clearly wasn't run: several new files lack a final newline, and there are stray };, double blank lines, and unused single_argument.h includes.
  • Parameter names in some headers don't match the .cpp files (particle_no vs particle, energy vs energy_MeV_u).
  • variant_cast<int> and variant_cast<long> are used inconsistently.
  • The header guard comment has a typo: MOMEMTUM.
  • Particle::get_internal_particle_no is a non-virtual stub that always throws and is only hidden by Ion's version. Keeping the single particle_to_internal_no() function is cleaner.

Suggested order

  1. Rebase onto master and restore stopping power and mass stopping power implemetations #182's stopping code.
  2. Fix issue 1.
  3. Route stopping_power_source through the parser.
  4. Fix the two bindings.
  5. Add round-trip tests for ¹²C.
  6. Update the READMEs and the naming doc.

🤖 Generated with Claude Code · model: Claude Opus 5.5 (claude-opus-5-5)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Several correctness defects (discarded Bethe-fallback result, wrong per-nucleon↔total energy conversion in three inverse converters, a mismatched docstring, and a broken example) need fixing before approval.

10 open issues
What changed in this PR

This PR completes the port of the remaining libamtrack converter functions to the Python (nanobind) bindings, bringing them in line with the existing multi-argument/cartesian-product wrapper pattern. The converters now take a particle argument and total kinetic energy (energy_MeV), and the stopping-power wrappers are migrated from the deprecated AT_*_E_MeV_single single-value functions to the array-based AT_*_with_no functions, switching the public energy input to per-nucleon (energy_MeV_u). Supporting infrastructure, docs, examples, and CI smoke tests are updated accordingly.

Changes:

  • Add 8 new converter bindings (gamma/momentum/energy-per-amu/dose/fluence conversions) and extend beta_from_energy/energy_from_beta to accept a particle and vectorized inputs.
  • Migrate stopping-power wrappers to AT_*_with_no and change the energy input semantics to MeV/u, with matching validation/error-message updates.
  • Introduce Ion::get_internal_particle_no() (replacing particle_to_long.h usage) and refresh tests, examples, docs, and CI invocations.
File Description
src/​stopping/​stopping_power.cpp Switch to AT_*_with_no; MeV/u semantics — fallback result is no longer assigned back (bug)
src/​stopping/​stopping_power.h Doc updates; particle description now inaccurately allows integer particle numbers
src/​stopping/​stopping_bindings.cpp Rename kwarg to energy_MeV_u and update docstrings
src/​converters/​energy_from_beta.cpp New particle-aware impl; uses wrong per-nucleon→total conversion
src/​converters/​energy_from_gamma.cpp New converter; wrong per-nucleon→total conversion
src/​converters/​energy_from_momentum.cpp New converter; wrong per-nucleon→total conversion
src/​converters/​beta_from_energy.cpp/​.h Particle-aware, vectorized rewrite
src/​converters/​gamma/​momentum/​*from_energy.*, energy(from|per)amu* New forward/inverse converters
src/​converters/​converters_bindings.cpp Register new converters; wrong docstring for fluence_from_dose; inconsistent momentum_from_energy kwarg
src/​converters/​momentum_from_energy.h New header; misspelled include-guard comment
src/​particles/​{particles.h,ions/​ion.h,particle_arguments.h} Add get_internal_particle_no() and rewire validation
tests/​test_{converters,function_behavior,multidim_input,stopping}.py Adapt tests to new signatures; new converters remain untested
examples/​*.ipynb Update usage; new stopping.ipynb passes integer particles that the API rejects
docs/​naming_convention.md, .github/​workflows/​* , scripts/​build_linux.sh Update signatures/invocations

Review effort: Balanced

Comment thread examples/stopping.ipynb
Comment on lines +36 to +37
"results_proton = stp.stopping_power(energies, particle=particle_proton, material=material)\n",
"results_carbon = stp.stopping_power(energies, particle=particle_carbon, material=material)"
Comment thread src/converters/converters_bindings.cpp Resolved
Comment thread src/converters/converters_bindings.cpp Outdated
Comment on lines +325 to +331
m.def("dose_from_fluence", &dose_from_fluence, nb::arg("energy_MeV"), nb::arg("particle"), nb::arg("fluence_cm2"),
nb::arg("material") = 1, nb::arg("stopping_power_source") = 1, nb::arg("cartesian_product") = false,
dose_from_fluence_doc);

m.def("fluence_from_dose", &fluence_from_dose, nb::arg("energy_MeV"), nb::arg("particle"), nb::arg("dose"),
nb::arg("material") = 1, nb::arg("stopping_power_source") = 1, nb::arg("cartesian_product") = false,
dose_from_fluence_doc);
Comment thread src/converters/converters_bindings.cpp Resolved
Comment thread src/converters/energy_from_beta.cpp Resolved
Comment thread src/converters/energy_from_gamma.cpp Resolved
Comment thread src/converters/energy_from_momentum.cpp Resolved
Comment thread src/converters/momentum_from_energy.h Resolved
Comment on lines +178 to 181
if (fallback_status != AT_Success || fallback_result < 0.0) {
throw std::invalid_argument("Stopping-power calculation failed for the selected source and material");
}
result = fallback_result;
}
* internally for the stopping-power models.
* @param particle Particle object.
* @param energy_MeV_u Kinetic energy in MeV per nucleon.
* @param particle Particle number (1000*Z + A) or Ion object.
Copilot review has found some mistakes like wrong naming scheme and wrong function names in few of them

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Piotr Pich <ppich@student.agh.edu.pl>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Port remaining converter functions from C/C++ to Python

5 participants