createPlanningTemplate

Create sample implementation for path planning interface

Description

example

createPlanningTemplate creates a planning template for a subclass of the nav.StateSpace class. The function opens a file in the MATLAB® Editor. Save your custom implementation and ensure the file is available on the MATLAB path. Alternative syntax: createPlanningTemplate("StateSpace")

example

createPlanningTemplate("StateValidator") creates a template for a subclass of the nav.StateValidator class.

Examples

collapse all

This example shows how to use the createPlanningTemplate function to generate a template for customizing your own state space definition and sampler to use with path planning algorithms. A simple implementation is provided with the template.

Call the create template function. This function generates a class definition file for you to modify for your own implementation.

createPlanningTemplate

Class and Property Definition

The first part of the template specifies the class definition and any properties for the class. Derive from the nav.StateSpace class. For this example, create a property for the uniform and normal distributions. You can specify any additional user-defined properties here.

classdef MyCustomStateSpace < nav.StateSpace & ...
        matlabshared.planning.internal.EnforceScalarHandle
     properties
        UniformDistribution
        NormalDistribution
        % Specify additional properties here
    end

Save your custom state space class and ensure your file name matches the class name.

Class Constructor

Use the constructor to set the name of the state space, the number of state variables, and define its boundaries. Alternatively, you can add input arguments to the function and pass the variables in when you create an object.

  • For each state variable, define the [min max] values for the state bounds.

  • Call the constructor of the base class.

  • For this example, you specify the normal and uniform distribution property values using predefined NormalDistribution and UniformDistribution classes.

  • Specify any other user-defined property values here.

 methods
        function obj = MyCustomStateSpace
            spaceName = "MyCustomStateSpace";
            numStateVariables = 3;
            stateBounds = [-100 100;  % [min max]
                           -100 100;
                           -100 100];
            
            obj@nav.StateSpace(spaceName, numStateVariables, stateBounds);
            
            obj.NormalDistribution = matlabshared.tracking.internal.NormalDistribution(numStateVariables);
            obj.UniformDistribution = matlabshared.tracking.internal.UniformDistribution(numStateVariables);
            % User-defined property values here
        end

Copy Semantics

Specify the copy method definition. Copy all the values of your user-defined variables into a new object, so copyObj is a deep copy. The default behavior given in this example creates a new copy of the object with the same name, state bounds, and distributions.

        function copyObj = copy(obj)
            copyObj = feval(class(obj));
            copyObj.StateBounds = obj.StateBounds;
            copyObj.UniformDistribution = obj.UniformDistribution.copy;
            copyObj.NormalDistribution = obj.NormalDistribution.copy;
        end

Enforce State Bounds

Specify how to ensure states are always within the state bounds. For this example, the state values get saturated at the minimum or maximum values for the state bounds.

        function boundedState = enforceStateBounds(obj, state)
            nav.internal.validation.validateStateMatrix(state, nan, obj.NumStateVariables, "enforceStateBounds", "state");
            boundedState = state;
            boundedState = min(max(boundedState, obj.StateBounds(:,1)'), ...
                obj.StateBounds(:,2)');
            
        end

Sample Uniformly

Specify the behavior for sampling across a uniform distribution. support multiple syntaxes to constrain the uniform distribution to a nearby state within a certain distance and sample multiple states.

STATE = sampleUniform(OBJ)
STATE = sampleUniform(OBJ,NUMSAMPLES)
STATE = sampleUniform(OBJ,NEARSTATE,DIST)
STATE = sampleUniform(OBJ,NEARSTATE,DIST,NUMSAMPLES)

For this example, use a validation function to process a varargin input that handles the varying input arguments.

         function state = sampleUniform(obj, varargin)
            narginchk(1,4);
            [numSamples, stateBounds] = obj.validateSampleUniformInput(varargin{:});
            
            obj.UniformDistribution.RandomVariableLimits = stateBounds;
            state = obj.UniformDistribution.sample(numSamples);
        end

Sample from Gaussian Distribution

Specify the behavior for sampling across a Gaussian distribution. Support multiple syntaxes for sampling a single state or multiple states.

STATE = sampleGaussian(OBJ, MEANSTATE, STDDEV)
STATE = sampleGaussian(OBJ, MEANSTATE, STDDEV, NUMSAMPLES)

        function state = sampleGaussian(obj, meanState, stdDev, varargin)    
            narginchk(3,4);
            
            [meanState, stdDev, numSamples] = obj.validateSampleGaussianInput(meanState, stdDev, varargin{:});
            
            obj.NormalDistribution.Mean = meanState;
            obj.NormalDistribution.Covariance = diag(stdDev.^2);
            
            state = obj.NormalDistribution.sample(numSamples);
            state = obj.enforceStateBounds(state);
            
        end

Interpolate Between States

Define how to interpolate between two states in your state space. Use an input, fraction, to determine how to sample along the path between two states. For this example, define a basic linear interpolation method using the difference between states.

        function interpState = interpolate(obj, state1, state2, fraction)
            narginchk(4,4);
            [state1, state2, fraction] = obj.validateInterpolateInput(state1, state2, fraction);
            
            stateDiff = state2 - state1;
            interpState = state1 + fraction' * stateDiff;
        end

Calculate Distance Between States

Specify how to calculate the distance between two states in your state space. Use the state1 and state2 inputs to define the start and end positions. Both inputs can be a single state (row vector) or multiple states (matrix of row vectors). For this example, calculate the distance based on the Euclidean distance between each pair of state positions.

        function dist = distance(obj, state1, state2)
            
            narginchk(3,3);
            
            nav.internal.validation.validateStateMatrix(state1, nan, obj.NumStateVariables, "distance", "state1");
            nav.internal.validation.validateStateMatrix(state2, size(state1,1), obj.NumStateVariables, "distance", "state2");

            stateDiff = bsxfun(@minus, state2, state1);
            dist = sqrt( sum( stateDiff.^2, 2 ) );
        end

Terminate the methods and class sections.

    end
end

Save your state space class definition. You can now use the class constructor to create an object for your state space.

This example shows how to use the createPlanningTemplate function to generate a template for customizing your own state validation class. State validation is used with path planning algorithms to ensure valid paths. The template function provides a basic implementation for example purposes.

Call the create template function. This function generates a class definition file for you to modify for your own implementation. Save this file.

createPlanningTemplate("StateValidator")

Class and Property Definition

The first part of the template specifies the class definition and any properties for the class. Derive from the nav.StateValidator class. You can specify any additional user-defined properties here.

classdef MyCustomStateValidator < nav.StateValidator & ...
        matlabshared.planning.internal.EnforceScalarHandle
    properties
       % User-defined properties
    end

Save your custom state validator class and ensure your file name matches the class name.

Class Constructor

Use the constructor to set the name of the state space validator and specify the state space object. Set a default value for the state space if one is not provided. Call the constructor of the base class. Initialize any other user-defined properties.

methods
        function obj = MyCustomStateValidator(space)
            narginchk(0,1)
            
            if nargin == 0
                space = stateSpaceSE2;
            end

            obj@nav.StateValidator(space);
            
           % Initialize user-defined properties
        end

Copy Semantics

Specify the copy method definition. Copy all the values of your user-defined variables into a new object, so copyObj is a deep copy. The default behavior given in this example creates a new copy of the object with the same type.

        function copyObj = copy(obj)
            copyObj = feval(class(obj), obj.StateSpace);
        end

Check State Validity

Define how a given state is validated. The state input can either be a single row vector, or a matrix of row vectors for multiple states. Customize this function for any special validation behavior for your state space like collision checking against obstacles.

        function isValid = isStateValid(obj, state) 
            narginchk(2,2);
            nav.internal.validation.validateStateMatrix(state, nan, obj.StateSpace.NumStateVariables, ...
                "isStateValid", "state");
            
            bounds = obj.StateSpace.StateBounds';
            inBounds = state >= bounds(1,:) & state <= bounds(2,:);
            isValid = all(inBounds, 2);
            
        end

Check Motion Validity

Define how to generate the motion between states and determine if it is valid. For this example, use linspace to evenly interpolate between states and check if these states are valid using isStateValid. Customize this function to sample between states or consider other analytical methods for determining if a vehicle can move between given states.

        function [isValid, lastValid] = isMotionValid(obj, state1, state2)
            narginchk(3,3);
            state1 = nav.internal.validation.validateStateVector(state1, ...
                obj.StateSpace.NumStateVariables, "isMotionValid", "state1");
            state2 = nav.internal.validation.validateStateVector(state2, ...
                obj.StateSpace.NumStateVariables, "isMotionValid", "state2");
            
            if (~obj.isStateValid(state1))
                error("statevalidator:StartStateInvalid", "The start state of the motion is invalid.");
            end
            
            % Interpolate at a fixed interval between states and check state validity
            numInterpPoints = 100;
            interpStates = obj.StateSpace.interpolate(state1, state2, linspace(0,1,numInterpPoints));
            interpValid = obj.isStateValid(interpStates);
            
            % Look for invalid states. Set lastValid state to index-1.
            firstInvalidIdx = find(~interpValid, 1);
            if isempty(firstInvalidIdx)
                isValid = true;
                lastValid = state2;
            else
                isValid = false;
                lastValid = interpStates(firstInvalidIdx-1,:);
            end
            
        end

Terminate the methods and class sections.

    end
end

Save your state space validator class definition. You can now use the class constructor to create an object for validation of states for a given state space.

Introduced in R2019b