API Reference¶
High-level façade for the forward-kinematics package.
This module exposes a single OOP entry point, ForwardApp, which
wraps the lower-level building blocks in core.py, io.py, and
tools/class_diagram.py and adds:
Robot spec loading (JSON/YAML) and explicit schema validation.
Forward kinematics for arbitrary serial chains (DH/MDH/PoE).
Analytical Jacobians (space/body).
Preset builders (SCARA, spherical wrist types 1–3) via
design.py.Class diagram generation via Graphviz DOT.
Timing and structured logging for reproducibility.
The design keeps public methods side-effect free (unless an output path_planning is provided) so they are straightforward to unit test under pytest.
Typical usage¶
>>> from forward_kinematics.app import ForwardApp
>>> app = ForwardApp()
>>> chain = app.load_robot("forward_kinematics/in/example_2r.json")
>>> T = app.fk(chain, q=[0.5, 0.25])
>>> J_space = app.jacobian_space(chain, q=[0.5, 0.25])
>>> app.save_transform("forward_kinematics/out/fk.json", T)
Notes
The CLI (
forward/cli.py) is a thin wrapper over this façade.JSON/YAML schema is defined in
io.py; validation usesjsonschema.For class diagrams, this module defers to
tools/class_diagram.py.
- class forward_kinematics.app.AppInfo(name: str = 'forward_kinematics-kinematics', version: str = '0.1.0', homepage: str = 'https://example.local/forward')[source]¶
Immutable metadata about the application.
- homepage: str = 'https://example.local/forward'¶
- name: str = 'forward_kinematics-kinematics'¶
- version: str = '0.1.0'¶
- class forward_kinematics.app.ForwardApp(in_dir: str | Path | None = None, out_dir: str | Path | None = None)[source]¶
High-level application façade for forward_kinematics kinematics workflows.
Responsibilities¶
Construct
SerialChaininstances from JSON/YAML specs.Validate specs against the JSON Schema.
Provide FK and analytical Jacobians (space/body).
Offer convenience builders for common robots (SCARA, spherical wrists).
Save/Load transforms and batch computations.
Generate a Graphviz DOT class diagram.
Composition¶
- Delegates to:
forward_kinematics.iofor parsing/validation/building serial chains.forward_kinematics.corefor Transform & kinematics math.forward_kinematics.designfor predefined robot_dynamics factories.forward_kinematics.tools.class_diagramfor DOT generation.
All public methods use explicit inputs and return values to remain trivial to unit test with pytest.
- param in_dir:
Default input directory for specs (used by helper methods).
- type in_dir:
PathLike, optional
- param out_dir:
Default output directory for results/artifacts.
- type out_dir:
PathLike, optional
- batch_fk(chain: SerialChain, q_list: Iterable[Sequence[int | float] | ndarray]) List[Transform][source]¶
Compute FK for a batch of joint vectors.
- Return type:
list[Transform]
- class_diagram_dot() str[source]¶
Build a Graphviz DOT description of the current package classes.
- Returns:
DOT string that can be rendered by Graphviz.
- Return type:
str
- fk(chain: SerialChain, q: Sequence[int | float] | ndarray) Transform[source]¶
Compute forward_kinematics kinematics (base-to-tool homogeneous transform).
- Parameters:
chain (SerialChain) – The robot_dynamics model.
q (array-like) – Joint vector (length == number of joints).
- Return type:
- jacobian_body(chain: SerialChain, q: Sequence[int | float] | ndarray) ndarray[source]¶
Compute the body Jacobian J_b(q).
- Return type:
(6, n) ndarray
- jacobian_space(chain: SerialChain, q: Sequence[int | float] | ndarray) ndarray[source]¶
Compute the space Jacobian J_s(q).
- Return type:
(6, n) ndarray
- load_robot(path: str | Path, *, validate: bool = True) SerialChain[source]¶
Load a robot_dynamics specification (JSON or YAML) and build a
SerialChain.The spec format is shared between JSON and YAML. Validation uses the JSON Schema returned by
forward_kinematics.io.robot_schema().- Parameters:
path (str or Path) – File path_planning to JSON/YAML robot_dynamics specification.
validate (bool) – Whether to validate against the schema before building.
- Return type:
- preset_scara(l1: int | float, l2: int | float, d: int | float = 0.0) SerialChain[source]¶
Build a planar SCARA (R|R|R|P) variant as a
SerialChain.- Parameters:
l1 (float) – Link lengths (planar arm).
l2 (float) – Link lengths (planar arm).
d (float) – Home prismatic offset (positive along tool axis).
- Return type:
- preset_spherical_wrist(wrist_type: int, d7: int | float = 0.0) SerialChain[source]¶
Build spherical wrist types 1–3 (Roll–Pitch–Roll, Roll–Pitch–Yaw, Pitch–Yaw–Roll).
- Parameters:
wrist_type ({1, 2, 3}) – Selects the rotation_kinematics order.
d7 (float) – Tool-frame offset along gripper axis.
- Return type:
- save_class_diagram(path: str | Path) Path[source]¶
Save the DOT representation of the class diagram to a file.
- Return type:
Path
Core math & object model for forward_kinematics kinematics (FK) and Jacobians.
This module is intentionally dependency-light (NumPy + our own utils) so it is easy to unit-test and reason about. It supports three link styles:
DHLink— Standard Denavit–Hartenberg (Eq. 5.5 style: Tz(d) Rz(θ) Tx(a) Rx(α))MDHLink— Modified DH (Craig) (Rz(θ) Tz(d) Tx(a) Rx(α))PoELink— Product-of-Exponentials with 6D screw axes in space frame
A SerialChain composes links and computes:
Forward kinematics: ^0T_n(q)
Analytical space Jacobian J_s(q)
Analytical body Jacobian J_b(q) (via adjoint transform)
Conventions¶
R^3 vectors are column vectors when embedded in 4x4 matrices.
Plücker twist stacking order for Jacobians is
[ω; v](6×1).For DH/MDH links, the joint axis is the local +z axis; we express it in the base frame via accumulated rotations.
For PoE chains, link screws are provided in the space frame; we use Adjoint products per Lynch & Park (modern robotics).
- class forward_kinematics.core.DHLink(a: float, alpha: float, d: float, theta_offset: float = 0.0, joint_type: str = 'R')[source]¶
Standard DH link (Craig Eq. 3.6 form): Tz(d) · Rz(θ) · Tx(a) · Rx(α).
- Parameters:
a (float) – Link length.
alpha (float) – Link twist (radians).
d (float) – Link offset (for R joint it’s constant; for P joint it’s variable).
theta_offset (float) – Constant offset added to revolute joint angle.
joint_type ({'R','P'}) – Revolute or prismatic.
- class forward_kinematics.core.Link[source]¶
Abstract base class for kinematic links.
- joint_type: str = 'R'¶
- class forward_kinematics.core.MDHLink(a: float, alpha: float, d: float, theta_offset: float = 0.0, joint_type: str = 'R')[source]¶
Modified DH link: Rz(θ) · Tz(d) · Tx(a) · Rx(α).
Same constructor as
DHLink.
- class forward_kinematics.core.PoELink(omega: ndarray, v: ndarray)[source]¶
Product-of-Exponentials link with space-frame screw axis.
- Parameters:
omega ((3,) array) – Angular axis of the screw; zero vector for prismatic.
v ((3,) array) – Linear part of the screw.
- class forward_kinematics.core.SerialChain(links: Sequence[Link], M: ndarray | None = None, name: str = 'robot_dynamics')[source]¶
Serial manipulator composed of
Linkinstances.- Parameters:
links (Sequence[Link]) – Ordered links from base (0) to tip (n-1).
M ((4,4) ndarray, optional) – Fixed tool transform applied_dynamics at the end (home/tool offset).
name (str) – Identifier.
Notes
FK is computed as
T = A1(q1) · A2(q2) · ... · An(qn) · M.For PoE,
Ai(qi)is the matrix exponentialexp([Si]^ qi)andMshould be the home pose of the end-effector.
- jacobian_body(q: Sequence[float]) ndarray[source]¶
- Analytical body Jacobian J_b(q) (6×n), related by
J_b(q) = Ad_{T(q)}^{-1} · J_s(q)
where T(q) = ^0T_n(q).
- jacobian_space(q: Sequence[float]) ndarray[source]¶
Analytical space Jacobian J_s(q) (6×n).
For DH/MDH: computed from accumulated frame origins/orientations. Column i uses z_{i-1} (axis in space) and p_{i-1}.
Revolute : [ ω_i = z ; v_i = p × z ]
Prismatic: [ ω_i = 0 ; v_i = z ]
For PoE : standard adjoint-based product-of-exponentials Jacobian.
- class forward_kinematics.core.Transform(R: ndarray, t: ndarray)[source]¶
SE(3) homogeneous transform T = [[R, t], [0, 1]].
- R¶
Rotation block.
- Type:
(3,3) ndarray
- t¶
Translation vector.
- Type:
(3,) ndarray
- R: ndarray¶
- apply(p: ndarray) ndarray[source]¶
Apply transform to point(s).
- Parameters:
p ((3,) or (3,n))
- Return type:
(3,) or (3,n)
- t: ndarray¶
Preset builders for common manipulators (SCARA, spherical wrists, planar arms).
All presets are expressed with standard DH links so they remain compatible
with the rest of the toolkit (FK, space/body Jacobians). Tool offsets are
applied_dynamics as the fixed terminal transform M in forward_kinematics.core.SerialChain.
Notes on spherical wrists¶
A spherical wrist is a 3-DOF orientation_kinematics mechanism with three intersecting, orthogonal joint axes. Although the rotation_kinematics orders are described in terms of rotations about global X/Y/Z (e.g., Z–X–Z), DH parameterizations still use local z joint axes; we achieve the desired rotation_kinematics orders by selecting link twists (α) that realign each successive local z-axis with the intended global axis before applying that joint’s θ.
The presets below use the following α patterns (all links have a=0, d=0):
- Type 1 (Roll–Pitch–Roll ≈ Z–X–Z)
α = [-π/2, +π/2, 0]
- Type 2 (Roll–Pitch–Yaw ≈ Z–Y–Z, “Euler wrist” variant)
α = [+π/2, -π/2, 0]
- Type 3 (Pitch–Yaw–Roll ≈ X–Y–Z)
α = [-π/2, -π/2, 0]
These produce the intended effective rotation_kinematics sequences while keeping the DH convention that each joint actuates around its local z-axis.
If you need a different convention (MDH or PoE), you can add parallel presets or feed equivalent screws into the PoE path_planning elsewhere in the codebase.
- forward_kinematics.design.build_planar_2r(l1: float, l2: float, *, name: str = 'planar_2R') SerialChain¶
Build a simple planar 2R arm in the x–y plane.
- Standard DH arrangement:
Joint 1: revolute about z0 at base
Joint 2: revolute about z1 at elbow
a2 carries link length l1; the fixed tool offset M carries l2
- Parameters:
l1 (float) – Link lengths.
l2 (float) – Link lengths.
- Return type:
- forward_kinematics.design.build_scara(l1: float, l2: float, d_home: float = 0.0, *, wrist_rotary: bool = False, name: str = 'SCARA') SerialChain¶
Build a SCARA manipulator.
Default is the classic 3-DOF planar variant (R–R–P), with an optional 4th yaw wrist (R–R–P–R). The prismatic joint is aligned with +z.
- DH parameterization (standard):
Link 1: a=0, α=0, d=0, θ = q1 Link 2: a=l1, α=0, d=0, θ = q2 Link 3: a=l2, α=0, d = d_home + q3 (prismatic) Link 4 (optional wrist yaw): a=0, α=0, d=0, θ = q4
- Parameters:
l1 (float) – Planar link lengths.
l2 (float) – Planar link lengths.
d_home (float) – Home offset for the vertical prismatic joint (positive along +z).
wrist_rotary (bool) – If True, include a 4th revolute wrist yaw (R–R–P–R).
name (str) – Model name.
- Return type:
- forward_kinematics.design.build_spherical_wrist(*, wrist_type: int, d7: float = 0.0, name: str = 'wrist') SerialChain¶
Build a 3-DOF spherical wrist preset with tool offset
Tz(d7)at the tip.The three types differ by the effective rotation_kinematics order, realized via DH link twists (α) that reorient each joint’s local z-axis:
Type 1 (Roll–Pitch–Roll ≈ Z–X–Z): α = [-π/2, +π/2, 0] Type 2 (Roll–Pitch–Yaw ≈ Z–Y–Z): α = [+π/2, -π/2, 0] Type 3 (Pitch–Yaw–Roll ≈ X–Y–Z): α = [-π/2, -π/2, 0]
All links have a=0 and d=0; the tool offset is applied_dynamics as M = Tz(d7).
- Parameters:
wrist_type ({1, 2, 3}) – Select rotation_kinematics order preset (see above).
d7 (float) – Tool offset along final +z.
name (str) – Model name.
- Return type:
- forward_kinematics.design.planar_2r(l1: float, l2: float, *, name: str = 'planar_2R') SerialChain[source]¶
Build a simple planar 2R arm in the x–y plane.
- Standard DH arrangement:
Joint 1: revolute about z0 at base
Joint 2: revolute about z1 at elbow
a2 carries link length l1; the fixed tool offset M carries l2
- Parameters:
l1 (float) – Link lengths.
l2 (float) – Link lengths.
- Return type:
- forward_kinematics.design.scara(l1: float, l2: float, d_home: float = 0.0, *, wrist_rotary: bool = False, name: str = 'SCARA') SerialChain[source]¶
Build a SCARA manipulator.
Default is the classic 3-DOF planar variant (R–R–P), with an optional 4th yaw wrist (R–R–P–R). The prismatic joint is aligned with +z.
- DH parameterization (standard):
Link 1: a=0, α=0, d=0, θ = q1 Link 2: a=l1, α=0, d=0, θ = q2 Link 3: a=l2, α=0, d = d_home + q3 (prismatic) Link 4 (optional wrist yaw): a=0, α=0, d=0, θ = q4
- Parameters:
l1 (float) – Planar link lengths.
l2 (float) – Planar link lengths.
d_home (float) – Home offset for the vertical prismatic joint (positive along +z).
wrist_rotary (bool) – If True, include a 4th revolute wrist yaw (R–R–P–R).
name (str) – Model name.
- Return type:
- forward_kinematics.design.spherical_wrist(*, wrist_type: int, d7: float = 0.0, name: str = 'wrist') SerialChain[source]¶
Build a 3-DOF spherical wrist preset with tool offset
Tz(d7)at the tip.The three types differ by the effective rotation_kinematics order, realized via DH link twists (α) that reorient each joint’s local z-axis:
Type 1 (Roll–Pitch–Roll ≈ Z–X–Z): α = [-π/2, +π/2, 0] Type 2 (Roll–Pitch–Yaw ≈ Z–Y–Z): α = [+π/2, -π/2, 0] Type 3 (Pitch–Yaw–Roll ≈ X–Y–Z): α = [-π/2, -π/2, 0]
All links have a=0 and d=0; the tool offset is applied_dynamics as M = Tz(d7).
- Parameters:
wrist_type ({1, 2, 3}) – Select rotation_kinematics order preset (see above).
d7 (float) – Tool offset along final +z.
name (str) – Model name.
- Return type:
I/O, schema, and builders for forward_kinematics-kinematics robot_dynamics specifications.
Features¶
JSON and YAML input (auto-detected by file extension).
JSON Schema validation (single source of truth).
Builders for DH, MDH, and PoE serial chains.
Simple transform saver for 4×4 matrices.
Spec format (uniform across JSON/YAML)¶
- Top-level keys:
name : str (optional) format : “dh” | “mdh” | “poe” # alias: “method” M : 4x4 matrix (optional) # tool/home transform links : list of link dicts # see each format below
- DH/MDH link:
- { “a”: float, “alpha”: float, “d”: float,
“theta_offset”: float=0.0, “joint_type”: “R”|”P” }
- PoE link (space frame screw):
{ “omega”: [wx, wy, wz], “v”: [vx, vy, vz] }
Examples
DH JSON: {
“name”: “planar_2r”, “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]]
}
PoE YAML: name: wrist format: poe M: [[1,0,0,0],[0,1,0,0],[0,0,1,0.15],[0,0,0,1]] links:
{omega: [0,0,1], v: [0,0,0]}
{omega: [1,0,0], v: [0,0,0]}
{omega: [0,0,1], v: [0,0,0]}
- forward_kinematics.io.build_chain_from_spec(spec: Mapping[str, Any]) SerialChain[source]¶
Build a
SerialChainfrom a validated spec mapping.Notes
This function does not perform schema validation; call
validate_spec()first if you need explicit checking.
- forward_kinematics.io.load_spec(path_or_dict: str | Path | Mapping[str, Any]) Dict[str, Any][source]¶
Load a spec from a file path_planning (JSON/YAML) or return a validated copy of an in-memory dict (no validation applied_dynamics here).
- forward_kinematics.io.load_spec_from_file(path: str | Path) Dict[str, Any][source]¶
Load a robot_dynamics spec from JSON or YAML file (auto-detected by extension).
- Return type:
dict
- forward_kinematics.io.robot_schema() Dict[str, Any][source]¶
Return the JSON Schema that validates our robot_dynamics specification.
- forward_kinematics.io.save_transform_json(path: str | Path, T: ndarray) None[source]¶
Save a 4×4 homogeneous transform as JSON { “matrix”: [[…],[…],[…],[…]] }.
- forward_kinematics.io.validate_spec(spec: Mapping[str, Any], schema: Mapping[str, Any] | None = None) None[source]¶
Validate a spec mapping against the JSON Schema.
- Raises:
jsonschema.ValidationError – If the spec does not conform.
Utility decorators and math helpers for forward_kinematics kinematics.
Exports¶
- 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) → elementwise array closeness
clamp(x, lo, hi)
normalize(v)
- Lie/SE(3) helpers:
skew(v) → 3×3 skew-symmetric from a 3-vector
vex(S) → inverse_kinematics of skew (vee operator)
hat_xi(ω, v) → 4×4 se(3) matrix from screw (ω, v)
adjoint(T) → 6×6 adjoint matrix of SE(3) transform
homogeneous(R, t) → 4×4 from (R, t)
- Validators:
is_rotation(R)
is_transform(T)
All helpers are NumPy-only to keep CI light and tests fast.
- forward_kinematics.utils.TOL: float = 1e-09¶
Default absolute tolerance for equality checks.
- forward_kinematics.utils.adjoint(T: ndarray) ndarray[source]¶
Adjoint representation Ad_T of an SE(3) transform T.
- Parameters:
T ((4,4) ndarray)
- Returns:
(6,6) ndarray –
- [[R, 0],
[p^ R, R]]
where R is the rotation_kinematics and p is the translation.
- forward_kinematics.utils.almost_equal(a: ndarray, b: ndarray, *, atol: float = 1e-09, rtol: float = 1e-09) bool[source]¶
Elementwise closeness for arrays.
- forward_kinematics.utils.clamp(x: float, lo: float, hi: float) float[source]¶
Clamp a scalar to [lo, hi].
- forward_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., (4, 4).
- Raises:
ValueError – If the returned object has a
shapeattribute that does not match.
Examples
>>> @ensure_shape(4, 4) ... def eye(): return np.eye(4) >>> eye().shape (4, 4)
- forward_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
- forward_kinematics.utils.homogeneous(R: ndarray, t: ndarray) ndarray[source]¶
Compose a 4x4 homogeneous transform from (R, t).
- forward_kinematics.utils.is_rotation(R: ndarray, *, atol: float = 1e-08) bool[source]¶
Heuristic check for a valid rotation_kinematics matrix (orthonormal & det ≈ 1).
- forward_kinematics.utils.is_transform(T: ndarray, *, atol: float = 1e-08) bool[source]¶
Heuristic check for a valid homogeneous transform.
- forward_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.
- forward_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