CLI, Rust, and Python APIs
Rust packages
The Rust API spans two primary packages.
gammalooprscontains the physics implementation, data model, integrands, integration, observables, and lower-level algorithms.gammaloop-apiprovides the supported state-loading API, session/command integration, CLI assembly, and the PyO3 extension used by the Python distribution.
Load a state with StateLoadOption::load(). Its options select a state directory, boot card, logging overrides, read-only behavior, and optional settings overrides. Once loaded, callers can create a CLI-style session or use dedicated structured operations. A raw command string is the compatibility fallback, not a replacement for a typed operation where one exists.
use std::path::PathBuf;
use gammaloop_api::{state::CommandHistory, StateLoadOption};
let mut loaded = StateLoadOption {
state_folder: Some(PathBuf::from("./state")),
..StateLoadOption::default()
}.load()?;
let command = CommandHistory::from_raw_string("display settings global")?;
loaded.cli_session().execute_command(command)?;Some Rust types are public so that GammaLoop’s packages can work together, but are not intended as stable integration points. Prefer the state-loading and structured-operation APIs described here; use the Rust orientation to choose a crate, then use that revision’s Rustdoc for exact signatures, trait implementations, and lower-level types.
Rust reference map
This authored map separates the supported workflow from the much larger compiled surface. Follow these exact Rustdoc paths instead of beginning in an arbitrary internal module:
- Load and command a state: begin with
StateLoadOption, retain the returnedLoadedState, and execute parsedCommandHistoryvalues throughCliSession. - Replay and inspect: use
RunHistoryfor run cards andIntegrandInfofor structured graph-group, orientation, loop-basis, cut, and threshold metadata. - Evaluate samples: construct
EvaluateSamplesfor the ordinaryf64boundary. UseEvaluateSamplesPreciseonly when the caller must retain the activef64,f128, or arbitrary-precision result type. - Work below the facade: the
gammalooprsRustdoc includes the integrand contract, runtime settings, precision-specific result records, and the mergeable histogram snapshot boundary. Treat public items not named by a maintained workflow as implementation-facing unless their crate documents a stronger compatibility promise.
Python packaging
The Python distribution and import package are both named
gammaloop. Its compiled backend is gammaloop._gammaloop, which applications normally access through the public package. This is separate from the symbolica.community.* modules used by Spenso, Idenso, and Vakint; installing GammaLoop does not install those community modules as independent packages.The main Python entry point is GammaLoopAPI. Its constructor loads or creates one stateful session:
from gammaloop import GammaLoopAPI
gl = GammaLoopAPI(
state_folder="./state",
boot_commands_path="./run.toml",
)
gl.run("display settings global")The Python package requires Python 3.11 or newer. Run just build-api when building the bindings from a source checkout.
Python reference map
The generated module reference covers every registered public export, but the objects form a few connected workflows rather than forty unrelated entry points:
- Session lifecycle: construct
GammaLoopAPI, then userun, the history getters, andSettingsValueto automate the same state and commands as the CLI. - Point evaluation:
evaluate_samplereturns oneEvaluationResult.evaluate_samplesreturnsBatchEvaluationResultwith those same records insamplesand optional numerical-stability diagnostics. Both retain each sample’s observable contribution without accumulating statistics. Create anObservableAccumulatorwithobservable_accumulator()and add samples with explicit outer coefficients. - Generated-integrand structure: start at
IntegrandInfo, then follow its graph groups into graph, orientation, loop-momentum-basis, cut, and threshold records. These objects describe compiled structure; they do not mutate it.generated_representationskeeps the stored generation order. Each graph’snative_residue_countsrecords the native map size for those modes; a group’scomplete_residue_sumdistinguishes a full physical sum from individual orientation execution. Theorientationslist describes runtime slots, which can contain one complete-sum slot even when the native LTD map has many keys. - Native residue maps:
get_residue_mapreturns the stored graph-level CFF or LTD catalogue, including exact affine energy bindings, immutable map keys, scalar variants, and surfaces. Its native entries are distinct from the execution slots inIntegrandInfo. - Events and observables: evaluation records lead to
EventGroupandEvent. For caller-owned aggregation,HistogramAccumulatorproduces immutableHistogramSnapshotrecords with raw statistics that remain mergeable and reconstructible.
The current Python module does not expose a supported structured
integrate() method. Run an integration through GammaLoopAPI.run("integrate ...") or the CLI and consume its persisted workspace/results. Several integration-result record classes are registered by the native module for ongoing API work, but without a public producer they are not part of the curated Python boundary yet.Objects returned by evaluation and integration are snapshots. Mutating a Python list or dictionary derived from them does not update the live GammaLoop session. The explicit mutable exception is
HistogramAccumulator, whose methods update caller-owned aggregation state.Do not yet use
HistogramAccumulator.fill_continuous_sample or fill_discrete_sample to replay raw correlated event entries when more than one entry can land in the same bin. The helper counts the call as one sample but currently accumulates the entries’ squared weights separately, unlike the native observable path, which groups their weights before recording one bin sample. Keep production histograms in the configured native observable pipeline until this statistical contract is aligned.Aggregate independent histogram samples
This safe standalone use keeps one entry per bin in each independent sample. Merge pending worker state before committing it, then retain raw sums and squared sums for later combinations:
from gammaloop import HistogramAccumulator
left = HistogramAccumulator.continuous("energy", 0.0, 4.0, 4)
right = HistogramAccumulator.continuous("energy", 0.0, 4.0, 4)
left.fill_continuous_sample([(0.5, 2.0)])
right.fill_continuous_sample([(2.5, 3.0)])
left.merge_in_place(right)
left.update_results()
snapshot = left.snapshot()
assert snapshot.sample_count == 2
assert snapshot.bins[0].sum_weights == 2.0
assert snapshot.bins[0].sum_weights_squared == 4.0
assert snapshot.bins[0].sum_weights / snapshot.sample_count == 1.0
assert snapshot.bins[2].sum_weights == 3.0
assert snapshot.bins[2].sum_weights_squared == 9.0
assert right.snapshot().sample_count == 0
assert len(left.rebin(2).snapshot().bins) == 2snapshot() includes both committed and pending samples. update_results() moves pending values into the completed counters; it is not needed merely to inspect the current snapshot. A successful merge_in_place consumes only the donor’s pending samples, so merge worker accumulators before committing them.
Inspect and evaluate an existing state
The following workflow assumes that ./state contains a generated integrand. Evaluation points are integrand-specific: their length must match the selected integrand and any discrete dimensions. Use the generated reference for the exact single-sample and batch contracts.
from collections.abc import Sequence
from gammaloop import GammaLoopAPI
api = GammaLoopAPI(state_folder="./state", read_only_state=True)
api.run("display processes")
print(api.get_run_history())
runtime = api.get_default_runtime_settings()
print(runtime.get("integrator.n_start"))
def evaluate_one(point: Sequence[float]) -> complex:
result = api.evaluate_sample(
point,
process_id=0,
minimal_output=True,
)
return result.integrand_resultThe documentation checks compile this example as Python syntax. They do not import or execute the native module: a runtime check additionally needs a built GammaLoop package, a provisioned backend and license, an existing generated state, and a point with the correct dimension.
The run method uses the same command language as the CLI and can change the in-memory state, settings, and run history. read_only_state=True protects files inside the active state directory; it does not make the Python object immutable or automatically persist the session. Inspect the live session through get_run_history, get_global_settings, and get_active_command_blocks.
For structured inspection, get_integrand_info describes the selected backend and graph structure, while get_integrand_settings and get_default_runtime_settings return detached, read-only SettingsValue snapshots. Use get(path), attribute access, indexing, or to_dict() to read them; modifying derived Python values does not update the live session.
Inspect native residue maps
get_residue_map(graph_name, process_id=None, integrand_name=None, returns a detached
three_dimensional_representation=None)ResidueMap for one generated graph. Select "cff" or "ltd" explicitly, or omit the representation to use the first mode in the stored generation order. The requested representation must already have been generated; this getter does not regenerate the graph. Process and integrand selectors resolve the same session ambiguities as the other inspection methods.
from gammaloop import GammaLoopAPI
api = GammaLoopAPI(state_folder="./state", read_only_state=True)
residue_map = api.get_residue_map(
"graph_name",
process_id=0,
integrand_name="integrand_name",
three_dimensional_representation="ltd",
)
for key, residues in residue_map.entries.items():
print(key.canonical_string)
for residue in residues:
print(residue.native_id, residue.label, len(residue.variants))entries is a Python dictionary from immutable, hashable ResidueMapKey objects to lists of Residue snapshots. A key contains the complete ordered edge directions, loop_energy_map, and edge_energy_map. Equality and hashing use these native values; labels, expression-local IDs, and scalar variants do not enter the key. Equal keys retain every associated native entry in their value list. A hash is a Python lookup value, not a persistent residue identifier.
Each LinearEnergyExpression exposes ordered internal_terms and external_terms pairs of edge ID and exact fractions.Fraction, together with uniform_scale_coeff and constant. These describe on-shell energies, external energies, the uniform numerator-sampling scale M, and the affine constant, respectively. The map arrays retain their native loop-slot and edge-slot order. canonical_string provides the existing native identity spelling for a key and a readable exact spelling for an affine expression. Snapshot classes have no public constructors; their returned containers do not mutate the stored graph or a key’s hash.
Each residue retains native_id, label, numerator_map_index, and all scalar variants. Variants preserve the exact prefactor, origin, repeated half-edge factors, denominator-edge support, both denominator sign-provenance maps, uniform-scale power, numerator surfaces, and the denominator tree. variant.thermal_weight supplies typed ThermalWeight, ThermalNumerator and ThermalDistributionFactor records for CFF media, preserving medium mode, signed energy lists, contour offsets and derivative orders. Vacuum LTD weights contain no thermal factors. Tree nodes retain their IDs, surface references, parents, and children; the getter does not expand the tree or discard repeated factors. Surface references use ("esurface", id), ("hsurface", id), or ("linear", id); unit and infinite references use ("unit", None) and ("infinite", None).
The shared surfaces dictionary supplies cached E/H/linear records, including physical E/H energy occurrences and external shifts, or exact linear expressions with their kind, origin, and numerator-only flag. residual_denominators, energy_factor_ownership, energy_factor_components and source_frame retain the generated scalar expression’s remaining denominators and convention metadata.
This is the stored graph-level native catalogue. It is not a catalogue of all projected UV or threshold-counterterm expressions, nor an evaluated, fully normalized production integrand. Native map IDs and keys remain separate from runtime complete-sum slots. Use the evaluation methods for physical values.
Sample evaluation contract
All three supported interfaces use the same two input layouts:
- An integration-space row contains the unit-hypercube coordinates expected by the selected integrand and discrete dimensions. Its required length is integrand-specific.
- A momentum-space row is
[k1x, k1y, k1z, k2x, k2y, k2z, ...]: exactly one spatial(px, py, pz)triplet per independent loop momentum. It contains neither loop-energy components nor external momenta; GammaLoop obtains the latter from the integrand’s kinematics. Select momentum space explicitly with--momentum-space,momentum_space=true, ormomentum_space=True.
Every momentum-space row must therefore have a coordinate count divisible by three, and its number of complete triplets must match the selected integrand, graph, or graph group. approach axes use the same layout and dimension as their midpoint. The CLI, structured Rust API, and Python API all reach the same input builder and reject incomplete triplets before numerical evaluation.
Precision selection is independent of the coordinate layout. With use_arb_prec=false, the configured stability ladder may evaluate and escalate through f64, f128, and arbitrary precision. Setting use_arb_prec=true forces arbitrary-precision (Arb) internal evaluation, using the configured Arb stability level when available and a default Arb level otherwise. The -f CLI shorthand has the same behavior. CLI output, Python numeric fields, and ordinary Rust EvaluateSamples results remain f64. Only Rust EvaluateSamplesPrecise retains the numeric type used by the selected stability level. Each stability level can also set three_dimensional_representation to a generated cff or ltd representation; omission selects the first entry of the generation-time three_dimensional_representations list. Stability diagnostics report both precision and representation. When forcing Arb without a configured Arb level, the fallback inherits the first stability level’s representation choice.
evaluate_sample returns one sample result with its complete event-group payload. evaluate_samples accepts a two-dimensional NumPy array and returns one result per row without accumulating observable statistics. Per-sample weights, discrete coordinates, graph names, and orientations must have the same row count as the input batch when provided. Graph and orientation selection applies only to momentum-space evaluation.
Both the ordinary Rust and Python endpoints expose numeric results through an f64 contract, even when use_arb_prec=True forces arbitrary-precision internal evaluation. Evaluation may warm the integrand and update in-memory caches, including in a read-only-state session. Observable statistics require explicit accumulation. Rust-only callers that must retain the active precision use evaluate_sample_precise and evaluate_samples_precise.
Point evaluation returns the native contribution including map Jacobians and channel partition factors, before the outer-grid weight. The kinematics, normalization, and weights guide defines the exact relation, with the reported unapplied for parameterized samples, and the correlated event-weight boundary. Direct momentum inputs can omit the reported Jacobian.
For a complete, source-backed run card and scripts that expose event groups, cut metadata, selectors, and merged histogram snapshots, follow the events and observables guide.
Symbolic conversion helpers
The supported module-level helpers are atom_to_canonical_string for parsing and canonicalizing a Symbolica expression, evaluate_graph_overall_factor for evaluating a graph’s symbolic prefactor, and contract for rewriting tensor contractions into Idenso dot-product notation. Their generated entries document accepted strings, return values, failure modes, and task-oriented examples.
CLI and settings reference
Shell completion
--completions emits a static script from the same Clap command tree as --help. Load it for the current shell or save it in the shell’s normal completion directory:
# Bash for the current session
source <(./gammaloop --completions bash)
# Zsh for the current session
source <(./gammaloop --completions zsh)Fish, Elvish, PowerShell, and Nushell are also supported values. For Fish, pipe the output to source; for Nushell, save the generated module and then source it. Bash and Fish output also registers the repository wrapper spelling ./gammaloop.
The generated shell script covers executable subcommands, flags, enumerated values, and path hints. Completion inside the interactive GammaLoop prompt additionally knows the active state’s processes, integrands, settings, model objects, graphs, cuts, and orientations. A static shell script cannot contain that changing session data.
Use ./gammaloop --help and the generated CLI and settings reference for command names, aliases, flags, positional arguments, defaults, possible values, and setting paths. The tutorials explain how commands and settings combine into a persistent workflow. The logging and diagnostics guide covers startup precedence, selective tag filters, sink routing, release-build limitations, and copyable investigation patterns.