API Reference¶
This page documents the public Python API of ng-imager.
This section is automatically generated from the Python docstrings using mkdocstrings. It covers the main simulation, imaging, and reconstruction modules that form the ng-imager pipeline.
The modules are grouped roughly by how you use them in an imaging workflow:
- Pipelines: high-level entry points that wire everything together.
- Physics & geometry: event / cone construction and projection math.
- I/O & configuration: reading event data, HDF5 storage, configuration.
- CLI & visualization: the command-line app and simple plotting utilities.
- Simulation & tools: synthetic data generation and LUT utilities.
Pipelines¶
High-level orchestration for running NOVO imaging.
ngimager.pipelines.core¶
The CLI is implemented via Typer, so the script behaves like a simple one-argument command:
- argument = path to TOML config file
The pipeline will:
- Load the TOML config
- Detect the adapter (PHITS, ROOT, HDF5 restart)
- Shape/validate hits → events
- Build cones (now neutron + gamma depending on run.neutrons, run.gammas)
- Run SBP imaging
- Write unified HDF5 output
You can always show help via:
- `python -m ngimager.pipelines.core --help`
Example run commands from project root:
python -m ngimager.pipelines.core path/to/config.toml
python -m ngimager.pipelines.core examples/configs/phits_usrdef_simple.toml
python -m ngimager.pipelines.core .\examples\configs\phits_usrdef_simple.toml
main ¶
main(cfg_path=typer.Argument(..., help='Path to TOML config file'), fast=typer.Option(False, '--fast', help='Override [run].fast = true (use aggressive fast settings)'), list_mode=typer.Option(False, '--list', help='Override [run].list = true (enable list-mode image output)'), neutrons=typer.Option(None, '--neutrons / --no-neutrons', help='Enable or disable neutron processing; overrides [run].neutrons when set'), gammas=typer.Option(None, '--gammas / --no-gammas', help='Enable or disable gamma processing; overrides [run].gammas when set'), input_path=typer.Option(None, '--input-path', '-i', help='Override [io].input_path from the TOML config.'), output_path=typer.Option(None, '--output-path', '-o', help='Override [io].output_path from the TOML config.'), plot_label=typer.Option(None, '--plot-label', help='Override [run].plot_label (annotation text used in visualization).'))
Run the unified ng-imager pipeline for a single config.
Source code in ngimager/pipelines/core.py
run_pipeline ¶
run_pipeline(cfg_path, *, fast=None, list_mode=None, neutrons=None, gammas=None, input_path=None, output_path=None, plot_label=None)
Orchestrate the full pipeline from a TOML config file.
CLI flags (--fast/--list/--neutrons/--no-neutrons/--gammas/--no-gammas) override the corresponding [run] fields when not None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg_path
|
str
|
Path to TOML configuration file. |
required |
input_path
|
str
|
When provided, overrides [io].input_path from the TOML file. |
None
|
output_path
|
str
|
When provided, overrides [io].output_path from the TOML file. |
None
|
plot_label
|
str
|
When provided, overrides [run].plot_label (used for HDF5 and visualization annotations). |
None
|
Returns:
| Type | Description |
|---|---|
Path to written HDF5 file.
|
|
Source code in ngimager/pipelines/core.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 | |
Physics: hits, events, kinematics, and cones¶
Building blocks that turn detector-level hits into reconstructed event cones.
ngimager.physics.hits¶
Hit-level representations (positions, times, deposited light/energy) and helpers.
Hit
dataclass
¶
Hit(det_id, r, t_ns, L=0.0, type='UNK', material='UNK', sigma_r_cm=None, sigma_t_ns=None, sigma_L=None, extras=dict())
Canonical detector hit (physics layer).
r: position [cm] t_ns: time [ns] L: light-like measure (e.g., Elong) (dimensionless or MeVee-scale per your LUT) type: particle tag for this hit (e.g., "n" for neutron, "g" for gamma, "UNK" if unknown) material: detector material tag (e.g., "M600") extras: arbitrary per-hit fields preserved from input (psd, dE_MeV, raw columns...)
ngimager.physics.events¶
Composite neutron and gamma events built from multiple hits.
GammaEvent
dataclass
¶
Three-interaction gamma event.
As with NeutronEvent, hits can arrive unsequenced; use .ordered() to get a time-ordered copy and .validate() to assert ordering.
ordered ¶
Return a GammaEvent with hits sorted by t_ns (h1 earliest).
If copy=False, reorders self in-place and returns self.
Source code in ngimager/physics/events.py
validate ¶
Raise ValueError if hits are not in (weakly/strictly) increasing time.
Source code in ngimager/physics/events.py
NeutronEvent
dataclass
¶
Two-scatter neutron event.
Hits can be unsequenced when first ingested (e.g. from ROOT/PHITS), so use .ordered() to get a time-ordered event and .validate() to assert the ordering.
ordered ¶
Return a NeutronEvent with hits ordered by t_ns (h1 earliest).
If copy=False, reorders self in-place and returns self.
Source code in ngimager/physics/events.py
validate ¶
Raise ValueError if the hits are not in time order.
Source code in ngimager/physics/events.py
ngimager.physics.kinematics¶
Kinematic relationships for neutrons and gamma rays (e.g. scatter angles, ToF).
compton_incident_energy_from_second_scatter ¶
Incident gamma energy Eg [MeV] from:
- dE1: energy deposited at 1st scatter [MeV]
- dE2: energy deposited at 2nd scatter [MeV]
- theta2: angle between 1->2 and 2->3 baselines [rad]
This mirrors the NOVO primer / legacy implementation:
Eg = dE1 + 0.5 * ( dE2 + sqrt( dE2^2 + 4*dE2*me / (1 - cos(theta2)) ) )
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs are non-physical (negative energies, grazing angles, etc.). |
Source code in ngimager/physics/kinematics.py
compton_theta_from_energies ¶
First Compton scatter angle theta1 [rad] from:
Eg : incident gamma energy [MeV]
Egp : post-first-scatter gamma energy [MeV]
Uses the standard Compton relation:
cos(theta) = 1 + me * (1/Eg - 1/Egp)
Raises:
| Type | Description |
|---|---|
ValueError
|
If energies are non-physical or the argument to arccos is out of [-1, 1]. |
Source code in ngimager/physics/kinematics.py
neutron_theta_from_hits ¶
neutron_theta_from_hits(r1_cm, t1_ns, r2_cm, t2_ns, Edep1_MeV, scatter_nucleus='H', return_En=False)
Full calculation consistent with the NOVO primer: E' via ToF between hits 1->2 (relativistic), E_n = E' + Edep1, theta_lab from COM using A = m_recoil/m_n.
If return_En is False (default), returns theta [rad]. If return_En is True, returns (theta [rad], En [MeV]).
Source code in ngimager/physics/kinematics.py
theta_lab_from_Erecoil_En ¶
Compute neutron lab-frame scattering half-angle [rad] from E_recoil, E_n, and A = m_recoil/m_n. Follows primer equations for theta_CoM then lab mapping.
Source code in ngimager/physics/kinematics.py
tof_energy_relativistic ¶
Relativistic neutron KE E' [MeV] from flight distance s [cm] and time dt [ns].
Source code in ngimager/physics/kinematics.py
ngimager.physics.cones¶
Construction of event cones (vertex, axis, half-angle) from reconstructed events.
build_cone_from_gamma ¶
build_cone_from_gamma(ev, energy_model, plane=None, prior=None, return_meta=False, return_perm=False)
Build a Compton gamma cone from a three-hit GammaEvent.
Behavior without plane/prior (backwards-compatible, PHITS-oriented): - Use ev.ordered() so that h1, h2, h3 are in increasing time, which is physically the true order in PHITS data. - Attempt to build a cone from this ordered triplet using _gamma_cone_from_ordered_hits. - If no physically valid cone exists for this ordering, raise ValueError.
Enhanced behavior when plane is provided:
- Generate all 3! permutations of (h1, h2, h3).
- For each ordering:
* call _gamma_cone_from_ordered_hits(h1, h2, h3),
* discard if it returns None (non-physical),
* discard if the cone axis does not point toward the plane
(t_int <= 0 via _axis_towards_plane),
* compute Δ = |φ − θ| using the configured prior or, if prior is None,
the plane center as an implicit prior.
- Select the candidate with minimal Δ.
- If no candidate survives, fall back to the ordered (time) triplet
as in the simple behavior; if that also fails, raise ValueError.
Return value
- If return_meta and return_perm are both False (default), returns only a Cone.
- If return_meta is True and return_perm is False, returns (cone, Eg_MeV) where Eg_MeV is the incident gamma energy for the selected ordering.
- If return_meta is False and return_perm is True, returns (cone, perm) where perm is a tuple (i0, i1, i2) with indices into the event's time-ordered hit list.
- If both return_meta and return_perm are True, returns (cone, Eg_MeV, perm).
Notes
-
For now, we do not use
energy_modelfor gammas: Hit.L is already the deposited energy in MeV (Edep) from the adapter. -
This function is designed so that callers who do not yet pass a Plane or Prior still get the old, simple behavior.
Source code in ngimager/physics/cones.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | |
build_cone_from_neutron ¶
build_cone_from_neutron(ev, energy_model, plane=None, prior=None, force_proton=False, return_meta=False)
Build a neutron cone using the NOVO imaging primer convention:
- apex O = X1 (first hit position),
- axis D = unit vector along the scattered neutron direction (X2 - X1),
- half-angle θ from elastic n–N kinematics in the lab frame.
Behavior (high level)
-
The event is assumed to be time-ordered (h1 before h2); callers should use ev.ordered() upstream, as the pipeline already does.
-
We always use the full kinematic chain from kinematics.py:
E' = E_n' from ToF between hits 1→2 (relativistic), En = E' + E_dep,1, θ = θ_lab(E_dep,1, En, A) with A = m_recoil / m_n,
where E_dep,1 is obtained from energy_model.first_scatter_energy(...)
and A is set by the assumed recoil nucleus ("H" or "C").
-
If
force_protonis True, or ifplaneis None, we build a single proton-recoil hypothesis and return it (backwards-compatible path). -
Otherwise, we build both proton and carbon hypotheses, reject any that are non-physical, enforce that the cone axis points toward the imaging plane, and then score the survivors against the prior using the same Δ = |φ − θ| metric used for gammas. The winner is the hypothesis with the smallest Δ.
If both hypotheses fail scoring (e.g. degenerate prior geometry), we fall back to the proton-only construction.
Notes
- This function does not mutate the event or record which hypothesis "won"; that bookkeeping is left to callers via the returned recoil_code and En.
Source code in ngimager/physics/cones.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
enumerate_gamma_cone_candidates ¶
Enumerate all physically valid Compton cones for the 3! permutations of a three-hit GammaEvent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ev
|
GammaEvent
|
A GammaEvent with exactly three hits (h1, h2, h3). The event is assumed to be already validated for basic consistency. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
candidates |
list[tuple[Cone, tuple[int, int, int]]]
|
List of (cone, perm) tuples where:
Only permutations that yield a physically valid Compton cone (non-negative energies, sensible angles, non-degenerate geometry) are returned. If no permutation is viable, the list is empty. |
Notes
-
This function is kinematics-only: it does NOT apply any priors or scoring; it simply reports all physically allowed cones.
-
Subsequent stages (e.g. in the pipeline) can:
- apply event- or cone-level filters to the candidates, and
- use spatial/energy priors to select a "best" cone for imaging.
Source code in ngimager/physics/cones.py
ngimager.physics.energy_strategies¶
Strategies for assigning energies to scatters (ELUT, ToF, fixed-energy, etc.).
EnergyFromDeposited ¶
Bases: EnergyStrategy
Treat Hit.L as deposited energy (MeV) directly.
This is intended for synthetic/sim sources like PHITS where Hit.L has already been filled from Edep_MeV in the adapter, so no E(L) inversion or ToF logic is needed.
EnergyFromFixedIncident ¶
Bases: EnergyStrategy
Monoenergetic incident neutron energy (e.g. DT source).
This strategy assumes a fixed incident neutron kinetic energy En. For a given 2-hit neutron event, we:
- Compute the post-scatter neutron energy E' from ToF between h1 and h2.
- Infer the first-scatter deposited energy as Edep1 = En - E'.
- Reject the event if E' >= En (non-physical upscatter).
The returned value is Edep1, which downstream kinematics combine with
E' to reconstruct En again. This keeps the math consistent with
neutron_theta_from_hits while enforcing monoenergetic DT semantics.
Source code in ngimager/physics/energy_strategies.py
EnergyFromToF ¶
Bases: EnergyStrategy
Compute E' from ToF, then E_total = dE + E'.
Source code in ngimager/physics/energy_strategies.py
EnergyStrategy ¶
Base protocol: compute first-scatter energy and optional σ.
first_scatter_energy ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h1
|
Hit
|
First and optional second hits in the event. |
required |
h2
|
Hit
|
First and optional second hits in the event. |
required |
material
|
str
|
Material key (e.g. "OGS", "M600") for LUT-based strategies. |
required |
species
|
Literal['proton', 'carbon'] | None
|
Recoil species key when relevant (e.g. "proton", "carbon"). |
'proton'
|
Returns:
| Name | Type | Description |
|---|---|---|
Edep1_MeV |
float
|
First-scatter deposited energy [MeV] to feed into the kinematics. |
sigma_MeV |
float or None
|
Optional uncertainty estimate on Edep1, or None if not provided. |
Source code in ngimager/physics/energy_strategies.py
ngimager.physics.priors¶
Source and geometry priors used to weight cones and regularize imaging.
Prior ¶
make_prior ¶
Small factory used by pipelines.core; returns a Prior or None.
Expected cfg_prior schema (from TOML, after Pydantic):
[prior] type = "none" | "point" | "line" strength = 1.0
# Point prior: # either: # point = [x, y, z] # or (future) nested [prior.point] can be normalized upstream.
# Line prior (preferred, nested): # [prior.line] # p0 = [x0, y0, z0] # p1 = [x1, y1, z1] # or: # [prior.line] # r0 = [x0, y0, z0] # direction = [dx, dy, dz] # # For backward compatibility we also accept flat: # line_p0 = [x0, y0, z0] # line_p1 = [x1, y1, z1]
Source code in ngimager/physics/priors.py
Geometry & Imaging¶
Geometry primitives and the simple back-projection (SBP) imager.
ngimager.geometry.plane¶
Imaging plane representation and coordinate transforms (u–v basis, etc.).
Plane
dataclass
¶
center ¶
Return the world-space coordinates of the geometric center of the imaging plane grid.
This is defined as the point corresponding to the midpoint in (u, v) coordinates:
u_c = 0.5 * (u_min + u_max)
v_c = 0.5 * (v_min + v_max)
and mapped back to 3D via plane_to_world.
Source code in ngimager/geometry/plane.py
ngimager.imaging.sbp¶
Simple back-projection implementation that projects cones onto an image plane.
cone_to_indices ¶
Unified entry point: cone → flat pixel indices.
engine = "scan": Use matrix-math scanning across rows/columns (continuous arcs). engine = "poly": Use ellipse parameterization when possible, falling back to general ray sampling for non-elliptic conics.
use_jit: When True and numba is available: - "scan" engine uses a JIT-compiled inner loop. - "poly" engine uses a JIT-compiled perimeter sampler. Otherwise, pure-Python paths are used.
Source code in ngimager/imaging/sbp.py
reconstruct_sbp ¶
reconstruct_sbp(cones, plane, list_mode=False, uncertainty_mode='off', workers='auto', chunk_cones='auto', progress=True, n_poly=360, sbp_engine='poly', use_jit=False)
Parallel SBP (analytic conic). If workers==0, runs single-process.
sbp_engine: "poly" – perimeter parametric ellipse (with ray fallback). "scan" – matrix-math scan across pixel-centered lines (continuous arcs).
use_jit: When True and numba is available, use a JIT-compiled inner loop for the "scan" engine to accelerate the row/column solving.
Source code in ngimager/imaging/sbp.py
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 | |
I/O & Configuration¶
Adapters for raw data, list-mode storage, LUT loading, and config handling.
ngimager.io.adapters¶
Adapters that convert external event formats (e.g. ROOT, PHITS-like) into ng-imager hits/events.
ngimager.io.adapters
Modular readers that turn external NOVO data sources (PHITS dumps or experiment/MC ROOT trees) into normalized physics-layer events (ngimager.physics.hits.Hit; ngimager.physics.events.{NeutronEvent,GammaEvent}) for the cone builder.
Design goals
- Keep I/O concerns isolated from physics/kinematics.
- Normalize units on ingest:
- distances -> cm
- times -> ns
- Be tolerant to schema variants by using small, explicit field maps.
- Stream (iterate) large files without loading everything into RAM.
- Remain side-effect free: yield Python objects; HDF5 is handled downstream.
Entry points
- class ROOTAdapter: reads NOVO ROOT trees ("novo_ddaq" or "hvl_geant4" styles).
- class PHITSAdapter: reads tabular PHITS lists (CSV/Parquet/HDF5).
- function make_adapter(cfg): factory from the [io.adapter] TOML section.
Config (example)
[io] input = "data/run42.root"
[io.adapter] type = "root" # "root" | "phits" style = "novo_ddaq" # ROOT styles: "novo_ddaq" | "hvl_geant4" unit_pos_is_mm = true time_units = "ns" # "ns" | "ps" require_gamma_triples = false # keep filtering in pipeline by default default_material = "M600" # tag assigned to all hits unless mapped
BaseAdapter ¶
Abstract adapter interface.
Yields physics-layer events normalized to cm/ns (and L if present).
iter_events ¶
Yield fully-typed physics events (NeutronEvent / GammaEvent, etc.) ready for cone building.
iter_raw_events ¶
Yield 'raw' events as collections of canonical Hit objects.
Semantics: - Each yielded item represents a single raw coincidence window. - For PHITS usrdef, this is a dict with at least: { "event_type": "n" | "g" | ..., "hits": [Hit, Hit, ...], ... (bookkeeping fields) } - Other adapters may choose a different raw representation, but must include a 'hits' field with a sequence of Hit objects.
Source code in ngimager/io/adapters.py
PHITSAdapter ¶
Bases: BaseAdapter
Read tabular event lists exported from PHITS post-processing.
Supported inputs: CSV (.csv), Parquet (.parquet/.pq), HDF (.h5/.hdf5).
The adapter expects row-wise events. Each row is either a neutron double or a gamma triple.
Canonical field names (columns): - x1,y1,z1,t1 ; x2,y2,z2,t2 ; [x3,y3,z3,t3] - det1,det2,[det3] ; L1,L2,[L3] (or elong1,elong2,[elong3]) - type (optional) values: 'n'|'g' ; if absent we infer by presence of 3rd hit
Units are assumed mm (pos) and ns (time) unless overridden.
Source code in ngimager/io/adapters.py
iter_events ¶
Unified iterator: - If 'path' ends with .out (PHITS usrdef, ragged): parse→Hit→shape→typed and yield typed events. - Otherwise (CSV/Parquet/HDF): fall back to the existing table-based row iterator.
Source code in ngimager/io/adapters.py
iter_raw_events ¶
Yield PHITS 'raw' events as dicts whose 'hits' entry is a list of canonical Hit objects.
For usrdef .out files this wraps from_phits_usrdef, which:
- parses the ragged usrdef text,
- canonicalizes hit fields to x_cm / y_cm / z_cm / t_ns / Edep_MeV / L,
- and converts each hit dict into a physics.hits.Hit, resolving the
material via this adapter's MaterialResolver.
For table-like PHITS exports (CSV/Parquet/HDF5) we currently don't have a native raw-event representation, so we conservatively reconstruct a minimal raw event around each typed event.
Source code in ngimager/io/adapters.py
RootNovoDdaqAdapter
dataclass
¶
RootNovoDdaqAdapter(tree_key='image_tree', unit_pos_is_mm=True, time_units='ns', default_material='UNK', material_map=None, require_gamma_triples=False, meta_tree_key='meta')
Bases: BaseAdapter
Adapter for NOVO DDAQ ROOT files ("image_tree" + optional "meta" tree).
This adapter:
- reads the main coincidence tree (image_tree) and yields raw events
with canonicalized hits, and
- can optionally read the run-level metadata tree (meta) via
read_meta_tree for passthrough into HDF5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree_key
|
str
|
Name of the ROOT TTree containing the imaging events (default: "image_tree"). |
'image_tree'
|
unit_pos_is_mm
|
bool
|
If True, hit positions are stored in mm and converted to cm. |
True
|
time_units
|
('ns', 'ps')
|
Units of the time branches (converted to ns). |
"ns"
|
default_material
|
str
|
Material tag to use when no mapping is provided. |
'UNK'
|
material_map
|
dict[int, str] or None
|
Mapping from det_id to material name. |
None
|
require_gamma_triples
|
bool
|
If True, drop gamma events that do not have exactly 3 hits. |
False
|
meta_tree_key
|
str or None
|
Name of the metadata TTree (default "meta"). If None, metadata extraction is disabled. |
'meta'
|
iter_events ¶
Placeholder: higher-level event shaping for NOVO DDAQ ROOT data.
For now, the ng-imager pipeline should consume iter_raw_events
and run the standard shaping / filtering stack on top. This method
is defined only to satisfy the BaseAdapter interface.
Source code in ngimager/io/adapters.py
iter_raw_events ¶
Yield raw coincidence windows as dicts:
{
"hits": [Hit, ...],
"multi": int, # as stored in the ROOT tree, if present
"entry": int, # global entry index
"source": "ROOT_NOVO_DDAQ",
}
This method is intentionally conservative and does not make any physics decisions about which hits belong to neutron vs gamma events; it simply exposes the coincidence window.
Source code in ngimager/io/adapters.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
read_meta_tree ¶
Read the NOVO 'meta' TTree (if present) and return a flat dict mapping branch names → Python scalars/strings.
This is intended for run-level metadata passthrough into HDF5. Returns None if no compatible meta tree is found.
Source code in ngimager/io/adapters.py
from_phits_usrdef ¶
Public convenience entry point for PHITS usrdef ingestion. Currently supports the 'short' format. 'auto' is reserved for future sniffing.
Source code in ngimager/io/adapters.py
make_adapter ¶
Create an adapter from a config dict (from TOML/CLI).
Expected keys under [io.adapter]: type: "root" | "phits" style: "novo_ddaq" | "hvl_geant4" (ROOT-only) unit_pos_is_mm: bool time_units: "ns" | "ps" require_gamma_triples: bool (ROOT-only) default_material: str
Source code in ngimager/io/adapters.py
parse_phits_usrdef_short ¶
Parse PHITS 'usrdef.out' short format into variable-multiplicity events. The [T-Userdefined] source code for this tally and documentation can be found at: https://github.com/Lindt8/T-Userdefined/tree/main/multi-coincidence_ng
Input row format (tokens; delimiters ';' and ',' are cosmetic): event_type #iomp #batch #history #no #name ; reg Edep(MeV) x(cm) y(cm) z(cm) t(ns) , reg Edep x y z t , ...
Where: - event_type: 'ne' (neutron) or 'ge' (gamma) - #iomp, #batch, #history, #no, #name: integers (PHITS bookkeeping) - For each hit: reg (int), Edep_MeV (float), x_cm (float), y_cm (float), z_cm (float), t_ns (float) - 2 hits min for 'ne', 3 hits min for 'ge', but higher multiplicities may appear.
Returns a list of dicts, each with: { "event_type": "n" | "g", "iomp": int, "batch": int, "history": int, "no": int, "name": int, "hits": [ {"reg": int, "Edep_MeV": float, "x_cm": float, "y_cm": float, "z_cm": float, "t_ns": float}, ... ], "source": "PHITS", "format": "usrdef.short", }
NOTE: This function performs no physics decisions (pair/triple selection, species mixing, etc.). It preserves all hits in the order they appear. Shaping happens downstream.
Source code in ngimager/io/adapters.py
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
ngimager.io.lm_store¶
List-mode HDF5 storage layout and helpers for reading/writing cone datasets.
write_cones ¶
write_cones(f, cone_ids, apex_xyz_cm, axis_xyz, theta_rad, species, recoil_code, incident_energy_MeV, event_index, gamma_hit_order=None)
Store per-cone geometric and classification parameters under /cones.
Layout: /cones/cone_id : [N] uint32 /cones/apex_xyz_cm : [N,3] float32 /cones/axis_xyz : [N,3] float32 /cones/theta_rad : [N] float32 /cones/species : [N] uint8 (0=neutron, 1=gamma) /cones/recoil_code : [N] uint8 (0=NA, 1=proton, 2=carbon) /cones/incident_energy_MeV : [N] float32 (En for n, Eg for g) /cones/event_index : [N] int32 (row index into /lm/event_* arrays) /cones/gamma_hit_order : [N,3] int8 (optional; see below)
/cones/species_labels : ["0=neutron", "1=gamma"] /cones/recoil_code_labels : ["0=NA", "1=proton", "2=carbon"]
Notes
- For gamma cones (species == 1), gamma_hit_order[i] = (i0, i1, i2) gives the indices into /lm/hit_*[event_index[i], :, :] that correspond to (first scatter, second scatter, third point) used to build that cone.
- For neutron cones (species == 0), gamma_hit_order[i] is (-1, -1, -1) and should be ignored.
Source code in ngimager/io/lm_store.py
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 | |
write_counters ¶
Store scalar counters under /meta/counters as attributes.
Each key in counters becomes an attribute on the /meta/counters group,
prefixed with a stage number:
S1_... → Stage 1 (raw events → hits)
S2_... → Stage 2 (hits → shaped/typed → event filters)
S3_... → Stage 3 (events → cones → cone filters)
S4_... → Stage 4 (cones → images)
This forces a "chronological" ordering when viewed in tools like HDFView (which sort attributes alphabetically).
Source code in ngimager/io/lm_store.py
write_event_cone_survival ¶
Store per-event survival information linking events → cones.
Layout (all under /lm):
/lm/event_cone_id : [N_events] int32 For each event row i (as in /lm/event_type, /lm/hit_*): - cone_id of the cone built from this event, or -1 if no cone.
/lm/event_imaged_cone_id : [N_events] int32 For each event row i: - cone_id of the cone that both exists AND hits the imaging plane (has non-empty pixel set), or -1 if none.
Notes
- event index i is simply the row index into /lm/event_type, /lm/hit_*.
- event_imaged_cone_id is only meaningfully populated when [run].list = true; for non-list runs it will typically be all -1.
Source code in ngimager/io/lm_store.py
write_events_hits ¶
Store per-event and per-hit data for list-mode analysis.
Layout (all under /lm):
/lm/materials/labels : [M] array of material strings /lm/event_type : [N] uint8, 0=n, 1=g /lm/event_meta_run_id : [N] int32 (optional meta) /lm/event_meta_file_ix : [N] int32 (optional meta) /lm/hit_pos_cm : [N,3,3] float32 (event, hit_index, xyz) /lm/hit_t_ns : [N,3] float64 /lm/hit_L_mevee : [N,3] float32 /lm/hit_det_id : [N,3] int32 /lm/hit_material_id : [N,3] int16
Convention: - Neutron events use hits [0,1] and leave slot 2 as NaN/-1. - Gamma events use hits [0,1,2].
Source code in ngimager/io/lm_store.py
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 | |
write_lm_indices ¶
Store list-mode indices mapping cones -> (u,v) pixels.
We store: /lm/cone_pixel_indices : ragged array of (cone_id, flat_index) pairs
where: - cone_id is the index into /cones/cone_id - flat_index is the flattened pixel index (row-major) on the imaging plane.
Source code in ngimager/io/lm_store.py
write_lm_ragged ¶
Write variable-length list-mode (ragged) datasets for events with arbitrary hit multiplicity. This is ADDITIVE and does not modify existing fixed-shape datasets you already write elsewhere.
Source code in ngimager/io/lm_store.py
write_projections ¶
Write 1D u/v projections (and optional ROI-limited projections) to HDF5, and optionally compute/write metrics.
Layout under /images/summed/projections/{species}:
u : [nu] float32, sum over v (rows)
v : [nv] float32, sum over u (cols)
u_roi : [nu] float32, ROI-limited u projection (zeros outside ROI)
v_roi : [nv] float32, ROI-limited v projection (zeros outside ROI)
Metrics layout (per species):
metrics/u : scalar metrics for the "all" u-projection
metrics/v : scalar metrics for the "all" v-projection
metrics/u_roi : scalar metrics for the ROI u-projection (if ROI defined)
metrics/v_roi : scalar metrics for the ROI v-projection (if ROI defined)
Each metrics group contains 0D datasets such as:
total_counts
mean_cm, median_cm, std_cm
peak_pos_cm, peak_value
edge_low_cm, edge_high_cm, edge_width_cm
summary_ok, peak_ok, edges_ok
The imaging plane grid (u_min/u_max/v_min/v_max/du/dv) is read from /meta.attrs as written by write_init().
Source code in ngimager/io/lm_store.py
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
write_root_novo_meta ¶
Persist NOVO DDAQ ROOT run-level metadata into HDF5 under /meta/root_novo_ddaq.
The input 'meta' is expected to be a flat mapping from branch names in the ROOT 'meta' TTree to Python scalars/strings, as returned by RootNovoDdaqAdapter.read_meta_tree().
Layout
/meta/root_novo_ddaq : group attrs: InputFileName, OutputFileName, CDFFileName, PSDCutsFileName SampleRate, NumDet, NumThreads, WriteHistograms, MergeMode, CardOffsetChannel, UsePositionVeto
/meta/root_novo_ddaq/detectors
det_id : [NumDet] int32
pos : [NumDet, 3] float32 (PosX, PosY, PosZ) [mm]
dim : [NumDet, 3] float32 (DimX, DimY, DimZ) [mm]
rot_deg : [NumDet, 3] float32 (RotX, RotY, RotZ) [deg]
local_time_offset : [NumDet] float32 [ns]
global_time_offset: [NumDet] float32 [ns]
pos_cal_file : [NumDet] string
energy_cal_file : [NumDet] string
is_start_det : [NumDet] int8
is_laser_det : [NumDet] int8
Source code in ngimager/io/lm_store.py
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 | |
write_summed ¶
Write summed image for a given species.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
open h5py.File
|
|
required |
species
|
"n" | "g" | "all" (string key)
|
|
required |
img
|
2D numpy array (nv, nu), float or int
|
|
required |
Source code in ngimager/io/lm_store.py
ngimager.io.lut¶
Loading and interpolating light-response lookup tables (LUTs) for scintillators.
build_lut_registry ¶
Build a registry mapping material -> species -> LUT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lut_paths
|
Dict[str, Dict[str, str]] | None
|
Configuration-style mapping, e.g.: Paths may be relative; they are resolved against When a material/species is omitted entirely from |
required |
base_dir
|
str | Path | None
|
Base directory for resolving relative paths (typically the directory containing the TOML config). If None, uses the current working directory. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Nested dictionary: {material: {species: LUT, ...}, ...} |
Source code in ngimager/io/lut.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
builtin_lut_path ¶
Return path to a built-in LUT .npz for given material/species.
Source code in ngimager/io/lut.py
ngimager.config.schemas¶
Pydantic schemas that define the TOML configuration structure.
ConeSpeciesOverrides ¶
Bases: BaseModel
Species-specific overrides for cone-level filters.
ConesFiltersCfg ¶
Bases: BaseModel
Cone-level filters with universal defaults plus neutron/gamma overrides.
TOML:
[filters.cones] max_delta_theta_deg = 5.0
[filters.cones.neutron] max_delta_theta_deg = 3.0
[filters.cones.gamma] max_delta_theta_deg = 8.0
Config ¶
Bases: BaseModel
Top-level TOML configuration.
DetectorFrameGeometry ¶
Bases: BaseModel
A simple rigid transform that maps detector-local coordinates to world coordinates:
p_world = R_xyz(rotation_deg) @ p_local + origin_cm
where rotation_deg = [rx, ry, rz] are Euler angles in degrees, applied in the fixed order Rx → Ry → Rz.
DetectorsCfg ¶
Bases: BaseModel
Mapping from detector IDs/regions to materials and optional geometry.
TOML:
[detectors] default_material = "OGS"
[detectors.material_map] 200 = "OGS" 210 = "M600" ...
Optional global detector-frame → world-frame transform:¶
[detectors.geometry.frame] origin_cm = [0.0, 0.0, 0.0] rotation_deg = [0.0, 0.0, 0.0]
OPTIONAL (stub for future expansion): per-detector transforms¶
[[detectors.geometry.detectors]] id = 0 origin_cm = [0.0, 0.0, 0.0] rotation_deg = [0.0, 0.0, 0.0]
DetectorsGeometryCfg ¶
Bases: BaseModel
Global detector-array geometry.
- 'frame' describes the overall detector coordinate frame relative to world coordinates.
- 'detectors' is an optional list for fine-grained per-detector transforms (currently unused, but reserved for future support).
EnergyCfg ¶
Bases: BaseModel
Energy strategy configuration.
strategy: "ELUT" – invert light via E(L) LUTs (per-material, per-species) "ToF" – simple ToF-based estimate (placeholder) "FixedEn" – fixed incident neutron energy (e.g. 14.1 MeV source) "Edep" – direct deposited energy (PHITS-style adapters)
EventSpeciesOverrides ¶
Bases: BaseModel
Species-specific overrides for event-level filters.
All fields are optional; when None, the universal [filters.events] value is used for ToF, and L-thresholds default to "no extra cut".
EventsFiltersCfg ¶
Bases: BaseModel
Event-level filters with universal defaults plus neutron/gamma overrides.
TOML:
[filters.events] tof_window_ns = [0.0, 30.0]
[filters.events.neutron] tof_window_ns = [0.0, 30.0] min_L1_MeVee = 0.0 min_L2_MeVee = 0.0
[filters.events.gamma] tof_window_ns = [0.0, 30.0] min_L_any_MeVee = 0.0
FastCfg ¶
Bases: BaseModel
Fast-mode override knobs.
Applied only when [run].fast = true; otherwise ignored.
FiltersCfg ¶
Bases: BaseModel
Top-level filter configuration, split into hits / events / cones.
HitSpeciesOverrides ¶
Bases: BaseModel
Species-specific overrides for hit-level filters.
All fields are optional; when None, the universal [filters.hits] value is used.
HitsFiltersCfg ¶
Bases: BaseModel
Hit-level filters with universal defaults plus neutron/gamma overrides.
TOML:
[filters.hits] min_light_MeVee = 50.0 max_light_MeVee = 1.0e6 psd_min = 0.0 psd_max = 1.0 bars_include = [] bars_exclude = [] materials_include = [] materials_exclude = []
[filters.hits.neutron] min_light_MeVee = 100.0 # optional override; others fall back to [filters.hits] psd_min = 0.2 # optional override; if omitted, uses [filters.hits] psd_max = 0.6
[filters.hits.gamma] # optional overrides...
IOCfg ¶
Bases: BaseModel
I/O paths and high-level source description.
TOML:
[io] input_path = "..." input_format = "phits_usrdef" # "phits_usrdef" | "root_novo_ddaq" | "hdf5_ngimager" output_path = "..."
PerDetectorGeometry ¶
Bases: BaseModel
OPTIONAL (stub for future expansion).
Describes an individual detector tile or module's placement within the detector-frame coordinate system. For now, ng-imager does not apply per-detector transforms, but the schema entry is accepted and stored for future expansion.
PipelineCfg ¶
Bases: BaseModel
Controls how far through the pipeline we run.
until = "hits" | "events" | "cones" | "image"
ProjectionAxisMetricsCfg ¶
Bases: BaseModel
Per-axis projection metrics controls.
These are applied separately for the u and v axes.
ProjectionMetricsCfg ¶
Bases: BaseModel
Controls whether projection metrics are computed and written to HDF5.
ProjectionPlotCfg ¶
Bases: BaseModel
Controls how projection metrics are visualized in vis/hdf.py.
(Plotting code will read these; they do not affect HDF5 contents.)
TOML example:
[vis.projections.plot]
# Basic visual toggles
show_peak_markers = true # vertical / horizontal lines at peak_pos_cm
show_edge_markers = true # lines at edge_low_cm / edge_high_cm
show_centroid_2d = false # crosshair at 2D centroid (if computed)
# Which metrics to use when both "all" and ROI curves exist
metrics_source = "auto" # "auto" | "all" | "roi" | "both"
curve_mode = "all+roi" # "all+roi" | "all_only" | "roi_only"
# Numeric summaries on the figure
# - "off" : no text annotations
# - "compact" : minimal one-line summary per axis
# - "full" : include more fields (e.g. edges) when available
annotate_summary = "compact"
# Optional extra panel with a table of metrics (future)
show_metrics_panel = false
RunCfg ¶
Bases: BaseModel
Global run controls that apply to the entire pipeline.
source_type: "cf252" | "dt" | "proton_center" | "phits" fast: Enable fast-mode overrides (see FastCfg and [fast] section). list: Enable list-mode imaging output (/lm/cone_pixel_indices, etc.).
VisCfg ¶
Bases: BaseModel
Visualization configuration.
These options control automatic image export from the pipeline and provide
defaults for the standalone ng-viz CLI.
VisProjectionsCfg ¶
Bases: BaseModel
Configuration for 1D projections and their analysis/visualization.
TOML:
[vis.projections]
enabled = true
roi_u_min_cm = -5.0
roi_u_max_cm = 5.0
roi_v_min_cm = -5.0
roi_v_max_cm = 5.0
[vis.projections.metrics]
enabled = true
[vis.projections.metrics.u]
compute_summary = true
compute_peak = true
compute_edges = false
edge_low_frac = 0.2
edge_high_frac = 0.8
min_counts = 100.0
[vis.projections.metrics.v]
compute_summary = true
compute_peak = true
compute_edges = true
[vis.projections.plot]
show_peak_markers = true
show_edge_markers = true
show_centroid_2d = false
metrics_source = "auto" # "auto" | "all" | "roi" | "both"
curve_mode = "all+roi" # "all+roi" | "all_only" | "roi_only"
annotate_summary = "compact" # "off" | "compact" | "full"
show_metrics_panel = false
roi_bounds_cm ¶
Return (u_min, u_max, v_min, v_max) in cm if a full ROI is defined, otherwise None.
Source code in ngimager/config/schemas.py
ngimager.config.load¶
User-facing helpers for loading and validating configuration from TOML files.
load_config ¶
Load a TOML config file into a Config object.
All paths inside the [io] table are interpreted relative to the location of the TOML file (cfg_dir), except when they are absolute.
In particular: - [io].input_path - [io].output_path - [io].restart_path - [io.extra_text_files].*
CLI overrides (e.g. --input-path/--output-path in ng-run) are applied later and remain relative to the current working directory.
Source code in ngimager/config/load.py
CLI & Visualization¶
Command-line entry point and basic visualization utilities.
ngimager.cli.viz¶
The ng-viz CLI application: entry point for visualizing ng-imager HDF5 outputs.
summed ¶
summed(h5_path=typer.Argument(..., help='Path to ng-imager HDF5 file (must contain /images/summed/*).'), species=typer.Option(['n', 'g', 'all'], '--species', '-s', help="Which images to render from /images/summed: any of 'n', 'g', 'all'."), center_on_plane_center=typer.Option(True, '--center-on-plane-center/--no-center-on-plane-center', help='Center axes on the imaging plane center.'), flip_vertical=typer.Option(True, '--flip-vertical/--no-flip-vertical', help='Flip the plotted image vertically (mainly for legacy comparison).'), axis_units=typer.Option('cm', '--axis-units', help="Axis units for plotting: 'cm' or 'mm'."), cmap=typer.Option('cividis', '--cmap', help="Matplotlib colormap to use (e.g. 'cividis', 'viridis')."), filename_pattern=typer.Option('{species}_{stem}.{ext}', '--filename-pattern', help='Python format string for output filenames; may use {stem}, {species}, {ext}.'), fmt=typer.Option(['png'], '--format', '-f', help="Output format(s) to write (e.g. 'png', 'pdf')."), plot_label=typer.Option(None, '--plot-label', help='Override run plot label annotation (defaults to any value stored under /meta.run_plot_label in the HDF5 file).'))
Render one or more /images/summed/{n,g,all} datasets to image files.
Source code in ngimager/cli/viz.py
ngimager.vis.hdf¶
Convenience functions for visualizing images stored in HDF5 output files.
render_summed_images ¶
render_summed_images(h5_path, species=('n', 'g', 'all'), filename_pattern='{species}_{stem}.{ext}', center_on_plane_center=True, flip_vertical=True, axis_units='cm', cmap='cividis', formats=('png',), projections=False, roi_u_min_cm=None, roi_u_max_cm=None, roi_v_min_cm=None, roi_v_max_cm=None, plot_label=None, metrics_source='auto', curve_mode='all+roi', annotate_summary='compact', show_metrics_panel=False, show_peak_markers=True, show_edge_markers=True, show_centroid_2d=False)
Render /images/summed/* datasets from an ng-imager HDF5 file to image files.
When projections=True, each figure shows:
- the main 2D image (u vs v),
- a 1D projection along u above the image,
- a 1D projection along v to the left of the image,
- an optional ROI rectangle (if roi_*_cm are provided),
- an annotation of the number of cones contributing to that species.
- and (when available) a run-level plot label drawn from [run].plot_label
or from the plot_label argument.
Source code in ngimager/vis/hdf.py
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 | |
Simulation & Tools¶
Developer utilities and LUT tools.
ngimager.tools.bundle_repo¶
Utility for snapshotting the repository (e.g. for embedding into an HDF5 file).
bundle_repo.py — produce a single-file text bundle of your repo.
Usage: python src/ngimager/tools/bundle_repo.py . -o repo_bundle.txt
What it does: - Writes a directory tree. - For each text file, writes a header with path/size/sha256 and the content. - Skips binaries and large files (configurable). - Skips typical junk dirs (.git, pycache, build artifacts).
build_tree ¶
Return a simple text tree of the repo.
Source code in ngimager/tools/bundle_repo.py
get_git_commit ¶
Best-effort retrieval of the current Git commit SHA for the repo root.
Returns a full 40-character SHA string if available, otherwise None. This is intentionally non-fatal: if the repo is not a Git checkout, or git is not installed, or anything else goes wrong, we just return None.
Source code in ngimager/tools/bundle_repo.py
is_textlike ¶
Heuristic to decide if a file is text-like.
Source code in ngimager/tools/bundle_repo.py
walk_repo ¶
Yield all files under root, skipping DEFAULT_EXCLUDE_DIRS.
Source code in ngimager/tools/bundle_repo.py
Light-response LUT tools¶
The ngimager.tools.generate_lut module contains functions for building, fitting, and using light-response lookup tables (LUTs) for NOVO scintillators.
NOVO_light_response_functions ¶
Created by Hunter N. Ratliff, 2025-10-17 This code generates light response functions/lookup-tables (LUTs), forward and inverse, for NOVO's M600 and OGS scintillators using my SRIM calculations as a basis for a Birks function fit whose parameters are optimized for proton light response data collected in NOVO's March 2024 PTB experiments.
==============================================================================¶
Light-Response Fitting and LUT Generation — Explainer¶
==============================================================================¶
This script builds physics-based light-response models for plastic scintillators and exports fast lookup tables (LUTs) to convert measured light output (MeVee) into recoil energy (MeV). It supports both proton and carbon recoils and produces figures for fit quality and inverse-response uncertainty bands.
What the script does (high level)¶
1) Loads stopping power data (SRIM) for protons and carbon and converts to linear stopping power using the scintillator density. 2) Loads experimental calibration data from PTB that map proton recoil energy to measured light output. 3) Fits a Birks-type light-yield model (Birks or Birks–Chou) to the calibration data. 4) Optionally constrains S to 1 using gamma Compton-edge calibration (MeVee scale). 5) Builds dense forward and inverse LUTs: - Forward: E -> L(E) - Inverse: L -> E(L), uniform grid in L for fast np.interp 6) Computes 68 percent confidence bands on E(L) by sampling the fitted parameters and propagating to inverse LUTs. 7) Exports portable artifacts (NPZ, CSV, JSON metadata) and generates plots.
Inputs¶
- SRIM stopping power files for H and C ions for each scintillator:
- Must include energy (MeV) and mass stopping power (MeV cm^2 / g).
- Energy range ideally covers 1 keV to at least 100–250 MeV.
- Scintillator density rho (g/cm^3) for each material.
- Experimental proton light-response calibration:
- Arrays of Ep_MeV (proton recoil energies) and L_MeVee (measured light output).
- Optional grouping labels for different neutron energies (En_indices, En_strs) to visualize subsets.
- Gamma Compton calibration (performed upstream):
- Data acquisition already outputs MeVee. This allows S to be fixed to 1 or softly constrained near 1.
Outputs¶
For each scintillator and species (proton, carbon):
- NPZ file: basepath.npz
- Arrays: L_inv (MeVee), E_inv (MeV)
- Optional arrays: E_inv_lo, E_inv_hi (16th and 84th percentile inverse bands)
- Metadata object with model, parameters, density, fit stats, grid sizes, timestamp
- CSV file: basepath.csv
- Two columns: L_inv_MeVee, E_inv_MeV (plaintext for sharing and longevity)
- JSON metadata: basepath.meta.json
- Human-readable metadata mirror of the NPZ meta
- Plots (if enabled):
- Birks fit and residuals (stacked) per scintillator
- Inverse response E(L) with 68 percent bands for proton and carbon
- Zoomed carbon inverse plot
Methods and process¶
1) Units and data prep - Convert mass stopping power to linear: dE/dx [MeV/cm] = rho * (dE/dx)_mass [MeV cm^2 / g]. - Interpolate dE/dx(E) with a monotone, nonnegative interpolant (shape-preserving cubic, or safe wrapper).
2) Light-response model - Birks: dL/dx = S * (dE/dx) / (1 + kB * dE/dx) - Birks–Chou (optional): dL/dx = S * (dE/dx) / (1 + kB * dE/dx + C * (dE/dx)^2) - Total light for a recoil of energy E is the integral of dL/dE over energy. Numerically integrate over a dense E grid.
3) Parameter fitting - Nonlinear least squares (scipy.optimize.least_squares) on residuals L_model(Ei) - L_data,i. - Residual variance scaling: covariance = sigma^2 * (J^T J)^-1 with sigma^2 = SSE / (N - p). - Report best-fit parameters, 1 sigma uncertainties, R^2, adjusted R^2, RMSE.
4) Handling S (electron-equivalent scale) - If data are already in MeVee via Compton-edge calibration, fix S = 1 (hard) or apply a soft Gaussian prior on S near 1 (e.g., sigma 0.01–0.02). - This removes S–kB degeneracy and stabilizes extrapolation.
5) Building LUTs - Forward: compute L(E) on a dense E grid (e.g., up to 250 MeV). - Inverse: create a uniformly spaced L grid and tabulate E(L) with np.interp. - Save proton and carbon inverse LUTs separately. Use float32 for compact storage and fast lookup.
6) Uncertainty bands (optional) - Draw samples of [S, kB, C] from the multivariate normal defined by the fitted covariance. - For each sample, compute inverse E(L) onto the fixed L grid. - Take the 16th and 84th percentiles across samples at each L to form a 68 percent confidence band. - Store E_inv_lo and E_inv_hi alongside the central inverse LUT.
7) Plotting (optional) - Fit-quality figure: top panel shows data and model L(E); bottom panel shows percent residuals. - Inverse figure: E(L) central curve with 68 percent band for proton and carbon. - Carbon often appears highly quenched; use a zoomed L range (e.g., L < 8 MeVee) or annotate unreachable regions using elastic kinematic caps.
How to use the LUTs downstream¶
- Load NPZ: L_inv, E_inv. Convert MeVee to recoil energy with Ep = np.interp(L_meas, L_inv, E_inv). Fast example drop-in code:
- If uncertainty bands were exported: compute Ep_lo and Ep_hi via the same interpolation on E_inv_lo and E_inv_hi.
- Use proton and carbon LUTs in parallel and let imaging logic choose between hypotheses or carry both with weights.
- Optional: clip carbon solutions using an elastic kinematic ceiling given a neutron energy bound.
Configuration knobs¶
- Model selection: use_Chou_C_term boolean to include the C term.
- S handling: lock S exactly to 1 via lock_S_to_1 = True or via bounds, or set a soft prior on S with prior_sigma.
- Grids: E_max, nE for forward integration; nL for inverse grid density.
- Band sampling: number of parameter draws, sample filtering for monotonicity and stability.
Assumptions and caveats¶
- Electron-equivalent calibration is already applied upstream; therefore S should be 1 or tightly constrained near 1.
- The carbon LUT is more uncertain in practice without carbon-tagged calibration; use it as a conservative branch and apply kinematic caps where appropriate.
- Extrapolation beyond the calibration Ep range is supported but rely on the band to communicate model uncertainty.
- Monotonicity is required for E(L) inversion; pathological parameter draws are rejected.
Troubleshooting¶
- Inverse interpolation error (requires at least two unique L points): occurs if a sampled parameter set produces nearly flat L(E). The sampler filters such draws; increase sample count or tighten priors if too many draws are rejected.
- Large parameter uncertainties under Birks–Chou: usually indicates kB and C are highly correlated and C is weakly identifiable; prefer simple Birks unless low-energy data demand C.
- Odd high-L divergence between Birks and Chou: typically due to unconstrained S; fix S via Compton calibration.
Dependencies¶
- numpy, scipy, matplotlib
- Hunters_tools (https://github.com/Lindt8/Hunters-tools/blob/master/Hunters_tools.py) module import (used for plotting)
- No runtime dependency on scipy in downstream imaging if you use saved L_inv and E_inv with np.interp.
Files written (per scintillator and species)¶
- basepath.npz: L_inv, E_inv, and optional E_inv_lo, E_inv_hi, plus metadata.
- basepath.csv: plaintext columns L_inv_MeVee, E_inv_MeV.
- basepath.meta.json: metadata (scintillator, species, model, parameters, density, fit stats, grid sizes, timestamp).
- Figures: fit and inverse-band plots if saving is enabled.
This design yields a transparent, physics-backed model with fast and portable inverse LUTs for experimental imaging.
Birks_params
module-attribute
¶
Birks_params = {'M600': {'S': 1.0, 'kB': 14.4, 'kB_linear': 14.4 * 0.001 / density['M600'], 'C': 0, 'C_linear': 0}, 'OGS': {'S': 0.83, 'kB': 5.5, 'kB_linear': 5.5 * 0.001 / density['OGS'], 'C': 0, 'C_linear': 0}}
As a note, these files are those directly produced by SRIM. The "SRIM_*.dat" files Joey used have column 1 units of MeV and column 2 units of keV / (mg/cm^2) (or, equivalently, MeV / (g/cm^2)).
read_SRIM_output ¶
Parses a SRIM output file, returning a dictionary object with particle energies in MeV and mass stopping powers in MeV / (g/cm^2).
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
read_light_response_file ¶
This function is for reading Joey's two-column light response data points files "LightOutput_*.dat". Column 1 is the recoil proton energy Ep / neutron energy lost dEn in MeV, and Column 2 is the light response in MeVee It returns a dictionary object where the Ep and L pairs are proerly ordered, ascending by Ep Blank lines delimit values taken from different source neutron energies
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
pm_fmt ¶
Format 'val ± err' preserving significant digits, handling very small numbers (e.g., 0.00301 ± 0.00012).
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
light_integral_grid ¶
Returns L(E) tabulated on E_grid using cumulative trapezoid integration of dL/dE. dL/dE = S / (1 + kBdEdx + CdEdx^2)
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
make_forward_inverse_LUT ¶
Build dense forward LUT (E->L) and inverse (L->E) interpolants. nE large => smooth & accurate integrals + inversion.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
fit_birks_params ¶
fit_birks_params(E_data, L_data, dedx_func, init=(1.0, 0.01, 0.0), use_C=False, bounds=((0, 0, 0), (np.inf, np.inf, np.inf)), prior_S=None, prior_sigma=None)
Fit (S, kB [, C]) by minimizing residuals on L(E). E_data in MeV (proton energy), L_data in MeVee. init: (S, kB[, C]) - use Joey's numbers as initial values bounds: ((Smin, kBmin, Cmin), (Smax, kBmax, Cmax))
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | |
make_inverse_sampler ¶
Build many inverse interpolants E(L) for uncertainty bands. Returns a list of callables E_of_L_samplers.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
inverse_with_bands ¶
For each L, return median and central 68% interval of E across samplers.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
compute_inverse_band ¶
Build 68% (16/84) percentile inverse E(L) on a fixed L grid (L_inv_ref) by sampling Birks params. Returns (E_inv_lo, E_inv_hi, E_inv_med). Any pathological samples (non-monotone L(E)) are skipped.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
accumulate_light_from_steps ¶
steps: iterable of dicts with keys {'dE', 'E_mid'} for a given recoil track returns total light for that track
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
build_inverse_L_grid ¶
Make a uniformly spaced grid in L (monotone), then tabulate E(L) with np.interp.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
save_lut_npz_csv ¶
Saves: - basepath + ".npz" (binary, fast) - basepath + ".csv" (plaintext, two columns: L_inv,E_inv) - basepath + ".meta.json" (small JSON metadata, human-readable)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
basepath
|
str | Path
|
Path without extension (e.g., Path("results/lut_M600_proton")). The function appends .npz, .csv, and .meta.json automatically. |
required |
L_inv
|
array - like
|
Inverse lookup arrays: L_inv (MeVee) and E_inv (MeV). |
required |
E_inv
|
array - like
|
Inverse lookup arrays: L_inv (MeVee) and E_inv (MeV). |
required |
meta
|
dict
|
Metadata dictionary describing the LUT contents. |
required |
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
Appendix: Full API Surface (Auto-Generated)¶
The following recursively lists all modules and submodules under the ngimager package.
Top-level package for ng-imager (ngimager).
The public user-facing entry points are:
- ngimager.pipelines.core.run_pipeline → used by the
ng-runCLI - ngimager.cli.viz.app → used by the
ng-vizCLI
Internally, the package is organized into:
- physics – hits, events, kinematics, cones, energy strategies
- geometry – imaging plane and coordinate transforms
- imaging – SBP and future imaging algorithms
- io – adapters, list-mode HDF5 storage, LUT loading
- config – Pydantic config schemas and loading helpers
- pipelines – high-level orchestration / CLI pipeline entry points
- vis – visualization utilities
- tools – helper scripts and LUT generators
cli ¶
Command-line interfaces (CLI) for ng-imager.
Currently exposed via:
ng-viz→ngimager.cli.viz:appng-run→ngimager.pipelines.core:app(defined in the pipelines package)
viz ¶
summed ¶
summed(h5_path=typer.Argument(..., help='Path to ng-imager HDF5 file (must contain /images/summed/*).'), species=typer.Option(['n', 'g', 'all'], '--species', '-s', help="Which images to render from /images/summed: any of 'n', 'g', 'all'."), center_on_plane_center=typer.Option(True, '--center-on-plane-center/--no-center-on-plane-center', help='Center axes on the imaging plane center.'), flip_vertical=typer.Option(True, '--flip-vertical/--no-flip-vertical', help='Flip the plotted image vertically (mainly for legacy comparison).'), axis_units=typer.Option('cm', '--axis-units', help="Axis units for plotting: 'cm' or 'mm'."), cmap=typer.Option('cividis', '--cmap', help="Matplotlib colormap to use (e.g. 'cividis', 'viridis')."), filename_pattern=typer.Option('{species}_{stem}.{ext}', '--filename-pattern', help='Python format string for output filenames; may use {stem}, {species}, {ext}.'), fmt=typer.Option(['png'], '--format', '-f', help="Output format(s) to write (e.g. 'png', 'pdf')."), plot_label=typer.Option(None, '--plot-label', help='Override run plot label annotation (defaults to any value stored under /meta.run_plot_label in the HDF5 file).'))
Render one or more /images/summed/{n,g,all} datasets to image files.
Source code in ngimager/cli/viz.py
config ¶
load ¶
load_config ¶
Load a TOML config file into a Config object.
All paths inside the [io] table are interpreted relative to the location of the TOML file (cfg_dir), except when they are absolute.
In particular: - [io].input_path - [io].output_path - [io].restart_path - [io.extra_text_files].*
CLI overrides (e.g. --input-path/--output-path in ng-run) are applied later and remain relative to the current working directory.
Source code in ngimager/config/load.py
materials ¶
schemas ¶
ConeSpeciesOverrides ¶
Bases: BaseModel
Species-specific overrides for cone-level filters.
ConesFiltersCfg ¶
Bases: BaseModel
Cone-level filters with universal defaults plus neutron/gamma overrides.
TOML:
[filters.cones] max_delta_theta_deg = 5.0
[filters.cones.neutron] max_delta_theta_deg = 3.0
[filters.cones.gamma] max_delta_theta_deg = 8.0
Config ¶
Bases: BaseModel
Top-level TOML configuration.
DetectorFrameGeometry ¶
Bases: BaseModel
A simple rigid transform that maps detector-local coordinates to world coordinates:
p_world = R_xyz(rotation_deg) @ p_local + origin_cm
where rotation_deg = [rx, ry, rz] are Euler angles in degrees, applied in the fixed order Rx → Ry → Rz.
DetectorsCfg ¶
Bases: BaseModel
Mapping from detector IDs/regions to materials and optional geometry.
TOML:
[detectors] default_material = "OGS"
[detectors.material_map] 200 = "OGS" 210 = "M600" ...
Optional global detector-frame → world-frame transform:¶
[detectors.geometry.frame] origin_cm = [0.0, 0.0, 0.0] rotation_deg = [0.0, 0.0, 0.0]
OPTIONAL (stub for future expansion): per-detector transforms¶
[[detectors.geometry.detectors]] id = 0 origin_cm = [0.0, 0.0, 0.0] rotation_deg = [0.0, 0.0, 0.0]
DetectorsGeometryCfg ¶
Bases: BaseModel
Global detector-array geometry.
- 'frame' describes the overall detector coordinate frame relative to world coordinates.
- 'detectors' is an optional list for fine-grained per-detector transforms (currently unused, but reserved for future support).
EnergyCfg ¶
Bases: BaseModel
Energy strategy configuration.
strategy: "ELUT" – invert light via E(L) LUTs (per-material, per-species) "ToF" – simple ToF-based estimate (placeholder) "FixedEn" – fixed incident neutron energy (e.g. 14.1 MeV source) "Edep" – direct deposited energy (PHITS-style adapters)
EventSpeciesOverrides ¶
Bases: BaseModel
Species-specific overrides for event-level filters.
All fields are optional; when None, the universal [filters.events] value is used for ToF, and L-thresholds default to "no extra cut".
EventsFiltersCfg ¶
Bases: BaseModel
Event-level filters with universal defaults plus neutron/gamma overrides.
TOML:
[filters.events] tof_window_ns = [0.0, 30.0]
[filters.events.neutron] tof_window_ns = [0.0, 30.0] min_L1_MeVee = 0.0 min_L2_MeVee = 0.0
[filters.events.gamma] tof_window_ns = [0.0, 30.0] min_L_any_MeVee = 0.0
FastCfg ¶
Bases: BaseModel
Fast-mode override knobs.
Applied only when [run].fast = true; otherwise ignored.
FiltersCfg ¶
Bases: BaseModel
Top-level filter configuration, split into hits / events / cones.
HitSpeciesOverrides ¶
Bases: BaseModel
Species-specific overrides for hit-level filters.
All fields are optional; when None, the universal [filters.hits] value is used.
HitsFiltersCfg ¶
Bases: BaseModel
Hit-level filters with universal defaults plus neutron/gamma overrides.
TOML:
[filters.hits] min_light_MeVee = 50.0 max_light_MeVee = 1.0e6 psd_min = 0.0 psd_max = 1.0 bars_include = [] bars_exclude = [] materials_include = [] materials_exclude = []
[filters.hits.neutron] min_light_MeVee = 100.0 # optional override; others fall back to [filters.hits] psd_min = 0.2 # optional override; if omitted, uses [filters.hits] psd_max = 0.6
[filters.hits.gamma] # optional overrides...
IOCfg ¶
Bases: BaseModel
I/O paths and high-level source description.
TOML:
[io] input_path = "..." input_format = "phits_usrdef" # "phits_usrdef" | "root_novo_ddaq" | "hdf5_ngimager" output_path = "..."
PerDetectorGeometry ¶
Bases: BaseModel
OPTIONAL (stub for future expansion).
Describes an individual detector tile or module's placement within the detector-frame coordinate system. For now, ng-imager does not apply per-detector transforms, but the schema entry is accepted and stored for future expansion.
PipelineCfg ¶
Bases: BaseModel
Controls how far through the pipeline we run.
until = "hits" | "events" | "cones" | "image"
ProjectionAxisMetricsCfg ¶
Bases: BaseModel
Per-axis projection metrics controls.
These are applied separately for the u and v axes.
ProjectionMetricsCfg ¶
Bases: BaseModel
Controls whether projection metrics are computed and written to HDF5.
ProjectionPlotCfg ¶
Bases: BaseModel
Controls how projection metrics are visualized in vis/hdf.py.
(Plotting code will read these; they do not affect HDF5 contents.)
TOML example:
[vis.projections.plot]
# Basic visual toggles
show_peak_markers = true # vertical / horizontal lines at peak_pos_cm
show_edge_markers = true # lines at edge_low_cm / edge_high_cm
show_centroid_2d = false # crosshair at 2D centroid (if computed)
# Which metrics to use when both "all" and ROI curves exist
metrics_source = "auto" # "auto" | "all" | "roi" | "both"
curve_mode = "all+roi" # "all+roi" | "all_only" | "roi_only"
# Numeric summaries on the figure
# - "off" : no text annotations
# - "compact" : minimal one-line summary per axis
# - "full" : include more fields (e.g. edges) when available
annotate_summary = "compact"
# Optional extra panel with a table of metrics (future)
show_metrics_panel = false
RunCfg ¶
Bases: BaseModel
Global run controls that apply to the entire pipeline.
source_type: "cf252" | "dt" | "proton_center" | "phits" fast: Enable fast-mode overrides (see FastCfg and [fast] section). list: Enable list-mode imaging output (/lm/cone_pixel_indices, etc.).
VisCfg ¶
Bases: BaseModel
Visualization configuration.
These options control automatic image export from the pipeline and provide
defaults for the standalone ng-viz CLI.
VisProjectionsCfg ¶
Bases: BaseModel
Configuration for 1D projections and their analysis/visualization.
TOML:
[vis.projections]
enabled = true
roi_u_min_cm = -5.0
roi_u_max_cm = 5.0
roi_v_min_cm = -5.0
roi_v_max_cm = 5.0
[vis.projections.metrics]
enabled = true
[vis.projections.metrics.u]
compute_summary = true
compute_peak = true
compute_edges = false
edge_low_frac = 0.2
edge_high_frac = 0.8
min_counts = 100.0
[vis.projections.metrics.v]
compute_summary = true
compute_peak = true
compute_edges = true
[vis.projections.plot]
show_peak_markers = true
show_edge_markers = true
show_centroid_2d = false
metrics_source = "auto" # "auto" | "all" | "roi" | "both"
curve_mode = "all+roi" # "all+roi" | "all_only" | "roi_only"
annotate_summary = "compact" # "off" | "compact" | "full"
show_metrics_panel = false
roi_bounds_cm ¶
Return (u_min, u_max, v_min, v_max) in cm if a full ROI is defined, otherwise None.
Source code in ngimager/config/schemas.py
filters ¶
cone_filters ¶
passes_delta_theta_cut ¶
Cone-level filters:
-
Δθ = |φ − θ|, where:
- φ is the angle between the cone axis and the direction from apex to the prior target (or plane center if prior is None),
- θ is the cone opening half-angle.
Uses _score_cone_against_prior (shared with neutron p/C selection and gamma permutation selection).
-
max_incident_energy_MeV:
- For neutrons, En is computed once in physics/kinematics and passed in from the cone builder.
- For gammas, Eg is likewise computed in the gamma cone builder.
Both cuts are optional; if a limit is not configured (or we don't have an incident_energy_MeV), that cut is skipped.
Returns True if the cone is accepted, False if rejected.
Counters (all optional, keyed by species when applicable)
- "cones_checked_delta_theta"
- "cones_checked_delta_theta_n"
- "cones_checked_delta_theta_g"
- "cones_rejected_delta_theta"
- "cones_rejected_delta_theta_n"
-
"cones_rejected_delta_theta_g"
-
"cones_checked_incident_energy"
- "cones_checked_incident_energy_n"
- "cones_checked_incident_energy_g"
- "cones_rejected_incident_energy"
- "cones_rejected_incident_energy_n"
- "cones_rejected_incident_energy_g"
Source code in ngimager/filters/cone_filters.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | |
event_filters ¶
apply_event_filters ¶
Apply event-level filters, currently:
- species-dependent ToF windows (Δt12 between first two hits)
- neutron-specific min L thresholds for first and second scatters
- gamma-specific min L threshold applied to all three scatters
Events that fail are removed and counted in events_rejected_filters and more specific counters:
- events_rejected_tof_window{,_n,_g}
- events_rejected_L1_min_n
- events_rejected_L2_min_n
- events_rejected_L_any_min_g
Source code in ngimager/filters/event_filters.py
hit_filters ¶
apply_hit_filters ¶
Apply universal + species-specific hit-level cuts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hits
|
Iterable[Hit]
|
Input Hit objects for a single raw event. |
required |
cfg
|
HitsFiltersCfg
|
[filters.hits] configuration (including .neutron/.gamma overrides). |
required |
counters
|
Dict[str, int]
|
Shared counters dict to be updated in-place. |
required |
particle_type
|
Optional[str]
|
Optional event-level 'n' or 'g'. Used as a fallback species tag when Hit.type is missing. |
None
|
Source code in ngimager/filters/hit_filters.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
is_reconstructable ¶
Early decision: does this raw event still have enough hits to ever form a reconstructable cone?
For now: - neutron (event_type 'n'): require ≥ 2 hits - gamma (event_type 'g'): require ≥ 3 hits - unknown: require ≥ 2 hits (conservative default)
If not reconstructable, the appropriate raw_events_rejected_unreconstructable counters are incremented.
Source code in ngimager/filters/hit_filters.py
shapers ¶
ShapedEvent
dataclass
¶
Minimal shaped event used between hit-level filtering and typed events.
species: "n" or "g" hits: [Hit,...] of correct multiplicity (2 for n, 3 for g) meta: dict of event-level bookkeeping (iomp/batch/history/etc.)
shape_events_for_cones ¶
Shape raw coincidence windows / events (variable multiplicity, mixed species) into candidate fixed-multiplicity ShapedEvents (2-hit neutron and 3-hit gamma events) suitable for cone building
Inputs: raw_events: iterable of dicts, each with at least a 'hits' key. 'hits' must be a sequence of canonical physics.hits.Hit objects. (Adapters and/or canonicalization are responsible for constructing Hits.) cfg: ShapeConfig controlling policies and caps.
Outputs: shaped: list of shaped event dicts with: - 'event_type': 'n' or 'g' - 'hits': list of hits (same objects as input) - plus any original metadata keys preserved diag: ShapeDiagnostics with counters and reasons.
Source code in ngimager/filters/shapers.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 | |
to_typed_events ¶
shaped_to_typed_events ¶
Convert shaped events (from shapers.shape_events_for_cones) into typed physics events (NeutronEvent / GammaEvent).
Assumptions: - shaped[i].species is "n" or "g" - shaped[i].hits has exactly 2 hits for "n", 3 hits for "g" - hits are already canonical physics.hits.Hit objects
Source code in ngimager/filters/to_typed_events.py
geometry ¶
plane ¶
Plane
dataclass
¶
center ¶
Return the world-space coordinates of the geometric center of the imaging plane grid.
This is defined as the point corresponding to the midpoint in (u, v) coordinates:
u_c = 0.5 * (u_min + u_max)
v_c = 0.5 * (v_min + v_max)
and mapped back to 3D via plane_to_world.
Source code in ngimager/geometry/plane.py
transforms ¶
apply_rigid_transform ¶
Apply a rigid transform (rotation + translation) to 3D points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
points_cm
|
ndarray | Sequence[Sequence[float]]
|
Array-like of shape (..., 3). Interpreted as row vectors in cm. |
required |
origin_cm
|
Sequence[float]
|
Translation vector (x, y, z) in cm, giving the detector origin in the world frame. |
required |
rotation_deg
|
Sequence[float]
|
Euler angles (rx, ry, rz) in degrees, applied as Rx → Ry → Rz. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Transformed points with the same shape as |
Notes
Mathematically:
p_world = R_xyz(rotation_deg) @ p_local + origin_cm
With row-vector data, we implement this as:
p_world_row = p_local_row @ R_xyz(rotation_deg).T + origin_cm
Source code in ngimager/geometry/transforms.py
euler_xyz_deg_to_matrix ¶
Build a 3x3 rotation matrix from XYZ Euler angles in degrees.
Convention (matches what we discussed):
rotation_deg = (rx, ry, rz)in degrees.- Rotations applied in fixed order Rx → Ry → Rz.
- Mathematical column-vector form:
v_world = R_xyz @ v_local
For row-vector data (shape (..., 3)), right-multiply by R.T instead.
Source code in ngimager/geometry/transforms.py
is_identity_transform ¶
Return True if the transform is (numerically) the identity.
This lets the pipeline skip transform work when both the origin and all Euler angles are effectively zero.
Source code in ngimager/geometry/transforms.py
imaging ¶
projection_metrics ¶
compute_projection_metrics ¶
Compute metrics for u/v projections (all + ROI) given configuration.
Returns a nested dict:
{
"u": {
"all": {...metrics...},
"roi": {...metrics...} # omitted if no ROI
},
"v": {
"all": {...},
"roi": {...}
}
}
Source code in ngimager/imaging/projection_metrics.py
sbp ¶
cone_to_indices ¶
Unified entry point: cone → flat pixel indices.
engine = "scan": Use matrix-math scanning across rows/columns (continuous arcs). engine = "poly": Use ellipse parameterization when possible, falling back to general ray sampling for non-elliptic conics.
use_jit: When True and numba is available: - "scan" engine uses a JIT-compiled inner loop. - "poly" engine uses a JIT-compiled perimeter sampler. Otherwise, pure-Python paths are used.
Source code in ngimager/imaging/sbp.py
reconstruct_sbp ¶
reconstruct_sbp(cones, plane, list_mode=False, uncertainty_mode='off', workers='auto', chunk_cones='auto', progress=True, n_poly=360, sbp_engine='poly', use_jit=False)
Parallel SBP (analytic conic). If workers==0, runs single-process.
sbp_engine: "poly" – perimeter parametric ellipse (with ray fallback). "scan" – matrix-math scan across pixel-centered lines (continuous arcs).
use_jit: When True and numba is available, use a JIT-compiled inner loop for the "scan" engine to accelerate the row/column solving.
Source code in ngimager/imaging/sbp.py
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 | |
io ¶
adapters ¶
ngimager.io.adapters
Modular readers that turn external NOVO data sources (PHITS dumps or experiment/MC ROOT trees) into normalized physics-layer events (ngimager.physics.hits.Hit; ngimager.physics.events.{NeutronEvent,GammaEvent}) for the cone builder.
Design goals
- Keep I/O concerns isolated from physics/kinematics.
- Normalize units on ingest:
- distances -> cm
- times -> ns
- Be tolerant to schema variants by using small, explicit field maps.
- Stream (iterate) large files without loading everything into RAM.
- Remain side-effect free: yield Python objects; HDF5 is handled downstream.
Entry points
- class ROOTAdapter: reads NOVO ROOT trees ("novo_ddaq" or "hvl_geant4" styles).
- class PHITSAdapter: reads tabular PHITS lists (CSV/Parquet/HDF5).
- function make_adapter(cfg): factory from the [io.adapter] TOML section.
Config (example)
[io] input = "data/run42.root"
[io.adapter] type = "root" # "root" | "phits" style = "novo_ddaq" # ROOT styles: "novo_ddaq" | "hvl_geant4" unit_pos_is_mm = true time_units = "ns" # "ns" | "ps" require_gamma_triples = false # keep filtering in pipeline by default default_material = "M600" # tag assigned to all hits unless mapped
BaseAdapter ¶
Abstract adapter interface.
Yields physics-layer events normalized to cm/ns (and L if present).
iter_events ¶
Yield fully-typed physics events (NeutronEvent / GammaEvent, etc.) ready for cone building.
iter_raw_events ¶
Yield 'raw' events as collections of canonical Hit objects.
Semantics: - Each yielded item represents a single raw coincidence window. - For PHITS usrdef, this is a dict with at least: { "event_type": "n" | "g" | ..., "hits": [Hit, Hit, ...], ... (bookkeeping fields) } - Other adapters may choose a different raw representation, but must include a 'hits' field with a sequence of Hit objects.
Source code in ngimager/io/adapters.py
PHITSAdapter ¶
Bases: BaseAdapter
Read tabular event lists exported from PHITS post-processing.
Supported inputs: CSV (.csv), Parquet (.parquet/.pq), HDF (.h5/.hdf5).
The adapter expects row-wise events. Each row is either a neutron double or a gamma triple.
Canonical field names (columns): - x1,y1,z1,t1 ; x2,y2,z2,t2 ; [x3,y3,z3,t3] - det1,det2,[det3] ; L1,L2,[L3] (or elong1,elong2,[elong3]) - type (optional) values: 'n'|'g' ; if absent we infer by presence of 3rd hit
Units are assumed mm (pos) and ns (time) unless overridden.
Source code in ngimager/io/adapters.py
iter_events ¶
Unified iterator: - If 'path' ends with .out (PHITS usrdef, ragged): parse→Hit→shape→typed and yield typed events. - Otherwise (CSV/Parquet/HDF): fall back to the existing table-based row iterator.
Source code in ngimager/io/adapters.py
iter_raw_events ¶
Yield PHITS 'raw' events as dicts whose 'hits' entry is a list of canonical Hit objects.
For usrdef .out files this wraps from_phits_usrdef, which:
- parses the ragged usrdef text,
- canonicalizes hit fields to x_cm / y_cm / z_cm / t_ns / Edep_MeV / L,
- and converts each hit dict into a physics.hits.Hit, resolving the
material via this adapter's MaterialResolver.
For table-like PHITS exports (CSV/Parquet/HDF5) we currently don't have a native raw-event representation, so we conservatively reconstruct a minimal raw event around each typed event.
Source code in ngimager/io/adapters.py
RootNovoDdaqAdapter
dataclass
¶
RootNovoDdaqAdapter(tree_key='image_tree', unit_pos_is_mm=True, time_units='ns', default_material='UNK', material_map=None, require_gamma_triples=False, meta_tree_key='meta')
Bases: BaseAdapter
Adapter for NOVO DDAQ ROOT files ("image_tree" + optional "meta" tree).
This adapter:
- reads the main coincidence tree (image_tree) and yields raw events
with canonicalized hits, and
- can optionally read the run-level metadata tree (meta) via
read_meta_tree for passthrough into HDF5.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tree_key
|
str
|
Name of the ROOT TTree containing the imaging events (default: "image_tree"). |
'image_tree'
|
unit_pos_is_mm
|
bool
|
If True, hit positions are stored in mm and converted to cm. |
True
|
time_units
|
('ns', 'ps')
|
Units of the time branches (converted to ns). |
"ns"
|
default_material
|
str
|
Material tag to use when no mapping is provided. |
'UNK'
|
material_map
|
dict[int, str] or None
|
Mapping from det_id to material name. |
None
|
require_gamma_triples
|
bool
|
If True, drop gamma events that do not have exactly 3 hits. |
False
|
meta_tree_key
|
str or None
|
Name of the metadata TTree (default "meta"). If None, metadata extraction is disabled. |
'meta'
|
iter_events ¶
Placeholder: higher-level event shaping for NOVO DDAQ ROOT data.
For now, the ng-imager pipeline should consume iter_raw_events
and run the standard shaping / filtering stack on top. This method
is defined only to satisfy the BaseAdapter interface.
Source code in ngimager/io/adapters.py
iter_raw_events ¶
Yield raw coincidence windows as dicts:
{
"hits": [Hit, ...],
"multi": int, # as stored in the ROOT tree, if present
"entry": int, # global entry index
"source": "ROOT_NOVO_DDAQ",
}
This method is intentionally conservative and does not make any physics decisions about which hits belong to neutron vs gamma events; it simply exposes the coincidence window.
Source code in ngimager/io/adapters.py
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
read_meta_tree ¶
Read the NOVO 'meta' TTree (if present) and return a flat dict mapping branch names → Python scalars/strings.
This is intended for run-level metadata passthrough into HDF5. Returns None if no compatible meta tree is found.
Source code in ngimager/io/adapters.py
from_phits_usrdef ¶
Public convenience entry point for PHITS usrdef ingestion. Currently supports the 'short' format. 'auto' is reserved for future sniffing.
Source code in ngimager/io/adapters.py
make_adapter ¶
Create an adapter from a config dict (from TOML/CLI).
Expected keys under [io.adapter]: type: "root" | "phits" style: "novo_ddaq" | "hvl_geant4" (ROOT-only) unit_pos_is_mm: bool time_units: "ns" | "ps" require_gamma_triples: bool (ROOT-only) default_material: str
Source code in ngimager/io/adapters.py
parse_phits_usrdef_short ¶
Parse PHITS 'usrdef.out' short format into variable-multiplicity events. The [T-Userdefined] source code for this tally and documentation can be found at: https://github.com/Lindt8/T-Userdefined/tree/main/multi-coincidence_ng
Input row format (tokens; delimiters ';' and ',' are cosmetic): event_type #iomp #batch #history #no #name ; reg Edep(MeV) x(cm) y(cm) z(cm) t(ns) , reg Edep x y z t , ...
Where: - event_type: 'ne' (neutron) or 'ge' (gamma) - #iomp, #batch, #history, #no, #name: integers (PHITS bookkeeping) - For each hit: reg (int), Edep_MeV (float), x_cm (float), y_cm (float), z_cm (float), t_ns (float) - 2 hits min for 'ne', 3 hits min for 'ge', but higher multiplicities may appear.
Returns a list of dicts, each with: { "event_type": "n" | "g", "iomp": int, "batch": int, "history": int, "no": int, "name": int, "hits": [ {"reg": int, "Edep_MeV": float, "x_cm": float, "y_cm": float, "z_cm": float, "t_ns": float}, ... ], "source": "PHITS", "format": "usrdef.short", }
NOTE: This function performs no physics decisions (pair/triple selection, species mixing, etc.). It preserves all hits in the order they appear. Shaping happens downstream.
Source code in ngimager/io/adapters.py
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | |
canonicalize ¶
canonicalize_events_inplace ¶
Ensure each hit dict has the canonical keys used by filters/shapers: x_cm, y_cm, z_cm, t_ns, L, Edep_MeV, det_id Missing values are filled conservatively (L from Edep_MeV if absent). Mutates in place; safe to call on PHITS/ROOT outputs.
Source code in ngimager/io/canonicalize.py
lm_store ¶
write_cones ¶
write_cones(f, cone_ids, apex_xyz_cm, axis_xyz, theta_rad, species, recoil_code, incident_energy_MeV, event_index, gamma_hit_order=None)
Store per-cone geometric and classification parameters under /cones.
Layout: /cones/cone_id : [N] uint32 /cones/apex_xyz_cm : [N,3] float32 /cones/axis_xyz : [N,3] float32 /cones/theta_rad : [N] float32 /cones/species : [N] uint8 (0=neutron, 1=gamma) /cones/recoil_code : [N] uint8 (0=NA, 1=proton, 2=carbon) /cones/incident_energy_MeV : [N] float32 (En for n, Eg for g) /cones/event_index : [N] int32 (row index into /lm/event_* arrays) /cones/gamma_hit_order : [N,3] int8 (optional; see below)
/cones/species_labels : ["0=neutron", "1=gamma"] /cones/recoil_code_labels : ["0=NA", "1=proton", "2=carbon"]
Notes
- For gamma cones (species == 1), gamma_hit_order[i] = (i0, i1, i2) gives the indices into /lm/hit_*[event_index[i], :, :] that correspond to (first scatter, second scatter, third point) used to build that cone.
- For neutron cones (species == 0), gamma_hit_order[i] is (-1, -1, -1) and should be ignored.
Source code in ngimager/io/lm_store.py
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 | |
write_counters ¶
Store scalar counters under /meta/counters as attributes.
Each key in counters becomes an attribute on the /meta/counters group,
prefixed with a stage number:
S1_... → Stage 1 (raw events → hits)
S2_... → Stage 2 (hits → shaped/typed → event filters)
S3_... → Stage 3 (events → cones → cone filters)
S4_... → Stage 4 (cones → images)
This forces a "chronological" ordering when viewed in tools like HDFView (which sort attributes alphabetically).
Source code in ngimager/io/lm_store.py
write_event_cone_survival ¶
Store per-event survival information linking events → cones.
Layout (all under /lm):
/lm/event_cone_id : [N_events] int32 For each event row i (as in /lm/event_type, /lm/hit_*): - cone_id of the cone built from this event, or -1 if no cone.
/lm/event_imaged_cone_id : [N_events] int32 For each event row i: - cone_id of the cone that both exists AND hits the imaging plane (has non-empty pixel set), or -1 if none.
Notes
- event index i is simply the row index into /lm/event_type, /lm/hit_*.
- event_imaged_cone_id is only meaningfully populated when [run].list = true; for non-list runs it will typically be all -1.
Source code in ngimager/io/lm_store.py
write_events_hits ¶
Store per-event and per-hit data for list-mode analysis.
Layout (all under /lm):
/lm/materials/labels : [M] array of material strings /lm/event_type : [N] uint8, 0=n, 1=g /lm/event_meta_run_id : [N] int32 (optional meta) /lm/event_meta_file_ix : [N] int32 (optional meta) /lm/hit_pos_cm : [N,3,3] float32 (event, hit_index, xyz) /lm/hit_t_ns : [N,3] float64 /lm/hit_L_mevee : [N,3] float32 /lm/hit_det_id : [N,3] int32 /lm/hit_material_id : [N,3] int16
Convention: - Neutron events use hits [0,1] and leave slot 2 as NaN/-1. - Gamma events use hits [0,1,2].
Source code in ngimager/io/lm_store.py
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 | |
write_lm_indices ¶
Store list-mode indices mapping cones -> (u,v) pixels.
We store: /lm/cone_pixel_indices : ragged array of (cone_id, flat_index) pairs
where: - cone_id is the index into /cones/cone_id - flat_index is the flattened pixel index (row-major) on the imaging plane.
Source code in ngimager/io/lm_store.py
write_lm_ragged ¶
Write variable-length list-mode (ragged) datasets for events with arbitrary hit multiplicity. This is ADDITIVE and does not modify existing fixed-shape datasets you already write elsewhere.
Source code in ngimager/io/lm_store.py
write_projections ¶
Write 1D u/v projections (and optional ROI-limited projections) to HDF5, and optionally compute/write metrics.
Layout under /images/summed/projections/{species}:
u : [nu] float32, sum over v (rows)
v : [nv] float32, sum over u (cols)
u_roi : [nu] float32, ROI-limited u projection (zeros outside ROI)
v_roi : [nv] float32, ROI-limited v projection (zeros outside ROI)
Metrics layout (per species):
metrics/u : scalar metrics for the "all" u-projection
metrics/v : scalar metrics for the "all" v-projection
metrics/u_roi : scalar metrics for the ROI u-projection (if ROI defined)
metrics/v_roi : scalar metrics for the ROI v-projection (if ROI defined)
Each metrics group contains 0D datasets such as:
total_counts
mean_cm, median_cm, std_cm
peak_pos_cm, peak_value
edge_low_cm, edge_high_cm, edge_width_cm
summary_ok, peak_ok, edges_ok
The imaging plane grid (u_min/u_max/v_min/v_max/du/dv) is read from /meta.attrs as written by write_init().
Source code in ngimager/io/lm_store.py
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 | |
write_root_novo_meta ¶
Persist NOVO DDAQ ROOT run-level metadata into HDF5 under /meta/root_novo_ddaq.
The input 'meta' is expected to be a flat mapping from branch names in the ROOT 'meta' TTree to Python scalars/strings, as returned by RootNovoDdaqAdapter.read_meta_tree().
Layout
/meta/root_novo_ddaq : group attrs: InputFileName, OutputFileName, CDFFileName, PSDCutsFileName SampleRate, NumDet, NumThreads, WriteHistograms, MergeMode, CardOffsetChannel, UsePositionVeto
/meta/root_novo_ddaq/detectors
det_id : [NumDet] int32
pos : [NumDet, 3] float32 (PosX, PosY, PosZ) [mm]
dim : [NumDet, 3] float32 (DimX, DimY, DimZ) [mm]
rot_deg : [NumDet, 3] float32 (RotX, RotY, RotZ) [deg]
local_time_offset : [NumDet] float32 [ns]
global_time_offset: [NumDet] float32 [ns]
pos_cal_file : [NumDet] string
energy_cal_file : [NumDet] string
is_start_det : [NumDet] int8
is_laser_det : [NumDet] int8
Source code in ngimager/io/lm_store.py
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 | |
write_summed ¶
Write summed image for a given species.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
open h5py.File
|
|
required |
species
|
"n" | "g" | "all" (string key)
|
|
required |
img
|
2D numpy array (nv, nu), float or int
|
|
required |
Source code in ngimager/io/lm_store.py
lut ¶
build_lut_registry ¶
Build a registry mapping material -> species -> LUT.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lut_paths
|
Dict[str, Dict[str, str]] | None
|
Configuration-style mapping, e.g.: Paths may be relative; they are resolved against When a material/species is omitted entirely from |
required |
base_dir
|
str | Path | None
|
Base directory for resolving relative paths (typically the directory containing the TOML config). If None, uses the current working directory. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Nested dictionary: {material: {species: LUT, ...}, ...} |
Source code in ngimager/io/lut.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
builtin_lut_path ¶
Return path to a built-in LUT .npz for given material/species.
Source code in ngimager/io/lut.py
physics ¶
cones ¶
build_cone_from_gamma ¶
build_cone_from_gamma(ev, energy_model, plane=None, prior=None, return_meta=False, return_perm=False)
Build a Compton gamma cone from a three-hit GammaEvent.
Behavior without plane/prior (backwards-compatible, PHITS-oriented): - Use ev.ordered() so that h1, h2, h3 are in increasing time, which is physically the true order in PHITS data. - Attempt to build a cone from this ordered triplet using _gamma_cone_from_ordered_hits. - If no physically valid cone exists for this ordering, raise ValueError.
Enhanced behavior when plane is provided:
- Generate all 3! permutations of (h1, h2, h3).
- For each ordering:
* call _gamma_cone_from_ordered_hits(h1, h2, h3),
* discard if it returns None (non-physical),
* discard if the cone axis does not point toward the plane
(t_int <= 0 via _axis_towards_plane),
* compute Δ = |φ − θ| using the configured prior or, if prior is None,
the plane center as an implicit prior.
- Select the candidate with minimal Δ.
- If no candidate survives, fall back to the ordered (time) triplet
as in the simple behavior; if that also fails, raise ValueError.
Return value
- If return_meta and return_perm are both False (default), returns only a Cone.
- If return_meta is True and return_perm is False, returns (cone, Eg_MeV) where Eg_MeV is the incident gamma energy for the selected ordering.
- If return_meta is False and return_perm is True, returns (cone, perm) where perm is a tuple (i0, i1, i2) with indices into the event's time-ordered hit list.
- If both return_meta and return_perm are True, returns (cone, Eg_MeV, perm).
Notes
-
For now, we do not use
energy_modelfor gammas: Hit.L is already the deposited energy in MeV (Edep) from the adapter. -
This function is designed so that callers who do not yet pass a Plane or Prior still get the old, simple behavior.
Source code in ngimager/physics/cones.py
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 | |
build_cone_from_neutron ¶
build_cone_from_neutron(ev, energy_model, plane=None, prior=None, force_proton=False, return_meta=False)
Build a neutron cone using the NOVO imaging primer convention:
- apex O = X1 (first hit position),
- axis D = unit vector along the scattered neutron direction (X2 - X1),
- half-angle θ from elastic n–N kinematics in the lab frame.
Behavior (high level)
-
The event is assumed to be time-ordered (h1 before h2); callers should use ev.ordered() upstream, as the pipeline already does.
-
We always use the full kinematic chain from kinematics.py:
E' = E_n' from ToF between hits 1→2 (relativistic), En = E' + E_dep,1, θ = θ_lab(E_dep,1, En, A) with A = m_recoil / m_n,
where E_dep,1 is obtained from energy_model.first_scatter_energy(...)
and A is set by the assumed recoil nucleus ("H" or "C").
-
If
force_protonis True, or ifplaneis None, we build a single proton-recoil hypothesis and return it (backwards-compatible path). -
Otherwise, we build both proton and carbon hypotheses, reject any that are non-physical, enforce that the cone axis points toward the imaging plane, and then score the survivors against the prior using the same Δ = |φ − θ| metric used for gammas. The winner is the hypothesis with the smallest Δ.
If both hypotheses fail scoring (e.g. degenerate prior geometry), we fall back to the proton-only construction.
Notes
- This function does not mutate the event or record which hypothesis "won"; that bookkeeping is left to callers via the returned recoil_code and En.
Source code in ngimager/physics/cones.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
enumerate_gamma_cone_candidates ¶
Enumerate all physically valid Compton cones for the 3! permutations of a three-hit GammaEvent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ev
|
GammaEvent
|
A GammaEvent with exactly three hits (h1, h2, h3). The event is assumed to be already validated for basic consistency. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
candidates |
list[tuple[Cone, tuple[int, int, int]]]
|
List of (cone, perm) tuples where:
Only permutations that yield a physically valid Compton cone (non-negative energies, sensible angles, non-degenerate geometry) are returned. If no permutation is viable, the list is empty. |
Notes
-
This function is kinematics-only: it does NOT apply any priors or scoring; it simply reports all physically allowed cones.
-
Subsequent stages (e.g. in the pipeline) can:
- apply event- or cone-level filters to the candidates, and
- use spatial/energy priors to select a "best" cone for imaging.
Source code in ngimager/physics/cones.py
energy_strategies ¶
EnergyFromDeposited ¶
Bases: EnergyStrategy
Treat Hit.L as deposited energy (MeV) directly.
This is intended for synthetic/sim sources like PHITS where Hit.L has already been filled from Edep_MeV in the adapter, so no E(L) inversion or ToF logic is needed.
EnergyFromFixedIncident ¶
Bases: EnergyStrategy
Monoenergetic incident neutron energy (e.g. DT source).
This strategy assumes a fixed incident neutron kinetic energy En. For a given 2-hit neutron event, we:
- Compute the post-scatter neutron energy E' from ToF between h1 and h2.
- Infer the first-scatter deposited energy as Edep1 = En - E'.
- Reject the event if E' >= En (non-physical upscatter).
The returned value is Edep1, which downstream kinematics combine with
E' to reconstruct En again. This keeps the math consistent with
neutron_theta_from_hits while enforcing monoenergetic DT semantics.
Source code in ngimager/physics/energy_strategies.py
EnergyFromToF ¶
Bases: EnergyStrategy
Compute E' from ToF, then E_total = dE + E'.
Source code in ngimager/physics/energy_strategies.py
EnergyStrategy ¶
Base protocol: compute first-scatter energy and optional σ.
first_scatter_energy ¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h1
|
Hit
|
First and optional second hits in the event. |
required |
h2
|
Hit
|
First and optional second hits in the event. |
required |
material
|
str
|
Material key (e.g. "OGS", "M600") for LUT-based strategies. |
required |
species
|
Literal['proton', 'carbon'] | None
|
Recoil species key when relevant (e.g. "proton", "carbon"). |
'proton'
|
Returns:
| Name | Type | Description |
|---|---|---|
Edep1_MeV |
float
|
First-scatter deposited energy [MeV] to feed into the kinematics. |
sigma_MeV |
float or None
|
Optional uncertainty estimate on Edep1, or None if not provided. |
Source code in ngimager/physics/energy_strategies.py
events ¶
GammaEvent
dataclass
¶
Three-interaction gamma event.
As with NeutronEvent, hits can arrive unsequenced; use .ordered() to get a time-ordered copy and .validate() to assert ordering.
ordered ¶
Return a GammaEvent with hits sorted by t_ns (h1 earliest).
If copy=False, reorders self in-place and returns self.
Source code in ngimager/physics/events.py
validate ¶
Raise ValueError if hits are not in (weakly/strictly) increasing time.
Source code in ngimager/physics/events.py
NeutronEvent
dataclass
¶
Two-scatter neutron event.
Hits can be unsequenced when first ingested (e.g. from ROOT/PHITS), so use .ordered() to get a time-ordered event and .validate() to assert the ordering.
ordered ¶
Return a NeutronEvent with hits ordered by t_ns (h1 earliest).
If copy=False, reorders self in-place and returns self.
Source code in ngimager/physics/events.py
validate ¶
Raise ValueError if the hits are not in time order.
Source code in ngimager/physics/events.py
hits ¶
Hit
dataclass
¶
Hit(det_id, r, t_ns, L=0.0, type='UNK', material='UNK', sigma_r_cm=None, sigma_t_ns=None, sigma_L=None, extras=dict())
Canonical detector hit (physics layer).
r: position [cm] t_ns: time [ns] L: light-like measure (e.g., Elong) (dimensionless or MeVee-scale per your LUT) type: particle tag for this hit (e.g., "n" for neutron, "g" for gamma, "UNK" if unknown) material: detector material tag (e.g., "M600") extras: arbitrary per-hit fields preserved from input (psd, dE_MeV, raw columns...)
kinematics ¶
compton_incident_energy_from_second_scatter ¶
Incident gamma energy Eg [MeV] from:
- dE1: energy deposited at 1st scatter [MeV]
- dE2: energy deposited at 2nd scatter [MeV]
- theta2: angle between 1->2 and 2->3 baselines [rad]
This mirrors the NOVO primer / legacy implementation:
Eg = dE1 + 0.5 * ( dE2 + sqrt( dE2^2 + 4*dE2*me / (1 - cos(theta2)) ) )
Raises:
| Type | Description |
|---|---|
ValueError
|
If inputs are non-physical (negative energies, grazing angles, etc.). |
Source code in ngimager/physics/kinematics.py
compton_theta_from_energies ¶
First Compton scatter angle theta1 [rad] from:
Eg : incident gamma energy [MeV]
Egp : post-first-scatter gamma energy [MeV]
Uses the standard Compton relation:
cos(theta) = 1 + me * (1/Eg - 1/Egp)
Raises:
| Type | Description |
|---|---|
ValueError
|
If energies are non-physical or the argument to arccos is out of [-1, 1]. |
Source code in ngimager/physics/kinematics.py
neutron_theta_from_hits ¶
neutron_theta_from_hits(r1_cm, t1_ns, r2_cm, t2_ns, Edep1_MeV, scatter_nucleus='H', return_En=False)
Full calculation consistent with the NOVO primer: E' via ToF between hits 1->2 (relativistic), E_n = E' + Edep1, theta_lab from COM using A = m_recoil/m_n.
If return_En is False (default), returns theta [rad]. If return_En is True, returns (theta [rad], En [MeV]).
Source code in ngimager/physics/kinematics.py
theta_lab_from_Erecoil_En ¶
Compute neutron lab-frame scattering half-angle [rad] from E_recoil, E_n, and A = m_recoil/m_n. Follows primer equations for theta_CoM then lab mapping.
Source code in ngimager/physics/kinematics.py
tof_energy_relativistic ¶
Relativistic neutron KE E' [MeV] from flight distance s [cm] and time dt [ns].
Source code in ngimager/physics/kinematics.py
priors ¶
Prior ¶
make_prior ¶
Small factory used by pipelines.core; returns a Prior or None.
Expected cfg_prior schema (from TOML, after Pydantic):
[prior] type = "none" | "point" | "line" strength = 1.0
# Point prior: # either: # point = [x, y, z] # or (future) nested [prior.point] can be normalized upstream.
# Line prior (preferred, nested): # [prior.line] # p0 = [x0, y0, z0] # p1 = [x1, y1, z1] # or: # [prior.line] # r0 = [x0, y0, z0] # direction = [dx, dy, dz] # # For backward compatibility we also accept flat: # line_p0 = [x0, y0, z0] # line_p1 = [x1, y1, z1]
Source code in ngimager/physics/priors.py
pipelines ¶
High-level imaging pipelines for ng-imager.
The main entry point is run_pipeline, which is what the ng-run
command-line tool calls under the hood.
run_pipeline ¶
run_pipeline(cfg_path, *, fast=None, list_mode=None, neutrons=None, gammas=None, input_path=None, output_path=None, plot_label=None)
Orchestrate the full pipeline from a TOML config file.
CLI flags (--fast/--list/--neutrons/--no-neutrons/--gammas/--no-gammas) override the corresponding [run] fields when not None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg_path
|
str
|
Path to TOML configuration file. |
required |
input_path
|
str
|
When provided, overrides [io].input_path from the TOML file. |
None
|
output_path
|
str
|
When provided, overrides [io].output_path from the TOML file. |
None
|
plot_label
|
str
|
When provided, overrides [run].plot_label (used for HDF5 and visualization annotations). |
None
|
Returns:
| Type | Description |
|---|---|
Path to written HDF5 file.
|
|
Source code in ngimager/pipelines/core.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 | |
core ¶
The CLI is implemented via Typer, so the script behaves like a simple one-argument command:
- argument = path to TOML config file
The pipeline will:
- Load the TOML config
- Detect the adapter (PHITS, ROOT, HDF5 restart)
- Shape/validate hits → events
- Build cones (now neutron + gamma depending on run.neutrons, run.gammas)
- Run SBP imaging
- Write unified HDF5 output
You can always show help via:
- `python -m ngimager.pipelines.core --help`
Example run commands from project root:
python -m ngimager.pipelines.core path/to/config.toml
python -m ngimager.pipelines.core examples/configs/phits_usrdef_simple.toml
python -m ngimager.pipelines.core .\examples\configs\phits_usrdef_simple.toml
main ¶
main(cfg_path=typer.Argument(..., help='Path to TOML config file'), fast=typer.Option(False, '--fast', help='Override [run].fast = true (use aggressive fast settings)'), list_mode=typer.Option(False, '--list', help='Override [run].list = true (enable list-mode image output)'), neutrons=typer.Option(None, '--neutrons / --no-neutrons', help='Enable or disable neutron processing; overrides [run].neutrons when set'), gammas=typer.Option(None, '--gammas / --no-gammas', help='Enable or disable gamma processing; overrides [run].gammas when set'), input_path=typer.Option(None, '--input-path', '-i', help='Override [io].input_path from the TOML config.'), output_path=typer.Option(None, '--output-path', '-o', help='Override [io].output_path from the TOML config.'), plot_label=typer.Option(None, '--plot-label', help='Override [run].plot_label (annotation text used in visualization).'))
Run the unified ng-imager pipeline for a single config.
Source code in ngimager/pipelines/core.py
run_pipeline ¶
run_pipeline(cfg_path, *, fast=None, list_mode=None, neutrons=None, gammas=None, input_path=None, output_path=None, plot_label=None)
Orchestrate the full pipeline from a TOML config file.
CLI flags (--fast/--list/--neutrons/--no-neutrons/--gammas/--no-gammas) override the corresponding [run] fields when not None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg_path
|
str
|
Path to TOML configuration file. |
required |
input_path
|
str
|
When provided, overrides [io].input_path from the TOML file. |
None
|
output_path
|
str
|
When provided, overrides [io].output_path from the TOML file. |
None
|
plot_label
|
str
|
When provided, overrides [run].plot_label (used for HDF5 and visualization annotations). |
None
|
Returns:
| Type | Description |
|---|---|
Path to written HDF5 file.
|
|
Source code in ngimager/pipelines/core.py
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 | |
tools ¶
bundle_repo ¶
bundle_repo.py — produce a single-file text bundle of your repo.
Usage: python src/ngimager/tools/bundle_repo.py . -o repo_bundle.txt
What it does: - Writes a directory tree. - For each text file, writes a header with path/size/sha256 and the content. - Skips binaries and large files (configurable). - Skips typical junk dirs (.git, pycache, build artifacts).
build_tree ¶
Return a simple text tree of the repo.
Source code in ngimager/tools/bundle_repo.py
get_git_commit ¶
Best-effort retrieval of the current Git commit SHA for the repo root.
Returns a full 40-character SHA string if available, otherwise None. This is intentionally non-fatal: if the repo is not a Git checkout, or git is not installed, or anything else goes wrong, we just return None.
Source code in ngimager/tools/bundle_repo.py
is_textlike ¶
Heuristic to decide if a file is text-like.
Source code in ngimager/tools/bundle_repo.py
walk_repo ¶
Yield all files under root, skipping DEFAULT_EXCLUDE_DIRS.
Source code in ngimager/tools/bundle_repo.py
generate_lut ¶
Light-response LUT generation tools for NOVO scintillators.
This subpackage exposes:
- :mod:
ngimager.tools.generate_lut.NOVO_light_response_functions— the script and helpers used to build E(L) LUTs for M600 and OGS from SRIM stopping power data and calibration measurements.
NOVO_light_response_functions ¶
Created by Hunter N. Ratliff, 2025-10-17 This code generates light response functions/lookup-tables (LUTs), forward and inverse, for NOVO's M600 and OGS scintillators using my SRIM calculations as a basis for a Birks function fit whose parameters are optimized for proton light response data collected in NOVO's March 2024 PTB experiments.
==============================================================================¶
Light-Response Fitting and LUT Generation — Explainer¶
==============================================================================¶
This script builds physics-based light-response models for plastic scintillators and exports fast lookup tables (LUTs) to convert measured light output (MeVee) into recoil energy (MeV). It supports both proton and carbon recoils and produces figures for fit quality and inverse-response uncertainty bands.
What the script does (high level)¶
1) Loads stopping power data (SRIM) for protons and carbon and converts to linear stopping power using the scintillator density. 2) Loads experimental calibration data from PTB that map proton recoil energy to measured light output. 3) Fits a Birks-type light-yield model (Birks or Birks–Chou) to the calibration data. 4) Optionally constrains S to 1 using gamma Compton-edge calibration (MeVee scale). 5) Builds dense forward and inverse LUTs: - Forward: E -> L(E) - Inverse: L -> E(L), uniform grid in L for fast np.interp 6) Computes 68 percent confidence bands on E(L) by sampling the fitted parameters and propagating to inverse LUTs. 7) Exports portable artifacts (NPZ, CSV, JSON metadata) and generates plots.
Inputs¶
- SRIM stopping power files for H and C ions for each scintillator:
- Must include energy (MeV) and mass stopping power (MeV cm^2 / g).
- Energy range ideally covers 1 keV to at least 100–250 MeV.
- Scintillator density rho (g/cm^3) for each material.
- Experimental proton light-response calibration:
- Arrays of Ep_MeV (proton recoil energies) and L_MeVee (measured light output).
- Optional grouping labels for different neutron energies (En_indices, En_strs) to visualize subsets.
- Gamma Compton calibration (performed upstream):
- Data acquisition already outputs MeVee. This allows S to be fixed to 1 or softly constrained near 1.
Outputs¶
For each scintillator and species (proton, carbon):
- NPZ file: basepath.npz
- Arrays: L_inv (MeVee), E_inv (MeV)
- Optional arrays: E_inv_lo, E_inv_hi (16th and 84th percentile inverse bands)
- Metadata object with model, parameters, density, fit stats, grid sizes, timestamp
- CSV file: basepath.csv
- Two columns: L_inv_MeVee, E_inv_MeV (plaintext for sharing and longevity)
- JSON metadata: basepath.meta.json
- Human-readable metadata mirror of the NPZ meta
- Plots (if enabled):
- Birks fit and residuals (stacked) per scintillator
- Inverse response E(L) with 68 percent bands for proton and carbon
- Zoomed carbon inverse plot
Methods and process¶
1) Units and data prep - Convert mass stopping power to linear: dE/dx [MeV/cm] = rho * (dE/dx)_mass [MeV cm^2 / g]. - Interpolate dE/dx(E) with a monotone, nonnegative interpolant (shape-preserving cubic, or safe wrapper).
2) Light-response model - Birks: dL/dx = S * (dE/dx) / (1 + kB * dE/dx) - Birks–Chou (optional): dL/dx = S * (dE/dx) / (1 + kB * dE/dx + C * (dE/dx)^2) - Total light for a recoil of energy E is the integral of dL/dE over energy. Numerically integrate over a dense E grid.
3) Parameter fitting - Nonlinear least squares (scipy.optimize.least_squares) on residuals L_model(Ei) - L_data,i. - Residual variance scaling: covariance = sigma^2 * (J^T J)^-1 with sigma^2 = SSE / (N - p). - Report best-fit parameters, 1 sigma uncertainties, R^2, adjusted R^2, RMSE.
4) Handling S (electron-equivalent scale) - If data are already in MeVee via Compton-edge calibration, fix S = 1 (hard) or apply a soft Gaussian prior on S near 1 (e.g., sigma 0.01–0.02). - This removes S–kB degeneracy and stabilizes extrapolation.
5) Building LUTs - Forward: compute L(E) on a dense E grid (e.g., up to 250 MeV). - Inverse: create a uniformly spaced L grid and tabulate E(L) with np.interp. - Save proton and carbon inverse LUTs separately. Use float32 for compact storage and fast lookup.
6) Uncertainty bands (optional) - Draw samples of [S, kB, C] from the multivariate normal defined by the fitted covariance. - For each sample, compute inverse E(L) onto the fixed L grid. - Take the 16th and 84th percentiles across samples at each L to form a 68 percent confidence band. - Store E_inv_lo and E_inv_hi alongside the central inverse LUT.
7) Plotting (optional) - Fit-quality figure: top panel shows data and model L(E); bottom panel shows percent residuals. - Inverse figure: E(L) central curve with 68 percent band for proton and carbon. - Carbon often appears highly quenched; use a zoomed L range (e.g., L < 8 MeVee) or annotate unreachable regions using elastic kinematic caps.
How to use the LUTs downstream¶
- Load NPZ: L_inv, E_inv. Convert MeVee to recoil energy with Ep = np.interp(L_meas, L_inv, E_inv). Fast example drop-in code:
- If uncertainty bands were exported: compute Ep_lo and Ep_hi via the same interpolation on E_inv_lo and E_inv_hi.
- Use proton and carbon LUTs in parallel and let imaging logic choose between hypotheses or carry both with weights.
- Optional: clip carbon solutions using an elastic kinematic ceiling given a neutron energy bound.
Configuration knobs¶
- Model selection: use_Chou_C_term boolean to include the C term.
- S handling: lock S exactly to 1 via lock_S_to_1 = True or via bounds, or set a soft prior on S with prior_sigma.
- Grids: E_max, nE for forward integration; nL for inverse grid density.
- Band sampling: number of parameter draws, sample filtering for monotonicity and stability.
Assumptions and caveats¶
- Electron-equivalent calibration is already applied upstream; therefore S should be 1 or tightly constrained near 1.
- The carbon LUT is more uncertain in practice without carbon-tagged calibration; use it as a conservative branch and apply kinematic caps where appropriate.
- Extrapolation beyond the calibration Ep range is supported but rely on the band to communicate model uncertainty.
- Monotonicity is required for E(L) inversion; pathological parameter draws are rejected.
Troubleshooting¶
- Inverse interpolation error (requires at least two unique L points): occurs if a sampled parameter set produces nearly flat L(E). The sampler filters such draws; increase sample count or tighten priors if too many draws are rejected.
- Large parameter uncertainties under Birks–Chou: usually indicates kB and C are highly correlated and C is weakly identifiable; prefer simple Birks unless low-energy data demand C.
- Odd high-L divergence between Birks and Chou: typically due to unconstrained S; fix S via Compton calibration.
Dependencies¶
- numpy, scipy, matplotlib
- Hunters_tools (https://github.com/Lindt8/Hunters-tools/blob/master/Hunters_tools.py) module import (used for plotting)
- No runtime dependency on scipy in downstream imaging if you use saved L_inv and E_inv with np.interp.
Files written (per scintillator and species)¶
- basepath.npz: L_inv, E_inv, and optional E_inv_lo, E_inv_hi, plus metadata.
- basepath.csv: plaintext columns L_inv_MeVee, E_inv_MeV.
- basepath.meta.json: metadata (scintillator, species, model, parameters, density, fit stats, grid sizes, timestamp).
- Figures: fit and inverse-band plots if saving is enabled.
This design yields a transparent, physics-backed model with fast and portable inverse LUTs for experimental imaging.
Birks_params
module-attribute
¶
Birks_params = {'M600': {'S': 1.0, 'kB': 14.4, 'kB_linear': 14.4 * 0.001 / density['M600'], 'C': 0, 'C_linear': 0}, 'OGS': {'S': 0.83, 'kB': 5.5, 'kB_linear': 5.5 * 0.001 / density['OGS'], 'C': 0, 'C_linear': 0}}
As a note, these files are those directly produced by SRIM. The "SRIM_*.dat" files Joey used have column 1 units of MeV and column 2 units of keV / (mg/cm^2) (or, equivalently, MeV / (g/cm^2)).
accumulate_light_from_steps ¶
steps: iterable of dicts with keys {'dE', 'E_mid'} for a given recoil track returns total light for that track
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
build_inverse_L_grid ¶
Make a uniformly spaced grid in L (monotone), then tabulate E(L) with np.interp.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
compute_inverse_band ¶
Build 68% (16/84) percentile inverse E(L) on a fixed L grid (L_inv_ref) by sampling Birks params. Returns (E_inv_lo, E_inv_hi, E_inv_med). Any pathological samples (non-monotone L(E)) are skipped.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
fit_birks_params ¶
fit_birks_params(E_data, L_data, dedx_func, init=(1.0, 0.01, 0.0), use_C=False, bounds=((0, 0, 0), (np.inf, np.inf, np.inf)), prior_S=None, prior_sigma=None)
Fit (S, kB [, C]) by minimizing residuals on L(E). E_data in MeV (proton energy), L_data in MeVee. init: (S, kB[, C]) - use Joey's numbers as initial values bounds: ((Smin, kBmin, Cmin), (Smax, kBmax, Cmax))
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | |
inverse_with_bands ¶
For each L, return median and central 68% interval of E across samplers.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
light_integral_grid ¶
Returns L(E) tabulated on E_grid using cumulative trapezoid integration of dL/dE. dL/dE = S / (1 + kBdEdx + CdEdx^2)
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
make_forward_inverse_LUT ¶
Build dense forward LUT (E->L) and inverse (L->E) interpolants. nE large => smooth & accurate integrals + inversion.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
make_inverse_sampler ¶
Build many inverse interpolants E(L) for uncertainty bands. Returns a list of callables E_of_L_samplers.
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
pm_fmt ¶
Format 'val ± err' preserving significant digits, handling very small numbers (e.g., 0.00301 ± 0.00012).
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
read_SRIM_output ¶
Parses a SRIM output file, returning a dictionary object with particle energies in MeV and mass stopping powers in MeV / (g/cm^2).
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
read_light_response_file ¶
This function is for reading Joey's two-column light response data points files "LightOutput_*.dat". Column 1 is the recoil proton energy Ep / neutron energy lost dEn in MeV, and Column 2 is the light response in MeVee It returns a dictionary object where the Ep and L pairs are proerly ordered, ascending by Ep Blank lines delimit values taken from different source neutron energies
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
save_lut_npz_csv ¶
Saves: - basepath + ".npz" (binary, fast) - basepath + ".csv" (plaintext, two columns: L_inv,E_inv) - basepath + ".meta.json" (small JSON metadata, human-readable)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
basepath
|
str | Path
|
Path without extension (e.g., Path("results/lut_M600_proton")). The function appends .npz, .csv, and .meta.json automatically. |
required |
L_inv
|
array - like
|
Inverse lookup arrays: L_inv (MeVee) and E_inv (MeV). |
required |
E_inv
|
array - like
|
Inverse lookup arrays: L_inv (MeVee) and E_inv (MeV). |
required |
meta
|
dict
|
Metadata dictionary describing the LUT contents. |
required |
Source code in ngimager/tools/generate_lut/NOVO_light_response_functions.py
hdf5_to_root ¶
ngimager.tools.hdf5_to_root¶
This module provides a standalone HDF5 → ROOT converter for ngimager output files. Although it is distributed as part of the ngimager package, the module is intentionally self-contained and can be used independently — for example by downloading just this file from GitHub without installing ngimager.
Dependencies
Only two Python packages are required:
- h5py (for reading the ngimager HDF5 file)
- uproot (for writing the output ROOT file)
No part of ngimager's internal codebase is imported here; the converter makes no assumptions beyond the documented HDF5 file structure.
Standalone Usage (Command Line)
If you have Python along with h5py and uproot installed, you can run:
python hdf5_to_root.py my_run.h5
python hdf5_to_root.py my_run.h5 -o output.root
python hdf5_to_root.py my_run.h5 --overwrite
The script will write my_run.root (or the specified output path) containing
ROOT TTrees for list-mode hits, cones, list-mode imaging pixel mappings,
summed SBP images, and file/run metadata.
Standalone Usage (Python API)
You may also import and call the converter from a standalone script:
from pathlib import Path
from hdf5_to_root import convert_hdf5_to_root
convert_hdf5_to_root(Path("my_run.h5"), Path("my_run.root"), overwrite=True)
Running Under ngimager (Installed Package)
When installed as part of ngimager, the ng-hdf2root console entry point is
registered automatically and can be invoked as:
ng-hdf2root my_run.h5
The behavior is identical to running main() from this module.
Purpose
The converter is designed for ROOT-centric analysis workflows. It flattens the HDF5 list-mode representation into ROOT-friendly TTrees that preserve all linkages between events, hits, cones, and (when present) list-mode imaging pixels. This enables fast, flexible histogramming and correlation analysis in ROOT with minimal dependence on the rest of ngimager.
convert_hdf5_to_root ¶
Convert a single ngimager HDF5 output file into a ROOT file using uproot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hdf_path
|
Path
|
Input HDF5 path produced by ngimager. |
required |
root_path
|
Path
|
Output ROOT path to create. |
required |
overwrite
|
bool
|
If False (default), refuse to overwrite an existing file. |
False
|
Source code in ngimager/tools/hdf5_to_root.py
inspect_cone ¶
inspect_cone.py
Helper for tracing a single cone through the ngimager HDF5 file.
Given an ngimager HDF5 output and either: * a cone index, * an event index, or * an "imaged" cone index (from /lm/event_imaged_cone_id),
this tool reconstructs the full chain
cone → (u, v) pixels → hits
and prints a human-readable summary. Optionally it can also plot the per-cone footprint on the imaging plane.
Usage
python -m ngimager.tools.inspect_cone path/to/file.h5 --cone-index 42
python -m ngimager.tools.inspect_cone path/to/file.h5 --event-index 10
python -m ngimager.tools.inspect_cone path/to/file.h5 --imaged-cone-index 7
# Show a quick imshow of the cone footprint:
python -m ngimager.tools.inspect_cone file.h5 --cone-index 42 --plot
Notes
- Intended for list-mode ngimager outputs (
run.list = true), but will gracefully degrade when list-mode pixel data are missing. - For large files, /lm/cone_pixel_indices can be big; this tool reads the whole dataset into memory, which is convenient but may be heavy for extremely large runs.
ConeTrace
dataclass
¶
ConeTrace(cone_index, event_index, is_gamma, cone_apex_cm, cone_axis_dir, cone_theta_deg, cone_incident_energy_MeV, cone_species_code, cone_recoil_code, gamma_hit_order, hits, pixels_available, flat_pixel_indices, u_idx, v_idx, image_uv)
In-memory representation of one cone and its provenance.
trace_cone_from_index ¶
High-level helper: build a ConeTrace object for cone_index.
Source code in ngimager/tools/inspect_cone.py
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | |
inspect_root ¶
inspect_root.py
Tiny helper for exploring ROOT files with uproot.
It prints: - Top-level keys and their class names - Directory structure (recursively) - For TTrees: branch names and types - Optionally: first few entries of a chosen TTree
Usage
Basic structure listing:
python inspect_root.py myfile.root
Show branches and a few entries from a specific tree:
python inspect_root.py myfile.root --tree image_tree --show-entries 5
If you're not sure of the tree name, just run without --tree first and look at the printed keys (TTrees are marked).
With real example file:
python src/ngimager/tools/inspect_root.py examples/imaging_datasets/NOVO_experiment_DT_at_PTB/autoSorted_coinc_detector_DT-14p8MeV_000041.root
python src/ngimager/tools/inspect_root.py examples/imaging_datasets/NOVO_experiment_DT_at_PTB/autoSorted_coinc_detector_DT-14p8MeV_000041.root --tree meta
Notes
- Requires
uproot(pip install uproot). - Works with uproot 4/5-style API.
describe_tree ¶
Print basic info about a TTree: number of entries and branch info.
Source code in ngimager/tools/inspect_root.py
find_tree ¶
Try to resolve a tree path like 'tree', 'dir/tree', etc.
Source code in ngimager/tools/inspect_root.py
show_entries ¶
Print the first n entries. If the tree has exactly one entry, pretty-print as key = value lines, which is great for metadata.
Source code in ngimager/tools/inspect_root.py
walk_directory ¶
Recursively print keys and class names under a ROOT directory.
Source code in ngimager/tools/inspect_root.py
phits_legacy_2_usrdef ¶
phits_legacy_2_usrdef.py
Convert a NOVO legacy imaging pickle file (containing neutron_records and gamma_records) into a PHITS usrdef-short style text file that can be parsed directly by the modern ng-imager PHITS adapter (parse_phits_usrdef_short / from_phits_usrdef).
This script is the structural inverse of phits_usrdef_2_legacy.py.
USAGE
Basic conversion:
$ python phits_legacy_2_usrdef.py legacy_imaging_records.pickle
This produces:
legacy_imaging_records_usrdef.out
in the same directory as the input file.
Specify an explicit output file:
$ python phits_legacy_2_usrdef.py legacy_imaging_records.pickle -o my_usrdef.out
INPUT FORMAT
The input must be a pickle file produced by the legacy imaging pipeline or by phits_usrdef_2_legacy.py. It must contain (at minimum) the keys:
'neutron_records' -- numpy structured array of 2-hit neutron events
'gamma_records' -- numpy structured array of 3-hit gamma events
The dtype layouts follow the legacy NOVO event record definitions.
OUTPUT FORMAT
The output is a plain-text file in PHITS usrdef-short format, where each line has the structure:
event_type iomp batch hist no name ; reg Edep x y z t , reg Edep x y z t , ...
For example:
ne 0 0 0 12 0 ; 200 0.45 -3.5 16.2 0.4 4.70 , 210 0.31 -3.3 16.8 0.6 4.78 ,
ge 0 0 0 7 0 ; 101 0.20 2.1 -3.0 0.9 7.50 , 105 0.12 2.8 -3.3 1.1 7.56 ,
110 0.07 3.4 -4.1 1.4 7.63 ,
These lines are fully compatible with:
parse_phits_usrdef_short(path)
from_phits_usrdef(path)
PHITSAdapter(...).iter_raw_events(path)
NOTES
• PHITS bookkeeping fields (iomp, batch, hist, name) are assigned default placeholder values; feel free to extend the script to generate structured metadata.
• Legacy dE/Elong values are written as Edep(MeV); the ng-imager parser treats energy fields transparently.
• This converter is intended for analysis, debugging, and round-trip testing between the legacy pipeline and the modern ng-imager framework.
convert_legacy_to_usrdef ¶
Convert legacy pickle → usrdef-short compatible text.
Output rows follow the format:
event_type iomp batch hist no name ; hit1 , hit2 , ...
where: • event_type = 'ne' or 'ge' • hit = 6 floating fields: reg Edep x_cm y_cm z_cm t_ns
Source code in ngimager/tools/phits_legacy_2_usrdef.py
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
format_hit ¶
Return one PHITS hit group as: reg Edep(MeV) x(cm) y(cm) z(cm) t(ns) (Space-separated, no commas — the adapter ignores commas and semicolons anyway.)
Source code in ngimager/tools/phits_legacy_2_usrdef.py
phits_usrdef_2_legacy ¶
phits_usrdef_2_legacy.py
Convert PHITS custom tally output into the event format expected by the legacy NOVO imaging code.
For now this is just a skeleton: it only parses CLI arguments and sets up a main() entry point.
convert_phits_to_legacy ¶
Stub for the actual conversion logic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
Path
|
PHITS custom tally output. |
required |
output_path
|
Path
|
Destination file in the legacy imaging format. |
required |
Source code in ngimager/tools/phits_usrdef_2_legacy.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
determine_output_path ¶
Determine the final output .pickle path.
Rules: - If output_path is None: same directory as input, filename = input basename + '_imaging_records.pickle' e.g. usrdef.out -> usrdef.out_imaging_records.pickle - If output_path is provided: ensure it ends with '.pickle'; if not, append '.pickle'.
Source code in ngimager/tools/phits_usrdef_2_legacy.py
vis ¶
hdf ¶
render_summed_images ¶
render_summed_images(h5_path, species=('n', 'g', 'all'), filename_pattern='{species}_{stem}.{ext}', center_on_plane_center=True, flip_vertical=True, axis_units='cm', cmap='cividis', formats=('png',), projections=False, roi_u_min_cm=None, roi_u_max_cm=None, roi_v_min_cm=None, roi_v_max_cm=None, plot_label=None, metrics_source='auto', curve_mode='all+roi', annotate_summary='compact', show_metrics_panel=False, show_peak_markers=True, show_edge_markers=True, show_centroid_2d=False)
Render /images/summed/* datasets from an ng-imager HDF5 file to image files.
When projections=True, each figure shows:
- the main 2D image (u vs v),
- a 1D projection along u above the image,
- a 1D projection along v to the left of the image,
- an optional ROI rectangle (if roi_*_cm are provided),
- an annotation of the number of cones contributing to that species.
- and (when available) a run-level plot label drawn from [run].plot_label
or from the plot_label argument.
Source code in ngimager/vis/hdf.py
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 | |