pylinkage.visualizer package

Submodules

pylinkage.visualizer.animated module

The visualizer module makes visualization of linkages easy using matplotlib.

Created on Mon Jun 14, 12:13:58 2021.

@author: HugoFara

pylinkage.visualizer.animated.plot_kinematic_linkage(linkage: Linkage, fig: Figure, axis: Axes, loci: Sequence[tuple[Coord, ...]], frames: int = 360, interval: float = 40) FuncAnimation

Plot a linkage with an animation.

Parameters:
  • linkage – The linkage to animate.

  • fig – Figure to support the axes.

  • axis – The subplot to draw on.

  • loci – list of list of coordinates.

  • frames – Number of frames to draw the linkage on.

  • interval – Delay between frames in milliseconds.

Returns:

The animation object.

pylinkage.visualizer.animated.show_linkage(linkage: Linkage, save: bool = False, prev: Sequence[Coord] | None = None, loci: Sequence[tuple[Coord, ...]] | None = None, points: int = 360, iteration_factor: float = 1, title: str | None = None, duration: float = 5, fps: int = 24) FuncAnimation

Display results as an animated drawing.

Parameters:
  • linkage – The Linkage you want to draw.

  • save – To save the animation.

  • prev – Previous coordinates to use for linkage.

  • loci – list of loci.

  • points – Number of points to draw for a crank revolution. Useless when loci are set.

  • iteration_factor – A simple way to subdivide the movement. The real number of points will be points * iteration_factor.

  • title – Figure title. Defaults to str(len(ani)).

  • duration – Animation duration (in seconds).

  • fps – Number of frames per second for the output video.

Returns:

The animation object.

pylinkage.visualizer.animated.swarm_tiled_repr(linkage: Linkage, swarm: tuple[int, Sequence[tuple[float, np.ndarray, Sequence[Coord]]]], fig: Figure, axes: np.ndarray, dimension_func: Callable[[np.ndarray], Sequence[float]] | None = None, points: int = 12, iteration_factor: float = 1) None

Show all the linkages in a swarm in tiled mode.

Parameters:
  • linkage – The original Linkage that will be MODIFIED.

  • swarm – Tuple of (iteration_number, list_of_agents) where each agent is (score, dimensions, initial_positions).

  • fig – Figure to support the axes.

  • axes – The subplot to draw on.

  • points – Number of steps to use for each Linkage.

  • iteration_factor – A simple way to subdivide the movement. The real number of points will be points * iteration_factor.

  • dimension_func – If you want a special formatting of dimensions from agents before passing them to the linkage.

pylinkage.visualizer.animated.update_animated_plot(linkage: Any, index: int, images: list[Line2D], loci: Sequence[tuple[Coord, ...]]) list[Line2D]

Modify im, instead of recreating it to make the animation run faster.

Works with legacy Linkage, modern SimLinkage, and Mechanism.

Parameters:
  • linkage – The linkage being animated.

  • index – Frame index.

  • images – Artist to be modified.

  • loci – list of loci.

Returns:

Updated version of images.

pylinkage.visualizer.core module

Core features for visualization.

This module provides shared utilities used by all visualization backends (matplotlib, plotly, drawsvg). It contains linkage introspection helpers that work with both the legacy pylinkage.linkage.Linkage (joints API) and the modern pylinkage.simulation.Linkage (components API).

For symbol definitions see symbols.

pylinkage.visualizer.core.build_connections(linkage: Any, components: list[Any]) list[tuple[int, int]]

Return (parent_idx, child_idx) pairs for every bar to draw.

Three cases:

  • Mechanism (has .links): iterate each link and emit all pairwise combinations of its joint indices. A ternary link with three joints yields three bars (the full triangle); a simple binary link yields one.

  • Legacy Linkage / modern SimLinkage (joint-/component-centric): fall back to per-component get_parent_pairs().

pylinkage.visualizer.core.build_rails(components: list[Any]) list[tuple[int, int]]

Return (end1_idx, end2_idx) pairs for every slider rail to draw.

Rails are the lines prismatic joints slide on; they are bars of the frame or of a link, not connections to the sliding joint itself.

pylinkage.visualizer.core.get_components(linkage: Any) list[Any]

Return the ordered list of joints/components from either API.

Works with both legacy Linkage.joints and modern SimLinkage.components.

pylinkage.visualizer.core.get_parent_pairs(component: Any) list[Any]

Return the parent components that should draw links to component.

Works with both legacy joints (joint0, joint1) and modern components (anchor, anchor1, anchor2).

pylinkage.visualizer.core.get_rail_pairs(component: Any) list[tuple[Any, Any]]

Return the (end1, end2) pairs of the rails component slides on.

A prismatic joint is drawn as a bar between the two points that define its line: RRPDyad.line_anchor1/line_anchor2, both lines of a PPDyad, or a legacy prismatic joint’s joint1/joint2.

pylinkage.visualizer.core.is_prismatic_like(component: Any) bool

True if the component is a slider (legacy Prismatic or RRPDyad).

pylinkage.visualizer.core.is_revolute_like(component: Any) bool

True if the component draws as a pin joint with two anchored parents.

Matches legacy Revolute/Pivot/Fixed and modern RRRDyad/FixedDyad.

pylinkage.visualizer.core.is_static_like(component: Any) bool

True if the component is a fixed-frame joint (Static/Ground).

pylinkage.visualizer.core.resolve_component(parent: Any, components: list[Any]) int | None

Resolve a parent reference to its index in the component list.

Handles direct membership, _AnchorProxy._parent, and legacy joint0/joint1 references.

Returns:

Index into components, or None if not found.

pylinkage.visualizer.drawsvg_viz module

drawsvg-based visualization for publication-quality kinematic diagrams.

This module provides SVG output with proper ISO 3952 kinematic symbols, suitable for engineering documentation and academic publications.

pylinkage.visualizer.drawsvg_viz.plot_linkage_svg(linkage: Linkage, loci: Iterable[tuple[Coord, ...]] | None = None, *, title: str | None = None, show_dimensions: bool = False, show_loci: bool = True, show_labels: bool = True, link_style: Literal['bar', 'bone', 'line'] = 'bar', scale: float = 80, padding: float = 100) Drawing

Create a publication-quality SVG kinematic diagram.

Parameters:
  • linkage – The linkage to visualize.

  • loci – Optional precomputed loci. If None, runs simulation.

  • title – Optional title for the diagram.

  • show_dimensions – Whether to show dimension lines.

  • show_loci – Whether to show joint movement paths.

  • show_labels – Whether to show joint labels.

  • link_style – Visual style for links (‘bar’, ‘bone’, or ‘line’).

  • scale – Pixels per unit.

  • padding – Canvas padding in pixels.

Returns:

A drawsvg.Drawing object.

pylinkage.visualizer.drawsvg_viz.plot_linkage_svg_with_velocity(linkage: Linkage, positions: NDArray[np.float64] | Sequence[tuple[float, float]], velocities: NDArray[np.float64] | Sequence[tuple[float, float]], *, title: str | None = None, show_labels: bool = True, link_style: Literal['bar', 'bone', 'line'] = 'bar', velocity_scale: float | None = None, velocity_color: str = '#0066CC', skip_static: bool = True, scale: float = 80, padding: float = 100) Drawing

Create an SVG diagram with velocity vectors overlaid.

Parameters:
  • linkage – The linkage to visualize.

  • positions – Joint positions, shape (n_joints, 2) or list of (x, y).

  • velocities – Joint velocities, shape (n_joints, 2) or list of (vx, vy).

  • title – Optional title for the diagram.

  • show_labels – Whether to show joint labels.

  • link_style – Visual style for links (‘bar’, ‘bone’, or ‘line’).

  • velocity_scale – Scaling factor for velocity arrows. Auto-computed if None.

  • velocity_color – Color for velocity arrows.

  • skip_static – Whether to skip velocity arrows for static joints.

  • scale – Pixels per unit.

  • padding – Canvas padding in pixels.

Returns:

A drawsvg.Drawing object.

Example

>>> linkage.set_input_velocity(crank, omega=10.0)
>>> positions, velocities = linkage.step_fast_with_kinematics()
>>> drawing = plot_linkage_svg_with_velocity(
...     linkage, positions[0], velocities[0]
... )
>>> drawing.save_svg("linkage_with_velocity.svg")
pylinkage.visualizer.drawsvg_viz.save_linkage_svg(linkage: Linkage, path: str, loci: Iterable[tuple[Coord, ...]] | None = None, **kwargs: object) None

Save a linkage diagram to an SVG file.

Parameters:
  • linkage – The linkage to visualize.

  • path – Output file path (should end in .svg).

  • loci – Optional precomputed loci.

  • **kwargs – Additional arguments passed to plot_linkage_svg.

pylinkage.visualizer.drawsvg_viz.save_linkage_svg_with_velocity(linkage: Linkage, path: str, positions: NDArray[np.float64] | Sequence[tuple[float, float]], velocities: NDArray[np.float64] | Sequence[tuple[float, float]], **kwargs: object) None

Save a linkage diagram with velocity vectors to an SVG file.

Parameters:
  • linkage – The linkage to visualize.

  • path – Output file path (should end in .svg).

  • positions – Joint positions, shape (n_joints, 2) or list of (x, y).

  • velocities – Joint velocities, shape (n_joints, 2) or list of (vx, vy).

  • **kwargs – Additional arguments passed to plot_linkage_svg_with_velocity.

pylinkage.visualizer.dxf_export module

DXF export for CAD/CNC applications.

This module provides DXF output for import into AutoCAD, CNC software, and other CAD applications that support the DXF format.

pylinkage.visualizer.dxf_export.plot_linkage_dxf(linkage: Linkage, loci: Iterable[tuple[Coord, ...]] | None = None, *, frame_index: int = 0, link_width: float | None = None, joint_radius: float | None = None) Any

Create a DXF drawing of the linkage.

Parameters:
  • linkage – The linkage to export.

  • loci – Optional precomputed loci. If None, runs simulation.

  • frame_index – Which simulation frame to export (0 = first).

  • link_width – Width of link bars in world units. Auto-scaled if None.

  • joint_radius – Radius of joint circles in world units. Auto-scaled if None.

Returns:

An ezdxf Drawing object ready to save.

Example

>>> from pylinkage.visualizer import plot_linkage_dxf, save_linkage_dxf
>>> doc = plot_linkage_dxf(linkage)
>>> doc.saveas("linkage.dxf")
pylinkage.visualizer.dxf_export.save_linkage_dxf(linkage: Linkage, path: str | Path, loci: Iterable[tuple[Coord, ...]] | None = None, **kwargs: object) None

Save linkage to a DXF file.

Parameters:
  • linkage – The linkage to export.

  • path – Output file path (should end in .dxf).

  • loci – Optional precomputed loci.

  • **kwargs – Additional arguments passed to plot_linkage_dxf.

Example

>>> from pylinkage.visualizer import save_linkage_dxf
>>> save_linkage_dxf(linkage, "output.dxf")

pylinkage.visualizer.kinematics module

Visualization of velocity and acceleration vectors.

This module provides functions to visualize kinematic quantities (velocity and acceleration) as vector arrows overlaid on linkage diagrams.

pylinkage.visualizer.kinematics.animate_kinematics(linkage: Linkage, *, show_velocity: bool = True, show_acceleration: bool = False, velocity_scale: float | None = None, fps: int = 24, duration: float = 5.0, figsize: tuple[float, float] = (12, 8), title: str | None = None, save_path: str | None = None) Figure

Create an animated visualization with velocity vectors.

Parameters:
  • linkage – The linkage to visualize.

  • show_velocity – Whether to show velocity vectors.

  • show_acceleration – Whether to show acceleration vectors.

  • velocity_scale – Arrow scale for velocities. Auto-computed if None.

  • fps – Frames per second.

  • duration – Animation duration in seconds.

  • figsize – Figure size (width, height) in inches.

  • title – Figure title.

  • save_path – If provided, save animation to this path (e.g., “animation.gif”).

Returns:

The matplotlib Figure object.

Example

>>> linkage.set_input_velocity(crank, omega=10.0)
>>> fig = animate_kinematics(linkage, show_velocity=True, save_path="vel.gif")
pylinkage.visualizer.kinematics.plot_acceleration_vectors(linkage: Linkage, axis: Axes, positions: NDArray[np.float64] | Sequence[tuple[float, float]], accelerations: NDArray[np.float64] | Sequence[tuple[float, float]], *, scale: float = 0.01, color: str = 'red', width: float = 0.004, label: str = 'Acceleration', skip_static: bool = True) Quiver

Plot acceleration vectors as arrows at joint positions.

Parameters:
  • linkage – The linkage being visualized.

  • axis – Matplotlib axes to draw on.

  • positions – Joint positions, shape (n_joints, 2) or list of (x, y).

  • accelerations – Joint accelerations, shape (n_joints, 2) or list of (ax, ay).

  • scale – Scaling factor for arrow length. Smaller = longer arrows.

  • color – Arrow color.

  • width – Arrow shaft width as fraction of plot width.

  • label – Legend label for the arrows.

  • skip_static – Whether to skip drawing arrows for static joints.

Returns:

The Quiver object for further customization.

pylinkage.visualizer.kinematics.plot_kinematics_frame(linkage: Linkage, axis: Axes, positions: NDArray[np.float64], velocities: NDArray[np.float64] | None = None, accelerations: NDArray[np.float64] | None = None, *, velocity_scale: float = 0.1, acceleration_scale: float = 0.01, show_velocity: bool = True, show_acceleration: bool = False) None

Plot a single frame of linkage with kinematic vectors.

Parameters:
  • linkage – The linkage being visualized.

  • axis – Matplotlib axes to draw on.

  • positions – Joint positions for this frame, shape (n_joints, 2).

  • velocities – Joint velocities, shape (n_joints, 2). Optional.

  • accelerations – Joint accelerations, shape (n_joints, 2). Optional.

  • velocity_scale – Scaling factor for velocity arrows.

  • acceleration_scale – Scaling factor for acceleration arrows.

  • show_velocity – Whether to show velocity vectors.

  • show_acceleration – Whether to show acceleration vectors.

pylinkage.visualizer.kinematics.plot_velocity_vectors(linkage: Linkage, axis: Axes, positions: NDArray[np.float64] | Sequence[tuple[float, float]], velocities: NDArray[np.float64] | Sequence[tuple[float, float]], *, scale: float = 0.1, color: str = 'blue', width: float = 0.005, label: str = 'Velocity', skip_static: bool = True) Quiver

Plot velocity vectors as arrows at joint positions.

Parameters:
  • linkage – The linkage being visualized.

  • axis – Matplotlib axes to draw on.

  • positions – Joint positions, shape (n_joints, 2) or list of (x, y).

  • velocities – Joint velocities, shape (n_joints, 2) or list of (vx, vy).

  • scale – Scaling factor for arrow length. Smaller = longer arrows.

  • color – Arrow color.

  • width – Arrow shaft width as fraction of plot width.

  • label – Legend label for the arrows.

  • skip_static – Whether to skip drawing arrows for static joints.

Returns:

The Quiver object for further customization.

pylinkage.visualizer.kinematics.show_kinematics(linkage: Linkage, frame_index: int = 0, *, show_velocity: bool = True, show_acceleration: bool = False, velocity_scale: float | None = None, acceleration_scale: float | None = None, figsize: tuple[float, float] = (10, 8), title: str | None = None) Figure

Display linkage with velocity and/or acceleration vectors.

Runs simulation with kinematics computation and displays the result at a specific frame.

Parameters:
  • linkage – The linkage to visualize.

  • frame_index – Which frame to display (0 = initial position).

  • show_velocity – Whether to show velocity vectors.

  • show_acceleration – Whether to show acceleration vectors.

  • velocity_scale – Arrow scale for velocities. Auto-computed if None.

  • acceleration_scale – Arrow scale for accelerations. Auto-computed if None.

  • figsize – Figure size (width, height) in inches.

  • title – Figure title.

Returns:

The matplotlib Figure object.

Example

>>> linkage.set_input_velocity(crank, omega=10.0)
>>> fig = show_kinematics(linkage, frame_index=25, show_velocity=True)

pylinkage.visualizer.plotly_viz module

Plotly-based visualization for interactive kinematic diagrams.

This module provides interactive HTML output with zoom, pan, hover tooltips, and animation controls. Includes velocity vector visualization.

Supports both legacy (pylinkage.linkage.Linkage) and modern (pylinkage.simulation.Linkage) linkage objects.

pylinkage.visualizer.plotly_viz.animate_linkage_plotly(linkage: LegacyLinkage | SimLinkage, loci: Iterable[tuple[Coord, ...]] | None = None, *, title: str | None = None, show_loci: bool = True, width: int = 900, height: int = 700, frame_duration: int = 50) go.Figure

Create an animated Plotly diagram with play/pause controls.

Accepts both legacy pylinkage.linkage.Linkage and modern pylinkage.simulation.Linkage objects.

Parameters:
  • linkage – The linkage to visualize (legacy or modern API).

  • loci – Optional precomputed loci. If None, runs simulation.

  • title – Optional title for the diagram.

  • show_loci – Whether to show joint movement paths.

  • width – Figure width in pixels.

  • height – Figure height in pixels.

  • frame_duration – Milliseconds per frame.

Returns:

A plotly Figure object with animation.

pylinkage.visualizer.plotly_viz.interactive_linkage_plotly(linkage: LegacyLinkage | SimLinkage, iterations: int | None = None, *, title: str | None = None, show_loci: bool = True, width: int = 800, height: int = 600) go.FigureWidget

Create an interactive linkage controlled by a crank-angle slider.

Pre-computes the full trajectory, then provides a slider (via ipywidgets) that scrubs through frames. The figure updates in-place using FigureWidget — no flickering, instant feedback.

Requires ipywidgets to be installed (pip install ipywidgets).

Accepts both legacy pylinkage.linkage.Linkage and modern pylinkage.simulation.Linkage objects.

Parameters:
  • linkage – The linkage to visualize (legacy or modern API).

  • iterations – Number of simulation steps. If None, uses the linkage’s rotation period.

  • title – Optional title for the diagram.

  • show_loci – Whether to show faded joint-path traces behind the mechanism.

  • width – Figure width in pixels.

  • height – Figure height in pixels.

Returns:

An ipywidgets.VBox containing the slider and figure. In Jupyter, just let the cell return it — no manual display() needed.

Example

In a Jupyter notebook:

from pylinkage.visualizer import interactive_linkage_plotly

interactive_linkage_plotly(hoeken)
pylinkage.visualizer.plotly_viz.plot_linkage_plotly(linkage: LegacyLinkage | SimLinkage, loci: Iterable[tuple[Coord, ...]] | None = None, *, title: str | None = None, show_dimensions: bool = False, show_loci: bool = True, show_labels: bool = True, width: int = 800, height: int = 600) go.Figure

Create an interactive Plotly diagram of a linkage.

Accepts both legacy pylinkage.linkage.Linkage and modern pylinkage.simulation.Linkage objects.

Parameters:
  • linkage – The linkage to visualize (legacy or modern API).

  • loci – Optional precomputed loci. If None, runs simulation.

  • title – Optional title for the diagram.

  • show_dimensions – Whether to show dimension annotations.

  • show_loci – Whether to show joint movement paths.

  • show_labels – Whether to show joint name labels.

  • width – Figure width in pixels.

  • height – Figure height in pixels.

Returns:

A plotly Figure object.

pylinkage.visualizer.plotly_viz.plot_linkage_plotly_with_velocity(linkage: LegacyLinkage, frame_index: int = 0, *, title: str | None = None, show_loci: bool = True, show_velocity: bool = True, velocity_scale: float | None = None, velocity_color: str = '#2196F3', width: int = 900, height: int = 700) go.Figure

Create an interactive Plotly diagram with velocity vectors.

Runs simulation with kinematics and displays velocity arrows at the specified frame.

Note

This function currently requires a legacy pylinkage.linkage.Linkage because it depends on step_fast_with_kinematics() and per-joint omega.

Parameters:
  • linkage – The linkage to visualize.

  • frame_index – Which frame to display (0 = initial position).

  • title – Optional title for the diagram.

  • show_loci – Whether to show joint movement paths.

  • show_velocity – Whether to show velocity vectors.

  • velocity_scale – Scaling factor for arrows. Auto-computed if None.

  • velocity_color – Color for velocity arrows.

  • width – Figure width in pixels.

  • height – Figure height in pixels.

Returns:

A plotly Figure object.

Example

>>> linkage.set_input_velocity(crank, omega=10.0)
>>> fig = plot_linkage_plotly_with_velocity(linkage, frame_index=25)
>>> fig.show()

pylinkage.visualizer.pso_plots module

Advanced visualization for Particle Swarm Optimization.

Provides parallel coordinates plots and dashboard layouts for visualizing PSO optimization with proper handling of different data types (lengths, angles, scores).

Created for improved PSO visualization in pylinkage.

pylinkage.visualizer.pso_plots.animate_dashboard(linkage: Linkage, history: History, dim_names: Sequence[str], dim_types: Sequence[str] | None = None, bounds: tuple[Sequence[float], Sequence[float]] | None = None, dimension_func: Callable[[np.ndarray], Sequence[float]] | None = None, interval: int = 500, save_path: str | None = None) FuncAnimation

Animate the dashboard layout over optimization history.

Parameters:
  • linkage – The linkage being optimized.

  • history – List of swarms, one per iteration.

  • dim_names – Names for each dimension.

  • dim_types – Type of each dimension (‘length’ or ‘angle’).

  • bounds – Optional (min_bounds, max_bounds).

  • dimension_func – Optional function to transform dimensions.

  • interval – Delay between frames in milliseconds.

  • save_path – If provided, save animation to this path.

Returns:

The animation object.

pylinkage.visualizer.pso_plots.animate_parallel_coordinates(history: History, dim_names: Sequence[str], dim_types: Sequence[str] | None = None, bounds: tuple[Sequence[float], Sequence[float]] | None = None, interval: int = 200, cmap: str = 'viridis', save_path: str | None = None) FuncAnimation

Animate parallel coordinates plot over optimization history.

Parameters:
  • history – List of swarms, one per iteration.

  • dim_names – Names for each dimension.

  • dim_types – Type of each dimension (‘length’, ‘angle’, or ‘score’).

  • bounds – Optional (min_bounds, max_bounds) for normalization.

  • interval – Delay between frames in milliseconds.

  • cmap – Colormap name.

  • save_path – If provided, save animation to this path.

Returns:

The animation object.

pylinkage.visualizer.pso_plots.dashboard_layout(linkage: Linkage, swarm: Swarm, score_history: Sequence[float], dim_names: Sequence[str], dim_types: Sequence[str] | None = None, bounds: tuple[Sequence[float], Sequence[float]] | None = None, dimension_func: Callable[[np.ndarray], Sequence[float]] | None = None, fig: Figure | None = None) Figure

Create a dashboard layout for PSO visualization.

Layout: +—————–+——————+ | Score History | Best Linkage | | (line plot) | (static plot) | +—————–+——————+ | Length Params | Angle Params | | (box plot) | (polar/circular) | +—————–+——————+

Parameters:
  • linkage – The linkage being optimized (will be modified).

  • swarm – Current swarm state.

  • score_history – History of best scores per iteration.

  • dim_names – Names for each dimension.

  • dim_types – Type of each dimension (‘length’ or ‘angle’).

  • bounds – Optional (min_bounds, max_bounds).

  • dimension_func – Optional function to transform dimensions.

  • fig – Existing figure to use.

Returns:

The matplotlib Figure object.

pylinkage.visualizer.pso_plots.normalize_data(data: ndarray, bounds: tuple[Sequence[float], Sequence[float]] | None = None) ndarray

Normalize data to [0, 1] range.

Parameters:
  • data – Array of shape (n_particles, n_dimensions).

  • bounds – Optional (min_bounds, max_bounds) for each dimension. If None, uses data min/max.

Returns:

Normalized data array.

pylinkage.visualizer.pso_plots.parallel_coordinates_plot(swarm: Swarm, dim_names: Sequence[str], dim_types: Sequence[str] | None = None, bounds: tuple[Sequence[float], Sequence[float]] | None = None, ax: Axes | None = None, cbar_ax: Axes | None = None, cmap: str = 'viridis', alpha: float = 0.3, highlight_best: int = 5) Axes

Create a parallel coordinates plot for a PSO swarm.

Each dimension gets its own vertical axis, normalized to [0, 1]. Particles are colored by their score (fitness).

Parameters:
  • swarm – Tuple of (iteration, list_of_agents) where each agent is (score, dimensions, initial_positions).

  • dim_names – Names for each dimension.

  • dim_types – Type of each dimension (‘length’, ‘angle’, or ‘score’). Used for axis grouping and labeling.

  • bounds – Optional (min_bounds, max_bounds) for normalization.

  • ax – Matplotlib axes to plot on. If None, creates new figure.

  • cbar_ax – Optional axes for the colorbar. If provided, colorbar is drawn there instead of stealing space from ax. Use this for animations to prevent layout shifts.

  • cmap – Colormap name for score coloring.

  • alpha – Line transparency for regular particles.

  • highlight_best – Number of best particles to highlight.

Returns:

The matplotlib Axes object.

pylinkage.visualizer.static module

Static (non-animated) linkage visualization.

Supports both legacy pylinkage.linkage.Linkage (joints API) and modern pylinkage.simulation.Linkage (components API).

pylinkage.visualizer.static.plot_static_linkage(linkage: Any, axis: Axes, loci: Iterable[tuple[Coord, ...]], locus_highlights: list[list[Coord]] | None = None, show_legend: bool = False, *, show_labels: bool = True, show_loci: bool = True, n_ghosts: int = 0, title: str | None = None) None

Plot a linkage at one position with joint trajectories.

Draws the mechanism bars at the initial position (bold, colored), joint trajectory paths (faded), ground pivot markers, and joint labels. Optionally draws “ghost” mechanism outlines at evenly spaced frames through the cycle.

Works with both the legacy Linkage (joints) and the modern SimLinkage (components) APIs.

Parameters:
  • linkage – The linkage to draw (legacy or modern).

  • axis – Matplotlib axes to draw on.

  • loci – Sequence of frames, each frame a tuple of (x, y) per joint.

  • locus_highlights – Optional list of coordinate lists to scatter.

  • show_legend – Add a legend with joint names.

  • show_labels – Annotate each joint with its name.

  • show_loci – Draw joint trajectory paths.

  • n_ghosts – Number of ghost mechanism outlines to draw through the cycle (0 = none).

  • title – Optional axes title.

pylinkage.visualizer.step_export module

STEP export for 3D CAD interchange.

This module provides STEP output for import into 3D CAD applications like FreeCAD, SolidWorks, Fusion 360, and other STEP-compatible software.

class pylinkage.visualizer.step_export.JointProfile(radius: float, length: float)

Bases: object

Profile for 3D joint geometry.

Variables:
  • radius (float) – Pin/hole radius in world units.

  • length (float) – Pin length in z-direction.

length: float
radius: float
class pylinkage.visualizer.step_export.LinkProfile(width: float, thickness: float, fillet_radius: float = 0.0)

Bases: object

Cross-section profile for 3D links.

Variables:
  • width (float) – Width of the link bar in world units.

  • thickness (float) – Thickness (z-direction) in world units.

  • fillet_radius (float) – Radius for edge rounding (0 for sharp edges).

fillet_radius: float = 0.0
thickness: float
width: float
pylinkage.visualizer.step_export.build_linkage_3d(linkage: Linkage, loci: Iterable[tuple[Coord, ...]] | None = None, *, frame_index: int = 0, link_profile: LinkProfile | None = None, joint_profile: JointProfile | None = None, z_offset: float = 0.0, include_pins: bool = True) Any

Build a 3D CAD model of the linkage.

Creates a build123d Compound containing all links and joint pins as separate solids for the specified frame position.

Parameters:
  • linkage – The linkage to model.

  • loci – Optional precomputed loci. If None, runs simulation.

  • frame_index – Which simulation frame to export (0 = first).

  • link_profile – Cross-section dimensions for links. Auto-scaled if None.

  • joint_profile – Dimensions for joint pins/holes. Auto-scaled if None.

  • z_offset – Base Z position for the linkage.

  • include_pins – Whether to model joint pins as separate parts.

Returns:

A build123d Compound with all parts.

Example

>>> from pylinkage.visualizer import build_linkage_3d, save_linkage_step
>>> model = build_linkage_3d(linkage)
>>> save_linkage_step(linkage, "linkage.step")
pylinkage.visualizer.step_export.save_linkage_step(linkage: Linkage, path: str | Path, loci: Iterable[tuple[Coord, ...]] | None = None, **kwargs: object) None

Save linkage to a STEP file.

Parameters:
  • linkage – The linkage to export.

  • path – Output file path (should end in .step or .stp).

  • loci – Optional precomputed loci.

  • **kwargs – Additional arguments passed to build_linkage_3d.

Example

>>> from pylinkage.visualizer import save_linkage_step
>>> save_linkage_step(linkage, "output.step")

pylinkage.visualizer.symbols module

Kinematic symbol definitions for engineering diagrams.

This module provides shared symbol metadata used by visualization backends to render proper ISO 3952 kinematic diagram symbols.

class pylinkage.visualizer.symbols.LinkStyle(value)

Bases: Enum

Visual styles for drawing links between joints.

BAR = 1
BONE = 2
LINE = 3
class pylinkage.visualizer.symbols.SymbolSpec(symbol_type: SymbolType, color: str, size: float, label_offset: tuple[float, float])

Bases: object

Specification for a kinematic symbol.

color: str
label_offset: tuple[float, float]
size: float
symbol_type: SymbolType
class pylinkage.visualizer.symbols.SymbolType(value)

Bases: Enum

Types of kinematic symbols.

CRANK = 3
FIXED = 5
GROUND = 1
LINEAR = 6
REVOLUTE = 2
SLIDER = 4

Get a link color by index, cycling through available colors.

Parameters:

index – The link index.

Returns:

Hex color string.

pylinkage.visualizer.symbols.get_symbol_spec(joint: Component) SymbolSpec

Get the symbol specification for a joint.

Parameters:

joint – The joint to get the symbol for.

Returns:

SymbolSpec for the joint type, or a default REVOLUTE spec if unknown.

pylinkage.visualizer.symbols.is_ground_joint(joint: Component) bool

Check if a joint should be rendered as a ground/fixed support.

Parameters:

joint – The joint to check.

Returns:

True if the joint is a ground joint (Static/Ground with no parents).

Module contents

Linkage visualization features.

Backends:
  • matplotlib (default): plot_static_linkage, plot_kinematic_linkage, show_linkage

  • plotly: plot_linkage_plotly, animate_linkage_plotly (interactive HTML)

  • drawsvg: plot_linkage_svg, save_linkage_svg (publication-quality SVG)

  • dxf: plot_linkage_dxf, save_linkage_dxf (CAD/CNC export)

  • step: build_linkage_3d, save_linkage_step (3D CAD interchange)