Trajectory Generation¶
Functions and classes for generating robot trajectories.
Overview¶
Trajectory generation converts 2D sketches to 3D robot joint positions using inverse kinematics.
graph LR
A[Sketch] --> B[Map to 3D]
B --> C[Solve IK]
C --> D[Interpolate]
D --> E[Trajectory]
Main Function¶
generate_trajectory¶
generate_trajectory
¶
Convenience function: Convert image directly to robot trajectory.
This is a one-shot function that combines image_to_sketch() and sketch_to_trajectory() for simple use cases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
|
Union[str, Path, ndarray, Image]
|
Input image (file path, numpy array, or PIL Image). |
required |
output_path
|
Optional[Union[str, Path]]
|
If provided, save trajectory JSON to this path. |
None
|
config
|
Optional[TrajectoryConfig]
|
Full configuration (uses sensible defaults if None). |
None
|
initial_q
|
Optional[Union[ndarray, dict, Trajectory]]
|
Initial joint configuration to start IK solving from. Can be one of: - numpy array of shape (n_joints,) with joint positions in radians - dict mapping joint names to positions in radians - Trajectory object (uses last waypoint) - None (default): use fixed initial pose for drawing This enables sequential trajectory execution where each new trajectory starts from the robot's current position. |
None
|
Returns:
| Type | Description |
|---|---|
Trajectory
|
Trajectory object ready for execution. |
Example
import pib3 trajectory = pib3.generate_trajectory("my_drawing.png") trajectory.to_json("output.json")
With custom config¶
from pib3 import TrajectoryConfig, PaperConfig config = TrajectoryConfig( ... paper=PaperConfig(size=0.20, drawing_scale=0.9), ... ) trajectory = pib3.generate_trajectory("drawing.png", config=config)
Sequential trajectories (robot draws multiple images)¶
traj1 = pib3.generate_trajectory("image1.png") traj2 = pib3.generate_trajectory("image2.png", initial_q=traj1) traj3 = pib3.generate_trajectory("image3.png", initial_q=traj2)
Source code in pib3/__init__.py
Usage¶
import pib3
# Basic usage
trajectory = pib3.generate_trajectory("drawing.png")
trajectory.to_json("output.json")
# With configuration
from pib3 import TrajectoryConfig, PaperConfig
config = TrajectoryConfig(
paper=PaperConfig(size=0.15, drawing_scale=0.9)
)
trajectory = pib3.generate_trajectory("drawing.png", config=config)
# With visualization during IK solving
trajectory = pib3.generate_trajectory(
"drawing.png",
visualize=True # Ignored (Swift removed)
)
sketch_to_trajectory¶
sketch_to_trajectory
¶
Convert a Sketch to a robot Trajectory using inverse kinematics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sketch
|
Sketch
|
Sketch object containing strokes to draw. |
required |
config
|
Optional[TrajectoryConfig]
|
Trajectory configuration. Uses defaults if None. |
None
|
progress_callback
|
Optional[Callable[[int, int, bool], None]]
|
Optional callback(current_point, total_points, success). |
None
|
initial_q
|
Optional[Union[ndarray, Dict[str, float], Trajectory]]
|
Initial joint configuration to start IK solving from. Can be one of: - numpy array of shape (n_joints,) with joint positions in radians - dict mapping joint names to positions in radians - Trajectory object (uses last waypoint) - None (default): use fixed initial pose for drawing This allows sequential trajectory execution where each new trajectory starts from the end position of the previous one. |
None
|
Returns:
| Type | Description |
|---|---|
Trajectory
|
Trajectory object with joint positions for each waypoint. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If roboticstoolbox is not installed. |
RuntimeError
|
If no IK solutions are found. |
Example
from pib3 import image_to_sketch, sketch_to_trajectory sketch = image_to_sketch("drawing.png") trajectory = sketch_to_trajectory(sketch) trajectory.to_json("output.json")
Sequential trajectories¶
traj1 = sketch_to_trajectory(sketch1) traj2 = sketch_to_trajectory(sketch2, initial_q=traj1) # Start from traj1 end
Source code in pib3/trajectory.py
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 | |
Usage¶
import pib3
# Step-by-step approach
sketch = pib3.image_to_sketch("drawing.png")
trajectory = pib3.sketch_to_trajectory(sketch)
# With progress callback
def on_progress(current, total, success):
print(f"Point {current}/{total}: {'OK' if success else 'FAIL'}")
trajectory = pib3.sketch_to_trajectory(
sketch,
progress_callback=on_progress
)
# With custom config
from pib3 import TrajectoryConfig
config = TrajectoryConfig(...)
trajectory = pib3.sketch_to_trajectory(sketch, config)
Trajectory Class¶
Trajectory
dataclass
¶
Robot joint trajectory for executing a drawing.
Stores joint positions in canonical Webots motor radians.
Attributes:
| Name | Type | Description |
|---|---|---|
joint_names |
List[str]
|
Names of joints in order (36 for PIB). |
waypoints |
ndarray
|
Array of shape (N, num_joints) with joint positions in radians. |
metadata |
dict
|
Additional info (paper position, IK stats, etc.) |
__len__
¶
to_json
¶
Save trajectory to JSON file with unit metadata.
Source code in pib3/trajectory.py
from_json
classmethod
¶
Load trajectory from JSON file.
Source code in pib3/trajectory.py
to_webots_format
¶
Convert waypoints to Webots motor positions (identity).
Waypoints are already in absolute radians. Per-joint offsets from the Webots starting position are applied by the backend, not here.
Source code in pib3/trajectory.py
Creating Trajectories¶
import numpy as np
from pib3 import Trajectory
# From arrays
joint_names = ["joint_0", "joint_1", "joint_2"]
waypoints = np.array([
[0.0, 0.0, 0.0],
[0.1, 0.2, 0.3],
[0.2, 0.4, 0.6],
])
trajectory = Trajectory(
joint_names=joint_names,
waypoints=waypoints,
metadata={"source": "custom"}
)
Saving and Loading¶
from pib3 import Trajectory
# Save to JSON
trajectory.to_json("my_trajectory.json")
# Load from JSON
loaded = Trajectory.from_json("my_trajectory.json")
# Access data
print(f"Waypoints: {len(loaded)}")
print(f"Joints: {loaded.joint_names}")
print(f"Metadata: {loaded.metadata}")
Format Conversion¶
# Get waypoints in Webots format (no offset, canonical format)
webots_waypoints = trajectory.to_webots_format()
# Get waypoints in robot format (centidegrees)
robot_waypoints = trajectory.to_robot_format()
JSON Format¶
{
"format_version": "1.0",
"unit": "radians",
"coordinate_frame": "webots",
"joint_names": ["turn_head_motor", "tilt_forward_motor", ...],
"waypoints": [
[0.1, 0.2, 0.3, ...],
[0.15, 0.25, 0.35, ...]
],
"metadata": {
"source": "pib3",
"robot_model": "pib",
"success_rate": 0.95,
"created_at": "2024-01-01T12:00:00Z"
}
}
IK Solver Details¶
The inverse kinematics solver uses:
- Algorithm: Damped Least Squares (DLS) gradient descent
- Convergence: Position error below tolerance
- Limits: Joint limits enforced during solving
- Fallback: Linear interpolation for failed points
Solver Parameters¶
| Parameter | Effect |
|---|---|
max_iterations |
More iterations = better accuracy, slower |
tolerance |
Smaller = more precise, harder to converge |
step_size |
Larger = faster convergence, risk of oscillation |
damping |
Higher = more stable near singularities |