Examples

Runnable, self-contained scripts live under examples/ in the repository. Each one exposes a run_example() function and can also be run directly, e.g.:

python examples/example_tm.py

Transformations

example_tm.py walks through building tm transforms from lists, arrays, rotation matrices, and quaternions, and combining them with the overloaded arithmetic operators.

 1import numpy as np
 2from basic_robotics.general import tm
 3
 4# Import the disp library to properly view instances of the transformations
 5from basic_robotics.utilities.disp import disp
 6
 7#The transformation library allows for seamless usage of rotation matrices and other forms of rotation information encoding.
 8
 9def run_example():
10    identity_matrix = tm()
11    disp(identity_matrix, 'identity') #This is just zeros in TAA format.
12
13    #Let's create a few more.
14    trans_x_2m = tm([2, 0, 0, 0, 0, 0]) #Translations can be created with a list (Xm, Ym, Zm, Xrad, Yrad, Zrad)
15    trans_y_4m = tm(np.array([0, 4, 0, 0, 0, 0])) # Translations can be created with a numpy array
16    rot_z_90 = tm([0, 0, 0, 0, 0, np.pi/2]) # Rotations can be declared in radians
17    trans_z_2m_neg = tm(np.array([[1, 0, 0, 0],[0, 1, 0, 0],[0, 0, 1, -2], [0, 0, 0, 1]]))
18    # Transformations can be created from rotation matrices
19
20    trans_x_2m_quat = tm([2, 0, 0, 0, 0, 0, 1]) # Transformations can even be declared with quaternions
21
22    list_of_transforms = [trans_x_2m, trans_y_4m, rot_z_90]
23    disp(list_of_transforms, 'transform list') # List of transforms will be displayed in columns
24
25    #Operations
26    new_simple_transform = trans_x_2m + trans_y_4m #Additon is element-wise on TAA form
27    new_transform_multiplied = trans_x_2m @ trans_y_4m #Transformation matrix multiplication uses '@'
28    new_double_transform = trans_x_2m * 2 # Multiplication by a scalar is elementwise
29
30    #And more visible in the function list documentation
31if __name__ == '__main__':
32    run_example()

Serial Arm (manual construction)

example_arm.py builds a 6-DOF serial arm by hand from screw axes, link transforms, and per-link inertia, then draws it with matplotlib.

 1import numpy as np
 2from basic_robotics.general import tm, fsr
 3from basic_robotics.kinematics import Arm
 4from basic_robotics.plotting.vis_matplotlib import plt, DrawArm
 5
 6
 7def run_example():
 8    fig = plt.figure()
 9    ax = plt.axes(projection = '3d')
10    ax.set_xlim3d(-3,3)
11    ax.set_ylim3d(-3,3)
12    ax.set_zlim3d(0,6)
13    Base_T = tm() # Set a transformation for the base
14
15            # Define some link lengths
16    L1 = 3
17    L2 = 3
18    L3 = 3
19    W = 0.1
20    # Define the transformations of each link
21    Tspace = [tm(np.array([[0],[0],[L1/2],[0],[0],[0]])),
22        tm(np.array([[L2/2],[0],[L1],[0],[0],[0]])),
23        tm(np.array([[L2+(L3/2)],[0],[L1],[0],[0],[0]])),
24        tm(np.array([[L2+L3+(W/2)],[0],[L1],[0],[0],[0]])),
25        tm(np.array([[L2+L3+W+(W/2)],[0],[L1],[0],[0],[0]])),
26        tm(np.array([[L2+L3+W+W+(W/2)],[0],[L1],[0],[0],[0]]))]
27    basic_arm_end_effector_home = fsr.TAAtoTM(np.array([[L2+L3+W+W+W],[0],[L1],[0],[0],[0]]))
28
29    basic_arm_joint_axes = np.array([[0, 0, 1],[0, 1, 0],[0, 1, 0],[1, 0, 0],[0, 1, 0],[1, 0, 0]]).conj().T
30    basic_arm_joint_homes = np.array([[0, 0, 0],[0, 0, L1],[L2, 0, L1],[L2+L3, 0, L1],[L2+L3+W, 0, L1],[L2+L3+2*W, 0, L1]]).conj().T
31    basic_arm_screw_list = np.zeros((6,6))
32
33    #Create the screw list
34    for i in range(0,6):
35        basic_arm_screw_list[0:6,i] = np.hstack((basic_arm_joint_axes[0:3,i],np.cross(basic_arm_joint_homes[0:3,i],basic_arm_joint_axes[0:3,i])))
36
37    #Input some basic dimensions
38    basic_arm_link_box_dims = np.array([[W, W, L1],[L2, W, W],[L3, W, W],[W, W, W],[W, W, W],[W, W, W]]).conj().T
39    basic_arm_link_mass_transforms = [None] * (len(basic_arm_screw_list) + 1)
40    basic_arm_link_mass_transforms[0] = Tspace[0]
41
42    #Set mass transforms
43    for i in range(1,6):
44        basic_arm_link_mass_transforms[i] = (Tspace[i-1].inv() @ Tspace[i])
45    basic_arm_link_mass_transforms[6] = (Tspace[5].inv() @ basic_arm_end_effector_home)
46    masses = np.array([20, 20, 20, 1, 1, 1])
47    basic_arm_inertia_list = np.zeros((6,6,6))
48
49    #Create spatial inertia matrices for links
50    for i in range(6):
51        basic_arm_inertia_list[i,:,:] = fsr.boxSpatialInertia(masses[i],basic_arm_link_box_dims[0,i],basic_arm_link_box_dims[1,i],basic_arm_link_box_dims[2,i])
52
53    # Create the arm from the above paramters
54    arm = Arm(Base_T,basic_arm_screw_list,basic_arm_end_effector_home,basic_arm_joint_homes,basic_arm_joint_axes)
55
56    #ALTERNATIVELY, JUST LOAD A URDF USING THE 'loadArmFromURDF' function in basic_robotics.kinematics
57    arm.setJointProperties(
58            np.array([np.pi, np.pi, np.pi, np.pi, np.pi, np.pi])* -2,
59            np.array([np.pi, np.pi, np.pi, np.pi, np.pi, np.pi]) * 2)
60    arm.setOrigins(link_homes_global = Tspace)
61    arm.setMassProperties(masses, basic_arm_link_mass_transforms, basic_arm_inertia_list)
62    arm.setVisColProperties(link_dimensions = basic_arm_link_box_dims)
63
64    #Draw the arm at a couple positions
65    #DrawArm(arm, ax, jdia = .3)
66    goal = arm.FK(np.array([np.pi/2, np.pi/4, -np.pi/4+.1, 0, 0, 0]))
67    DrawArm(arm, ax, jdia = .3)
68    plt.show()
69
70if __name__ == '__main__':
71    run_example()

Serial Arm (minimal setup + static forces)

example_arm_minimal.py builds the same arm with only the parameters required for kinematics, then computes joint torques and cross-moments needed to resist an applied end-effector wrench.

 1import numpy as np
 2from basic_robotics.general import tm, fsr, Wrench
 3from basic_robotics.kinematics import Arm
 4from basic_robotics.plotting.vis_matplotlib import plt, DrawArm
 5from basic_robotics.utilities.disp import disp
 6
 7
 8def run_example():
 9    fig = plt.figure()
10    ax = plt.axes(projection = '3d')
11    ax.set_xlim3d(-3,3)
12    ax.set_ylim3d(-3,3)
13    ax.set_zlim3d(0,6)
14    Base_T = tm() # Set a transformation for the base
15
16            # Define some link lengths
17    L1 = 3
18    L2 = 3
19    L3 = 3
20    W = 0.1
21    # Define the transformations of each link
22    basic_arm_end_effector_home = fsr.TAAtoTM(np.array([[L2+L3+W+W+W],[0],[L1],[0],[0],[0]]))
23
24    basic_arm_joint_axes = np.array([[0, 0, 1],[0, 1, 0],[0, 1, 0],[1, 0, 0],[0, 1, 0],[1, 0, 0]]).conj().T
25    basic_arm_joint_homes = np.array([[0, 0, 0],[0, 0, L1],[L2, 0, L1],[L2+L3, 0, L1],[L2+L3+W, 0, L1],[L2+L3+2*W, 0, L1]]).conj().T
26    basic_arm_screw_list = np.zeros((6,6))
27
28    #Create the screw list
29    for i in range(0,6):
30        basic_arm_screw_list[0:6,i] = np.hstack((basic_arm_joint_axes[0:3,i],np.cross(basic_arm_joint_homes[0:3,i],basic_arm_joint_axes[0:3,i])))
31
32    #Input some basic dimensions
33    basic_arm_link_box_dims = np.array([[W, W, L1],[L2, W, W],[L3, W, W],[W, W, W],[W, W, W],[W, W, W]]).conj().T
34
35    # Create the arm from the above paramters
36    arm = Arm(Base_T,basic_arm_screw_list,basic_arm_end_effector_home,basic_arm_joint_homes,basic_arm_joint_axes)
37
38    #ALTERNATIVELY, JUST LOAD A URDF USING THE 'loadArmFromURDF' function in basic_robotics.kinematics
39    arm.setJointProperties(
40            np.array([np.pi, np.pi, np.pi, np.pi, np.pi, np.pi])* -2,
41            np.array([np.pi, np.pi, np.pi, np.pi, np.pi, np.pi]) * 2)
42    arm.setVisColProperties(link_dimensions = basic_arm_link_box_dims)
43
44    #Draw the arm at a couple positions
45    #DrawArm(arm, ax, jdia = .3)
46    goal = arm.FK(np.array([np.pi/2, np.pi/4, -np.pi/4+.1, -np.pi/6, np.pi/6, np.pi/8]))
47    wrench = Wrench(np.array([3, 5, -40]), arm.getEEPos(), tm())
48    torques = arm.staticForces(wrench)
49    wrench_list = arm.staticForcesWithCrossMoments(wrench)
50
51    disp(torques, "torques")
52    disp(wrench_list, "wrench list")
53
54    DrawArm(arm, ax, jdia = .3)
55    plt.show()
56
57if __name__ == '__main__':
58    run_example()

Stewart Platform

example_sp.py loads a Stewart platform from a JSON parameter file and draws it with matplotlib.

 1import json
 2import os
 3import matplotlib.pyplot as plt
 4
 5import basic_robotics #Import the General Library
 6from basic_robotics.general import tm #Import transformation library
 7from basic_robotics.utilities.disp import disp
 8# SP Tests
 9disp("Beginning SP Test")
10from basic_robotics.kinematics import loadSP
11from basic_robotics.plotting.vis_matplotlib import drawSP
12
13def run_example():
14    basic_sp = {
15    "Name":"Basic SP","Type":"SP","BottomPlate":{"Thickness":0.1,"JointRadius":0.9,"JointSpacing":9,"Mass": 6},
16    "TopPlate":{"Thickness":0.16,"JointRadius":0.3,"JointSpacing":25,"Mass": 1},
17    "Actuators":{"MinExtension":0.75,"MaxExtension":1.5,"MotorMass":0.5,"ShaftMass":0.9,"ForceLimit": 800,"MotorCOGD":0.2,"ShaftCOGD":0.2},
18    "Drawing":{"TopRadius":1,"BottomRadius":1,"ShaftRadius": 0.1,"MotorRadius": 0.2},
19    "Settings":{"MaxAngleDev":55,"GenerateActuators":0,"IgnoreRestHeight":1,"UseSpin":0,"AssignMasses":1,"InferActuatorCOG":1},
20    "Params":{"RestHeight":1.2,"Spin":30}}
21
22    basic_sp_string = json.dumps(basic_sp)
23    with open ('sp_test_data.json', 'w') as outfile:
24        outfile.write(basic_sp_string)
25
26    sp_model = loadSP('sp_test_data.json', '')
27    fig = plt.figure()
28    ax = plt.axes(projection = '3d')
29    ax.set_xlim3d(-1,1)
30    ax.set_ylim3d(-1,1)
31    ax.set_zlim3d(0,2)
32
33    #Delete file
34    os.remove('sp_test_data.json')
35    drawSP(sp_model, ax)
36    plt.show()
37
38if __name__ == '__main__':
39    run_example()

Stewart Platform Static Forces

example_sp_forces.py extends the basic Stewart platform example with an applied top-plate wrench, solving for the resulting leg forces.

 1import json
 2import os
 3import matplotlib.pyplot as plt
 4import numpy as np
 5
 6import basic_robotics #Import the General Library
 7from basic_robotics.general import tm, fsr
 8from basic_robotics.utilities.disp import disp
 9# SP Tests
10disp("Beginning SP Test")
11from basic_robotics.kinematics import loadSP
12from basic_robotics.plotting.vis_matplotlib import drawSP, drawWrench
13
14def run_example():
15    basic_sp = {
16    "Name":"Basic SP","Type":"SP","BottomPlate":{"Thickness":0.1,"JointRadius":0.9,"JointSpacing":9,"Mass": 6},
17    "TopPlate":{"Thickness":0.16,"JointRadius":0.3,"JointSpacing":25,"Mass": 1},
18    "Actuators":{"MinExtension":0.75,"MaxExtension":1.5,"MotorMass":0.5,"ShaftMass":0.9,"ForceLimit": 800,"MotorCOGD":0.2,"ShaftCOGD":0.2},
19    "Drawing":{"TopRadius":1,"BottomRadius":1,"ShaftRadius": 0.1,"MotorRadius": 0.2},
20    "Settings":{"MaxAngleDev":55,"GenerateActuators":0,"IgnoreRestHeight":1,"UseSpin":0,"AssignMasses":1,"InferActuatorCOG":1},
21    "Params":{"RestHeight":1.2,"Spin":30}}
22
23    basic_sp_string = json.dumps(basic_sp)
24    with open ('sp_test_data.json', 'w') as outfile:
25        outfile.write(basic_sp_string)
26
27    sp_model = loadSP('sp_test_data.json', '')
28    fig = plt.figure()
29    ax = plt.axes(projection = '3d')
30    ax.set_xlim3d(-1,1)
31    ax.set_ylim3d(-1,1)
32    ax.set_zlim3d(0,2)
33
34    #Delete file
35    os.remove('sp_test_data.json')
36
37
38    goal_position = tm([0, 0, 1.0, 0, -np.pi/6, 0])
39    sp_model.IK(goal_position)
40
41    #Make a Wrench Acting in Global Space
42    wrench = fsr.makeWrench(sp_model.getTopT(), 5, sp_model.grav)
43    #                       positiona applied,  Kg  [0, 0, -9.81]
44
45    #Ignore masses of the platform itself.
46    tau = sp_model.staticForces(wrench)
47    disp(tau, 'Leg Forces')
48
49    #Include masses of the platform itself.
50    tau = sp_model.carryMassCalc(wrench)[0]
51    disp(tau, 'platform version')
52
53    drawSP(sp_model, ax, forces=True)
54    drawWrench(wrench, 5*9.81, ax)
55    #Plotting will show forces.
56    plt.show()
57
58if __name__ == '__main__':
59    run_example()

Path Planning

example_path_planning.py loads an arm from a URDF and plans a collision-aware joint-space path between two configurations with RRT*.

 1import random
 2from basic_robotics.general import tm
 3from basic_robotics.kinematics import loadArmFromURDF
 4from basic_robotics.path_planning import RRTStar, PathNode
 5from basic_robotics.plotting.vis_matplotlib import *
 6
 7def run_example():
 8    fig = plt.figure()
 9    ax = plt.axes(projection = '3d')
10    ax.set_xlim3d(-1,1)
11    ax.set_ylim3d(-1,1)
12    ax.set_zlim3d(0,2)
13    arm = loadArmFromURDF('tests/test_helpers/irb_2400.urdf')
14
15    #Generate an RRT* instance
16    init = arm.getEEPos()
17    rrt = RRTStar(init)
18    rrt.addObstruction([0.5, 0.5, 0.7], [1.2, 1.2, 1.2]) # Add some random obstructions
19    rrt.addObstruction([0.5, 0.5, -2], [1, 1, 0.5])
20    
21
22    goal = arm.FK(np.array([np.pi/3, np.pi/3, -np.pi/8, np.pi/10, -np.pi/4, np.pi/5]))
23    arm.FK(np.zeros(6))
24
25    DrawObstructions(rrt.obstructions, ax) #Draw the obstructions for visulization
26
27    #Find a path through the environment
28    random.seed(10)
29    traj = rrt.findPathGeneral(
30    lambda: rrt.generalGenerateTree( # Generate a general RRT* tree using:
31        lambda : PathNode(arm.randomPos()), # Random generation for path nodes
32        lambda x, y : rrt.distance(x, y), # Distance between nodes as a cost
33        lambda x, y : rrt.armObstruction(arm,x,y)), #Basic rtree collision detection as obstruction checking
34    goal) # Goal position
35
36    DrawRRTPath(traj, ax, 'green') # Draw the finalized path
37    arm.IK(traj[-2])
38    DrawArm(arm, ax)
39
40    plt.show() #Show the plot
41
42if __name__ == '__main__':
43    run_example()

Three.js Web Visualization

example_3js_vis.py streams an arm’s pose to the bundled three.js web client. Start the server first with python -m basic_robotics.plotting.vis_3js_server.

 1import time
 2from basic_robotics.kinematics import loadArmFromURDF
 3from basic_robotics.plotting.vis_3js_client import *
 4import os
 5import numpy as np
 6
 7def run_example():
 8
 9    c = DrawClient()
10    c.delete()
11    c.makeFloor()
12    arm = loadArmFromURDF(
13        os.path.abspath(
14            './tests/test_helpers/ur_description/ur10.urdf'))
15    arm_vis = ArmPlot("UR5", arm, c)
16    for i in np.linspace(-np.pi, np.pi, 6000):
17        time.sleep(0.001)#30FPS
18        arm.FK(np.array([i, i, i, i, 0, 0]))
19        arm_vis.update(True)
20
21if __name__ == '__main__':
22    run_example()

OPC UA Communications

example_ua_comm.py demonstrates wiring up OPCUA_Client com ports against a running OPC UA server (e.g. the Prosys demo server).

 1from basic_robotics.interfaces import OPCUA_Client
 2
 3def run_example():
 4    opc = OPCUA_Client('tcp://localhost:48010')
 5    try:
 6        opc.newComPort('Boiler1_FillLevel', "OPCEndpoint", ["0:Objects", "2:Demo","2:BoilerDemo","2:Boiler1", "2:FillLevelSensor", "2:FillLevel"])
 7        opc.newComPort('Boiler2_FillLevelSetpoint', "OPCEndpoint", ["0:Objects", "2:Demo","2:BoilerDemo","2:Boiler1", "2:FillLevelSetPoint"])
 8
 9        opc.openCom()
10        #print(opc.getData("Boiler1_temp"))
11        print(opc.getData("Boiler1_FillLevel"))
12
13
14        print(opc.getData("Boiler2_FillLevelSetpoint"))
15
16        opc.sendData("Boiler2_FillLevelSetpoint", 7.9)
17        print(opc.getData("Boiler2_FillLevelSetpoint"))
18        opc.sendData("Boiler2_FillLevelSetpoint", 0.0)
19
20        opc.closeCom()
21    except Exception as e:
22        print(e)
23        opc.closeCom()