Skip to main content

minilink

Write the equations once. Simulate, analyze, control, plan, optimize, learn.

Open In Colab Notebooks PyPI API License: MIT

trajectory optimization task-space impedance control model predictive control reinforcement learning
trajectory optimization impedance control
interactive 3-D
model predictive control
interactive 3-D
reinforcement learning

Minilink is an open-source Python framework for dynamical systems and control. A model is a DynamicSystem: a short class whose equations read like the textbook. Models and controllers, yours or from the catalog, compose into block diagrams with three operators, and a diagram is itself a DynamicSystem. One toolbox works on any of them: simulation and animation, linearization and frequency response, classical and state-space design, value iteration, sampling-based planning, trajectory optimization, model predictive control and reinforcement learning. NumPy, SciPy and Matplotlib are enough for a course; the same equations compile and differentiate under JAX for research.

Write a model

A model is dynamics f, outputs h and body poses tf, functions of the state x, the input u, the time t and the parameters params:

dx/dt = f(x, u, t; params)      dynamics
y     = h(x, u, t; params)      one per output port, default y = x
T     = tf(x, u, t; params)     body poses, for animation

Write f, and the model simulates and plots. Write h to choose what the sensor measures:

import numpy as np
from minilink import DynamicSystem


class MassSpringDamper(DynamicSystem):
    def __init__(self):
        super().__init__(n=2, input_dim=1, output_dim=1)

    def f(self, x, u, t=0, params=None):
        m, k, b = 1.0, 4.0, 0.3
        p, v = x

        # m p̈ + b ṗ + k p = u
        a = (u[0] - b * v - k * p) / m

        return np.array([v, a])

    def h(self, x, u, t=0, params=None):
        p, v = x

        return np.array([p])  # the sensor reads the position only


plant = MassSpringDamper()
plant.x0[0] = 1.0
plant.compute_trajectory(tf=10.0)
plant.plot_trajectory()

Add tf and a skin, and it animates on matplotlib, plotly, meshcat (3-D) or pygame, and you can drive it from the keyboard (10_graphical). f, h and tf read (x, u, t; params) and nothing else: no hidden state on the object. That one convention is what lets a model compose, run in batches and differentiate.

Compose into a diagram

controller @ plant closes a loop, a >> b is a series connection, a + b puts blocks side by side. The controller can be yours, or one of the catalog's:

from minilink import PID

loop = PID(2.0, 0.5, 1.0) @ plant
loop.compute_trajectory(tf=10.0)
loop.plot_diagram()
loop.plot_trajectory()

closed-loop diagram

The operator inserts the error junction, names the two sides controller and plant, and the loop linearizes, animates and nests like any other model. The catalog has the plants a course needs, with their parameters and start as data (Pendulum, CartPole, DoublePendulum, UR5Manipulator, KinematicBicycle, UdeSRacecar, Drone2D, Rocket, Boat2D, …) and the control laws (PID, ImpedanceController, StateFeedbackController, ComputedTorqueController, SlidingModeController, ModelPredictiveController, NeuralPolicyController):

from minilink import Pendulum

pendulum = Pendulum()
pendulum.params["l"] = 2.0
pendulum.x0[0] = 2.0
pendulum.compute_trajectory(tf=10.0)
pendulum.animate()

One toolbox, every System

Every tool is a verb on a System, a leaf or a whole diagram alike. One pendulum, six tools:

one pendulum through six tools

Simulate, plot, animate, play compute_trajectory, plot_trajectory, plot_phase_plane, animate, game
Analyze linearize, bode, pzmap, margins, root_locus, step_response
Design lqr, place, kalman, lqg, PID, ImpedanceController
Plan and learn DynamicProgrammingPlanner, RRTPlanner, TrajectoryOptimizationPlanner, ModelPredictiveController, ReinforcementLearningPlanner

One problem, every planner

A PlanningProblem is a system, a cost and boundary sets. Every planner takes the same problem, from LQR to value iteration, tree search, trajectory optimization and reinforcement learning, and returns a PlanningSolution whose policy is a controller:

from minilink import (
    BallSet, DynamicProgrammingPlanner, PlanningProblem, QuadraticCost,
    RRTPlanner, TrajectoryOptimizationPlanner,
)

plant = Pendulum()
x_down, x_up = np.array([0.0, 0.0]), np.array([np.pi, 0.0])
problem = PlanningProblem(
    sys=plant, x_start=x_down, x_goal=x_up, Xf=BallSet(x_up, 0.2), tf=4.0,
    cost=QuadraticCost.from_system(plant, Q=np.eye(2), R=np.eye(1), xbar=x_up),
    X=plant.state.box,
)

vi = DynamicProgrammingPlanner(problem, x_grid=(101, 101), u_grid=(11,), dt=0.05)
rrt = RRTPlanner(problem, seed=0)
opt = TrajectoryOptimizationPlanner(problem, n_steps=40, transcription="direct_collocation")

policy = vi.solve().policy            # value iteration: the policy is a controller
tree_traj = rrt.solve().trajectory    # kinodynamic tree search, bang-bang inputs
plan = opt.solve().trajectory         # direct collocation

loop = policy @ plant                 # the script closes the loop

Fast and differentiable with JAX, optional

The same f traces under JAX. One compiled evaluator gives exact derivatives, batched rollouts and gradients through a whole simulation:

ev = plant.compile(backend="jax")
x0s = np.tile([1.0, 0.0], (1000, 1))              # 1000 rollouts released at 1 rad
lengths = np.linspace(0.5, 2.0, 1000)             # one rod length per rollout

A = plant.jacobian("f", "x", x_up)                # exact linearization
S = plant.jacobian("f", "params", x_up)           # sensitivity to each physical parameter
xs = ev.rollout_batch(x0s, n_steps=1000, dt=0.005,
                      params=dict(plant.params, l=lengths))   # a family of rod lengths, one call

1000 rollouts of 1000 RK4 steps take 27 ms as a compiled batch, against about 32 s one step at a time in Python (Apple M4 Max, the showcase notebook). Derivatives are exact to machine precision, float64 by default. See 07_compile and the JAX showcase.

Install

Python 3.10+. Recommended: conda, everything included (JAX, Graphviz, Ipopt, 3-D animation, Jupyter):

git clone https://github.com/alx87grd/minilink.git && cd minilink
conda env create -f environment.yml && conda activate minilink
conda env config vars set PYTHONPATH="$PWD" && conda deactivate && conda activate minilink

Colab: open any notebook with "Open in Colab", or start yours with

!git clone https://github.com/alx87grd/minilink
import sys; sys.path.insert(0, "/content/minilink")

pip: pip install minilink runs simulation, plots, LQR and value iteration on NumPy, SciPy and Matplotlib; pip install "minilink[full]" adds JAX, plotly, meshcat, pygame, sympy and gymnasium. Two optional tools need a system install pip cannot do: plot_diagram() needs Graphviz (install, then pip install graphviz) and the Ipopt solver needs conda install -c conda-forge cyipopt (trajectory optimization runs on SciPy without it).

Learn more

Minilink is the successor of pyro.

Metadata

Release files for minilink 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for minilink 0.2.0
File Size Uploaded Provenance Actions
minilink-0.2.0.tar.gz 5.8 MB With provenance Details for minilink-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for minilink 0.2.0
File Interpreter ABI Platform Actions
minilink-0.2.0-py3-none-any.whl Python 3 none any Details for minilink-0.2.0-py3-none-any.whl

Total release size: 6.7 MB

Security for minilink 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page