Skip to content

Latest commit

 

History

History
750 lines (585 loc) · 13.2 KB

File metadata and controls

750 lines (585 loc) · 13.2 KB

API reference

This is a compact reference to the public API used by the examples. It is organized by package rather than by implementation file. Private modules and helpers whose names begin with _ are intentionally omitted.

For interface rules and shapes, see Conventions.

barrier_states.models

Core models

from barrier_states.models import (
    AdaptiveCruiseControlForceRate,
    CartPole,
    DifferentialDrive,
    DoubleIntegrator,
    LinearSystem,
    MultiAgentSingleIntegrator,
    PlanarQuadrotor,
    Quadrotor12D,
    discretize,
    toy_linear_system,
)

LinearSystem

LinearSystem(A, B, name="linear_system")

Continuous linear control-affine model with matrix data available as A and B.

DoubleIntegrator

DoubleIntegrator(dimension=2)

Creates a continuous double-integrator model in the requested spatial dimension.

DifferentialDrive

DifferentialDrive(wheel_radius=0.2, half_track_width=0.2)

Planar differential-drive model.

CartPole

CartPole(cart_mass=1.0, pole_mass=0.05, gravity=9.81, pole_length=1.0)

Nonlinear cart-pole model.

PlanarQuadrotor

PlanarQuadrotor(mass=1.0, gravity=9.81)

Continuous planar quadrotor model.

Quadrotor12D

Quadrotor12D(
    mass=1.0,
    gravity=9.81,
    inertia_x=1.0,
    inertia_y=1.0,
    inertia_z=1.0,
    wind_force=None,
    wind_torque=None,
)

Twelve-state 3D quadrotor model.

AdaptiveCruiseControlForceRate

AdaptiveCruiseControlForceRate(
    mass=1650.0,
    f0=0.1,
    f1=5.0,
    f2=0.25,
    desired_speed=22.0,
    leader_acceleration=0.0,
)

ACC model used by the BaS-PID example.

MultiAgentSingleIntegrator

MultiAgentSingleIntegrator(num_agents=2, dimension=2)

Stacked continuous single-integrator agents. Useful attributes include num_agents, dimension, and agent_indices.

toy_linear_system

model = toy_linear_system()

Small linear system used by introductory examples.

discretize

discrete_model = discretize(model, dt, method="euler")

Creates a discrete model from a supported continuous model.


barrier_states.constraints

from barrier_states.constraints import (
    StateConstraint,
    UnsafeStateError,
    acc_time_headway,
    combine_constraints,
    multiagent_distance,
    obstacles_2d,
    obstacles_3d,
    state_limits,
)

StateConstraint

Represents one or more safety functions and their derivatives. Important members include:

constraint.h(x)
constraint.h_x(x)
constraint.h_xx(x)          # when available
constraint.is_safe(x)
constraint.check_safe(x)
constraint.state_dim
constraint.num_constraints
constraint.labels
constraint.has_hessian

state_limits

state_limits(
    state_indices,
    lower=-np.inf,
    upper=np.inf,
    *,
    state_dim,
)

Constructs lower and/or upper state limits.

obstacles_2d

obstacles_2d(
    centers,
    radii,
    *,
    state_dim,
    state_indices=(0, 1),
    clearance=0.0,
)

Constructs circular obstacle-avoidance constraints.

obstacles_3d

obstacles_3d(
    centers,
    radii,
    *,
    state_dim,
    state_indices=(0, 1, 2),
    clearance=0.0,
)

Constructs spherical obstacle-avoidance constraints.

acc_time_headway

acc_time_headway(
    time_headway=1.8,
    standstill_distance=0.0,
    *,
    state_dim=5,
    state_indices=(1, 2),
)

ACC following-distance safety constraint.

multiagent_distance

multiagent_distance(
    num_agents=2,
    minimum_distance=0.25,
    *,
    dimension=2,
    pairs=None,
)

Constructs pairwise minimum-distance constraints for stacked agent positions.

combine_constraints

combine_constraints(
    *constraints,
    name="combined_constraints",
    labels=None,
)

Concatenates multiple StateConstraint objects without aggregating their values.


barrier_states.barriers

from barrier_states.barriers import (
    BarrierFunction,
    BarrierSDCFactor,
    logarithmic,
    reciprocal,
    sdc_factor,
)

reciprocal

reciprocal(constraint, alpha=1.0, *, aggregate="none")

Builds reciprocal barriers with

$$ B(h)=\frac{\alpha}{h}. $$

logarithmic

logarithmic(constraint, alpha=1.0, *, aggregate="none")

Builds logarithmic barriers with

$$ B(h)=\alpha\log!\left(\frac{1+h}{h}\right). $$

Aggregation values

aggregate="none"
aggregate="harmonic"
aggregate="barrier_sum"

BarrierFunction

Useful public data and evaluations include:

barrier.constraint
barrier.aggregate
barrier.alpha
barrier.num_barriers
barrier.state_dim
barrier.beta(x)
barrier.beta_x(x)
barrier.beta_xx(x)          # when available
barrier.active_h_x(x)

sdc_factor

sdc_factor(
    barrier,
    reference_state,
    *,
    shift=True,
    method="auto",
    relative_tolerance=1e-8,
    absolute_tolerance=1e-10,
    difference_tolerance=1e-10,
)

Creates the Barrier State SDC factorization used by the SDRE workflow.


barrier_states.bas

from barrier_states.bas import (
    DynamicContinuous,
    DynamicContinuousSDC,
    DynamicDiscrete,
)

DynamicContinuous

DynamicContinuous(
    model,
    barrier,
    gamma=1.0,
    reference_state=None,
)

Continuous Barrier State subsystem. Principal methods:

bas.value(x)
bas.error(x, z)
bas.f(x, z)
bas.g(x, z)
bas.flow(x, z, u)
bas.flow_x(x, z, u)
bas.flow_z(x, z, u)
bas.flow_u(x, z, u)

DynamicDiscrete

DynamicDiscrete(
    model,
    barrier,
    rho=0.0,
    reference_state=None,
)

Discrete Barrier State subsystem. Principal methods:

dbas.value(x)
dbas.error(x, z)
dbas.step(x, z, u)
dbas.step_x(x, z, u)
dbas.step_z(x, z, u)
dbas.step_u(x, z, u)

DynamicContinuousSDC

DynamicContinuousSDC(
    model,
    barrier,
    plant_sdc,
    gamma=1.0,
    reference_state=None,
    reference_input=None,
    factor_method="auto",
)

Continuous BaS realization with the additional SDC data required by SDRE.


barrier_states.embedding

from barrier_states.embedding import EmbeddedContinuous, EmbeddedDiscrete

EmbeddedContinuous

EmbeddedContinuous(model, bas)

Creates the continuous augmented model. Principal methods:

embedded.f(xbar)
embedded.g(xbar)
embedded.flow(xbar, u)
embedded.flow_x(xbar, u)
embedded.flow_u(xbar, u)
embedded.augment_state(x, barrier_state=None)
embedded.split_state(xbar)
embedded.barrier_error(xbar)

For an SDC-aware BaS realization, the embedded object also supplies the state-dependent representation consumed by SDREFeedback.

EmbeddedDiscrete

EmbeddedDiscrete(model, dbas)

Creates the discrete augmented model. Principal methods:

embedded.step(xbar, u)
embedded.step_x(xbar, u)
embedded.step_u(xbar, u)
embedded.augment_state(x, barrier_state=None)
embedded.split_state(xbar)
embedded.barrier_error(xbar)

barrier_states.controllers

from barrier_states.controllers import (
    DDPMPC,
    PIDBaSFeedback,
    SDREFeedback,
    StateFeedback,
    TrajectoryPolicy,
    trajectory_policy,
)

StateFeedback

StateFeedback(
    model,
    gain,
    reference_state=None,
    reference_input=None,
    input_lower=None,
    input_upper=None,
)

PIDBaSFeedback

PIDBaSFeedback(
    model,
    error,
    *,
    integral=None,
    derivative=None,
    bas_signal=None,
    kp=0.0,
    ki=0.0,
    kd=0.0,
    kb=0.0,
    reference_input=None,
    input_lower=None,
    input_upper=None,
)

SDREFeedback

SDREFeedback(
    model,
    Q,
    R,
    *,
    input_lower=None,
    input_upper=None,
    compute_eigenvalues=False,
)

TrajectoryPolicy

TrajectoryPolicy(
    solution,
    *,
    use_feedback=True,
    input_lower=None,
    input_upper=None,
)

Convenience constructor:

policy = trajectory_policy(solution, use_feedback=True)

DDPMPC

DDPMPC(
    model,
    cost,
    horizon,
    initial_controls=None,
    *,
    method="ilqr",
    input_lower=None,
    input_upper=None,
    **ddp_options,
)

See Trajectory optimization for receding-horizon behavior, solver reuse, prediction history, and execution details.


barrier_states.costs

from barrier_states.costs import QuadraticDiscrete, quadratic_discrete

quadratic_discrete

quadratic_discrete(
    Q,
    R,
    Qf,
    x_ref=None,
    u_ref=None,
    x_final_ref=None,
)

The cost object provides

cost.stage(x, u, k=None)
cost.stage_derivatives(x, u, k=None)
cost.stage_expansion(x, u, k=None)
cost.terminal(x, k=None)
cost.terminal_derivatives(x, k=None)
cost.terminal_expansion(x, k=None)
cost.trajectory(states, controls)

barrier_states.solvers

from barrier_states.solvers import DDPHistory, DDPSolution, ddp

ddp

ddp(
    model,
    cost,
    x0,
    controls,
    *,
    method="ilqr",
    max_iters=100,
    tol_cost=1e-6,
    tol_grad=1e-6,
    alphas=(...),
    reg_init=1e-6,
    reg_min=1e-9,
    reg_max=1e9,
    reg_factor=10.0,
    input_lower=None,
    input_upper=None,
    safety_check=True,
    verbose=True,
    store_trajectories=False,
    tol_type="absolute",
)

The controls initial guess has shape (N, m).

method="ilqr" requires first-order discrete dynamics. method="ddp" additionally requires step_xx, step_uu, and step_ux.

See Trajectory optimization for solver behavior and result fields.


barrier_states.simulation

from barrier_states.simulation import (
    rollout_discrete,
    simulate_acc_leader_profile,
    simulate_continuous,
    simulate_discrete,
)

simulate_continuous

simulate_continuous(
    model,
    policy,
    time,
    x0=None,
    method="RK45",
    **solver_options,
)

simulate_discrete

simulate_discrete(
    model,
    policy,
    steps=None,
    x0=None,
)

rollout_discrete

states = rollout_discrete(model, x0, controls)

barrier_states.plotting

The plotting package includes general trajectory/history utilities plus system-specific visualizations.

from barrier_states.plotting import (
    AnimationResult,
    animate_acc,
    animate_cart_pole,
    animate_ddp_trajectory_iterations,
    animate_differential_drive,
    animate_mpc_trajectory_2d,
    animate_multiagent,
    animate_quadrotor_3d,
    plot_acc_response,
    plot_bas_state,
    plot_cart_pole,
    plot_constraint_history,
    plot_control,
    plot_ddp_history,
    plot_differential_drive,
    plot_mpc_trajectory_2d,
    plot_multiagent_trajectories,
    plot_quadrotor_states,
    plot_state_trajectory_2d,
    plot_state_trajectory_3d,
)

General rules:

  • plotting functions do not call plt.show();
  • obstacle geometry is read from constraint plotting metadata where available;
  • every animate_* function returns an AnimationResult;
  • GIF and MP4 export are supported by every animation helper.

AnimationResult

All animation helpers share one signature block and one return type:

result = animate_<system>(
    sim, *, constraints=None, reference_state=None,
    frame_skip=1, playback_speed=1.0, interval=None, figsize=None,
    save=None, fps=30.0, dpi=120,
    repeat=False, title="...",
)
result.animation          # matplotlib.animation.FuncAnimation
result.figure             # matplotlib.figure.Figure
result.axes               # dict of role name -> Axes
result.artists            # dict of role name -> animated artist
result.data               # dict of derived arrays
result.save(path, fps=30.0, dpi=120)   # .gif or .mp4, chosen by suffix

save is a single output path; its suffix selects the writer. GIF export needs only Pillow, which Matplotlib already requires. MP4 export needs the external ffmpeg binary and raises RuntimeError if it is unavailable.

interval is in milliseconds and overrides the timestep-derived value. Otherwise the interval follows the simulation timestep scaled by frame_skip and playback_speed, so playback_speed=1 plays back in real time. animate_ddp_trajectory_iterations is indexed by solver iteration rather than time, so it takes frames_per_iteration and hold_frames instead of playback_speed.

Keep the AnimationResult alive until plt.show() or export; Matplotlib does not retain its own reference to the animation.


Public workflow summary

A typical continuous workflow imports from five main namespaces:

from barrier_states.models import ...
from barrier_states.constraints import ...
from barrier_states.barriers import ...
from barrier_states.bas import ...
from barrier_states.embedding import ...

and then adds a controller, simulator, and plotting utilities.

A trajectory-optimization workflow additionally uses

from barrier_states.costs import ...
from barrier_states.solvers import ...
from barrier_states.controllers import trajectory_policy

or DDPMPC for online receding-horizon control.