API Reference¶
High-level façade for the inverse_kinematics-kinematics package.
This class mirrors the forward_kinematics module’s app: it centralizes file I/O, preset builders, and IK solvers (closed-form and iterative) behind a small, testable API. Importantly, it does not import inverse_kinematics.apis to avoid circular imports with any service layer.
- class inverse_kinematics.app.AppInfo(name: str = 'inverse_kinematics-kinematics', version: str = '0.1.0', homepage: str = 'https://example.local/inverse')[source]¶
Immutable metadata about the application.
- homepage: str = 'https://example.local/inverse'¶
- name: str = 'inverse_kinematics-kinematics'¶
- version: str = '0.1.0'¶
- class inverse_kinematics.app.InverseApp(in_dir: str | Path | None = None, out_dir: str | Path | None = None)[source]¶
High-level application façade for inverse_kinematics kinematics workflows.
Responsibilities¶
Load/validate robot_dynamics specs and build
SerialChain.Closed-form IK helpers for supported models (e.g. planar 2R).
Iterative IK (Newton–Raphson / DLS) for general chains.
Preset builders mirroring those in
inverse_kinematics.design.Class diagram export (DOT text) and Mermaid markdown emitter.
Problem-API utilities used by the CLI/tests (solve / batch / from-file).
- class_diagram_dot() str[source]¶
Return a Graphviz DOT class diagram covering the inverse_kinematics package.
- generate_class_diagram(out_markdown: Path) Path[source]¶
Discover classes in the inverse_kinematics package and emit a Markdown file with a Mermaid classDiagram block. We include classes, inheritance, and basic associations inferred from type annotations.
The CLI tests only assert that a valid Mermaid block exists, but this implementation reflects the actual code instead of a static stub.
- load_robot(path: str | Path, *, validate: bool = True) SerialChain[source]¶
Load a robot_dynamics specification (JSON or YAML) and build a
SerialChain.
- preset_planar_2r(l1: int | float, l2: int | float) SerialChain[source]¶
- preset_scara(l1: int | float, l2: int | float, d: int | float = 0.0, wrist_rotary: bool = False) SerialChain[source]¶
- preset_spherical_wrist(wrist_type: int, d_tool: int | float = 0.0) SerialChain[source]¶
- solve(problem: Mapping[str, Any]) List[List[float]][source]¶
- Solve a single problem dict of the form:
{“model”: {…}, “method”: {…}, “pose”: {…}}
- solve_batch(*, model: Mapping[str, Any], poses: Sequence[Mapping[str, Any]], method: Mapping[str, Any]) List[List[List[float]]][source]¶
Solve a batch of poses for a fixed model & method. Returns list-of-lists: one list per pose, each containing solutions.
- solve_closed_form_planar2r(x: float, y: float, l1: float, l2: float) List[ndarray][source]¶
Closed-form planar 2R IK; returns two branches when reachable.
- solve_closed_form_wrist(R: ndarray) List[ndarray][source]¶
Closed-form spherical wrist orientation_kinematics.
- solve_from_path(path: str | Path) List[List[float]][source]¶
Load a single problem JSON file and solve it.
- solve_iterative(chain: SerialChain, T_target: ndarray | Transform, q0: Sequence[int | float] | ndarray, *, tol: float = 1e-06, max_iters: int = 50, damping: float | None = None, position_weight: float = 1.0, orientation_weight: float = 1.0, space: str = 'space')[source]¶
Newton–Raphson / Damped-Least-Squares IK.
- Parameters:
chain (SerialChain)
T_target (4×4 matrix or Transform)
q0 (initial joint vector)
tol (stopping tolerance on twist norm)
max_iters (iteration cap)
damping (if provided, LM damping parameter (λ))
space ("space" or "body" Jacobian convention for the step)
- Returns:
An object with attribute .q (np.ndarray), containing the first/best
joint solution returned by the underlying IterativeIK solver. This
preserves backward-compat behavior expected elsewhere in the app.
- solve_planar2r(*, l1: float, l2: float, x: float, y: float, method: str = 'analytic', q0: Sequence[float] | None = None, tol: float = 1e-06, itmax: int = 200, lambda_damp: float = 0.001, space: str = 'space') List[List[float]][source]¶
Solve planar-2R IK for a single (x, y) target using either the analytic or the iterative solver. Returns a list of solutions, each a list [q1, q2] in radians.
HTTP-and-Python APIs for the inverse_kinematics-kinematics package.
Two entry points:
InverseService — a lightweight, framework-free wrapper around InverseApp used by unit tests and Python callers.
create_rest_app() — optional FastAPI factory (only if FastAPI/Pydantic are installed). Not required for unit tests.
Notes for FastAPI/Pydantic v2: - Avoid deprecated regex= on Field. Use validators instead. - Use field_validator (v2) instead of validator (v1). - Use .model_dump() if you need a dict from a Pydantic model instance.
- class inverse_kinematics.apis.BatchSolveRequest(*, model: Dict[str, Any], method: Dict[str, Any], poses: List[Dict[str, Any]], q0: List[float] | None = None)[source]¶
- method: Dict[str, Any]¶
- model: Dict[str, Any]¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- poses: List[Dict[str, Any]]¶
- q0: List[float] | None¶
- class inverse_kinematics.apis.InverseService(app: ~inverse_kinematics.app.InverseApp = <inverse_kinematics.app.InverseApp object>)[source]¶
Testable Python facade around
inverse_kinematics.app.InverseApp.Notes
Methods return plain lists/ndarrays, matching tests’ expectations.
No imports from web frameworks here (keeps it dead-simple to test).
- app: InverseApp = <inverse_kinematics.app.InverseApp object>¶
- class_diagram_mermaid() str[source]¶
Generate and return a Mermaid class diagram (Markdown block as text).
- problem_from_file(path: str) Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]][source]¶
Load a problem JSON file with keys: ‘model’, ‘method’, ‘pose’. Returns (model, method, pose).
- save_solutions(out_path_or_name: str, solutions: List[ndarray]) str[source]¶
Save solutions JSON and return the actual file path_planning (as string).
The file layout is a simple list-of-lists under {“solutions”: …}.
- solve(model_spec: Dict[str, Any], method_spec: Dict[str, Any], pose_spec: Dict[str, Any], q0: Sequence[float] | None = None) List[ndarray][source]¶
Solve IK for a given model/method/pose spec (single pose).
- Returns:
All solution branches for the pose.
- Return type:
list[np.ndarray]
- solve_batch(model_spec: Dict[str, Any], method_spec: Dict[str, Any], poses: Iterable[Dict[str, Any]], q0: Sequence[float] | None = None) List[List[ndarray]][source]¶
Run IK for a set of pose specs (e.g., a path_planning).
- Returns:
For each pose, the list of solutions.
- Return type:
list[list[np.ndarray]]
- solve_planar2r(l1: float, l2: float, x: float, y: float, *, method: str = 'analytic', tol: float = 1e-06, itmax: int = 200, lambda_damp: float = 0.001, q0: Sequence[float] | None = None, space: str = 'space') List[ndarray][source]¶
Convenience planar-2R entry point.
- Return type:
list[np.ndarray]
- class inverse_kinematics.apis.Planar2RRequest(*, l1: float, l2: float, x: float, y: float, method: str = 'analytic', tol: float = 1e-06, itmax: int = 200, lambda_damp: float = 0.001, q0: List[float] | None = None, space: str = 'space')[source]¶
- itmax: int¶
- l1: float¶
- l2: float¶
- lambda_damp: float¶
- method: str¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- q0: List[float] | None¶
- space: str¶
- tol: float¶
- x: float¶
- y: float¶
- class inverse_kinematics.apis.ProblemModel(*, model: Dict[str, Any], method: Dict[str, Any], pose: Dict[str, Any])[source]¶
Generic IK problem: {‘model’: {…}, ‘method’: {…}, ‘pose’: {…}}
- method: Dict[str, Any]¶
- model: Dict[str, Any]¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- pose: Dict[str, Any]¶
- class inverse_kinematics.apis.SolveRequest(*, model: Dict[str, Any], method: Dict[str, Any], pose: Dict[str, Any], q0: List[float] | None = None)[source]¶
- method: Dict[str, Any]¶
- model: Dict[str, Any]¶
- model_config: ClassVar[ConfigDict] = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- pose: Dict[str, Any]¶
- q0: List[float] | None¶
- inverse_kinematics.apis.create_rest_app()[source]¶
Factory that returns a FastAPI app exposing the service as HTTP endpoints.
- Return type:
fastapi.FastAPI
- Raises:
ImportError – If FastAPI or Pydantic are not installed.
Core math, object model, and inverse_kinematics-kinematics solvers.
What’s inside¶
Rotation, Transform — SO(3)/SE(3) helpers
Link, DHLink, MDHLink — kinematic links (DH/MDH)
SerialChain — FK + Jacobians
SolverBase — base IK interface
Planar2RAnalytic — closed-form 2R planar (T-based API)
AnalyticPlanar2R — test-friendly 2R planar (xy-vector API)
analytic_planar2r(chain,x,y) — free function wrapper
SphericalWrist6RAnalytic — decoupled 6R with spherical wrist
IterativeIK(space=space|body) — Newton / DLS iterative solver
ClosedFormIK — small stateless formulas
- class inverse_kinematics.core.AnalyticPlanar2R[source]¶
- Test adapter used by the suite:
solver.solve(chain, np.array([x, y, 0.0])) -> List[np.ndarray]
- Assumes a standard-DH planar_2r chain built via design.planar_2r:
L1.a = l1, L1.alpha = 0, L1.d = 0
L2.a = l2, L2.alpha = 0, L2.d = 0
chain.M = I
- solve(chain: SerialChain, p_xy: ndarray) List[ndarray][source]¶
- class inverse_kinematics.core.DHLink(a: float, alpha: float, d: float, theta_offset: float = 0.0, joint_type: str = 'R')[source]¶
- class inverse_kinematics.core.IterativeIK(lambda_damp: float = 0.001, tol: float = 1e-06, itmax: int = 200, *, space: str = 'space')[source]¶
- Newton / Damped-Least-Squares IK:
δq = (JᵀJ + λ² I)⁻¹ Jᵀ e
Important
The Jacobian stacks columns as [ω; v], so e must be [w; dp] in that order.
Use space-consistent error with the space Jacobian, and body-consistent error with the body Jacobian.
If the target rotation_kinematics is identity and the chain is low-DOF (e.g., 2R planar), we automatically use position-only error to match typical usage in tests.
- solve(chain: SerialChain, T_goal: ndarray, q0: ndarray) List[ndarray][source]¶
- class inverse_kinematics.core.MDHLink(a: float, alpha: float, d: float, theta_offset: float = 0.0, joint_type: str = 'R')[source]¶
- class inverse_kinematics.core.Planar2RAnalytic(l1: float, l2: float)[source]¶
Closed-form IK for planar 2R using a 4×4 pose (position only).
- solve(chain: SerialChain, T_goal: ndarray, q0: ndarray | None = None) List[ndarray][source]¶
- class inverse_kinematics.core.SerialChain(links: Sequence[Link], M: ndarray | None = None, name: str = 'robot_dynamics')[source]¶
-
- jacobian_space(q: Sequence[float]) ndarray[source]¶
Geometric space Jacobian J(q) (6×n).
Columns are [ω; v]. Linear part uses v = z × (p_e − p_{i−1}).
- prefix(k: int) SerialChain[source]¶
- class inverse_kinematics.core.SolverBase[source]¶
- solve(chain: SerialChain, T_goal: ndarray, q0: ndarray) List[ndarray][source]¶
- class inverse_kinematics.core.SphericalWrist6RAnalytic(d_tool: float, arm_solver: SolverBase)[source]¶
Decoupling approach for a 6R with spherical wrist (Pieper-type).
- solve(chain: SerialChain, T_goal: ndarray, q0: ndarray) List[ndarray][source]¶
- class inverse_kinematics.core.Transform(R: 'np.ndarray', t: 'np.ndarray')[source]¶
- R: ndarray¶
- t: ndarray¶
- inverse_kinematics.core.analytic_planar2r(chain: SerialChain, x: float, y: float) List[ndarray][source]¶
Free function variant used by tests (if present). Assumes standard-DH planar_2r.
I/O, schema, and builders for inverse_kinematics-kinematics problems.
This module complements the forward_kinematics package’s I/O by focusing on the inverse_kinematics side. It supports two levels of modeling input:
High-level models (recommended for IK): {
“kind”: “planar2r” | “arm_3r” | “spherical_wrist” | “six_dof_spherical”, … parameters per kind …
}
Low-level chains (DH/MDH), identical to forward_kinematics core: {
“format”: “dh” | “mdh”, “links”: [ {a, alpha, d, theta_offset?, joint_type?}, … ], “M”: [[…],[…],[…],[…]] # optional tool transform
}
- A complete IK problem file is a JSON/YAML object with:
- {
“model”: <model spec, high-level or low-level>, “method”: {“method”: “analytic” | “iterative”, …params…}, “pose”: {“x”:…, “y”:…, “z”?, “roll”?, “pitch”?, “yaw”?} OR
{“T”: [[…],[…],[…],[…]]}
}
Features¶
JSON and YAML input (auto-detected by extension).
JSON Schema validation for IK problems and low-level chains.
Builders for DH/MDH serial chains and high-level presets (via design.py).
Helpers to save solution sets to JSON.
Examples
IK problem (high-level model): {
“model”: {“kind”: “planar2r”, “l1”: 1.0, “l2”: 1.0}, “method”: {“method”: “analytic”}, “pose”: {“x”: 1.0, “y”: 1.0}
}
IK problem (low-level chain): {
- “model”: {
“format”: “dh”, “links”: [
{“a”: 0.0, “alpha”: 0.0, “d”: 0.0, “joint_type”: “R”}, {“a”: 1.0, “alpha”: 0.0, “d”: 0.0, “joint_type”: “R”}
], “M”: [[1,0,0,1.0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
}, “method”: {“method”: “iterative”, “tol”: 1e-8, “itmax”: 200, “lambda”: 1e-3}, “pose”: {“T”: [[…],[…],[…],[…]]}
}
- inverse_kinematics.io.build_chain_from_high_level(model: Mapping[str, Any]) SerialChain[source]¶
Build a
SerialChainfrom a high-level model mapping (planar2r, arm_3r, spherical_wrist, six_dof_spherical).
- inverse_kinematics.io.build_chain_from_low_level(model: Mapping[str, Any]) SerialChain[source]¶
Build a
SerialChainfrom a low-level DH/MDH model mapping.
- inverse_kinematics.io.build_chain_from_model(model: Mapping[str, Any], *, validate: bool = False) SerialChain[source]¶
Build a
SerialChainfrom either a high-level or low-level model dict.If validate is True, the function validates against the appropriate schema.
- inverse_kinematics.io.chain_schema() Dict[str, Any][source]¶
Schema for low-level DH/MDH chain models.
- inverse_kinematics.io.load_json_or_yaml(path: str | Path) Dict[str, Any][source]¶
Load dict from a JSON or YAML file based on extension.
- inverse_kinematics.io.load_problem_from_file(path: str | Path, *, validate: bool = True) Dict[str, Any][source]¶
Load an IK problem from JSON/YAML file.
- inverse_kinematics.io.method_schema() Dict[str, Any][source]¶
Schema for IK method selection & parameters.
- inverse_kinematics.io.model_schema() Dict[str, Any][source]¶
Schema for high-level model specs used by IK presets.
- inverse_kinematics.io.pose_schema() Dict[str, Any][source]¶
Schema for pose targets: either (x,y[,z,roll,pitch,yaw]) or 4×4 T.
- inverse_kinematics.io.save_problem_json(path: str | Path, problem: Mapping[str, Any]) None[source]¶
Save an IK problem dict to JSON (no validation performed here).
- inverse_kinematics.io.save_solutions_json(path: str | Path, solutions: Sequence[ndarray]) None[source]¶
- Save a set of IK solutions as JSON:
{ “solutions”: [[…], […], …] }
- inverse_kinematics.io.validate_chain_model(model: Mapping[str, Any]) None[source]¶
Validate a low-level DH/MDH chain model against
chain_schema().
- inverse_kinematics.io.validate_high_level_model(model: Mapping[str, Any]) None[source]¶
Validate a high-level model against
model_schema().
- inverse_kinematics.io.validate_problem(problem: Mapping[str, Any]) None[source]¶
Validate an IK problem dict against
problem_schema().
Utility decorators and math helpers for inverse_kinematics kinematics.
This module mirrors the forward_kinematics toolkit’s style but adds IK-oriented helpers: - Decorators:
timed(fn) → records fn runtime (seconds) on wrapper.last_runtime
ensure_shape(*shape) → validates ndarray shape of the return value
- Numerical helpers:
TOL (default tolerance)
almost_equal(a, b)
clamp(x, lo, hi)
normalize(v)
- Lie/SE(3) helpers:
skew(v) / vex(S) (hat / vee)
hat_xi(ω, v) → 4×4 se(3) from screw
adjoint(T) → 6×6 Ad_T
homogeneous(R, t) → 4×4 from (R, t)
so3_log(R) → rotation_kinematics vector (axis-angle in R^3)
se3_log(T) → 6×1 twist (approximate; good for small motions)
- IK helpers:
rpy_to_R(roll, pitch, yaw) → Rz(yaw) Ry(pitch) Rx(roll)
R_to_rpy(R)
pose_error(T_curr, T_des, *, mode=”small”) → 6×1 task-space error
dls_step(J, e, lam) → damped least-squares Δq
manipulability_metrics(J) → {min_sing, cond, detJJT, rank}
These are NumPy-only to keep CI light and tests fast.
References to Chapter 6¶
Geometric Jacobian & conditioning: (6.289–6.296), (singularity discussion 6.324–6.329)
Newton/LM IK step: (6.298–6.299)
Small-angle SO(3) log used for orientation_kinematics error in iterative IK.
- inverse_kinematics.utils.R_to_rpy(R: ndarray) Tuple[float, float, float][source]¶
Inverse of rpy_to_R (yaw-pitch-roll convention).
- inverse_kinematics.utils.TOL: float = 1e-09¶
Default absolute tolerance for equality checks.
- inverse_kinematics.utils.adjoint(T: ndarray) ndarray[source]¶
Adjoint representation Ad_T of an SE(3) transform T.
- Returns:
- [[R, 0],
[p^ R, R]]
- Return type:
(6,6) ndarray
- inverse_kinematics.utils.almost_equal(a: ndarray, b: ndarray, *, atol: float = 1e-09, rtol: float = 1e-09) bool[source]¶
Elementwise closeness for arrays.
- inverse_kinematics.utils.clamp(x: float, lo: float, hi: float) float[source]¶
Clamp a scalar to [lo, hi].
- inverse_kinematics.utils.dls_step(J: ndarray, e: ndarray, lam: float) ndarray[source]¶
- Damped least-squares (Levenberg–Marquardt) step:
Δq = (JᵀJ + λ² I)⁻¹ Jᵀ e
Matches (6.298–6.299). Handles over/under/fully determined cases.
- inverse_kinematics.utils.ensure_shape(*shape: int) Callable[[Callable[[...], ndarray]], Callable[[...], ndarray]][source]¶
Decorator that validates the ndarray shape of the returned value.
- Parameters:
shape (tuple[int]) – Expected shape, e.g., (6,) or (4, 4).
- inverse_kinematics.utils.hat_xi(omega: ndarray, v: ndarray) ndarray[source]¶
Build a 4×4 se(3) matrix from a screw (ω, v).
- Returns:
- [[ [ω]^, v ],
[ 0 , 0 ]]
- Return type:
(4,4) ndarray
- inverse_kinematics.utils.homogeneous(R: ndarray, t: ndarray) ndarray[source]¶
Compose a 4×4 homogeneous transform from (R, t).
- inverse_kinematics.utils.manipulability_metrics(J: ndarray, *, tol: float = 1e-08) Dict[str, float][source]¶
Basic singularity metrics for a geometric Jacobian (6.324–6.329). :returns:
min_sing : smallest singular value σ_min
cond : σ_max / σ_min (∞ if σ_min≈0)
detJJT : determinant of J Jᵀ (product σ_i^2 for square J)
rank : numeric rank
- Return type:
dict with keys
- inverse_kinematics.utils.normalize(v: ndarray, eps: float = 1e-12) ndarray[source]¶
Return a unit-length copy of vector v; if ||v|| < eps, returns v unchanged.
- inverse_kinematics.utils.pose_error(T_curr: ndarray, T_des: ndarray, *, mode: str = 'small') ndarray[source]¶
Compute a 6×1 task-space error e = [dp; dθ] between two poses.
- Parameters:
T_curr ((4,4) ndarray) – Current and desired transforms.
T_des ((4,4) ndarray) – Current and desired transforms.
mode ({"small", "so3"}) –
“small”: uses small-angle rotation_kinematics vector: 0.5 * vee(Rerr - Rerr^T)
”so3”: uses full SO(3) log for orientation_kinematics
- Returns:
e = [dx, dy, dz, wx, wy, wz]
- Return type:
(6,) ndarray
- inverse_kinematics.utils.rpy_to_R(roll: float, pitch: float, yaw: float) ndarray[source]¶
Construct rotation_kinematics R = Rz(yaw) * Ry(pitch) * Rx(roll).
- inverse_kinematics.utils.se3_log(T: ndarray) ndarray[source]¶
Approximate log map SE(3) → R^6; returns [ω; v] such that exp([ξ]^)=T. Uses a first-order approximation appropriate for small motions and for iterative IK error vectors (δ pose). For larger motions, use a full SO(3) log and the series for G^{-1}; that’s overkill for per-iteration errors.
- inverse_kinematics.utils.skew(v: ndarray) ndarray[source]¶
Skew-symmetric matrix [v]^ of a 3-vector.
- Parameters:
v ((3,) array-like)
- Return type:
(3,3) ndarray
- inverse_kinematics.utils.so3_log(R: ndarray, *, eps: float = 1e-12) ndarray[source]¶
Map SO(3) → R^3 (rotation_kinematics vector). Returns ω such that exp([ω]^)=R.
For small angles, this reduces to vex(R - R^T)/2 (small-angle approx).