API Reference

This reference covers the main classes and interfaces in Asgard.

GimleAPI

Main entry point combining equation creation, compilation, simulation, and evaluation.

from gimle.asgard.api import GimleAPI

Creating

gimle = GimleAPI()

Methods

Method Description
create_equation(equation_str) Create a GimleEquation from a LEAN-style string.
create_circuit(circuit_str) Create a GimleCircuit from a string.
compile(equation) Compile a GimleEquation to a GimleCircuit.
simulate(circuit, input_data, dim_labels, ...) Simulate a circuit. Returns SimulationResult.
evaluate(result, **coordinates) Evaluate stream(s) at specific coordinate points.
validate_input_data(circuit, input_data, dim_labels) Check input data matches circuit expectations.
create_input_data(coefficients, dim_labels) Create properly-shaped input array from coefficients.
plot_1d(stream, x_range, n_points=100) Plot a 1D stream.
plot_2d(stream, x_range, y_range, n_points=50) Plot a 2D stream as heatmap.
plot_solution(equation, input_data, dim_labels, x_range) Compile, execute, and plot in one call.
available_operations() List equation operations with descriptions.
available_circuit_atomics() List circuit atomics with degree info.
available_rewrite_rules() List rewrite rule groups.
available_calculi() List available calculus types.
available_simulation_methods() List available simulation methods.

GimleEquation

High-level interface for mathematical equations.

from gimle.asgard.api import GimleEquation

Creating

eq = GimleEquation.from_string("int(f, x) = g")

Methods

Method Description
from_string(equation_str) Create from LEAN-style string.
to_string() Convert to string representation.
to_latex() Convert to LaTeX representation.
compile_to_circuit() Compile to a GimleCircuit.
rewrite(rule_group="eq_full", strategy="repeat") Apply rewrite rules. Returns (GimleEquation, List[str]).

Properties

Property Description
equation The parsed Equation object.

Supported Operations

Syntax Description
int(f, x) Integrate f with respect to x
diff(f, x) Differentiate f with respect to x
f + g Addition
f - g Subtraction
f * g Multiplication
f / g Division
f ^ g Exponentiation
abstraction x.term Lambda abstraction
apply(f, x) Function application

GimleCircuit

High-level interface for computational circuits.

from gimle.asgard.api import GimleCircuit

Creating

circuit = GimleCircuit.from_string("composition(add, register(x))")

Methods

Method Description
from_string(circuit_str) Create from string representation.
to_string() Convert to string.
to_equation() Decompile back to a GimleEquation.
validate() Validate structure and degree compatibility.
compose(other) Sequential composition (other after self).
parallel(other) Parallel composition (self alongside other).
fan_out(*others) Duplicate input to feed circuits in parallel.
trace() Apply trace operator for feedback/recursion.
get_operations() Extract ordered list of atomic operations.
get_complexity() Get complexity metrics (depth, operation count, etc.).
rewrite(rule_group="circuit_full", strategy="repeat") Apply rewrite rules. Returns (GimleCircuit, List[str]).

Properties

Property Description
circuit The parsed Circuit object.
input_degree Number of input wires.
output_degree Number of output wires.

Circuit Atomics

Atomic In Out Description
add 2 1 Add two streams
multiplication 2 1 Multiply two streams
id 1 1 Identity (pass-through)
split 1 2 Duplicate input
swap 2 2 Swap two wires
terminal 1 0 Discard input
const(c) 0 1 Constant value
scalar(c) 1 1 Multiply by constant
var(f) 1 1 Named variable
param(p) 1 1 Named parameter
register(x) 1 1 Integration (stream shift right)
deregister(x) 1 1 Differentiation (stream shift left)
stochastic_register(x) 1 1 Stochastic integration
convolution(x) 2 1 Convolution
sin(n) 1 1 Sine (n = max degree)
cos(n) 1 1 Cosine (n = max degree)
exp(n) 1 1 Exponential (n = max degree)
power(n) 1 1 Power function
abs 1 1 Absolute value
log 1 1 Logarithm

Stream

Represents polynomial coefficient data as a JAX array with dimension labels.

from gimle.asgard.runtime.stream import Stream

Creating

import jax.numpy as jnp

stream = Stream(
    data=jnp.array([[1.0, 2.0, 3.0, 4.0]]),
    dim_labels=("x",),
    chunk_size=1,
)

Methods

Method Description
has_dimension(label) Check if stream has a dimension with given label.
get_dimension_index(label) Get the index of a dimension by its label.
validate_compatible(other) Validate another stream is compatible for element-wise ops.
broadcast_with(other) Broadcast two streams to compatible chunk sizes.

Properties

Property Description
data JAX array with shape (chunk_size, dim1, dim2, ...).
dim_labels Tuple of dimension names.
chunk_size Size of the time dimension (first axis).
shape Shape of the stream data.
spatial_shape Shape of spatial dimensions (excluding time axis).
ndim Total number of dimensions.
spatial_ndim Number of spatial dimensions.

Calculus Types

Different calculus implementations for stream evaluation.

from gimle.asgard.runtime.stream_evaluator import (
    RealCalculus,
    StochasticCalculus,
    DiscreteCalculus,
)

RealCalculus

Standard real analysis with Taylor expansion.

real = RealCalculus(center=0.0)
Method Description
evaluate_basis_at_point(degree, point) Evaluate Taylor basis: (x-center)^degree / degree!
evaluate_at_point(coefficients, point) Evaluate polynomial expansion at a given point.

StochasticCalculus

Monte Carlo path simulation for stochastic differential equations.

stochastic = StochasticCalculus(
    drift=0.0,
    diffusion=1.0,
    n_paths=1000,
    dt=0.01,
    seed=42,
    interpretation="ito",  # or "stratonovich"
)
Method Description
simulate_sde(x0, drift_fn, diffusion_fn, t_start, t_end) Simulate SDE: dX = drift(X,t) dt + diffusion(X,t) dW.
simulate_coupled_sde(x0_vector, drift_fns, diffusion_fns, ...) Simulate coupled system of SDEs with correlated noise.
generate_brownian_paths(t_start, t_end) Generate Brownian motion paths.
generate_brownian_increments(n_steps) Generate Brownian motion increments dW.
generate_correlated_increments(n_equations, n_steps, correlation) Generate correlated Brownian increments.
euler_maruyama_step(x, drift, diffusion, dW) Single Euler-Maruyama step.
heun_step(x, drift_fn, diffusion_fn, t, dW) Single Heun predictor-corrector step (Stratonovich).
Property Description
drift Drift coefficient.
diffusion Diffusion coefficient.
n_paths Number of Monte Carlo paths.
dt Time step for discretization.
seed Random seed for reproducibility.
interpretation "ito" (Euler-Maruyama) or "stratonovich" (Heun).

DiscreteCalculus

Evaluation of discrete sequences.

discrete = DiscreteCalculus(start_index=0)
Method Description
evaluate_basis_at_point(degree, point) Returns 1 if point == degree, else 0.
evaluate_at_point(coefficients, point) Evaluate discrete sequence at specific time step.

SimulationResult

Unified result from circuit simulation, handling both deterministic and stochastic outputs.

from gimle.asgard.api import SimulationResult

Properties

Property Type Description
coefficients Optional[List[Stream]] Coefficient streams (deterministic only)
trajectories Optional[Array] Evaluated trajectories (both deterministic and stochastic)
is_stochastic bool Whether this is a stochastic simulation
n_paths int Number of trajectories (1 for deterministic, >1 for stochastic)
dim_labels Tuple[str, ...] Dimension labels for spatial axes
times Optional[Array] Time grid points (stochastic only)
coordinates Optional[Dict[str, Array]] Coordinate points where trajectories were evaluated

Methods

Method Description
evaluate(**coords) Evaluate coefficients at specific coordinates (deterministic only).
get_trajectory(path_idx=0) Get a single trajectory by index.
get_statistics() Compute mean, std, and quantiles across Monte Carlo paths.

Usage

# Deterministic
result = gimle.simulate(circuit, [data], dim_labels=("x",))
values = result.evaluate(x=jnp.linspace(0, 3, 100))

# Stochastic
result = gimle.simulate(circuit, [data], dim_labels=("t",),
    calculus=stochastic_calc, t_range=(0, 10), x0=1.0,
    drift_fn=lambda x, t: -x, diffusion_fn=lambda x, t: 0.5)
stats = result.get_statistics()  # mean, std, q05, q50, q95

Circuit Optimization

GradientBasedOptimizer

Optimizes circuit parameters (scalar, const values) using JAX numerical gradients. See Gradient Optimization.

from gimle.asgard.circuit.circuit_gradients import GradientBasedOptimizer
optimizer = GradientBasedOptimizer(
    learning_rate=0.01,
    num_iterations=100,
    tolerance=1e-6,
)
optimized_circuit, loss_history = optimizer.optimize(circuit, dataset)
Method Description
optimize(circuit, dataset, verbose=True) Optimize parameters to fit dataset. Returns (Circuit, List[float]).

Structure Search Optimizers

Optimizes circuit structure by exploring rewrite-rule neighbors. All share the same optimize(initial_circuit, max_iterations=100) interface, returning an OptimizationResult. See Circuit Search.

from gimle.asgard.circuit.circuit_optimizer import (
    GreedyCircuitOptimizer,
    BeamSearchOptimizer,
    GeneticCircuitOptimizer,
)
from gimle.asgard.circuit.circuit_search import CircuitSearchSpace
Optimizer Key Parameters Strategy
GreedyCircuitOptimizer(search_space, fitness) Hill-climbing, stops when no neighbor improves.
BeamSearchOptimizer(search_space, fitness, beam_width=5) beam_width Maintains top-k candidates each iteration.
GeneticCircuitOptimizer(search_space, fitness, population_size=20, mutation_rate=0.3, elite_size=2) population_size, mutation_rate, elite_size Tournament selection with elite preservation.

Fitness Evaluators

Score circuits against a dataset.

from gimle.asgard.circuit.circuit_fitness import (
    DatasetSample,
    MSEFitnessEvaluator,
    MultiObjectiveFitnessEvaluator,
)

DatasetSample — a single training example:

Field Type Description
inputs List[Stream] Input streams for the circuit.
expected_outputs List[Stream] Expected output streams.
weight float Sample weight in loss computation (default 1.0).

Evaluators:

Evaluator Description
MSEFitnessEvaluator(dataset) Mean squared error loss.
MAEFitnessEvaluator(dataset) Mean absolute error loss.
CustomFitnessEvaluator(dataset, loss_fn) User-defined loss function.
MultiObjectiveFitnessEvaluator(dataset, primary_evaluator, complexity_weight=0.1) Primary loss + circuit complexity penalty.

All evaluators expose evaluate(circuit) → FitnessResult and compare(circuit1, circuit2) → int.

CLI Commands

parse

Parse equations or circuits.

asgard parse "int(f, x) = g"
asgard parse -c "composition(add, id)"
asgard parse "f = g" --json

compile

Compile equations to circuits.

asgard compile "int(f, x) = g"
asgard compile "int(f, x) = g" --json

run

Execute circuits with data.

asgard run "scalar(2.0)" --input "1,2,3"

rewrite

Apply rewrite rules to an equation or circuit.

asgard rewrite "diff(int(f, x), x)"
asgard rewrite "diff(int(f, x), x)" -r eq_elimination_rules
asgard rewrite "diff(int(f, x), x)" --repeat
asgard rewrite "diff(int(f, x), x)" --show-all
asgard rewrite -c "composition(id, id)" -r circuit_full
Flag Description
expression Equation or circuit string (positional)
-c, --circuit Treat input as a circuit instead of an equation
-r, --rules Rule group to apply (default: eq_full or circuit_full)
--repeat Apply rules repeatedly until no more changes
--show-all Show all possible single-step rewrites

list

List available components.

asgard list operations   # Equation operations
asgard list atomics      # Circuit atomics
asgard list rules        # Rewrite rules
asgard list calculi      # Calculus types

monitor

Launch the results monitoring dashboard.

asgard monitor --storage ./results --port 8080

example

Run YAML-defined examples.

asgard example --list
asgard example basic/01_integration.yaml
asgard example -c basic
asgard example -c stochastic --monitor

Storage

AsgardStorage

High-level storage for monitor runs and results. Used by the CLI, YAML example runner, and monitor dashboard.

from gimle.asgard.monitor.storage import AsgardStorage

Creating

storage = AsgardStorage("./results")
storage = AsgardStorage("/tmp/asgard-runs", callback=my_callback)

Methods

Method Description
create_run(name, equation, circuit, metadata) Create a new Run.
save_run(run) Persist a Run to disk.
load_run(run_id) Load a Run by ID.
list_runs() List all saved runs.
delete_run(run_id) Delete a run and its results.
add_result(run, result_type, data, display, array_fields) Attach a Result to a run.
save_result(result) Persist a Result to disk.
load_result(result_id, load_arrays) Load a result by ID.
delete_result(result_id) Delete a result.
save_simulation_result(name, result_type, data, ...) Create run + result in one call.
get_run_with_results(run_id) Load run with all its results.

Low-Level Storage

For direct file or S3 access without monitor integration:

from gimle.asgard.core.data.file import FileStorage
from gimle.asgard.core.data.s3 import S3Storage

See the Storage guide for details.

Rewrite Rules

Available rule groups for symbolic manipulation.

Equation Rules

Rule Group Description
eq_integration_rules Integration and differentiation rules.
eq_elimination_rules Simplification rules.
eq_ring_rules Algebraic ring properties.
eq_full All equation rules combined.

Circuit Rules

Rule Group Description
circuit_category_rules Composition associativity, identity laws.
circuit_monoidal_rules Tensor product associativity, interchange laws.
circuit_atomic_rules Commutativity of add/multiply, zero/one identities.
circuit_trace_rules Trace naturality, cyclic properties.
circuit_compose_rules Power series composition identity and associativity.
circuit_sde_rules Constant drift/diffusion specializations for SDE circuits.
circuit_full All circuit rules combined (excludes circuit_sde_rules).

Compilation Rules

Rule Group Description
equation_to_circuit Compile equation to circuit.
circuit_to_equation Decompile circuit to equation.

Usage

from gimle.asgard.api import GimleEquation

eq = GimleEquation.from_string("diff(int(f, x), x)")

# Apply specific rule group
new_eq, rules_applied = eq.rewrite("eq_elimination_rules")
# Result: f

# Apply all rules
new_eq, rules_applied = eq.rewrite("eq_full")