On this page

GammaLoopAPI

gammaloop Class

GammaLoopAPI(state_folder: Optional[str | os.PathLike | pathlib.Path] = None, boot_commands_path: Optional[str | os.PathLike | pathlib.Path] = None, model_file: Optional[str | os.PathLike | pathlib.Path] = None, trace_logs_filename: Optional[str] = None, level: Optional[LogLevel] = None, logfile_level: Optional[LogLevel] = None, logging_prefix: object | None = None, read_only_state: bool = False, settings_global_path: Optional[str | os.PathLike | pathlib.Path] = None, settings_runtime_defaults_path: Optional[str | os.PathLike | pathlib.Path] = None, clean_state: bool = False)

Load, inspect, and evaluate one mutable GammaLoop session.

One instance owns a GammaLoop state, run history, CLI settings, default runtime settings, and session state. Calls to run and the evaluation methods all act on that same in-memory session.

Notes

read_only_state=True prevents writes inside the active state directory; it does not make this Python object immutable. Commands may still change in-memory settings, processes, or run history. Create separate instances when independent sessions are required.

Constructor

#

Load or create a GammaLoop state and initialize its CLI session.

Returns

GammaLoopAPI

A stateful API instance sharing one state, history, and settings session.

Raises

Exception

If startup options conflict, the state or settings cannot be loaded, a boot command fails, or a boot card requests process exit.

Examples

Open an existing generated state without permitting writes to it:

api = GammaLoopAPI(state_folder="./state", read_only_state=True)

Parameters

NameTypeDefaultDescription
state_folderOptional[str | os.PathLike | pathlib.Path]None

State directory to load or create. The default is ./gammaloop_state.

boot_commands_pathOptional[str | os.PathLike | pathlib.Path]None

TOML run card whose commands are applied during startup.

model_fileOptional[str | os.PathLike | pathlib.Path]None

Model file override used while loading or initializing the state.

trace_logs_filenameOptional[str]None

File receiving native trace records for this session.

levelOptional[LogLevel]None

Terminal log-level override for this session.

logfile_levelOptional[LogLevel]None

File log-level override for this session.

logging_prefixobject | NoneNone

Native logging-prefix configuration.

read_only_stateboolFalse

Prevent writes whose target lies inside the active state directory and disable file logging there. In-memory session changes remain possible.

settings_global_pathOptional[str | os.PathLike | pathlib.Path]None

TOML file overriding the global settings loaded at startup.

settings_runtime_defaults_pathOptional[str | os.PathLike | pathlib.Path]None

TOML file overriding the default runtime settings loaded at startup.

clean_stateboolFalse

Remove the resolved state path before startup. This is destructive and cannot be combined with read_only_state=True.

Member details

evaluate_sample

Method
#
evaluate_sample(point: Sequence[float], process_id: Optional[int] = None, integrand_name: Optional[str] = None, use_arb_prec: bool = False, minimal_output: bool = False, return_events: Optional[bool] = None, momentum_space: bool = False, integrator_weight: Optional[float] = None, discrete_dim: Optional[Sequence[int]] = None, graph_name: Optional[str] = None, orientation: Optional[int] = None) -> EvaluationResult

Evaluate one integration or momentum-space sample.

Returns

EvaluationResult

The sample evaluation and the observable snapshot for its one-row batch.

Raises

Exception

If integrand selection is ambiguous or invalid, dimensions do not match, graph or orientation selection is invalid, or warm-up/evaluation fails.

Notes

With use_arb_prec=False, evaluation follows the configured f64, f128, and arbitrary-precision stability ladder. use_arb_prec=True forces arbitrary-precision (Arb) internal evaluation. Python-visible numeric fields use the package's float64 output contract. Evaluation may warm the integrand and update in-memory caches or observable snapshots even in a read-only-state session.

See Also

GammaLoop's sample-evaluation contract in the interface guide and the maintained events-and-observables example.

Examples

Evaluate one point from the repository's differential API regression fixture:

from pathlib import Path

from gammaloop import GammaLoopAPI

example = Path("examples/api/python/epem_a_ddxg_xs_LO")
api = GammaLoopAPI(
    state_folder=example / "state",
    boot_commands_path=example / "run.toml",
    clean_state=True,
)
point = [0.17, 0.31, 0.53, 0.23, 0.41, 0.67]
result = api.evaluate_sample(point, return_events=True)
assert result.parameterization_jacobian is not None
assert result.stability_results
assert result.event_groups

This card verifies API and event plumbing. Its powered coupling selector is not an independently reviewed perturbative-order definition or normalization benchmark.

Parameters

NameTypeDefaultDescription
pointSequence[float]

Coordinates for one sample. In integration space, the length must match the selected integrand and discrete_dim. In momentum space, values are grouped as (px, py, pz) with one triplet per independent loop momentum. Energy components and external momenta are not accepted.

process_idOptional[int]None

Process containing the integrand. Supply this when selection is ambiguous.

integrand_nameOptional[str]None

Integrand to evaluate. Supply this when selection is ambiguous.

use_arb_precboolFalse

Force arbitrary-precision (Arb) internal evaluation instead of following the configured stability ladder. Returned numeric fields remain float64.

minimal_outputboolFalse

Omit the optional evaluation metadata from the returned sample.

return_eventsOptional[bool]None

Temporarily override event generation for this call. The integrand setting is restored afterward.

momentum_spaceboolFalse

Interpret point as consecutive spatial loop-momentum (px, py, pz) triplets instead of integration-space coordinates.

integrator_weightOptional[float]None

Weight associated with this sample. The default is 1.0.

discrete_dimOptional[Sequence[int]]None

Discrete integration coordinates used to determine the expected dimension.

graph_nameOptional[str]None

Graph selected for momentum-space evaluation.

orientationOptional[int]None

Orientation index for graph_name in momentum-space evaluation.

evaluate_samples

Method
#
evaluate_samples(points: numpy.NDArray[numpy.float64], process_id: Optional[int] = None, integrand_name: Optional[str] = None, use_arb_prec: bool = False, minimal_output: bool = False, return_events: Optional[bool] = None, momentum_space: bool = False, integrator_weights: Optional[numpy.NDArray[numpy.float64]] = None, discrete_dims: numpy.NDArray[numpy.unsignedinteger] | None = None, graph_names: Optional[Sequence[Optional[str]]] = None, orientations: Optional[Sequence[Optional[int]]] = None) -> BatchEvaluationResult

Evaluate a batch of integration or momentum-space samples.

Returns

BatchEvaluationResult

Per-sample evaluations and one observable snapshot for the complete batch.

Raises

Exception

If integrand selection is ambiguous or invalid, array or option lengths do not match, dimensions are invalid, or warm-up/evaluation fails.

Notes

With use_arb_prec=False, evaluation follows the configured f64, f128, and arbitrary-precision stability ladder. use_arb_prec=True forces arbitrary-precision (Arb) internal evaluation. Python-visible numeric fields use the package's float64 output contract. Evaluation may update in-memory caches or observable snapshots in a read-only-state session.

See Also

GammaLoop's sample-evaluation contract in the interface guide and the maintained events-and-observables example.

Examples

Evaluate two rows and inspect their per-sample events and batch-level histograms:

from pathlib import Path

import numpy as np
from gammaloop import GammaLoopAPI

example = Path("examples/api/python/epem_a_ddxg_xs_LO")
api = GammaLoopAPI(
    state_folder=example / "state",
    boot_commands_path=example / "run.toml",
    clean_state=True,
)
points = np.array([
    [0.17, 0.31, 0.53, 0.23, 0.41, 0.67],
    [0.11, 0.29, 0.47, 0.19, 0.37, 0.59],
], dtype=float)
result = api.evaluate_samples(points, return_events=True)
assert len(result.samples) == 2
assert all(sample.event_groups for sample in result.samples)
assert result.observables["leading_jet_pt_hist"].sample_count == 2
assert len(result.observables["leading_jet_pt_hist"].bins) == 8

The fixture exercises the API surface; its powered coupling selector is not a validated perturbative-order or normalization benchmark.

Parameters

NameTypeDefaultDescription
pointsnumpy.NDArray[numpy.float64]

Two-dimensional array with one sample per row. Integration-space columns must match the selected integrand; momentum-space columns are flattened (px, py, pz) groups with one triplet per independent loop momentum. Energy components and external momenta are not accepted.

process_idOptional[int]None

Process containing the integrand. Supply this when selection is ambiguous.

integrand_nameOptional[str]None

Integrand to evaluate. Supply this when selection is ambiguous.

use_arb_precboolFalse

Force arbitrary-precision (Arb) internal evaluation instead of following the configured stability ladder. Returned numeric fields remain float64.

minimal_outputboolFalse

Omit the optional evaluation metadata from every returned sample.

return_eventsOptional[bool]None

Temporarily override event generation for this call. The integrand setting is restored afterward.

momentum_spaceboolFalse

Interpret each row as consecutive spatial loop-momentum (px, py, pz) triplets instead of integration-space coordinates.

integrator_weightsOptional[numpy.NDArray[numpy.float64]]None

One weight per row. Defaults to 1.0 for every sample.

discrete_dimsnumpy.NDArray[numpy.unsignedinteger] | NoneNone

Two-dimensional array with one row of discrete coordinates per sample.

graph_namesOptional[Sequence[Optional[str]]]None

Momentum-space graph selection for each sample.

orientationsOptional[Sequence[Optional[int]]]None

Momentum-space orientation selection for each sample.

import_graphs

Method
#
import_graphs(graphs: str, process_name: Optional[str] = None, process_id: Optional[int] = None, integrand_name: Optional[str] = None, format: str = 'dot', overwrite: bool = False, append: bool = False) -> None

Import DOT graphs into a new or existing process/integrand collection.

Raises

Exception

If selectors conflict, the source is missing or malformed, or importing fails.

Parameters

NameTypeDefaultDescription
graphsstr

DOT file path when format="dot" or inline DOT text when format="string".

process_nameOptional[str]None

Process to create or update. Inline text requires one of these selectors.

process_idOptional[int]None

Process to create or update. Inline text requires one of these selectors.

integrand_nameOptional[str]None

Integrand within the selected process.

formatstr'dot'

Select file-backed or inline input.

overwriteboolFalse

Replace an existing collection or append to it; these modes conflict.

appendboolFalse

Replace an existing collection or append to it; these modes conflict.

get_lmbs

Method
#
get_lmbs(graphs: str, format: str = 'dot') -> list[list[tuple[list[int], list[int], dict[int, tuple[list[int], list[int]]]]]]

Generate loop-momentum bases for each supplied graph.

Returns

list

Per graph, a list of (loop_edges, external_edges, edge_signatures) tuples. Each signature contains its loop and external coefficients.

Parameters

NameTypeDefaultDescription
graphsstr

DOT file path or inline DOT text, as selected by format.

formatstr'dot'

Select file-backed or inline input.

get_orientations

Method
#
get_orientations(graph_name: str, process_id: Optional[int] = None, integrand_name: Optional[str] = None) -> list[dict[int, int]]

Return the causal-flow orientations generated for one graph.

Each returned dictionary maps an edge id to 1 (default), -1 (reversed), or 0 (undirected). Supply process and integrand selectors when the active state does not identify a unique integrand.

Returns

list[dict[int, int]]

One edge-direction mapping per generated orientation.

Parameters

NameTypeDefaultDescription
graph_namestr

Name of the graph within the selected integrand.

process_idOptional[int]None

Numeric process identifier; omit when process selection is unambiguous.

integrand_nameOptional[str]None

Integrand containing the graph; omit when integrand selection is unambiguous.

get_model

Method
#
get_model() -> str

Serialize the active physics model as JSON.

Returns

str

JSON representation of the model currently owned by this session.

evaluate

Method
#
evaluate(process_id: Optional[int] = None, graphs_group_name: Optional[str] = None, result_path: Optional[str | os.PathLike | pathlib.Path] = None, numerical: bool = True, number_of_terms_in_epsilon_expansion: Optional[int] = None) -> str

Evaluate one generated graph group as a symbolic or numerical expression.

Returns

str

Canonical Symbolica representation of the result.

Parameters

NameTypeDefaultDescription
process_idOptional[int]None

Process containing the requested graph group.

graphs_group_nameOptional[str]None

Group to evaluate when the current state is ambiguous.

result_pathOptional[str | os.PathLike | pathlib.Path]None

Optional destination for the evaluated expression.

numericalboolTrue

Evaluate numerically instead of retaining a symbolic result.

number_of_terms_in_epsilon_expansionOptional[int]None

Truncate the dimensional-regulator expansion to this many terms.

import_model

Method
#
import_model(model_specifier: str | os.PathLike | pathlib.Path, simplify_model: bool = True) -> None

Replace the active model from a GammaLoop model file or supported model source.

simplify_model applies the standard symbolic simplification pass while importing. Existing process data may no longer be compatible with a replaced model, so import the model before generating processes.

Parameters

NameTypeDefaultDescription
model_specifierstr | os.PathLike | pathlib.Path

Path or model specifier accepted by GammaLoop's model importer.

simplify_modelboolTrue

Apply the standard symbolic simplification pass while importing.

list_outputs

Method
#
list_outputs() -> tuple[dict[str, int], dict[str, int]]

List generated amplitude and cross-section names with their process ids.

Returns

tuple[dict[str, int], dict[str, int]]

Amplitude mapping followed by the cross-section mapping.

get_integrand_info

Method
#
get_integrand_info(process_id: Optional[int] = None, integrand_name: Optional[str] = None) -> IntegrandInfo

Describe the selected generated integrand and its graph structure.

Returns

IntegrandInfo

Structured process, backend, graph, orientation, cut, and size metadata.

Raises

Exception

If no unique generated integrand matches the selection.

Examples

Inspect the generated graph groups in the repository's differential API fixture:

from pathlib import Path

from gammaloop import GammaLoopAPI

example = Path("examples/api/python/epem_a_ddxg_xs_LO")
api = GammaLoopAPI(
    state_folder=example / "state",
    boot_commands_path=example / "run.toml",
    clean_state=True,
)
info = api.get_integrand_info()
assert info.kind == "cross section"
assert info.graph_count == 2
assert info.graph_group_count == len(info.graph_groups)
assert all(
    sum(graph.is_master for graph in group.graphs) == 1
    for group in info.graph_groups
)

This fixture's powered coupling selector is a regression input, not a reviewed physical perturbative-order definition.

Parameters

NameTypeDefaultDescription
process_idOptional[int]None

Process containing the integrand. Supply this when selection is ambiguous.

integrand_nameOptional[str]None

Integrand to inspect. Supply this when selection is ambiguous.

get_integrand_settings

Method
#
get_integrand_settings(process_id: Optional[int] = None, integrand_name: Optional[str] = None) -> SettingsValue

Return a detached, read-only snapshot of one integrand's settings.

Returns

SettingsValue

Serialized settings snapshot supporting get(path), attribute access, indexing, and to_dict(). Mutating it does not update the live session.

Raises

Exception

If selection fails, the integrand has not been generated, or its settings cannot be serialized.

Examples

Read a nested setting without changing the live integrand:

settings = api.get_integrand_settings(process_id=0)
print(settings.get("general.generate_events"))

Parameters

NameTypeDefaultDescription
process_idOptional[int]None

Process containing the integrand. Supply this when selection is ambiguous.

integrand_nameOptional[str]None

Integrand whose settings are required.

get_run_history

Method
#
get_run_history() -> str

Render the current in-memory run history as TOML.

Returns

str

TOML representation of the history owned by this API instance.

Raises

Exception

If the current history cannot be serialized.

Notes

This reports the live session, including commands run through run; it does not imply that the history has been persisted to the state directory.

Examples

Capture a reproducible run card from the current session:

run_card_toml = api.get_run_history()

get_global_settings

Method
#
get_global_settings() -> str

Render the current effective CLI and global settings as TOML.

Returns

str

TOML representation of the settings used by this API session.

Raises

Exception

If the settings cannot be rendered.

Examples

Record the effective settings after applying startup overrides:

settings_toml = api.get_global_settings()

get_active_command_blocks

Method
#
get_active_command_blocks() -> dict[str, list[str]]

Return the named command blocks in the current run history.

Returns

dict[str, list[str]]

Mapping from block name to its rendered CLI commands.

Examples

Inspect the commands currently grouped under each block:

for name, commands in api.get_active_command_blocks().items():
    print(name, commands)

get_default_runtime_settings

Method
#
get_default_runtime_settings() -> SettingsValue

Return a detached, read-only snapshot of the default runtime settings.

Returns

SettingsValue

Serialized settings including defaults. Use get(path) or to_dict() to inspect it; changes to derived Python values do not affect the session.

Raises

Exception

If the settings cannot be serialized.

Examples

Inspect a runtime default by its documented settings path:

runtime = api.get_default_runtime_settings()
print(runtime.get("integrator.n_start"))

get_dot_files

Method
#
get_dot_files(process: Optional[int | str] = None, integrand_name: Optional[str] = None, settings: DotExportSettings = ...) -> str

Render a selected amplitude or cross section as Graphviz DOT text.

Returns

str

DOT source suitable for Graphviz or GammaLoop's drawing pipeline.

Parameters

NameTypeDefaultDescription
processOptional[int | str]None

Process id or name; omit only when selection is unambiguous.

integrand_nameOptional[str]None

Integrand to render.

settingsDotExportSettingsruntime default

Controls diagram combination, UV terms, algebra, and generated fields.

run

Method
#
run(command: str) -> None

Parse and execute a CLI command in this API instance's session.

Returns

None

The command's normal output is emitted through the configured CLI/logging sinks; inspect structured state through the corresponding getter methods.

Raises

Exception

If the command cannot be parsed or execution fails.

Notes

Commands share and may mutate the instance's in-memory state, settings, and run history. read_only_state=True only blocks writes inside the active state directory. The API does not automatically persist the session after this call; persistence depends on the executed command's explicit output behavior.

Examples

Display the processes loaded in the current state:

api.run("display processes")

Parameters

NameTypeDefaultDescription
commandstr

GammaLoop CLI command text.

generate_cff

Method
#
generate_cff(dot_string: str, subgraph_nodes: Sequence[str], reverse_dangling: Sequence[int], orientation_pattern: Optional[str] = None) -> list[tuple[dict[int, int], str]]

Build a causal-flow expression from an inline DOT graph or one of its subgraphs.

Returns

list[tuple[dict[int, int], str]]

Edge-direction maps paired with their energy-denominator expressions.

Parameters

NameTypeDefaultDescription
dot_stringstr

Inline DOT graph using particles from the active model.

subgraph_nodesSequence[str]

Vertex names retained in the subgraph; an empty sequence selects all nodes.

reverse_danglingSequence[int]

Dangling edge ids whose orientation is reversed.

orientation_patternOptional[str]None

Pattern restricting returned causal-flow orientations.

generate_cff_as_json_string

Method
#
generate_cff_as_json_string(dot_string: str, subgraph_nodes: Sequence[str], reverse_dangling: Sequence[int], orientation_pattern: Optional[str] = None) -> str

Serialize a causal-flow expression and its surfaces as JSON.

This accepts the same graph, subgraph, and dangling-edge inputs as generate_cff. The current JSON representation is intended for GammaLoop tooling and may contain internal structural details.

Returns

str

JSON representation of the causal-flow expression and E-surfaces.

Parameters

NameTypeDefaultDescription
dot_stringstr

Inline DOT graph using particles from the active model.

subgraph_nodesSequence[str]

Vertex names retained in the subgraph; an empty sequence selects all nodes.

reverse_danglingSequence[int]

Dangling edge ids whose orientation is reversed.

orientation_patternOptional[str]None

Pattern restricting returned causal-flow orientations.