Skip to content

Union particle - #3095

Open
mads-bertelsen-agentic wants to merge 19 commits into
mccode-dev:mainfrom
mads-bertelsen-agentic:Union_particle
Open

mads-bertelsen-agentic wants to merge 19 commits into
mccode-dev:mainfrom
mads-bertelsen-agentic:Union_particle

Conversation

@mads-bertelsen-agentic

@mads-bertelsen-agentic mads-bertelsen-agentic commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

Free-form text area

Please describe what your PR is adding in terms of features or bugfixes:

Refactors Union process, surface and logger callbacks to use the particle state directly in both McStas and McXtrace. This reduces duplicated state handling and adds an optional safe_mode to protect particle fields from unintended callback changes.
Along the way, the update fixes particle-frame transformations, RNG forwarding, photon absorption logging and several unnecessary particle copies. It also adds regression coverage under Tests_union.
Compatibility note: Custom Union callbacks must be updated to the particle-based API. RNG forwarding and skipping unused absorption samples can change seeded trajectories.


Declaration of use of AI-tools

  • Please add a checkmark here if you used AI-tools during the work for this contribution
  • Furter, please describe how / where and for what the tools were used:
    opencode session with GPT-6.1 Terra - aim of switching to _particle approach

Development OS / boundary conditions

Please describe what OS you developed and tested your additions on, and if any special dependencies are required:
OS X 14.6.1 (23G93)


PR Checklist for contributing to McStas/McXtrace

For a coherent and useful contribution to McStas/McXtrace, please fill in relevant parts of the checklist:

  • My contribution includes patches to an existing component file

    • I have used the mcdoc utility and rendered a reasonable documentation page for the component (please attach as screenshot in comments!)
    • I have ensured that basic use of the component is OK (e.g. an instrument using it compiles?)
    • I have used the mctest utility to test one or more instruments making use of the component (please attach mcviewtest report as screenshot in comments)
    • I have used the mccode-clangformat tool to apply the standard McCode component indentation scheme
    • I have used the mcrun --c-lint "linter" and followed advice to remove most / all warnings that are raised
  • My contribution includes a new component file

    • I have ensured that naming of parameters are in the style of existing components. (Please check the McStas or McXtrace NOMENCLATURE docs.)
    • I have ensured that component parameters are in the usually units of McStas or McXtrace (SI + neutron/x-ray 'usual' units)
    • I have used the mcdoc utility and rendered a reasonable documentation page for the component (please attach as screenshot in comments!)
    • I have ensured that basic use of the component is OK (e.g. an instrument using it compiles?)
    • I have included a corresponding example instrument and will fill in the new instrument section below
    • I have used the mccode-clangformat tool to apply the standard McCode component indentation scheme
    • My new component is added within the contrib component category
  • My contribution includes a new instrument file

    • I have used the mcdoc utility and rendered a reasonable documentation page for the instrument (please attach as screenshot in comments!)
    • I have ensured that basic use of the instrument is OK (e.g. it compiles?)
    • ... and provided reasonable default parameters in that instrument that produce reasonable output
    • ... and maybe even added a %Test: line (or a %TestScan: line for a parameter scan) to describe expected behaviour
    • I have used the mcrun --c-lint "linter" and followed advice to remove most / all warnings that are raised
    • My new instrument is added within the examples hierarchy in a folder in the style of examples/ESS/New_stuff/New_stuff.instr
    • My new instrument has a new, unique filename, not clashing with existing example instruments
    • My new instrument requires a data/input file. If the datafile is specific for my instrument I have left it in the same example folder, but if general use I have placed it in the global data folder.
  • My work touches / adds to the runtime lib code (.c,.h etc in multiple locations

    • I am have added reasoning and documentation for the change below
    • I am attaching test output in the comments
    • Unit test: every new or changed common/lib/share, mccode/nlib/share, mcstas-comps/share or mcxtrace-comps/share library and runtime file (.c, .h, .h.in) has a Test_lib_<name> instrument in examples/libtest/ (McStas and/or McXtrace), with a %Test: line where the result can be checked. If it cannot be standalone, say why in the free-form text (e.g. needs a component or external package)

@mads-bertelsen-agentic
mads-bertelsen-agentic marked this pull request as draft November 12, 2026 07:18
@willend

willend commented Nov 12, 2026

Copy link
Copy Markdown
Contributor

GPU (nvc) build of Test_union_particle fails on the fprintf calls in union_particle_test_dump() (Union_particle_test_support.comp): final_state sits after the NOACC Union_master, so its TRACE lands in the GPU kernel, where variadic calls are not supported.

Simplest fix: mark Union_particle_test_support as NOACC. Alternative if it should run on GPU: store the particle in TRACE and dump in SAVE (as Event_monitor_simple does). An #ifndef OPENACC guard would leave final_state.log empty on GPU.

Not verified with an nvc build.

@mads-bertelsen-agentic

Copy link
Copy Markdown
Contributor Author

When doing clangformat a problem was found

I ran mccode-clangformat on the PR’s changed source files. It formats 41 of 43 files cleanly, but I left IncoherentPhonon_process.comp and Inhomogenous_incoherent_process.comp unchanged because the formatter breaks their one-line dispatch macros.

For example, this macro:

#define UNION_CASE_PHYSICS_SCATTERING_INCOHERENTPHONON(out, ...) case IncoherentPhonon: out = IncoherentPhonon_physics_scattering(__VA_ARGS__); break;

is reformatted into a macro line ending after the function call, with //break; on the next line. That puts break outside the macro, so the generated switch case can fall through. The same issue occurs in the other component’s dispatch macro.

For this pull request the clangformating was reverted on the affected lines.

@willend

willend commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

@mads-bertelsen I have filed #3123 and have started an investigation to avoid breaking # instructions no matter how long.

@mads-bertelsen-agentic
mads-bertelsen-agentic marked this pull request as ready for review November 17, 2026 08:12
@mads-bertelsen-agentic

Copy link
Copy Markdown
Contributor Author

Running c-lint on Union_demos/demonstration produce what an LLM calls false positives. It's related to the mcdisplay code for union, and it seems there is underlying logic preventing that indices can get out of bounds, but cppcheck doesn't catch that and marks it as an error. Instrument and mcdisplay runs well without any errors / warnings.

Checking Demonstration.c: MCDEFAULT_NCOUNT=1000000;ND_BUFFER=10000000;SIGABRT=1;SIGBREAK=1;SIGBUS=1;SIGPE=1;SIGHUP=1;SIGILL=1;SIGINT=1;SIGKILL=1;SIGUSR1=1;SIGUSR2=1;SIGPIPE=1;SIGQUIT=1;SIGSEGV=1;SIGTRAP=1;SIGURG=1;SIGFPE=1;SIGKILL=1;SIGTERM=1;__unix__=1...
Demonstration.c:16170:22: error: Array 's[3][8]' accessed at index s[3][0], which is out of bounds. [arrayIndexOutOfBounds]
        double sp = s[k][0], sq = 1 - s[(k+2)%3][0]; // fractions from v[k] towards w1 and w2
                     ^
Demonstration.c:16168:19: note: Assuming that condition 'k<3' is not redundant
        for (k=0;k<3;k++) if (n[k] == 1 && n[(k+2)%3] == 1) break; // lone vertex v[k] between the two cut edges
                  ^
Demonstration.c:16170:22: note: Array index out of bounds
        double sp = s[k][0], sq = 1 - s[(k+2)%3][0]; // fractions from v[k] towards w1 and w2
                     ^
Demonstration.c:16171:32: error: Array 'v[3]' accessed at index 3, which is out of bounds. [arrayIndexOutOfBounds]
        Coords p = coords_add(v[k],coords_scalar_mult(coords_sub(w1,v[k]),sp));
                               ^
Demonstration.c:16168:19: note: Assuming that condition 'k<3' is not redundant
        for (k=0;k<3;k++) if (n[k] == 1 && n[(k+2)%3] == 1) break; // lone vertex v[k] between the two cut edges
                  ^
Demonstration.c:16171:32: note: Array index out of bounds
        Coords p = coords_add(v[k],coords_scalar_mult(coords_sub(w1,v[k]),sp));
                               ^
Demonstration.c:16171:70: error: Array 'v[3]' accessed at index 3, which is out of bounds. [arrayIndexOutOfBounds]
        Coords p = coords_add(v[k],coords_scalar_mult(coords_sub(w1,v[k]),sp));
                                                                     ^
Demonstration.c:16168:19: note: Assuming that condition 'k<3' is not redundant
        for (k=0;k<3;k++) if (n[k] == 1 && n[(k+2)%3] == 1) break; // lone vertex v[k] between the two cut edges

@willend

willend commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

@mads-bertelsen sometimes I've tricked the lint'er past these types of things by a simple init e.g. int k=0; outside of the for-loop, may be worth a try? Otherwise I believe the current mode where we "follow advice to remove most / all warnings that are raised by the linter" is OK, i.e. some warnings 'will be'.

@mads-bertelsen-agentic

Copy link
Copy Markdown
Contributor Author

There seems to something preventing the antlr version from building, but it seems to have to do with some dependency and not this code change

@mads-bertelsen-agentic

mads-bertelsen-agentic commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

No antlr passed, but a different test had this error:

xargs -n1 ./src/devel/bin/mccode-simdir-cleanfiles -d
usage: mccode-simdir-cleanfiles [-h] [-p {win,linux,mac}] [-d DIR]
mccode-simdir-cleanfiles: error: argument -d/--dir: expected one argument

Edit: The root cause seemed to be an ubuntu server being unavailable so install failed, rerunning the job

@willend

willend commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Thanks for this. Moving the Union callbacks over to _class_particle is the right direction. It removes a lot of duplicated state handling in Union_master (the r/v/k/ray_* bookkeeping), and the logger cleanup is welcome. A few things need attention before merging.

Bug

  • union_tri_add in mcstas-comps/share/union-lib.c (around L1921): this hunk isn't part of the particle refactor, and it changes behaviour. The new if (k >= 0 && k < 3) wrapper moves the return out of the inner if. Before, a triangle that failed the straight-cut test fell through to the split-in-4 refinement below. Now it returns without emitting anything, so mcdisplay will drop triangles. Please revert this hunk. (k >= 0 is always true there anyway.)

Propagation

  • Switching to PROP_NO_G_DT is an improvement over the old hand-written x += vx*dt …. One question: in McStas, mcPROP_DT also does spin precession when mcMagnet is set, absorbs on NaN/Inf p, and the macro calls DISALLOW_BACKPROP. Is that intended inside the Union loop? An ABSORB part-way through would skip the end-of-ray conditional and logger handling.

Simplicity

  • safe_mode: what is the use case for three levels? Loggers already receive const _class_particle*, so the compiler protects them, and the logger copy-and-check wrappers look redundant. For processes, mode 1 silently restores fields, which hides a broken callback instead of exposing it. I'd suggest keeping at most the checking mode (2), or dropping the option and relying on const and review.
  • Particle copies: TRACE now makes several whole-struct _class_particle copies per event (reference_particle, sample_particle inside the sampling loop, process_particle, the *_before copies, and the logger before/after pair). reference_particle only needs position and velocity for the intersection calls. Please trim the copies that aren't needed.
  • Smaller cleanups:
    • The UNION_PARTICLE_* macros alias functions of the same name. Please call the functions directly.
    • move_and_aim_neutron should reuse union_particle_translate_to_local instead of doing the same subtraction inline.
    • randvec_target_rect → randvec_target_rect_real(…,0,0,0,1) is what the macro already expands to. Please leave it as it was.
  • Tests: the Python runner in Tests_union/ isn't run by mctest or CI. Please move the essential checks into %Test: lines on the instruments so they run automatically.

Compatibility

  • This breaks every external Union process, surface and logger. Could you add a one-line summary for the next changelog that says what users need to change? Comment here is fine

Scope: we'll take this one as it is. Going forward, please keep each PR to one well-defined concern (for example the API change, the fixes, and new options or tests separately). That makes review much faster.

@willend willend mentioned this pull request Nov 24, 2026
2 tasks done
Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Call particle helpers directly and restore the standard rectangular targeting macro in both flavours.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Use transport snapshots for temporary changes, retain RNG advancement, and keep diagnostic copies in safe modes. Cover snapshot and callback behavior in the Union particle regression.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
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.

2 participants

⌂ Proxy