# Motion Planning

Motion planning is about planning a collision free path from one robot configuration to another, avoiding any obstacles in the workspace. In the core RobWork library (rw::pathplanning namespace), there is an interface for such planners called QToQPlanner. RobWork provides a pathplanning library with implementation of various planning algorithms. These are found under the namespace rwlibs::pathplanners and implements the QToQPlanner interface:

 ARWPlanner Adaptive Random Walk Planner API PRMPlanner Probabilistic RoadMap Planner API RRTPlanner Rapidly-exploring Random Tree Planner API SBLPlanner Single-query Bi-directional Lazy collision checking Planner API Z3Planner Z3 Method API

See the API documentation for each of these classes for references to litterature and more information about possible variants of the algorithms.

## Example Scene

We will use the SimplePA10Demo scene for demonstration of pathplanning. This scene has a Mitsubishi PA-10 robot mounted on a gantry. To move from one location in the scene to another requires pathplanning to avoid collisions.

SinglePA10Demo scene from the Device & Scene Collection (RobWorkData).

## Metrics

rw::math::Metric<X> is the general interface for measuring a distance between a pair of values of type X. Path planning algorithms, for example, often require a metric for measuring the distance between configurations.

Metrics available in RobWork include:

• Manhattan metric (rw::math::MetricFactory::makeManhattan(), rw::math::MetricFactory::makeWeightedManhattan())

• Euclidean metric (rw::math::MetricFactory::makeEuclidean(), rw::math::makeWeightedEuclidean())

• Infinity metric (rw::math::MetricFactory::makeInfinity(), rw::math::MetricFactory::makeWeightedInfinity())

These build-in metrics can be instantiated for configuration types (rw::math::Q) and other vector types such as rw::math::Vector3D and std::vector<double>. This program shows instantiation and expected output for 3 different metrics:

1#include <rw/math/Metric.hpp>
2#include <rw/math/MetricFactory.hpp>
3
4using rw::core::Ptr;
5using namespace rw::math;
6
7void metricExample()
8{
9    typedef Vector3D<> V;
10    typedef Ptr<Metric<V> > VMetricPtr;
11
12    VMetricPtr m1 = MetricFactory::makeManhattan<V>();
13    VMetricPtr m2 = MetricFactory::makeEuclidean<V>();
14    VMetricPtr mInf = MetricFactory::makeInfinity<V>();
15
16    const V a(0, 0, 0);
17    const V b(1, 1, 1);
18
19    std::cout
20        << m1->distance(a, b) << " is " << 3.0 << "\n"
21        << m2->distance(a, b) << " is " << sqrt(3.0) << "\n"
22        << mInf->distance(a, b) << " is " << 1 << "\n";
23}

## QIKSolver

For use in planning the IK sampler interface (rw::pathplanning::QIKSampler) hides details of selection of IK solver and start configurations for the solver. The program below tests the default iterative IK solver for a device. The program selects 10 random base to end transforms for a device using the forward kinematics for the device. Using the default IK sampler, the program then checks that an IK solution is found for all transforms. Only a small number of start configurations are used for each target transform, and therefore the IK sampler might not always find an IK solution. If the IK sampler is constrained by the requirement that the IK solutions must be collision free, then solutions for only a subset of the target transforms are found.

2#include <rw/models/WorkCell.hpp>
3#include <rw/pathplanning/QConstraint.hpp>
4#include <rw/pathplanning/QIKSampler.hpp>
5#include <rw/pathplanning/QSampler.hpp>
6#include <rw/proximity/CollisionDetector.hpp>
7#include <rwlibs/proximitystrategies/ProximityStrategyYaobi.hpp>
8
9using rw::core::ownedPtr;
10using rw::kinematics::State;
12using namespace rw::math;
13using namespace rw::models;
14using namespace rw::pathplanning;
15using rw::proximity::CollisionDetector;
16using namespace rwlibs::proximitystrategies;
17
18typedef std::vector<Transform3D<> > TransformPath;
19
20TransformPath getRandomTargets(const Device& device, State state, int targetCnt)
21{
22    TransformPath result;
23    QSampler::Ptr sampler = QSampler::makeUniform(device);
24    for (int cnt = 0; cnt < targetCnt; cnt++) {
25        device.setQ(sampler->sample(), state);
26        result.push_back(device.baseTend(state));
27    }
28    return result;
29}
30
31void printReachableTargets(
32    const TransformPath& targets,
33    QIKSampler& ik)
34{
35    int i = 0;
36    for(const Transform3D<>& target: targets) {
37        const Q q = ik.sample(target);
38        std::cout << i << " " << (q.empty() ? "False" : "True") << "\n";
39        ++i;
40    }
41}
42
43void invkinExample(
44    Device& device, const State& state, QConstraint& constraint)
45{
46    QIKSampler::Ptr ik_any = QIKSampler::make(&device, state, NULL, NULL, 25);
47    QIKSampler::Ptr ik_cfree = QIKSampler::makeConstrained(ik_any, &constraint, 25);
48
49    const TransformPath targets = getRandomTargets(device, state, 10);
50
51    std::cout << "IK solutions found for targets:\n";
52    printReachableTargets(targets, *ik_any);
53
54    std::cout << "Collision free IK solutions found for targets:\n";
55    printReachableTargets(targets, *ik_cfree);
56}
57
58int main(int argc, char** argv)
59{
60    if (argc != 2) {
61        std::cout << "Usage: " << argv[0] << " <workcell-file>\n";
62        exit(1);
63    }
64
66    Device::Ptr device = workcell->getDevices().front();
67    const State state = workcell->getDefaultState();
68
69    CollisionDetector::Ptr detector = ownedPtr( new CollisionDetector(
70        workcell, ProximityStrategyYaobi::make()) );
71
72    QConstraint::Ptr constraint = QConstraint::make(detector, device, state);
73
74    invkinExample(*device, state, *constraint);
75}

## PathPlanning

rw::pathplanning::PathPlanner<From, To, Path> is the general interface for finding a path of type Path connecting a start location of type From and an goal location of type To.

Important variations of this interface includes:

• rw::pathplanning::QToQPlanner: Standard planning of a configuration space path that connects a start configuration to a goal configuration.

• rw::pathplanning::QToTPlanner: Planning of a configuration space path connecting a start configuration to any end configuration for which a spatial constraint represented a value of type rw::math::Transform3D<> is satisfied. Typically, planners of this type find paths for devices such that the tool of the device ends up at the given goal transformation (in other words, the planner of type rw::pathplanning::QToTPlanner implicitly solves an inverse kinematics problem).

• rw::pathplanning::QToQSamplerPlanner: Planning of a configuration space path from a start configuration to any end configuration returned by the sampler (rw::pathplanning::QSampler) representing the goal region.

These 3 planners all represent the resulting path by a sequence of configurations (rw::trajectory::QPath).

The path planners of RobWork are placed in the library rw_pathplanners. The example below instantiates a path planner for the first device of the workcell and plans a number of paths to random collision free configurations of the workcell. The full configuration space path mapped to the corresponding sequence of states (rw::kinematics::State) and written to a file that can be loaded into RobWorkStudio using the PlayBack plugin. The example makes use of configuration space sampling and path planning constraints described in these earlier sections:

1#include <rw/models/WorkCell.hpp>
2#include <rw/models/Models.hpp>
4#include <rw/pathplanning/QSampler.hpp>
5#include <rw/pathplanning/QToQPlanner.hpp>
6#include <rw/proximity/CollisionDetector.hpp>
7#include <rwlibs/proximitystrategies/ProximityStrategyYaobi.hpp>
8#include <rwlibs/pathplanners/sbl/SBLPlanner.hpp>
9
10using rw::math::Q;
11using namespace rw::models;
12using rw::kinematics::State;
13using namespace rw::pathplanning;
14using rw::proximity::CollisionDetector;
16using rwlibs::proximitystrategies::ProximityStrategyYaobi;
17using namespace rwlibs::pathplanners;
18
19void plannerExample(WorkCell& workcell)
20{
21    // The common state for which to plan the paths.
22    const State state = workcell.getDefaultState();
23
24    // The first device of the workcell.
25    Device::Ptr device = workcell.getDevices().front();
26
27    CollisionDetector coldect(&workcell, ProximityStrategyYaobi::make());
28
29    // The q constraint is to avoid collisions.
30    QConstraint::Ptr constraint = QConstraint::make(&coldect, device, state);
31
32    // the edge constraint tests the constraint on edges, eg. edge between two configurations
33    QEdgeConstraintIncremental::Ptr edgeconstraint = QEdgeConstraintIncremental::makeDefault(
34        constraint, device);
35
36    // An SBL based point-to-point path planner.
37    QToQPlanner::Ptr planner = SBLPlanner::makeQToQPlanner(
38        SBLSetup::make(constraint, edgeconstraint, device));
39
40    // A sampler of collision free configurations for the device.
41    QSampler::Ptr cfreeQ = QSampler::makeConstrained(
42        QSampler::makeUniform(device), constraint);
43
44    // The start configuration for the path.
45    Q pos = device->getQ(state);
46
47    // Plan 10 paths to sampled collision free configurations.
48    rw::trajectory::Path<Q> path;
49    for (int cnt = 0; cnt < 10; cnt++) {
50        const Q next = cfreeQ->sample();
51        const bool ok = planner->query(pos, next, path);
52        if (!ok) {
54            return;
55        } else {
56            pos = next;
57        }
58    }
59
60    // Map the configurations to a sequence of states.
61    const std::vector<State> states = Models::getStatePath(*device, path, state);
62
63    // Write the sequence of states to a file.
65        workcell, states, "ex-path-planning.rwplay");
66}

The path planner of the above example is based on the SBL algorithm. This example shows instantiation of some more of the available path planners:

1#include <rw/pathplanning/PlannerConstraint.hpp>
2#include <rwlibs/pathplanners/sbl/SBLPlanner.hpp>
3#include <rwlibs/pathplanners/sbl/SBLSetup.hpp>
4#include <rwlibs/pathplanners/rrt/RRTPlanner.hpp>
5#include <rwlibs/pathplanners/arw/ARWPlanner.hpp>
6
7using rw::models::Device;
8using namespace rw::pathplanning;
9using namespace rwlibs::pathplanners;
10
11QToQPlanner::Ptr getQToQPlanner(
12    Device::Ptr device,
13    const PlannerConstraint constraint,
14    const std::string& type)
15{
16    if (type == "SBL") {
17    	QConstraint::Ptr qconstraint = constraint.getQConstraintPtr();
18        return SBLPlanner::makeQToQPlanner(SBLSetup::make(qconstraint, QEdgeConstraintIncremental::makeDefault(qconstraint,device), device));
19    } else if (type == "RRT") {
20        return RRTPlanner::makeQToQPlanner(constraint, device);
21    } else if (type == "ARW") {
22        return ARWPlanner::makeQToQPlanner(constraint, device);
23    } else {
24        return NULL;
25    }
26}

Variations of these constructor functions have options for example for controlling the configuration space exploration of the planner.

## Workcell and configuration space constraints

A collision detector (rw::proximity::CollisionDetector) is an example of a constraint on the states of a workcell. Collision checking is but one form of constraint, and applications may implement their constraints in terms of other classes than rw::proximity::CollisionDetector.

The general interface for a discrete constraint on states (rw::kinematics::State) is rw::pathplanning::StateConstraint. The method to call to check if a constraint is satisfied for a state is rw::pathplanning::StateConstraint::inCollision(). The naming of the method is only a convention. The constraint need not not be concerned with actual collisions of the workcell. A user may inherit from the interface and implement any kind of constraint they desire.

Path planners and other planners often operate on configurations (rw::math::Q) rather than workcell states (rw::kinematics::State). The interface for a discrete constraint on the configuration space is rw::pathplanning::QConstraint and the method to call to check if the constraint is satisfied is rw::pathplanning::QConstraint::inCollision().

rw::pathplanning::StateConstraint as well as rw::pathplanning::QConstraint provide constructor functions and functions for combining constraints.

A sampling based path planner typically calls a configuration constraint (rw::pathplanning::QConstraint) to verify individual configurations. The path planner connects individual configurations by edges, and verifies if the device can follow the path represented by the edge. The interface for verifying a configuration space path connecting a pair of configurations is called rw::pathplanning::QEdgeConstraint. The method on the interface to verify the edge is rw::pathplanning::QEdgeConstraint::inCollision().

Given a configuration constraint (rw::pathplanning::QConstraint), a constraint for an edge (rw::pathplanning::QEdgeConstraint) can be implemented by discretely checking the edge for collisions. When constructing such edge constraint (see rw::pathplanning::QEdgeConstraint::make()) you can specify the resolution and metric for the discrete verification of the edge, or a default metric and resolution can be used.

A configuration constraint together with an edge constraint is named a planner constraint (rw::pathplanning::PlannerConstraint). rw::pathplanning::PlannerConstraint::make() utility functions are provided to ease the construction of constraints for standard collision detection.

This program constructs a collision detector and corresponding default planner constraint for the first device of the workcell. The program calls the planner constraint to check if the edge from the lower to upper corner of the configuration space can be traversed:

1#include <rw/models/Device.hpp>
2#include <rw/models/WorkCell.hpp>
3#include <rw/pathplanning/PlannerConstraint.hpp>
4#include <rw/proximity/CollisionDetector.hpp>
5#include <rwlibs/proximitystrategies/ProximityStrategyYaobi.hpp>
6
7using rw::core::ownedPtr;
8using rw::math::Q;
9using namespace rw::models;
10using rw::pathplanning::PlannerConstraint;
11using rw::proximity::CollisionDetector;
12using rwlibs::proximitystrategies::ProximityStrategyYaobi;
13
14void constraintExample(WorkCell& workcell)
15{
16    Device::Ptr device = workcell.getDevices().front();
17
18    const PlannerConstraint constraint = PlannerConstraint::make(
19        ownedPtr( new CollisionDetector(
20            &workcell, ProximityStrategyYaobi::make() ) ),
21        device,
22        workcell.getDefaultState());
23
24    const Q start = device->getBounds().first;
25    const Q end = device->getBounds().second;
26
27    std::cout
28        << "Start configuration is in collision: "
29        << constraint.getQConstraint().inCollision(start)
30        << "\n"
31        << "End configuration is in collision: "
32        << constraint.getQConstraint().inCollision(end)
33        << "\n"
34        << "Edge from start to end is in collision: "
35        << constraint.getQEdgeConstraint().inCollision(start, end)
36        << "\n";
37}

## Configuration space sampling

Configuration space sampling is a useful tool for path planners and various other planning algorithms.

The interface for a sampler of the configuration space is rw::pathplanning::QSampler. The rw::pathplanning::QSampler interface provides constructor functions, including:

• rw::pathplanning::QSampler::makeFinite(): Deterministic sampling from a finite sequence of configurations.

• rw::pathplanning::QSampler::makeUniform(): Configurations for a device sampled uniformly at random.

• rw::pathplanning::QSampler::makeConstrained(): A sampler filtered by a constraint.

This example shows the construction of a sampler of collision free configurations. The sampler calls a randomized sampler of the configuration space of the device, and filters these configurations by the constraint that the configurations should be collision free.

1#include <rw/models/WorkCell.hpp>
2#include <rw/models/Device.hpp>
3#include <rw/proximity/CollisionDetector.hpp>
4#include <rw/pathplanning/QConstraint.hpp>
5#include <rw/pathplanning/QSampler.hpp>
6#include <rw/math/Q.hpp>
7#include <rwlibs/proximitystrategies/ProximityStrategyYaobi.hpp>
8
9using rw::core::ownedPtr;
10using rw::math::Q;
11using namespace rw::models;
12using rw::proximity::CollisionDetector;
13using namespace rw::pathplanning;
14using rwlibs::proximitystrategies::ProximityStrategyYaobi;
15
16void samplerExample(WorkCell& workcell)
17{
18    Device::Ptr device = workcell.getDevices().front();
19
20    CollisionDetector::Ptr coldect = ownedPtr( new CollisionDetector(&workcell, ProximityStrategyYaobi::make()) );
21
22    QConstraint::Ptr constraint = QConstraint::make(
23        coldect,
24        device,
25        workcell.getDefaultState());
26
27    QSampler::Ptr anyQ = QSampler::makeUniform(device);
28    QSampler::Ptr cfreeQ = QSampler::makeConstrained(anyQ, constraint);
29
30    for (int i = 0; i < 4; i++) {
31        const Q q = cfreeQ->sample();
32        std::cout
33            << "Q(" << i << ") is in collision: "
34            << constraint->inCollision(q) << "\n";
35    }
36}

## RobWorkStudio Planning Plugin

Open the Planning , Jog and Log plugins.

## C++

1#include <rw/core/Ptr.hpp>
2#include <rw/kinematics/State.hpp>
4#include <rw/math/Q.hpp>
5#include <rw/models/CompositeDevice.hpp>
6#include <rw/models/Device.hpp>
7#include <rw/pathplanning/PlannerConstraint.hpp>
8#include <rw/pathplanning/QToQPlanner.hpp>
9#include <rw/proximity/CollisionDetector.hpp>
10#include <rw/proximity/CollisionStrategy.hpp>
11#include <rw/proximity/ProximityData.hpp>
12#include <rw/trajectory/Path.hpp>
13#include <rwlibs/pathplanners/rrt/RRTPlanner.hpp>
14#include <rwlibs/proximitystrategies/ProximityStrategyFactory.hpp>
15
16using rw::core::ownedPtr;
17using rw::kinematics::State;
19using rw::math::Q;
20using namespace rw::models;
21using namespace rw::proximity;
22using namespace rw::pathplanning;
23using rw::trajectory::QPath;
24using rwlibs::pathplanners::RRTPlanner;
25using rwlibs::proximitystrategies::ProximityStrategyFactory;
26
27#define WC_FILE "/scenes/SinglePA10Demo/SinglePA10DemoGantry.wc.xml"
28
29int main (int argc, char** argv)
30{
31    if (argc != 2) {
32        std::cout << "Usage: " << argv[0] << " <path/to/RobWorkData>" << std::endl;
33        exit (1);
34    }
35    const std::string path = argv[1];
36
38    if (wc.isNull ())
39        RW_THROW ("WorkCell could not be loaded.");
40    const Device::Ptr gantry = wc->findDevice ("Gantry");
41    const Device::Ptr pa10   = wc->findDevice ("PA10");
42    if (gantry.isNull ())
43        RW_THROW ("Gantry device could not be found.");
44    if (pa10.isNull ())
45        RW_THROW ("PA10 device could not be found.");
46
47    const State defState     = wc->getDefaultState ();
48    const Device::Ptr device = ownedPtr (new CompositeDevice (
49        gantry->getBase (), wc->getDevices (), pa10->getEnd (), "Composite", defState));
50
51    const CollisionStrategy::Ptr cdstrategy =
52        ProximityStrategyFactory::makeCollisionStrategy ("PQP");
53    if (cdstrategy.isNull ())
54        RW_THROW ("PQP Collision Strategy could not be found.");
55    const CollisionDetector::Ptr collisionDetector =
56        ownedPtr (new CollisionDetector (wc, cdstrategy));
57    const PlannerConstraint con    = PlannerConstraint::make (collisionDetector, device, defState);
58    const QToQPlanner::Ptr planner = RRTPlanner::makeQToQPlanner (con, device);
59
60    const Q beg (9, -0.67, -0.79, 2.8, -0.02, -1.01, -0.26, -0.77, -1.01, 0);
61    const Q end (9, 0.57, 0.79, -1.23, 0.21, -0.63, -0.55, -0.07, -1.08, 0);
62
63    ProximityData pdata;
64    State state = defState;
65    device->setQ (beg, state);
66    if (collisionDetector->inCollision (state, pdata))
67        RW_THROW ("Initial configuration in collision! can not plan a path.");
68    device->setQ (end, state);
69    if (collisionDetector->inCollision (state, pdata))
70        RW_THROW ("Final configuration in collision! can not plan a path.");
71
72    QPath result;
73    if (planner->query (beg, end, result)) {
74        std::cout << "Planned path with " << result.size ();
75        std::cout << " configurations" << std::endl;
76    }
77
78    return 0;
79}

## Python

1import sdurw_models
2from sdurw import *
4from sdurw_pathplanners import RRTPlanner
5from sdurw_proximitystrategies import ProximityStrategyFactory
6import sys
7
8WC_FILE = "/scenes/SinglePA10Demo/SinglePA10DemoGantry.wc.xml"
9
10if __name__ == '__main__':
11    if len(sys.argv) != 2:
12        print("Usage: python3 " + sys.argv[0] + " <path/to/RobWorkData>")
13        sys.exit(1)
14
16    if wc.isNull():
17        raise Exception("WorkCell could not be loaded")
18    gantry = wc.findDevice("Gantry")
19    pa10 = wc.findDevice("PA10")
20    if gantry.isNull():
21        raise Exception("Gantry device could not be found.")
22    if pa10.isNull():
23        raise Exception("PA10 device could not be found.")
24
25    defState = wc.getDefaultState()
26    device = sdurw_models.ownedPtr(CompositeDevice(gantry.getBase(), wc.getDevices(), pa10.getEnd(), "Composite", defState))
27
28    cdstrategy = ProximityStrategyFactory.makeCollisionStrategy("PQP")
29    if cdstrategy.isNull():
30        raise Exception("PQP Collision Strategy could not be found.")
31    print(device.cptr())
32    collisionDetector = sdurw_proximity.ownedPtr(CollisionDetector(wc, cdstrategy))
33    con = PlannerConstraint.make(collisionDetector, device, defState)
34    planner = RRTPlanner.makeQToQPlanner(con, device.asDevicePtr())
35
36    beg = Q(9, -0.67, -0.79, 2.8, -0.02, -1.01, -0.26, -0.77, -1.01, 0)
37    end = Q(9, 0.57, 0.79, -1.23, 0.21, -0.63, -0.55, -0.07, -1.08, 0)
38
39    pdata = ProximityData()
40    state = defState
41    device.setQ(beg, state)
42    if collisionDetector.inCollision(state, pdata):
43        raise Exception("Initial configuration in collision!")
44    device.setQ(end, state)
45    if collisionDetector.inCollision(state, pdata):
46        raise Exception("Final configuration in collision!")
47
48    result = []
49    if planner.query(beg, end, result):
50        print("Planned path with " + str(len(result)) + " configurations")

## Java

1import java.lang.String;
3import org.robwork.sdurw.*;
4import org.robwork.sdurw_math.*;
5import org.robwork.sdurw_models.*;
6import org.robwork.sdurw_kinematics.*;
7import org.robwork.sdurw_proximity.*;
8import static org.robwork.sdurw.sdurw.ownedPtr;
9import org.robwork.sdurw_pathplanners.RRTPlanner;
10import org.robwork.sdurw_proximitystrategies.ProximityStrategyFactory;
11
12public class ExMotionPlanning {
13    public static final String WC_FILE =
14            "/scenes/SinglePA10Demo/SinglePA10DemoGantry.wc.xml";
15
16    public static void main(String[] args) throws Exception {
24
25        if (args.length != 1) {
26            System.out.print("Usage: java " + ExMotionPlanning.class.getSimpleName());
27            System.out.println(" <path/to/RobWorkData>");
28            System.exit(1);
29        }
30
32        if (wc.isNull())
33            throw new Exception("WorkCell could not be loaded.");
34        DevicePtr gantry = wc.findDevice("Gantry");
35        DevicePtr pa10 = wc.findDevice("PA10");
36        if (gantry.isNull())
37            throw new Exception("Gantry device could not be found.");
38        if (pa10.isNull())
39            throw new Exception("PA10 device could not be found.");
40
41        State defState = wc.getDefaultState();
42        CompositeDevicePtr device = sdurw_models.ownedPtr(new CompositeDevice(new FramePtr(gantry.getBase()),
43                wc.getDevices(), new FramePtr(pa10.getEnd()), "Composite", defState));
44
45        CollisionStrategyPtr cdstrategy =
46                ProximityStrategyFactory.makeCollisionStrategy("PQP");
47        if (cdstrategy.isNull())
48            throw new Exception("PQP Collision Strategy could not be found.");
49        CollisionDetectorPtr collisionDetector = sdurw_proximity.ownedPtr(
50                new CollisionDetector(wc, cdstrategy));
51        PlannerConstraint con = PlannerConstraint.make(collisionDetector,
52                device.asDeviceCPtr(), defState);
53        QToQPlannerPtr planner = RRTPlanner.makeQToQPlanner(con, device.asDevicePtr());
54        State state = wc.getDefaultState();
55
56        final Q beg = new Q(9, -0.67, -0.79, 2.8, -0.02, -1.01, -0.26, -0.77, -1.01, 0);
57        final Q end = new Q(9, 0.57, 0.79, -1.23, 0.21, -0.63, -0.55, -0.07, -1.08, 0);
58
59        ProximityData pdata = new ProximityData();
60        device.setQ(beg, state);
61        if (collisionDetector.inCollision(state, pdata))
62            throw new Exception("Initial configuration in collision!");
63        device.setQ(end, state);
64        if (collisionDetector.inCollision(state, pdata))
65            throw new Exception("Final configuration in collision!");
66
67        PathQ result = new PathQ();
68        if (planner.query(beg, end, result)) {
69            System.out.print("Planned path with " + result.size());
70            System.out.println(" configurations");
71        }
72    }
73}

## LUA

This example shows how pathplanning can be done in a LUA script. You can run this script directly in the RobWorkStudio LUA plugin. If you want to run the script without RobWorkStudio, see the Standalone LUA section.

1require("sdurw_core")
2require("sdurw_models")
3require("sdurw_proximity")
5require("sdurw_trajectory")
6require("sdurw_pathplanning")
7require("sdurw")
8require("sdurw_pathplanners")
9require("sdurw_proximitystrategies")
10using("sdurw_models")
11using("sdurw_proximity")
13using("sdurw_trajectory")
14using("sdurw")
15using("sdurw_pathplanning")
16using("sdurw_pathplanners")
17using("sdurw_proximitystrategies")
18
19require("sdurw_math")
20using("sdurw_math")
21
22if #arg ~= 1 then
23    print("Usage: lua ex-motionplanning.lua <path/to/RobWorkData>")
24    return 1
25end
26
27local WC_FILE = "/scenes/SinglePA10Demo/SinglePA10DemoGantry.wc.xml"
28
30if wc:isNull() then
31    error("WorkCell could not be loaded")
32end
33local gantry = wc:findDevice("Gantry")
34local pa10 = wc:findDevice("PA10")
35if gantry:isNull() then
36    error("Gantry device could not be found.")
37end
38if pa10:isNull() then
39    error("PA10 device could not be found.")
40end
41
42local state = wc:getDefaultState()
43local device = sdurw_models.ownedPtr(CompositeDevice(gantry:getBase(), wc:getDevices(),
44                        pa10:getEnd(), "Composite", state))
45
46local cdstrategy = sdurw_proximitystrategies.ProximityStrategyFactory.makeCollisionStrategy("PQP")
47if cdstrategy:isNull() then
48    error("PQP Collision Strategy could not be found.")
49end
50local collisionDetector = sdurw_proximity.ownedPtr(CollisionDetector(wc, cdstrategy))
51local con = PlannerConstraint.make(collisionDetector, device:asDeviceCPtr(), state)
52local planner = RRTPlanner.makeQToQPlanner(con, device:asDevicePtr())
53
54local beg = Q(9, -0.67, -0.79, 2.8, -0.02, -1.01, -0.26, -0.77, -1.01, 0)
55local fin = Q(9, 0.57, 0.79, -1.23, 0.21, -0.63, -0.55, -0.07, -1.08, 0)
56
57local pdata = ProximityData()
58device:setQ(beg, state)
59if collisionDetector:inCollision(state, pdata) then
60    error("Initial configuration in collision!")
61end
62device:setQ(fin, state)
63if collisionDetector:inCollision(state, pdata) then
64    error("Final configuration in collision!")
65end
66
67local result = PathQ()
68if planner:query(beg, fin, result) then
69    print("Planned path with " .. result:size() .. " configurations")
70end

In lines 8-26 the WorkCell is loaded, and the two devices ‘Gantry’ and ‘PA10’ are extracted. Rember to check is the returned smart pointers are null, as this would indicate that something went wrong. If you continue without checking, you will likely end up with segmentation errors.

In lines 28 and 29, we first get the default state of the workcell. This is used to construct a new CompositeDevice. The CompositeDevice will make the two devices act as one device to the pathplanning algorithms. As the PA10 device is placed at the end of the Gantry device, we specify the base frame to be the PA10 base frame, and the end frame to be the PA10 end frame. The name of the device will be “Composite” and we construct the CompositeDevice from all the devices in the WorkCell (assuming there is only the two). If you only have one device to plan for, there is obviously no need for constructing a CompositeDevice. Instead, use the device in the WorkCell directly.

In lines 32-35 a CollisionStrategy is created. We base this on the PQP strategy. Remember to check that the returned smart pointer is not null before continuing.

In lines 36-38 a CollisionDetector is created based on this collision strategy. The detector is then wrapped in a PlannerConstraint. Finally, a RRTPlanner is constructed based on the PlannerConstraint. The planner works for our CompositeDevice.

In lines 40-51 the initial and goal configurations are defined. Before planning, we first check that these are collision free. The CollisionDetector uses the ProximityData structure to speed up collision detection by performing caching inbetween calls to inCollision.

Finally, in line 43-56, we do the actual pathplanning query. The result will be stored in the PathQ object, and we print the size of the path.

### LUA API References

There is currently no separate API documentation for the LUA interface. Instead, see the references for Python and Java in API References. These are very similar to the LUA interface.

### Standalone LUA

The code above will work when executed from the RobWorkStudio Lua plugin. It is also possible to execute the LUA script in a standalone script without using RobWorkStudio. In the RobWork/bin directory there will be a executable called ‘lua’ which is the LUA interpreter that can be used to execute standalone scripts. The script to execute must be given as the first argument to this program.

1package.cpath = package.cpath .. ";/path/to/RobWork/libs/relwithdebinfo/lib?_lua.so"
2require("rw")
3require("rw_pathplanners")
4require("rw_proximitystrategies")
5
6function openpackage (ns)
7  for n,v in pairs(ns) do
8    if _G[n] ~= nil then
9      print("name clash: " .. n .. " is already defined")
10    else
11      _G[n] = v
12    end
13  end
14end
15
16openpackage(rw)
17openpackage(rw_pathplanners)
18openpackage(rw_proximitystrategies)
19
20-- then all of the above

You must tell LUA where to find the native RobWork libraries. This is done in the first line by appending to the LUA cpath. In line 2-4 the necessary native libraries are loaded. The question mark in line 1 is automatically substituted by the names given to require.

Lines 6 to 18 is optional. By default, the imported package functions are refered to by scoped names, such as ‘rw_pathplanners.RRTPlanner’. By using the openpackage function, all these scoped names are moved to the global table. That means you can refer directly to the RobWork types, for instance with ‘RRTPlanner’ instead of the longer ‘rw_pathplanners.RRTPlanner’. To just import a single type to global namespace, you could instead specify

local RRTPlanner = rw_pathplanners.RRTPlanner

After this initial import of the native libraries, the script in the LUA section can be run.

## API References

Below is a list of relevant API references to the types used in the example, in the order they are used. Use this if you want to know more about options and finetuning of the algorithms.

 C++ API Python API Reference Javadoc rw::loaders::WorkCellLoader::Factory rw.WorkCellLoaderFactory org.robwork.rw.WorkCellLoaderFactory rw::models::Device::Ptr rw.DevicePtr org.robwork.rw.DevicePtr rw::kinematics::State rw.State org.robwork.rw.State rw::models::CompositeDevice rw.CompositeDevice org.robwork.rw.CompositeDevice rw.CompositeDevicePtr org.robwork.rw.CompositeDevicePtr rwlibs::proximitystrategies::ProximityStrategyFactory rw_proximitystrategies.ProximityStrategyFactory org.robwork.rw_proximitystrategies.ProximityStrategyFactory rw::proximity::CollisionDetector rw.CollisionDetector org.robwork.rw.CollisionDetector rw::pathplanning::PlannerConstraint rw.PlannerConstraint org.robwork.rw.PlannerConstraint rwlibs::pathplanners::RRTPlanner rw_pathplanners.RRTPlanner org.robwork.rw_pathplanners.RRTPlanner rw::math::Q rw.Q org.robwork.rw.Q rw::proximity::ProximityData rw.ProximityData org.robwork.rw.ProximityData rw::trajectory::QPath rw.PathQ org.robwork.rw.PathQ